{"commit":"219c474860ca7674070ef19fa95f0282b7c92399","old_file":"mpages\/admin.py","new_file":"mpages\/admin.py","old_contents":"from django.contrib import admin\n\nfrom .models import Page, PageRead, Tag\n\n\nclass PageAdmin(admin.ModelAdmin):\n search_fields = [\"title\"]\n list_display = [\"title\", \"parent\", \"updated\"]\n prepopulated_fields = {\"slug\": (\"title\",)}\n readonly_fields = [\"updated\"]\n ordering = [\"parent\", \"title\"]\n filter_horizontal = (\"tags\",)\n save_on_top = True\n fieldsets = (\n (\n None,\n {\n \"fields\": (\n (\"content\",),\n (\"title\", \"parent\"),\n (\"slug\", \"updated\"),\n (\"tags\",),\n )\n },\n ),\n )\n\n\nadmin.site.register(Page, PageAdmin)\nadmin.site.register(PageRead)\nadmin.site.register(Tag)\n","new_contents":"from django.contrib import admin\n\nfrom .models import Page, PageRead, Tag\n\n\nclass PageAdmin(admin.ModelAdmin):\n search_fields = [\"title\"]\n list_display = [\"title\", \"parent\", \"updated\"]\n prepopulated_fields = {\"slug\": (\"title\",)}\n readonly_fields = [\"updated\"]\n ordering = [\"parent\", \"title\"]\n filter_horizontal = (\"tags\",)\n save_on_top = True\n fieldsets = (\n (\n None,\n {\n \"fields\": (\n (\"content\",),\n (\"title\", \"parent\"),\n (\"slug\", \"updated\"),\n (\"tags\",),\n )\n },\n ),\n )\n\n def formfield_for_foreignkey(self, db_field, request, **kwargs):\n if db_field.name == \"parent\":\n kwargs[\"queryset\"] = Page.objects.order_by(\"title\")\n return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)\n\n\nadmin.site.register(Page, PageAdmin)\nadmin.site.register(PageRead)\nadmin.site.register(Tag)\n","subject":"Order parents in Admin select field","message":"Order parents in Admin select field\n","lang":"Python","license":"bsd-3-clause","repos":"ahernp\/DMCM,ahernp\/DMCM,ahernp\/DMCM"} {"commit":"f76783ddb616c74e22feb003cb12952375cad658","old_file":"corehq\/apps\/hqwebapp\/encoders.py","new_file":"corehq\/apps\/hqwebapp\/encoders.py","old_contents":"import json\nimport datetime\nfrom django.utils.encoding import force_unicode\nfrom django.utils.functional import Promise\n\n\nclass LazyEncoder(json.JSONEncoder):\n \"\"\"Taken from https:\/\/github.com\/tomchristie\/django-rest-framework\/issues\/87\n This makes sure that ugettext_lazy refrences in a dict are properly evaluated\n \"\"\"\n def default(self, obj):\n if isinstance(obj, Promise):\n return force_unicode(obj)\n return super(LazyEncoder, self).default(obj)\n","new_contents":"import json\nimport datetime\nfrom decimal import Decimal\nfrom django.utils.encoding import force_unicode\nfrom django.utils.functional import Promise\n\n\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, Decimal):\n return str(obj)\n return super(DecimalEncoder, self).default(obj)\n\n\nclass LazyEncoder(DecimalEncoder):\n \"\"\"Taken from https:\/\/github.com\/tomchristie\/django-rest-framework\/issues\/87\n This makes sure that ugettext_lazy refrences in a dict are properly evaluated\n \"\"\"\n def default(self, obj):\n if isinstance(obj, Promise):\n return force_unicode(obj)\n return super(LazyEncoder, self).default(obj)\n","subject":"Fix for json encoding Decimal values","message":"Fix for json encoding Decimal values\n","lang":"Python","license":"bsd-3-clause","repos":"SEL-Columbia\/commcare-hq,qedsoftware\/commcare-hq,dimagi\/commcare-hq,qedsoftware\/commcare-hq,SEL-Columbia\/commcare-hq,qedsoftware\/commcare-hq,qedsoftware\/commcare-hq,dimagi\/commcare-hq,puttarajubr\/commcare-hq,SEL-Columbia\/commcare-hq,puttarajubr\/commcare-hq,dimagi\/commcare-hq,qedsoftware\/commcare-hq,puttarajubr\/commcare-hq,puttarajubr\/commcare-hq,dimagi\/commcare-hq,dimagi\/commcare-hq"} {"commit":"991973e554758e7a9881453d7668925902e610b9","old_file":"tests.py","new_file":"tests.py","old_contents":"#!\/usr\/bin\/env python\n\nimport unittest\n\nimport git_mnemonic as gm\n\nclass GitMnemonicTests(unittest.TestCase):\n def test_encode(self):\n self.assertTrue(gm.encode(\"master\"))\n\n def test_decode(self):\n self.assertTrue(gm.decode(\"bis alo ama aha\"))\n\n def test_invertible(self):\n once = gm.encode(\"master\")\n self.assertEquals(gm.encode(gm.decode(once)), once)\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)","new_contents":"#!\/usr\/bin\/env python\n\nimport unittest\n\nimport git_mnemonic as gm\n\nclass GitMnemonicTests(unittest.TestCase):\n def test_encode(self):\n self.assertTrue(gm.encode(\"master\"))\n\n def test_decode(self):\n self.assertTrue(gm.decode(\"bis alo ama aha\"))\n\n def test_invertible(self):\n once = gm.encode(\"master\")\n self.assertEquals(gm.encode(gm.decode(once)), once)\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(GitMnemonicTests)\n results = unittest.TextTestRunner(verbosity=2).run(suite)\n if not results.wasSuccessful():\n import sys\n sys.exit(1)","subject":"Make unittest test runner work in older pythons","message":"Make unittest test runner work in older pythons\n","lang":"Python","license":"mit","repos":"glenjamin\/git-mnemonic"} {"commit":"cb08d25f49b8b4c5177c8afdd9a69330992ee854","old_file":"tests\/replay\/test_replay.py","new_file":"tests\/replay\/test_replay.py","old_contents":"# -*- coding: utf-8 -*-\n\n\"\"\"\ntest_replay\n-----------\n\"\"\"\n\nimport pytest\n\nfrom cookiecutter import replay, main, exceptions\n\n\ndef test_get_replay_file_name():\n \"\"\"Make sure that replay.get_file_name generates a valid json file path.\"\"\"\n assert replay.get_file_name('foo', 'bar') == 'foo\/bar.json'\n\n\n@pytest.fixture(params=[\n {'no_input': True},\n {'extra_context': {}},\n {'no_input': True, 'extra_context': {}},\n])\ndef invalid_kwargs(request):\n return request.param\n\n\ndef test_raise_on_invalid_mode(invalid_kwargs):\n with pytest.raises(exceptions.InvalidModeException):\n main.cookiecutter('foo', replay=True, **invalid_kwargs)\n","new_contents":"# -*- coding: utf-8 -*-\n\n\"\"\"\ntest_replay\n-----------\n\"\"\"\n\nimport pytest\n\nfrom cookiecutter import replay, main, exceptions\n\n\ndef test_get_replay_file_name():\n \"\"\"Make sure that replay.get_file_name generates a valid json file path.\"\"\"\n assert replay.get_file_name('foo', 'bar') == 'foo\/bar.json'\n\n\n@pytest.fixture(params=[\n {'no_input': True},\n {'extra_context': {}},\n {'no_input': True, 'extra_context': {}},\n])\ndef invalid_kwargs(request):\n return request.param\n\n\ndef test_raise_on_invalid_mode(invalid_kwargs):\n with pytest.raises(exceptions.InvalidModeException):\n main.cookiecutter('foo', replay=True, **invalid_kwargs)\n\n\ndef test_main_does_not_invoke_dump_but_load(mocker):\n mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')\n mock_gen_context = mocker.patch('cookiecutter.main.generate_context')\n mock_gen_files = mocker.patch('cookiecutter.main.generate_files')\n mock_replay_dump = mocker.patch('cookiecutter.main.dump')\n mock_replay_load = mocker.patch('cookiecutter.main.load')\n\n main.cookiecutter('foobar', replay=True)\n\n assert not mock_prompt.called\n assert not mock_gen_context.called\n assert not mock_replay_dump.called\n assert mock_replay_load.called\n assert mock_gen_files.called\n\n\ndef test_main_does_not_invoke_load_but_dump(mocker):\n mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')\n mock_gen_context = mocker.patch('cookiecutter.main.generate_context')\n mock_gen_files = mocker.patch('cookiecutter.main.generate_files')\n mock_replay_dump = mocker.patch('cookiecutter.main.dump')\n mock_replay_load = mocker.patch('cookiecutter.main.load')\n\n main.cookiecutter('foobar', replay=False)\n\n assert mock_prompt.called\n assert mock_gen_context.called\n assert mock_replay_dump.called\n assert not mock_replay_load.called\n assert mock_gen_files.called\n","subject":"Add tests for a correct behaviour in cookiecutter.main for replay","message":"Add tests for a correct behaviour in cookiecutter.main for replay\n","lang":"Python","license":"bsd-3-clause","repos":"christabor\/cookiecutter,luzfcb\/cookiecutter,hackebrot\/cookiecutter,cguardia\/cookiecutter,pjbull\/cookiecutter,dajose\/cookiecutter,michaeljoseph\/cookiecutter,moi65\/cookiecutter,terryjbates\/cookiecutter,takeflight\/cookiecutter,terryjbates\/cookiecutter,luzfcb\/cookiecutter,agconti\/cookiecutter,cguardia\/cookiecutter,christabor\/cookiecutter,audreyr\/cookiecutter,stevepiercy\/cookiecutter,willingc\/cookiecutter,venumech\/cookiecutter,stevepiercy\/cookiecutter,takeflight\/cookiecutter,pjbull\/cookiecutter,benthomasson\/cookiecutter,agconti\/cookiecutter,benthomasson\/cookiecutter,Springerle\/cookiecutter,ramiroluz\/cookiecutter,audreyr\/cookiecutter,moi65\/cookiecutter,dajose\/cookiecutter,hackebrot\/cookiecutter,michaeljoseph\/cookiecutter,Springerle\/cookiecutter,ramiroluz\/cookiecutter,venumech\/cookiecutter,willingc\/cookiecutter"} {"commit":"9547988a1a9ef8faf22d9bfa881f4e542637fd46","old_file":"utils.py","new_file":"utils.py","old_contents":"import xmlrpclib\nimport cPickle\nimport subprocess\nfrom time import sleep\n\np = None\ns = None\n\ndef start_plot_server():\n global p\n if p is None:\n p = subprocess.Popen([\"python\", \"plot_server.py\"])\n\ndef stop_plot_server():\n if p is not None:\n p.terminate()\n sleep(0.01)\n p.kill()\n\ndef plot_server_alive():\n global s\n try:\n s.alive()\n except Exception, e:\n if str(e).endswith(\"Connection refused\"):\n return False\n else:\n raise\n return True\n\n\ndef establish_connection():\n global s\n s = xmlrpclib.ServerProxy(\"http:\/\/localhost:8000\/\", allow_none=True)\n if not plot_server_alive():\n start_plot_server()\n print \"waiting for the plot server to start up...\"\n while not plot_server_alive():\n sleep(0.05)\n print \" done.\"\n\ndef plot(vert, triangles):\n print \"plotting using mayavi...\"\n v = cPickle.dumps(vert)\n t = cPickle.dumps(triangles)\n s.plot(v, t)\n print \" done.\"\n\nestablish_connection()\n","new_contents":"import xmlrpclib\nimport cPickle\nimport subprocess\nfrom time import sleep\n\np = None\ns = None\n\ndef start_plot_server():\n global p\n if p is None:\n p = subprocess.Popen([\"python\", \"plot_server.py\"])\n\ndef stop_plot_server():\n if p is not None:\n p.terminate()\n sleep(0.01)\n p.kill()\n\ndef plot_server_alive():\n global s\n try:\n s.alive()\n except Exception, e:\n if str(e).endswith(\"Connection refused\"):\n return False\n else:\n raise\n return True\n\n\ndef establish_connection():\n global s\n if s is not None:\n return\n s = xmlrpclib.ServerProxy(\"http:\/\/localhost:8000\/\", allow_none=True)\n if not plot_server_alive():\n start_plot_server()\n print \"waiting for the plot server to start up...\"\n while not plot_server_alive():\n sleep(0.05)\n print \" done.\"\n\ndef plot(vert, triangles):\n establish_connection()\n print \"plotting using mayavi...\"\n v = cPickle.dumps(vert)\n t = cPickle.dumps(triangles)\n s.plot(v, t)\n print \" done.\"\n\n","subject":"Establish connection only when needed","message":"Establish connection only when needed\n","lang":"Python","license":"bsd-3-clause","repos":"certik\/mhd-hermes,certik\/mhd-hermes"} {"commit":"f3b9cc6392e4c271ae11417357ecdc196f1c3ae7","old_file":"python_scripts\/extractor_python_readability_server.py","new_file":"python_scripts\/extractor_python_readability_server.py","old_contents":"#!\/usr\/bin\/python\n\nimport sys\nimport os\nimport glob\n#sys.path.append(os.path.join(os.path.dirname(__file__), \"gen-py\"))\nsys.path.append(os.path.join(os.path.dirname(__file__),\"gen-py\/thrift_solr\/\"))\nsys.path.append(os.path.dirname(__file__) )\n\nfrom thrift.transport import TSocket \nfrom thrift.server import TServer \n#import thrift_solr\n\n\nimport ExtractorService\n\nimport sys\n\nimport readability\n\nimport readability\n\ndef extract_with_python_readability( raw_content ):\n doc = readability.Document( raw_content )\n \n return [ u'' + doc.short_title(),\n u'' + doc.summary() ]\n\nclass ExtractorHandler:\n def extract_html( self, raw_html ):\n\n #print raw_html\n\n #raw_html = raw_html.encode( 'utf-8' )\n\n ret = extract_with_python_readability( raw_html )\n #print ret[1]\n return ret\n\nhandler = ExtractorHandler()\nprocessor = ExtractorService.Processor(handler)\nlistening_socket = TSocket.TServerSocket(port=9090)\nserver = TServer.TThreadPoolServer(processor, listening_socket)\n\nprint (\"[Server] Started\")\nserver.serve()\n","new_contents":"#!\/usr\/bin\/python\n\nimport sys\nimport os\nimport glob\n#sys.path.append(os.path.join(os.path.dirname(__file__), \"gen-py\"))\nsys.path.append(os.path.join(os.path.dirname(__file__),\"gen-py\/thrift_solr\/\"))\nsys.path.append(os.path.dirname(__file__) )\n\nfrom thrift.transport import TSocket \nfrom thrift.transport import TTransport\nfrom thrift.protocol import TBinaryProtocol\nfrom thrift.server import TServer \nfrom thrift.protocol.TBinaryProtocol import TBinaryProtocolAccelerated\n\n#import thrift_solr\n\n\nimport ExtractorService\n\nimport sys\n\nimport readability\n\nimport readability\n\ndef extract_with_python_readability( raw_content ):\n doc = readability.Document( raw_content )\n \n return [ u'' + doc.short_title(),\n u'' + doc.summary() ]\n\nclass ExtractorHandler:\n def extract_html( self, raw_html ):\n\n #print raw_html\n\n #raw_html = raw_html.encode( 'utf-8' )\n\n ret = extract_with_python_readability( raw_html )\n #print ret[1]\n return ret\n\nhandler = ExtractorHandler()\nprocessor = ExtractorService.Processor(handler)\nlistening_socket = TSocket.TServerSocket(port=9090)\ntfactory = TTransport.TBufferedTransportFactory()\n#pfactory = TBinaryProtocol.TBinaryProtocolFactory()\npfactory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory()\n\nserver = TServer.TThreadPoolServer(processor, listening_socket, tfactory, pfactory)\n\nprint (\"[Server] Started\")\nserver.serve()\n","subject":"Use the TBinaryProtocolAccelerated protocol instead of TBinaryProtocol to improve performance.","message":"Use the TBinaryProtocolAccelerated protocol instead of TBinaryProtocol to improve performance.\n","lang":"Python","license":"agpl-3.0","repos":"AchyuthIIIT\/mediacloud,berkmancenter\/mediacloud,AchyuthIIIT\/mediacloud,AchyuthIIIT\/mediacloud,berkmancenter\/mediacloud,AchyuthIIIT\/mediacloud,berkmancenter\/mediacloud,berkmancenter\/mediacloud,AchyuthIIIT\/mediacloud,AchyuthIIIT\/mediacloud,berkmancenter\/mediacloud,AchyuthIIIT\/mediacloud,AchyuthIIIT\/mediacloud,AchyuthIIIT\/mediacloud"} {"commit":"a6034ffa4d81bb57c5d86876ee72e0436426e6d2","old_file":"imhotep_foodcritic\/plugin.py","new_file":"imhotep_foodcritic\/plugin.py","old_contents":"from imhotep.tools import Tool\nfrom collections import defaultdict\nimport json\nimport os\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\nclass FoodCritic(Tool):\n\n def invoke(self,\n dirname,\n filenames=set(),\n config_file=None,\n file_list=None):\n retval = defaultdict(lambda: defaultdict(list))\n if file_list is None:\n cmd = \"find %s\/cookbooks -type d -maxdepth 1 ! -path %s\/cookbooks | xargs foodcritic\" % (dirname, dirname)\n else:\n cmd = \"foodcritic %s\" % (\" \".join(file_list))\n log.debug(\"Command: %s\", cmd)\n try:\n output = self.executor(cmd)\n for line in output.split('\\n'):\n rule, message, file_name, line_number = line.split(':')\n file_name = file_name.lstrip()\n file_name = file_name.replace(dirname, \"\")[1:]\n message = \"[%s](http:\/\/acrmp.github.io\/foodcritic\/#%s): %s\" % (rule, rule, message)\n retval[file_name][line_number].append(message)\n except:\n pass\n return retval\n","new_contents":"from imhotep.tools import Tool\nfrom collections import defaultdict\nimport json\nimport os\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\nclass FoodCritic(Tool):\n\n def invoke(self,\n dirname,\n filenames=set(),\n config_file=None):\n retval = defaultdict(lambda: defaultdict(list))\n if len(filenames) == 0:\n cmd = \"find %s\/cookbooks -type d -maxdepth 1 ! -path %s\/cookbooks | xargs foodcritic\" % (dirname, dirname)\n else:\n filenames = [\"%s\/%s\" % (dirname, \"\/\".join(filename.split('\/')[:2])) for filename in filenames]\n cmd = \"foodcritic %s\" % (\" \".join(filenames))\n log.debug(\"Command: %s\", cmd)\n try:\n output = self.executor(cmd)\n for line in output.split('\\n'):\n rule, message, file_name, line_number = line.split(':')\n file_name = file_name.lstrip()\n file_name = file_name.replace(dirname, \"\")[1:]\n message = \"[%s](http:\/\/acrmp.github.io\/foodcritic\/#%s): %s\" % (rule, rule, message)\n retval[file_name][line_number].append(message)\n except:\n pass\n return retval\n","subject":"Update support for passing in filenames.","message":"Update support for passing in filenames.\n\nThis shit is gross\n","lang":"Python","license":"mit","repos":"scottjab\/imhotep_foodcritic"} {"commit":"3ce1b928f36c314ab07c334843b2db96626f469e","old_file":"kyokai\/asphalt.py","new_file":"kyokai\/asphalt.py","old_contents":"\"\"\"\nAsphalt framework mixin for Kyokai.\n\"\"\"\nimport logging\n\nimport asyncio\nfrom functools import partial\nfrom typing import Union\n\nfrom asphalt.core import Component, resolve_reference, Context\nfrom typeguard import check_argument_types\n\nfrom kyokai.app import Kyokai\nfrom kyokai.protocol import KyokaiProtocol\nfrom kyokai.context import HTTPRequestContext\n\nlogger = logging.getLogger(\"Kyokai\")\n\n\nclass KyoukaiComponent(Component):\n def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444, **cfg):\n assert check_argument_types()\n if not isinstance(app, Kyokai):\n self.app = resolve_reference(app)\n else:\n self.app = app\n self.ip = ip\n self.port = port\n self._extra_cfg = cfg\n\n # Set HTTPRequestContext's `cfg` val to the extra config.\n HTTPRequestContext.cfg = self._extra_cfg\n\n self.server = None\n\n self.app.reconfigure(cfg)\n\n def get_protocol(self, ctx: Context):\n return KyokaiProtocol(self.app, ctx)\n\n async def start(self, ctx: Context):\n \"\"\"\n Starts a Kyokai server.\n \"\"\"\n protocol = self.get_protocol(ctx)\n self.server = await asyncio.get_event_loop().create_server(protocol, self.ip, self.port)\n logger.info(\"Kyokai serving on {}:{}.\".format(self.ip, self.port))\n","new_contents":"\"\"\"\nAsphalt framework mixin for Kyokai.\n\"\"\"\nimport logging\n\nimport asyncio\nfrom functools import partial\nfrom typing import Union\n\nfrom asphalt.core import Component, resolve_reference, Context\nfrom typeguard import check_argument_types\n\nfrom kyokai.app import Kyokai\nfrom kyokai.protocol import KyokaiProtocol\nfrom kyokai.context import HTTPRequestContext\n\nlogger = logging.getLogger(\"Kyokai\")\n\n\nclass KyoukaiComponent(Component):\n def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444, **cfg):\n assert check_argument_types()\n if not isinstance(app, Kyokai):\n self.app = resolve_reference(app)\n else:\n self.app = app\n self.ip = ip\n self.port = port\n self._extra_cfg = cfg\n\n # Set HTTPRequestContext's `cfg` val to the extra config.\n HTTPRequestContext.cfg = self._extra_cfg\n\n self.server = None\n\n self.app.reconfigure(cfg)\n\n def get_protocol(self, ctx: Context):\n return KyokaiProtocol(self.app, ctx)\n\n async def start(self, ctx: Context):\n \"\"\"\n Starts a Kyokai server.\n \"\"\"\n protocol = partial(self.get_protocol, ctx)\n self.server = await asyncio.get_event_loop().create_server(protocol, self.ip, self.port)\n logger.info(\"Kyokai serving on {}:{}.\".format(self.ip, self.port))\n","subject":"Make this into a partial to get the protocol correctly.","message":"Make this into a partial to get the protocol correctly.\n","lang":"Python","license":"mit","repos":"SunDwarf\/Kyoukai"} {"commit":"b352c3e1f5e8812d29f2e8a1bca807bea5da8cc4","old_file":"test\/test_hx_launcher.py","new_file":"test\/test_hx_launcher.py","old_contents":"import pytest_twisted\n\nfrom hendrix.ux import main\nfrom hendrix.options import HendrixOptionParser\n\n\ndef test_no_arguments_gives_help_text(mocker):\n\n class MockFile(object):\n @classmethod\n def write(cls, whatever):\n cls.things_written = whatever\n\n class MockStdOut(object):\n\n @classmethod\n def write(cls, whatever):\n HendrixOptionParser.print_help(MockFile)\n assert MockFile.things_written == whatever\n\n mocker.patch('sys.stdout', new=MockStdOut)\n main([])\n","new_contents":"from hendrix.options import HendrixOptionParser\nfrom hendrix.ux import main\n\n\ndef test_no_arguments_gives_help_text(mocker):\n class MockFile(object):\n @classmethod\n def write(cls, whatever):\n cls.things_written = whatever\n\n class MockStdOut(object):\n\n @classmethod\n def write(cls, whatever):\n HendrixOptionParser.print_help(MockFile)\n assert MockFile.things_written == whatever\n\n mocker.patch('sys.stdout', new=MockStdOut)\n main([])\n","subject":"Test for the hx launcher.","message":"Test for the hx launcher.\n","lang":"Python","license":"mit","repos":"hangarunderground\/hendrix,hendrix\/hendrix,hangarunderground\/hendrix,hendrix\/hendrix,jMyles\/hendrix,hendrix\/hendrix,jMyles\/hendrix,hangarunderground\/hendrix,hangarunderground\/hendrix,jMyles\/hendrix"} {"commit":"ad21c9255f6246944cd032ad50082c0aca46fcb3","old_file":"neurokernel\/tools\/mpi.py","new_file":"neurokernel\/tools\/mpi.py","old_contents":"#!\/usr\/bin\/env python\n\n\"\"\"\nMPI utilities.\n\"\"\"\n\nfrom mpi4py import MPI\nimport twiggy\n\nclass MPIOutput(twiggy.outputs.Output):\n \"\"\"\n Output messages to a file via MPI I\/O.\n \"\"\"\n\n def __init__(self, name, format, comm,\n mode=MPI.MODE_CREATE | MPI.MODE_WRONLY,\n close_atexit=True):\n self.filename = name\n self._format = format if format is not None else self._noop_format\n self.comm = comm\n self.mode = mode\n super(MPIOutput, self).__init__(format, close_atexit)\n\n def _open(self):\n self.file = MPI.File.Open(self.comm, self.filename,\n self.mode)\n\n def _close(self):\n self.file.Close()\n\n def _write(self, x):\n self.file.Iwrite_shared(x)\n\n","new_contents":"#!\/usr\/bin\/env python\n\n\"\"\"\nMPI utilities.\n\"\"\"\n\nfrom mpi4py import MPI\nimport twiggy\n\nclass MPIOutput(twiggy.outputs.Output):\n \"\"\"\n Output messages to a file via MPI I\/O.\n \"\"\"\n\n def __init__(self, name, format, comm,\n mode=MPI.MODE_CREATE | MPI.MODE_WRONLY,\n close_atexit=True):\n self.filename = name\n self._format = format if format is not None else self._noop_format\n self.comm = comm\n self.mode = mode\n super(MPIOutput, self).__init__(format, close_atexit)\n\n def _open(self):\n self.file = MPI.File.Open(self.comm, self.filename,\n self.mode)\n\n def _close(self):\n self.file.Close()\n\n def _write(self, x):\n self.file.Iwrite_shared(x)\n\n # This seems to be necessary to prevent some log lines from being lost:\n self.file.Sync()\n","subject":"Call MPIOutput.file.Sync() in MPIOutput.file._write() to prevent log lines from intermittently being lost.","message":"Call MPIOutput.file.Sync() in MPIOutput.file._write() to prevent log lines from intermittently being lost.\n","lang":"Python","license":"bsd-3-clause","repos":"cerrno\/neurokernel"} {"commit":"2a4b02fe84542f3f44fa4e6913f86ed3a4771d43","old_file":"issue_tracker\/core\/models.py","new_file":"issue_tracker\/core\/models.py","old_contents":"from django.db import models\nfrom django.contrib.auth.models import User\n\nclass Project(models.Model):\n user = models.ForeignKey(User)\n name = models.CharField(max_length=100)\n version = models.CharField(max_length=15, null=True)\n release_date = models.DateField(null=True)\n\nclass Issue(models.Model):\n project = models.ForeignKey(Project)\n status_choices = (\n (\"0\", \"OPEN\"),\n (\"1\", \"IN PROGRESS\"),\n (\"2\", \"FINISHED\"),\n (\"3\", \"CLOSED\"),\n (\"4\", \"CANCELED\"),\n )\n status = models.CharField(max_length=10, choices=status_choices)\n level_choices = (\n (\"0\", \"LOW\"),\n (\"1\", \"MEDIUM\"),\n (\"2\", \"HIGH\"),\n (\"3\", \"CRITICAL\"),\n (\"4\", \"BLOCKER\"),\n )\n level = models.CharField(max_length=10, choices=level_choices)\n title = models.CharField(max_length=50, null=True)\n description = models.CharField(max_length=50, null=True)\n date_created = models.DateField(auto_now_add=True) \n date_completed = models.DateField(null=True) \n # TODO implement these\n # time_estimate \n # percentage_completed \n\nclass Comments(models.Model):\n issue = models.ForeignKey(Issue)\n comment = models.CharField(max_length=500)\n user = models.ForeignKey(User,null=True, blank=True)\n\n","new_contents":"from django.db import models\nfrom django.contrib.auth.models import User\n\nclass Project(models.Model):\n user = models.ForeignKey(User)\n name = models.CharField(max_length=100)\n version = models.CharField(max_length=15, null=True)\n release_date = models.DateField(null=True)\n\nclass Issue(models.Model):\n project = models.ForeignKey(Project)\n status_choices = (\n (\"0\", \"OPEN\"),\n (\"1\", \"IN PROGRESS\"),\n (\"2\", \"FINISHED\"),\n (\"3\", \"CLOSED\"),\n (\"4\", \"CANCELED\"),\n )\n status = models.CharField(max_length=10, choices=status_choices)\n level_choices = (\n (\"0\", \"LOW\"),\n (\"1\", \"MEDIUM\"),\n (\"2\", \"HIGH\"),\n (\"3\", \"CRITICAL\"),\n (\"4\", \"BLOCKER\"),\n )\n level = models.CharField(max_length=10, choices=level_choices)\n title = models.CharField(max_length=50, null=True)\n description = models.CharField(max_length=50, null=True)\n date_created = models.DateField(auto_now_add=True) \n date_completed = models.DateField(null=True) \n # TODO implement these\n # time_estimate \n # percentage_completed \n\nclass Comments(models.Model):\n issue = models.ForeignKey(Issue)\n comment = models.TextField(max_length=500)\n date_created = models.DateTimeField(null=False, auto_now_add=True) \n user = models.ForeignKey(User,null=True, blank=True)\n\n","subject":"Change comment from a charfield to a textfield, and add a date_created field; which is not working correctly.","message":"Change comment from a charfield to a textfield, and add a date_created field; which is not working correctly.\n","lang":"Python","license":"mit","repos":"hfrequency\/django-issue-tracker"} {"commit":"4485b65722645d6c9617b5ff4aea6d62ee8a9adf","old_file":"bumblebee_status\/modules\/contrib\/optman.py","new_file":"bumblebee_status\/modules\/contrib\/optman.py","old_contents":"\"\"\"Displays currently active gpu by optimus-manager\nRequires the following packages:\n\n * optimus-manager\n\n\"\"\"\n\nimport subprocess\n\nimport core.module\nimport core.widget\n\n\nclass Module(core.module.Module):\n def __init__(self, config, theme):\n super().__init__(config, theme, core.widget.Widget(self.output))\n self.__gpumode = \"\"\n\n def output(self, _):\n return \"GPU: {}\".format(self.__gpumode)\n\n def update(self):\n cmd = [\"optimus-manager\", \"--print-mode\"]\n output = (\n subprocess.Popen(cmd, stdout=subprocess.PIPE)\n .communicate()[0]\n .decode(\"utf-8\")\n .lower()\n )\n\n if \"intel\" in output:\n self.__gpumode = \"Intel\"\n elif \"nvidia\" in output:\n self.__gpumode = \"Nvidia\"\n elif \"amd\" in output:\n self.__gpumode = \"AMD\"\n","new_contents":"\"\"\"Displays currently active gpu by optimus-manager\nRequires the following packages:\n\n * optimus-manager\n\n\"\"\"\n\nimport core.module\nimport core.widget\n\nimport util.cli\n\nclass Module(core.module.Module):\n def __init__(self, config, theme):\n super().__init__(config, theme, core.widget.Widget(self.output))\n self.__gpumode = \"\"\n\n def output(self, _):\n return \"GPU: {}\".format(self.__gpumode)\n\n def update(self):\n cmd = \"optimus-manager --print-mode\"\n output = util.cli.execute(cmd).strip()\n\n if \"intel\" in output:\n self.__gpumode = \"Intel\"\n elif \"nvidia\" in output:\n self.__gpumode = \"Nvidia\"\n elif \"amd\" in output:\n self.__gpumode = \"AMD\"\n","subject":"Use the existing util.cli module","message":"Use the existing util.cli module","lang":"Python","license":"mit","repos":"tobi-wan-kenobi\/bumblebee-status,tobi-wan-kenobi\/bumblebee-status"} {"commit":"7ad0e624e4bccab39b56152e9d4c6d5fba8dc528","old_file":"dudebot\/__init__.py","new_file":"dudebot\/__init__.py","old_contents":"","new_contents":"from core import BotAI\nfrom core import Connector\n\nfrom decorators import message_must_begin_with\nfrom decorators import message_must_begin_with_attr\nfrom decorators import message_must_begin_with_nickname\n","subject":"Allow modules that use dudebot to just import dudebot...","message":"Allow modules that use dudebot to just import dudebot...\n","lang":"Python","license":"bsd-2-clause","repos":"sujaymansingh\/dudebot"} {"commit":"710d94f0b08b3d51fbcfda13050dc21e3d53f2e7","old_file":"yunity\/resources\/tests\/integration\/test_chat__add_invalid_user_to_chat_fails\/request.py","new_file":"yunity\/resources\/tests\/integration\/test_chat__add_invalid_user_to_chat_fails\/request.py","old_contents":"from .initial_data import request_user, chatid\n\nrequest = {\n \"endpoint\": \"\/api\/chats\/{}\/participants\".format(chatid),\n \"method\": \"post\",\n \"user\": request_user,\n \"body\": {\n \"users\": [666666]\n }\n}\n","new_contents":"from .initial_data import request_user, chatid\n\nrequest = {\n \"endpoint\": \"\/api\/chats\/{}\/participants\".format(chatid),\n \"method\": \"post\",\n \"user\": request_user,\n \"body\": {\n \"users\": [666666, 22]\n }\n}\n","subject":"Fix testcase for better coverage","message":"Fix testcase for better coverage\n","lang":"Python","license":"agpl-3.0","repos":"yunity\/yunity-core,yunity\/foodsaving-backend,yunity\/yunity-core,yunity\/foodsaving-backend,yunity\/foodsaving-backend"} {"commit":"3307bfb7075a527dc7805da2ff735f461f5fc02f","old_file":"employees\/models.py","new_file":"employees\/models.py","old_contents":"from __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom django.utils.encoding import python_2_unicode_compatible\n\n\n@python_2_unicode_compatible\nclass Role(models.Model):\n name = models.CharField(max_length=100)\n\n def __str__(self):\n return self.name\n\n\n@python_2_unicode_compatible\nclass Category(models.Model):\n name = models.CharField(max_length=100)\n weight = models.PositiveSmallIntegerField(default=1)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name_plural = \"categories\"\n ordering = ['weight']\n\n\nclass Employee(AbstractUser):\n role = models.ForeignKey(Role, null=True, blank=True)\n skype_id = models.CharField(max_length=200, null=True, blank=True)\n last_month_score = models.PositiveIntegerField(default=0)\n current_month_score = models.PositiveIntegerField(default=0)\n level = models.PositiveIntegerField(default=0)\n total_score = models.PositiveIntegerField(default=0)\n avatar = models.ImageField(upload_to='avatar', null=True, blank=True)\n categories = models.ManyToManyField(Category)\n","new_contents":"from __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom django.utils.encoding import python_2_unicode_compatible\n\n\n@python_2_unicode_compatible\nclass Role(models.Model):\n name = models.CharField(max_length=100)\n\n def __str__(self):\n return self.name\n\n\n@python_2_unicode_compatible\nclass Category(models.Model):\n name = models.CharField(max_length=100)\n weight = models.PositiveSmallIntegerField(default=1)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name_plural = \"categories\"\n ordering = ['weight']\n\n\nclass Employee(AbstractUser):\n role = models.ForeignKey(Role, null=True, blank=True)\n skype_id = models.CharField(max_length=200, null=True, blank=True)\n last_month_score = models.PositiveIntegerField(default=0)\n current_month_score = models.PositiveIntegerField(default=0)\n level = models.PositiveIntegerField(default=0)\n total_score = models.PositiveIntegerField(default=0)\n avatar = models.ImageField(upload_to='avatar', null=True, blank=True)\n categories = models.ManyToManyField(Category, blank=True)\n","subject":"Change categories field to non required.","message":"Change categories field to non required.\n","lang":"Python","license":"mit","repos":"neosergio\/allstars"} {"commit":"b8bc10e151f12e2bfe2c03765a410a04325a3233","old_file":"satchmo\/product\/templatetags\/satchmo_product.py","new_file":"satchmo\/product\/templatetags\/satchmo_product.py","old_contents":"from django import template\nfrom django.conf import settings\nfrom django.core import urlresolvers\nfrom django.template import Context, Template\nfrom django.utils.translation import get_language, ugettext_lazy as _\nfrom satchmo.configuration import config_value\nfrom satchmo.product.models import Category\nfrom satchmo.shop.templatetags import get_filter_args\n\nregister = template.Library()\n\ndef is_producttype(product, ptype):\n \"\"\"Returns True if product is ptype\"\"\"\n if ptype in product.get_subtypes():\n return \"true\"\n else:\n return \"\"\n\nregister.filter('is_producttype', is_producttype)\n\ndef product_images(product, args=\"\"):\n args, kwargs = get_filter_args(args, \n keywords=('include_main', 'maximum'), \n boolargs=('include_main'),\n intargs=('maximum'),\n stripquotes=True)\n\n q = product.productimage_set\n if kwargs.get('include_main', True):\n q = q.all()\n else:\n main = product.main_image\n q = q.exclude(id = main.id)\n \n maximum = kwargs.get('maximum', -1)\n if maximum>-1:\n q = list(q)[:maximum]\n \n return q\n\nregister.filter('product_images', product_images)\n\ndef smart_attr(product, key):\n \"\"\"Run the smart_attr function on the spec'd product\n \"\"\"\n return product.smart_attr(key)\n \nregister.filter('smart_attr', smart_attr)\n","new_contents":"from django import template\nfrom django.conf import settings\nfrom django.core import urlresolvers\nfrom django.template import Context, Template\nfrom django.utils.translation import get_language, ugettext_lazy as _\nfrom satchmo.configuration import config_value\nfrom satchmo.product.models import Category\nfrom satchmo.shop.templatetags import get_filter_args\n\nregister = template.Library()\n\ndef is_producttype(product, ptype):\n \"\"\"Returns True if product is ptype\"\"\"\n if ptype in product.get_subtypes():\n return True\n else:\n return False\n\nregister.filter('is_producttype', is_producttype)\n\ndef product_images(product, args=\"\"):\n args, kwargs = get_filter_args(args,\n keywords=('include_main', 'maximum'),\n boolargs=('include_main'),\n intargs=('maximum'),\n stripquotes=True)\n\n q = product.productimage_set\n if kwargs.get('include_main', True):\n q = q.all()\n else:\n main = product.main_image\n q = q.exclude(id = main.id)\n\n maximum = kwargs.get('maximum', -1)\n if maximum>-1:\n q = list(q)[:maximum]\n\n return q\n\nregister.filter('product_images', product_images)\n\ndef smart_attr(product, key):\n \"\"\"Run the smart_attr function on the spec'd product\n \"\"\"\n return product.smart_attr(key)\n\nregister.filter('smart_attr', smart_attr)\n","subject":"Change the is_producttype template tag to return a boolean rather than a string.","message":"Change the is_producttype template tag to return a boolean rather than a string.\n\n--HG--\nextra : convert_revision : svn%3Aa38d40e9-c014-0410-b785-c606c0c8e7de\/satchmo\/trunk%401200\n","lang":"Python","license":"bsd-3-clause","repos":"Ryati\/satchmo,ringemup\/satchmo,Ryati\/satchmo,dokterbob\/satchmo,twidi\/satchmo,twidi\/satchmo,dokterbob\/satchmo,ringemup\/satchmo"} {"commit":"b4247769fcaa67d09e0f38d1283cf4f28ddc350e","old_file":"cookiecutter\/extensions.py","new_file":"cookiecutter\/extensions.py","old_contents":"# -*- coding: utf-8 -*-\n\n\"\"\"Jinja2 extensions.\"\"\"\n\nimport json\n\nfrom jinja2.ext import Extension\n\n\nclass JsonifyExtension(Extension):\n \"\"\"Jinja2 extension to convert a python object to json.\"\"\"\n\n def __init__(self, environment):\n \"\"\"Initilize extension with given environment.\"\"\"\n super(JsonifyExtension, self).__init__(environment)\n\n def jsonify(obj):\n return json.dumps(obj, sort_keys=True, indent=4)\n\n environment.filters['jsonify'] = jsonify\n","new_contents":"# -*- coding: utf-8 -*-\n\n\"\"\"Jinja2 extensions.\"\"\"\n\nimport json\n\nfrom jinja2.ext import Extension\n\n\nclass JsonifyExtension(Extension):\n \"\"\"Jinja2 extension to convert a Python object to JSON.\"\"\"\n\n def __init__(self, environment):\n \"\"\"Initialize the extension with the given environment.\"\"\"\n super(JsonifyExtension, self).__init__(environment)\n\n def jsonify(obj):\n return json.dumps(obj, sort_keys=True, indent=4)\n\n environment.filters['jsonify'] = jsonify\n","subject":"Fix typo and improve grammar in doc string","message":"Fix typo and improve grammar in doc string\n","lang":"Python","license":"bsd-3-clause","repos":"michaeljoseph\/cookiecutter,dajose\/cookiecutter,audreyr\/cookiecutter,hackebrot\/cookiecutter,audreyr\/cookiecutter,hackebrot\/cookiecutter,luzfcb\/cookiecutter,pjbull\/cookiecutter,dajose\/cookiecutter,pjbull\/cookiecutter,luzfcb\/cookiecutter,michaeljoseph\/cookiecutter"} {"commit":"42ec5ed6d56fcc59c99d175e1c9280d00cd3bef1","old_file":"tests\/test_published_results.py","new_file":"tests\/test_published_results.py","old_contents":"\n\"\"\" To test if the new code produces the same precision values on the published results.\"\"\"\n\nfrom __future__ import division, print_function\nimport pytest\nimport numpy as np\n\nimport eniric.Qcalculator as Q\nimport eniric.IOmodule as IO\nfrom bin.prec_1 import calc_prec1\n\n# For python2.X compatibility\nfile_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError)\n\npath = \"data\/Published_Results\/resampled\/\"\n\n\n@pytest.mark.xfail(raises=file_error_to_catch) # Data file may not exist\ndef test_presicion_1():\n \"\"\" New precision 1 test that works.\"\"\"\n published_results = {1: 3.8, 5: 9.1, 10: 20.7}\n path = \"data\/resampled\/\"\n for vsini in [1, 5, 10]:\n # name = \"Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt\".format(vsini)\n __, p1 = calc_prec1(\"M0\", \"Y\", vsini, \"100k\", 3, resampled_dir=path)\n\n assert np.round(p1, 1).value == published_results[vsini]\n","new_contents":"\n\"\"\" To test if the new code produces the same precision values on the published results.\"\"\"\n\nfrom __future__ import division, print_function\nimport pytest\nimport numpy as np\n\nimport eniric.Qcalculator as Q\nimport eniric.IOmodule as IO\nfrom bin.prec_1 import calc_prec1\n\n# For python2.X compatibility\nfile_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError)\n\npath = \"data\/Published_Results\/resampled\/\"\n\n\n@pytest.mark.xfail(raises=file_error_to_catch) # Data file may not exist\ndef test_presicion_1():\n \"\"\" New precision 1 test that works.\"\"\"\n published_results = {1: 3.8, 5: 9.1, 10: 20.7}\n path = \"data\/resampled\/\"\n for vsini in [1, 5, 10]:\n # name = \"Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt\".format(vsini)\n __, p1 = calc_prec1(\"M0\", \"Y\", vsini, \"100k\", 3, resampled_dir=path)\n\n # assert np.round(p1, 1).value == published_results[vsini]\n assert np.round(100 * p1, 1).value == published_results[vsini] # With incorect normalization\n","subject":"Add known offset for known bad calibration.","message":"Add known offset for known bad calibration.\n\n\nFormer-commit-id: afa3d6a66e32bbcc2b20f00f7e63fba5cb45882e [formerly 0470ca22b8a24205d2eb1c66caee912c990da0b3] [formerly c23210f4056c27e61708da2f2440bce3eda151a8 [formerly 5c0a6b9c0fefd2b88b9382d4a6ed98d9eac626df]]\nFormer-commit-id: 8bfdaa1f7940b26aee05f20e801616f4a8d1d55d [formerly 1c85db5b2b87b73dfb28a1db171ff79a69e3a24a]\nFormer-commit-id: d02a26b263c5c59776a35fc130e5c96b7ac30f5d","lang":"Python","license":"mit","repos":"jason-neal\/eniric,jason-neal\/eniric"} {"commit":"f3df3b2b8e1167e953457a85f2297d28b6a39729","old_file":"examples\/Micro.Blog\/microblog.py","new_file":"examples\/Micro.Blog\/microblog.py","old_contents":"from getpass import getpass\nfrom bessie import BaseClient\n\nimport config \n\n\nclass MicroBlogApi(BaseClient):\n\n\tendpoints = config.available_endpoints\n\tseparator = '\/'\n\tbase_url='https:\/\/micro.blog'\n\n\tdef __init__(self, path='', token=''):\n\t\tself.token = token\n\t\tsuper(self.__class__, self).__init__(path, token=token)\n\n\t# override method from BaseClient to inject Authorization header\n\tdef _prepare_request(self):\n\t\tsuper(self.__class__, self)._prepare_request()\n\t\tself.request.headers['Authorization'] = 'Token {}'.format(self.token)\n\n\nif __name__ == '__main__':\n\ttoken = getpass('Token... ')\n\tmba = MicroBlogApi(token=token)\n\n\t# GET - https:\/\/micro.blog\/posts\/all\n\tposts = mba.posts.all.get()\n\n\tprint(posts.status_code, posts.reason)\n\tprint(posts.json())\n","new_contents":"from getpass import getpass\nfrom bessie import BaseClient\n\nimport config \n\n\nclass MicroBlogApi(BaseClient):\n\n\tendpoints = config.available_endpoints\n\tseparator = '\/'\n\tbase_url='https:\/\/micro.blog'\n\n\tdef __init__(self, path='', path_params=None, token=''):\n\t\tself.token = token\n\t\tsuper(self.__class__, self).__init__(path, path_params, token=token)\n\n\t# override method from BaseClient to inject Authorization header\n\tdef _prepare_request(self):\n\t\tsuper(self.__class__, self)._prepare_request()\n\t\tself.request.headers['Authorization'] = 'Token {}'.format(self.token)\n\n\nif __name__ == '__main__':\n\ttoken = getpass('Token... ')\n\tmba = MicroBlogApi(token=token)\n\n\t# GET - https:\/\/micro.blog\/posts\/all\n\tposts = mba.posts.all.get()\n\n\tprint(posts.status_code, posts.reason)\n\tprint(posts.json())\n","subject":"Include path_params in override constructor","message":"Include path_params in override constructor\n","lang":"Python","license":"mit","repos":"andymitchhank\/bessie"} {"commit":"c9980756dcee82cc570208e73ec1a2112aea0155","old_file":"tvtk\/tests\/test_scene.py","new_file":"tvtk\/tests\/test_scene.py","old_contents":"\"\"\" Tests for the garbage collection of Scene objects.\n\"\"\"\n# Authors: Deepak Surti, Ioannis Tziakos\n# Copyright (c) 2015, Enthought, Inc.\n# License: BSD Style.\n\nimport unittest\nimport weakref\nimport gc\n\nfrom traits.etsconfig.api import ETSConfig\n\nfrom tvtk.pyface.scene import Scene\nfrom tvtk.tests.common import restore_gc_state\n\n\nclass TestScene(unittest.TestCase):\n\n @unittest.skipIf(\n ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)')\n def test_scene_garbage_collected(self):\n\n # given\n scene_collected = []\n scene_weakref = None\n\n def scene_collected_callback(weakref):\n scene_collected.append(True)\n\n def do():\n scene = Scene()\n reference = weakref.ref(scene, scene_collected_callback)\n scene.close()\n return reference\n\n # when\n with restore_gc_state():\n gc.disable()\n scene_weakref = do()\n\n # The Scene should have been collected.\n self.assertTrue(scene_collected[0])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","new_contents":"\"\"\" Tests for the garbage collection of Scene objects.\n\"\"\"\n# Authors: Deepak Surti, Ioannis Tziakos\n# Copyright (c) 2015, Enthought, Inc.\n# License: BSD Style.\n\nimport unittest\nimport weakref\nimport gc\n\nfrom traits.etsconfig.api import ETSConfig\n\nfrom tvtk.pyface.scene import Scene\nfrom tvtk.tests.common import restore_gc_state\n\n\nclass TestScene(unittest.TestCase):\n\n @unittest.skipIf(\n ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)')\n def test_scene_garbage_collected(self):\n\n # given\n scene_collected = []\n scene_weakref = None\n\n def scene_collected_callback(weakref):\n scene_collected.append(True)\n\n def do():\n scene = Scene()\n reference = weakref.ref(scene, scene_collected_callback)\n scene.close()\n return reference\n\n # when\n with restore_gc_state():\n gc.disable()\n scene_weakref = do()\n\n # The Scene should have been collected.\n self.assertTrue(scene_collected[0])\n self.assertIsNone(scene_weakref())\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","subject":"Add weakref assertion in test case","message":"Add weakref assertion in test case\n","lang":"Python","license":"bsd-3-clause","repos":"alexandreleroux\/mayavi,dmsurti\/mayavi,dmsurti\/mayavi,alexandreleroux\/mayavi,liulion\/mayavi,liulion\/mayavi"} {"commit":"74b2883c3371304e8f5ea95b0454fb006d85ba3d","old_file":"mapentity\/urls.py","new_file":"mapentity\/urls.py","old_contents":"from django.conf import settings\nfrom django.conf.urls import patterns, url\n\nfrom . import app_settings\nfrom .views import (map_screenshot, convert, history_delete,\n serve_secure_media, JSSettings)\n\n\n_MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')[1:]\n\n\nurlpatterns = patterns(\n '',\n url(r'^%s(?P.*?)$' % _MEDIA_URL, serve_secure_media),\n url(r'^map_screenshot\/$', map_screenshot, name='map_screenshot'),\n url(r'^convert\/$', convert, name='convert'),\n url(r'^history\/delete\/$', history_delete, name='history_delete'),\n # See default value in app_settings.JS_SETTINGS.\n # Will be overriden, most probably.\n url(r'^api\/settings.json$', JSSettings.as_view(), name='js_settings'),\n)\n","new_contents":"from django.conf import settings\nfrom django.conf.urls import patterns, url\n\nfrom . import app_settings\nfrom .views import (map_screenshot, convert, history_delete,\n serve_secure_media, JSSettings)\n\n\n_MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')\nif _MEDIA_URL.startswith('\/'):\n _MEDIA_URL = _MEDIA_URL[1:]\nif _MEDIA_URL.endswith('\/'):\n _MEDIA_URL = _MEDIA_URL[:-1]\n\n\nurlpatterns = patterns(\n '',\n url(r'^%s(?P.*?)$' % _MEDIA_URL, serve_secure_media),\n url(r'^map_screenshot\/$', map_screenshot, name='map_screenshot'),\n url(r'^convert\/$', convert, name='convert'),\n url(r'^history\/delete\/$', history_delete, name='history_delete'),\n # See default value in app_settings.JS_SETTINGS.\n # Will be overriden, most probably.\n url(r'^api\/settings.json$', JSSettings.as_view(), name='js_settings'),\n)\n","subject":"Remove leading and trailing slash of MEDIA_URL","message":"Remove leading and trailing slash of MEDIA_URL\n\nConflicts:\n\n\tmapentity\/static\/mapentity\/Leaflet.label\n","lang":"Python","license":"bsd-3-clause","repos":"Anaethelion\/django-mapentity,Anaethelion\/django-mapentity,makinacorpus\/django-mapentity,makinacorpus\/django-mapentity,Anaethelion\/django-mapentity,makinacorpus\/django-mapentity"} {"commit":"4cde7c1c651647214d73bf6e42a9051960228af6","old_file":"slave\/skia_slave_scripts\/android_render_pdfs.py","new_file":"slave\/skia_slave_scripts\/android_render_pdfs.py","old_contents":"#!\/usr\/bin\/env python\n# Copyright (c) 2012 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\" Run the Skia render_pdfs executable. \"\"\"\n\nfrom android_build_step import AndroidBuildStep\nfrom build_step import BuildStep\nfrom render_pdfs import RenderPdfs\nfrom utils import android_utils\nimport sys\n\n\nBINARY_NAME = 'render_pdfs'\n\n\nclass AndroidRenderPdfs(RenderPdfs, AndroidBuildStep):\n def DoRenderPdfs(self):\n args = self._PdfArgs(self._device_dirs.SKPDir())\n android_utils.RunShell(self._serial, [BINARY_NAME] + args)\n\nif '__main__' == __name__:\n sys.exit(BuildStep.RunBuildStep(AndroidRenderPdfs))\n\n","new_contents":"#!\/usr\/bin\/env python\n# Copyright (c) 2012 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\" Run the Skia render_pdfs executable. \"\"\"\n\nfrom android_build_step import AndroidBuildStep\nfrom build_step import BuildStep\nfrom render_pdfs import RenderPdfs\nfrom utils import android_utils\nimport sys\n\n\nBINARY_NAME = 'render_pdfs'\n\n\nclass AndroidRenderPdfs(RenderPdfs, AndroidBuildStep):\n def DoRenderPdfs(self):\n args = self._PdfArgs(self._device_dirs.SKPDir())\n android_utils.RunSkia(self._serial, [BINARY_NAME] + args,\n use_intent=(not self._has_root),\n stop_shell=self._has_root)\n\nif '__main__' == __name__:\n sys.exit(BuildStep.RunBuildStep(AndroidRenderPdfs))\n\n","subject":"Fix RenderPDFs on Android Review URL: https:\/\/codereview.appspot.com\/7306057","message":"Fix RenderPDFs on Android\nReview URL: https:\/\/codereview.appspot.com\/7306057\n\ngit-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@7623 2bbb7eff-a529-9590-31e7-b0007b416f81\n","lang":"Python","license":"bsd-3-clause","repos":"google\/skia-buildbot,google\/skia-buildbot,google\/skia-buildbot,Tiger66639\/skia-buildbot,Tiger66639\/skia-buildbot,google\/skia-buildbot,Tiger66639\/skia-buildbot,google\/skia-buildbot,google\/skia-buildbot,Tiger66639\/skia-buildbot,Tiger66639\/skia-buildbot,google\/skia-buildbot,Tiger66639\/skia-buildbot,Tiger66639\/skia-buildbot,google\/skia-buildbot"} {"commit":"6953b831c3c48a3512a86ca9e7e92edbf7a62f08","old_file":"tests\/integration\/test_sqs.py","new_file":"tests\/integration\/test_sqs.py","old_contents":"import os\nfrom asyncaws import SQS\nfrom tornado.testing import AsyncTestCase, gen_test\n\naws_key_id = os.environ['AWS_ACCESS_KEY_ID']\naws_key_secret = os.environ['AWS_SECRET_ACCESS_KEY']\naws_region = os.environ['AWS_REGION']\n\n\nclass TestSQS(AsyncTestCase):\n sqs = SQS(aws_key_id, aws_key_secret, aws_region, async=False)\n\n @gen_test(timeout=60)\n def test_create_queue(self):\n queue_url = self.sqs.create_queue(\n \"test-queue\", {\"MessageRetentionPeriod\": 60})\n self.assertIsInstance(queue_url, str)\n self.assertTrue(queue_url.startswith('http'))\n get_attr_result = self.sqs.get_queue_attributes(\n queue_url, ['MessageRetentionPeriod'])\n self.assertIsInstance(get_attr_result, dict)\n self.assertEqual(get_attr_result['MessageRetentionPeriod'], '60')\n add_perm_result = self.sqs.add_permission(\n queue_url, ['637085312181'], [\"SendMessage\"], \"test-permission-id\")\n self.assertIsInstance(add_perm_result, str)\n delete_result = self.sqs.delete_queue(queue_url)\n self.assertIsInstance(delete_result, str)\n","new_contents":"import os\nfrom asyncaws import SQS\nfrom tornado.testing import AsyncTestCase, gen_test\nfrom random import randint\n\naws_key_id = os.environ['AWS_ACCESS_KEY_ID']\naws_key_secret = os.environ['AWS_SECRET_ACCESS_KEY']\naws_region = os.environ['AWS_REGION']\naws_test_account_id = \"637085312181\"\n\n\nclass TestSQS(AsyncTestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.sqs = SQS(aws_key_id, aws_key_secret, aws_region, async=False)\n cls.queue_name = \"test-queue-%s\" % randint(1000, 9999)\n cls.queue_url = cls.sqs.create_queue(\n cls.queue_name, {\"MessageRetentionPeriod\": 60})\n\n @classmethod\n def tearDownClass(cls):\n cls.sqs.delete_queue(cls.queue_url)\n\n @gen_test\n def test_queue_actions(self):\n self.assertTrue(self.queue_url.startswith('http'))\n get_attr_result = self.sqs.get_queue_attributes(\n self.queue_url, ['MessageRetentionPeriod'])\n self.assertIsInstance(get_attr_result, dict)\n self.assertEqual(get_attr_result['MessageRetentionPeriod'], '60')\n add_perm_result = self.sqs.add_permission(\n self.queue_url, [aws_test_account_id], [\"SendMessage\"], \"test-permission-id\")\n self.assertIsInstance(add_perm_result, str)\n","subject":"Add correct setUp\/tearDown methods for integration sqs test","message":"Add correct setUp\/tearDown methods for integration sqs test\n","lang":"Python","license":"mit","repos":"MA3STR0\/AsyncAWS"} {"commit":"180e574471d449cfb3500c720741b36008917ec0","old_file":"example_project\/urls.py","new_file":"example_project\/urls.py","old_contents":"import re\nimport sys\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.conf.urls import patterns, include, url\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\n# Admin section\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = staticfiles_urlpatterns()\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n# If we're running test, then we need to serve static files even though DEBUG\n# is false to prevent lots of 404s. So do what staticfiles_urlpatterns would do.\nif 'test' in sys.argv:\n static_url = re.escape(settings.STATIC_URL.lstrip('\/'))\n urlpatterns += patterns('',\n url(r'^%s(?P.*)$' % static_url, 'django.views.static.serve', {\n 'document_root': settings.STATIC_ROOT,\n }),\n url('^(?Pfavicon\\.ico)$', 'django.views.static.serve', {\n 'document_root': settings.STATIC_ROOT,\n }),\n )\n\nurlpatterns += patterns('',\n\n url(r'^accounts\/login\/$', 'django.contrib.auth.views.login'),\n url(r'^accounts\/logout\/$', 'django.contrib.auth.views.logout'),\n\n url(r'^', include('speeches.urls', app_name='speeches', namespace='speeches')),\n)\n","new_contents":"import re\nimport sys\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.conf.urls import patterns, include, url\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\n# Admin section\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = staticfiles_urlpatterns()\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n# If we're running test, then we need to serve static files even though DEBUG\n# is false to prevent lots of 404s. So do what staticfiles_urlpatterns would do.\nif 'test' in sys.argv:\n static_url = re.escape(settings.STATIC_URL.lstrip('\/'))\n urlpatterns += patterns('',\n url(r'^%s(?P.*)$' % static_url, 'django.views.static.serve', {\n 'document_root': settings.STATIC_ROOT,\n }),\n url('^(?Pfavicon\\.ico)$', 'django.views.static.serve', {\n 'document_root': settings.STATIC_ROOT,\n }),\n )\n\nurlpatterns += patterns('',\n (r'^admin\/doc\/', include('django.contrib.admindocs.urls')),\n (r'^admin\/', include(admin.site.urls)),\n\n url(r'^accounts\/login\/$', 'django.contrib.auth.views.login'),\n url(r'^accounts\/logout\/$', 'django.contrib.auth.views.logout'),\n\n url(r'^', include('speeches.urls', app_name='speeches', namespace='speeches')),\n)\n","subject":"Include admin in example project.","message":"Include admin in example project.\n","lang":"Python","license":"agpl-3.0","repos":"opencorato\/sayit,opencorato\/sayit,opencorato\/sayit,opencorato\/sayit"} {"commit":"7dd17cc10f7e0857ab3017177d6c4abeb115ff07","old_file":"south\/models.py","new_file":"south\/models.py","old_contents":"from django.db import models\nfrom south.db import DEFAULT_DB_ALIAS\n\nclass MigrationHistory(models.Model):\n app_name = models.CharField(max_length=255)\n migration = models.CharField(max_length=255)\n applied = models.DateTimeField(blank=True)\n\n @classmethod\n def for_migration(cls, migration, database):\n try:\n # Switch on multi-db-ness\n if database != DEFAULT_DB_ALIAS:\n # Django 1.2\n objects = cls.objects.using(database)\n else:\n # Django <= 1.1\n objects = cls.objects\n return objects.get(\n app_name=migration.app_label(),\n migration=migration.name(),\n )\n except cls.DoesNotExist:\n return cls(\n app_name=migration.app_label(),\n migration=migration.name(),\n )\n\n def get_migrations(self):\n from south.migration.base import Migrations\n return Migrations(self.app_name)\n\n def get_migration(self):\n return self.get_migrations().migration(self.migration)\n \n def __str__(self):\n return \"<%s: %s>\" % (self.app_name, self.migration)\n","new_contents":"from django.db import models\nfrom south.db import DEFAULT_DB_ALIAS\n\n# If we detect Django 1.7 or higher, then exit\n# Placed here so it's guaranteed to be imported on Django start\nimport django\nif django.VERSION[0] > 1 or (django.VERSION[0] == 1 and django.VERSION[1] > 6):\n raise RuntimeError(\"South does not support Django 1.7 or higher. Please use native Django migrations.\")\n\nclass MigrationHistory(models.Model):\n app_name = models.CharField(max_length=255)\n migration = models.CharField(max_length=255)\n applied = models.DateTimeField(blank=True)\n\n @classmethod\n def for_migration(cls, migration, database):\n try:\n # Switch on multi-db-ness\n if database != DEFAULT_DB_ALIAS:\n # Django 1.2\n objects = cls.objects.using(database)\n else:\n # Django <= 1.1\n objects = cls.objects\n return objects.get(\n app_name=migration.app_label(),\n migration=migration.name(),\n )\n except cls.DoesNotExist:\n return cls(\n app_name=migration.app_label(),\n migration=migration.name(),\n )\n\n def get_migrations(self):\n from south.migration.base import Migrations\n return Migrations(self.app_name)\n\n def get_migration(self):\n return self.get_migrations().migration(self.migration)\n \n def __str__(self):\n return \"<%s: %s>\" % (self.app_name, self.migration)\n","subject":"Add explicit version check for Django 1.7 or above","message":"Add explicit version check for Django 1.7 or above\n","lang":"Python","license":"apache-2.0","repos":"smartfile\/django-south,smartfile\/django-south"} {"commit":"b4cd58a9c5c27fb32b4f13cfc2d41206bb6b86a1","old_file":"lib\/presenter.py","new_file":"lib\/presenter.py","old_contents":"import os\nimport tempfile\nfrom subprocess import call\n\n\nclass SlidePresenter(object):\n\n def __init__(self):\n pass\n\n def present(self, slides):\n for sno, slide in enumerate(slides):\n with open(os.path.join(tempfile.gettempdir(), str(sno)+\".md\"), 'w') as f:\n f.write(slide)\n\n\nclass VimPresenter(SlidePresenter):\n\n def __init__(self, vim_rc_generator, vim_args=[]):\n super(VimPresenter, self).__init__()\n self.vim_args = vim_args\n self.vim_rc_generator = vim_rc_generator\n\n def withRC(self):\n temp_rc = self.vim_rc_generator.generateFile()\n self.vim_args += ['-u', temp_rc]\n return self\n\n def _get_command(self, num_slides):\n self.withRC()\n return ['vim'] + self.vim_args + [os.path.join(tempfile.gettempdir(), str(num)+\".md\") for num in xrange(num_slides)]\n\n def present(self, slides):\n super(VimPresenter, self).present(slides)\n call(self._get_command(len(slides)))\n\nclass VimRCGenerator(object):\n def __init__(self):\n self.rc_string = \"set nonu\"\n\n def generateFile(self):\n temp_vimrc = os.path.join(tempfile.gettempdir(), 'rand.vimrc')\n with open(temp_vimrc, 'w') as f:\n f.write(self.rc_string)\n return temp_vimrc\n","new_contents":"import os\nimport tempfile\nfrom subprocess import call\n\n\nclass SlidePresenter(object):\n\n def __init__(self):\n pass\n\n def present(self, slides):\n for sno, slide in enumerate(slides):\n with open(os.path.join(tempfile.gettempdir(), str(sno)+\".md\"), 'w') as f:\n f.write(slide)\n\n\nclass VimPresenter(SlidePresenter):\n\n def __init__(self, vim_rc_generator, vim_args=[]):\n super(VimPresenter, self).__init__()\n self.vim_args = vim_args\n self.vim_rc_generator = vim_rc_generator\n\n def withRC(self):\n temp_rc = self.vim_rc_generator.generateFile()\n self.vim_args += ['-u', temp_rc]\n return self\n\n def _get_command(self, num_slides):\n self.withRC()\n return ['vim'] + self.vim_args + [os.path.join(tempfile.gettempdir(), str(num)+\".md\") for num in range(num_slides)]\n\n def present(self, slides):\n super(VimPresenter, self).present(slides)\n call(self._get_command(len(slides)))\n\nclass VimRCGenerator(object):\n def __init__(self):\n self.rc_string = \"set nonu\"\n\n def generateFile(self):\n temp_vimrc = os.path.join(tempfile.gettempdir(), 'rand.vimrc')\n with open(temp_vimrc, 'w') as f:\n f.write(self.rc_string)\n return temp_vimrc\n","subject":"Use range instead of xrange","message":"Use range instead of xrange\n","lang":"Python","license":"mit","repos":"gabber12\/slides.vim"} {"commit":"fe85f1f135d2a7831afee6c8ab0bad394beb8aba","old_file":"src\/ais.py","new_file":"src\/ais.py","old_contents":"class MonsterAI(object):\n def __init__(self, level):\n self.owner = None\n self.level = level\n\n def take_turn(self):\n self.owner.log.log_begin_turn(self.owner.oid)\n self._take_turn()\n\n def _take_turn(self):\n raise NotImplementedError('Subclass this before usage please.')\n\n\nclass TestMonster(MonsterAI):\n def _take_turn(self):\n enemies = self.level.get_objects_outside_faction(self.owner.faction)\n if len(enemies) > 0:\n distances = {self.owner.distance_to(e): e for e in enemies}\n closest_distance = min(distances)\n closest_enemy = distances[closest_distance]\n if closest_distance <= 1.5:\n self.owner.fighter.attack(closest_enemy)\n else:\n self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level)\n","new_contents":"from src.constants import *\n\n\nclass MonsterAI(object):\n def __init__(self, level):\n self.owner = None\n self.level = level\n\n def take_turn(self):\n self.owner.log.log_begin_turn(self.owner.oid)\n self._take_turn()\n\n def _take_turn(self):\n raise NotImplementedError('Subclass this before usage please.')\n\n\nclass TestMonster(MonsterAI):\n def _take_turn(self):\n\n enemies = self.level.get_objects_outside_faction(self.owner.faction)\n\n if len(enemies) > 0:\n # Identify the closest enemy\n distances = {self.owner.distance_to(e): e for e in enemies}\n closest_distance = min(distances)\n closest_enemy = distances[closest_distance]\n\n # Inspect inventory for usable items\n if self.owner.inventory is not None:\n usable = self.owner.inventory.get_usable_items()\n throwing_items = [i for i in usable if i.item.can_use(self.owner, closest_enemy, self.level)]\n else:\n throwing_items = []\n\n # Attack if adjacent\n if closest_distance <= 1.5:\n self.owner.fighter.attack(closest_enemy)\n # Throw if you have a throwing item\n if len(throwing_items) > 0:\n throwing_items[0].item.use(self.owner, closest_enemy, self.level)\n else:\n self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level)\n","subject":"Add throwing item usage to test AI","message":"Add throwing item usage to test AI\n\nUnforutnately the item isn't evicted from the inventory on usage,\nso the guy with the throwing item can kill everybody, but it's\nworking - he does throw it!\n","lang":"Python","license":"mit","repos":"MoyTW\/RL_Arena_Experiment"} {"commit":"3db0d12163d839c00965338c4f8efe29a85b3de7","old_file":"journal.py","new_file":"journal.py","old_contents":"# -*- coding: utf-8 -*-\nfrom flask import Flask\nimport os\nimport psycopg2\nfrom contextlib import closing\n\nDB_SCHEMA = \"\"\"\nDROP TABLE IF EXISTS entries;\nCREATE TABLE entries (\n id serial PRIMARY KEY,\n title VARCHAR (127) NOT NULL,\n text TEXT NOT NULL,\n created TIMESTAMP NOT NULL\n)\n\"\"\"\n\napp = Flask(__name__)\napp.config['DATABASE'] = os.environ.get(\n 'DATABASE_URL', 'dbname=learning_journal user=miked, lfritts'\n)\n\n\ndef connect_db():\n \"\"\"Return a connection to the configured database\"\"\"\n return psycopg2.connect(app.config['DATABASE'])\n\n\ndef init_db():\n \"\"\"Initialize the database using DB_SCHEMA\n\n WARNING: executing this function will drop existing tables.\n \"\"\"\n with closing(connect_db()) as db:\n db.cursor().execute(DB_SCHEMA)\n db.commit()\n\n\n@app.route('\/')\ndef hello():\n return u'Hello world!'\n\nif __name__ == '__main__':\n app.run(debug=True)\n","new_contents":"# -*- coding: utf-8 -*-\nfrom flask import Flask\nimport os\nimport psycopg2\nfrom contextlib import closing\n\nDB_SCHEMA = \"\"\"\nDROP TABLE IF EXISTS entries;\nCREATE TABLE entries (\n id serial PRIMARY KEY,\n title VARCHAR (127) NOT NULL,\n text TEXT NOT NULL,\n created TIMESTAMP NOT NULL\n)\n\"\"\"\n\napp = Flask(__name__)\napp.config['DATABASE'] = os.environ.get(\n 'DATABASE_URL', 'dbname=learning_journal'\n)\n\n\ndef connect_db():\n \"\"\"Return a connection to the configured database\"\"\"\n return psycopg2.connect(app.config['DATABASE'])\n\n\ndef init_db():\n \"\"\"Initialize the database using DB_SCHEMA\n\n WARNING: executing this function will drop existing tables.\n \"\"\"\n with closing(connect_db()) as db:\n db.cursor().execute(DB_SCHEMA)\n db.commit()\n\n\n@app.route('\/')\ndef hello():\n return u'Hello world!'\n\nif __name__ == '__main__':\n app.run(debug=True)\n","subject":"Remove user from db connection string","message":"Remove user from db connection string\n","lang":"Python","license":"mit","repos":"lfritts\/learning_journal,lfritts\/learning_journal"} {"commit":"fe78335e4f469e22f9a1de7a1e5ddd52021a7f0f","old_file":"linesep.py","new_file":"linesep.py","old_contents":"STARTER = -1\nSEPARATOR = 0\nTERMINATOR = 1\n\ndef readlines(fp, sep, mode=TERMINATOR, retain=True, size=512):\n if mode < 0:\n return _readlines_start(fp, sep, retain, size)\n elif mode == 0:\n return _readlines_sep(fp, sep, size)\n else:\n return _readlines_term(fp, sep, retain, size)\n\ndef _readlines_start(fp, sep, retain=True, size=512):\n # Omits empty leading entry\n entries = _readlines_sep(fp, sep, size=size)\n e = next(entries)\n if e:\n yield e\n for e in entries:\n if retain:\n e = sep + e\n yield e\n\ndef _readlines_sep(fp, sep, size=512):\n buff = ''\n for chunk in iter(lambda: fp.read(size), ''):\n buff += chunk\n lines = buff.split(sep)\n buff = lines.pop()\n for l in lines:\n yield l\n yield buff\n\ndef _readlines_term(fp, sep, retain=True, size=512):\n # Omits empty trailing entry\n buff = ''\n for chunk in iter(lambda: fp.read(size), ''):\n buff += chunk\n lines = buff.split(sep)\n buff = lines.pop()\n for l in lines:\n if retain:\n l += sep\n yield l\n if buff:\n yield buff\n","new_contents":"def read_begun(fp, sep, retain=True, size=512):\n # Omits empty leading entry\n entries = read_separated(fp, sep, size=size)\n e = next(entries)\n if e:\n yield e\n for e in entries:\n if retain:\n e = sep + e\n yield e\n\ndef read_separated(fp, sep, size=512):\n buff = ''\n for chunk in iter(lambda: fp.read(size), ''):\n buff += chunk\n lines = buff.split(sep)\n buff = lines.pop()\n for l in lines:\n yield l\n yield buff\n\ndef read_terminated(fp, sep, retain=True, size=512):\n # Omits empty trailing entry\n buff = ''\n for chunk in iter(lambda: fp.read(size), ''):\n buff += chunk\n lines = buff.split(sep)\n buff = lines.pop()\n for l in lines:\n if retain:\n l += sep\n yield l\n if buff:\n yield buff\n","subject":"Use three public functions instead of one","message":"Use three public functions instead of one\n","lang":"Python","license":"mit","repos":"jwodder\/linesep"} {"commit":"93650252e195b036698ded99d271d6249f0bd80f","old_file":"project\/scripts\/dates.py","new_file":"project\/scripts\/dates.py","old_contents":"# For now I am assuming the investment date will be returned from the db \n# as a string yyyy-mm-dd, representing the day the trend was purchased in UTC time\n\n#!\/usr\/bin\/env python3\n\nfrom datetime import datetime, timedelta\nimport pytz\n\n\ndef get_start_times(date):\n \"\"\"\n date: an epoch integer representing the date that the investment was purchased\n returns the integers (year, month, day)\n \"\"\"\n datetime_object = datetime.utcfromtimestamp(date)\n return datetime_object.year, datetime_object.month, datetime_object.day\n\n\ndef get_end_times():\n \"\"\"\n returns the end dates to query pytrends for as integers (year, month, day)\n \"\"\"\n datetime = get_current_date() - timedelta(days = 1) #get yesterday's date\n return datetime.year, datetime.month, datetime.day\n\n\ndef get_current_date():\n \"\"\"\n returns the current date in UTC as a datetime object\n \"\"\"\n utc = pytz.utc\n date = datetime.now(tz=utc)\n return date\n\n\ndef date_to_epoch(date):\n \"\"\"\n converts date object back into epoch\n \"\"\"\n return date.timestamp()\n","new_contents":"# For now I am assuming the investment date will be returned from the db \n# as a string yyyy-mm-dd, representing the day the trend was purchased in UTC time\n\n#!\/usr\/bin\/env python3\n\nfrom datetime import datetime, timedelta\nimport pytz\n\n\ndef get_start_times(date):\n \"\"\"\n date: an epoch integer representing the date that the investment was purchased\n returns the integers (year, month, day)\n \"\"\"\n datetime_object = datetime.utcfromtimestamp(date)\n return datetime_object.year, datetime_object.month, datetime_object.day\n\n\ndef get_end_times():\n \"\"\"\n returns the end dates to query pytrends for as integers (year, month, day)\n \"\"\"\n datetime = get_current_date() - timedelta(days = 1) #get yesterday's date\n return datetime.year, datetime.month, datetime.day\n\n\ndef get_current_date():\n \"\"\"\n returns the current date in UTC as a datetime object\n \"\"\"\n utc = pytz.utc\n date = datetime.now(tz=utc)\n return date\n\n\ndef date_to_epoch(date):\n \"\"\"\n converts date object back into epoch\n \"\"\"\n return int(date.timestamp())\n","subject":"Make sure epoch return type is int","message":"Make sure epoch return type is int\n","lang":"Python","license":"apache-2.0","repos":"googleinterns\/sgonks,googleinterns\/sgonks,googleinterns\/sgonks,googleinterns\/sgonks"} {"commit":"e9ae6b7f92ee0a4585adc11e695cc15cbe425e23","old_file":"morepath\/app.py","new_file":"morepath\/app.py","old_contents":"from .interfaces import IRoot, IApp\nfrom .publish import publish\nfrom .request import Request\nfrom .traject import Traject\nfrom comparch import ClassRegistry, Lookup, ChainClassLookup\n\nknown_apps = {}\n\nclass App(IApp, ClassRegistry):\n def __init__(self, name='', parent=None):\n super(App, self).__init__()\n self.name = name\n self.root_model = None\n self.root_obj = None\n self.child_apps = {}\n self.parent = parent\n self.traject = Traject()\n if self.parent is not None:\n parent.add_child(self)\n\n def add_child(self, app):\n self.child_apps[app.name] = app\n self.traject.register(app.name, lambda: app, conflicting=True)\n\n def class_lookup(self):\n if self.parent is None:\n return ChainClassLookup(self, global_app)\n return ChainClassLookup(self, self.parent.class_lookup())\n \n def __call__(self, environ, start_response):\n # XXX do caching lookup where?\n lookup = Lookup(self.class_lookup())\n request = Request(environ)\n request.lookup = lookup\n response = publish(request, self, lookup)\n return response(environ, start_response)\n\nglobal_app = App()\n\n# XXX this shouldn't be here but be the root of the global app\nclass Root(IRoot):\n pass\nroot = Root()\n","new_contents":"from .interfaces import IRoot, IApp\nfrom .publish import publish\nfrom .request import Request\nfrom .traject import Traject\nfrom comparch import ClassRegistry, Lookup, ChainClassLookup\n\nknown_apps = {}\n\nclass App(IApp, ClassRegistry):\n def __init__(self, name='', parent=None):\n super(App, self).__init__()\n self.name = name\n self.root_model = None\n self.root_obj = None\n self.child_apps = {}\n self.parent = parent\n self.traject = Traject()\n if self.parent is not None:\n parent.add_child(self)\n\n def add_child(self, app):\n self.child_apps[app.name] = app\n self.traject.register(app.name, lambda: app, conflicting=True)\n\n def class_lookup(self):\n if self.parent is None:\n return ChainClassLookup(self, global_app)\n return ChainClassLookup(self, self.parent.class_lookup())\n \n def __call__(self, environ, start_response):\n # XXX do caching lookup where?\n lookup = Lookup(self.class_lookup())\n request = Request(environ)\n request.lookup = lookup\n response = publish(request, self, lookup)\n return response(environ, start_response)\n\nglobal_app = App()\n","subject":"Remove root that wasn't used.","message":"Remove root that wasn't used.\n","lang":"Python","license":"bsd-3-clause","repos":"faassen\/morepath,morepath\/morepath,taschini\/morepath"} {"commit":"a7938ed9ec814fa9cf53272ceb65e84d11d50dc1","old_file":"moto\/s3\/urls.py","new_file":"moto\/s3\/urls.py","old_contents":"from __future__ import unicode_literals\n\nfrom moto.compat import OrderedDict\nfrom .responses import S3ResponseInstance\n\nurl_bases = [\n \"https?:\/\/s3(.*).amazonaws.com\",\n \"https?:\/\/(?P[a-zA-Z0-9\\-_.]*)\\.?s3(.*).amazonaws.com\"\n]\n\nurl_paths = OrderedDict([\n # subdomain bucket\n ('{0}\/$', S3ResponseInstance.bucket_response),\n\n # subdomain key of path-based bucket\n ('{0}\/(?P.+)', S3ResponseInstance.ambiguous_response),\n\n # path-based bucket + key\n ('{0}\/(?P[a-zA-Z0-9\\-_.\/]+)\/(?P.+)', S3ResponseInstance.key_response),\n])\n","new_contents":"from __future__ import unicode_literals\n\nfrom .responses import S3ResponseInstance\n\nurl_bases = [\n \"https?:\/\/s3(.*).amazonaws.com\",\n \"https?:\/\/(?P[a-zA-Z0-9\\-_.]*)\\.?s3(.*).amazonaws.com\"\n]\n\nurl_paths = {\n # subdomain bucket\n '{0}\/$': S3ResponseInstance.bucket_response,\n\n # subdomain key of path-based bucket\n '{0}\/(?P[^\/]+)\/?$': S3ResponseInstance.ambiguous_response,\n\n # path-based bucket + key\n '{0}\/(?P[a-zA-Z0-9\\-_.\/]+)\/(?P.+)': S3ResponseInstance.key_response,\n}\n","subject":"Fix s3 url regex to ensure path-based bucket and key does not catch.","message":"Fix s3 url regex to ensure path-based bucket and key does not catch.\n","lang":"Python","license":"apache-2.0","repos":"william-richard\/moto,kefo\/moto,botify-labs\/moto,2rs2ts\/moto,dbfr3qs\/moto,im-auld\/moto,william-richard\/moto,william-richard\/moto,Affirm\/moto,kefo\/moto,botify-labs\/moto,Brett55\/moto,ZuluPro\/moto,ZuluPro\/moto,okomestudio\/moto,spulec\/moto,whummer\/moto,william-richard\/moto,kefo\/moto,kefo\/moto,ZuluPro\/moto,dbfr3qs\/moto,heddle317\/moto,Brett55\/moto,whummer\/moto,mrucci\/moto,gjtempleton\/moto,rocky4570\/moto,spulec\/moto,whummer\/moto,tootedom\/moto,Brett55\/moto,heddle317\/moto,gjtempleton\/moto,IlyaSukhanov\/moto,botify-labs\/moto,2rs2ts\/moto,spulec\/moto,william-richard\/moto,okomestudio\/moto,ZuluPro\/moto,okomestudio\/moto,whummer\/moto,gjtempleton\/moto,Affirm\/moto,rocky4570\/moto,silveregg\/moto,2rs2ts\/moto,spulec\/moto,botify-labs\/moto,okomestudio\/moto,dbfr3qs\/moto,heddle317\/moto,whummer\/moto,rocky4570\/moto,Affirm\/moto,dbfr3qs\/moto,Brett55\/moto,Brett55\/moto,dbfr3qs\/moto,spulec\/moto,2rs2ts\/moto,gjtempleton\/moto,botify-labs\/moto,botify-labs\/moto,spulec\/moto,whummer\/moto,kefo\/moto,Brett55\/moto,Affirm\/moto,braintreeps\/moto,ZuluPro\/moto,heddle317\/moto,gjtempleton\/moto,Affirm\/moto,rocky4570\/moto,okomestudio\/moto,rocky4570\/moto,Affirm\/moto,heddle317\/moto,2rs2ts\/moto,dbfr3qs\/moto,rocky4570\/moto,ZuluPro\/moto,william-richard\/moto,riccardomc\/moto,okomestudio\/moto"} {"commit":"429c2548835aef1cb1655229ee11f42ccf189bd1","old_file":"shopping_list.py","new_file":"shopping_list.py","old_contents":"shopping_list = []\n\ndef show_help():\n print(\"What should we pick up at the store?\")\n print(\"Enter DONE to stop. Enter HELP for this help. Enter SHOW to see your current list.\")\n\n","new_contents":"shopping_list = []\n\ndef show_help():\n print(\"What should we pick up at the store?\")\n print(\"Enter DONE to stop. Enter HELP for this help. Enter SHOW to see your current list.\")\n\ndef add_to_list(item):\n shopping_list.append(item)\n print(\"Added! List has {} items.\".format(len(shopping_list)))\n\n\n","subject":"Add an item to the shopping list.","message":"Add an item to the shopping list.\n","lang":"Python","license":"mit","repos":"adityatrivedi\/shopping-list"} {"commit":"39ce4e74a6b7115a35260fa2722ace1792cb1780","old_file":"python\/count_triplets.py","new_file":"python\/count_triplets.py","old_contents":"#!\/bin\/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import Counter\n\ndef countTriplets(arr, r):\n potential_triplets_with_middle = Counter()\n potential_triplets_with_end = Counter()\n total_triplets = 0\n for num in arr:\n # num completed potential_triplets_with_end[num] triplets\n if potential_triplets_with_end[num]:\n total_triplets += potential_triplets_with_end[num]\n\n # num can be the middle number in potential_triplets_with_middle[num] triplets\n if potential_triplets_with_middle[num]:\n potential_triplets_with_end[num * r] += potential_triplets_with_middle[num]\n\n # num can be the begining of a triplet\n potential_triplets_with_middle[num * r] += 1\n print(\"num\", num, \" middle\", potential_triplets_with_middle, \" end\", potential_triplets_with_end, \" total\", total_triplets)\n return total_triplets\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n nr = input().rstrip().split()\n\n n = int(nr[0])\n\n r = int(nr[1])\n\n arr = list(map(int, input().rstrip().split()))\n\n ans = countTriplets(arr, r)\n\n fptr.write(str(ans) + '\\n')\n\n fptr.close()\n","new_contents":"#!\/bin\/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import Counter\n\n\ndef countTriplets(arr, r):\n potential_triplets_with_middle = Counter()\n potential_triplets_with_end = Counter()\n total_triplets = 0\n for num in arr:\n # num completed potential_triplets_with_end[num] triplets\n if potential_triplets_with_end[num]:\n total_triplets += potential_triplets_with_end[num]\n\n # num can be the middle number in\n # potential_triplets_with_middle[num] triplets\n if potential_triplets_with_middle[num]:\n potential_triplets_with_end[num * r] += \\\n potential_triplets_with_middle[num]\n\n # num can be the begining of a triplet\n potential_triplets_with_middle[num * r] += 1\n return total_triplets\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n nr = input().rstrip().split()\n\n n = int(nr[0])\n\n r = int(nr[1])\n\n arr = list(map(int, input().rstrip().split()))\n\n ans = countTriplets(arr, r)\n\n fptr.write(str(ans) + '\\n')\n\n fptr.close()\n","subject":"Remove debug output and pycodestyle","message":"Remove debug output and pycodestyle\n","lang":"Python","license":"mit","repos":"rootulp\/hackerrank,rootulp\/hackerrank,rootulp\/hackerrank,rootulp\/hackerrank,rootulp\/hackerrank,rootulp\/hackerrank"} {"commit":"5dd78f614e5882bc2a3fcae24117a26ee34371ac","old_file":"register-result.py","new_file":"register-result.py","old_contents":"#!\/usr\/bin\/env python\n\nimport json\nimport socket\nimport sys\n\nif len(sys.argv) < 4:\n print(\"Error: Usage \")\n sys.exit(128)\n\ncheck_client = sys.argv[1]\ncheck_name = sys.argv[2]\ncheck_output = sys.argv[3]\ncheck_status = int(sys.argv[4])\ncheck_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000\n\n# Our result dict\nresult = dict()\nresult['source'] = check_client\nresult['name'] = check_name\nresult['output'] = check_output\nresult['status'] = check_status\nresult['ttl'] = check_ttl\n\n# TCP socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_address = ('localhost', 3030)\nsock.connect(server_address)\nprint (json.dumps(result))\nsocket.sendall(json.dumps(result))\n","new_contents":"#!\/usr\/bin\/env python\n\nimport json\nimport socket\nimport sys\n\nif len(sys.argv) < 4:\n print(\"Error: Usage \")\n sys.exit(128)\n\ncheck_client = sys.argv[1]\ncheck_name = sys.argv[2]\ncheck_output = sys.argv[3]\ncheck_status = int(sys.argv[4])\ncheck_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000\n\n# Our result dict\nresult = dict()\nresult['source'] = check_client\nresult['name'] = check_name\nresult['output'] = check_output\nresult['status'] = check_status\nresult['ttl'] = check_ttl\n\n# TCP socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_address = ('localhost', 3030)\nsock.connect(server_address)\nsock.sendall(json.dumps(result))\nprint (json.dumps(result))\n","subject":"Fix mistake with socket constructor","message":"Fix mistake with socket constructor\n","lang":"Python","license":"mit","repos":"panubo\/docker-monitor,panubo\/docker-monitor,panubo\/docker-monitor"} {"commit":"7124d56b3edd85c64dcc7f3ff0fa172102fe8358","old_file":"devtools\/travis-ci\/update_versions_json.py","new_file":"devtools\/travis-ci\/update_versions_json.py","old_contents":"import json\n\ntry:\n # Only works in Python 3.5\n from urllib.request import urlopen\nexcept ImportError:\n from urllib2 import urlopen\nfrom yank import version\n\nif not version.release:\n print(\"This is not a release.\")\n exit(0)\n\nURL = 'http:\/\/www.getyank.org'\ntry:\n data = urlopen(URL + '\/versions.json').read().decode()\n versions = json.loads(data)\nexcept:\n # Initial population\n versions = [\n {'version': \"0.14.1\",\n 'display': \"0.14.1\",\n 'url': \"{base}\/{version}\".format(base=URL, version=\"0.14.1\"),\n 'latest': False\n }\n ]\n\n# Debug lines\n# import pdb\n# sd = urlopen('http:\/\/mdtraj.org' + '\/versions.json').read().decode()\n# sv = json.loads(sd)\n\n# Sort the list so the versions are in the right order online\nversions = sorted(versions, key=lambda k: k['version'])\n\n# new release so all the others are now old\nfor i in range(len(versions)):\n versions[i]['latest'] = False\n\nversions.append({\n 'version': version.version,\n 'display': version.short_version,\n 'url': \"{base}\/{version}\".format(base=URL, version=version.version),\n 'latest': True,\n})\n\nwith open(\"docs\/_deploy\/versions.json\", 'w') as versionf:\n json.dump(versions, versionf, indent=2)\n","new_contents":"import json\n\ntry:\n # Only works in Python 3.5\n from urllib.request import urlopen\nexcept ImportError:\n from urllib2 import urlopen\nfrom yank import version\n\n#if not version.release:\n# print(\"This is not a release.\")\n# exit(0)\n\nURL = 'http:\/\/www.getyank.org'\ntry:\n data = urlopen(URL + '\/versions.json').read().decode()\n versions = json.loads(data)\nexcept:\n # Initial population\n versions = [\n {'version': \"0.14.1\",\n 'display': \"0.14.1\",\n 'url': \"{base}\/{version}\".format(base=URL, version=\"0.14.1\"),\n 'latest': False\n }\n ]\n\n# Debug lines\n# import pdb\n# sd = urlopen('http:\/\/mdtraj.org' + '\/versions.json').read().decode()\n# sv = json.loads(sd)\n\n# Sort the list so the versions are in the right order online\nversions = sorted(versions, key=lambda k: k['version'])\n\n# new release so all the others are now old\nfor i in range(len(versions)):\n versions[i]['latest'] = False\n\nversions.append({\n 'version': version.version,\n 'display': version.short_version,\n 'url': \"{base}\/{version}\".format(base=URL, version=version.version),\n 'latest': True,\n})\n\nwith open(\"docs\/_deploy\/versions.json\", 'w') as versionf:\n json.dump(versions, versionf, indent=2)\n","subject":"Disable the check for the initial versions push","message":"Disable the check for the initial versions push\n","lang":"Python","license":"mit","repos":"andrrizzi\/yank,andrrizzi\/yank,choderalab\/yank,andrrizzi\/yank,choderalab\/yank"} {"commit":"5e57dce84ffe7be7e699af1e2be953d5a65d8435","old_file":"tests\/test_module.py","new_file":"tests\/test_module.py","old_contents":"#!\/usr\/bin\/env python\n#\n# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)\n# Copyright (c) 2008-2014 California Institute of Technology.\n# License: 3-clause BSD. The full license text is available at:\n# - http:\/\/trac.mystic.cacr.caltech.edu\/project\/pathos\/browser\/dill\/LICENSE\n\nimport sys\nimport dill\nimport test_mixins as module\n\nmodule.a = 1234\n\npik_mod = dill.dumps(module)\n\nmodule.a = 0\n\n# remove module\ndel sys.modules[module.__name__]\ndel module\n\nmodule = dill.loads(pik_mod)\nassert module.a == 1234\nassert module.double_add(1, 2, 3) == 2 * module.fx\n","new_contents":"#!\/usr\/bin\/env python\n#\n# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)\n# Copyright (c) 2008-2014 California Institute of Technology.\n# License: 3-clause BSD. The full license text is available at:\n# - http:\/\/trac.mystic.cacr.caltech.edu\/project\/pathos\/browser\/dill\/LICENSE\n\nimport sys\nimport dill\nimport test_mixins as module\n\ncached = (module.__cached__ if hasattr(module, \"__cached__\")\n else module.__file__ + \"c\")\n\nmodule.a = 1234\n\npik_mod = dill.dumps(module)\n\nmodule.a = 0\n\n# remove module\ndel sys.modules[module.__name__]\ndel module\n\nmodule = dill.loads(pik_mod)\nassert hasattr(module, \"a\") and module.a == 1234\nassert module.double_add(1, 2, 3) == 2 * module.fx\n\n# clean up\nimport os\nos.remove(cached)\nif os.path.exists(\"__pycache__\") and not os.listdir(\"__pycache__\"):\n os.removedirs(\"__pycache__\")\n","subject":"Add code to clean up","message":"Add code to clean up\n","lang":"Python","license":"bsd-3-clause","repos":"wxiang7\/dill,mindw\/dill"} {"commit":"66a6223ca2c512f3f39ecb4867547a440611713b","old_file":"nisl\/__init__.py","new_file":"nisl\/__init__.py","old_contents":"\"\"\"\nMachine Learning module for NeuroImaging in python\n==================================================\n\nSee http:\/\/nisl.github.com for complete documentation.\n\"\"\"\n\n#from . import check_build\n#from .base import clone\n\n\ntry:\n from numpy.testing import nosetester\n\n class NoseTester(nosetester.NoseTester):\n \"\"\" Subclass numpy's NoseTester to add doctests by default\n \"\"\"\n\n def test(self, label='fast', verbose=1, extra_argv=['--exe'],\n doctests=True, coverage=False):\n \"\"\"Run the full test suite\n\n Examples\n --------\n This will run the test suite and stop at the first failing\n example\n >>> from nisl import test\n >>> test(extra_argv=['--exe', '-sx']) #doctest: +SKIP\n \"\"\"\n return super(NoseTester, self).test(label=label, verbose=verbose,\n extra_argv=extra_argv,\n doctests=doctests, coverage=coverage)\n\n test = NoseTester().test\n del nosetester\nexcept:\n pass\n\n\n__all__ = ['datasets']\n\n__version__ = '2010'\n","new_contents":"\"\"\"\nMachine Learning module for NeuroImaging in python\n==================================================\n\nSee http:\/\/nisl.github.com for complete documentation.\n\"\"\"\n\ntry:\n import numpy\nexcept ImportError:\n print 'Numpy could not be found, please install it properly to use nisl.'\n\n\ntry:\n import scipy\nexcept ImportError:\n print 'Scipy could not be found, please install it properly to use nisl.'\n\ntry:\n import sklearn\nexcept ImportError:\n print 'Sklearn could not be found, please install it properly to use nisl.'\n\n\ntry:\n from numpy.testing import nosetester\n\n class NoseTester(nosetester.NoseTester):\n \"\"\" Subclass numpy's NoseTester to add doctests by default\n \"\"\"\n\n def test(self, label='fast', verbose=1, extra_argv=['--exe'],\n doctests=True, coverage=False):\n \"\"\"Run the full test suite\n\n Examples\n --------\n This will run the test suite and stop at the first failing\n example\n >>> from nisl import test\n >>> test(extra_argv=['--exe', '-sx']) #doctest: +SKIP\n \"\"\"\n return super(NoseTester, self).test(label=label, verbose=verbose,\n extra_argv=extra_argv,\n doctests=doctests, coverage=coverage)\n\n test = NoseTester().test\n del nosetester\nexcept:\n pass\n\n\n__all__ = ['datasets']\n\n__version__ = '2010'\n","subject":"Add an error message when trying to load nisl without having Numpy, Scipy and Sklearn installed.","message":"Add an error message when trying to load nisl without having Numpy, Scipy and Sklearn installed.\n","lang":"Python","license":"bsd-3-clause","repos":"abenicho\/isvr"} {"commit":"5a74ebe16cc46b93c5d6a7cb4880e74a7ea69442","old_file":"chainerx\/_cuda.py","new_file":"chainerx\/_cuda.py","old_contents":"import chainerx\nfrom chainerx import _pybind_cuda\n\ntry:\n import cupy\n _cupy_available = True\nexcept Exception:\n _cupy_available = False\n\n\n_chainerx_allocator = None\n\n\ndef cupy_share_allocator(owner=chainerx._global_context):\n # Replace CuPy's allocator with ChainerX's if ChainerX is available with\n # the CUDA backend. This is needed in order to share the GPU memory\n # without having both modules using separate memory pools.\n\n # TODO(imanishi): Make sure this allocator works when the global\n # default context is changed by the user. It currently will not\n # since the allocator is only configured here once.\n try:\n owner.get_backend('cuda')\n except chainerx.BackendError:\n raise RuntimeError(\n 'Cannot share allocator with CuPy without the CUDA backend.')\n\n if not _cupy_available:\n raise RuntimeError(\n 'Cannot share allocator with CuPy since CuPy is not available.')\n\n param = _pybind_cuda.get_backend_ptr()\n malloc_func, free_func = _pybind_cuda.get_backend_malloc_free_ptrs()\n\n global _chainerx_allocator\n _chainerx_allocator = cupy.cuda.memory.CFunctionAllocator(\n param, malloc_func, free_func, owner)\n\n cupy.cuda.set_allocator(_chainerx_allocator.malloc)\n","new_contents":"import chainerx\n\ntry:\n import cupy\n _cupy_available = True\nexcept Exception:\n _cupy_available = False\n\n\n_chainerx_allocator = None\n\n\ndef cupy_share_allocator(owner=chainerx._global_context):\n # Replace CuPy's allocator with ChainerX's if ChainerX is available with\n # the CUDA backend. This is needed in order to share the GPU memory\n # without having both modules using separate memory pools.\n\n # TODO(imanishi): Make sure this allocator works when the global\n # default context is changed by the user. It currently will not\n # since the allocator is only configured here once.\n try:\n owner.get_backend('cuda')\n except chainerx.BackendError:\n raise RuntimeError(\n 'Cannot share allocator with CuPy without the CUDA backend.')\n\n if not _cupy_available:\n raise RuntimeError(\n 'Cannot share allocator with CuPy since CuPy is not available.')\n\n param = chainerx._pybind_cuda.get_backend_ptr()\n malloc_func, free_func = (\n chainerx._pybind_cuda.get_backend_malloc_free_ptrs())\n\n global _chainerx_allocator\n _chainerx_allocator = cupy.cuda.memory.CFunctionAllocator(\n param, malloc_func, free_func, owner)\n\n cupy.cuda.set_allocator(_chainerx_allocator.malloc)\n","subject":"Fix import error when CUDA is not available","message":"Fix import error when CUDA is not available\n","lang":"Python","license":"mit","repos":"okuta\/chainer,keisuke-umezawa\/chainer,wkentaro\/chainer,chainer\/chainer,hvy\/chainer,wkentaro\/chainer,hvy\/chainer,keisuke-umezawa\/chainer,chainer\/chainer,wkentaro\/chainer,keisuke-umezawa\/chainer,chainer\/chainer,tkerola\/chainer,keisuke-umezawa\/chainer,pfnet\/chainer,okuta\/chainer,wkentaro\/chainer,niboshi\/chainer,niboshi\/chainer,hvy\/chainer,niboshi\/chainer,okuta\/chainer,okuta\/chainer,hvy\/chainer,chainer\/chainer,niboshi\/chainer"} {"commit":"910e1a1762dac1d62c8a6749286c436d6c2b28d9","old_file":"UM\/Operations\/RemoveSceneNodeOperation.py","new_file":"UM\/Operations\/RemoveSceneNodeOperation.py","old_contents":"# Copyright (c) 2015 Ultimaker B.V.\n# Uranium is released under the terms of the AGPLv3 or higher.\n\nfrom . import Operation\n\nfrom UM.Scene.Selection import Selection\nfrom UM.Application import Application\n\n\n## An operation that removes a SceneNode from the scene.\nclass RemoveSceneNodeOperation(Operation.Operation):\n ## Initialises the RemoveSceneNodeOperation.\n #\n # \\param node The node to remove.\n def __init__(self, node):\n super().__init__()\n self._node = node\n self._parent = node.getParent()\n\n ## Undoes the operation, putting the node back in the scene.\n def undo(self):\n self._node.setParent(self._parent) # Hanging it back under its original parent puts it back in the scene.\n\n ## Redo the operation, removing the node again.\n def redo(self):\n self._node.setParent(None)\n\n\n # Hack to ensure that the _onchanged is triggered correctly.\n # We can't do it the right way as most remove changes don't need to trigger\n # a reslice (eg; removing hull nodes don't need to trigger reslice).\n try:\n Application.getInstance().getBackend().forceSlice()\n except:\n pass\n if Selection.isSelected(self._node): # Also remove the selection.\n Selection.remove(self._node)\n","new_contents":"# Copyright (c) 2015 Ultimaker B.V.\n# Uranium is released under the terms of the AGPLv3 or higher.\n\nfrom . import Operation\n\nfrom UM.Scene.Selection import Selection\nfrom UM.Application import Application\n\n\n## An operation that removes a SceneNode from the scene.\nclass RemoveSceneNodeOperation(Operation.Operation):\n ## Initialises the RemoveSceneNodeOperation.\n #\n # \\param node The node to remove.\n def __init__(self, node):\n super().__init__()\n self._node = node\n self._parent = node.getParent()\n\n ## Undoes the operation, putting the node back in the scene.\n def undo(self):\n self._node.setParent(self._parent) # Hanging it back under its original parent puts it back in the scene.\n\n ## Redo the operation, removing the node again.\n def redo(self):\n old_parent = self._parent\n self._node.setParent(None)\n\n if old_parent and old_parent.callDecoration(\"isGroup\"):\n old_parent.callDecoration(\"recomputeConvexHull\")\n\n # Hack to ensure that the _onchanged is triggered correctly.\n # We can't do it the right way as most remove changes don't need to trigger\n # a reslice (eg; removing hull nodes don't need to trigger reslice).\n try:\n Application.getInstance().getBackend().forceSlice()\n except:\n pass\n if Selection.isSelected(self._node): # Also remove the selection.\n Selection.remove(self._node)\n","subject":"Update convex hull of the group when removing a node from the group","message":"Update convex hull of the group when removing a node from the group\n\nCURA-2573\n","lang":"Python","license":"agpl-3.0","repos":"onitake\/Uranium,onitake\/Uranium"} {"commit":"a17f711a6e055a9de4674e4c35570a2c6d6f0335","old_file":"ttysend.py","new_file":"ttysend.py","old_contents":"from __future__ import print_function\nimport sys\nimport os\nimport fcntl\nimport termios\nimport argparse\n\n\nclass RootRequired(Exception):\n\n \"\"\"Our standard exception.\"\"\"\n\n pass\n\n\ndef send(data, tty):\n \"\"\"Send each char of data to tty.\"\"\"\n if(os.getuid() != 0):\n raise RootRequired('Only root can send input to other TTYs.')\n for c in data:\n fcntl.ioctl(tty, termios.TIOCSTI, c)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('tty', type=argparse.FileType('w'),\n help='display a square of a given number')\n group = parser.add_mutually_exclusive_group()\n group.add_argument('-n', action='store_true',\n help='Do not print the trailing newline character.')\n group.add_argument('--stdin', action='store_true',\n help='Read input from stdin.')\n args, data = parser.parse_known_args()\n\n # Prepare data\n if args.stdin:\n data = sys.stdin.read()\n else:\n data = ' '.join(data)\n\n # Send data\n try:\n send(data, args.tty)\n except RootRequired, e:\n sys.exit(print('ERROR:', e, file=sys.stderr))\n\n # Handle trailing newline\n if data[-1][-1] != '\\n' and not args.n:\n send('\\n', args.tty)\n","new_contents":"#!\/usr\/bin\/env python\nfrom __future__ import print_function\nimport sys\nimport os\nimport fcntl\nimport termios\nimport argparse\n\n\nclass RootRequired(Exception):\n\n \"\"\"Our standard exception.\"\"\"\n\n pass\n\n\ndef send(data, tty):\n if len(data):\n # Handle trailing newline\n if data[-1][-1] != '\\n':\n data += '\\n'\n send_raw(data, tty)\n\ndef send_raw(data, tty):\n \"\"\"Send each char of data to tty.\"\"\"\n if(os.getuid() != 0):\n raise RootRequired('Only root can send input to other TTYs.')\n for c in data:\n fcntl.ioctl(tty, termios.TIOCSTI, c)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('tty', type=argparse.FileType('w'),\n help='display a square of a given number')\n group = parser.add_mutually_exclusive_group()\n group.add_argument('-n', action='store_true',\n help='Do not force a trailing newline character.')\n group.add_argument('--stdin', action='store_true',\n help='Read input from stdin.')\n args, data = parser.parse_known_args()\n\n # Prepare data\n if args.stdin:\n data = sys.stdin.read()\n else:\n data = ' '.join(data)\n\n # Send data\n try:\n if args.n:\n send_raw(data, args.tty)\n else:\n send(data, args.tty)\n except RootRequired, e:\n sys.exit(print('ERROR:', e, file=sys.stderr))\n","subject":"Move newline handling to a function.","message":"Move newline handling to a function.\n\nAllows library users to choose to force trailing newlines.\n","lang":"Python","license":"mit","repos":"RichardBronosky\/ttysend"} {"commit":"782c1b8379d38f99de413398919aa797af0df645","old_file":"plot_s_curve.py","new_file":"plot_s_curve.py","old_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nfrom numpy import array, log\nimport sys\n\nx = []\n\ny = []\n\ninfile = open(sys.argv[1])\n\nfor line in infile:\n data = line.replace('\\n','').split()\n print(data)\n try : \n x.append(float(data[0]))\n y.append(float(data[1]))\n except ValueError:\n pass\n\n#x = array(x)\n#y = array(y)\n\nfigManager = plt.get_current_fig_manager()\nfigManager.window.showMaximized()\n#plt.plot(log(x),log(y))\nplt.plot(x,y,\"o\")\n\nplt.ylabel('$\\log T$')\nplt.xlabel('$\\log \\Sigma$')\nplt.grid()\nplt.show()\n","new_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nfrom numpy import array, log\nimport sys\nimport os\n\nimport matplotlib.animation as animation\n\nfig = plt.figure()\n\ninpath = sys.argv[1]\n\nif os.path.isfile(inpath):\n print('Visiting {}'.format(inpath))\n filenames = [inpath]\nelse:\n _filenames = os.listdir(inpath)\n _filenames.sort()\n filesnames = [inpath + '\/' + fname for fname in _filesnames if '_tot.dat' in fname]\n \n print('Visiting all files of {}'.format(inpath))\n\naxline, = plt.plot(0, 0, 'o')\n\ndef draw_once(filename):\n x = []\n y = []\n if not 'tot.dat' in filename:\n return ([0], [0])\n else:\n print('Visiting {}'.format(filename))\n outfile = filename.replace('.dat', '.png')\n \n for line in open(filename):\n data = line.replace('\\n', '').split()\n try :\n print (data)\n xData = float(data[0])\n yData = float(data[1])\n x.append(xData)\n y.append(yData)\n except ValueError:\n pass\n\n axline.set_xdata(x)\n axline.set_ydata(y)\n\n return axline,\n\ndef init():\n print('Initialisation')\n plt.ylabel('$\\log T$')\n plt.xlabel('$\\log \\Sigma$')\n plt.xlim(1.8, 4)\n plt.ylim(6, 8)\n plt.grid()\n\nif len(filenames) > 1:\n ani = animation.FuncAnimation(fig, draw_once, filenames, init_func=init, interval=10)\nelse:\n init()\n draw_once(filenames[0])\n plt.show()\n# x, y = draw_once(filenames[2])\n# plt.plot(x, y, 'o')\n\n","subject":"Use animation if dirname is provided","message":"Use animation if dirname is provided\n","lang":"Python","license":"mit","repos":"M2-AAIS\/BAD"} {"commit":"c42ce24984b557b8b82c252112310e8d259e79df","old_file":"setup.py","new_file":"setup.py","old_contents":"#!\/usr\/bin\/env python3\n\nfrom setuptools import setup, find_packages\n\nsetup(\n name='ppp_datamodel',\n version='0.5.3',\n description='Data model for the Projet Pensées Profondes.',\n url='https:\/\/github.com\/ProjetPP\/PPP-datamodel-Python',\n author='Valentin Lorentz',\n author_email='valentin.lorentz+ppp@ens-lyon.org',\n license='MIT',\n classifiers=[\n 'Development Status :: 1 - Planning',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Topic :: Software Development :: Libraries',\n ],\n install_requires=[\n ],\n packages=[\n 'ppp_datamodel',\n ],\n)\n\n\n","new_contents":"#!\/usr\/bin\/env python3\n\nfrom setuptools import setup, find_packages\n\nsetup(\n name='ppp_datamodel',\n version='0.5.4',\n description='Data model for the Projet Pensées Profondes.',\n url='https:\/\/github.com\/ProjetPP\/PPP-datamodel-Python',\n author='Valentin Lorentz',\n author_email='valentin.lorentz+ppp@ens-lyon.org',\n license='MIT',\n classifiers=[\n 'Development Status :: 1 - Planning',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Topic :: Software Development :: Libraries',\n ],\n install_requires=[\n ],\n packages=[\n 'ppp_datamodel',\n ],\n)\n\n\n","subject":"Bump version number to 0.5.4.","message":"Bump version number to 0.5.4.\n","lang":"Python","license":"agpl-3.0","repos":"ProjetPP\/PPP-datamodel-Python,ProjetPP\/PPP-datamodel-Python"} {"commit":"c5ef0d8333bb427c588aa65ee6f081742c31c41e","old_file":"setup.py","new_file":"setup.py","old_contents":"from setuptools import setup, find_packages\n\n\nsetup(\n name='snippets',\n version='0.0.dev',\n license='ISC',\n description='Code snippets repository generator',\n url='https:\/\/github.com\/trilan\/snippets',\n author='Mike Yumatov',\n author_email='mike@yumatov.org',\n packages=find_packages(),\n classifiers=[\n 'Development Status :: 1 - Planning',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: ISC License (ISCL)',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet :: WWW\/HTTP',\n ],\n)\n","new_contents":"from setuptools import setup, find_packages\n\n\nsetup(\n name='snippets',\n version='0.0.dev',\n license='ISC',\n description='Code snippets repository generator',\n url='https:\/\/github.com\/trilan\/snippets',\n author='Mike Yumatov',\n author_email='mike@yumatov.org',\n packages=find_packages(),\n install_requires=[\n 'Pygments',\n ],\n classifiers=[\n 'Development Status :: 1 - Planning',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: ISC License (ISCL)',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet :: WWW\/HTTP',\n ],\n)\n","subject":"Add Pygments as installation requirement","message":"Add Pygments as installation requirement\n","lang":"Python","license":"isc","repos":"trilan\/snippets,trilan\/snippets"} {"commit":"56572fd9e38274074c8476f25dd47ee0799271ea","old_file":"setup.py","new_file":"setup.py","old_contents":"from distutils.core import setup\nsetup(name='pv_atmos',\n version='1.1',\n description='Utilities for scientific visualization with ParaView',\n long_description='This package is described in a peer-reviewed open access article, which can be found at http:\/\/dx.doi.org\/10.5334\/jors.al'.\n author='Martin Jucker',\n url='https:\/\/github.com\/mjucker\/pv_atmos',\n package_dir={'pv_atmos': ''},\n packages=['pv_atmos'],\n )","new_contents":"from distutils.core import setup\nsetup(name='pv_atmos',\n version='1.1.1',\n description='Utilities for scientific visualization with ParaView',\n long_description='This package is described in a peer-reviewed open access article, which can be found at http:\/\/dx.doi.org\/10.5334\/jors.al'.\n author='Martin Jucker',\n url='https:\/\/github.com\/mjucker\/pv_atmos',\n package_dir={'pv_atmos': ''},\n packages=['pv_atmos'],\n )\n","subject":"Update to appropriate version number","message":"Update to appropriate version number","lang":"Python","license":"mit","repos":"mjucker\/pv_atmos"} {"commit":"e61b7b91157f0d198c90cb3652f6656bd6c44cba","old_file":"setup.py","new_file":"setup.py","old_contents":"\"\"\"Setup script to generate an stand-alone executable.\n\nAuthor-email: \"Dietmar Winkler\" \n\nLicense: See UNLICENSE file\n\nUsage: Run the build process by running the command 'python setup.py build'\n If everything works well you should find a subdirectory in the build\n subdirectory that contains the files needed to run the script\n without Python\n\n\"\"\"\n\nfrom setuptools import setup, find_packages\n\n\nCLASSIFIERS = \"\"\"\nEnvironment :: Console\nIntended Audience :: Developers\nOperating System :: OS Independent\nProgramming Language :: Python :: 2\n\"\"\".strip().splitlines()\n\nMETA = {\n 'name': 'ttws',\n 'url': 'https:\/\/github.com\/dietmarw\/trimtrailingwhitespaces',\n 'version': '0.3',\n 'description': 'WSGI middleware to handle HTTP responses using exceptions',\n 'description': 'Script to remove trailing whitespaces from textfiles.',\n 'classifiers': CLASSIFIERS,\n 'license': 'UNLICENSE',\n 'author': 'Dietmar Winkler',\n 'author_email': 'http:\/\/claimid\/dietmarw',\n 'packages': find_packages(exclude=['test']),\n 'entry_points': {\n 'console_scripts': 'ttws = ttws.cli:main'\n },\n 'platforms': 'Posix; MacOS X; Windows',\n 'include_package_data': False,\n 'zip_safe': False,\n 'install_requires': ['pyparsing'],\n 'extras_require': {\n 'testing': ['pytest']\n }\n}\n\n\nif __name__ == '__main__':\n setup(**META)\n","new_contents":"\"\"\"Setup script to generate an stand-alone executable.\n\nAuthor-email: \"Dietmar Winkler\" \n\nLicense: See UNLICENSE file\n\nUsage: Run the build process by running the command 'python setup.py build'\n If everything works well you should find a subdirectory in the build\n subdirectory that contains the files needed to run the script\n without Python\n\n\"\"\"\n\nfrom setuptools import setup, find_packages\n\n\nCLASSIFIERS = \"\"\"\nEnvironment :: Console\nIntended Audience :: Developers\nOperating System :: OS Independent\nProgramming Language :: Python :: 2\n\"\"\".strip().splitlines()\n\nMETA = {\n 'name': 'ttws',\n 'url': 'https:\/\/github.com\/dietmarw\/trimtrailingwhitespaces',\n 'version': '0.3',\n 'description': 'Script to remove trailing whitespaces from textfiles.',\n 'classifiers': CLASSIFIERS,\n 'license': 'UNLICENSE',\n 'author': 'Dietmar Winkler',\n 'author_email': 'http:\/\/claimid\/dietmarw',\n 'packages': find_packages(exclude=['test']),\n 'entry_points': {\n 'console_scripts': 'ttws = ttws.cli:main'\n },\n 'platforms': 'Posix; MacOS X; Windows',\n 'include_package_data': False,\n 'zip_safe': False,\n 'install_requires': ['pyparsing'],\n 'extras_require': {\n 'testing': ['pytest']\n }\n}\n\n\nif __name__ == '__main__':\n setup(**META)\n","subject":"Remove string from a copy and paste fail.","message":"Remove string from a copy and paste fail.\n","lang":"Python","license":"unlicense","repos":"dietmarw\/trimtrailingwhitespaces"} {"commit":"7886e2a7b55ad03e125f7e69a78574c2044b518b","old_file":"setup.py","new_file":"setup.py","old_contents":"#!\/usr\/bin\/env python\nfrom setuptools import setup\n\nsetup(\n name='py-vkontakte',\n version='2016.8',\n packages=['vk'],\n url='https:\/\/github.com\/sgaynetdinov\/py-vkontakte',\n license='MIT License',\n author='Sergey Gaynetdinov',\n author_email='s.gaynetdinov@gmail.com',\n description='Python API wrapper around vk.com API',\n classifiers=[\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7'\n ],\n install_requires=[\n 'requests',\n ],\n)\n","new_contents":"#!\/usr\/bin\/env python\nfrom setuptools import setup\n\nsetup(\n name='py-vkontakte',\n version='2016.10',\n packages=['vk'],\n url='https:\/\/github.com\/sgaynetdinov\/py-vkontakte',\n license='MIT License',\n author='Sergey Gaynetdinov',\n author_email='s.gaynetdinov@gmail.com',\n description='Python API wrapper around vk.com API',\n classifiers=[\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7'\n ],\n install_requires=[\n 'requests',\n ],\n)\n","subject":"Change version `2016.8` => `2016.10`","message":"Change version `2016.8` => `2016.10`\n","lang":"Python","license":"mit","repos":"sgaynetdinov\/py-vkontakte"} {"commit":"02d3f0f0b7c27f04289f8fd488973fdf17c8f42f","old_file":"setup.py","new_file":"setup.py","old_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\n\nimport xml4h\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nsetup(\n name=xml4h.__title__,\n version=xml4h.__version__,\n description='XML for Humans in Python',\n long_description=open('README.rst').read(),\n author='James Murty',\n author_email='james@murty.co',\n url='https:\/\/github.com\/jmurty\/xml4h',\n packages=[\n 'xml4h',\n 'xml4h.impls',\n ],\n package_dir={'xml4h': 'xml4h'},\n package_data={'': ['README.rst', 'LICENSE']},\n include_package_data=True,\n install_requires=[\n 'six',\n ],\n license=open('LICENSE').read(),\n # http:\/\/pypi.python.org\/pypi?%3Aaction=list_classifiers\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Topic :: Text Processing :: Markup :: XML',\n 'Natural Language :: English',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n # 'Programming Language :: Python :: 3.0',\n # 'Programming Language :: Python :: 3.1',\n # 'Programming Language :: Python :: 3.2',\n ],\n test_suite='tests',\n)\n","new_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\n\nimport xml4h\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nsetup(\n name=xml4h.__title__,\n version=xml4h.__version__,\n description='XML for Humans in Python',\n long_description=open('README.rst').read(),\n author='James Murty',\n author_email='james@murty.co',\n url='https:\/\/github.com\/jmurty\/xml4h',\n packages=[\n 'xml4h',\n 'xml4h.impls',\n ],\n package_dir={'xml4h': 'xml4h'},\n package_data={'': ['README.rst', 'LICENSE']},\n include_package_data=True,\n install_requires=[\n 'six',\n ],\n license=open('LICENSE').read(),\n # http:\/\/pypi.python.org\/pypi?%3Aaction=list_classifiers\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Topic :: Text Processing :: Markup :: XML',\n 'Natural Language :: English',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n ],\n test_suite='tests',\n)\n","subject":"Update Python version classifiers to supported versions","message":"Update Python version classifiers to supported versions\n","lang":"Python","license":"mit","repos":"jmurty\/xml4h"} {"commit":"cb965a2dc227c9c498a8c95f48bb5ce24a6db66c","old_file":"setup.py","new_file":"setup.py","old_contents":"from distutils.core import setup\n\ndesc = (\n 'An interface to the Pluggable Authentication Modules (PAM) library'\n 'on linux, written in pure python (using ctypes)'\n)\n\nsetup(name='python3-simplepam', version='0.1.4',\n description=desc,\n py_modules=['simplepam'],\n author='Leon Weber , Chris AtLee ',\n author_email='leon@leonweber.de',\n url='https:\/\/github.com\/leonnnn\/python3-simplepam',\n license='MIT'\n )\n","new_contents":"from distutils.core import setup\n\ndesc = (\n 'An interface to the Pluggable Authentication Modules (PAM) library '\n 'on linux, written in pure python (using ctypes)'\n)\n\nsetup(name='python3-simplepam', version='0.1.4',\n description=desc,\n py_modules=['simplepam'],\n author='Leon Weber , Chris AtLee ',\n author_email='leon@leonweber.de',\n url='https:\/\/github.com\/leonnnn\/python3-simplepam',\n license='MIT'\n )\n","subject":"Add missing space in description","message":"Add missing space in description\n","lang":"Python","license":"mit","repos":"leonnnn\/python3-simplepam"} {"commit":"38d30c5589dfbdae92198a404d58400ec3c2ed4b","old_file":"setup.py","new_file":"setup.py","old_contents":"from setuptools import setup, find_packages\n\n\nsetup(\n name=\"echidna\",\n version=\"0.0.1-dev\",\n url='http:\/\/github.com\/praekelt\/echidna',\n license='BSD',\n description='A scalable pub-sub WebSocket service.',\n long_description=open('README.rst', 'r').read(),\n author='Praekelt Foundation',\n author_email='dev@praekeltfoundation.org',\n packages=find_packages(),\n install_requires=[\n 'Twisted',\n 'cyclone',\n 'txzookeeper',\n 'redis',\n 'zope.dottedname',\n ],\n tests_require=[\n 'ws4py',\n 'requests',\n ],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Web Environment',\n 'Framework :: Cyclone',\n 'Framework :: Twisted',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: POSIX',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Communications',\n 'Topic :: Internet',\n 'Topic :: System :: Networking',\n ]\n)\n","new_contents":"from setuptools import setup, find_packages\n\n\nsetup(\n name=\"echidna\",\n version=\"0.0.1-dev\",\n url='http:\/\/github.com\/praekelt\/echidna',\n license='BSD',\n description='A scalable pub-sub WebSocket service.',\n long_description=open('README.rst', 'r').read(),\n author='Praekelt Foundation',\n author_email='dev@praekeltfoundation.org',\n packages=find_packages(),\n install_requires=[\n 'Twisted',\n 'cyclone',\n 'txzookeeper',\n 'redis',\n 'zope.dottedname',\n 'ws4py',\n ],\n tests_require=[\n 'ws4py',\n 'requests',\n ],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Web Environment',\n 'Framework :: Cyclone',\n 'Framework :: Twisted',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: POSIX',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Communications',\n 'Topic :: Internet',\n 'Topic :: System :: Networking',\n ]\n)\n","subject":"Add ws4py to normal requirements in an attempt to get Travis to install it","message":"Add ws4py to normal requirements in an attempt to get Travis to install it\n","lang":"Python","license":"bsd-3-clause","repos":"praekelt\/echidna,praekelt\/echidna,praekelt\/echidna,praekelt\/echidna"} {"commit":"4a810640a3ccdaaa975b9d1b807ff7365282e5b9","old_file":"django_website\/settings\/docs.py","new_file":"django_website\/settings\/docs.py","old_contents":"from django_website.settings.www import *\n\nPREPEND_WWW = False\nAPPEND_SLASH = True\nINSTALLED_APPS = ['django_website.docs']\nTEMPLATE_CONTEXT_PROCESSORS += [\"django.core.context_processors.request\"]\nROOT_URLCONF = 'django_website.urls.docs'\nCACHE_MIDDLEWARE_KEY_PREFIX = 'djangodocs'\n\n# Where to store the build Sphinx docs.\nif PRODUCTION:\n DOCS_BUILD_ROOT = BASE.parent.child('docbuilds')\nelse:\n DOCS_BUILD_ROOT = '\/tmp\/djangodocs'\n","new_contents":"from django_website.settings.www import *\n\nPREPEND_WWW = False\nAPPEND_SLASH = True\nINSTALLED_APPS = ['django_website.docs']\nTEMPLATE_CONTEXT_PROCESSORS += [\"django.core.context_processors.request\"]\nROOT_URLCONF = 'django_website.urls.docs'\nCACHE_MIDDLEWARE_KEY_PREFIX = 'djangodocs'\n\n# Where to store the build Sphinx docs.\nif PRODUCTION:\n DOCS_BUILD_ROOT = BASE.ancestor(2).child('docbuilds')\nelse:\n DOCS_BUILD_ROOT = '\/tmp\/djangodocs'\n","subject":"Fix the docbuilds path location.","message":"Fix the docbuilds path location.\n","lang":"Python","license":"bsd-3-clause","repos":"relekang\/djangoproject.com,gnarf\/djangoproject.com,relekang\/djangoproject.com,django\/djangoproject.com,django\/djangoproject.com,khkaminska\/djangoproject.com,nanuxbe\/django,khkaminska\/djangoproject.com,nanuxbe\/django,vxvinh1511\/djangoproject.com,django\/djangoproject.com,django\/djangoproject.com,vxvinh1511\/djangoproject.com,rmoorman\/djangoproject.com,nanuxbe\/django,django\/djangoproject.com,khkaminska\/djangoproject.com,django\/djangoproject.com,hassanabidpk\/djangoproject.com,hassanabidpk\/djangoproject.com,khkaminska\/djangoproject.com,rmoorman\/djangoproject.com,xavierdutreilh\/djangoproject.com,alawnchen\/djangoproject.com,vxvinh1511\/djangoproject.com,xavierdutreilh\/djangoproject.com,alawnchen\/djangoproject.com,rmoorman\/djangoproject.com,alawnchen\/djangoproject.com,hassanabidpk\/djangoproject.com,gnarf\/djangoproject.com,alawnchen\/djangoproject.com,relekang\/djangoproject.com,relekang\/djangoproject.com,nanuxbe\/django,hassanabidpk\/djangoproject.com,vxvinh1511\/djangoproject.com,rmoorman\/djangoproject.com,xavierdutreilh\/djangoproject.com,gnarf\/djangoproject.com,gnarf\/djangoproject.com,xavierdutreilh\/djangoproject.com"} {"commit":"f39c6ff64478f4b20f5eaa26ec060275cdc81813","old_file":"setup.py","new_file":"setup.py","old_contents":"from setuptools import setup, find_packages\n\nimport codecs\nimport os\nimport re\n\nroot_dir = os.path.abspath(os.path.dirname(__file__))\nPACKAGE = 'hackernews_scraper'\n\ndef get_version(package_name):\n version_re = re.compile(r\"^__version__ = [\\\"']([\\w_.-]+)[\\\"']$\")\n package_components = package_name.split('.')\n init_path = os.path.join(root_dir, *(package_components + ['__init__.py']))\n with codecs.open(init_path, 'r', 'utf-8') as f:\n for line in f:\n match = version_re.match(line[:-1])\n if match:\n return match.groups()[0]\n return '0.1.0'\n\nsetup(name=PACKAGE\n description='Python library for retrieving comments and stories from HackerNews',\n packages=find_packages(),\n version=get_version(PACKAGE),\n install_requires=['requests'],\n url='https:\/\/github.com\/NiGhTTraX\/hackernews-scraper',\n license='MIT',\n platforms='any',\n tests_require=['nose', 'factory_boy', 'httpretty'],\n )\n","new_contents":"from setuptools import setup, find_packages\n\nimport codecs\nimport os\nimport re\n\nroot_dir = os.path.abspath(os.path.dirname(__file__))\nPACKAGE = 'hackernews_scraper'\n\ndef get_version(package_name):\n version_re = re.compile(r\"^__version__ = [\\\"']([\\w_.-]+)[\\\"']$\")\n package_components = package_name.split('.')\n init_path = os.path.join(root_dir, *(package_components + ['__init__.py']))\n with codecs.open(init_path, 'r', 'utf-8') as f:\n for line in f:\n match = version_re.match(line[:-1])\n if match:\n return match.groups()[0]\n raise Exception(\"No package version found!\")\n\nsetup(name=PACKAGE\n description='Python library for retrieving comments and stories from HackerNews',\n packages=find_packages(),\n version=get_version(PACKAGE),\n install_requires=['requests'],\n url='https:\/\/github.com\/NiGhTTraX\/hackernews-scraper',\n license='MIT',\n platforms='any',\n tests_require=['nose', 'factory_boy', 'httpretty'],\n )\n","subject":"Raise exception if version does not exist","message":"Raise exception if version does not exist\n","lang":"Python","license":"bsd-2-clause","repos":"NiGhTTraX\/hackernews-scraper"} {"commit":"a0e795cb0bed84ae6161f5e64290910f2ffe8ee6","old_file":"setup.py","new_file":"setup.py","old_contents":"#!\/usr\/bin\/env python\nimport collections\nfrom setuptools import setup\n\nfrom pip.req import parse_requirements\n\ndependency_links = []\ninstall_requires = []\n\nReqOpts = collections.namedtuple('ReqOpts', ['skip_requirements_regex', 'default_vcs'])\n\nopts = ReqOpts(None, 'git')\n\nfor ir in parse_requirements(\"requirements.txt\", options=opts):\n if ir is not None:\n if ir.url is not None:\n dependency_links.append(str(ir.url))\n if ir.req is not None:\n install_requires.append(str(ir.req))\n\nsetup(\n name='vertica-python',\n version='0.1',\n description='A native Python client for the Vertica database.',\n author='Justin Berka',\n author_email='justin@uber.com',\n url='https:\/\/github.com\/uber\/vertica-python\/',\n keywords=\"database vertica\",\n packages=['vertica_python'],\n license=\"MIT\",\n install_requires=install_requires,\n dependency_links=dependency_links,\n classifiers = [\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python\",\n \"Topic :: Database\",\n \"Topic :: Database :: Database Engines\/Servers\",\n \"Operating System :: OS Independent\"\n ]\n)\n","new_contents":"#!\/usr\/bin\/env python\nimport collections\nfrom setuptools import setup\n\nfrom pip.req import parse_requirements\n\ndependency_links = []\ninstall_requires = []\n\nReqOpts = collections.namedtuple('ReqOpts', ['skip_requirements_regex', 'default_vcs'])\n\nopts = ReqOpts(None, 'git')\n\nfor ir in parse_requirements(\"requirements.txt\", options=opts):\n if ir is not None:\n if ir.url is not None:\n dependency_links.append(str(ir.url))\n if ir.req is not None:\n install_requires.append(str(ir.req))\n\nsetup(\n name='vertica-python',\n version='0.1',\n description='A native Python client for the Vertica database.',\n author='Justin Berka',\n author_email='justin@uber.com',\n url='https:\/\/github.com\/uber\/vertica-python\/',\n keywords=\"database vertica\",\n packages=['vertica_python'],\n package_data={\n '': ['*.txt', '*.md'],\n },\n license=\"MIT\",\n install_requires=install_requires,\n dependency_links=dependency_links,\n classifiers = [\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python\",\n \"Topic :: Database\",\n \"Topic :: Database :: Database Engines\/Servers\",\n \"Operating System :: OS Independent\"\n ]\n)\n","subject":"Add .md and .txt files to package","message":"Add .md and .txt files to package\n","lang":"Python","license":"apache-2.0","repos":"uber\/vertica-python,twneale\/vertica-python,brokendata\/vertica-python,natthew\/vertica-python,dennisobrien\/vertica-python"} {"commit":"c3bb736962d77d1fdd0207ba2ee487c1177451c7","old_file":"setup.py","new_file":"setup.py","old_contents":"#!\/usr\/bin\/env python\n\nfrom distutils.core import setup\n\nwith open('README.rst') as file:\n long_description = file.read()\n\nclassifiers = [\n 'Programming Language :: Python :: 3',\n 'Development Status :: 5 - Production\/Stable',\n 'License :: OSI Approved',\n 'Intended Audience :: Developers',\n 'Natural Language :: French',\n 'Operating System :: OS Independent',\n 'Topic :: Utilities',\n]\n\nsetup(name='PyEventEmitter',\n version='1.0.2',\n description='Simple python events library',\n long_description=long_description,\n author='Etienne Tissieres',\n author_email='etienne.tissieres@gmail.com',\n url='https:\/\/github.com\/etissieres\/PyEventEmitter',\n packages=['event_emitter'],\n license='MIT',\n classifiers=classifiers)\n","new_contents":"#!\/usr\/bin\/env python\n\nfrom distutils.core import setup\n\nwith open('README.rst') as file:\n long_description = file.read()\n\nclassifiers = [\n 'Programming Language :: Python :: 3',\n 'Development Status :: 5 - Production\/Stable',\n 'License :: OSI Approved',\n 'Intended Audience :: Developers',\n 'Natural Language :: French',\n 'Operating System :: OS Independent',\n 'Topic :: Utilities',\n]\n\nsetup(name='PyEventEmitter',\n version='1.0.3',\n description='Simple python events library',\n long_description=long_description,\n author='Etienne Tissieres',\n author_email='etienne.tissieres@gmail.com',\n url='https:\/\/github.com\/etissieres\/PyEventEmitter',\n packages=['event_emitter'],\n license='MIT',\n classifiers=classifiers)\n","subject":"Upgrade version to publish a release without tests","message":"Upgrade version to publish a release without tests\n","lang":"Python","license":"mit","repos":"etissieres\/PyEventEmitter"} {"commit":"1372c00a0668cc6a39953264d23f012391afe768","old_file":"python\/helpers\/pycharm\/_jb_unittest_runner.py","new_file":"python\/helpers\/pycharm\/_jb_unittest_runner.py","old_contents":"# coding=utf-8\nimport os\nfrom unittest import main\n\nfrom _jb_runner_tools import jb_start_tests, jb_doc_args\nfrom teamcity import unittestpy\n\nif __name__ == '__main__':\n path, targets, additional_args = jb_start_tests()\n\n args = [\"python -m unittest\"]\n if path:\n discovery_args = [\"discover\", \"-s\"]\n # Unittest does not support script directly, but it can use \"discover\" to find all tests in some folder\n # filtering by script\n assert os.path.exists(path), \"{0}: No such file or directory\".format(path)\n if os.path.isfile(path):\n discovery_args += [os.path.dirname(path), \"-p\", os.path.basename(path)]\n else:\n discovery_args.append(path)\n additional_args = discovery_args + additional_args\n else:\n additional_args += targets\n args += additional_args\n jb_doc_args(\"unittests\", args)\n main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner())\n","new_contents":"# coding=utf-8\nimport os\nfrom unittest import main\n\nfrom _jb_runner_tools import jb_start_tests, jb_doc_args\nfrom teamcity import unittestpy\n\nif __name__ == '__main__':\n path, targets, additional_args = jb_start_tests()\n\n args = [\"python -m unittest\"]\n if path:\n discovery_args = [\"discover\", \"-s\"]\n # Unittest does not support script directly, but it can use \"discover\" to find all tests in some folder\n # filtering by script\n assert os.path.exists(path), \"{0}: No such file or directory\".format(path)\n if os.path.isfile(path):\n discovery_args += [os.path.dirname(path), \"-p\", os.path.basename(path)]\n else:\n discovery_args.append(path)\n additional_args = discovery_args + additional_args\n elif targets:\n additional_args += targets\n args += additional_args\n jb_doc_args(\"unittests\", args)\n main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner())\n","subject":"Check variable before accessing it","message":"PY-22460: Check variable before accessing it\n","lang":"Python","license":"apache-2.0","repos":"mglukhikh\/intellij-community,ThiagoGarciaAlves\/intellij-community,asedunov\/intellij-community,vvv1559\/intellij-community,signed\/intellij-community,suncycheng\/intellij-community,mglukhikh\/intellij-community,allotria\/intellij-community,xfournet\/intellij-community,signed\/intellij-community,mglukhikh\/intellij-community,xfournet\/intellij-community,FHannes\/intellij-community,da1z\/intellij-community,asedunov\/intellij-community,ibinti\/intellij-community,ThiagoGarciaAlves\/intellij-community,mglukhikh\/intellij-community,semonte\/intellij-community,allotria\/intellij-community,allotria\/intellij-community,signed\/intellij-community,vvv1559\/intellij-community,apixandru\/intellij-community,suncycheng\/intellij-community,mglukhikh\/intellij-community,signed\/intellij-community,vvv1559\/intellij-community,asedunov\/intellij-community,vvv1559\/intellij-community,apixandru\/intellij-community,semonte\/intellij-community,mglukhikh\/intellij-community,mglukhikh\/intellij-community,asedunov\/intellij-community,allotria\/intellij-community,ibinti\/intellij-community,allotria\/intellij-community,allotria\/intellij-community,ThiagoGarciaAlves\/intellij-community,suncycheng\/intellij-community,apixandru\/intellij-community,asedunov\/intellij-community,ThiagoGarciaAlves\/intellij-community,vvv1559\/intellij-community,semonte\/intellij-community,xfournet\/intellij-community,vvv1559\/intellij-community,suncycheng\/intellij-community,xfournet\/intellij-community,signed\/intellij-community,signed\/intellij-community,ThiagoGarciaAlves\/intellij-community,da1z\/intellij-community,apixandru\/intellij-community,apixandru\/intellij-community,semonte\/intellij-community,signed\/intellij-community,mglukhikh\/intellij-community,xfournet\/intellij-community,asedunov\/intellij-community,ibinti\/intellij-community,ibinti\/intellij-community,vvv1559\/intellij-community,FHannes\/intellij-community,FHannes\/intellij-community,suncycheng\/intellij-community,semonte\/intellij-community,asedunov\/intellij-community,signed\/intellij-community,ibinti\/intellij-community,xfournet\/intellij-community,da1z\/intellij-community,vvv1559\/intellij-community,semonte\/intellij-community,da1z\/intellij-community,semonte\/intellij-community,ibinti\/intellij-community,FHannes\/intellij-community,FHannes\/intellij-community,signed\/intellij-community,ibinti\/intellij-community,ibinti\/intellij-community,da1z\/intellij-community,allotria\/intellij-community,apixandru\/intellij-community,da1z\/intellij-community,ThiagoGarciaAlves\/intellij-community,allotria\/intellij-community,suncycheng\/intellij-community,apixandru\/intellij-community,FHannes\/intellij-community,da1z\/intellij-community,da1z\/intellij-community,xfournet\/intellij-community,ThiagoGarciaAlves\/intellij-community,mglukhikh\/intellij-community,ibinti\/intellij-community,xfournet\/intellij-community,xfournet\/intellij-community,asedunov\/intellij-community,semonte\/intellij-community,FHannes\/intellij-community,xfournet\/intellij-community,ThiagoGarciaAlves\/intellij-community,semonte\/intellij-community,ibinti\/intellij-community,suncycheng\/intellij-community,apixandru\/intellij-community,suncycheng\/intellij-community,ibinti\/intellij-community,signed\/intellij-community,vvv1559\/intellij-community,allotria\/intellij-community,asedunov\/intellij-community,apixandru\/intellij-community,signed\/intellij-community,allotria\/intellij-community,ThiagoGarciaAlves\/intellij-community,ThiagoGarciaAlves\/intellij-community,semonte\/intellij-community,apixandru\/intellij-community,suncycheng\/intellij-community,apixandru\/intellij-community,semonte\/intellij-community,asedunov\/intellij-community,suncycheng\/intellij-community,ThiagoGarciaAlves\/intellij-community,signed\/intellij-community,da1z\/intellij-community,allotria\/intellij-community,da1z\/intellij-community,suncycheng\/intellij-community,asedunov\/intellij-community,da1z\/intellij-community,asedunov\/intellij-community,FHannes\/intellij-community,FHannes\/intellij-community,xfournet\/intellij-community,FHannes\/intellij-community,mglukhikh\/intellij-community,xfournet\/intellij-community,vvv1559\/intellij-community,apixandru\/intellij-community,allotria\/intellij-community,signed\/intellij-community,vvv1559\/intellij-community,allotria\/intellij-community,suncycheng\/intellij-community,ibinti\/intellij-community,ThiagoGarciaAlves\/intellij-community,ibinti\/intellij-community,FHannes\/intellij-community,semonte\/intellij-community,apixandru\/intellij-community,mglukhikh\/intellij-community,da1z\/intellij-community,vvv1559\/intellij-community,apixandru\/intellij-community,mglukhikh\/intellij-community,FHannes\/intellij-community,vvv1559\/intellij-community,asedunov\/intellij-community,FHannes\/intellij-community,semonte\/intellij-community,da1z\/intellij-community,xfournet\/intellij-community,mglukhikh\/intellij-community"} {"commit":"58a3ce8fa771d2ba5ed48de08b29c306bb895776","old_file":"ncbi_genome_download\/__init__.py","new_file":"ncbi_genome_download\/__init__.py","old_contents":"\"\"\"Download genome files from the NCBI\"\"\"\nfrom .config import (\n SUPPORTED_TAXONOMIC_GROUPS,\n NgdConfig\n)\nfrom .core import (\n args_download,\n download,\n argument_parser,\n)\n\n__version__ = '0.2.10'\n__all__ = [\n 'download',\n 'args_download',\n 'SUPPORTED_TAXONOMIC_GROUPS',\n 'NgdConfig',\n 'argument_parser'\n]\n","new_contents":"\"\"\"Download genome files from the NCBI\"\"\"\nfrom .config import (\n SUPPORTED_TAXONOMIC_GROUPS,\n NgdConfig\n)\nfrom .core import (\n args_download,\n download,\n argument_parser,\n)\n\n__version__ = '0.2.11'\n__all__ = [\n 'download',\n 'args_download',\n 'SUPPORTED_TAXONOMIC_GROUPS',\n 'NgdConfig',\n 'argument_parser'\n]\n","subject":"Bump version number to 0.2.11","message":"Bump version number to 0.2.11\n\nSigned-off-by: Kai Blin \n","lang":"Python","license":"apache-2.0","repos":"kblin\/ncbi-genome-download,kblin\/ncbi-genome-download"} {"commit":"d486505f270125a4b5c7f460f4f39a9c1eab9a1f","old_file":"setup.py","new_file":"setup.py","old_contents":"from setuptools import setup\n\n\nsetup(\n name='tephi',\n version='0.2.0-alpha',\n url='https:\/\/github.com\/SciTools\/tephi',\n author='Bill Little',\n author_email='bill.james.little@gmail.com',\n packages=['tephi', 'tephi.tests'],\n package_dir={'': 'lib'},\n package_data={'tephi': ['etc\/test_data\/*.txt'] + ['etc\/test_results\/*.pkl']},\n classifiers=['License :: OSI Approved :: '\n 'GNU Lesser General Public License v3 (LGPLv3)'],\n description='Tephigram plotting in Python',\n long_description=open('README.rst').read(),\n test_suite='tephi.tests',\n)\n","new_contents":"from setuptools import setup\n\n\nsetup(\n name='tephi',\n version='0.2.0-alpha',\n url='https:\/\/github.com\/SciTools\/tephi',\n author='Bill Little',\n author_email='bill.james.little@gmail.com',\n packages=['tephi', 'tephi.tests'],\n package_dir={'': 'lib'},\n package_data={'tephi': ['etc\/test_data\/*.txt'] + ['etc\/test_results\/*.pkl']},\n classifiers=['License :: OSI Approved :: '\n 'GNU Lesser General Public License v3 (LGPLv3)',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',],\n description='Tephigram plotting in Python',\n long_description=open('README.rst').read(),\n test_suite='tephi.tests',\n)\n","subject":"Add Python 2 and 3 PyPI classifiers.","message":"Add Python 2 and 3 PyPI classifiers.\n","lang":"Python","license":"bsd-3-clause","repos":"SciTools\/tephi"} {"commit":"3053219149f7dac7ab073fc24488116b1b280b77","old_file":"money_rounding.py","new_file":"money_rounding.py","old_contents":"def get_price_without_vat(price_to_show, vat_percent):\n raise NotImplementedError()\n\n\ndef get_price_without_vat_from_other_valuta(conversion_rate, origin_price,\n origin_vat, other_vat):\n raise NotImplementedError()\n","new_contents":"def show_pretty_price(value):\n raise NotImplementedError()\n","subject":"Use function described in readme","message":"Use function described in readme","lang":"Python","license":"mit","repos":"coolshop-com\/coolshop-application-assignment"} {"commit":"ea7200bc9774f69562b37f177ad18ca606998dfa","old_file":"perfrunner\/utils\/debug.py","new_file":"perfrunner\/utils\/debug.py","old_contents":"import glob\nimport shutil\nfrom optparse import OptionParser\n\nfrom perfrunner.helpers.remote import RemoteHelper\nfrom perfrunner.settings import ClusterSpec\n\n\ndef get_options():\n usage = '%prog -c cluster'\n\n parser = OptionParser(usage)\n\n parser.add_option('-c', dest='cluster_spec_fname',\n help='path to the cluster specification file',\n metavar='cluster.spec')\n\n options, args = parser.parse_args()\n if not options.cluster_spec_fname:\n parser.error('Please specify a cluster specification')\n\n return options, args\n\n\ndef main():\n options, args = get_options()\n\n cluster_spec = ClusterSpec()\n cluster_spec.parse(options.cluster_spec_fname, args)\n\n remote = RemoteHelper(cluster_spec, test_config=None, verbose=False)\n\n remote.collect_info()\n for hostname in cluster_spec.yield_hostnames():\n for fname in glob.glob('{}\/*.zip'.format(hostname)):\n shutil.move(fname, '{}.zip'.format(hostname))\n\n\nif __name__ == '__main__':\n main()\n","new_contents":"import glob\nimport os.path\nimport shutil\nfrom optparse import OptionParser\n\nfrom perfrunner.helpers.remote import RemoteHelper\nfrom perfrunner.settings import ClusterSpec\n\n\ndef get_options():\n usage = '%prog -c cluster'\n\n parser = OptionParser(usage)\n\n parser.add_option('-c', dest='cluster_spec_fname',\n help='path to the cluster specification file',\n metavar='cluster.spec')\n\n options, args = parser.parse_args()\n if not options.cluster_spec_fname:\n parser.error('Please specify a cluster specification')\n\n return options, args\n\n\ndef main():\n options, args = get_options()\n\n cluster_spec = ClusterSpec()\n cluster_spec.parse(options.cluster_spec_fname, args)\n\n remote = RemoteHelper(cluster_spec, test_config=None, verbose=False)\n\n remote.collect_info()\n for hostname in cluster_spec.yield_hostnames():\n for fname in glob.glob('{}\/*.zip'.format(hostname)):\n shutil.move(fname, '{}.zip'.format(hostname))\n\n if cluster_spec.backup is not None:\n logs = os.path.join(cluster_spec.backup, 'logs')\n if os.path.exists(logs):\n shutil.make_archive('tools', 'zip', logs)\n\n\nif __name__ == '__main__':\n main()\n","subject":"Archive logs from the tools","message":"Archive logs from the tools\n\nChange-Id: I184473d20cc2763fbc97c993bfcab36b80d1c864\nReviewed-on: http:\/\/review.couchbase.org\/76571\nTested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>\nReviewed-by: Pavel Paulau \n","lang":"Python","license":"apache-2.0","repos":"couchbase\/perfrunner,couchbase\/perfrunner,pavel-paulau\/perfrunner,couchbase\/perfrunner,couchbase\/perfrunner,pavel-paulau\/perfrunner,couchbase\/perfrunner,couchbase\/perfrunner,pavel-paulau\/perfrunner,pavel-paulau\/perfrunner,pavel-paulau\/perfrunner"} {"commit":"41416afdd05df56180a8d795ed77e83e0851efdd","old_file":"setup.py","new_file":"setup.py","old_contents":"#!\/usr\/bin\/env python\n\nfrom setuptools import setup\n\nsetup(name='drcli',\n version='0.1',\n description='Command-line tools for docrep',\n author = 'schwa lab',\n url='http:\/\/schwa.org\/git\/drcli.git',\n packages=['drcli'],\n scripts=['dr'],\n install_requires=['argparse'],\n package_data = {\n 'drcli': ['plugins\/*\/*.py'],\n },\n license='Apache 2.0',\n )\n\n","new_contents":"#!\/usr\/bin\/env python\n\nfrom setuptools import setup\n\nsetup(name='drcli',\n version='0.2',\n description='Command-line tools for docrep',\n author = 'schwa lab',\n url='http:\/\/schwa.org\/git\/drcli.git',\n packages=['drcli'],\n scripts=['dr'],\n install_requires=['argparse', 'brownie'],\n package_data = {\n 'drcli': ['plugins\/*\/*.py'],\n },\n license='Apache 2.0',\n )\n\n","subject":"Set version to 0.2; add brownie dependency","message":"Set version to 0.2; add brownie dependency\n","lang":"Python","license":"mit","repos":"schwa-lab\/dr-apps-python"} {"commit":"22e82e3fb6949efe862216feafaedb2da9b19c62","old_file":"filehandler.py","new_file":"filehandler.py","old_contents":"import csv\nimport sys\nimport urllib\n\nfrom scheduleitem import ScheduleItem\nfrom team import Team\n\n\ndef read(uri):\n \"\"\"Open a File or a Web URL\"\"\"\n if uri.startswith('http:\/\/') or uri.startswith('https:\/\/'):\n return open_url(uri)\n else:\n return open_file(uri)\n\n\ndef open_url(url):\n \"\"\"Return the games file data as an array\"\"\"\n try:\n with urllib.request.urlopen(url) as response:\n return response.read()\n except urllib.HTTPError as e:\n msg = \"Could Not Open URL {}.\\nThe Code is: {} \"\n print(msg.format(url, e.code))\n sys.exit(1)\n except urllib.URLError as e:\n msg = \"Could Not Open URL {}.\\nThe Reason is: {} \"\n print(msg.format(url.url, e.reason))\n sys.exit(1)\n\n\ndef open_file(uri):\n \"\"\"Return the games file data as an array\"\"\"\n try:\n with open(uri, 'r') as f:\n return f.read()\n except IOError:\n msg = \"Could not open file: `{}`\"\n print(msg.format(uri))\n sys.exit(1)\n\n\ndef load_schedules(games_file):\n with open(games_file, 'r') as f:\n return [ScheduleItem.from_str(line) for line in f.readlines()]\n\n\ndef load_teams_data(data_file):\n with open(data_file, 'r') as csv_file:\n reader = csv.reader(csv_file)\n # Skip the header row\n next(reader)\n return [Team(row[0], row[2], row[3]) for row in reader]\n","new_contents":"import csv\nimport sys\nimport urllib.error\nimport urllib.request\n\n\nfrom scheduleitem import ScheduleItem\nfrom team import Team\n\n\ndef read(uri):\n \"\"\"Open a File or a Web URL\"\"\"\n if uri.startswith('http:\/\/') or uri.startswith('https:\/\/'):\n return open_url(uri)\n else:\n return open_local_file(uri)\n\n\ndef open_url(url):\n \"\"\"Return the game file data.\"\"\"\n with urllib.request.urlopen(url) as response:\n if response.status != 200:\n msg = 'Status {}. Could Not Open URL {}. Reason: {}'\n raise urllib.error.HTTPError(\n msg.format(response.status, url, response.msg)\n )\n encoding = sys.getdefaultencoding()\n return [line.decode(encoding) for line in response.readlines()]\n\n\ndef open_local_file(uri):\n \"\"\"Return the games file data as an array\"\"\"\n with open(uri, 'r') as f:\n return f.readlines()\n\n\ndef load_schedules(uri):\n data = read(uri)\n return [ScheduleItem.from_str(line) for line in data]\n\n\ndef load_teams_data(data_file):\n with open(data_file, 'r') as csv_file:\n reader = csv.reader(csv_file)\n next(reader) # Skip the header row\n return [Team(row[0], row[2], row[3]) for row in reader]\n","subject":"Update file handlers to use Python3 urllib","message":"Update file handlers to use Python3 urllib\n","lang":"Python","license":"mit","repos":"brianjbuck\/robie"} {"commit":"650682c3643912c53e643d7b1074f1a6c4a1556b","old_file":"setup.py","new_file":"setup.py","old_contents":"from setuptools import setup, find_packages\n# To use a consistent encoding\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(\n name='django-cra-helper',\n version='1.0.2',\n description='The missing piece of the Django + React puzzle',\n long_description=long_description,\n long_description_content_type=\"text\/markdown\",\n url='https:\/\/github.com\/MasterKale\/django-cra-helper',\n author='Matthew Miller',\n author_email='matthew@millerti.me',\n license='MIT',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n ],\n keywords='django react create-react-app integrate',\n packages=find_packages(exclude=['contrib', 'docs', 'tests']),\n install_requires=[\n 'bleach>=2'\n ],\n)\n","new_contents":"from setuptools import setup, find_packages\n# To use a consistent encoding\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(\n name='django-cra-helper',\n version='1.1.0',\n description='The missing piece of the Django + React puzzle',\n long_description=long_description,\n long_description_content_type=\"text\/markdown\",\n url='https:\/\/github.com\/MasterKale\/django-cra-helper',\n author='Matthew Miller',\n author_email='matthew@millerti.me',\n license='MIT',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n ],\n keywords='django react create-react-app integrate',\n packages=find_packages(exclude=['contrib', 'docs', 'tests']),\n install_requires=[\n 'bleach>=2'\n ],\n)\n","subject":"Update package version to v1.1.0","message":"Update package version to v1.1.0\n","lang":"Python","license":"mit","repos":"MasterKale\/django-cra-helper"} {"commit":"c1dcdb3c8856fbfd449524f66f5fc819eb1a19bc","old_file":"setup.py","new_file":"setup.py","old_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\n\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n\nwith open('README.rst') as readme_file:\n readme = readme_file.read()\n\nwith open('HISTORY.rst') as history_file:\n history = history_file.read().replace('.. :changelog:', '')\n\nrequirements = [\n 'SQLAlchemy',\n 'python-dateutil',\n 'python-magic',\n 'elasticsearch',\n]\n\ntest_requirements = [\n 'coverage',\n]\n\nsetup(\n name='esis',\n version='0.1.0',\n description=\"Elastic Search Index & Search\",\n long_description=readme + '\\n\\n' + history,\n author=\"Javier Collado\",\n author_email='jcollado@nowsecure.com',\n url='https:\/\/github.com\/jcollado\/esis',\n packages=[\n 'esis',\n ],\n package_dir={'esis':\n 'esis'},\n include_package_data=True,\n install_requires=requirements,\n license=\"MIT\",\n zip_safe=False,\n keywords='elastic search index sqlite',\n entry_points={\n 'console_scripts': [\n 'esis = esis.cli:main',\n ]\n },\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 2.7',\n ],\n test_suite='tests',\n tests_require=test_requirements\n)\n","new_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\n\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n\nwith open('README.rst') as readme_file:\n readme = readme_file.read()\n\nwith open('HISTORY.rst') as history_file:\n history = history_file.read().replace('.. :changelog:', '')\n\nrequirements = [\n 'SQLAlchemy',\n 'python-dateutil',\n 'python-magic',\n 'elasticsearch',\n]\n\ntest_requirements = [\n 'coverage',\n]\n\nsetup(\n name='esis',\n version='0.1.0',\n description=\"Elastic Search Index & Search\",\n long_description=readme + '\\n\\n' + history,\n author=\"Javier Collado\",\n author_email='jcollado@nowsecure.com',\n url='https:\/\/github.com\/jcollado\/esis',\n packages=[\n 'esis',\n ],\n package_dir={'esis':\n 'esis'},\n include_package_data=True,\n install_requires=requirements,\n license=\"MIT\",\n zip_safe=False,\n keywords='elastic search index sqlite',\n entry_points={\n 'console_scripts': [\n 'esis = esis.cli:main',\n ]\n },\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 2.7',\n ],\n test_suite='tests',\n tests_require=test_requirements\n)\n","subject":"Move development status to alpha","message":"Move development status to alpha\n","lang":"Python","license":"mit","repos":"jcollado\/esis"} {"commit":"7b4b2fcbcb9a95c07f09b71305afa0c5ce95fe99","old_file":"tenant_schemas\/routers.py","new_file":"tenant_schemas\/routers.py","old_contents":"from django.conf import settings\n\n\nclass TenantSyncRouter(object):\n \"\"\"\n A router to control which applications will be synced,\n depending if we are syncing the shared apps or the tenant apps.\n \"\"\"\n\n def allow_syncdb(self, db, model):\n # the imports below need to be done here else django <1.5 goes crazy\n # https:\/\/code.djangoproject.com\/ticket\/20704\n from django.db import connection\n from tenant_schemas.utils import get_public_schema_name, app_labels\n\n if connection.schema_name == get_public_schema_name():\n if model._meta.app_label not in app_labels(settings.SHARED_APPS):\n return False\n else:\n if model._meta.app_label not in app_labels(settings.TENANT_APPS):\n return False\n\n return None\n","new_contents":"from django.conf import settings\n\n\nclass TenantSyncRouter(object):\n \"\"\"\n A router to control which applications will be synced,\n depending if we are syncing the shared apps or the tenant apps.\n \"\"\"\n\n def allow_migrate(self, db, model):\n # the imports below need to be done here else django <1.5 goes crazy\n # https:\/\/code.djangoproject.com\/ticket\/20704\n from django.db import connection\n from tenant_schemas.utils import get_public_schema_name, app_labels\n\n if connection.schema_name == get_public_schema_name():\n if model._meta.app_label not in app_labels(settings.SHARED_APPS):\n return False\n else:\n if model._meta.app_label not in app_labels(settings.TENANT_APPS):\n return False\n\n return None\n\n def allow_syncdb(self, db, model):\n # allow_syncdb was changed to allow_migrate in django 1.7\n return self.allow_migrate(db, model)\n","subject":"Add database router allow_migrate() for Django 1.7","message":"Add database router allow_migrate() for Django 1.7\n","lang":"Python","license":"mit","repos":"goodtune\/django-tenant-schemas,Mobytes\/django-tenant-schemas,kajarenc\/django-tenant-schemas,honur\/django-tenant-schemas,mcanaves\/django-tenant-schemas,ArtProcessors\/django-tenant-schemas,goodtune\/django-tenant-schemas,ArtProcessors\/django-tenant-schemas,bernardopires\/django-tenant-schemas,bernardopires\/django-tenant-schemas,pombredanne\/django-tenant-schemas"} {"commit":"1c11d8e2169a90efcd16340c46114cf978e2343f","old_file":"setup.py","new_file":"setup.py","old_contents":"#!\/usr\/bin\/env python\n\nimport sys\ntry:\n from setuptools import setup, Extension\nexcept ImportError:\n from distutils.core import setup, Extension\n\nuinput = Extension('libuinput',\n sources = ['src\/uinput.c'])\n\ndeps = ['libusb1', 'psutil']\nif sys.version_info < (3,4):\n deps.append('enum34')\n\nsetup(name='python-steamcontroller',\n version='1.1',\n description='Steam Controller userland driver',\n author='Stany MARCEL',\n author_email='stanypub@gmail.com',\n url='https:\/\/github.com\/ynsta\/steamcontroller',\n package_dir={'steamcontroller': 'src'},\n packages=['steamcontroller'],\n scripts=['scripts\/sc-dump.py',\n 'scripts\/sc-xbox.py',\n 'scripts\/sc-desktop.py',\n 'scripts\/sc-test-cmsg.py',\n 'scripts\/sc-gyro-plot.py',\n 'scripts\/vdf2json.py',\n 'scripts\/json2vdf.py'],\n license='MIT',\n platforms=['Linux'],\n install_requires=deps,\n ext_modules=[uinput, ])\n","new_contents":"#!\/usr\/bin\/env python\n\nimport sys\ntry:\n from setuptools import setup, Extension\nexcept ImportError:\n from distutils.core import setup, Extension\n\nuinput = Extension('libuinput',\n sources = ['src\/uinput.c'])\n\ndeps = ['libusb1', 'psutil']\nif sys.version_info < (3,4):\n deps.append('enum34')\n\nsetup(name='python-steamcontroller',\n version='1.1',\n description='Steam Controller userland driver',\n author='Stany MARCEL',\n author_email='stanypub@gmail.com',\n url='https:\/\/github.com\/ynsta\/steamcontroller',\n package_dir={'steamcontroller': 'src'},\n packages=['steamcontroller'],\n scripts=['scripts\/sc-dump.py',\n 'scripts\/sc-xbox.py',\n 'scripts\/sc-desktop.py',\n 'scripts\/sc-mixed.py',\n 'scripts\/sc-test-cmsg.py',\n 'scripts\/sc-gyro-plot.py',\n 'scripts\/vdf2json.py',\n 'scripts\/json2vdf.py'],\n license='MIT',\n platforms=['Linux'],\n install_requires=deps,\n ext_modules=[uinput, ])\n","subject":"Add sc-mixed.py in installed scripts","message":"Add sc-mixed.py in installed scripts\n\nSigned-off-by: Stany MARCEL <3e139d47b96f775f4bc13af807cbc2ea7c67e72b@gmail.com>\n","lang":"Python","license":"mit","repos":"ynsta\/steamcontroller,ynsta\/steamcontroller"} {"commit":"b3acf639f310019d042bbe24e653a6f79c240858","old_file":"setup.py","new_file":"setup.py","old_contents":"from distutils.core import Extension, setup\n\nfrom Cython.Build import cythonize\n\ntry:\n from Cython.Distutils import build_ext\nexcept ImportError:\n use_cython = False\nelse:\n use_cython = True\n\n\nif use_cython:\n extensions = [\n Extension('mathix.vector', ['mathix\/vector.pyx']),\n ]\n\n cmdclass = {\n 'build_ext': build_ext\n }\nelse:\n extensions = [\n Extension('mathix.vector', ['mathix\/vector.c']),\n ]\n\n cmdclass = {}\n\n\nsetup(\n name='mathix',\n\n author='Peith Vergil',\n\n version='0.1',\n\n cmdclass=cmdclass,\n\n packages=[\n 'mathix',\n ],\n\n keywords='useless simple math library',\n\n description='A useless simple math library.',\n\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Programming Language :: Cython',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n ],\n\n ext_modules=cythonize(extensions)\n)\n","new_contents":"from distutils.core import Extension, setup\n\ntry:\n from Cython.Distutils import build_ext\nexcept ImportError:\n use_cython = False\nelse:\n use_cython = True\n\n\nif use_cython:\n extensions = [\n Extension('mathix.vector', ['mathix\/vector.pyx']),\n ]\n\n cmdclass = {\n 'build_ext': build_ext\n }\nelse:\n extensions = [\n Extension('mathix.vector', ['mathix\/vector.c']),\n ]\n\n cmdclass = {}\n\n\nsetup(\n name='mathix',\n\n author='Peith Vergil',\n\n version='0.1',\n\n cmdclass=cmdclass,\n\n packages=[\n 'mathix',\n ],\n\n keywords='useless simple math library',\n\n description='A useless simple math library.',\n\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Programming Language :: Cython',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n ],\n\n ext_modules=extensions\n)\n","subject":"Remove the importing of the \"cythonize\" function.","message":"Remove the importing of the \"cythonize\" function.\n","lang":"Python","license":"mit","repos":"PeithVergil\/cython-example"} {"commit":"f8cbb96f2d5040d060799f62b642e8bb80060d07","old_file":"setup.py","new_file":"setup.py","old_contents":"#!\/usr\/bin\/env python\n#coding: utf-8\nfrom distribute_setup import use_setuptools\nuse_setuptools()\n\nfrom aero.__version__ import __version__, __title__, __authors__, __email__, __license__, __url__, __download_url__\nfrom setuptools import setup\n\nsetup(\n\tname = __title__,\n\tauthor = __authors__,\n\tauthor_email = __email__,\n\tversion = __version__,\n\tlicense = __license__,\n\turl = __url__,\n\tdownload_url = __download_url__,\n\tpackages = ['aero', 'aero.adapters'],\n package_data ={'aero': ['assets\/*.ascii']},\n description = [descr for descr in open('README.txt').read().splitlines() if descr.strip() and '===' not in descr][1],\n long_description=open('README.txt').read(),\n\tscripts = [\"aero\/aero\"],\n\n)\n","new_contents":"#!\/usr\/bin\/env python\n#coding: utf-8\nfrom distribute_setup import use_setuptools\nuse_setuptools()\n\nfrom aero.__version__ import __version__, __title__, __authors__, __email__, __license__, __url__, __download_url__\nfrom setuptools import setup\n\nsetup(\n\tname = __title__,\n\tauthor = __authors__,\n\tauthor_email = __email__,\n\tversion = __version__,\n\tlicense = __license__,\n\turl = __url__,\n\tdownload_url = __download_url__,\n\tpackages = ['aero', 'aero.adapters'],\n package_data ={'aero': ['assets\/*.ascii']},\n description = [descr for descr in open('README.txt').read().splitlines() if descr.strip() and '===' not in descr][1],\n long_description=open('README.txt').read(),\n\tinstall_requires = [\"argparse\",\"Beaker\",\"PyYAML\"],\n\tscripts = [\"aero\/aero\"],\n\n)\n","subject":"Add project dependencies to install","message":"Add project dependencies to install\n","lang":"Python","license":"bsd-3-clause","repos":"Aeronautics\/aero"} {"commit":"507ac62597b30ccfa58841ccf26207b67baa8eac","old_file":"setup.py","new_file":"setup.py","old_contents":"from setuptools import setup, find_packages\n\nsetup(\n name='django-lightweight-queue',\n\n url=\"https:\/\/chris-lamb.co.uk\/projects\/django-lightweight-queue\",\n version='2.0.1',\n description=\"Lightweight & modular queue and cron system for Django\",\n\n author=\"Chris Lamb\",\n author_email='chris@chris-lamb.co.uk',\n license=\"BSD\",\n\n packages=find_packages(),\n)\n","new_contents":"from setuptools import setup, find_packages\n\nsetup(\n name='django-lightweight-queue',\n\n url=\"https:\/\/chris-lamb.co.uk\/projects\/django-lightweight-queue\",\n version='2.0.1',\n description=\"Lightweight & modular queue and cron system for Django\",\n\n author=\"Chris Lamb\",\n author_email='chris@chris-lamb.co.uk',\n license=\"BSD\",\n\n packages=find_packages(),\n\n install_requires=(\n 'Django>=1.8',\n ),\n)\n","subject":"Update Django requirement to latest LTS","message":"Update Django requirement to latest LTS\n","lang":"Python","license":"bsd-3-clause","repos":"lamby\/django-lightweight-queue"} {"commit":"6621d8b34c4d35d5d39cd64177e17c22518528c0","old_file":"setup.py","new_file":"setup.py","old_contents":"# -*- coding: utf-8 -*-\n\n'''\nFlask-LDAPConn\n--------------\n\nFlask extension providing ldap3 connection object and ORM\nto accessing LDAP servers.\n'''\n\n\nfrom setuptools import setup\n\n\nsetup(\n name='Flask-LDAPConn',\n version='0.6.5',\n url='http:\/\/github.com\/rroemhild\/flask-ldapconn',\n license='BSD',\n author='Rafael Römhild',\n author_email='rafael@roemhild.de',\n keywords='flask ldap ldap3 orm',\n description='Pure python, LDAP connection and ORM for Flask Applications',\n long_description=open('README.rst').read(),\n packages=[\n 'flask_ldapconn'\n ],\n zip_safe=False,\n platforms='any',\n install_requires=[\n 'Flask==0.10.1',\n 'ldap3==0.9.9.1',\n 'six==1.10.0'\n ],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Framework :: Flask',\n 'Topic :: Internet :: WWW\/HTTP :: Dynamic Content',\n 'Topic :: Software Development :: Libraries :: Python Modules'\n ]\n)\n","new_contents":"# -*- coding: utf-8 -*-\n\n'''\nFlask-LDAPConn\n--------------\n\nFlask extension providing ldap3 connection object and ORM\nto accessing LDAP servers.\n'''\n\n\nfrom setuptools import setup\n\n\nsetup(\n name='Flask-LDAPConn',\n version='0.6.6',\n url='http:\/\/github.com\/rroemhild\/flask-ldapconn',\n license='BSD',\n author='Rafael Römhild',\n author_email='rafael@roemhild.de',\n keywords='flask ldap ldap3 orm',\n description='Pure python, LDAP connection and ORM for Flask Applications',\n long_description=open('README.rst').read(),\n packages=[\n 'flask_ldapconn'\n ],\n zip_safe=False,\n platforms='any',\n install_requires=[\n 'Flask==0.10.1',\n 'ldap3==0.9.9.1',\n 'six==1.10.0'\n ],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Framework :: Flask',\n 'Topic :: Internet :: WWW\/HTTP :: Dynamic Content',\n 'Topic :: Software Development :: Libraries :: Python Modules'\n ]\n)\n","subject":"Bump version 0.6.5 -> 0.6.6","message":"Bump version 0.6.5 -> 0.6.6\n","lang":"Python","license":"bsd-2-clause","repos":"rroemhild\/flask-ldapconn"} {"commit":"f8fcdb461f414f3c29263edd7e5c9906d76435a1","old_file":"setup.py","new_file":"setup.py","old_contents":"from setuptools import setup\n\nsetup(\n name='pytest-flakes',\n description='pytest plugin to check source code with pyflakes',\n long_description=open(\"README.rst\").read(),\n license=\"MIT license\",\n version='1.0.1',\n author='Florian Schulze, Holger Krekel and Ronny Pfannschmidt',\n author_email='florian.schulze@gmx.net',\n url='https:\/\/github.com\/fschulze\/pytest-flakes',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Framework :: Pytest',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Software Development :: Testing',\n ],\n py_modules=['pytest_flakes'],\n entry_points={'pytest11': ['flakes = pytest_flakes']},\n install_requires=['pytest-cache', 'pytest>=2.3.dev14', 'pyflakes'])\n","new_contents":"from setuptools import setup\n\nsetup(\n name='pytest-flakes',\n description='pytest plugin to check source code with pyflakes',\n long_description=open(\"README.rst\").read(),\n license=\"MIT license\",\n version='1.0.1',\n author='Florian Schulze, Holger Krekel and Ronny Pfannschmidt',\n author_email='florian.schulze@gmx.net',\n url='https:\/\/github.com\/fschulze\/pytest-flakes',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Framework :: Pytest',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Software Development :: Testing',\n ],\n py_modules=['pytest_flakes'],\n entry_points={'pytest11': ['flakes = pytest_flakes']},\n install_requires=['pytest-cache', 'pytest>=2.3.dev14', 'pyflakes'])\n","subject":"Use correct MIT license classifier.","message":"Use correct MIT license classifier.\n\n`LICENSE` contains the MIT\/Expat license but `setup.py` uses the LGPLv3\nclassifier. I assume the later is an oversight.\n","lang":"Python","license":"mit","repos":"fschulze\/pytest-flakes"} {"commit":"787ee9390fbf2ace59d2f8544b735feb6c895dda","old_file":"setup.py","new_file":"setup.py","old_contents":"import os\n\nfrom setuptools import setup\n\nPACKAGE_VERSION = '0.3'\n\n\ndef version():\n if os.getenv('TRAVIS'):\n return os.getenv('TRAVIS_BUILD_NUMBER')\n else:\n import odintools\n\n return odintools.version(PACKAGE_VERSION, os.environ.get('BUILD_NUMBER'))\n\n\nsetup(\n name='osaapi',\n version_getter=version,\n author='apsliteteam, oznu',\n author_email='aps@odin.com',\n packages=['osaapi'],\n url='https:\/\/aps.odin.com',\n license='Apache License',\n description='A python client for the Odin Service Automation (OSA) and billing APIs.',\n long_description=open('README.md').read(),\n setup_requires=['odintools'],\n odintools=True,\n)\n","new_contents":"import os\n\nfrom setuptools import setup\n\nPACKAGE_VERSION = '0.3'\n\n\ndef version():\n import odintools\n b = os.getenv('TRAVIS_BUILD_NUMBER') if os.getenv('TRAVIS') else os.environ.get('BUILD_NUMBER')\n return odintools.version(PACKAGE_VERSION, b)\n\n\nsetup(\n name='osaapi',\n version_getter=version,\n author='apsliteteam, oznu',\n author_email='aps@odin.com',\n packages=['osaapi'],\n url='https:\/\/aps.odin.com',\n license='Apache License',\n description='A python client for the Odin Service Automation (OSA) and billing APIs.',\n long_description=open('README.md').read(),\n setup_requires=['odintools'],\n odintools=True,\n)\n","subject":"Fix issue with version setter","message":"Fix issue with version setter\n","lang":"Python","license":"apache-2.0","repos":"odin-public\/osaAPI"} {"commit":"df97966941f2ffe924f98b329b136edf069eb6ca","old_file":"setup.py","new_file":"setup.py","old_contents":"#!\/usr\/bin\/env python\n\"\"\"Django\/PostgreSQL implementation of the Meteor DDP service.\"\"\"\nimport os.path\nfrom setuptools import setup, find_packages\n\nsetup(\n name='django-ddp',\n version='0.2.0',\n description=__doc__,\n long_description=open('README.rst').read(),\n author='Tyson Clugg',\n author_email='tyson@clugg.net',\n url='https:\/\/github.com\/commoncode\/django-ddp',\n packages=find_packages(),\n include_package_data=True,\n install_requires=[\n 'Django>=1.7',\n 'psycopg2>=2.5.4',\n 'gevent>=1.0',\n 'gevent-websocket>=0.9',\n 'meteor-ejson>=1.0',\n 'psycogreen>=1.0',\n 'django-dbarray>=0.2',\n ],\n classifiers=[\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"Topic :: Internet :: WWW\/HTTP\",\n ],\n)\n","new_contents":"#!\/usr\/bin\/env python\n\"\"\"Django\/PostgreSQL implementation of the Meteor DDP service.\"\"\"\nimport os.path\nfrom setuptools import setup, find_packages\n\nsetup(\n name='django-ddp',\n version='0.2.1',\n description=__doc__,\n long_description=open('README.rst').read(),\n author='Tyson Clugg',\n author_email='tyson@clugg.net',\n url='https:\/\/github.com\/commoncode\/django-ddp',\n packages=find_packages(),\n include_package_data=True,\n install_requires=[\n 'Django>=1.7',\n 'psycopg2>=2.5.4',\n 'gevent>=1.0',\n 'gevent-websocket>=0.9',\n 'meteor-ejson>=1.0',\n 'psycogreen>=1.0',\n 'django-dbarray>=0.2',\n ],\n classifiers=[\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"Topic :: Internet :: WWW\/HTTP\",\n ],\n)\n","subject":"Bump version number in preparation for next release.","message":"Bump version number in preparation for next release.\n","lang":"Python","license":"mit","repos":"django-ddp\/django-ddp,commoncode\/django-ddp,django-ddp\/django-ddp,PythonicNinja\/django-ddp,commoncode\/django-ddp,commoncode\/django-ddp,django-ddp\/django-ddp,commoncode\/django-ddp,django-ddp\/django-ddp,PythonicNinja\/django-ddp,PythonicNinja\/django-ddp"} {"commit":"d63d391d5b9ee221c0cd67e030895f4598430f08","old_file":"onetime\/models.py","new_file":"onetime\/models.py","old_contents":"from datetime import datetime\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nclass Key(models.Model):\n user = models.ForeignKey(User)\n key = models.CharField(max_length=40)\n created = models.DateTimeField(auto_now_add=True)\n usage_left = models.IntegerField(null=True, default=1)\n expires = models.DateTimeField(null=True)\n next = models.CharField(null=True, max_length=200)\n\n def __unicode__(self):\n return '%s (%s)' % (self.key, self.user.username)\n\n def is_valid(self):\n if self.usage_left is not None and self.usage_left <= 0:\n return False\n if self.expires is not None and self.expires < datetime.now():\n return False\n return True\n\n def update_usage(self):\n if self.usage_left is not None:\n self.usage_left -= 1\n self.save()\n\n","new_contents":"from datetime import datetime\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nclass Key(models.Model):\n user = models.ForeignKey(User)\n key = models.CharField(max_length=40)\n created = models.DateTimeField(auto_now_add=True)\n usage_left = models.IntegerField(null=True, default=1)\n expires = models.DateTimeField(null=True)\n next = models.CharField(null=True, max_length=200)\n\n def __unicode__(self):\n return '%s (%s)' % (self.key, self.user.username)\n\n def is_valid(self):\n if self.usage_left is not None and self.usage_left <= 0:\n return False\n if self.expires is not None and self.expires < datetime.now():\n return False\n return True\n\n def update_usage(self):\n if self.usage_left is not None and self.usage_left > 0:\n self.usage_left -= 1\n self.save()\n\n","subject":"Update key usage when the usage_left counter is still greater than zero.","message":"Update key usage when the usage_left counter is still greater than zero.\n","lang":"Python","license":"bsd-3-clause","repos":"uploadcare\/django-loginurl,vanschelven\/cmsplugin-journal,ISIFoundation\/influenzanet-website,ISIFoundation\/influenzanet-website,fajran\/django-loginurl,ISIFoundation\/influenzanet-website,ISIFoundation\/influenzanet-website,ISIFoundation\/influenzanet-website,ISIFoundation\/influenzanet-website,ISIFoundation\/influenzanet-website"} {"commit":"c8a0f4f439c2123c9b7f9b081f91d75b1f9a8a13","old_file":"dmoj\/checkers\/linecount.py","new_file":"dmoj\/checkers\/linecount.py","old_contents":"from re import split as resplit\nfrom typing import Callable, Union\n\nfrom dmoj.result import CheckerResult\nfrom dmoj.utils.unicode import utf8bytes\n\nverdict = u\"\\u2717\\u2713\"\n\n\ndef check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True,\n match: Callable[[bytes, bytes], bool] = lambda p, j: p.strip() == j.strip(),\n **kwargs) -> Union[CheckerResult, bool]:\n process_lines = list(filter(None, resplit(b'[\\r\\n]', utf8bytes(process_output))))\n judge_lines = list(filter(None, resplit(b'[\\r\\n]', utf8bytes(judge_output))))\n\n if len(process_lines) > len(judge_lines):\n return False\n\n if not judge_lines:\n return True\n\n if isinstance(match, str):\n match = eval(match)\n\n cases = [verdict[0]] * len(judge_lines)\n count = 0\n\n for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)):\n if match(process_line, judge_line):\n cases[i] = verdict[1]\n count += 1\n\n return CheckerResult(count == len(judge_lines), point_value * (1.0 * count \/ len(judge_lines)),\n ''.join(cases) if feedback else \"\")\n\n\ncheck.run_on_error = True # type: ignore\n","new_contents":"from re import split as resplit\nfrom typing import Callable, Union\n\nfrom dmoj.result import CheckerResult\nfrom dmoj.utils.unicode import utf8bytes\n\nverdict = u\"\\u2717\\u2713\"\n\n\ndef check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True,\n **kwargs) -> Union[CheckerResult, bool]:\n process_lines = list(filter(None, resplit(b'[\\r\\n]', utf8bytes(process_output))))\n judge_lines = list(filter(None, resplit(b'[\\r\\n]', utf8bytes(judge_output))))\n\n if len(process_lines) > len(judge_lines):\n return False\n\n if not judge_lines:\n return True\n\n cases = [verdict[0]] * len(judge_lines)\n count = 0\n\n for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)):\n if process_line.strip() == judge_line.strip():\n cases[i] = verdict[1]\n count += 1\n\n return CheckerResult(count == len(judge_lines), point_value * (1.0 * count \/ len(judge_lines)),\n ''.join(cases) if feedback else \"\")\n\n\ncheck.run_on_error = True # type: ignore\n","subject":"Remove the match param to fix RCE.","message":"Remove the match param to fix RCE.","lang":"Python","license":"agpl-3.0","repos":"DMOJ\/judge,DMOJ\/judge,DMOJ\/judge"} {"commit":"18b62174d8fd48691a78f23b0a9f806eb7eb01f7","old_file":"indra\/tests\/test_tas.py","new_file":"indra\/tests\/test_tas.py","old_contents":"from nose.plugins.attrib import attr\nfrom indra.sources.tas import process_from_web\n\n\n@attr('slow')\ndef test_processor():\n tp = process_from_web(affinity_class_limit=10)\n assert tp\n assert tp.statements\n num_stmts = len(tp.statements)\n # This is the total number of statements about human genes\n assert num_stmts == 1130277, num_stmts\n assert all(len(s.evidence) >= 1 for s in tp.statements), \\\n 'Some statements lack any evidence'\n","new_contents":"from nose.plugins.attrib import attr\nfrom indra.sources.tas import process_from_web\n\n\n@attr('slow')\ndef test_processor():\n tp = process_from_web(affinity_class_limit=10)\n assert tp\n assert tp.statements\n num_stmts = len(tp.statements)\n # This is the total number of statements about human genes\n assert num_stmts == 1128585, num_stmts\n assert all(len(s.evidence) >= 1 for s in tp.statements), \\\n 'Some statements lack any evidence'\n","subject":"Update test again after better aggregation","message":"Update test again after better aggregation\n","lang":"Python","license":"bsd-2-clause","repos":"johnbachman\/indra,bgyori\/indra,johnbachman\/belpy,sorgerlab\/indra,sorgerlab\/indra,johnbachman\/belpy,sorgerlab\/belpy,bgyori\/indra,sorgerlab\/belpy,johnbachman\/indra,bgyori\/indra,johnbachman\/indra,sorgerlab\/indra,sorgerlab\/belpy,johnbachman\/belpy"} {"commit":"973641c7d68f4b1505541a06ec46901b412ab56b","old_file":"tests\/test_constraints.py","new_file":"tests\/test_constraints.py","old_contents":"import unittest\n\nimport numpy as np\n\nfrom constraints import (generate_constraints_function,\n generate_constraint_gradients_function, )\nfrom robot_arm import RobotArm\n\n\nclass TestConstraintFunctions(unittest.TestCase):\n def setUp(self):\n self.lengths = (3, 2, 2,)\n self.destinations = (\n (5, 4, 6, 4, 5),\n (0, 2, 0.5, -2, -1),\n )\n self.theta = (np.pi, np.pi \/ 2, 0,)\n self.thetas = np.ones((3 * 5,))\n self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)\n self.constraints_func = generate_constraints_function(self.robot_arm)\n self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)\n\n def test_constraints_func_return_type(self):\n constraints = self.constraints_func(self.thetas)\n self.assertEqual(constraints.shape, (2 * 5,))\n\n def test_constraint_gradients_func_return_type(self):\n constraint_gradients = self.constraint_gradients_func(self.thetas)\n self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))\n # print(np.array2string(constraint_gradients, max_line_width=np.inf))\n","new_contents":"import unittest\n\nimport numpy as np\n\nfrom constraints import (generate_constraints_function,\n generate_constraint_gradients_function, )\nfrom robot_arm import RobotArm\n\n\nclass TestConstraintFunctions(unittest.TestCase):\n def setUp(self):\n self.lengths = (3, 2, 2,)\n self.destinations = (\n (5, 4, 6, 4, 5),\n (0, 2, 0.5, -2, -1),\n )\n self.theta = (np.pi, np.pi \/ 2, 0,)\n self.thetas = np.ones((3 * 5,))\n self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta)\n self.constraints_func = generate_constraints_function(self.robot_arm)\n self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm)\n\n def test_constraints_func_return_type(self):\n constraints = self.constraints_func(self.thetas)\n self.assertEqual(constraints.shape, (2 * 5,))\n\n def test_constraint_gradients_func_return_type(self):\n constraint_gradients = self.constraint_gradients_func(self.thetas)\n self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5))\n # print(np.array2string(constraint_gradients, max_line_width=np.inf))\n\n def test_licq(self):\n constraint_gradients = self.constraint_gradients_func(self.thetas)\n rank = np.linalg.matrix_rank(constraint_gradients)\n self.assertEqual(rank, 2 * 5)\n","subject":"Test LICQ condition of constraint gradient","message":"Test LICQ condition of constraint gradient\n","lang":"Python","license":"mit","repos":"JakobGM\/robotarm-optimization"} {"commit":"c8c9c42f14c742c6fcb180b7a3cc1bab1655ac46","old_file":"projections\/simpleexpr.py","new_file":"projections\/simpleexpr.py","old_contents":"\nimport numpy as np\nimport numpy.ma as ma\n\nimport projections.r2py.reval as reval\nimport projections.r2py.rparser as rparser\n\nclass SimpleExpr():\n def __init__(self, name, expr):\n self.name = name\n self.tree = reval.make_inputs(rparser.parse(expr))\n lokals = {}\n exec(reval.to_py(self.tree, name), lokals)\n self.func = lokals[name + '_st']\n\n @property\n def syms(self):\n return reval.find_inputs(self.tree)\n \n def eval(self, df):\n try:\n res = self.func(df)\n except KeyError as e:\n print(\"Error: input '%s' not defined\" % e)\n raise e\n if not isinstance(res, np.ndarray):\n res = ma.masked_array(np.full(tuple(df.values())[0].shape, res,\n dtype=np.float32))\n return res\n","new_contents":"\nimport numpy as np\nimport numpy.ma as ma\n\nimport projections.r2py.reval as reval\nimport projections.r2py.rparser as rparser\n\nclass SimpleExpr():\n def __init__(self, name, expr):\n self.name = name\n self.tree = reval.make_inputs(rparser.parse(expr))\n lokals = {}\n exec(reval.to_py(self.tree, name), lokals)\n self.func = lokals[name + '_st']\n\n @property\n def syms(self):\n return reval.find_inputs(self.tree)\n \n def eval(self, df):\n try:\n res = self.func(df)\n except KeyError as e:\n print(\"Error: input '%s' not defined\" % e)\n raise e\n if not isinstance(res, np.ndarray):\n arrays = filter(lambda v: isinstance(v, np.ndarray), df.values())\n res = ma.masked_array(np.full(tuple(arrays)[0].shape, res,\n dtype=np.float32))\n return res\n","subject":"Improve determination of array shape for constant expressions","message":"Improve determination of array shape for constant expressions\n\nWhen Evaluating a constant expression, I only used to look at the first\ncolumn in the df dictionary. But that could also be a constant or\nexpression. So look instead at all columns and find the first numpy\narray.\n","lang":"Python","license":"apache-2.0","repos":"ricardog\/raster-project,ricardog\/raster-project,ricardog\/raster-project,ricardog\/raster-project,ricardog\/raster-project"} {"commit":"632180274abe4cf91f65cf0e84f817dc7124e293","old_file":"zerver\/migrations\/0108_fix_default_string_id.py","new_file":"zerver\/migrations\/0108_fix_default_string_id.py","old_contents":"# -*- coding: utf-8 -*-\n# Generated by Django 1.11.4 on 2017-08-24 02:39\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations\n\ndef fix_realm_string_ids(apps, schema_editor):\n # type: (StateApps, DatabaseSchemaEditor) -> None\n Realm = apps.get_model('zerver', 'Realm')\n if Realm.objects.count() != 2:\n return\n\n zulip_realm = Realm.objects.get(string_id=\"zulip\")\n try:\n user_realm = Realm.objects.exclude(id=zulip_realm.id)[0]\n except Realm.DoesNotExist:\n return\n\n user_realm.string_id = \"\"\n user_realm.save()\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('zerver', '0107_multiuseinvite'),\n ]\n\n operations = [\n migrations.RunPython(fix_realm_string_ids,\n reverse_code=migrations.RunPython.noop),\n ]\n","new_contents":"# -*- coding: utf-8 -*-\n# Generated by Django 1.11.4 on 2017-08-24 02:39\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations\nfrom django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor\nfrom django.db.migrations.state import StateApps\n\ndef fix_realm_string_ids(apps, schema_editor):\n # type: (StateApps, DatabaseSchemaEditor) -> None\n Realm = apps.get_model('zerver', 'Realm')\n if Realm.objects.count() != 2:\n return\n\n zulip_realm = Realm.objects.get(string_id=\"zulip\")\n try:\n user_realm = Realm.objects.exclude(id=zulip_realm.id)[0]\n except Realm.DoesNotExist:\n return\n\n user_realm.string_id = \"\"\n user_realm.save()\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('zerver', '0107_multiuseinvite'),\n ]\n\n operations = [\n migrations.RunPython(fix_realm_string_ids,\n reverse_code=migrations.RunPython.noop),\n ]\n","subject":"Add imports needed for new migration.","message":"mypy: Add imports needed for new migration.\n","lang":"Python","license":"apache-2.0","repos":"eeshangarg\/zulip,Galexrt\/zulip,shubhamdhama\/zulip,punchagan\/zulip,Galexrt\/zulip,tommyip\/zulip,brainwane\/zulip,tommyip\/zulip,zulip\/zulip,brainwane\/zulip,punchagan\/zulip,eeshangarg\/zulip,rht\/zulip,timabbott\/zulip,rht\/zulip,zulip\/zulip,andersk\/zulip,synicalsyntax\/zulip,brainwane\/zulip,rht\/zulip,eeshangarg\/zulip,rishig\/zulip,andersk\/zulip,timabbott\/zulip,amanharitsh123\/zulip,synicalsyntax\/zulip,timabbott\/zulip,rht\/zulip,jackrzhang\/zulip,rishig\/zulip,mahim97\/zulip,Galexrt\/zulip,kou\/zulip,brockwhittaker\/zulip,kou\/zulip,eeshangarg\/zulip,andersk\/zulip,dhcrzf\/zulip,hackerkid\/zulip,brockwhittaker\/zulip,verma-varsha\/zulip,showell\/zulip,brainwane\/zulip,kou\/zulip,shubhamdhama\/zulip,tommyip\/zulip,andersk\/zulip,brainwane\/zulip,eeshangarg\/zulip,hackerkid\/zulip,brainwane\/zulip,eeshangarg\/zulip,zulip\/zulip,andersk\/zulip,brainwane\/zulip,verma-varsha\/zulip,jackrzhang\/zulip,timabbott\/zulip,zulip\/zulip,synicalsyntax\/zulip,timabbott\/zulip,rht\/zulip,synicalsyntax\/zulip,Galexrt\/zulip,zulip\/zulip,dhcrzf\/zulip,rht\/zulip,showell\/zulip,rishig\/zulip,synicalsyntax\/zulip,mahim97\/zulip,kou\/zulip,mahim97\/zulip,verma-varsha\/zulip,showell\/zulip,Galexrt\/zulip,Galexrt\/zulip,jackrzhang\/zulip,eeshangarg\/zulip,synicalsyntax\/zulip,hackerkid\/zulip,punchagan\/zulip,tommyip\/zulip,shubhamdhama\/zulip,jackrzhang\/zulip,amanharitsh123\/zulip,tommyip\/zulip,jackrzhang\/zulip,amanharitsh123\/zulip,jackrzhang\/zulip,dhcrzf\/zulip,rishig\/zulip,dhcrzf\/zulip,dhcrzf\/zulip,mahim97\/zulip,shubhamdhama\/zulip,shubhamdhama\/zulip,rishig\/zulip,kou\/zulip,hackerkid\/zulip,mahim97\/zulip,zulip\/zulip,tommyip\/zulip,kou\/zulip,showell\/zulip,shubhamdhama\/zulip,punchagan\/zulip,rishig\/zulip,brockwhittaker\/zulip,punchagan\/zulip,andersk\/zulip,synicalsyntax\/zulip,amanharitsh123\/zulip,dhcrzf\/zulip,kou\/zulip,rht\/zulip,brockwhittaker\/zulip,zulip\/zulip,rishig\/zulip,verma-varsha\/zulip,punchagan\/zulip,hackerkid\/zulip,showell\/zulip,brockwhittaker\/zulip,hackerkid\/zulip,amanharitsh123\/zulip,mahim97\/zulip,showell\/zulip,Galexrt\/zulip,hackerkid\/zulip,shubhamdhama\/zulip,verma-varsha\/zulip,amanharitsh123\/zulip,brockwhittaker\/zulip,timabbott\/zulip,verma-varsha\/zulip,showell\/zulip,punchagan\/zulip,tommyip\/zulip,jackrzhang\/zulip,andersk\/zulip,timabbott\/zulip,dhcrzf\/zulip"} {"commit":"91ef89371f7ba99346ba982a3fdb7fc2105a9840","old_file":"superdesk\/users\/__init__.py","new_file":"superdesk\/users\/__init__.py","old_contents":"# -*- coding: utf-8; -*-\n#\n# This file is part of Superdesk.\n#\n# Copyright 2013, 2014 Sourcefabric z.u. and contributors.\n#\n# For the full copyright and license information, please see the\n# AUTHORS and LICENSE files distributed with this source code, or\n# at https:\/\/www.sourcefabric.org\/superdesk\/license\n\nfrom .users import RolesResource, UsersResource\nfrom .services import DBUsersService, RolesService, is_admin # noqa\nimport superdesk\n\n\ndef init_app(app):\n endpoint_name = 'users'\n service = DBUsersService(endpoint_name, backend=superdesk.get_backend())\n UsersResource(endpoint_name, app=app, service=service)\n\n endpoint_name = 'roles'\n service = RolesService(endpoint_name, backend=superdesk.get_backend())\n RolesResource(endpoint_name, app=app, service=service)\n\n superdesk.privilege(name='users', label='User Management', description='User can manage users.')\n superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.')\n\n # Registering with intrinsic privileges because: A user should be allowed to update their own profile.\n superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])\n","new_contents":"# -*- coding: utf-8; -*-\n#\n# This file is part of Superdesk.\n#\n# Copyright 2013, 2014 Sourcefabric z.u. and contributors.\n#\n# For the full copyright and license information, please see the\n# AUTHORS and LICENSE files distributed with this source code, or\n# at https:\/\/www.sourcefabric.org\/superdesk\/license\n\nfrom .users import RolesResource, UsersResource\nfrom .services import UsersService, DBUsersService, RolesService, is_admin # noqa\nimport superdesk\n\n\ndef init_app(app):\n endpoint_name = 'users'\n service = DBUsersService(endpoint_name, backend=superdesk.get_backend())\n UsersResource(endpoint_name, app=app, service=service)\n\n endpoint_name = 'roles'\n service = RolesService(endpoint_name, backend=superdesk.get_backend())\n RolesResource(endpoint_name, app=app, service=service)\n\n superdesk.privilege(name='users', label='User Management', description='User can manage users.')\n superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.')\n\n # Registering with intrinsic privileges because: A user should be allowed to update their own profile.\n superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])\n","subject":"Make UsersResource reusable for LDAP","message":"Make UsersResource reusable for LDAP\n","lang":"Python","license":"agpl-3.0","repos":"ioanpocol\/superdesk-core,plamut\/superdesk-core,akintolga\/superdesk-core,ancafarcas\/superdesk-core,ancafarcas\/superdesk-core,nistormihai\/superdesk-core,superdesk\/superdesk-core,sivakuna-aap\/superdesk-core,superdesk\/superdesk-core,mdhaman\/superdesk-core,petrjasek\/superdesk-core,mdhaman\/superdesk-core,mugurrus\/superdesk-core,mugurrus\/superdesk-core,mdhaman\/superdesk-core,superdesk\/superdesk-core,ioanpocol\/superdesk-core,sivakuna-aap\/superdesk-core,marwoodandrew\/superdesk-core,plamut\/superdesk-core,superdesk\/superdesk-core,petrjasek\/superdesk-core,ioanpocol\/superdesk-core,marwoodandrew\/superdesk-core,hlmnrmr\/superdesk-core,akintolga\/superdesk-core,nistormihai\/superdesk-core,hlmnrmr\/superdesk-core,mugurrus\/superdesk-core,petrjasek\/superdesk-core,petrjasek\/superdesk-core"} {"commit":"c0b7f0566380d06d11178969053fbc8d4128e100","old_file":"keybase\/__init__.py","new_file":"keybase\/__init__.py","old_contents":"'''\n.. moduleauthor:: Ian Chesal \n'''\n\n__version__ = '1.0.0'\n__all__ = ['keybase']\n\n","new_contents":"'''\n.. moduleauthor:: Ian Chesal \n'''\n\n__version__ = '1.0.1'\n__all__ = ['keybase']\n\n","subject":"Bump version 1.0.0 -> 1.0.1","message":"Bump version 1.0.0 -> 1.0.1\n","lang":"Python","license":"apache-2.0","repos":"ianchesal\/keybase-python,ianchesal\/keybase-python"} {"commit":"4fec4d9265007f644048811eade72718ed44fa58","old_file":"cms\/cache\/permissions.py","new_file":"cms\/cache\/permissions.py","old_contents":"# -*- coding: utf-8 -*-\nfrom django.conf import settings\nfrom django.core.cache import cache\n\npermission_cache_keys = [] \nall_keys = []\n\ndef get_cache_key(user, key):\n return \"%s:permission:%s:%s\" % (\n settings.CMS_CACHE_PREFIX, user.username, key)\n\ndef get_permission_cache(user, key):\n \"\"\"\n Helper for reading values from cache\n \"\"\"\n return cache.get(get_cache_key(user, key))\n\ndef set_permission_cache(user, key, value):\n \"\"\"\n Helper method for storing values in cache. Stores used keys so\n all of them can be cleaned when clean_permission_cache gets called.\n \"\"\"\n # store this key, so we can clean it when required\n cache_key = get_cache_key(user, key)\n \n if not cache_key in all_keys:\n all_keys.append(cache_key)\n if not key in permission_cache_keys:\n permission_cache_keys.append(key)\n cache.set(cache_key, value, settings.CMS_CACHE_DURATIONS['permissions'])\n\ndef clear_user_permission_cache(user):\n \"\"\"\n Cleans permission cache for given user.\n \"\"\"\n for key in permission_cache_keys:\n cache.delete(get_cache_key(user, key)) \n\ndef clear_permission_cache():\n for key in all_keys:\n cache.delete(key)\n","new_contents":"# -*- coding: utf-8 -*-\nfrom django.conf import settings\nfrom django.core.cache import cache\n\nfrom django.contrib.auth.models import User\n\nPERMISSION_KEYS = [\n 'can_change', 'can_add', 'can_delete',\n 'can_change_advanced_settings', 'can_publish',\n 'can_change_permissions', 'can_move_page',\n 'can_moderate', 'can_view']\n\n\ndef get_cache_key(user, key):\n return \"%s:permission:%s:%s\" % (\n settings.CMS_CACHE_PREFIX, user.username, key)\n\n\ndef get_permission_cache(user, key):\n \"\"\"\n Helper for reading values from cache\n \"\"\"\n return cache.get(get_cache_key(user, key))\n\n\ndef set_permission_cache(user, key, value):\n \"\"\"\n Helper method for storing values in cache. Stores used keys so\n all of them can be cleaned when clean_permission_cache gets called.\n \"\"\"\n # store this key, so we can clean it when required\n cache_key = get_cache_key(user, key)\n cache.set(cache_key, value, settings.CMS_CACHE_DURATIONS['permissions'])\n\n\ndef clear_user_permission_cache(user):\n \"\"\"\n Cleans permission cache for given user.\n \"\"\"\n for key in PERMISSION_KEYS:\n cache.delete(get_cache_key(user, key))\n\n\ndef clear_permission_cache():\n users = User.objects.filter(is_active=True)\n for user in users:\n for key in PERMISSION_KEYS:\n cache_key = get_cache_key(user, key)\n cache.delete(cache_key)\n","subject":"Fix for issue 1423 * no longer rely on global variables for invalidating caches","message":"Fix for issue 1423\n* no longer rely on global variables for invalidating caches\n","lang":"Python","license":"bsd-3-clause","repos":"SofiaReis\/django-cms,11craft\/django-cms,sznekol\/django-cms,vad\/django-cms,farhaadila\/django-cms,astagi\/django-cms,andyzsf\/django-cms,chkir\/django-cms,farhaadila\/django-cms,benzkji\/django-cms,bittner\/django-cms,360youlun\/django-cms,philippze\/django-cms,DylannCordel\/django-cms,jsma\/django-cms,intip\/django-cms,leture\/django-cms,josjevv\/django-cms,timgraham\/django-cms,netzkolchose\/django-cms,mkoistinen\/django-cms,leture\/django-cms,MagicSolutions\/django-cms,saintbird\/django-cms,SmithsonianEnterprises\/django-cms,rsalmaso\/django-cms,ojii\/django-cms,SinnerSchraderMobileMirrors\/django-cms,jrief\/django-cms,vstoykov\/django-cms,benzkji\/django-cms,nostalgiaz\/django-cms,intgr\/django-cms,MagicSolutions\/django-cms,selecsosi\/django-cms,robmagee\/django-cms,dhorelik\/django-cms,youprofit\/django-cms,kk9599\/django-cms,jeffreylu9\/django-cms,pbs\/django-cms,wuzhihui1123\/django-cms,DylannCordel\/django-cms,isotoma\/django-cms,wuzhihui1123\/django-cms,divio\/django-cms,rscnt\/django-cms,owers19856\/django-cms,SachaMPS\/django-cms,jsma\/django-cms,robmagee\/django-cms,rscnt\/django-cms,rryan\/django-cms,jproffitt\/django-cms,mkoistinen\/django-cms,jrclaramunt\/django-cms,jsma\/django-cms,pancentric\/django-cms,nimbis\/django-cms,evildmp\/django-cms,czpython\/django-cms,youprofit\/django-cms,11craft\/django-cms,czpython\/django-cms,stefanfoulis\/django-cms,philippze\/django-cms,andyzsf\/django-cms,divio\/django-cms,czpython\/django-cms,saintbird\/django-cms,rryan\/django-cms,jproffitt\/django-cms,youprofit\/django-cms,FinalAngel\/django-cms,sephii\/django-cms,rryan\/django-cms,keimlink\/django-cms,vad\/django-cms,chkir\/django-cms,irudayarajisawa\/django-cms,adaptivelogic\/django-cms,selecsosi\/django-cms,frnhr\/django-cms,takeshineshiro\/django-cms,FinalAngel\/django-cms,dhorelik\/django-cms,benzkji\/django-cms,webu\/django-cms,nostalgiaz\/django-cms,rsalmaso\/django-cms,selecsosi\/django-cms,SinnerSchraderMobileMirrors\/django-cms,yakky\/django-cms,datakortet\/django-cms,ojii\/django-cms,sznekol\/django-cms,adaptivelogic\/django-cms,foobacca\/django-cms,bittner\/django-cms,memnonila\/django-cms,vad\/django-cms,benzkji\/django-cms,ScholzVolkmer\/django-cms,irudayarajisawa\/django-cms,intip\/django-cms,vad\/django-cms,nostalgiaz\/django-cms,evildmp\/django-cms,stefanw\/django-cms,liuyisiyisi\/django-cms,intgr\/django-cms,vxsx\/django-cms,nimbis\/django-cms,stefanw\/django-cms,netzkolchose\/django-cms,intgr\/django-cms,czpython\/django-cms,chmberl\/django-cms,donce\/django-cms,wyg3958\/django-cms,andyzsf\/django-cms,bittner\/django-cms,sephii\/django-cms,selecsosi\/django-cms,frnhr\/django-cms,liuyisiyisi\/django-cms,SinnerSchraderMobileMirrors\/django-cms,cyberintruder\/django-cms,SachaMPS\/django-cms,rryan\/django-cms,owers19856\/django-cms,mkoistinen\/django-cms,foobacca\/django-cms,timgraham\/django-cms,frnhr\/django-cms,Vegasvikk\/django-cms,stefanfoulis\/django-cms,intgr\/django-cms,Jaccorot\/django-cms,iddqd1\/django-cms,ScholzVolkmer\/django-cms,foobacca\/django-cms,SachaMPS\/django-cms,jproffitt\/django-cms,cyberintruder\/django-cms,pbs\/django-cms,astagi\/django-cms,isotoma\/django-cms,qnub\/django-cms,qnub\/django-cms,isotoma\/django-cms,datakortet\/django-cms,vxsx\/django-cms,rsalmaso\/django-cms,ScholzVolkmer\/django-cms,pbs\/django-cms,petecummings\/django-cms,vstoykov\/django-cms,yakky\/django-cms,vxsx\/django-cms,robmagee\/django-cms,DylannCordel\/django-cms,memnonila\/django-cms,timgraham\/django-cms,wyg3958\/django-cms,foobacca\/django-cms,josjevv\/django-cms,Livefyre\/django-cms,SofiaReis\/django-cms,Livefyre\/django-cms,andyzsf\/django-cms,SmithsonianEnterprises\/django-cms,sephii\/django-cms,irudayarajisawa\/django-cms,stefanw\/django-cms,farhaadila\/django-cms,netzkolchose\/django-cms,kk9599\/django-cms,FinalAngel\/django-cms,360youlun\/django-cms,takeshineshiro\/django-cms,divio\/django-cms,evildmp\/django-cms,petecummings\/django-cms,jrclaramunt\/django-cms,divio\/django-cms,Livefyre\/django-cms,petecummings\/django-cms,jrief\/django-cms,rscnt\/django-cms,stefanw\/django-cms,nimbis\/django-cms,pixbuffer\/django-cms,AlexProfi\/django-cms,pancentric\/django-cms,11craft\/django-cms,Vegasvikk\/django-cms,wyg3958\/django-cms,nostalgiaz\/django-cms,kk9599\/django-cms,Jaccorot\/django-cms,pixbuffer\/django-cms,pixbuffer\/django-cms,dhorelik\/django-cms,evildmp\/django-cms,360youlun\/django-cms,AlexProfi\/django-cms,chkir\/django-cms,stefanfoulis\/django-cms,pbs\/django-cms,iddqd1\/django-cms,datakortet\/django-cms,memnonila\/django-cms,iddqd1\/django-cms,keimlink\/django-cms,astagi\/django-cms,sephii\/django-cms,frnhr\/django-cms,josjevv\/django-cms,pancentric\/django-cms,wuzhihui1123\/django-cms,vstoykov\/django-cms,liuyisiyisi\/django-cms,Livefyre\/django-cms,cyberintruder\/django-cms,webu\/django-cms,Jaccorot\/django-cms,jrief\/django-cms,intip\/django-cms,saintbird\/django-cms,SmithsonianEnterprises\/django-cms,isotoma\/django-cms,intip\/django-cms,MagicSolutions\/django-cms,jrief\/django-cms,SofiaReis\/django-cms,yakky\/django-cms,jeffreylu9\/django-cms,11craft\/django-cms,rsalmaso\/django-cms,qnub\/django-cms,owers19856\/django-cms,nimbis\/django-cms,takeshineshiro\/django-cms,bittner\/django-cms,sznekol\/django-cms,ojii\/django-cms,stefanfoulis\/django-cms,vxsx\/django-cms,leture\/django-cms,jeffreylu9\/django-cms,keimlink\/django-cms,AlexProfi\/django-cms,wuzhihui1123\/django-cms,chmberl\/django-cms,jrclaramunt\/django-cms,webu\/django-cms,jsma\/django-cms,mkoistinen\/django-cms,jproffitt\/django-cms,datakortet\/django-cms,FinalAngel\/django-cms,jeffreylu9\/django-cms,donce\/django-cms,yakky\/django-cms,adaptivelogic\/django-cms,chmberl\/django-cms,Vegasvikk\/django-cms,philippze\/django-cms,donce\/django-cms,netzkolchose\/django-cms"} {"commit":"05e19922a5a0f7268ce1a34e25e5deb8e9a2f5d3","old_file":"sfmtools.py","new_file":"sfmtools.py","old_contents":"\"\"\" Utility functions for PhotoScan processing \"\"\"\n\nimport os, sys\nimport PhotoScan\n\ndef align_and_clean_photos(chunk):\n ncameras = len(chunk.cameras)\n for frame in chunk.frames:\n frame.matchPhotos()\n\n chunk.alignCameras()\n for camera in chunk.cameras:\n if camera.transform is None:\n chunk.remove(camera)\n \n naligned = len(chunk.cameras)\n print('%d\/%d cameras aligned' % (naligned, ncameras))\n\ndef export_dems(resolution, formatstring, pathname)\n if not os.path.isdir(pathname):\n os.mkdir(pathname)\n \n nchunks = len(PhotoScan.app.document.chunks)\n nexported = nchunks\n for chunk in PhotoScan.app.document.chunks:\n filename = ''.join([pathname, chunk.label.split(' '), '.', formatstring])\n exported = chunk.exportDem(filename, format=formatstring, dx=resolution, dy=resolution)\n if not exported:\n print('Export failed:', chunk.label)\n nexported -= 1\n \n print('%d\/%d DEMs exported' % (nexported, nchunks))\n \n","new_contents":"\"\"\" Utility functions for PhotoScan processing \"\"\"\n\nimport os, sys\nimport PhotoScan\n\ndef align_and_clean_photos(chunk):\n ncameras = len(chunk.cameras)\n for frame in chunk.frames:\n frame.matchPhotos()\n\n chunk.alignCameras()\n for camera in chunk.cameras:\n if camera.transform is None:\n chunk.remove(camera)\n \n naligned = len(chunk.cameras)\n print('%d\/%d cameras aligned' % (naligned, ncameras))\n\ndef export_dems(resolution, formatstring, pathname)\n if not os.path.isdir(pathname):\n os.mkdir(pathname)\n if pathname[-1:] is not '\/':\n pathname = ''.join(pathname, '\/')\n \n nchunks = len(PhotoScan.app.document.chunks)\n nexported = nchunks\n for chunk in PhotoScan.app.document.chunks:\n filename = ''.join([pathname, chunk.label.split(' '), '.', formatstring])\n exported = chunk.exportDem(filename, format=formatstring, dx=resolution, dy=resolution)\n if not exported:\n print('Export failed:', chunk.label)\n nexported -= 1\n \n print('%d\/%d DEMs exported' % (nexported, nchunks))\n \n","subject":"Check for trailing slash in path","message":"Check for trailing slash in path","lang":"Python","license":"mit","repos":"rmsare\/sfmtools"} {"commit":"33328f7d6c3fbab4a7ae968103828ac40463543b","old_file":"__main__.py","new_file":"__main__.py","old_contents":"#!\/usr\/bin\/env python\n\n# MAKE IT UNICODE OK\nimport sys\nreload( sys )\nsys.setdefaultencoding( 'utf-8' )\n\nimport os, sys\nimport Bot\nimport logging\n\t\nif __name__ == '__main__':\n\tlogging.basicConfig( level = logging.DEBUG, format = '[%(asctime)s] %(levelname)s: %(message)s' )\n\tlogging.getLogger().addHandler( logging.FileHandler( 'ircbot.log' ) )\n\tlogging.info( \"Welcome to botje\" )\n\tfork = True\n\tif len( sys.argv ) > 1:\n\t\tif sys.argv[1] == '-nofork':\n\t\t\tfork = False\n\tif fork:\n\t\ttry:\n\t\t\tpid = os.fork()\n\t\t\tif pid > 0:\n\t\t\t\tlogging.info( 'Forked into PID {0}'.format( pid ) )\n\t\t\t\tsys.exit(0)\n\t\t\tsys.stdout = open( '\/tmp\/ircbot.log', 'w' )\n\t\texcept OSError as error:\n\t\t\tlogging.error( 'Unable to fork. Error: {0} ({1})'.format( error.errno, error.strerror ) )\n\t\t\tsys.exit(1)\n\tbotje = Bot.Bot()\n\twhile True:\n\t\ttry:\n\t\t\tbotje.start()\n\t\texcept Bot.BotReloadException:\n\t\t\tlogging.info( 'Force reloading Bot class' )\n\t\t\tbotje = None\n\t\t\treload(Bot)\n\t\t\tbotje = Bot.Bot()\n\t\tlogging.info( 'Botje died, restarting in 5...' )\n\t\timport time\n\t\ttime.sleep( 5 )\n","new_contents":"#!\/usr\/bin\/env python\n\n# MAKE IT UNICODE OK\nimport sys\nreload( sys )\nsys.setdefaultencoding( 'utf-8' )\n\nimport os, sys\nimport Bot\nimport logging\n\t\nif __name__ == '__main__':\n\tlogging.basicConfig( filename = 'ircbot.log', level = logging.DEBUG, format = '[%(asctime)s] %(levelname)s: %(message)s' )\n\tlogging.info( \"Welcome to botje\" )\n\tfork = True\n\tif len( sys.argv ) > 1:\n\t\tif sys.argv[1] == '-nofork':\n\t\t\tfork = False\n\tif fork:\n\t\ttry:\n\t\t\tpid = os.fork()\n\t\t\tif pid > 0:\n\t\t\t\tlogging.info( 'Forked into PID {0}'.format( pid ) )\n\t\t\t\tsys.exit(0)\n\t\t\tsys.stdout = open( '\/tmp\/ircbot.log', 'w' )\n\t\texcept OSError as error:\n\t\t\tlogging.error( 'Unable to fork. Error: {0} ({1})'.format( error.errno, error.strerror ) )\n\t\t\tsys.exit(1)\n\tbotje = Bot.Bot()\n\twhile True:\n\t\ttry:\n\t\t\tbotje.start()\n\t\texcept Bot.BotReloadException:\n\t\t\tlogging.info( 'Force reloading Bot class' )\n\t\t\tbotje = None\n\t\t\treload(Bot)\n\t\t\tbotje = Bot.Bot()\n\t\tlogging.info( 'Botje died, restarting in 5...' )\n\t\timport time\n\t\ttime.sleep( 5 )\n","subject":"Set default logger to file","message":"Set default logger to file\n","lang":"Python","license":"mit","repos":"jawsper\/modularirc"} {"commit":"0bd84e74a30806f1e317288aa5dee87b4c669790","old_file":"shcol\/config.py","new_file":"shcol\/config.py","old_contents":"# -*- coding: utf-8 -*-\n# Copyright (c) 2013-2015, Sebastian Linke\n\n# Released under the Simplified BSD license\n# (see LICENSE file for details).\n\n\"\"\"\nConstants that are used by `shcol` in many places. This is meant to modified (if\nneeded) only *before* running `shcol`, since most of these constants are only\nread during initialization of the `shcol`-package.\n\"\"\"\nimport logging\nimport os\nimport sys\n\nENCODING = 'utf-8'\nERROR_STREAM = sys.stderr\nINPUT_STREAM = sys.stdin\nLINE_WIDTH = None\nLINESEP = '\\n'\nLOGGER = logging.getLogger('shol')\nMAKE_UNIQUE = False\nON_WINDOWS = 'windows' in os.getenv('os', '').lower()\nPY_VERSION = sys.version_info[:2]\nSORT_ITEMS = False\nSPACING = 2\nSTARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else ''))\nTERMINAL_STREAM = sys.stdout\nUNICODE_TYPE = type(u'')\n","new_contents":"# -*- coding: utf-8 -*-\n# Copyright (c) 2013-2015, Sebastian Linke\n\n# Released under the Simplified BSD license\n# (see LICENSE file for details).\n\n\"\"\"\nConstants that are used by `shcol` in many places. This is meant to modified (if\nneeded) only *before* running `shcol`, since most of these constants are only\nread during initialization of the `shcol`-package.\n\"\"\"\nimport logging\nimport os\nimport sys\n\nERROR_STREAM = sys.stderr\nINPUT_STREAM = sys.stdin\nLINE_WIDTH = None\nLINESEP = '\\n'\nLOGGER = logging.getLogger('shol')\nMAKE_UNIQUE = False\nON_WINDOWS = 'windows' in os.getenv('os', '').lower()\nPY_VERSION = sys.version_info[:2]\nSORT_ITEMS = False\nSPACING = 2\nSTARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else ''))\nTERMINAL_STREAM = sys.stdout\nUNICODE_TYPE = type(u'')\n\nENCODING = TERMINAL_STREAM.encoding or 'utf-8'\n","subject":"Use output stream's encoding (if any). Blindly using UTF-8 would break output on Windows terminals.","message":"Use output stream's encoding (if any).\nBlindly using UTF-8 would break output on Windows terminals.\n","lang":"Python","license":"bsd-2-clause","repos":"seblin\/shcol"} {"commit":"bbc960aaf95569d4cafcbae7e4b1c638973f3797","old_file":"lbrynet\/__init__.py","new_file":"lbrynet\/__init__.py","old_contents":"import logging\n\n__version__ = \"0.17.0\"\nversion = tuple(__version__.split('.'))\n\nlogging.getLogger(__name__).addHandler(logging.NullHandler())\n","new_contents":"import logging\n\n__version__ = \"0.17.1rc1\"\nversion = tuple(__version__.split('.'))\n\nlogging.getLogger(__name__).addHandler(logging.NullHandler())\n","subject":"Bump version 0.17.0 --> 0.17.1rc1","message":"Bump version 0.17.0 --> 0.17.1rc1\n\nSigned-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>\n","lang":"Python","license":"mit","repos":"lbryio\/lbry,lbryio\/lbry,lbryio\/lbry"} {"commit":"49a275a268fba520252ee864c39934699c053d13","old_file":"csunplugged\/resources\/views\/barcode_checksum_poster.py","new_file":"csunplugged\/resources\/views\/barcode_checksum_poster.py","old_contents":"\"\"\"Module for generating Barcode Checksum Poster resource.\"\"\"\n\nfrom PIL import Image\nfrom utils.retrieve_query_parameter import retrieve_query_parameter\n\n\ndef resource_image(request, resource):\n \"\"\"Create a image for Barcode Checksum Poster resource.\n\n Args:\n request: HTTP request object (QueryDict).\n resource: Object of resource data (Resource).\n\n Returns:\n A list of Pillow image objects.\n \"\"\"\n # Retrieve parameters\n parameter_options = valid_options()\n barcode_length = retrieve_query_parameter(request, \"barcode_length\", parameter_options[\"barcode_length\"])\n\n image_path = \"static\/img\/resources\/barcode-checksum-poster\/{}-digits.png\"\n image = Image.open(image_path.format(barcode_length))\n return image\n\n\ndef subtitle(request, resource):\n \"\"\"Return the subtitle string of the resource.\n\n Used after the resource name in the filename, and\n also on the resource image.\n\n Args:\n request: HTTP request object (QueryDict).\n resource: Object of resource data (Resource).\n\n Returns:\n Text for subtitle (str).\n \"\"\"\n barcode_length = retrieve_query_parameter(request, \"barcode_length\")\n paper_size = retrieve_query_parameter(request, \"paper_size\")\n return \"{} digits - {}\".format(barcode_length, paper_size)\n\n\ndef valid_options():\n \"\"\"Provide dictionary of all valid parameters.\n\n This excludes the header text parameter.\n\n Returns:\n All valid options (dict).\n \"\"\"\n return {\n \"barcode_length\": [\"12\", \"13\"],\n \"paper_size\": [\"a4\", \"letter\"],\n }\n","new_contents":"\"\"\"Module for generating Barcode Checksum Poster resource.\"\"\"\n\nfrom PIL import Image\nfrom utils.retrieve_query_parameter import retrieve_query_parameter\n\n\ndef resource(request, resource):\n \"\"\"Create a image for Barcode Checksum Poster resource.\n\n Args:\n request: HTTP request object (QueryDict).\n resource: Object of resource data (Resource).\n\n Returns:\n A dictionary for the resource page.\n \"\"\"\n # Retrieve parameters\n parameter_options = valid_options()\n barcode_length = retrieve_query_parameter(request, \"barcode_length\", parameter_options[\"barcode_length\"])\n\n image_path = \"static\/img\/resources\/barcode-checksum-poster\/{}-digits.png\"\n image = Image.open(image_path.format(barcode_length))\n return {\"type\": \"image\", \"data\": image}\n\n\ndef subtitle(request, resource):\n \"\"\"Return the subtitle string of the resource.\n\n Used after the resource name in the filename, and\n also on the resource image.\n\n Args:\n request: HTTP request object (QueryDict).\n resource: Object of resource data (Resource).\n\n Returns:\n Text for subtitle (str).\n \"\"\"\n barcode_length = retrieve_query_parameter(request, \"barcode_length\")\n paper_size = retrieve_query_parameter(request, \"paper_size\")\n return \"{} digits - {}\".format(barcode_length, paper_size)\n\n\ndef valid_options():\n \"\"\"Provide dictionary of all valid parameters.\n\n This excludes the header text parameter.\n\n Returns:\n All valid options (dict).\n \"\"\"\n return {\n \"barcode_length\": [\"12\", \"13\"],\n \"paper_size\": [\"a4\", \"letter\"],\n }\n","subject":"Update barcode resource to new resource specification","message":"Update barcode resource to new resource specification\n","lang":"Python","license":"mit","repos":"uccser\/cs-unplugged,uccser\/cs-unplugged,uccser\/cs-unplugged,uccser\/cs-unplugged"} {"commit":"ee74fa5705fbf276e092b778f5bead9ffcd04b5e","old_file":"django_fixmystreet\/fixmystreet\/tests\/__init__.py","new_file":"django_fixmystreet\/fixmystreet\/tests\/__init__.py","old_contents":"import shutil\nimport os\n\nfrom django.core.files.storage import default_storage\nfrom django.test import TestCase\n\nclass SampleFilesTestCase(TestCase):\n fixtures = ['sample']\n\n @classmethod\n def setUpClass(cls):\n default_storage.location = 'media' # force using source media folder to avoid real data erasing\n # @classmethod\n # def setUpClass(cls):\n # shutil.copytree('media', 'media-tmp')\n # default_storage.location = 'media-tmp'\n# \n # @classmethod\n # def tearDownClass(self):\n # shutil.rmtree('media-tmp')\n\n def _fixture_setup(self):\n if os.path.exists('media\/photos'):\n shutil.rmtree('media\/photos')\n shutil.copytree('media\/photos-sample', 'media\/photos')\n super(SampleFilesTestCase, self)._fixture_setup()\n\n def tearDown(self):\n shutil.rmtree('media-tmp\/photos')\n\nfrom django_fixmystreet.fixmystreet.tests.views import *\nfrom django_fixmystreet.fixmystreet.tests.reports import *\nfrom django_fixmystreet.fixmystreet.tests.users import *\nfrom django_fixmystreet.fixmystreet.tests.organisation_entity import *\nfrom django_fixmystreet.fixmystreet.tests.mail import *\n# from django_fixmystreet.fixmystreet.tests.api import *\n","new_contents":"import shutil\nimport os\n\nfrom django.core.files.storage import default_storage\nfrom django.test import TestCase\n\nclass SampleFilesTestCase(TestCase):\n fixtures = ['sample']\n\n @classmethod\n def setUpClass(cls):\n default_storage.location = 'media' # force using source media folder to avoid real data erasing\n # @classmethod\n # def setUpClass(cls):\n # shutil.copytree('media', 'media-tmp')\n # default_storage.location = 'media-tmp'\n# \n # @classmethod\n # def tearDownClass(self):\n # shutil.rmtree('media-tmp')\n\n def _fixture_setup(self):\n if os.path.exists('media\/photos'):\n shutil.rmtree('media\/photos')\n shutil.copytree('media\/photos-sample', 'media\/photos')\n super(SampleFilesTestCase, self)._fixture_setup()\n\n def tearDown(self):\n shutil.rmtree('media\/photos')\n\nfrom django_fixmystreet.fixmystreet.tests.views import *\nfrom django_fixmystreet.fixmystreet.tests.reports import *\nfrom django_fixmystreet.fixmystreet.tests.users import *\nfrom django_fixmystreet.fixmystreet.tests.organisation_entity import *\nfrom django_fixmystreet.fixmystreet.tests.mail import *\n# from django_fixmystreet.fixmystreet.tests.api import *\n","subject":"Fix unit test fixtures files","message":"Fix unit test fixtures files\n","lang":"Python","license":"agpl-3.0","repos":"IMIO\/django-fixmystreet,IMIO\/django-fixmystreet,IMIO\/django-fixmystreet,IMIO\/django-fixmystreet"} {"commit":"12f3bb8c82b97496c79948d323f7076b6618293a","old_file":"saleor\/graphql\/scalars.py","new_file":"saleor\/graphql\/scalars.py","old_contents":"from graphene.types import Scalar\nfrom graphql.language import ast\n\n\nclass AttributesFilterScalar(Scalar):\n\n @staticmethod\n def coerce_filter(value):\n if isinstance(value, tuple) and len(value) == 2:\n return \":\".join(value)\n\n serialize = coerce_filter\n parse_value = coerce_filter\n\n @staticmethod\n def parse_literal(node):\n if isinstance(node, ast.StringValue):\n splitted = node.value.split(\":\")\n if len(splitted) == 2:\n return tuple(splitted)\n","new_contents":"from graphene.types import Scalar\nfrom graphql.language import ast\n\n\nclass AttributesFilterScalar(Scalar):\n\n @staticmethod\n def parse_literal(node):\n if isinstance(node, ast.StringValue):\n splitted = node.value.split(\":\")\n if len(splitted) == 2:\n return tuple(splitted)\n\n @staticmethod\n def parse_value(value):\n if isinstance(value, basestring):\n splitted = value.split(\":\")\n if len(splitted) == 2:\n return tuple(splitted)\n\n @staticmethod\n def serialize(value):\n if isinstance(value, tuple) and len(value) == 2:\n return \":\".join(value)\n","subject":"Fix parsing attributes filter values in GraphQL API","message":"Fix parsing attributes filter values in GraphQL API\n","lang":"Python","license":"bsd-3-clause","repos":"KenMutemi\/saleor,KenMutemi\/saleor,jreigel\/saleor,itbabu\/saleor,maferelo\/saleor,maferelo\/saleor,jreigel\/saleor,jreigel\/saleor,HyperManTT\/ECommerceSaleor,mociepka\/saleor,UITools\/saleor,UITools\/saleor,maferelo\/saleor,car3oon\/saleor,itbabu\/saleor,UITools\/saleor,HyperManTT\/ECommerceSaleor,car3oon\/saleor,car3oon\/saleor,UITools\/saleor,HyperManTT\/ECommerceSaleor,tfroehlich82\/saleor,itbabu\/saleor,tfroehlich82\/saleor,tfroehlich82\/saleor,KenMutemi\/saleor,mociepka\/saleor,UITools\/saleor,mociepka\/saleor"} {"commit":"5b8ff4276fbe92d5ccd5fa63fecccc5ff7d571a9","old_file":"quokka\/core\/tests\/test_models.py","new_file":"quokka\/core\/tests\/test_models.py","old_contents":"# coding: utf-8\nfrom . import BaseTestCase\n\nfrom ..models import Channel\n\n\nclass TestCoreModels(BaseTestCase):\n def setUp(self):\n # Create method was not returning the created object with\n # the create() method\n self.channel, new = Channel.objects.get_or_create(\n title=u'Monkey Island',\n description=u'The coolest pirate history ever',\n )\n\n def tearDown(self):\n self.channel.delete()\n\n def test_channel_fields(self):\n self.assertEqual(self.channel.title, u'Monkey Island')\n self.assertEqual(self.channel.slug, u'monkey-island')\n self.assertEqual(self.channel.description,\n u'The coolest pirate history ever')\n","new_contents":"# coding: utf-8\nfrom . import BaseTestCase\n\nfrom ..models import Channel\n\n\nclass TestChannel(BaseTestCase):\n def setUp(self):\n # Create method was not returning the created object with\n # the create() method\n self.parent, new = Channel.objects.get_or_create(\n title=u'Father',\n )\n self.channel, new = Channel.objects.get_or_create(\n title=u'Monkey Island',\n description=u'The coolest pirate history ever',\n parent=self.parent,\n tags=['tag1', 'tag2'],\n )\n\n def tearDown(self):\n self.channel.delete()\n\n def test_channel_fields(self):\n self.assertEqual(self.channel.title, u'Monkey Island')\n self.assertEqual(self.channel.slug, u'monkey-island')\n self.assertEqual(self.channel.long_slug, u'father\/monkey-island')\n self.assertEqual(self.channel.mpath, u',father,monkey-island,')\n self.assertEqual(self.channel.description,\n u'The coolest pirate history ever')\n self.assertEqual(self.channel.tags, ['tag1', 'tag2'])\n self.assertEqual(self.channel.parent, self.parent)\n self.assertEqual(unicode(self.channel), u'father\/monkey-island')\n\n def test_get_ancestors(self):\n self.assertEqual(list(self.channel.get_ancestors()), [self.channel,\n self.parent])\n\n def test_get_ancestors_slug(self):\n self.assertEqual(self.channel.get_ancestors_slugs(),\n [u'father\/monkey-island', u'father'])\n\n def test_get_children(self):\n self.assertEqual(list(self.parent.get_children()), [self.channel])\n\n def test_get_descendants(self):\n self.assertEqual(list(self.parent.get_descendants()),\n [self.parent, self.channel])\n\n def test_absolute_urls(self):\n self.assertEqual(self.channel.get_absolute_url(),\n '\/father\/monkey-island\/')\n self.assertEqual(self.parent.get_absolute_url(),\n '\/father\/')\n\n def test_get_canonical_url(self):\n self.assertEqual(self.channel.get_canonical_url(),\n '\/father\/monkey-island\/')\n self.assertEqual(self.parent.get_canonical_url(),\n '\/father\/')\n","subject":"Add more core tests \/ Rename test","message":"Add more core tests \/ Rename test\n","lang":"Python","license":"mit","repos":"romulocollopy\/quokka,felipevolpone\/quokka,lnick\/quokka,ChengChiongWah\/quokka,felipevolpone\/quokka,wushuyi\/quokka,wushuyi\/quokka,cbeloni\/quokka,felipevolpone\/quokka,CoolCloud\/quokka,ChengChiongWah\/quokka,lnick\/quokka,romulocollopy\/quokka,Ckai1991\/quokka,cbeloni\/quokka,CoolCloud\/quokka,alexandre\/quokka,felipevolpone\/quokka,fdumpling\/quokka,fdumpling\/quokka,romulocollopy\/quokka,CoolCloud\/quokka,maurobaraldi\/quokka,maurobaraldi\/quokka,romulocollopy\/quokka,Ckai1991\/quokka,fdumpling\/quokka,cbeloni\/quokka,ChengChiongWah\/quokka,lnick\/quokka,ChengChiongWah\/quokka,Ckai1991\/quokka,wushuyi\/quokka,lnick\/quokka,fdumpling\/quokka,CoolCloud\/quokka,alexandre\/quokka,Ckai1991\/quokka,maurobaraldi\/quokka,maurobaraldi\/quokka,wushuyi\/quokka,cbeloni\/quokka"} {"commit":"3037562643bc1ddaf081a6fa9c757aed4101bb53","old_file":"robots\/urls.py","new_file":"robots\/urls.py","old_contents":"try:\n from django.conf.urls import patterns, url\nexcept ImportError:\n from django.conf.urls.defaults import patterns, url\n\nurlpatterns = patterns(\n 'robots.views',\n url(r'^$', 'rules_list', name='robots_rule_list'),\n)\n","new_contents":"from django.conf.urls import url\n\nfrom robots.views import rules_list\n\n\nurlpatterns = [\n url(r'^$', rules_list, name='robots_rule_list'),\n]\n","subject":"Fix warnings about URLconf in Django 1.9","message":"Fix warnings about URLconf in Django 1.9\n\n* django.conf.urls.patterns will be removed in Django 1.10\n* Passing a dotted path and not a view function will be deprecated in\n Django 1.10\n","lang":"Python","license":"bsd-3-clause","repos":"jezdez\/django-robots,jezdez\/django-robots,jscott1971\/django-robots,jscott1971\/django-robots,jazzband\/django-robots,jazzband\/django-robots"} {"commit":"76243416f36a932c16bee93cc753de3d71168f0b","old_file":"manager\/__init__.py","new_file":"manager\/__init__.py","old_contents":"import os\n\nfrom flask import Flask\nfrom flask.ext.assets import Bundle, Environment\nfrom flask.ext.login import LoginManager\nfrom flask.ext.sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\n# Load the app config\napp.config.from_object(\"config.Config\")\n\nassets = Environment(app)\ndb= SQLAlchemy(app)\n\nlogin = LoginManager()\nlogin.init_app(app)\n\nassets.load_path = [\n os.path.join(os.path.dirname(__file__), 'static'),\n os.path.join(os.path.dirname(__file__), 'static', 'bower_components')\n]\n\nassets.register(\n 'js_all',\n Bundle(\n 'jquery\/dist\/jquery.min.js',\n 'bootstrap\/dist\/js\/bootstrap.min.js',\n output='js_all.js'\n )\n)\n\nassets.register(\n 'css_all',\n Bundle(\n 'bootswatch\/sandstone\/bootstrap.css',\n 'css\/ignition.css',\n output='css_all.css'\n )\n)\n\nfrom manager.views import core\n","new_contents":"import os\n\nfrom flask import Flask\nfrom flask.ext.assets import Bundle, Environment\nfrom flask.ext.login import LoginManager\nfrom flask.ext.sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\n# Load the app config\napp.config.from_object(\"config.Config\")\n\nassets = Environment(app)\ndb= SQLAlchemy(app)\n\nlogin = LoginManager()\nlogin.init_app(app)\n\nassets.load_path = [\n os.path.join(os.path.dirname(__file__), 'static'),\n os.path.join(os.path.dirname(__file__), 'static', 'bower_components')\n]\n\nassets.register(\n 'js_all',\n Bundle(\n 'jquery\/dist\/jquery.min.js',\n 'bootstrap\/dist\/js\/bootstrap.min.js',\n output='js_all.js'\n )\n)\n\nassets.register(\n 'css_all',\n Bundle(\n 'bootswatch\/sandstone\/bootstrap.css',\n 'css\/ignition.css',\n output='css_all.css'\n )\n)\n\nfrom manager.views import core\nfrom manager.models import users","subject":"Add user table to module init","message":"Add user table to module init\n","lang":"Python","license":"mit","repos":"hreeder\/ignition,hreeder\/ignition,hreeder\/ignition"} {"commit":"aba5ae9736b064fd1e3541de3ef36371d92fc875","old_file":"RandoAmisSecours\/admin.py","new_file":"RandoAmisSecours\/admin.py","old_contents":"# -*- coding: utf-8 -*-\n# vim: set ts=4\n\n# Copyright 2013 Rémi Duraffort\n# This file is part of RandoAmisSecours.\n#\n# RandoAmisSecours is free software: you can redistribute it and\/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# RandoAmisSecours is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with RandoAmisSecours. If not, see \n\nfrom django.contrib import admin\nfrom models import *\n\nadmin.site.register(FriendRequest)\nadmin.site.register(Outing)\nadmin.site.register(Profile)\n","new_contents":"# -*- coding: utf-8 -*-\n# vim: set ts=4\n\n# Copyright 2013 Rémi Duraffort\n# This file is part of RandoAmisSecours.\n#\n# RandoAmisSecours is free software: you can redistribute it and\/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# RandoAmisSecours is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with RandoAmisSecours. If not, see \n\nfrom django.contrib import admin\nfrom RandoAmisSecours.models import *\n\nadmin.site.register(FriendRequest)\nadmin.site.register(Outing)\nadmin.site.register(Profile)\n","subject":"Fix import when using python3.3","message":"Fix import when using python3.3\n","lang":"Python","license":"agpl-3.0","repos":"ivoire\/RandoAmisSecours,ivoire\/RandoAmisSecours"} {"commit":"b3ef748df9eca585ae3fc77da666ba5ce93bc428","old_file":"lala\/plugins\/fortune.py","new_file":"lala\/plugins\/fortune.py","old_contents":"import logging\n\nfrom functools import partial\nfrom lala.util import command, msg\nfrom twisted.internet.utils import getProcessOutput\n\n@command\ndef fortune(user, channel, text):\n \"\"\"Show a random, hopefully interesting, adage\"\"\"\n _call_fortune(user, channel)\n\n@command\ndef ofortune(user, channel, text):\n \"\"\"Show a random, hopefully interesting, offensive adage\"\"\"\n _call_fortune(user, channel, [\"-o\"])\n\ndef _call_fortune(user, channel, args=[]):\n \"\"\"Call the ``fortune`` executable with ``args`` (a sequence of strings).\n \"\"\"\n callback = partial(_send_output_to_channel, user, channel)\n errback = partial(_send_error_to_channel, user, channel)\n deferred = getProcessOutput(\"fortune\", args)\n deferred.addCallback(callback)\n deferred.addErrback(errback)\n deferred.addErrback(logging.error)\n\ndef _send_output_to_channel(user, channel, text):\n msg(channel, \"%s: %s\" %(user, text.replace(\"\\n\",\"\")))\n\ndef _send_error_to_channel(user, channel, exception):\n msg(channel, \"%s: Sorry, no fortune for you today! Details are in the log.\" % user)\n return exception\n","new_contents":"import logging\n\nfrom functools import partial\nfrom lala.util import command, msg\nfrom twisted.internet.utils import getProcessOutput\n\n@command\ndef fortune(user, channel, text):\n \"\"\"Show a random, hopefully interesting, adage\"\"\"\n _call_fortune(user, channel)\n\n@command\ndef ofortune(user, channel, text):\n \"\"\"Show a random, hopefully interesting, offensive adage\"\"\"\n _call_fortune(user, channel, [\"-o\"])\n\ndef _call_fortune(user, channel, args=[]):\n \"\"\"Call the ``fortune`` executable with ``args`` (a sequence of strings).\n \"\"\"\n callback = partial(_send_output_to_channel, user, channel)\n errback = partial(_send_error_to_channel, user, channel)\n deferred = getProcessOutput(\"fortune\", args)\n deferred.addCallback(callback)\n deferred.addErrback(errback)\n deferred.addErrback(logging.error)\n\ndef _send_output_to_channel(user, channel, text):\n msg(channel, \"%s: %s\" %(user, text.replace(\"\\n\",\" \")))\n\ndef _send_error_to_channel(user, channel, exception):\n msg(channel, \"%s: Sorry, no fortune for you today! Details are in the log.\" % user)\n return exception\n","subject":"Replace newlines with spaces for readability","message":"Replace newlines with spaces for readability\n","lang":"Python","license":"mit","repos":"mineo\/lala,mineo\/lala"} {"commit":"b9e1b34348444c4c51c8fd30ff7882552e21939b","old_file":"temba\/msgs\/migrations\/0094_auto_20170501_1641.py","new_file":"temba\/msgs\/migrations\/0094_auto_20170501_1641.py","old_contents":"# -*- coding: utf-8 -*-\n# Generated by Django 1.10.5 on 2017-05-01 16:41\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport temba.utils.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('msgs', '0093_populate_translatables'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='broadcast',\n name='language_dict',\n ),\n migrations.RemoveField(\n model_name='broadcast',\n name='media_dict',\n ),\n migrations.RemoveField(\n model_name='broadcast',\n name='text',\n ),\n migrations.AlterField(\n model_name='broadcast',\n name='base_language',\n field=models.CharField(help_text='The language used to send this to contacts without a language',\n max_length=4),\n ),\n migrations.AlterField(\n model_name='broadcast',\n name='translations',\n field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text',\n max_length=640, verbose_name='Translations'),\n ),\n migrations.RenameField(\n model_name='broadcast',\n old_name='translations',\n new_name='text',\n ),\n ]\n","new_contents":"# -*- coding: utf-8 -*-\n# Generated by Django 1.10.5 on 2017-05-01 16:41\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport temba.utils.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('msgs', '0093_populate_translatables'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='broadcast',\n name='base_language',\n field=models.CharField(help_text='The language used to send this to contacts without a language',\n max_length=4),\n ),\n migrations.AlterField(\n model_name='broadcast',\n name='translations',\n field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text',\n max_length=640, verbose_name='Translations'),\n ),\n migrations.RemoveField(\n model_name='broadcast',\n name='language_dict',\n ),\n migrations.RemoveField(\n model_name='broadcast',\n name='media_dict',\n ),\n migrations.RemoveField(\n model_name='broadcast',\n name='text',\n ),\n migrations.RenameField(\n model_name='broadcast',\n old_name='translations',\n new_name='text',\n ),\n ]\n","subject":"Change order of operations within migration so breaking schema changes come last","message":"Change order of operations within migration so breaking schema changes come last\n","lang":"Python","license":"agpl-3.0","repos":"pulilab\/rapidpro,pulilab\/rapidpro,pulilab\/rapidpro,pulilab\/rapidpro,pulilab\/rapidpro"} {"commit":"3c9da01bee3d157e344f3ad317b777b3977b2e4d","old_file":"account_invoice_start_end_dates\/models\/account_move.py","new_file":"account_invoice_start_end_dates\/models\/account_move.py","old_contents":"# Copyright 2019 Akretion France \n# @author: Alexis de Lattre \n# License AGPL-3.0 or later (http:\/\/www.gnu.org\/licenses\/agpl).\n\nfrom odoo import _, models\nfrom odoo.exceptions import UserError\n\n\nclass AccountMove(models.Model):\n _inherit = \"account.move\"\n\n def action_post(self):\n for move in self:\n for line in move.line_ids:\n if line.product_id and line.product_id.must_have_dates:\n if not line.start_date or not line.end_date:\n raise UserError(\n _(\n \"Missing Start Date and End Date for invoice \"\n \"line with Product '%s' which has the \"\n \"property 'Must Have Start and End Dates'.\"\n )\n % (line.product_id.display_name)\n )\n return super(AccountMove, self).action_post()\n","new_contents":"# Copyright 2019 Akretion France \n# @author: Alexis de Lattre \n# License AGPL-3.0 or later (http:\/\/www.gnu.org\/licenses\/agpl).\n\nfrom odoo import _, models\nfrom odoo.exceptions import UserError\n\n\nclass AccountMove(models.Model):\n _inherit = \"account.move\"\n\n def action_post(self):\n for move in self:\n for line in move.line_ids:\n if line.product_id and line.product_id.must_have_dates:\n if not line.start_date or not line.end_date:\n raise UserError(\n _(\n \"Missing Start Date and End Date for invoice \"\n \"line with Product '%s' which has the \"\n \"property 'Must Have Start and End Dates'.\"\n )\n % (line.product_id.display_name)\n )\n return super().action_post()\n","subject":"Use super() instead of super(classname, self)","message":"Use super() instead of super(classname, self)\n","lang":"Python","license":"agpl-3.0","repos":"OCA\/account-closing,OCA\/account-closing"} {"commit":"d0919465239399f1ab6d65bbd8c42b1b9657ddb6","old_file":"scripts\/utils.py","new_file":"scripts\/utils.py","old_contents":"#!\/usr\/bin\/env python3\n\n# Touhou Community Reliant Automatic Patcher\n# Scripts\n#\n# ----\n#\n\"\"\"Utility functions shared among all the scripts.\"\"\"\n\nfrom collections import OrderedDict\nimport json\nimport os\n\njson_load_params = {\n 'object_pairs_hook': OrderedDict\n}\n\ndef patch_files_filter(files):\n \"\"\"Filters all file names that can not be among the content of a patch.\"\"\"\n for i in files:\n if i != 'files.js':\n yield i\n\n\njson_dump_params = {\n 'ensure_ascii': False,\n 'indent': '\\t',\n 'separators': (',', ': '),\n 'sort_keys': True\n}\n\n# Default parameters for JSON input and output\ndef json_load(fn):\n with open(fn, 'r', encoding='utf-8') as file:\n return json.load(file, **json_load_params)\n\n\ndef json_store(fn, obj, dirs=['']):\n \"\"\"Saves the JSON object [obj] to [fn], creating all necessary\n directories in the process. If [dirs] is given, the function is\n executed for every root directory in the array.\"\"\"\n for i in dirs:\n full_fn = os.path.join(i, fn)\n os.makedirs(os.path.dirname(full_fn), exist_ok=True)\n with open(full_fn, 'w', encoding='utf-8') as file:\n json.dump(obj, file, **json_dump_params)\n file.write('\\n')\n","new_contents":"#!\/usr\/bin\/env python3\n\n# Touhou Community Reliant Automatic Patcher\n# Scripts\n#\n# ----\n#\n\"\"\"Utility functions shared among all the scripts.\"\"\"\n\nfrom collections import OrderedDict\nimport json\nimport os\n\njson_load_params = {\n 'object_pairs_hook': OrderedDict\n}\n\ndef patch_files_filter(files):\n \"\"\"Filters all file names that can not be among the content of a patch.\"\"\"\n for i in files:\n if i != 'files.js':\n yield i\n\n\njson_dump_params = {\n 'ensure_ascii': False,\n 'indent': '\\t',\n 'separators': (',', ': '),\n 'sort_keys': True\n}\n\n# Default parameters for JSON input and output\ndef json_load(fn, json_kwargs=json_load_params):\n with open(fn, 'r', encoding='utf-8') as file:\n return json.load(file, **json_kwargs)\n\n\ndef json_store(fn, obj, dirs=[''], json_kwargs=json_dump_params):\n \"\"\"Saves the JSON object [obj] to [fn], creating all necessary\n directories in the process. If [dirs] is given, the function is\n executed for every root directory in the array.\"\"\"\n for i in dirs:\n full_fn = os.path.join(i, fn)\n os.makedirs(os.path.dirname(full_fn), exist_ok=True)\n with open(full_fn, 'w', encoding='utf-8') as file:\n json.dump(obj, file, **json_kwargs)\n file.write('\\n')\n","subject":"Allow to override the JSON loading and dumping parameters.","message":"scripts: Allow to override the JSON loading and dumping parameters.\n","lang":"Python","license":"unlicense","repos":"VBChunguk\/thcrap,thpatch\/thcrap,VBChunguk\/thcrap,thpatch\/thcrap,thpatch\/thcrap,thpatch\/thcrap,thpatch\/thcrap,VBChunguk\/thcrap"} {"commit":"b0254fd4090c0d17f60a87f3fe5fe28c0382310e","old_file":"scripts\/v0to1.py","new_file":"scripts\/v0to1.py","old_contents":"#!\/usr\/bin\/env python\nimport sys\nimport h5py\n\ninfiles = sys.argv[1:]\n\nfor infile in infiles:\n with h5py.File(infile, 'a') as h5:\n print(infile)\n if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1:\n\n if 'matrix' in h5 and not 'pixels' in h5:\n print('renaming matrix --> pixels')\n h5['pixels'] = h5['matrix']\n\n if 'scaffolds' in h5 and not 'chroms' in h5:\n print('renaming scaffolds --> chroms')\n h5['chroms'] = h5['scaffolds']\n\n h5.attrs['format-version'] = 1\n\n","new_contents":"#!\/usr\/bin\/env python\nimport sys\nimport h5py\n\ninfiles = sys.argv[1:]\n\nfor infile in infiles:\n with h5py.File(infile, 'a') as h5:\n print(infile)\n if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1:\n\n if 'matrix' in h5 and not 'pixels' in h5:\n print('renaming matrix --> pixels')\n h5['pixels'] = h5['matrix']\n del h5['matrix']\n\n if 'scaffolds' in h5 and not 'chroms' in h5:\n print('renaming scaffolds --> chroms')\n h5['chroms'] = h5['scaffolds']\n del h5['scaffolds']\n\n h5.attrs['format-version'] = 1\n\n","subject":"Drop old names from v0","message":"Drop old names from v0\n","lang":"Python","license":"bsd-3-clause","repos":"mirnylab\/cooler"} {"commit":"de82b44979f3e3b1c7e73594cd2138d00add4e47","old_file":"test-console.py","new_file":"test-console.py","old_contents":"import logging\nlogging.basicConfig(level=logging.DEBUG)\n\nimport mdk_tracing\nimport time\n\nimport quark\n\ntracer = mdk_tracing.Tracer.withURLsAndToken(\"ws:\/\/localhost:52690\/ws\", None, None)\n# tracer = mdk_tracing.Tracer.withURLsAndToken(\"wss:\/\/tracing-develop.datawire.io\/ws\", None, None)\n\ndef goodHandler(result):\n\t# logging.info(\"Good!\")\n\n\tfor record in result:\n\t\tlogging.info(record.toString())\n\t\t\ndef badHandler(result):\n\tlogging.info(\"Failure: %s\" % result.toString())\n\ndef formatLogRecord(record):\n\treturn(\"%.3f %s %s\" % (record.timestamp, record.record.level, record.record.text))\n\ndef poller(hrm=None):\n\t# logging.info(\"POLLING\")\n\n\ttracer.poll() \\\n\t .andEither(goodHandler, badHandler) \\\n\t .andFinally(lambda x: quark.IO.schedule(1)) \\\n\t .andFinally(poller)\n\npoller()\n","new_contents":"import logging\nlogging.basicConfig(level=logging.DEBUG)\n\nimport mdk_tracing\nimport time\n\nimport quark\n\n# tracer = mdk_tracing.Tracer.withURLsAndToken(\"ws:\/\/localhost:52690\/ws\", None, None)\ntracer = mdk_tracing.Tracer.withURLsAndToken(\"wss:\/\/tracing-develop.datawire.io\/ws\", None, None)\n\ndef goodHandler(result):\n\t# logging.info(\"Good!\")\n\n\tfor record in result:\n\t\tlogging.info(record.toString())\n\t\t\ndef badHandler(result):\n\tlogging.info(\"Failure: %s\" % result.toString())\n\ndef formatLogRecord(record):\n\treturn(\"%.3f %s %s\" % (record.timestamp, record.record.level, record.record.text))\n\ndef poller(hrm=None):\n\t# logging.info(\"POLLING\")\n\n\ttracer.poll() \\\n\t .andEither(goodHandler, badHandler) \\\n\t .andFinally(lambda x: quark.IO.schedule(1)) \\\n\t .andFinally(poller)\n\npoller()\n","subject":"Switch console to use tracing-develop","message":"Switch console to use tracing-develop\n","lang":"Python","license":"apache-2.0","repos":"datawire\/mdk,datawire\/mdk,datawire\/mdk,datawire\/mdk"} {"commit":"43350965e171e6a3bfd89af3dd192ab5c9281b3a","old_file":"vumi\/blinkenlights\/tests\/test_message20110818.py","new_file":"vumi\/blinkenlights\/tests\/test_message20110818.py","old_contents":"from twisted.trial.unittest import TestCase\nimport vumi.blinkenlights.message20110818 as message\nimport time\n\n\nclass TestMessage(TestCase):\n\n def test_to_dict(self):\n now = time.time()\n datapoint = (\"vumi.w1.a_metric\", now, 1.5)\n msg = message.MetricMessage()\n msg.append(datapoint)\n self.assertEqual(msg.to_dict(), {\n 'datapoints': [datapoint],\n })\n\n def test_from_dict(self):\n now = time.time()\n datapoint = (\"vumi.w1.a_metric\", now, 1.5)\n msgdict = {\"datapoints\": [datapoint]}\n msg = message.MetricMessage.from_dict(msgdict)\n self.assertEqual(msg._datapoints, [datapoint])\n","new_contents":"from twisted.trial.unittest import TestCase\nimport vumi.blinkenlights.message20110818 as message\nimport time\n\n\nclass TestMessage(TestCase):\n\n def test_to_dict(self):\n now = time.time()\n datapoint = (\"vumi.w1.a_metric\", now, 1.5)\n msg = message.MetricMessage()\n msg.append(datapoint)\n self.assertEqual(msg.to_dict(), {\n 'datapoints': [datapoint],\n })\n\n def test_from_dict(self):\n now = time.time()\n datapoint = (\"vumi.w1.a_metric\", now, 1.5)\n msgdict = {\"datapoints\": [datapoint]}\n msg = message.MetricMessage.from_dict(msgdict)\n self.assertEqual(msg._datapoints, [datapoint])\n\n def test_extend(self):\n now = time.time()\n datapoint = (\"vumi.w1.a_metric\", now, 1.5)\n msg = message.MetricMessage()\n msg.extend([datapoint, datapoint, datapoint])\n self.assertEqual(msg._datapoints, [\n datapoint, datapoint, datapoint])\n","subject":"Add test for extend method.","message":"Add test for extend method.\n","lang":"Python","license":"bsd-3-clause","repos":"TouK\/vumi,vishwaprakashmishra\/xmatrix,vishwaprakashmishra\/xmatrix,vishwaprakashmishra\/xmatrix,TouK\/vumi,harrissoerja\/vumi,TouK\/vumi,harrissoerja\/vumi,harrissoerja\/vumi"} {"commit":"f5198851aebb000a6107b3f9ce34825da200abff","old_file":"src\/foremast\/utils\/get_template.py","new_file":"src\/foremast\/utils\/get_template.py","old_contents":"\"\"\"Render Jinja2 template.\"\"\"\nimport logging\nimport os\n\nimport jinja2\n\nLOG = logging.getLogger(__name__)\n\n\ndef get_template(template_file='', **kwargs):\n \"\"\"Get the Jinja2 template and renders with dict _kwargs_.\n\n Args:\n kwargs: Keywords to use for rendering the Jinja2 template.\n\n Returns:\n String of rendered JSON template.\n \"\"\"\n here = os.path.dirname(os.path.realpath(__file__))\n templatedir = '{0}\/..\/templates\/'.format(here)\n LOG.debug('Template directory: %s', templatedir)\n LOG.debug('Template file: %s', template_file)\n\n jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader(templatedir))\n template = jinjaenv.get_template(template_file)\n for k,v in kwargs.items():\n LOG.debug('%s => %s', k,v)\n rendered_json = template.render(**kwargs)\n\n LOG.debug('Rendered JSON:\\n%s', rendered_json)\n return rendered_json\n","new_contents":"\"\"\"Render Jinja2 template.\"\"\"\nimport logging\nimport os\n\nimport jinja2\n\nLOG = logging.getLogger(__name__)\n\n\ndef get_template(template_file='', **kwargs):\n \"\"\"Get the Jinja2 template and renders with dict _kwargs_.\n\n Args:\n kwargs: Keywords to use for rendering the Jinja2 template.\n\n Returns:\n String of rendered JSON template.\n \"\"\"\n here = os.path.dirname(os.path.realpath(__file__))\n templatedir = '{0}\/..\/templates\/'.format(here)\n LOG.debug('Template directory: %s', templatedir)\n LOG.debug('Template file: %s', template_file)\n\n jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader(templatedir))\n template = jinjaenv.get_template(template_file)\n for key, value in kwargs.items():\n LOG.debug('%s => %s', key, value)\n rendered_json = template.render(**kwargs)\n\n LOG.debug('Rendered JSON:\\n%s', rendered_json)\n return rendered_json\n","subject":"Use more descriptive variable names","message":"style: Use more descriptive variable names\n\nSee also: PSOBAT-1197\n","lang":"Python","license":"apache-2.0","repos":"gogoair\/foremast,gogoair\/foremast"} {"commit":"159d09e18dc3b10b7ba3c104a2761f300d50ff28","old_file":"organizer\/models.py","new_file":"organizer\/models.py","old_contents":"from django.db import models\n\n\n# Model Field Reference\n# https:\/\/docs.djangoproject.com\/en\/1.8\/ref\/models\/fields\/\n\n\nclass Tag(models.Model):\n name = models.CharField(\n max_length=31, unique=True)\n slug = models.SlugField(\n max_length=31,\n unique=True,\n help_text='A label for URL config.')\n\n\nclass Startup(models.Model):\n name = models.CharField(max_length=31)\n slug = models.SlugField()\n description = models.TextField()\n founded_date = models.DateField()\n contact = models.EmailField()\n website = models.URLField()\n tags = models.ManyToManyField(Tag)\n\n\nclass NewsLink(models.Model):\n title = models.CharField(max_length=63)\n pub_date = models.DateField()\n link = models.URLField()\n startup = models.ForeignKey(Startup)\n","new_contents":"from django.db import models\n\n\n# Model Field Reference\n# https:\/\/docs.djangoproject.com\/en\/1.8\/ref\/models\/fields\/\n\n\nclass Tag(models.Model):\n name = models.CharField(\n max_length=31, unique=True)\n slug = models.SlugField(\n max_length=31,\n unique=True,\n help_text='A label for URL config.')\n\n\nclass Startup(models.Model):\n name = models.CharField(max_length=31)\n slug = models.SlugField()\n description = models.TextField()\n founded_date = models.DateField()\n contact = models.EmailField()\n website = models.URLField()\n tags = models.ManyToManyField(Tag)\n\n\nclass NewsLink(models.Model):\n title = models.CharField(max_length=63)\n pub_date = models.DateField('date published')\n link = models.URLField(max_length=255)\n startup = models.ForeignKey(Startup)\n","subject":"Add options to NewsLink model fields.","message":"Ch03: Add options to NewsLink model fields. [skip ci]\n\nField options allow us to easily customize behavior of a field.\n\nVerbose name documentation:\n\n https:\/\/docs.djangoproject.com\/en\/1.8\/ref\/models\/fields\/#verbose-name\n https:\/\/docs.djangoproject.com\/en\/1.8\/topics\/db\/models\/#verbose-field-names\n\nThe max_length field option is defined in CharField and inherited by all\nCharField subclasses (but is typically optional in these subclasses,\nunlike CharField itself).\n\nThe 255 character limit of the URLField is based on RFC 3986.\n\n https:\/\/tools.ietf.org\/html\/rfc3986\n","lang":"Python","license":"bsd-2-clause","repos":"jambonrose\/DjangoUnleashed-1.8,jambonrose\/DjangoUnleashed-1.8"} {"commit":"761fbb68f72ff8f425ad40670ea908b4959d3292","old_file":"specchio\/main.py","new_file":"specchio\/main.py","old_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport time\n\nfrom watchdog.observers import Observer\n\nfrom specchio.handlers import SpecchioEventHandler\nfrom specchio.utils import init_logger, logger\n\n\ndef main():\n \"\"\"Main function for specchio\n\n Example: specchio test\/ user@host:test\/\n\n :return: None\n \"\"\"\n if len(sys.argv) == 3:\n src_path = sys.argv[1].strip()\n dst_ssh, dst_path = sys.argv[2].strip().split(\":\")\n event_handler = SpecchioEventHandler(\n src_path=src_path, dst_ssh=dst_path, dst_path=dst_path\n )\n init_logger()\n logger.info(\"Initialize Specchio\")\n observer = Observer()\n observer.schedule(event_handler, src_path, recursive=True)\n observer.start()\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n observer.stop()\n observer.join()\n else:\n print \"\"\"Specchio is a tool that can help you rsync your file,\nit use `.gitignore` in git to discern which file is ignored.\n\nUsage: specchio src\/ user@host:dst\"\"\"\n","new_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport time\n\nfrom watchdog.observers import Observer\n\nfrom specchio.handlers import SpecchioEventHandler\nfrom specchio.utils import init_logger, logger\n\n\ndef main():\n \"\"\"Main function for specchio\n\n Example: specchio test\/ user@host:test\/\n\n :return: None\n \"\"\"\n if len(sys.argv) == 3:\n src_path = sys.argv[1].strip()\n dst_ssh, dst_path = sys.argv[2].strip().split(\":\")\n event_handler = SpecchioEventHandler(\n src_path=src_path, dst_ssh=dst_path, dst_path=dst_path\n )\n init_logger()\n logger.info(\"Initialize Specchio\")\n observer = Observer()\n observer.schedule(event_handler, src_path, recursive=True)\n observer.start()\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n observer.stop()\n observer.join()\n else:\n print \"\"\"Usage: specchio src\/ user@host:dst\/\"\"\"\n","subject":"Fix the output when there is wrong usage","message":"Fix the output when there is wrong usage\n","lang":"Python","license":"mit","repos":"brickgao\/specchio"} {"commit":"e910c9f3ee3fec868f2a6dfb7b7d337440cbb768","old_file":"virtool\/logs.py","new_file":"virtool\/logs.py","old_contents":"import logging.handlers\n\nimport coloredlogs\n\n\ndef configure(verbose=False):\n logging_level = logging.INFO if verbose else logging.DEBUG\n\n logging.captureWarnings(True)\n\n log_format = \"%(asctime)-20s %(module)-11s %(levelname)-8s %(message)s\"\n\n coloredlogs.install(\n level=logging_level,\n fmt=log_format\n )\n\n logger = logging.getLogger(\"virtool\")\n\n handler = logging.handlers.RotatingFileHandler(\"virtool.log\", maxBytes=1000000, backupCount=5)\n handler.setFormatter(logging.Formatter(log_format))\n\n logger.addHandler(handler)\n\n return logger\n","new_contents":"import logging.handlers\n\nimport coloredlogs\n\n\ndef configure(verbose=False):\n logging_level = logging.INFO if verbose else logging.DEBUG\n\n logging.captureWarnings(True)\n\n log_format = \"%(asctime)-20s %(module)-11s %(levelname)-8s %(message)s\"\n\n coloredlogs.install(\n level=logging_level,\n fmt=log_format\n )\n\n logger = logging.getLogger()\n\n handler = logging.handlers.RotatingFileHandler(\"virtool.log\", maxBytes=1000000, backupCount=5)\n handler.setFormatter(logging.Formatter(log_format))\n\n logger.addHandler(handler)\n\n return logger\n","subject":"Write all log lines to log files","message":"Write all log lines to log files\n\nOnly the virtool logger was being written before.","lang":"Python","license":"mit","repos":"igboyes\/virtool,virtool\/virtool,virtool\/virtool,igboyes\/virtool"} {"commit":"0ddbea23c8703576e260fa5b57474930393e7d1a","old_file":"base\/components\/merchandise\/media\/views.py","new_file":"base\/components\/merchandise\/media\/views.py","old_contents":"","new_contents":"from django.views.generic import DetailView\n\nfrom .models import Videodisc\n\n\nclass VideodiscDetailView(DetailView):\n model = Videodisc\n template_name = 'merchandise\/media\/videodisc_detail.html'\n","subject":"Create a small detail view for videodiscs.","message":"Create a small detail view for videodiscs.\n","lang":"Python","license":"apache-2.0","repos":"hello-base\/web,hello-base\/web,hello-base\/web,hello-base\/web"} {"commit":"5d188a71ae43ec8858f985dddbb0ff970cd18e73","old_file":"feder\/domains\/apps.py","new_file":"feder\/domains\/apps.py","old_contents":"from django.apps import AppConfig\n\n\nclass DomainsConfig(AppConfig):\n name = \"domains\"\n","new_contents":"from django.apps import AppConfig\n\n\nclass DomainsConfig(AppConfig):\n name = \"feder.domains\"\n","subject":"Fix DomainsConfig.name to fix rtfd build","message":"Fix DomainsConfig.name to fix rtfd build\n","lang":"Python","license":"mit","repos":"watchdogpolska\/feder,watchdogpolska\/feder,watchdogpolska\/feder,watchdogpolska\/feder"} {"commit":"f6e8907b0e742b47425de140cc7b308c3815ffce","old_file":"dequorum\/forms.py","new_file":"dequorum\/forms.py","old_contents":"\nfrom django import forms\nfrom django.forms import widgets\n\nfrom . import models\n\n\nclass ThreadCreateForm(forms.ModelForm):\n\n class Meta:\n model = models.Thread\n fields = ['title']\n\n\nclass MessageCreateForm(forms.ModelForm):\n\n class Meta:\n model = models.Message\n fields = ['body']\n\n\nclass TagFilterForm(forms.Form):\n tag = forms.ModelMultipleChoiceField(\n queryset=models.Tag.objects.all(),\n required=True,\n widget=widgets.CheckboxSelectMultiple\n )","new_contents":"\nfrom django import forms\nfrom django.forms import widgets\n\nfrom . import models\n\n\nclass ThreadCreateForm(forms.ModelForm):\n\n class Meta:\n model = models.Thread\n fields = ['title']\n\n\nclass MessageCreateForm(forms.ModelForm):\n\n class Meta:\n model = models.Message\n fields = ['body']\n\n\nclass TagFilterForm(forms.Form):\n tag = forms.ModelMultipleChoiceField(\n queryset=models.Tag.objects.all(),\n required=False,\n widget=widgets.CheckboxSelectMultiple\n )\n","subject":"Mark tags as not required in filter form","message":"Mark tags as not required in filter form\n","lang":"Python","license":"mit","repos":"funkybob\/django-dequorum,funkybob\/django-dequorum,funkybob\/django-dequorum"} {"commit":"58734468f027ddff31bfa7dc685f4af177e8dbb1","old_file":"t5x\/__init__.py","new_file":"t5x\/__init__.py","old_contents":"# Copyright 2021 The T5X Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Import API modules.\"\"\"\n\nimport t5x.adafactor\nimport t5x.checkpoints\nimport t5x.decoding\nimport t5x.gin_utils\nimport t5x.models\nimport t5x.multihost_utils\nimport t5x.partitioning\nimport t5x.state_utils\nimport t5x.train_state\nimport t5x.trainer\nimport t5x.utils\n\n# Version number.\nfrom t5x.version import __version__\n\n# TODO(adarob): Move clients to t5x.checkpointing and rename\n# checkpoints.py to checkpointing.py\ncheckpointing = t5x.checkpoints\n","new_contents":"# Copyright 2021 The T5X Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Import API modules.\"\"\"\n\nimport t5x.adafactor\nimport t5x.checkpoints\nimport t5x.decoding\nimport t5x.gin_utils\nimport t5x.losses\nimport t5x.models\nimport t5x.multihost_utils\nimport t5x.partitioning\nimport t5x.state_utils\nimport t5x.train_state\nimport t5x.trainer\nimport t5x.utils\n\n# Version number.\nfrom t5x.version import __version__\n\n# TODO(adarob): Move clients to t5x.checkpointing and rename\n# checkpoints.py to checkpointing.py\ncheckpointing = t5x.checkpoints\n","subject":"Add t5x.losses to public API.","message":"Add t5x.losses to public API.\n\nPiperOrigin-RevId: 417631806\n","lang":"Python","license":"apache-2.0","repos":"google-research\/t5x"} {"commit":"34960807eac1818a8167ff015e941c42be8827da","old_file":"checkenv.py","new_file":"checkenv.py","old_contents":"from colorama import Fore\nfrom pkgutil import iter_modules\n\n\ndef check_import(packagename):\n \"\"\"\n Checks that a package is present. Returns true if it is available, and\n false if not available.\n \"\"\"\n if packagename in (name for _, name, _ in iter_modules()):\n return True\n else:\n return False\n\n\npackages = ['missingno', 'pytest', 'pytest_cov', 'tinydb', 'yaml',\n 'pandas_summary', 'environment_kernels', 'hypothesis']\n\ntry:\n for pkg in packages:\n assert check_import(pkg)\n print(Fore.GREEN + 'All packages found; environment checks passed.')\nexcept AssertionError:\n print(Fore.RED + f\"{pkg} cannot be found. Please pip or conda install.\")\n","new_contents":"from colorama import Fore, Style\nfrom pkgutil import iter_modules\n\n\ndef check_import(packagename):\n \"\"\"\n Checks that a package is present. Returns true if it is available, and\n false if not available.\n \"\"\"\n if packagename in (name for _, name, _ in iter_modules()):\n return True\n else:\n return False\n\n\npackages = ['missingno', 'pytest', 'pytest_cov', 'tinydb', 'yaml',\n 'pandas_summary', 'environment_kernels', 'hypothesis']\n\ntry:\n for pkg in packages:\n assert check_import(pkg)\n print(Fore.GREEN + 'All packages found; environment checks passed.')\nexcept AssertionError:\n print(Fore.RED + f\"{pkg} cannot be found. Please pip or conda install.\")\n\nStyle.RESET_ALL\n","subject":"Reset colors at the end","message":"Reset colors at the end\n","lang":"Python","license":"mit","repos":"ericmjl\/data-testing-tutorial,ericmjl\/data-testing-tutorial"} {"commit":"dfa752590c944fc07253c01c3d99b640a46dae1d","old_file":"jinja2_time\/jinja2_time.py","new_file":"jinja2_time\/jinja2_time.py","old_contents":"# -*- coding: utf-8 -*-\n\nimport arrow\n\nfrom jinja2 import nodes\nfrom jinja2.ext import Extension\n\n\nclass TimeExtension(Extension):\n tags = set(['now'])\n\n def __init__(self, environment):\n super(TimeExtension, self).__init__(environment)\n\n # add the defaults to the environment\n environment.extend(\n datetime_format='%Y-%m-%d',\n )\n\n def _now(self, timezone, datetime_format):\n datetime_format = datetime_format or self.environment.datetime_format\n return arrow.now(timezone).strftime(datetime_format)\n\n def parse(self, parser):\n lineno = next(parser.stream).lineno\n\n args = [parser.parse_expression()]\n\n if parser.stream.skip_if('comma'):\n args.append(parser.parse_expression())\n else:\n args.append(nodes.Const(None))\n\n call = self.call_method('_now', args, lineno=lineno)\n\n return nodes.Output([call], lineno=lineno)\n","new_contents":"# -*- coding: utf-8 -*-\n\nimport arrow\n\nfrom jinja2 import nodes\nfrom jinja2.ext import Extension\n\n\nclass TimeExtension(Extension):\n tags = set(['now'])\n\n def __init__(self, environment):\n super(TimeExtension, self).__init__(environment)\n\n # add the defaults to the environment\n environment.extend(datetime_format='%Y-%m-%d')\n\n def _datetime(self, timezone, operator, offset, datetime_format):\n d = arrow.now(timezone)\n\n # Parse replace kwargs from offset and include operator\n replace_params = {}\n for param in offset.split(','):\n interval, value = param.split('=')\n replace_params[interval] = float(operator + value)\n d = d.replace(**replace_params)\n\n if datetime_format is None:\n datetime_format = self.environment.datetime_format\n return d.strftime(datetime_format)\n\n def _now(self, timezone, datetime_format):\n if datetime_format is None:\n datetime_format = self.environment.datetime_format\n return arrow.now(timezone).strftime(datetime_format)\n\n def parse(self, parser):\n lineno = next(parser.stream).lineno\n\n node = parser.parse_expression()\n\n if parser.stream.skip_if('comma'):\n datetime_format = parser.parse_expression()\n else:\n datetime_format = nodes.Const(None)\n\n if isinstance(node, nodes.Add):\n call_method = self.call_method(\n '_datetime',\n [node.left, nodes.Const('+'), node.right, datetime_format],\n lineno=lineno,\n )\n elif isinstance(node, nodes.Sub):\n call_method = self.call_method(\n '_datetime',\n [node.left, nodes.Const('-'), node.right, datetime_format],\n lineno=lineno,\n )\n else:\n call_method = self.call_method(\n '_now',\n [node, datetime_format],\n lineno=lineno,\n )\n return nodes.Output([call_method], lineno=lineno)\n","subject":"Implement parser method for optional offset","message":"Implement parser method for optional offset\n","lang":"Python","license":"mit","repos":"hackebrot\/jinja2-time"} {"commit":"5b3d69d2c9338ab0c50fd9ea8cf3c01adf0c1de3","old_file":"breakpad.py","new_file":"breakpad.py","old_contents":"# Copyright (c) 2009 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Breakpad for Python.\n\nSends a notification when a process stops on an exception.\"\"\"\n\nimport atexit\nimport getpass\nimport urllib\nimport traceback\nimport sys\n\n\ndef SendStack(stack, url='http:\/\/chromium-status.appspot.com\/breakpad'):\n print 'Do you want to send a crash report [y\/N]? ',\n if sys.stdin.read(1).lower() == 'y':\n try:\n params = {\n 'args': sys.argv,\n 'stack': stack,\n 'user': getpass.getuser(),\n }\n request = urllib.urlopen(url, urllib.urlencode(params))\n print request.read()\n request.close()\n except IOError:\n print('There was a failure while trying to send the stack trace. Too bad.')\n\n\n@atexit.register\ndef CheckForException():\n if 'test' in sys.modules['__main__'].__file__:\n # Probably a unit test.\n return\n last_tb = getattr(sys, 'last_traceback', None)\n if last_tb:\n SendStack(''.join(traceback.format_tb(last_tb)))\n","new_contents":"# Copyright (c) 2009 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Breakpad for Python.\n\nSends a notification when a process stops on an exception.\"\"\"\n\nimport atexit\nimport getpass\nimport urllib\nimport traceback\nimport sys\n\n\ndef SendStack(stack, url='http:\/\/chromium-status.appspot.com\/breakpad'):\n print 'Do you want to send a crash report [y\/N]? ',\n if sys.stdin.read(1).lower() == 'y':\n try:\n params = {\n 'args': sys.argv,\n 'stack': stack,\n 'user': getpass.getuser(),\n }\n request = urllib.urlopen(url, urllib.urlencode(params))\n print request.read()\n request.close()\n except IOError:\n print('There was a failure while trying to send the stack trace. Too bad.')\n\n\n#@atexit.register\ndef CheckForException():\n if 'test' in sys.modules['__main__'].__file__:\n # Probably a unit test.\n return\n last_tb = getattr(sys, 'last_traceback', None)\n if last_tb:\n SendStack(''.join(traceback.format_tb(last_tb)))\n","subject":"Disable braekpad automatic registration while we figure out stuff","message":"Disable braekpad automatic registration while we figure out stuff\n\nReview URL: http:\/\/codereview.chromium.org\/462022\n\ngit-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33686 0039d316-1c4b-4281-b951-d872f2087c98\n","lang":"Python","license":"bsd-3-clause","repos":"xuyuhan\/depot_tools,npe9\/depot_tools,SuYiling\/chrome_depot_tools,Neozaru\/depot_tools,npe9\/depot_tools,Midrya\/chromium,michalliu\/chromium-depot_tools,kaiix\/depot_tools,disigma\/depot_tools,Chilledheart\/depot_tools,fracting\/depot_tools,airtimemedia\/depot_tools,Midrya\/chromium,duongbaoduy\/gtools,coreos\/depot_tools,duongbaoduy\/gtools,liaorubei\/depot_tools,coreos\/depot_tools,duanwujie\/depot_tools,duanwujie\/depot_tools,jankeromnes\/depot_tools,SuYiling\/chrome_depot_tools,primiano\/depot_tools,jankeromnes\/depot_tools,smikes\/depot_tools,G-P-S\/depot_tools,G-P-S\/depot_tools,HackFisher\/depot_tools,fanjunwei\/depot_tools,Phonebooth\/depot_tools,azunite\/chrome_build,Phonebooth\/depot_tools,cpanelli\/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,Neozaru\/depot_tools,HackFisher\/depot_tools,Neozaru\/depot_tools,jankeromnes\/depot_tools,jankeromnes\/depot_tools,cybertk\/depot_tools,airtimemedia\/depot_tools,coreos\/depot_tools,CoherentLabs\/depot_tools,xuyuhan\/depot_tools,kaiix\/depot_tools,primiano\/depot_tools,cybertk\/depot_tools,azunite\/chrome_build,fanjunwei\/depot_tools,airtimemedia\/depot_tools,xuyuhan\/depot_tools,fracting\/depot_tools,yetu\/repotools,jankeromnes\/depot_tools,cybertk\/depot_tools,ajohnson23\/depot_tools,sarvex\/depot-tools,primiano\/depot_tools,kromain\/chromium-tools,jankeromnes\/depot_tools,eatbyte\/depot_tools,gcodetogit\/depot_tools,eatbyte\/depot_tools,fracting\/depot_tools,michalliu\/chromium-depot_tools,SuYiling\/chrome_depot_tools,cpanelli\/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,coreos\/depot_tools,withtone\/depot_tools,mlufei\/depot_tools,azureplus\/chromium_depot_tools,duanwujie\/depot_tools,cybertk\/depot_tools,sarvex\/depot-tools,hsharsha\/depot_tools,coreos\/depot_tools,cpanelli\/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,Chilledheart\/depot_tools,ajohnson23\/depot_tools,chinmaygarde\/depot_tools,smikes\/depot_tools,kromain\/chromium-tools,smikes\/depot_tools,duongbaoduy\/gtools,Neozaru\/depot_tools,aleonliao\/depot_tools,smikes\/depot_tools,kaiix\/depot_tools,xuyuhan\/depot_tools,hsharsha\/depot_tools,yetu\/repotools,liaorubei\/depot_tools,withtone\/depot_tools,cybertk\/depot_tools,coreos\/depot_tools,npe9\/depot_tools,azureplus\/chromium_depot_tools,chinmaygarde\/depot_tools,Chilledheart\/depot_tools,yetu\/repotools,michalliu\/chromium-depot_tools,aleonliao\/depot_tools,airtimemedia\/depot_tools,liaorubei\/depot_tools,sarvex\/depot-tools,eatbyte\/depot_tools,eatbyte\/depot_tools,disigma\/depot_tools,Phonebooth\/depot_tools,npe9\/depot_tools,azureplus\/chromium_depot_tools,Neozaru\/depot_tools,fanjunwei\/depot_tools,azunite\/chrome_build,chinmaygarde\/depot_tools,Midrya\/chromium,kromain\/chromium-tools,disigma\/depot_tools,G-P-S\/depot_tools,G-P-S\/depot_tools,mlufei\/depot_tools,CoherentLabs\/depot_tools,kromain\/chromium-tools,gcodetogit\/depot_tools,jankeromnes\/depot_tools,Chilledheart\/depot_tools,sarvex\/depot-tools,HackFisher\/depot_tools,gcodetogit\/depot_tools,withtone\/depot_tools,aleonliao\/depot_tools,hsharsha\/depot_tools,mlufei\/depot_tools,Chilledheart\/depot_tools,smikes\/depot_tools,liaorubei\/depot_tools,ajohnson23\/depot_tools,Phonebooth\/depot_tools,fanjunwei\/depot_tools,michalliu\/chromium-depot_tools,HackFisher\/depot_tools"} {"commit":"d68f28581cd3c3f57f7c41adbd65676887a51136","old_file":"opps\/channels\/tests\/test_forms.py","new_file":"opps\/channels\/tests\/test_forms.py","old_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\n\nfrom django.test import TestCase\nfrom django.contrib.sites.models import Site\nfrom django.contrib.auth import get_user_model\n\nfrom opps.channels.models import Channel\nfrom opps.channels.forms import ChannelAdminForm\n\n\nclass ChannelFormTest(TestCase):\n\n def setUp(self):\n User = get_user_model()\n self.user = User.objects.create(username=u'test', password='test')\n self.site = Site.objects.filter(name=u'example.com').get()\n self.parent = Channel.objects.create(name=u'Home', slug=u'home',\n description=u'home page',\n site=self.site, user=self.user)\n\n def test_init(self):\n \"\"\"\n Test successful init without data\n \"\"\"\n form = ChannelAdminForm(instance=self.parent)\n self.assertTrue(isinstance(form.instance, Channel))\n self.assertEqual(form.instance.pk, self.parent.pk)\n\n","new_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\n\nfrom django.test import TestCase\nfrom django.contrib.sites.models import Site\nfrom django.contrib.auth import get_user_model\n\nfrom opps.channels.models import Channel\nfrom opps.channels.forms import ChannelAdminForm\n\n\nclass ChannelFormTest(TestCase):\n\n def setUp(self):\n User = get_user_model()\n self.user = User.objects.create(username=u'test', password='test')\n self.site = Site.objects.filter(name=u'example.com').get()\n self.parent = Channel.objects.create(name=u'Home', slug=u'home',\n description=u'home page',\n site=self.site, user=self.user)\n\n def test_init(self):\n \"\"\"\n Test successful init without data\n \"\"\"\n form = ChannelAdminForm(instance=self.parent)\n self.assertTrue(isinstance(form.instance, Channel))\n self.assertEqual(form.instance.pk, self.parent.pk)\n self.assertEqual(int(form.fields['slug'].widget.attrs['maxlength']), 150)\n\n def test_readonly_slug(self):\n \"\"\"\n Check readonly field slug\n \"\"\"\n form = ChannelAdminForm(instance=self.parent)\n self.assertTrue(form.fields['slug'].widget.attrs['readonly'])\n\n form_2 = ChannelAdminForm()\n self.assertNotIn('readonly', form_2.fields['slug'].widget.attrs)\n","subject":"Add test check readonly field slug of channel","message":"Add test check readonly field slug of channel\n","lang":"Python","license":"mit","repos":"jeanmask\/opps,opps\/opps,jeanmask\/opps,YACOWS\/opps,williamroot\/opps,williamroot\/opps,opps\/opps,YACOWS\/opps,YACOWS\/opps,williamroot\/opps,williamroot\/opps,jeanmask\/opps,YACOWS\/opps,opps\/opps,jeanmask\/opps,opps\/opps"} {"commit":"b97115679929dfe4f69618f756850617f265048f","old_file":"service\/pixelated\/config\/site.py","new_file":"service\/pixelated\/config\/site.py","old_contents":"from twisted.web.server import Site, Request\n\n\nclass AddCSPHeaderRequest(Request):\n CSP_HEADER_VALUES = \"default-src 'self'; style-src 'self' 'unsafe-inline'\"\n\n def process(self):\n self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES)\n self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES)\n self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES)\n self.setHeader('X-Frame-Options', 'SAMEORIGIN')\n self.setHeader('X-XSS-Protection', '1; mode=block')\n self.setHeader('X-Content-Type-Options', 'nosniff')\n\n if self.isSecure():\n self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')\n\n Request.process(self)\n\n\nclass PixelatedSite(Site):\n\n requestFactory = AddCSPHeaderRequest\n\n @classmethod\n def enable_csp_requests(cls):\n cls.requestFactory = AddCSPHeaderRequest\n\n @classmethod\n def disable_csp_requests(cls):\n cls.requestFactory = Site.requestFactory\n","new_contents":"from twisted.web.server import Site, Request\n\n\nclass AddSecurityHeadersRequest(Request):\n CSP_HEADER_VALUES = \"default-src 'self'; style-src 'self' 'unsafe-inline'\"\n\n def process(self):\n self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES)\n self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES)\n self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES)\n self.setHeader('X-Frame-Options', 'SAMEORIGIN')\n self.setHeader('X-XSS-Protection', '1; mode=block')\n self.setHeader('X-Content-Type-Options', 'nosniff')\n\n if self.isSecure():\n self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')\n\n Request.process(self)\n\n\nclass PixelatedSite(Site):\n\n requestFactory = AddSecurityHeadersRequest\n\n @classmethod\n def enable_csp_requests(cls):\n cls.requestFactory = AddSecurityHeadersRequest\n\n @classmethod\n def disable_csp_requests(cls):\n cls.requestFactory = Site.requestFactory\n","subject":"Rename class to match intent","message":"Rename class to match intent\n","lang":"Python","license":"agpl-3.0","repos":"pixelated-project\/pixelated-user-agent,pixelated\/pixelated-user-agent,pixelated-project\/pixelated-user-agent,pixelated-project\/pixelated-user-agent,pixelated-project\/pixelated-user-agent,pixelated\/pixelated-user-agent,pixelated-project\/pixelated-user-agent,pixelated\/pixelated-user-agent,pixelated\/pixelated-user-agent,pixelated\/pixelated-user-agent"} {"commit":"4b245b9a859552adb9c19fafc4bdfab5780782f2","old_file":"d1_common_python\/src\/d1_common\/__init__.py","new_file":"d1_common_python\/src\/d1_common\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\n\n# This work was created by participants in the DataONE project, and is\n# jointly copyrighted by participating institutions in DataONE. For\n# more information on DataONE, see our web site at http:\/\/dataone.org.\n#\n# Copyright 2009-2016 DataONE\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"d1_common\nShared code for DataONE Python libraries\n\"\"\"\n\n__version__ = \"2.1.0\"\n\n__all__ = [\n 'const',\n 'exceptions',\n 'upload',\n 'xmlrunner',\n 'types.exceptions',\n 'types.dataoneTypes',\n 'types.dataoneErrors',\n 'ext.mimeparser',\n]\n","new_contents":"# -*- coding: utf-8 -*-\n\n# This work was created by participants in the DataONE project, and is\n# jointly copyrighted by participating institutions in DataONE. For\n# more information on DataONE, see our web site at http:\/\/dataone.org.\n#\n# Copyright 2009-2016 DataONE\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"d1_common\nShared code for DataONE Python libraries\n\"\"\"\n\n__version__ = \"2.1.0\"\n\n# Set default logging handler to avoid \"No handler found\" warnings.\nimport logging\n\ntry:\n from logging import NullHandler\nexcept ImportError:\n class NullHandler(logging.Handler):\n def emit(self, record):\n pass\n\nlogging.getLogger(__name__).addHandler(NullHandler())\n","subject":"Add logging NullHandler to prevent \"no handler found\" errors","message":"Add logging NullHandler to prevent \"no handler found\" errors\n\nThis fixes the issue where \"no handler found\" errors would be printed by\nthe library if library clients did not set up logging.\n","lang":"Python","license":"apache-2.0","repos":"DataONEorg\/d1_python,DataONEorg\/d1_python,DataONEorg\/d1_python,DataONEorg\/d1_python"} {"commit":"af8a96e08029e2dc746cfa1ecbd7a6d02be1c374","old_file":"InvenTree\/company\/forms.py","new_file":"InvenTree\/company\/forms.py","old_contents":"\"\"\"\nDjango Forms for interacting with Company app\n\"\"\"\n\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom InvenTree.forms import HelperForm\n\nfrom .models import Company\nfrom .models import SupplierPart\nfrom .models import SupplierPriceBreak\n\n\nclass EditCompanyForm(HelperForm):\n \"\"\" Form for editing a Company object \"\"\"\n\n class Meta:\n model = Company\n fields = [\n 'name',\n 'description',\n 'website',\n 'address',\n 'phone',\n 'email',\n 'contact',\n 'is_customer',\n 'is_supplier',\n 'notes'\n ]\n\n\nclass CompanyImageForm(HelperForm):\n \"\"\" Form for uploading a Company image \"\"\"\n\n class Meta:\n model = Company\n fields = [\n 'image'\n ]\n\n\nclass EditSupplierPartForm(HelperForm):\n \"\"\" Form for editing a SupplierPart object \"\"\"\n\n class Meta:\n model = SupplierPart\n fields = [\n 'part',\n 'supplier',\n 'SKU',\n 'description',\n 'manufacturer',\n 'MPN',\n 'URL',\n 'note',\n 'base_cost',\n 'multiple',\n 'packaging',\n 'lead_time'\n ]\n\n\nclass EditPriceBreakForm(HelperForm):\n \"\"\" Form for creating \/ editing a supplier price break \"\"\"\n\n class Meta:\n model = SupplierPriceBreak\n fields = [\n 'part',\n 'quantity',\n 'cost'\n ]\n","new_contents":"\"\"\"\nDjango Forms for interacting with Company app\n\"\"\"\n\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom InvenTree.forms import HelperForm\n\nfrom .models import Company\nfrom .models import SupplierPart\nfrom .models import SupplierPriceBreak\n\n\nclass EditCompanyForm(HelperForm):\n \"\"\" Form for editing a Company object \"\"\"\n\n class Meta:\n model = Company\n fields = [\n 'name',\n 'description',\n 'website',\n 'address',\n 'phone',\n 'email',\n 'contact',\n 'is_customer',\n 'is_supplier',\n 'notes'\n ]\n\n\nclass CompanyImageForm(HelperForm):\n \"\"\" Form for uploading a Company image \"\"\"\n\n class Meta:\n model = Company\n fields = [\n 'image'\n ]\n\n\nclass EditSupplierPartForm(HelperForm):\n \"\"\" Form for editing a SupplierPart object \"\"\"\n\n class Meta:\n model = SupplierPart\n fields = [\n 'part',\n 'supplier',\n 'SKU',\n 'description',\n 'manufacturer',\n 'MPN',\n 'URL',\n 'note',\n 'base_cost',\n 'multiple',\n 'packaging',\n 'lead_time'\n ]\n\n\nclass EditPriceBreakForm(HelperForm):\n \"\"\" Form for creating \/ editing a supplier price break \"\"\"\n\n class Meta:\n model = SupplierPriceBreak\n fields = [\n 'part',\n 'quantity',\n 'cost',\n 'currency',\n ]\n","subject":"Add option to edit currency","message":"Add option to edit currency\n","lang":"Python","license":"mit","repos":"SchrodingersGat\/InvenTree,SchrodingersGat\/InvenTree,inventree\/InvenTree,inventree\/InvenTree,SchrodingersGat\/InvenTree,inventree\/InvenTree,SchrodingersGat\/InvenTree,inventree\/InvenTree"} {"commit":"824c46b7d3953e1933a72def4edf058a577487ea","old_file":"byceps\/services\/attendance\/transfer\/models.py","new_file":"byceps\/services\/attendance\/transfer\/models.py","old_contents":"\"\"\"\nbyceps.services.attendance.transfer.models\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n:Copyright: 2006-2019 Jochen Kupperschmidt\n:License: Modified BSD, see LICENSE for details.\n\"\"\"\n\nfrom attr import attrib, attrs\n\nfrom ....services.seating.models.seat import Seat\nfrom ....services.user.models.user import User\n\n\n@attrs(slots=True) # Not yet frozen b\/c models are not immutable.\nclass Attendee:\n user = attrib(type=User)\n seat = attrib(type=Seat)\n checked_in = attrib(type=bool)\n","new_contents":"\"\"\"\nbyceps.services.attendance.transfer.models\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n:Copyright: 2006-2019 Jochen Kupperschmidt\n:License: Modified BSD, see LICENSE for details.\n\"\"\"\n\nfrom dataclasses import dataclass\n\nfrom ....services.seating.models.seat import Seat\nfrom ....services.user.models.user import User\n\n\n@dataclass # Not yet frozen b\/c models are not immutable.\nclass Attendee:\n user: User\n seat: Seat\n checked_in: bool\n","subject":"Use `dataclass` instead of `attr` for attendance model","message":"Use `dataclass` instead of `attr` for attendance model\n","lang":"Python","license":"bsd-3-clause","repos":"m-ober\/byceps,homeworkprod\/byceps,homeworkprod\/byceps,m-ober\/byceps,m-ober\/byceps,homeworkprod\/byceps"} {"commit":"7d52ee6030b2e59a6b6cb6dce78686e8d551281b","old_file":"examples\/horizontal_boxplot.py","new_file":"examples\/horizontal_boxplot.py","old_contents":"\"\"\"\nHorizontal boxplot with observations\n====================================\n\n_thumb: .7, .37\n\"\"\"\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set(style=\"ticks\")\n\n# Initialize the figure\nf, ax = plt.subplots(figsize=(7, 6))\nax.set_xscale(\"log\")\n\n# Load the example planets dataset\nplanets = sns.load_dataset(\"planets\")\n\n# Plot the orbital period with horizontal boxes\nsns.boxplot(x=\"distance\", y=\"method\", data=planets,\n whis=np.inf, palette=\"vlag\")\n\n# Add in points to show each observation\nsns.swarmplot(x=\"distance\", y=\"method\", data=planets,\n size=2, color=\".3\", linewidth=0)\n\n\n# Make the quantitative axis logarithmic\nax.xaxis.grid(True)\nax.set(ylabel=\"\")\nsns.despine(trim=True, left=True)\n","new_contents":"\"\"\"\nHorizontal boxplot with observations\n====================================\n\n_thumb: .7, .37\n\"\"\"\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nsns.set(style=\"ticks\")\n\n# Initialize the figure with a logarithmic x axis\nf, ax = plt.subplots(figsize=(7, 6))\nax.set_xscale(\"log\")\n\n# Load the example planets dataset\nplanets = sns.load_dataset(\"planets\")\n\n# Plot the orbital period with horizontal boxes\nsns.boxplot(x=\"distance\", y=\"method\", data=planets,\n whis=np.inf, palette=\"vlag\")\n\n# Add in points to show each observation\nsns.swarmplot(x=\"distance\", y=\"method\", data=planets,\n size=2, color=\".3\", linewidth=0)\n\n# Tweak the visual presentation\nax.xaxis.grid(True)\nax.set(ylabel=\"\")\nsns.despine(trim=True, left=True)\n","subject":"Fix comments in horizontal boxplot example","message":"Fix comments in horizontal boxplot example\n","lang":"Python","license":"bsd-3-clause","repos":"mwaskom\/seaborn,phobson\/seaborn,arokem\/seaborn,lukauskas\/seaborn,anntzer\/seaborn,arokem\/seaborn,sauliusl\/seaborn,mwaskom\/seaborn,phobson\/seaborn,petebachant\/seaborn,anntzer\/seaborn,lukauskas\/seaborn"} {"commit":"7bc23b277e53bb1c826dc6af7296b688ba9a97f1","old_file":"blimp_boards\/users\/urls.py","new_file":"blimp_boards\/users\/urls.py","old_contents":"from django.conf.urls import patterns, url\n\nfrom . import views\n\napi_urlpatterns = patterns(\n # Prefix\n '',\n\n (r'auth\/signin\/$', views.SigninAPIView.as_view()),\n (r'auth\/signup\/$', views.SignupAPIView.as_view()),\n (r'auth\/username\/validate\/$', views.ValidateUsernameAPIView.as_view()),\n\n (r'auth\/forgot_password\/$', views.ForgotPasswordAPIView.as_view()),\n (r'auth\/reset_password\/$', views.ResetPasswordAPIView.as_view()),\n\n (r'users\/me\/$', views.UserSettingsAPIView.as_view()),\n (r'users\/me\/change_password\/$', views.ChangePasswordAPIView.as_view()),\n)\n\nurlpatterns = patterns(\n # Prefix\n '',\n\n url(r'signin\/$',\n views.SigninValidateTokenHTMLView.as_view(),\n name='auth-signin'),\n\n url(r'signup\/$',\n views.SignupValidateTokenHTMLView.as_view(),\n name='auth-signup'),\n\n url(r'reset_password\/$',\n views.ResetPasswordHTMLView.as_view(),\n name='auth-reset-password'),\n)\n","new_contents":"from django.conf.urls import patterns, url\n\nfrom . import views\n\napi_urlpatterns = patterns(\n # Prefix\n '',\n\n (r'auth\/signin\/$', views.SigninAPIView.as_view()),\n (r'auth\/signup\/$', views.SignupAPIView.as_view()),\n (r'auth\/username\/validate\/$', views.ValidateUsernameAPIView.as_view()),\n\n (r'auth\/forgot_password\/$', views.ForgotPasswordAPIView.as_view()),\n (r'auth\/reset_password\/$', views.ResetPasswordAPIView.as_view()),\n\n (r'users\/me\/$', views.UserSettingsAPIView.as_view()),\n (r'users\/me\/change_password\/$', views.ChangePasswordAPIView.as_view()),\n)\n\nurlpatterns = patterns(\n # Prefix\n '',\n\n url(r'signin\/$',\n views.SigninValidateTokenHTMLView.as_view(),\n name='auth-signin'),\n\n url(r'signup\/',\n views.SignupValidateTokenHTMLView.as_view(),\n name='auth-signup'),\n\n url(r'reset_password\/$',\n views.ResetPasswordHTMLView.as_view(),\n name='auth-reset-password'),\n)\n","subject":"Change to signup url to allow steps","message":"Change to signup url to allow steps","lang":"Python","license":"agpl-3.0","repos":"GetBlimp\/boards-backend,jessamynsmith\/boards-backend,jessamynsmith\/boards-backend"} {"commit":"582c0e22c2d91b11a667933532b0a802757b26f6","old_file":"templates\/dns_param_template.py","new_file":"templates\/dns_param_template.py","old_contents":"import string\n\ntemplate = string.Template(\"\"\"#\n# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.\n#\n# DNS configuration options\n#\n\n[DEFAULT]\n# dns_config_file=dns_config.xml\n hostip=$__contrail_host_ip__ # Resolved IP of `hostname`\n hostname=$__contrail_hostname__ # Retrieved as `hostname`\n# http_server_port=8092\n# log_category=\n# log_disable=0\n log_file=\/var\/log\/contrail\/dns.log\n# log_files_count=10\n# log_file_size=10485760 # 10MB\n# log_level=SYS_NOTICE\n# log_local=0\n# test_mode=0\n\n[COLLECTOR]\n# port=8086\n# server= # Provided by discovery server\n\n[DISCOVERY]\n# port=5998\n server=$__contrail_discovery_ip__ # discovery-server IP address\n\n[IFMAP]\n certs_store=$__contrail_cert_ops__\n password=$__contrail_ifmap_paswd__\n# server_url= # Provided by discovery server, e.g. https:\/\/127.0.0.1:8443\n user=$__contrail_ifmap_usr__\n\n\"\"\")\n","new_contents":"import string\n\ntemplate = string.Template(\"\"\"#\n# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.\n#\n# DNS configuration options\n#\n\n[DEFAULT]\n# dns_config_file=dns_config.xml\n hostip=$__contrail_host_ip__ # Resolved IP of `hostname`\n hostname=$__contrail_hostname__ # Retrieved as `hostname`\n# http_server_port=8092\n# log_category=\n# log_disable=0\n log_file=\/var\/log\/contrail\/dns.log\n# log_files_count=10\n# log_file_size=1048576 # 1MB\n# log_level=SYS_NOTICE\n# log_local=0\n# test_mode=0\n\n[COLLECTOR]\n# port=8086\n# server= # Provided by discovery server\n\n[DISCOVERY]\n# port=5998\n server=$__contrail_discovery_ip__ # discovery-server IP address\n\n[IFMAP]\n certs_store=$__contrail_cert_ops__\n password=$__contrail_ifmap_paswd__\n# server_url= # Provided by discovery server, e.g. https:\/\/127.0.0.1:8443\n user=$__contrail_ifmap_usr__\n\n\"\"\")\n","subject":"Change log file size to 1MB","message":"Change log file size to 1MB\n","lang":"Python","license":"apache-2.0","repos":"Juniper\/contrail-provisioning,Juniper\/contrail-provisioning"} {"commit":"ca4be3892ec0c1b5bc337a9fae10503b5f7f765a","old_file":"bika\/lims\/browser\/validation.py","new_file":"bika\/lims\/browser\/validation.py","old_contents":"from Products.Archetypes.browser.validation import InlineValidationView as _IVV\nfrom Acquisition import aq_inner\nfrom Products.CMFCore.utils import getToolByName\nimport json\n\n\nSKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference')\n\nclass InlineValidationView(_IVV):\n\n def __call__(self, uid, fname, value):\n '''Validate a given field. Return any error messages.\n '''\n res = {'errmsg': ''}\n\n if value not in self.request:\n return json.dumps(res)\n\n rc = getToolByName(aq_inner(self.context), 'reference_catalog')\n instance = rc.lookupObject(uid)\n # make sure this works for portal_factory items\n if instance is None:\n instance = self.context\n\n field = instance.getField(fname)\n if field and field.type not in SKIP_VALIDATION_FIELDTYPES:\n return super(InlineValidationView, self).__call__(uid, fname, value)\n\n self.request.response.setHeader('Content-Type', 'application\/json')\n return json.dumps(res)\n","new_contents":"from Products.Archetypes.browser.validation import InlineValidationView as _IVV\nfrom Acquisition import aq_inner\nfrom Products.CMFCore.utils import getToolByName\nimport json\n\n\nSKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference')\n\nclass InlineValidationView(_IVV):\n\n def __call__(self, uid, fname, value):\n '''Validate a given field. Return any error messages.\n '''\n res = {'errmsg': ''}\n\n rc = getToolByName(aq_inner(self.context), 'reference_catalog')\n instance = rc.lookupObject(uid)\n # make sure this works for portal_factory items\n if instance is None:\n instance = self.context\n\n field = instance.getField(fname)\n if field and field.type not in SKIP_VALIDATION_FIELDTYPES:\n return super(InlineValidationView, self).__call__(uid, fname, value)\n\n self.request.response.setHeader('Content-Type', 'application\/json')\n return json.dumps(res)\n","subject":"Revert \"Inline Validation fails silently if request is malformed\"","message":"Revert \"Inline Validation fails silently if request is malformed\"\n\nThis reverts commit 723e4eb603568d3a60190d8d292cc335a74b79d5.\n","lang":"Python","license":"agpl-3.0","repos":"labsanmartin\/Bika-LIMS,veroc\/Bika-LIMS,veroc\/Bika-LIMS,rockfruit\/bika.lims,veroc\/Bika-LIMS,labsanmartin\/Bika-LIMS,anneline\/Bika-LIMS,DeBortoliWines\/Bika-LIMS,DeBortoliWines\/Bika-LIMS,anneline\/Bika-LIMS,DeBortoliWines\/Bika-LIMS,anneline\/Bika-LIMS,rockfruit\/bika.lims,labsanmartin\/Bika-LIMS"} {"commit":"fb58117527c486401d07e046077151d3217e576f","old_file":"python\/copy-market-report.py","new_file":"python\/copy-market-report.py","old_contents":"import yaml\nfrom time import gmtime, strftime\nfrom shutil import copy\n\nwith open('..\/config\/betfair_config.yml', 'r') as f:\n doc = yaml.load(f)\n\ndata_dir = doc['default']['betfair']['data_dir']\ntodays_date = strftime('%Y-%-m-%d', gmtime())\n\nsrc='\/tmp\/market-report.pdf'\ndest=data_dir + '\/data\/' + todays_date + '\/market-report.pdf'\n\npng_src='\/tmp\/distance-and-runners-scatter.png'\npng_dest=data_dir + '\/data\/' + todays_date + '\/distance-and-runners-scatter.png'\n\ncopy(src,dest)\ncopy(png_src,png_dest)\n","new_contents":"import yaml\nfrom time import gmtime, strftime\nfrom shutil import copy\n\nwith open('..\/config\/betfair_config.yml', 'r') as f:\n doc = yaml.load(f)\n\ndata_dir = doc['default']['betfair']['data_dir']\ntodays_date = strftime('%Y-%-m-%-d', gmtime())\n\nsrc='\/tmp\/market-report.pdf'\ndest=data_dir + '\/data\/' + todays_date + '\/market-report.pdf'\n\npng_src='\/tmp\/distance-and-runners-scatter.png'\npng_dest=data_dir + '\/data\/' + todays_date + '\/distance-and-runners-scatter.png'\n\ncopy(src,dest)\ncopy(png_src,png_dest)\n","subject":"Fix bug reading filenames for days with 1 number","message":"Fix bug reading filenames for days with 1 number\n","lang":"Python","license":"apache-2.0","repos":"cranburyattic\/bf-app,cranburyattic\/bf-app,cranburyattic\/bf-app,cranburyattic\/bf-app"} {"commit":"6949339cda8c60b74341f854d9a00aa8abbfe4d5","old_file":"test\/level_sets_measure_test.py","new_file":"test\/level_sets_measure_test.py","old_contents":"__author__ = 'intsco'\n\nimport cPickle\nfrom engine.pyIMS.image_measures.level_sets_measure import measure_of_chaos_dict\nfrom unittest import TestCase\nimport unittest\nfrom os.path import join, realpath, dirname\n\n\nclass MeasureOfChaosDictTest(TestCase):\n\n def setUp(self):\n self.rows, self.cols = 65, 65\n self.input_fn = join(dirname(realpath(__file__)), 'data\/measure_of_chaos_dict_test_input.pkl')\n with open(self.input_fn) as f:\n self.input_data = cPickle.load(f)\n\n def testMOCBoundaries(self):\n for img_d in self.input_data:\n if len(img_d) > 0:\n assert 0 <= measure_of_chaos_dict(img_d, self.rows, self.cols) <= 1\n\n def testEmptyInput(self):\n # print measure_of_chaos_dict({}, self.cols, self.cols)\n self.assertRaises(Exception, measure_of_chaos_dict, {}, self.cols, self.cols)\n self.assertRaises(Exception, measure_of_chaos_dict, None, self.cols, self.cols)\n self.assertRaises(Exception, measure_of_chaos_dict, (), self.cols, self.cols)\n self.assertRaises(Exception, measure_of_chaos_dict, [], self.cols, self.cols)\n\n def testMaxInputDictKeyVal(self):\n max_key_val = self.rows * self.cols - 1\n self.assertRaises(Exception, measure_of_chaos_dict, {max_key_val + 10: 1}, self.rows, self.cols)\n\n\nif __name__ == '__main__':\n unittest.main()\n","new_contents":"import unittest\n\nimport numpy as np\n\nfrom ..image_measures.level_sets_measure import measure_of_chaos, _nan_to_zero\n\n\nclass MeasureOfChaosTest(unittest.TestCase):\n def test__nan_to_zero_with_ge_zero(self):\n ids = (\n np.zeros(1),\n np.ones(range(1, 10)),\n np.arange(1024 * 1024)\n )\n for id_ in ids:\n before = id_.copy()\n _nan_to_zero(id_)\n np.testing.assert_array_equal(before, id_)\n\n def test__nan_to_zero_with_negatives(self):\n negs = (\n np.array([-1]),\n -np.arange(1, 1024 * 1024 + 1).reshape((1024, 1024)),\n np.linspace(0, -20, 201)\n )\n for neg in negs:\n sh = neg.shape\n _nan_to_zero(neg)\n np.testing.assert_array_equal(neg, np.zeros(sh))\n\nif __name__ == '__main__':\n unittest.main()\n","subject":"Implement first tests for _nan_to_zero","message":"Implement first tests for _nan_to_zero\n\n- Remove outdated dict test class\n- write some test methods\n","lang":"Python","license":"apache-2.0","repos":"andy-d-palmer\/pyIMS,alexandrovteam\/pyImagingMSpec"} {"commit":"12f4b26d98c3ba765a11efeca3b646b5e9d0a0fb","old_file":"running.py","new_file":"running.py","old_contents":"import tcxparser\nfrom configparser import ConfigParser\nfrom datetime import datetime\nimport urllib.request\nimport dateutil.parser\n\nt = '1984-06-02T19:05:00.000Z'\n# Darksky weather API\n# Create config file manually\nparser = ConfigParser()\nparser.read('slowburn.config', encoding='utf-8')\ndarksky_key = parser.get('darksky', 'key')\n\ntcx = tcxparser.TCXParser('gps_logs\/2017-06-15_Running.tcx')\nrun_time = tcx.completed_at\n\ndef convert_time_to_unix(time):\n parsed_time = dateutil.parser.parse(time)\n time_in_unix = parsed_time.strftime('%s')\n return time_in_unix\n\nunix_run_time = convert_time_to_unix(run_time)\ndarksky_request = urllib.request.urlopen(\"https:\/\/api.darksky.net\/forecast\/\" + darksky_key + \"\/42.3601,-71.0589,\" + unix_run_time + \"?exclude=currently,flags\").read()\nprint(darksky_request)\n\n\nclass getWeather:\n def __init__(self, date, time):\n self.date = date\n self.time = time\n\n def goodbye(self, date):\n print(\"my name is \" + date)\n","new_contents":"import tcxparser\nfrom configparser import ConfigParser\nfrom datetime import datetime\nimport urllib.request\nimport dateutil.parser\n\nt = '1984-06-02T19:05:00.000Z'\n# Darksky weather API\n# Create config file manually\nparser = ConfigParser()\nparser.read('slowburn.config', encoding='utf-8')\ndarksky_key = parser.get('darksky', 'key')\n\ntcx = tcxparser.TCXParser('gps_logs\/2017-06-15_Running.tcx')\nrun_time = tcx.completed_at\n\ndef convert_time_to_unix(time):\n parsed_time = dateutil.parser.parse(time)\n time_in_unix = parsed_time.strftime('%s')\n return time_in_unix\n\nunix_run_time = convert_time_to_unix(run_time)\ndarksky_request = urllib.request.urlopen(\"https:\/\/api.darksky.net\/forecast\/\" + darksky_key + \"\/\" + str(tcx.latitude) + \",\" + str(tcx.longitude) + \",\" + unix_run_time + \"?exclude=currently,flags\").read()\nprint(darksky_request)\n\nclass getWeather:\n def __init__(self, date, time):\n self.date = date\n self.time = time\n\n def goodbye(self, date):\n print(\"my name is \" + date)\n","subject":"Use TCX coordinates to fetch local weather","message":"Use TCX coordinates to fetch local weather\n","lang":"Python","license":"mit","repos":"briansuhr\/slowburn"} {"commit":"5a7b13e26e94d03bc92600d9c24b3b2e8bc4321c","old_file":"dstar_lib\/aprsis.py","new_file":"dstar_lib\/aprsis.py","old_contents":"import aprslib\nimport logging\n\nimport nmea\n\nclass AprsIS:\n\n\tlogger = None\n\n\tdef __init__(self, callsign, password):\n\t\tself.logger = logging.getLogger(__name__)\n\t\tself.aprs_connection = aprslib.IS(callsign, password)\n\t\tself.aprs_connection.connect()\n\n\tdef send_beacon(self, callsign, sfx, message, gpgga):\n\t\tposition = nmea.gpgga_get_position(gpgga)\n\t\taprs_frame = callsign+'>APK'+sfx+',DSTAR*:!'+position['lat'] + position['lat_coord'] + '\\\\'+position['long']+position['long_coord']+'a\/A=' + position['height'] + message\n\t\tself.logger.info(\"Sending APRS Frame: \" + aprs_frame)\n\t\ttry:\n\t\t\tself.aprs_connection.sendall(aprs.Frame(aprs_frame))\n\t\texcept:\n\t\t\tself.logger.info(\"Invalid aprs frame: \" + aprs_frame)\n","new_contents":"import aprslib\nimport logging\n\nimport nmea\n\nclass AprsIS:\n\n\tlogger = None\n\n\tdef __init__(self, callsign, password):\n\t\tself.logger = logging.getLogger(__name__)\n\t\tself.aprs_connection = aprslib.IS(callsign, password)\n\t\tself.aprs_connection.connect()\n\n\tdef send_beacon(self, callsign, sfx, message, gpgga):\n\t\tposition = nmea.gpgga_get_position(gpgga)\n\t\taprs_frame = callsign+'>APK'+sfx+',DSTAR*:!'+position['lat'] + position['lat_coord'] + '\\\\'+position['long']+position['long_coord']+'a\/A=' + position['height'] + message\n\t\tself.logger.info(\"Sending APRS Frame: \" + aprs_frame)\n\t\ttry:\n\t\t\tself.aprs_connection.sendall(aprs_frame)\n\t\t\tself.logger.info(\"APRS Beacon sent!\")\n\t\texcept Exception, e:\n\t\t\tself.logger.info(\"Invalid aprs frame [%s] - %s\" % (aprs_frame, str(e))\n","subject":"Fix an issue with the new aprslib","message":"Fix an issue with the new aprslib\n","lang":"Python","license":"mit","repos":"elielsardanons\/dstar_sniffer,elielsardanons\/dstar_sniffer"} {"commit":"132b148ca8701ee867b7a08432a3595a213ce470","old_file":"cedexis\/radar\/tests\/test_cli.py","new_file":"cedexis\/radar\/tests\/test_cli.py","old_contents":"import unittest\nimport types\n\nimport cedexis.radar.cli\n\nclass TestCommandLineInterface(unittest.TestCase):\n\n def test_main(self):\n self.assertTrue(isinstance(cedexis.radar.cli.main, types.FunctionType))\n","new_contents":"import unittest\nfrom unittest.mock import patch, MagicMock, call\nimport types\nfrom pprint import pprint\n\nimport cedexis.radar.cli\n\nclass TestCommandLineInterface(unittest.TestCase):\n\n def test_main(self):\n self.assertTrue(isinstance(cedexis.radar.cli.main, types.FunctionType))\n\n @patch('logging.getLogger')\n @patch('argparse.ArgumentParser')\n @patch('cedexis.radar.run_session')\n @patch('time.sleep')\n def test_config_file_with_cli_params(self, mock_sleep, mock_run_session,\n mock_ArgumentParser, mock_getLogger):\n args = make_default_args()\n args.continuous = True\n args.max_runs = 3\n args.repeat_delay = 60\n mock_parser = MagicMock()\n mock_parser.parse_args.return_value = args\n mock_ArgumentParser.return_value = mock_parser\n cedexis.radar.cli.main()\n\n # Assert\n # print(mock_run_session.call_args)\n self.assertEqual(\n mock_run_session.call_args_list,\n [\n call(1, 12345, 'sandbox', False, None, None, False, None),\n call(1, 12345, 'sandbox', False, None, None, False, None),\n call(1, 12345, 'sandbox', False, None, None, False, None)\n ])\n # print(mock_sleep.call_args)\n self.assertEqual(mock_sleep.call_args_list, [call(60),call(60)])\n\ndef make_default_args():\n args = lambda: None\n args.zone_id = 1\n args.customer_id = 12345\n args.api_key = 'sandbox'\n args.secure = False\n args.config_file = 'some config file path'\n args.tracer = None\n args.provider_id = None\n args.report_server = None\n args.max_runs = None\n args.repeat_delay = None\n return args\n","subject":"Add unit test for overrides","message":"Add unit test for overrides\n","lang":"Python","license":"mit","repos":"cedexis\/cedexis.radar"} {"commit":"70f167d3d5a7540fb3521b82ec70bf7c6db09a99","old_file":"tests\/test_contrib.py","new_file":"tests\/test_contrib.py","old_contents":"from __future__ import print_function\n\nimport cooler.contrib.higlass as cch\nimport h5py\nimport os.path as op\n\ntestdir = op.realpath(op.dirname(__file__))\n\ndef test_data_retrieval():\n data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')\n \n f = h5py.File(data_file, 'r')\n \n data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)\n\n assert(data['genome_start1'].iloc[0] == 0.)\n assert(data['genome_start2'].iloc[0] == 0.)\n\n data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)\n\n assert(data['genome_start1'].iloc[-1] > 255000000)\n assert(data['genome_start1'].iloc[-1] < 256000000)\n #print(\"ge1\", data['genome_end1'])\n","new_contents":"from __future__ import print_function\n\nimport cooler.contrib.higlass as cch\nimport cooler.contrib.recursive_agg_onefile as ra\nimport h5py\nimport os.path as op\n\ntestdir = op.realpath(op.dirname(__file__))\n\ndef test_data_retrieval():\n data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')\n \n f = h5py.File(data_file, 'r')\n \n data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)\n\n assert(data['genome_start1'].iloc[0] == 0.)\n assert(data['genome_start2'].iloc[0] == 0.)\n\n data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)\n\n assert(data['genome_start1'].iloc[-1] > 255000000)\n assert(data['genome_start1'].iloc[-1] < 256000000)\n #print(\"ge1\", data['genome_end1'])\n\n\ndef test_recursive_agg():\n infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool')\n outfile = '\/tmp\/bla.cool'\n chunksize = int(10e6)\n n_zooms = 2\n n_cpus = 8\n ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus)\n ra.balance(outfile, n_zooms, chunksize, n_cpus)","subject":"Add test for recursive agg","message":"Add test for recursive agg\n","lang":"Python","license":"bsd-3-clause","repos":"mirnylab\/cooler"} {"commit":"27a0165d45f52114ebb65d59cf8e4f84f3232881","old_file":"tests\/test_lattice.py","new_file":"tests\/test_lattice.py","old_contents":"import rml.lattice\n\ndef test_create_lattice():\n l = rml.lattice.Lattice()\n assert(len(l)) == 0\n\ndef test_non_negative_lattice():\n l = rml.lattice.Lattice()\n assert(len(l)) >= 0\n","new_contents":"import rml.lattice\nimport rml.element\n\ndef test_create_lattice():\n l = rml.lattice.Lattice()\n assert(len(l)) == 0\n\n\ndef test_non_negative_lattice():\n l = rml.lattice.Lattice()\n assert(len(l)) >= 0\n\n\ndef test_lattice_with_one_element():\n l = rml.lattice.Lattice()\n element_length = 1.5\n e = rml.element.Element('dummy', element_length)\n l.append_element(e)\n # There is one element in the lattice.\n assert(len(l) == 1)\n # The total length of the lattice is the same as its one element.\n assert l.length() = element_length\n\n","subject":"Test simple lattice with one element.","message":"Test simple lattice with one element.\n","lang":"Python","license":"apache-2.0","repos":"willrogers\/pml,willrogers\/pml,razvanvasile\/RML"} {"commit":"7591189527ad05be62a561afadf70b217d725b1f","old_file":"scrapi\/processing\/osf\/__init__.py","new_file":"scrapi\/processing\/osf\/__init__.py","old_contents":"from scrapi.processing.osf import crud\nfrom scrapi.processing.osf import collision\nfrom scrapi.processing.base import BaseProcessor\n\n\nclass OSFProcessor(BaseProcessor):\n NAME = 'osf'\n\n def process_normalized(self, raw_doc, normalized):\n if crud.is_event(normalized):\n crud.create_event(normalized)\n return\n\n report_hash = collision.generate_report_hash_list(normalized)\n resource_hash = collision.generate_resource_hash_list(normalized)\n\n report = collision.detect_collisions(report_hash)\n resource = collision.detect_collisions(resource_hash)\n\n if not resource:\n resource = crud.create_resource(normalized, resource_hash)\n elif not crud.is_claimed(resource):\n crud.update_resource(normalized, resource)\n\n if not report:\n crud.create_report(normalized, resource, report_hash)\n else:\n crud.update_report(normalized, report)\n","new_contents":"from scrapi.processing.osf import crud\nfrom scrapi.processing.osf import collision\nfrom scrapi.processing.base import BaseProcessor\n\n\nclass OSFProcessor(BaseProcessor):\n NAME = 'osf'\n\n def process_normalized(self, raw_doc, normalized):\n if crud.is_event(normalized):\n crud.create_event(normalized)\n return\n\n normalized['collisionCategory'] = crud.get_collision_cat(normalized['source'])\n\n report_norm = normalized\n resource_norm = crud.clean_report(normalized)\n\n report_hash = collision.generate_report_hash_list(report_norm)\n resource_hash = collision.generate_resource_hash_list(resource_norm)\n\n report = collision.detect_collisions(report_hash)\n resource = collision.detect_collisions(resource_hash)\n\n if not resource:\n resource = crud.create_resource(resource_norm, resource_hash)\n elif not crud.is_claimed(resource):\n crud.update_resource(resource_norm, resource)\n\n if not report:\n crud.create_report(report_norm, resource, report_hash)\n else:\n crud.update_report(report_norm, report)\n","subject":"Make sure to keep certain report fields out of resources","message":"Make sure to keep certain report fields out of resources\n","lang":"Python","license":"apache-2.0","repos":"alexgarciac\/scrapi,erinspace\/scrapi,icereval\/scrapi,mehanig\/scrapi,felliott\/scrapi,erinspace\/scrapi,CenterForOpenScience\/scrapi,fabianvf\/scrapi,mehanig\/scrapi,ostwald\/scrapi,fabianvf\/scrapi,CenterForOpenScience\/scrapi,felliott\/scrapi,jeffreyliu3230\/scrapi"} {"commit":"3fe86c259e6015ca535510bd692cc26d5d4e64cc","old_file":"bin\/license_finder_pip.py","new_file":"bin\/license_finder_pip.py","old_contents":"#!\/usr\/bin\/env python\n\nimport json\nfrom pip.req import parse_requirements\nfrom pip.download import PipSession\nfrom pip._vendor import pkg_resources\nfrom pip._vendor.six import print_\n\nrequirements = [pkg_resources.Requirement(str(req.req)) for req\n in parse_requirements('requirements.txt', session=PipSession())]\n\ntransform = lambda dist: {\n 'name': dist.project_name,\n 'version': dist.version,\n 'location': dist.location,\n 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())),\n }\n\npackages = [transform(dist) for dist\n in pkg_resources.working_set.resolve(requirements)]\n\nprint_(json.dumps(packages))\n","new_contents":"#!\/usr\/bin\/env python\n\nimport json\nfrom pip.req import parse_requirements\nfrom pip.download import PipSession\nfrom pip._vendor import pkg_resources\nfrom pip._vendor.six import print_\n\nrequirements = [pkg_resources.Requirement.parse(str(req.req)) for req\n in parse_requirements('requirements.txt', session=PipSession())]\n\ntransform = lambda dist: {\n 'name': dist.project_name,\n 'version': dist.version,\n 'location': dist.location,\n 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())),\n }\n\npackages = [transform(dist) for dist\n in pkg_resources.working_set.resolve(requirements)]\n\nprint_(json.dumps(packages))\n","subject":"Use parse() method to instantiate Requirement","message":"Use parse() method to instantiate Requirement\n\n[Fix #224]\n\nSigned-off-by: Tony Wong <3261da024e85c36767bb9324ced93ba4333a2c77@pivotal.io>\n","lang":"Python","license":"mit","repos":"bspeck\/LicenseFinder,sschuberth\/LicenseFinder,bdshroyer\/LicenseFinder,bdshroyer\/LicenseFinder,bspeck\/LicenseFinder,bdshroyer\/LicenseFinder,tinfoil\/LicenseFinder,tinfoil\/LicenseFinder,bspeck\/LicenseFinder,pivotal\/LicenseFinder,bdshroyer\/LicenseFinder,bspeck\/LicenseFinder,sschuberth\/LicenseFinder,bspeck\/LicenseFinder,pivotal\/LicenseFinder,tinfoil\/LicenseFinder,bdshroyer\/LicenseFinder,pivotal\/LicenseFinder,sschuberth\/LicenseFinder,pivotal\/LicenseFinder,tinfoil\/LicenseFinder,sschuberth\/LicenseFinder,pivotal\/LicenseFinder,pivotal\/LicenseFinder,sschuberth\/LicenseFinder,tinfoil\/LicenseFinder,pivotal\/LicenseFinder"} {"commit":"166e0980fc20b507763395297e8a67c7dcb3a3da","old_file":"examples\/neural_network_inference\/onnx_converter\/small_example.py","new_file":"examples\/neural_network_inference\/onnx_converter\/small_example.py","old_contents":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom onnx_coreml import convert\n\n# Step 0 - (a) Define ML Model\nclass small_model(nn.Module):\n def __init__(self):\n super(small_model, self).__init__()\n self.fc1 = nn.Linear(768, 256)\n self.fc2 = nn.Linear(256, 10)\n\n def forward(self, x):\n y = F.relu(self.fc1(x))\n y = F.softmax(self.fc2(y))\n return y\n\n# Step 0 - (b) Create model or Load from dist\nmodel = small_model()\ndummy_input = torch.randn(768)\n\n# Step 1 - PyTorch to ONNX model\ntorch.onnx.export(model, dummy_input, '.\/small_model.onnx')\n\n# Step 2 - ONNX to CoreML model\nmlmodel = convert(model='.\/small_model.onnx', target_ios='13')\n# Save converted CoreML model\nmlmodel.save('small_model.mlmodel')\n","new_contents":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom onnx_coreml import convert\n\n# Step 0 - (a) Define ML Model\nclass small_model(nn.Module):\n def __init__(self):\n super(small_model, self).__init__()\n self.fc1 = nn.Linear(768, 256)\n self.fc2 = nn.Linear(256, 10)\n\n def forward(self, x):\n y = F.relu(self.fc1(x))\n y = F.softmax(self.fc2(y))\n return y\n\n# Step 0 - (b) Create model or Load from dist\nmodel = small_model()\ndummy_input = torch.randn(768)\n\n# Step 1 - PyTorch to ONNX model\ntorch.onnx.export(model, dummy_input, '.\/small_model.onnx')\n\n# Step 2 - ONNX to CoreML model\nmlmodel = convert(model='.\/small_model.onnx', minimum_ios_deployment_target='13')\n# Save converted CoreML model\nmlmodel.save('small_model.mlmodel')\n","subject":"Update the example with latest interface","message":"Update the example with latest interface\n\nUpdate the example with the latest interface of the function \"convert\"","lang":"Python","license":"bsd-3-clause","repos":"apple\/coremltools,apple\/coremltools,apple\/coremltools,apple\/coremltools"} {"commit":"967ea6b083437cbe6c87b173567981e1ae41fefc","old_file":"project\/wsgi\/tomodev.py","new_file":"project\/wsgi\/tomodev.py","old_contents":"\"\"\"\nWSGI config for project.\n\nThis module contains the WSGI application used by Django's development server\nand any production WSGI deployments. It should expose a module-level variable\nnamed ``application``. Django's ``runserver`` and ``runfcgi`` commands discover\nthis application via the ``WSGI_APPLICATION`` setting.\n\nUsually you will have the standard Django WSGI application here, but it also\nmight make sense to replace the whole Django WSGI application with a custom one\nthat later delegates to the Django one. For example, you could introduce WSGI\nmiddleware here, or combine a Django application with an application of another\nframework.\n\n\"\"\"\nimport os\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"project.settings.tomodev\")\n\n# This application object is used by any WSGI server configured to use this\n# file. This includes Django's development server, if the WSGI_APPLICATION\n# setting points here.\nfrom django.core.handlers.wsgi import WSGIHandler\napplication = WSGIHandler()\n\n# Apply WSGI middleware here.\n# from helloworld.wsgi import HelloWorldApplication\n# application = HelloWorldApplication(application)\n","new_contents":"\"\"\"\nWSGI config for project.\n\nThis module contains the WSGI application used by Django's development server\nand any production WSGI deployments. It should expose a module-level variable\nnamed ``application``. Django's ``runserver`` and ``runfcgi`` commands discover\nthis application via the ``WSGI_APPLICATION`` setting.\n\nUsually you will have the standard Django WSGI application here, but it also\nmight make sense to replace the whole Django WSGI application with a custom one\nthat later delegates to the Django one. For example, you could introduce WSGI\nmiddleware here, or combine a Django application with an application of another\nframework.\n\n\"\"\"\nimport os\nimport site\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"project.settings.tomodev\")\n\nbase_path = os.path.abspath(\"..\/..\")\nsite.addsitedir(base_path)\nsite.addsitedir(os.path.join(base_path, 'virtualenv\/lib\/python2.6\/site-packages'))\n\n# This application object is used by any WSGI server configured to use this\n# file. This includes Django's development server, if the WSGI_APPLICATION\n# setting points here.\nfrom django.core.handlers.wsgi import WSGIHandler\napplication = WSGIHandler()\n\n# Apply WSGI middleware here.\n# from helloworld.wsgi import HelloWorldApplication\n# application = HelloWorldApplication(application)\n","subject":"Set Python path inside WSGI application","message":"Set Python path inside WSGI application","lang":"Python","license":"agpl-3.0","repos":"ul-fmf\/projekt-tomo,ul-fmf\/projekt-tomo,matijapretnar\/projekt-tomo,ul-fmf\/projekt-tomo,matijapretnar\/projekt-tomo,ul-fmf\/projekt-tomo,ul-fmf\/projekt-tomo,ul-fmf\/projekt-tomo,matijapretnar\/projekt-tomo,matijapretnar\/projekt-tomo,matijapretnar\/projekt-tomo"} {"commit":"2198ae847cb257d210c043bb08d52206df749a24","old_file":"Jeeves\/jeeves.py","new_file":"Jeeves\/jeeves.py","old_contents":"import discord\nimport asyncio\nimport random\nimport configparser\nimport json\n\ndef RunBot(config_file):\n config = configparser.ConfigParser()\n config.read(config_file)\n\n client = discord.Client()\n\n @client.event\n async def on_ready():\n print('------')\n print('Logged in as %s (%s)' % (client.user.name, client.user.id))\n print('------')\n\n @client.event\n async def on_message(message):\n if message.channel.id == \"123410749765713920\":\n if message.content.startswith('-knugen'):\n \n await client.send_message(message.channel, random.choice(knugenLinks))\n\n client.run(config['Bot']['token'])\n\nif __name__ == \"__main__\":\n print(\"Please use the start.py script in the root directory instead\")\n","new_contents":"import discord\nimport asyncio\nimport random\nimport configparser\nimport json\n\ndef RunBot(config_file):\n config = configparser.ConfigParser()\n config.read(config_file)\n\n client = discord.Client()\n\n @client.event\n async def on_ready():\n print('------')\n print('Logged in as %s (%s)' % (client.user.name, client.user.id))\n print('------')\n\n @client.event\n async def on_message(message):\n if message.channel.id == \"123410749765713920\":\n if message.content.startswith('-knugen'):\n with open('config\/data.json') as data_file:\n data = json.loads(data_file.read())\n await client.send_message(message.channel, random.choice(data['knugenLinks']))\n\n client.run(config['Bot']['token'])\n\nif __name__ == \"__main__\":\n print(\"Please use the start.py script in the root directory instead\")\n","subject":"Change knugen command to use array in config\/data.json instead of hardcoded array.","message":"Change knugen command to use array in config\/data.json instead of hardcoded array.\n","lang":"Python","license":"mit","repos":"havokoc\/MyManJeeves"} {"commit":"b26200860337d4dba13aeafe7cfb9dff8bf181d0","old_file":"salt\/grains\/nxos.py","new_file":"salt\/grains\/nxos.py","old_contents":"# -*- coding: utf-8 -*-\n'''\nGrains for Cisco NX OS Switches Proxy minions\n\n.. versionadded: Carbon\n\nFor documentation on setting up the nxos proxy minion look in the documentation\nfor :doc:`salt.proxy.nxos<\/ref\/proxy\/all\/salt.proxy.nxos>`.\n'''\n# Import Python Libs\nfrom __future__ import absolute_import\n\n# Import Salt Libs\nimport salt.utils\nimport salt.modules.nxos\n\nimport logging\nlog = logging.getLogger(__name__)\n\n__proxyenabled__ = ['nxos']\n__virtualname__ = 'nxos'\n\n\ndef __virtual__():\n try:\n if salt.utils.is_proxy() and __opts__['proxy']['proxytype'] == 'nxos':\n return __virtualname__\n except KeyError:\n pass\n\n return False\n\n\ndef proxy_functions(proxy=None):\n if proxy is None:\n return {}\n if proxy['nxos.initialized']() is False:\n return {}\n return {'nxos': proxy['nxos.grains']()}\n","new_contents":"# -*- coding: utf-8 -*-\n'''\nGrains for Cisco NX OS Switches Proxy minions\n\n.. versionadded: 2016.11.0\n\nFor documentation on setting up the nxos proxy minion look in the documentation\nfor :doc:`salt.proxy.nxos<\/ref\/proxy\/all\/salt.proxy.nxos>`.\n'''\n# Import Python Libs\nfrom __future__ import absolute_import\n\n# Import Salt Libs\nimport salt.utils\nimport salt.modules.nxos\n\nimport logging\nlog = logging.getLogger(__name__)\n\n__proxyenabled__ = ['nxos']\n__virtualname__ = 'nxos'\n\n\ndef __virtual__():\n try:\n if salt.utils.is_proxy() and __opts__['proxy']['proxytype'] == 'nxos':\n return __virtualname__\n except KeyError:\n pass\n\n return False\n\n\ndef proxy_functions(proxy=None):\n if proxy is None:\n return {}\n if proxy['nxos.initialized']() is False:\n return {}\n return {'nxos': proxy['nxos.grains']()}\n","subject":"Update Carbon versionadded tags to 2016.11.0 in grains\/*","message":"Update Carbon versionadded tags to 2016.11.0 in grains\/*\n","lang":"Python","license":"apache-2.0","repos":"saltstack\/salt,saltstack\/salt,saltstack\/salt,saltstack\/salt,saltstack\/salt"} {"commit":"74728ef66fd13bfd7ad01f930114c2375e752d13","old_file":"examples\/skel.py","new_file":"examples\/skel.py","old_contents":"try:\n import _path\nexcept NameError:\n pass\nimport pygame\nimport spyral\nimport sys\n\nSIZE = (640, 480)\nBG_COLOR = (0, 0, 0)\n\nclass Game(spyral.Scene):\n \"\"\"\n A Scene represents a distinct state of your game. They could be menus,\n different subgames, or any other things which are mostly distinct.\n \n A Scene should define two methods, update and render.\n \"\"\"\n def __init__(self):\n \"\"\"\n The __init__ message for a scene should set up the camera(s) for the\n scene, and other structures which are needed for the scene\n \"\"\"\n spyral.Scene.__init__(self, SIZE)\n \n self.register(\"system.quit\", sys.exit)\n\nprint spyral.widgets\nspyral.widgets.register('Testing', 'a')\nprint spyral.widgets.Testing(1,2,3)\nprint spyral.widgets.TextInputWidget\n\n\nif __name__ == \"__main__\":\n spyral.director.init(SIZE) # the director is the manager for your scenes\n spyral.director.run(scene=Game()) # This will run your game. It will not return.\n","new_contents":"try:\n import _path\nexcept NameError:\n pass\nimport pygame\nimport spyral\nimport sys\n\nSIZE = (640, 480)\nBG_COLOR = (0, 0, 0)\n\nclass Game(spyral.Scene):\n \"\"\"\n A Scene represents a distinct state of your game. They could be menus,\n different subgames, or any other things which are mostly distinct.\n \n A Scene should define two methods, update and render.\n \"\"\"\n def __init__(self):\n \"\"\"\n The __init__ message for a scene should set up the camera(s) for the\n scene, and other structures which are needed for the scene\n \"\"\"\n spyral.Scene.__init__(self, SIZE)\n \n self.register(\"system.quit\", sys.exit)\n\nif __name__ == \"__main__\":\n spyral.director.init(SIZE) # the director is the manager for your scenes\n spyral.director.run(scene=Game()) # This will run your game. It will not return.\n","subject":"Remove some accidentally committed code.","message":"Remove some accidentally committed code.\n","lang":"Python","license":"lgpl-2.1","repos":"platipy\/spyral"} {"commit":"b881247b182a45774ed494146904dcf2b1826d5e","old_file":"sla_bot.py","new_file":"sla_bot.py","old_contents":"import discord\nimport asyncio\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print('------')\n\n@client.event\nasync def on_message(message):\n if message.content.startswith('!test'):\n await client.send_message(message.channel, 'Hello world!')\n\nclient.run('paste_token_here')","new_contents":"import asyncio\n\nimport discord\nfrom discord.ext import commands\n\n\n\nbot = commands.Bot(command_prefix='!', description='test')\n\n@bot.event\nasync def on_ready():\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print('------')\n \n@bot.command()\nasync def test():\n await bot.say('Hello World!')\n\nbot.run('paste_token_here')\n","subject":"Switch to Bot object instead of Client","message":"Switch to Bot object instead of Client\n\nBetter reflects examples in discord.py project\n","lang":"Python","license":"mit","repos":"EsqWiggles\/SLA-bot,EsqWiggles\/SLA-bot"} {"commit":"0ce553f791ba0aac599cc0ae5c4784fece9cb3da","old_file":"bugsnag\/django\/middleware.py","new_file":"bugsnag\/django\/middleware.py","old_contents":"from __future__ import division, print_function, absolute_import\n\nimport bugsnag\nimport bugsnag.django\n\ndef is_development_server(request):\n server = request.META.get('wsgi.file_wrapper', None)\n\n if server is None:\n return False\n\n return server.__module__ == 'django.core.servers.basehttp'\n\nclass BugsnagMiddleware(object):\n def __init__(self):\n bugsnag.django.configure()\n\n # pylint: disable-msg=R0201\n def process_request(self, request):\n if is_development_server(request):\n bugsnag.configure(release_stage=\"development\")\n\n bugsnag.configure_request(django_request=request)\n\n return None\n\n # pylint: disable-msg=W0613\n def process_response(self, request, response):\n bugsnag.clear_request_config()\n\n return response\n\n def process_exception(self, request, exception):\n try:\n bugsnag.auto_notify(exception)\n\n except Exception as exc:\n bugsnag.log(\"Error in exception middleware: %s\" % exc)\n\n bugsnag.clear_request_config()\n\n return None\n","new_contents":"from __future__ import division, print_function, absolute_import\n\nimport bugsnag\nimport bugsnag.django\n\nclass BugsnagMiddleware(object):\n def __init__(self):\n bugsnag.django.configure()\n\n # pylint: disable-msg=R0201\n def process_request(self, request):\n bugsnag.configure_request(django_request=request)\n\n return None\n\n # pylint: disable-msg=W0613\n def process_response(self, request, response):\n bugsnag.clear_request_config()\n\n return response\n\n def process_exception(self, request, exception):\n try:\n bugsnag.auto_notify(exception)\n\n except Exception as exc:\n bugsnag.log(\"Error in exception middleware: %s\" % exc)\n\n bugsnag.clear_request_config()\n\n return None\n","subject":"Remove obsolete check for development","message":"Remove obsolete check for development\n","lang":"Python","license":"mit","repos":"bugsnag\/bugsnag-python,bugsnag\/bugsnag-python,overplumbum\/bugsnag-python,overplumbum\/bugsnag-python"} {"commit":"e4d746ba6c5b842529c9dafb31a90bdd31fee687","old_file":"performanceplatform\/__init__.py","new_file":"performanceplatform\/__init__.py","old_contents":"# Namespace package: https:\/\/docs.python.org\/2\/library\/pkgutil.html\ntry:\n import pkg_resources\n pkg_resources.declare_namespace(__name__)\nexcept ImportError:\n from pkgutil import extend_path\n __path__ = extend_path(__path__, __name__)\n","new_contents":"__import__('pkg_resources').declare_namespace(__name__)\n","subject":"Fix namespacing for PyPi installs","message":"Fix namespacing for PyPi installs\n\nSee https:\/\/github.com\/alphagov\/performanceplatform-client\/pull\/5\n","lang":"Python","license":"mit","repos":"alphagov\/performanceplatform-collector,alphagov\/performanceplatform-collector,alphagov\/performanceplatform-collector"} {"commit":"4b340e0712956ea44eace7382dd743890958a0fd","old_file":"widgets\/card.py","new_file":"widgets\/card.py","old_contents":"# -*- coding: utf-8 -*-\n\nfrom flask import render_template\n\nfrom models.person import Person\n\n\ndef card(person_or_id, detailed=False, small=False):\n\n if isinstance(person_or_id, Person):\n person = person_or_id\n else:\n person = Person.query.filter_by(id=person_or_id).first()\n\n return render_template('widgets\/card.html', person=person, detailed=detailed, small=small)\n\n","new_contents":"# -*- coding: utf-8 -*-\n\nfrom flask import render_template\n\nfrom models.person import Person\n\n\ndef card(person_or_id, **kwargs):\n\n if isinstance(person_or_id, Person):\n person = person_or_id\n else:\n person = Person.query.filter_by(id=person_or_id).first()\n\n return render_template('widgets\/card.html', person=person, **kwargs)\n\n","subject":"Revert \"Fix a bug in caching\"","message":"Revert \"Fix a bug in caching\"\n\nThis reverts commit 2565df456ecb290f620ce4dadca19c76b0eeb1af.\n\nConflicts:\n\twidgets\/card.py\n","lang":"Python","license":"apache-2.0","repos":"teampopong\/pokr.kr,teampopong\/pokr.kr,teampopong\/pokr.kr,teampopong\/pokr.kr"} {"commit":"fa75cdb0114d86b626a77ea19897abd532fd4aeb","old_file":"src\/hack4lt\/forms.py","new_file":"src\/hack4lt\/forms.py","old_contents":"from django import forms\nfrom django.contrib.auth import authenticate\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom hack4lt.models import Hacker\n\n\n\n\nclass RegistrationForm(forms.ModelForm):\n class Meta:\n model = Hacker\n fields = ('username', 'first_name', 'last_name', 'email', 'repository',\n 'website', 'stackoverflow_user', 'description')\n\n\nclass LoginForm(forms.Form):\n username = forms.CharField(label=_('Username'), max_length=100)\n password = forms.CharField(label=_('Password'), max_length=128,\n widget=forms.PasswordInput(render_value=False))\n\n def clean(self):\n cleaned_data = super(LoginForm, self).clean()\n if self.errors:\n return cleaned_data\n\n user = authenticate(**cleaned_data)\n if not user:\n raise forms.ValidationError(_('Username or password is incorrect'))\n cleaned_data['user'] = user\n return cleaned_data\n","new_contents":"from django import forms\nfrom django.contrib.auth import authenticate\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.forms.util import ErrorList\n\nfrom hack4lt.models import Hacker\n\n\n\nclass RegistrationForm(forms.ModelForm):\n password = forms.CharField(label=_('Password'), max_length=128, min_length=6,\n widget=forms.PasswordInput(render_value=False))\n password_repeat = forms.CharField(label=_('Repeat Password'), min_length=6,\n max_length=128, widget=forms.PasswordInput(render_value=False))\n\n class Meta:\n model = Hacker\n fields = ('username', 'password', 'password_repeat', 'first_name',\n 'last_name', 'email', 'repository', 'website',\n 'stackoverflow_user', 'description')\n\n def is_valid(self):\n valid = super(RegistrationForm, self).is_valid()\n if not valid:\n return valid\n\n first_password = self.cleaned_data.get('password')\n repeat_password = self.cleaned_data.get('password_repeat')\n\n if first_password == repeat_password:\n return True\n errors = self._errors.setdefault('password', ErrorList())\n errors.append(u'Passwords do not match')\n return False\n\n\nclass LoginForm(forms.Form):\n username = forms.CharField(label=_('Username'), max_length=100)\n password = forms.CharField(label=_('Password'), max_length=128,\n widget=forms.PasswordInput(render_value=False))\n\n def clean(self):\n cleaned_data = super(LoginForm, self).clean()\n if self.errors:\n return cleaned_data\n\n user = authenticate(**cleaned_data)\n if not user:\n raise forms.ValidationError(_('Username or password is incorrect'))\n cleaned_data['user'] = user\n return cleaned_data\n","subject":"Add password and password_repeat fields to registration form.","message":"Add password and password_repeat fields to registration form.\n","lang":"Python","license":"bsd-3-clause","repos":"niekas\/Hack4LT"} {"commit":"640aff6378b6f47d68645822fc5c2bb3fd737710","old_file":"salt\/modules\/test_virtual.py","new_file":"salt\/modules\/test_virtual.py","old_contents":"# -*- coding: utf-8 -*-\n'''\nModule for running arbitrary tests with a __virtual__ function\n'''\nfrom __future__ import absolute_import\n\n\ndef __virtual__():\n return False\n\n\ndef test():\n return True\n","new_contents":"# -*- coding: utf-8 -*-\n'''\nModule for running arbitrary tests with a __virtual__ function\n'''\nfrom __future__ import absolute_import\n\n\ndef __virtual__():\n return False\n\n\ndef ping():\n return True\n","subject":"Fix mis-naming from pylint cleanup","message":"Fix mis-naming from pylint cleanup\n","lang":"Python","license":"apache-2.0","repos":"saltstack\/salt,saltstack\/salt,saltstack\/salt,saltstack\/salt,saltstack\/salt"} {"commit":"467e8e4d8113a8f6473d7f82d86d5401053362b8","old_file":"scripts\/gen-release-notes.py","new_file":"scripts\/gen-release-notes.py","old_contents":"\"\"\"\nGenerates the release notes for the latest release, in Markdown.\n\nConvert CHANGELOG.rst to Markdown, and extracts just the latest release.\n\nWrites to ``scripts\/latest-release-notes.md``, which can be\nused with https:\/\/github.com\/softprops\/action-gh-release.\n\"\"\"\nfrom pathlib import Path\n\nimport pypandoc\n\nthis_dir = Path(__file__).parent\nrst_text = (this_dir.parent \/ \"CHANGELOG.rst\").read_text(encoding=\"UTF-8\")\nmd_text = pypandoc.convert_text(\n rst_text, \"md\", format=\"rst\", extra_args=[\"--wrap=preserve\"]\n)\n\noutput_lines = []\nfirst_heading_found = False\nfor line in md_text.splitlines():\n if line.startswith(\"# \"):\n if first_heading_found:\n break\n first_heading_found = True\n output_lines.append(line)\n\noutput_fn = this_dir \/ \"latest-release-notes.md\"\noutput_fn.write_text(\"\\n\".join(output_lines), encoding=\"UTF-8\")\nprint(output_fn, \"generated.\")\n","new_contents":"\"\"\"\nGenerates the release notes for the latest release, in Markdown.\n\nConvert CHANGELOG.rst to Markdown, and extracts just the latest release.\n\nWrites to ``scripts\/latest-release-notes.md``, which can be\nused with https:\/\/github.com\/softprops\/action-gh-release.\n\"\"\"\nfrom pathlib import Path\n\nimport pypandoc\n\nthis_dir = Path(__file__).parent\nrst_text = (this_dir.parent \/ \"CHANGELOG.rst\").read_text(encoding=\"UTF-8\")\nmd_text = pypandoc.convert_text(\n rst_text, \"md\", format=\"rst\", extra_args=[\"--wrap=preserve\"]\n)\n\noutput_lines = []\nfirst_heading_found = False\nfor line in md_text.splitlines():\n if line.startswith(\"# \"):\n if first_heading_found:\n break\n first_heading_found = True\n else:\n output_lines.append(line)\n\noutput_fn = this_dir \/ \"latest-release-notes.md\"\noutput_fn.write_text(\"\\n\".join(output_lines), encoding=\"UTF-8\")\nprint(output_fn, \"generated.\")\n","subject":"Remove release title from the GitHub release notes body","message":"Remove release title from the GitHub release notes body\n","lang":"Python","license":"mit","repos":"pytest-dev\/pytest-mock"} {"commit":"ac33c7fcee74053dae6edfdd4596bfe03098711d","old_file":"waptpkg.py","new_file":"waptpkg.py","old_contents":"# -*- coding: utf-8 -*-\n\nimport os\nimport waptpackage\nfrom waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey\n\ndef download(remote, path, pkg):\n \"\"\"Downloads package\"\"\"\n if not pkg.package:\n return False\n\n res = remote.download_packages(pkg, path)\n if res['errors']:\n return False\n\n pkg_path = res['downloaded'] and res['downloaded'][0] or res['skipped'][0]\n if not pkg_path:\n return False\n\n return pkg_path\n\ndef check_signature(pkg):\n \"\"\"Check package signature if \/etc\/ssl\/certs exists\"\"\"\n if not os.path.exists('\/etc\/ssl\/certs'):\n return True\n\n if not waptpackage.PackageEntry(waptfile=pkg.localpath).check_control_signature(SSLCABundle('\/etc\/ssl\/certs')):\n return False\n\n return True\n\ndef overwrite_signature(pkg):\n \"\"\"Overwrite imported package signature\"\"\"\n cert_file = os.environ.get('WAPT_CERT')\n key_file = os.environ.get('WAPT_KEY')\n password = os.environ.get('WAPT_PASSWD')\n if not (cert_file and key_file and password):\n return False\n\n crt = SSLCertificate(cert_file)\n key = SSLPrivateKey(key_file, password=password)\n\n return pkg.sign_package(crt, key)\n\ndef hash(pkg):\n \"\"\"Creates a hash based on package properties\"\"\"\n\n return \"%s:%s\" % (pkg.package, pkg.architecture)\n","new_contents":"# -*- coding: utf-8 -*-\n\nimport os\nimport waptpackage\nfrom waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey\n\ndef download(remote, path, pkg):\n \"\"\"Downloads package\"\"\"\n if not pkg.package:\n return False\n\n res = remote.download_packages(pkg, path)\n if res['errors']:\n return False\n\n pkg_path = res['downloaded'] and res['downloaded'][0] or res['skipped'][0]\n if not pkg_path:\n return False\n\n return pkg_path\n\ndef check_signature(pkg):\n \"\"\"Check package signature if \/etc\/ssl\/certs exists\"\"\"\n if not os.path.exists('\/etc\/ssl\/certs'):\n return True\n\n if not waptpackage.PackageEntry(waptfile=pkg.localpath).check_control_signature(SSLCABundle('\/etc\/ssl\/certs')):\n return False\n\n return True\n\ndef overwrite_signature(pkg):\n \"\"\"Overwrite imported package signature\"\"\"\n cert_file = os.environ.get('WAPT_CERT')\n key_file = os.environ.get('WAPT_KEY')\n password = os.environ.get('WAPT_PASSWD')\n if not (cert_file and key_file and password):\n return False\n\n crt = SSLCertificate(cert_file)\n key = SSLPrivateKey(key_file, password=password)\n\n return pkg.sign_package(crt, key)\n\ndef hash(pkg):\n \"\"\"Creates a hash based on package properties\"\"\"\n\n return \"%s:%s:%s\" % (pkg.package, pkg.architecture, pkg.locale)\n","subject":"Include locale in package hash","message":"Include locale in package hash\n","lang":"Python","license":"mit","repos":"jf-guillou\/wapt-scripts"} {"commit":"13ba6bf5c12c46aa43c0060d40458fe453df9c33","old_file":"ydf\/yaml_ext.py","new_file":"ydf\/yaml_ext.py","old_contents":"\"\"\"\n ydf\/yaml_ext\n ~~~~~~~~~~~~\n\n Contains extensions to existing YAML functionality.\n\"\"\"\n\nimport collections\n\nfrom ruamel import yaml\nfrom ruamel.yaml import resolver\n\n\nclass OrderedLoader(yaml.Loader):\n \"\"\"\n Extends the default YAML loader to use :class:`~collections.OrderedDict` for mapping\n types.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(OrderedLoader, self).__init__(*args, **kwargs)\n self.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, self.construct_ordered_mapping)\n\n @staticmethod\n def construct_ordered_mapping(loader, node):\n loader.flatten_mapping(node)\n return collections.OrderedDict(loader.construct_pairs(node))\n\n\ndef load(stream):\n \"\"\"\n Load the given YAML string.\n \"\"\"\n return yaml.load(stream, OrderedLoader)\n","new_contents":"\"\"\"\n ydf\/yaml_ext\n ~~~~~~~~~~~~\n\n Contains extensions to existing YAML functionality.\n\"\"\"\n\nimport collections\n\nfrom ruamel import yaml\nfrom ruamel.yaml import resolver\n\n\nclass OrderedRoundTripLoader(yaml.RoundTripLoader):\n \"\"\"\n Extends the default round trip YAML loader to use :class:`~collections.OrderedDict` for mapping\n types.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(OrderedRoundTripLoader, self).__init__(*args, **kwargs)\n self.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, self.construct_ordered_mapping)\n\n @staticmethod\n def construct_ordered_mapping(loader, node):\n loader.flatten_mapping(node)\n return collections.OrderedDict(loader.construct_pairs(node))\n\n\ndef load_all(stream):\n \"\"\"\n Load all documents within the given YAML string.\n\n :param stream: A valid YAML stream.\n :return: Generator that yields each document found in the YAML stream.\n \"\"\"\n return yaml.load_all(stream, OrderedRoundTripLoader)\n","subject":"Switch to round trip loader to support multiple documents.","message":"Switch to round trip loader to support multiple documents.\n","lang":"Python","license":"apache-2.0","repos":"ahawker\/ydf"} {"commit":"9b586b953bfe3c94adb40d0a804de3d46fca1887","old_file":"httpie\/config.py","new_file":"httpie\/config.py","old_contents":"import os\n\n__author__ = 'jakub'\n\n\nCONFIG_DIR = os.path.expanduser('~\/.httpie')\n","new_contents":"import os\nfrom requests.compat import is_windows\n\n__author__ = 'jakub'\n\n\nCONFIG_DIR = (os.path.expanduser('~\/.httpie') if not is_windows else\n os.path.expandvars(r'%APPDATA%\\\\httpie'))\n","subject":"Use %APPDATA% for data on Windows.","message":"Use %APPDATA% for data on Windows.\n","lang":"Python","license":"bsd-3-clause","repos":"codingjoe\/httpie,konopski\/httpie,Bogon\/httpie,fontenele\/httpie,aredo\/httpie,GrimDerp\/httpie,vietlq\/httpie,paran0ids0ul\/httpie,gnagel\/httpie,fontenele\/httpie,lingtalfi\/httpie,rschmidtz\/httpie,alexeikabak\/httpie,konopski\/httpie,PKRoma\/httpie,GrimDerp\/httpie,PKRoma\/httpie,bright-sparks\/httpie,marklap\/httpie,fritaly\/httpie,rgordeev\/httpie,kaushik94\/httpie,paran0ids0ul\/httpie,mblayman\/httpie,saisai\/httpie,vietlq\/httpie,zerin108\/httpie,ardydedase\/httpie,keita1314\/httpie,aredo\/httpie,hoatle\/httpie,meigrafd\/httpie,jakubroztocil\/httpie,alex-bretet\/httpie,alfcrisci\/httpie,sofianhw\/httpie,codingjoe\/httpie,JPWKU\/httpie,gnagel\/httpie,insionng\/httpie,zerodark\/httpie,bright-sparks\/httpie,alexeikabak\/httpie,Bogon\/httpie,jkbrzt\/httpie,avtoritet\/httpie,lk1ngaa7\/httpie,fritaly\/httpie,bgarrels\/httpie,HackerTool\/httpie,rschmidtz\/httpie,zerin108\/httpie,marklap\/httpie,HackerTool\/httpie,danieldc\/httpie,danieldc\/httpie,guiquanz\/httpie,chaos33\/httpie,jcrumb\/httpie,Batterfii\/httpie,a-x-\/httpie,bitcoinfees\/two1-httpie,kevinlondon\/httpie,rusheel\/httpie,alex-bretet\/httpie,insionng\/httpie,kevinlondon\/httpie,rgordeev\/httpie,hoatle\/httpie,Batterfii\/httpie,bitcoinfees\/two1-httpie,jakubroztocil\/httpie,alfcrisci\/httpie,MiteshShah\/httpie,lingtalfi\/httpie,ardydedase\/httpie,normabuttz\/httpie,lk1ngaa7\/httpie,jakubroztocil\/httpie,guiquanz\/httpie,bgarrels\/httpie,whitefoxx\/httpie,jkbrzt\/httpie,wandec\/first,meigrafd\/httpie,jkbrzt\/httpie,mblayman\/httpie,zerodark\/httpie,sofianhw\/httpie,avtoritet\/httpie,jcrumb\/httpie,tylertebbs20\/Practice-httpie,normabuttz\/httpie,a-x-\/httpie,whitefoxx\/httpie,tylertebbs20\/Practice-httpie,saisai\/httpie,rusheel\/httpie,JPWKU\/httpie,MiteshShah\/httpie,keita1314\/httpie"} {"commit":"085edf28b2e70552789407e16ca83faf78313672","old_file":"version.py","new_file":"version.py","old_contents":"major = 0\nminor=0\npatch=0\nbranch=\"dev\"\ntimestamp=1376579871.17","new_contents":"major = 0\nminor=0\npatch=25\nbranch=\"master\"\ntimestamp=1376610207.69","subject":"Tag commit for v0.0.25-master generated by gitmake.py","message":"Tag commit for v0.0.25-master generated by gitmake.py\n","lang":"Python","license":"mit","repos":"ryansturmer\/gitmake"} {"commit":"09d85cf39fd8196b26b357ee3f0b9fbb67770014","old_file":"flask_jq.py","new_file":"flask_jq.py","old_contents":"from flask import Flask, jsonify, render_template, request\napp = Flask(__name__)\n\n\n@app.route('\/_add_numbers')\ndef add_numbers():\n ''' Because numbers must be added server side '''\n a = request.args.get('a', 0, type=int)\n b = request.args.get('b', 0, type=int)\n return jsonify(result=a + b)\n\n\n@app.route('\/')\ndef index():\n return render_template('index.html')\n","new_contents":"from flask import Flask, jsonify, render_template, request\napp = Flask(__name__)\n\n\n@app.route('\/_add_numbers')\ndef add_numbers():\n ''' Because numbers must be added server side '''\n a = request.args.get('a', 0, type=int)\n b = request.args.get('b', 0, type=int)\n return jsonify(result=a + b)\n\n\n@app.route('\/')\ndef index():\n return render_template('index.html')\n\nif __name__ == '__main__':\n app.run('0.0.0.0',port=4000)\n","subject":"Add app run on main","message":"Add app run on main\n","lang":"Python","license":"mit","repos":"avidas\/flask-jquery,avidas\/flask-jquery,avidas\/flask-jquery"} {"commit":"c5ba874987b2e788ae905a1a84e7f2575ff9f991","old_file":"conman\/redirects\/models.py","new_file":"conman\/redirects\/models.py","old_contents":"from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom conman.routes.models import Route\nfrom . import views\n\n\nclass RouteRedirect(Route):\n \"\"\"\n When `route` is browsed to, browser should be redirected to `target`.\n\n This model holds the data required to make that connection.\n \"\"\"\n target = models.ForeignKey('routes.Route', related_name='+')\n permanent = models.BooleanField(default=False, blank=True)\n\n view = views.RouteRedirectView.as_view()\n\n def clean(self):\n \"\"\"Forbid setting target equal to self.\"\"\"\n if self.target_id == self.route_ptr_id:\n error = {'target': _('A RouteRedirect cannot redirect to itself.')}\n raise ValidationError(error)\n\n def save(self, *args, **kwargs):\n \"\"\"Validate the Redirect before saving.\"\"\"\n self.clean()\n return super().save(*args, **kwargs)\n\n\nclass URLRedirect(Route):\n \"\"\"A `Route` that redirects to an arbitrary URL.\"\"\"\n target = models.URLField(max_length=2000)\n permanent = models.BooleanField(default=False, blank=True)\n\n view = views.URLRedirectView.as_view()\n","new_contents":"from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom conman.routes.models import Route\nfrom . import views\n\n\nclass RouteRedirect(Route):\n \"\"\"\n When `route` is browsed to, browser should be redirected to `target`.\n\n This model holds the data required to make that connection.\n \"\"\"\n target = models.ForeignKey('routes.Route', related_name='+')\n permanent = models.BooleanField(default=False)\n\n view = views.RouteRedirectView.as_view()\n\n def clean(self):\n \"\"\"Forbid setting target equal to self.\"\"\"\n if self.target_id == self.route_ptr_id:\n error = {'target': _('A RouteRedirect cannot redirect to itself.')}\n raise ValidationError(error)\n\n def save(self, *args, **kwargs):\n \"\"\"Validate the Redirect before saving.\"\"\"\n self.clean()\n return super().save(*args, **kwargs)\n\n\nclass URLRedirect(Route):\n \"\"\"A `Route` that redirects to an arbitrary URL.\"\"\"\n target = models.URLField(max_length=2000)\n permanent = models.BooleanField(default=False)\n\n view = views.URLRedirectView.as_view()\n","subject":"Remove explicit default from BooleanField","message":"Remove explicit default from BooleanField\n","lang":"Python","license":"bsd-2-clause","repos":"Ian-Foote\/django-conman,meshy\/django-conman,meshy\/django-conman"} {"commit":"f5d56b0c54af414f02721a1a02a0eaf80dbba898","old_file":"client\/python\/unrealcv\/util.py","new_file":"client\/python\/unrealcv\/util.py","old_contents":"import numpy as np\nimport PIL\nfrom io import BytesIO\n# StringIO module is removed in python3, use io module\n\ndef read_png(res):\n import PIL.Image\n img = PIL.Image.open(BytesIO(res))\n return np.asarray(img)\n\ndef read_npy(res):\n # res is a binary buffer\n return np.load(BytesIO(res))\n","new_contents":"import numpy as np\nimport PIL.Image\nfrom io import BytesIO\n# StringIO module is removed in python3, use io module\n\ndef read_png(res):\n img = None\n try:\n PIL_img = PIL.Image.open(BytesIO(res))\n img = np.asarray(PIL_img)\n except:\n print('Read png can not parse response %s' % str(res[:20]))\n return img\n\ndef read_npy(res):\n # res is a binary buffer\n arr = None\n try:\n arr = np.load(BytesIO(res))\n except:\n print('Read npy can not parse response %s' % str(res[:20]))\n return arr\n","subject":"Handle exceptions in read_png and read_npy.","message":"Handle exceptions in read_png and read_npy.\n","lang":"Python","license":"mit","repos":"unrealcv\/unrealcv,unrealcv\/unrealcv,unrealcv\/unrealcv,unrealcv\/unrealcv,unrealcv\/unrealcv"} {"commit":"95f0ae5e04df6e5ce454b15551133caacfd44536","old_file":"services\/netflix.py","new_file":"services\/netflix.py","old_contents":"import foauth.providers\n\n\nclass Netflix(foauth.providers.OAuth1):\n # General info about the provider\n provider_url = 'https:\/\/www.netflix.com\/'\n docs_url = 'http:\/\/developer.netflix.com\/docs'\n\n # URLs to interact with the API\n request_token_url = 'http:\/\/api.netflix.com\/oauth\/request_token'\n authorize_url = 'https:\/\/api-user.netflix.com\/oauth\/login'\n access_token_url = 'http:\/\/api.netflix.com\/oauth\/access_token'\n api_domains = ['api-public.netflix.com', 'api.netflix.com']\n\n available_permissions = [\n (None, 'read and manage your queue'),\n ]\n","new_contents":"import foauth.providers\nfrom oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_QUERY\n\n\nclass Netflix(foauth.providers.OAuth1):\n # General info about the provider\n provider_url = 'https:\/\/www.netflix.com\/'\n docs_url = 'http:\/\/developer.netflix.com\/docs'\n\n # URLs to interact with the API\n request_token_url = 'http:\/\/api.netflix.com\/oauth\/request_token'\n authorize_url = 'https:\/\/api-user.netflix.com\/oauth\/login'\n access_token_url = 'http:\/\/api.netflix.com\/oauth\/access_token'\n api_domains = ['api-public.netflix.com', 'api.netflix.com']\n\n available_permissions = [\n (None, 'read and manage your queue'),\n ]\n\n https = False\n signature_type = SIGNATURE_TYPE_QUERY\n\n def get_authorize_params(self, redirect_uri):\n params = super(Netflix, self).get_authorize_params(redirect_uri)\n params['oauth_consumer_key'] = self.client_id\n return params\n","subject":"Fix token retrieval for Netflix","message":"Fix token retrieval for Netflix\n","lang":"Python","license":"bsd-3-clause","repos":"foauth\/foauth.org,foauth\/oauth-proxy,foauth\/foauth.org,foauth\/foauth.org"} {"commit":"3093941ebed1f9c726a88776819ee181cdb0b869","old_file":"piper\/db\/core.py","new_file":"piper\/db\/core.py","old_contents":"import logbook\n\n\n# Let's name this DatabaseBase. 'tis a silly name.\nclass DatabaseBase(object):\n \"\"\"\n Abstract class representing a persistance layer\n\n \"\"\"\n\n def __init__(self):\n self.log = logbook.Logger(self.__class__.__name__)\n\n def init(self, ns, config):\n raise NotImplementedError()\n\n\nclass DbCLI(object):\n def __init__(self, cls):\n self.cls = cls\n self.log = logbook.Logger(self.__class__.__name__)\n\n def compose(self, parser): # pragma: nocover\n db = parser.add_parser('db', help='Perform database tasks')\n\n sub = db.add_subparsers(help='Database commands', dest=\"db_command\")\n sub.add_parser('init', help='Do the initial setup of the database')\n\n return 'db', self.run\n\n def run(self, ns, config):\n self.cls.init(ns, config)\n return 0\n","new_contents":"import logbook\n\n\nclass LazyDatabaseMixin(object):\n \"\"\"\n A mixin class that gives the subclass lazy access to the database layer\n\n The lazy attribute self.db is added, and the database class is gotten from\n self.config, and an instance is made and returned.\n\n \"\"\"\n\n _db = None\n\n @property\n def db(self):\n assert self.config is not None, \\\n 'Database accessed before self.config was set.'\n\n if self._db is None:\n self._db = self.config.get_database()\n self._db.setup()\n\n return self._db\n\n\n# Let's name this DatabaseBase. 'tis a silly name.\nclass DatabaseBase(object):\n \"\"\"\n Abstract class representing a persistance layer\n\n \"\"\"\n\n def __init__(self):\n self.log = logbook.Logger(self.__class__.__name__)\n\n def init(self, ns, config):\n raise NotImplementedError()\n\n\nclass DbCLI(object):\n def __init__(self, cls):\n self.cls = cls\n self.log = logbook.Logger(self.__class__.__name__)\n\n def compose(self, parser): # pragma: nocover\n db = parser.add_parser('db', help='Perform database tasks')\n\n sub = db.add_subparsers(help='Database commands', dest=\"db_command\")\n sub.add_parser('init', help='Do the initial setup of the database')\n\n return 'db', self.run\n\n def run(self, ns, config):\n self.cls.init(ns, config)\n return 0\n","subject":"Add first iteration of LazyDatabaseMixin()","message":"Add first iteration of LazyDatabaseMixin()\n","lang":"Python","license":"mit","repos":"thiderman\/piper"} {"commit":"4de82c9a0737c079634a87d0ea358fba7840a419","old_file":"sesame\/test_settings.py","new_file":"sesame\/test_settings.py","old_contents":"from __future__ import unicode_literals\n\nAUTHENTICATION_BACKENDS = [\n \"django.contrib.auth.backends.ModelBackend\",\n \"sesame.backends.ModelBackend\",\n]\n\nCACHES = {\"default\": {\"BACKEND\": \"django.core.cache.backends.locmem.LocMemCache\"}}\n\nDATABASES = {\"default\": {\"ENGINE\": \"django.db.backends.sqlite3\"}}\n\nINSTALLED_APPS = [\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"sesame\",\n \"sesame.test_app\",\n]\n\nLOGGING_CONFIG = None\n\nMIDDLEWARE = [\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n]\n\nROOT_URLCONF = \"sesame.test_urls\"\n\nSECRET_KEY = \"Anyone who finds an URL will be able to log in. Seriously.\"\n\nSESSION_ENGINE = \"django.contrib.sessions.backends.cache\"\n\nTEMPLATES = [{\"BACKEND\": \"django.template.backends.django.DjangoTemplates\"}]\n","new_contents":"from __future__ import unicode_literals\n\nAUTHENTICATION_BACKENDS = [\n \"django.contrib.auth.backends.ModelBackend\",\n \"sesame.backends.ModelBackend\",\n]\n\nCACHES = {\"default\": {\"BACKEND\": \"django.core.cache.backends.locmem.LocMemCache\"}}\n\nDATABASES = {\"default\": {\"ENGINE\": \"django.db.backends.sqlite3\"}}\n\nINSTALLED_APPS = [\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"sesame\",\n \"sesame.test_app\",\n]\n\nLOGGING_CONFIG = None\n\nMIDDLEWARE = [\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n]\n\nPASSWORD_HASHERS = [\"django.contrib.auth.hashers.SHA1PasswordHasher\"]\n\nROOT_URLCONF = \"sesame.test_urls\"\n\nSECRET_KEY = \"Anyone who finds an URL will be able to log in. Seriously.\"\n\nSESSION_ENGINE = \"django.contrib.sessions.backends.cache\"\n\nTEMPLATES = [{\"BACKEND\": \"django.template.backends.django.DjangoTemplates\"}]\n","subject":"Use a fast password hasher for tests.","message":"Use a fast password hasher for tests.\n\nSpeed is obviously more important than security in tests.\n","lang":"Python","license":"bsd-3-clause","repos":"aaugustin\/django-sesame,aaugustin\/django-sesame"} {"commit":"cdae77dee9888d6d6094566747650bf80d631f03","old_file":"station.py","new_file":"station.py","old_contents":"\"\"\"Creates the station class\"\"\"\n\n\n\n#import ask_user from ask_user\n#import int_check from int_check\n#import reasonable_check from reasonable_check\n\n\nclass Station:\n \"\"\"\n Each train station is an instance of the Station class.\n Methods:\n __init__: creates a new stations\n total_station_pop: calculates total station population\n ask_user(prompt, lower_range, upper_range): function to get input, maybe it should live\n somewhere else?\n \"\"\"\n\n def __init__(self, capacity, escalators, train_wait, travelors_arriving, travelors_departing):\n self.capacity = user.says(\"Enter the max capacity of the station between\" lower \"and\" upper)\n self.escalators = user.says(\"Enter the number of escalators in the station between\" lower \"and\" upper)\n self.train_wait = user.says(\"Enter the wait time between trains in seconds between\" lower \"and\" upper)\n self.travelors_arriving = user.says(\"How many people just exited the train? between\" lower \"and\" upper)\n self.travelors_departing = user.says(\"How many people are waiting for the train? between\" lower \"and\" upper)\n","new_contents":"\"\"\"Creates the station class\"\"\"\n\n\n\n#import request_integer_in_range from request_integer_in_range\n\n\n\nclass Station:\n \"\"\"\n Each train station is an instance of the Station class.\n Methods:\n __init__: creates a new stations\n request_integer_in_range : requests an integer in a range\n \n \"\"\"\n\n def __init__(self, capacity, escalators, train_wait, travelors_arriving, travelors_departing):\n self.capacity = request_integer_in_range(\"Enter the station capacity between 10 and 10000: \", 10, 10000)\n self.escalators = request_integer_in_range(\"Enter an odd number of escalators between 1 and 7: \", 1, 7)\n self.train_wait = request_integer_in_range(\"Enter the wait time between trains in seconds between 60 and 1800 \", 60, 1800)\n self.travelors_arriving = request_integer_in_range(\"Enter the number of people exiting the train between 1 and 500: \", 1, 500)\n self.travelors_departing = request_integer_in_range(\"Enter the number of people waiting for the train between 1 and 500: \", 1, 500)\n","subject":"Integrate integer test function into instantiation","message":"Integrate integer test function into instantiation\n\nRef #23","lang":"Python","license":"mit","repos":"ForestPride\/rail-problem"} {"commit":"9ea05a80114237a87af73e91cb929686235baa3e","old_file":"lib\/rpnpy\/__init__.py","new_file":"lib\/rpnpy\/__init__.py","old_contents":"import sys\nimport ctypes as _ct\n\nif sys.version_info < (3,):\n integer_types = (int, long,)\n range = xrange\nelse:\n integer_types = (int,)\n long = int\n # xrange = range\n\nC_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))\nC_WCHAR2CHAR.__doc__ = 'Convert str to bytes'\n\nC_CHAR2WCHAR = lambda x: str(x.decode('ascii'))\nC_CHAR2WCHAR.__doc__ = 'Convert bytes to str'\n\nC_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))\nC_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'\n","new_contents":"import sys\nimport ctypes as _ct\n\nif sys.version_info < (3,):\n integer_types = (int, long,)\n range = xrange\nelse:\n integer_types = (int,)\n long = int\n range = range\n\nC_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))\nC_WCHAR2CHAR.__doc__ = 'Convert str to bytes'\n\nC_CHAR2WCHAR = lambda x: str(x.decode('ascii'))\nC_CHAR2WCHAR.__doc__ = 'Convert bytes to str'\n\nC_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))\nC_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'\n","subject":"Add missing rpnpy.range reference for Python 3.","message":"Add missing rpnpy.range reference for Python 3.\n\nSigned-off-by: Stephane_Chamberland <1054841519c328088796c1f3c72c14f95c4efe35@science.gc.ca>\n","lang":"Python","license":"lgpl-2.1","repos":"meteokid\/python-rpn,meteokid\/python-rpn,meteokid\/python-rpn,meteokid\/python-rpn"} {"commit":"fff0b4af89e02ff834221ef056b7dcb979dc6cd7","old_file":"webpay\/webpay.py","new_file":"webpay\/webpay.py","old_contents":"from .api import Account, Charges, Customers\nimport requests\n\nclass WebPay:\n def __init__(self, key, api_base = 'https:\/\/api.webpay.jp\/v1'):\n self.key = key\n self.api_base = api_base\n self.account = Account(self)\n self.charges = Charges(self)\n self.customers = Customers(self)\n\n def post(self, path, params):\n r = requests.post(self.api_base + path, auth = (self.key, ''), params = params)\n return r.json()\n\n def get(self, path, params = {}):\n r = requests.get(self.api_base + path, auth = (self.key, ''), params = params)\n return r.json()\n\n def delete(self, path, params = {}):\n r = requests.delete(self.api_base + path, auth = (self.key, ''), params = params)\n return r.json()\n","new_contents":"from .api import Account, Charges, Customers\nimport requests\nimport json\n\nclass WebPay:\n def __init__(self, key, api_base = 'https:\/\/api.webpay.jp\/v1'):\n self.key = key\n self.api_base = api_base\n self.account = Account(self)\n self.charges = Charges(self)\n self.customers = Customers(self)\n\n def post(self, path, params):\n r = requests.post(self.api_base + path, auth = (self.key, ''), data = json.dumps(params))\n return r.json()\n\n def get(self, path, params = {}):\n r = requests.get(self.api_base + path, auth = (self.key, ''), params = params)\n return r.json()\n\n def delete(self, path, params = {}):\n r = requests.delete(self.api_base + path, auth = (self.key, ''), data = json.dumps(params))\n return r.json()\n","subject":"Use JSON for other than GET request","message":"Use JSON for other than GET request\n\nBecause internal dict parameters is not handled as expected.\n\n >>> payload = {'key1': 'value1', 'key2': 'value2', 'set': {'a': 'x', 'b': 'y'}}\n >>> r = requests.post(\"http:\/\/httpbin.org\/post\", data=payload)\n >>> r.json()\n {...\n 'form': {'key2': 'value2', 'key1': 'value1', 'set': ['a', 'b']}\n ...}\n","lang":"Python","license":"mit","repos":"yamaneko1212\/webpay-python"} {"commit":"b67617abe1e8530523da7231a9d74283935a1bb7","old_file":"htext\/ja\/utils.py","new_file":"htext\/ja\/utils.py","old_contents":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport re\nimport six\n\nBASIC_LATIN_RE = re.compile(r'[\\u0021-\\u007E]')\nWHITESPACE_RE = re.compile(\"[\\s]+\", re.UNICODE)\n\n\ndef force_text(value):\n if isinstance(value, six.text_type):\n return value\n elif isinstance(value, six.string_types):\n return six.b(value).decode()\n else:\n value = str(value)\n return value if isinstance(value, six.text_type) else value.decode()\n\n\ndef basic_latin_to_fullwidth(value):\n \"\"\"\n 基本ラテン文字を全角に変換する\n U+0021..U+007FはU+FF01..U+FF5Eに対応しているので\n コードポイントに差分の0xFEE0を足す\n \"\"\"\n _value = value.replace(' ', '\\u3000')\n return BASIC_LATIN_RE.sub(lambda x: unichr(ord(x.group(0)) + 0xFEE0), _value)\n\n\ndef aggregate_whitespace(value):\n return ' '.join(WHITESPACE_RE.split(value))\n","new_contents":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport re\nimport six\n\nBASIC_LATIN_RE = re.compile(r'[\\u0021-\\u007E]')\nWHITESPACE_RE = re.compile(\"[\\s]+\", re.UNICODE)\n\n\ndef force_text(value):\n if isinstance(value, six.text_type):\n return value\n elif isinstance(value, six.string_types):\n return six.b(value).decode('utf-8')\n else:\n value = str(value)\n return value if isinstance(value, six.text_type) else value.decode('utf-8')\n\n\ndef basic_latin_to_fullwidth(value):\n \"\"\"\n 基本ラテン文字を全角に変換する\n U+0021..U+007FはU+FF01..U+FF5Eに対応しているので\n コードポイントに差分の0xFEE0を足す\n \"\"\"\n _value = value.replace(' ', '\\u3000')\n return BASIC_LATIN_RE.sub(lambda x: unichr(ord(x.group(0)) + 0xFEE0), _value)\n\n\ndef aggregate_whitespace(value):\n return ' '.join(WHITESPACE_RE.split(value))\n","subject":"Fix UnicodeDecodeError on the environments where the default encoding is ascii","message":"Fix UnicodeDecodeError on the environments where the default encoding is ascii\n","lang":"Python","license":"mit","repos":"hunza\/htext"} {"commit":"0e7fdc409c17870ada40f43f72b9b20b7f490519","old_file":"d_parser\/helpers\/get_body.py","new_file":"d_parser\/helpers\/get_body.py","old_contents":"def get_body(grab, encoding='cp1251', bom=False, skip_errors=True, fix_spec_chars=True):\n return grab.doc.convert_body_to_unicode(grab.doc.body, bom, encoding, skip_errors, fix_spec_chars)\n","new_contents":"# TODO: remove useless params\ndef get_body(grab, encoding='cp1251', bom=False, skip_errors=True, fix_spec_chars=True):\n return grab.doc.body.decode('utf-8', 'ignore')\n","subject":"Rework get body text method","message":"Rework get body text method\n","lang":"Python","license":"mit","repos":"Holovin\/D_GrabDemo"} {"commit":"68aefd4c1bc682dc04721f5572ab21b609e1818f","old_file":"manage.py","new_file":"manage.py","old_contents":"import os\n\nfrom app import create_app, db\nfrom app.models import User, Category\n\nfrom flask_script import Manager\nfrom flask_migrate import Migrate, MigrateCommand\n\napp = create_app(os.getenv('FLASK_CONFIG') or 'default')\nmanager = Manager(app)\nmigrate = Migrate(app, db)\nmanager.add_command('db', MigrateCommand)\n\n#pylint: disable-msg=E1101\n@manager.command\ndef adduser(email, username, admin=False):\n \"\"\" Register a new user\"\"\"\n from getpass import getpass\n password = getpass()\n password2 = getpass(prompt='Confirm: ')\n\n if password != password2:\n import sys\n sys.exit(\"Error: Passwords do not match!\")\n\n db.create_all()\n\n category = Category.get_by_name('Almenn frétt')\n if category is None:\n category = Category(name='Almenn frétt', active=True)\n db.session.add(category)\n\n user = User(email=email,\n username=username,\n password=password,\n is_admin=admin)\n db.session.add(user)\n db.session.commit()\n\n print('User {0} was registered successfully!'.format(username))\n\nif __name__ == '__main__':\n manager.run()\n","new_contents":"import os\n\nfrom app import create_app, db\nfrom app.models import User, Category\n\nfrom flask_script import Manager\nfrom flask_migrate import Migrate, MigrateCommand\n\napp = create_app(os.getenv('FLASK_CONFIG') or 'default')\nmanager = Manager(app)\nmigrate = Migrate(app, db)\nmanager.add_command('db', MigrateCommand)\n\n#pylint: disable-msg=E1101\n@manager.command\ndef adduser(email, username, admin=False):\n \"\"\" Register a new user\"\"\"\n from getpass import getpass\n password = getpass()\n password2 = getpass(prompt='Confirm: ')\n\n if password != password2:\n import sys\n sys.exit(\"Error: Passwords do not match!\")\n\n db.create_all()\n\n category = Category.get_by_name('Almenn frétt')\n if category is None:\n category = Category(name='Almenn frétt',\n name_en='General News',\n active=True)\n db.session.add(category)\n\n user = User(email=email,\n username=username,\n password=password,\n is_admin=admin)\n db.session.add(user)\n db.session.commit()\n\n print('User {0} was registered successfully!'.format(username))\n\nif __name__ == '__main__':\n manager.run()\n","subject":"Add name_en field due to 'not null' constraint on the Category table","message":"Add name_en field due to 'not null' constraint on the Category table\n","lang":"Python","license":"mit","repos":"finnurtorfa\/aflafrettir.is,finnurtorfa\/aflafrettir.is,finnurtorfa\/aflafrettir.is,finnurtorfa\/aflafrettir.is"} {"commit":"c563c0deb99d3364df3650321c914164d99d32cf","old_file":"been\/source\/markdowndirectory.py","new_file":"been\/source\/markdowndirectory.py","old_contents":"from been.core import DirectorySource, source_registry\nfrom hashlib import sha1\nimport re\nimport unicodedata\nimport time\nimport markdown\n\ndef slugify(value):\n value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore')\n value = unicode(re.sub('[^\\w\\s-]', '', value).strip().lower())\n return re.sub('[-\\s]+', '-', value)\n\nclass MarkdownDirectory(DirectorySource):\n kind = 'markdown'\n def process_event(self, event):\n md = markdown.Markdown(extensions=['meta'])\n html = md.convert(event['content'])\n event['title'] = ' '.join(md.Meta.get('title', [event['filename']]))\n event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])]))\n event['summary'] = ' '.join(md.Meta.get('summary', [event['content'][:100]]))\n if md.Meta.get('published'):\n # Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT)\n event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S')))\n event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest()\n if time.gmtime() < event['timestamp']:\n return None\n else:\n return event\nsource_registry.add(MarkdownDirectory)\n","new_contents":"from been.core import DirectorySource, source_registry\nfrom hashlib import sha1\nimport re\nimport unicodedata\nimport time\nimport markdown\n\n# slugify from Django source (BSD license)\ndef slugify(value):\n value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore')\n value = unicode(re.sub('[^\\w\\s-]', '', value).strip().lower())\n return re.sub('[-\\s]+', '-', value)\n\nclass MarkdownDirectory(DirectorySource):\n kind = 'markdown'\n def process_event(self, event):\n md = markdown.Markdown(extensions=['meta'])\n html = md.convert(event['content'])\n event['title'] = ' '.join(md.Meta.get('title', [event['filename']]))\n event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])]))\n event['summary'] = ' '.join(md.Meta.get('summary', [event['content'][:100]]))\n if md.Meta.get('published'):\n # Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT)\n event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S')))\n event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest()\n if time.gmtime() < event['timestamp']:\n return None\n else:\n return event\nsource_registry.add(MarkdownDirectory)\n","subject":"Add attribution to slugify function.","message":"Add attribution to slugify function.\n","lang":"Python","license":"bsd-3-clause","repos":"chromakode\/been"} {"commit":"8f41ff94ecfceedf14cea03e7f2ca08df380edb0","old_file":"weight\/models.py","new_file":"weight\/models.py","old_contents":"# -*- coding: utf-8 -*-\n\n# This file is part of Workout Manager.\n# \n# Workout Manager is free software: you can redistribute it and\/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# Workout Manager is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU Affero General Public License\n# along with Workout Manager. If not, see .\n\nfrom django.db import models\n\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import ugettext_lazy as _\n\nclass WeightEntry(models.Model):\n \"\"\"Model for a weight point\n \"\"\"\n creation_date = models.DateField(_('Creation date'))\n weight = models.FloatField(_('Weight'))\n user = models.ForeignKey(User, verbose_name = _('User'))\n\n # Metaclass to set some other properties\n class Meta:\n \n # Order by creation_date, ascending (oldest last), better for diagram\n ordering = [\"creation_date\", ]\n \n def __unicode__(self):\n \"\"\"Return a more human-readable representation\n \"\"\"\n return \"%s: %s kg\" % (self.creation_date, self.weight)\n","new_contents":"# -*- coding: utf-8 -*-\n\n# This file is part of Workout Manager.\n# \n# Workout Manager is free software: you can redistribute it and\/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# Workout Manager is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU Affero General Public License\n# along with Workout Manager. If not, see .\n\nfrom django.db import models\n\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import ugettext_lazy as _\n\nclass WeightEntry(models.Model):\n \"\"\"Model for a weight point\n \"\"\"\n creation_date = models.DateField(verbose_name = _('Date'))\n weight = models.FloatField(verbose_name = _('Weight'))\n user = models.ForeignKey(User, verbose_name = _('User'))\n\n # Metaclass to set some other properties\n class Meta:\n \n # Order by creation_date, ascending (oldest last), better for diagram\n ordering = [\"creation_date\", ]\n \n def __unicode__(self):\n \"\"\"Return a more human-readable representation\n \"\"\"\n return \"%s: %s kg\" % (self.creation_date, self.weight)\n","subject":"Make the verbose name for weight entries more user friendly","message":"Make the verbose name for weight entries more user friendly\n","lang":"Python","license":"agpl-3.0","repos":"rolandgeider\/wger,petervanderdoes\/wger,DeveloperMal\/wger,petervanderdoes\/wger,kjagoo\/wger_stark,rolandgeider\/wger,wger-project\/wger,petervanderdoes\/wger,wger-project\/wger,kjagoo\/wger_stark,DeveloperMal\/wger,kjagoo\/wger_stark,wger-project\/wger,wger-project\/wger,rolandgeider\/wger,DeveloperMal\/wger,DeveloperMal\/wger,kjagoo\/wger_stark,petervanderdoes\/wger,rolandgeider\/wger"} {"commit":"1b0a5388c246dba1707f768e9be08b3a63503a31","old_file":"samples\/python\/topology\/tweepy\/app.py","new_file":"samples\/python\/topology\/tweepy\/app.py","old_contents":"from streamsx.topology.topology import *\nimport streamsx.topology.context\nimport sys\nimport tweets\n\n#\n# Continually stream tweets that contain\n# the terms passed on the command line.\n#\n# python3 app.py Food GlutenFree\n#\ndef main():\n terms = sys.argv[1:]\n topo = Topology(\"TweetsUsingTweepy\")\n\n # Event based source stream\n # Each tuple is a dictionary containing\n # the full tweet (converted from JSON)\n ts = topo.source(tweets.tweets(terms))\n \n # get the text of the tweet\n ts = ts.transform(tweets.text)\n\n # just print it\n ts.print()\n\n streamsx.topology.context.submit(\"DISTRIBUTED\", topo.graph)\n\nif __name__ == '__main__':\n main()\n","new_contents":"from streamsx.topology.topology import *\nimport streamsx.topology.context\nimport sys\nimport tweets\n\n#\n# Continually stream tweets that contain\n# the terms passed on the command line.\n#\n# python3 app.py Food GlutenFree\n#\n#\n# Requires tweepy to be installed\n#\n# pip3 install tweepy\n#\n# http:\/\/www.tweepy.org\/\n#\n# You must create Twitter application authentication tokens\n# and set them in the mykeys.py module.\n# Note this is only intended as a simple sample,\n#\n\ndef main():\n terms = sys.argv[1:]\n topo = Topology(\"TweetsUsingTweepy\")\n\n # Event based source stream\n # Each tuple is a dictionary containing\n # the full tweet (converted from JSON)\n ts = topo.source(tweets.tweets(terms))\n \n # get the text of the tweet\n ts = ts.transform(tweets.text)\n\n # just print it\n ts.print()\n\n streamsx.topology.context.submit(\"DISTRIBUTED\", topo.graph)\n\nif __name__ == '__main__':\n main()\n","subject":"Add some info about tweepy","message":"Add some info about tweepy\n","lang":"Python","license":"apache-2.0","repos":"IBMStreams\/streamsx.topology,ddebrunner\/streamsx.topology,wmarshall484\/streamsx.topology,wmarshall484\/streamsx.topology,ddebrunner\/streamsx.topology,wmarshall484\/streamsx.topology,IBMStreams\/streamsx.topology,IBMStreams\/streamsx.topology,ibmkendrick\/streamsx.topology,ddebrunner\/streamsx.topology,ibmkendrick\/streamsx.topology,ibmkendrick\/streamsx.topology,ibmkendrick\/streamsx.topology,IBMStreams\/streamsx.topology,wmarshall484\/streamsx.topology,IBMStreams\/streamsx.topology,ddebrunner\/streamsx.topology,IBMStreams\/streamsx.topology,ibmkendrick\/streamsx.topology,wmarshall484\/streamsx.topology,ibmkendrick\/streamsx.topology,ibmkendrick\/streamsx.topology,ddebrunner\/streamsx.topology,wmarshall484\/streamsx.topology,IBMStreams\/streamsx.topology,ddebrunner\/streamsx.topology,ddebrunner\/streamsx.topology,wmarshall484\/streamsx.topology,wmarshall484\/streamsx.topology"} {"commit":"c8a0aee9b68b0567adb8285c3264d244e2ed71ca","old_file":"bnw\/handlers\/command_register.py","new_file":"bnw\/handlers\/command_register.py","old_contents":"# -*- coding: utf-8 -*-\n# from twisted.words.xish import domish\nfrom twisted.words.protocols.jabber.xmpp_stringprep import nodeprep\n\nfrom base import *\nimport random\nimport time\nimport bnw.core.bnw_objects as objs\n\n\ndef _(s, user):\n return s\n\nfrom uuid import uuid4\nimport re\n\n\n@check_arg(name=USER_RE)\n@defer.inlineCallbacks\ndef cmd_register(request, name=\"\"):\n \"\"\" Регистрация \"\"\"\n if request.user:\n defer.returnValue(\n dict(ok=False,\n desc=u'You are already registered as %s' % (\n request.user['name'],),\n )\n )\n else:\n name = name.lower()[:128]\n if name == 'anonymous':\n defer.returnValue(\n dict(ok=False, desc=u'You aren''t anonymous.')\n )\n\n user = objs.User({'id': uuid4().hex,\n 'name': name,\n 'login_key': uuid4().hex,\n 'regdate': int(time.time()),\n 'jid': request.jid.userhost(),\n 'interface': 'redeye',\n 'settings': {\n 'servicejid': request.to.userhost()\n },\n })\n if not (yield objs.User.find_one({'name': name})):\n _ = yield user.save()\n defer.returnValue(\n dict(ok=True, desc='We registered you as %s.' % (name,))\n )\n else:\n defer.returnValue(\n dict(ok=True, desc='This username is already taken')\n )\n","new_contents":"# -*- coding: utf-8 -*-\n# from twisted.words.xish import domish\nfrom twisted.words.protocols.jabber.xmpp_stringprep import nodeprep\n\nfrom base import *\nimport random\nimport time\nimport bnw.core.bnw_objects as objs\n\n\ndef _(s, user):\n return s\n\nfrom uuid import uuid4\nimport re\n\n\n@check_arg(name=USER_RE)\n@defer.inlineCallbacks\ndef cmd_register(request, name=\"\"):\n \"\"\" Регистрация \"\"\"\n if request.user:\n defer.returnValue(\n dict(ok=False,\n desc=u'You are already registered as %s' % (\n request.user['name'],),\n )\n )\n else:\n name = name.lower()[:128]\n if name == 'anonymous':\n defer.returnValue(\n dict(ok=False, desc=u'You aren''t anonymous.')\n )\n\n user = objs.User({'id': uuid4().hex,\n 'name': name,\n 'login_key': uuid4().hex,\n 'regdate': int(time.time()),\n 'jid': request.jid.userhost(),\n 'interface': 'redeye',\n 'settings': {\n 'servicejid': request.to.userhost()\n },\n })\n if not (yield objs.User.find_one({'name': name})):\n _ = yield user.save()\n defer.returnValue(\n dict(ok=True, desc='We registered you as %s.' % (name,))\n )\n else:\n defer.returnValue(\n dict(ok=False, desc='This username is already taken')\n )\n","subject":"Make \"register\" return False when username is already taken","message":"Make \"register\" return False when username is already taken\n","lang":"Python","license":"bsd-2-clause","repos":"stiletto\/bnw,ojab\/bnw,ojab\/bnw,stiletto\/bnw,stiletto\/bnw,un-def\/bnw,un-def\/bnw,stiletto\/bnw,ojab\/bnw,ojab\/bnw,un-def\/bnw,un-def\/bnw"} {"commit":"d0c3906a0af504f61f39e1bc2f0fd43a71bda747","old_file":"sharedmock\/asserters.py","new_file":"sharedmock\/asserters.py","old_contents":"from pprint import pformat\n\n\ndef assert_calls_equal(expected, actual):\n \"\"\"\n Check whether the given mock object (or mock method) calls are equal and\n return a nicely formatted message.\n \"\"\"\n if not expected == actual:\n raise_calls_differ_error(expected, actual)\n\n\ndef raise_calls_differ_error(expected, actual):\n \"\"\"\"\n Raise an AssertionError with pretty print format for the given expected\n and actual mock calls in order to ensure consistent print style for better\n readability.\n \"\"\"\n expected_str = pformat(expected)\n actual_str = pformat(actual)\n msg = '\\nMock calls differ!\\nExpected calls:\\n%s\\nActual calls:\\n%s' % (expected_str,\n actual_str)\n raise AssertionError(msg)\n\n\ndef assert_calls_equal_unsorted(expected, actual):\n \"\"\"\n Raises an AssertionError if the two iterables do not contain the same items.\n\n The order of the items is ignored\n \"\"\"\n for expected in expected:\n if expected not in actual:\n raise_calls_differ_error(expected, actual)\n","new_contents":"from pprint import pformat\n\n\ndef assert_calls_equal(expected, actual):\n \"\"\"\n Check whether the given mock object (or mock method) calls are equal and\n return a nicely formatted message.\n \"\"\"\n if not expected == actual:\n raise_calls_differ_error(expected, actual)\n\n\ndef raise_calls_differ_error(expected, actual):\n \"\"\"\n Raise an AssertionError with pretty print format for the given expected\n and actual mock calls in order to ensure consistent print style for better\n readability.\n \"\"\"\n expected_str = pformat(expected)\n actual_str = pformat(actual)\n msg = '\\nMock calls differ!\\nExpected calls:\\n%s\\nActual calls:\\n%s' % (expected_str,\n actual_str)\n raise AssertionError(msg)\n\n\ndef assert_calls_equal_unsorted(expected, actual):\n \"\"\"\n Raises an AssertionError if the two iterables do not contain the same items.\n\n The order of the items is ignored\n \"\"\"\n for expected in expected:\n if expected not in actual:\n raise_calls_differ_error(expected, actual)\n","subject":"Remove extraneous quote in asserter dockstring","message":"Remove extraneous quote in asserter dockstring\n","lang":"Python","license":"apache-2.0","repos":"elritsch\/python-sharedmock"} {"commit":"b8d812039051addacda3c04d2cfe657a58bc3681","old_file":"yolk\/__init__.py","new_file":"yolk\/__init__.py","old_contents":"\"\"\"yolk.\n\nAuthor: Rob Cakebread \n\nLicense : BSD\n\n\"\"\"\n\n__version__ = '0.7.1'\n","new_contents":"\"\"\"yolk.\n\nAuthor: Rob Cakebread \n\nLicense : BSD\n\n\"\"\"\n\n__version__ = '0.7.2'\n","subject":"Increment patch version to 0.7.2","message":"Increment patch version to 0.7.2\n","lang":"Python","license":"bsd-3-clause","repos":"myint\/yolk,myint\/yolk"} {"commit":"14f2161efbd9c8377e6ff3675c48aba1ac0c47d5","old_file":"API\/chat\/forms.py","new_file":"API\/chat\/forms.py","old_contents":"import time\n\nfrom django import forms\nfrom .models import Message\nfrom .utils import timestamp_to_datetime, datetime_to_timestamp\n\n\n\nclass MessageForm(forms.Form):\n text = forms.CharField(widget=forms.Textarea)\n typing = forms.BooleanField(required=False)\n\n\nclass MessageCreationForm(MessageForm):\n username = forms.CharField(max_length=20)\n datetime_start = forms.IntegerField()\n\n def clean_datetime_start(self):\n now = int(round(time.time() * 1000))\n timestamp = int(self.data['datetime_start'])\n if now < timestamp:\n timestamp = now\n\n self.cleaned_data['datetime_start'] = timestamp_to_datetime(timestamp)\n\n def save(self):\n self.clean_datetime_start()\n\n message = Message.objects.create(channel=self.channel, **self.cleaned_data)\n\n if not message.typing:\n message.datetime_sent = message.datetime_start\n message.save()\n\n return message;\n\n\nclass MessagePatchForm(MessageForm):\n datetime_sent = forms.IntegerField()\n\n def save(self, message):\n timestamp_start = datetime_to_timestamp(message.datetime_start)\n timestamp_sent = int(self.cleaned_data['datetime_sent'])\n\n if timestamp_sent < timestamp_start:\n timestamp_sent = timestamp_start\n\n message.datetime_sent = timestamp_to_datetime(timestamp_sent)\n message.text = self.cleaned_data['text']\n message.typing = self.cleaned_data.get('typing', False)\n\n message.save()\n","new_contents":"import time\n\nfrom django import forms\nfrom .models import Message\nfrom .utils import timestamp_to_datetime, datetime_to_timestamp\n\n\n\nclass MessageForm(forms.Form):\n text = forms.CharField(widget=forms.Textarea)\n typing = forms.BooleanField(required=False)\n message_type = forms.CharField(widget=forms.Textarea)\n\n\nclass MessageCreationForm(MessageForm):\n username = forms.CharField(max_length=20)\n datetime_start = forms.IntegerField()\n\n def clean_datetime_start(self):\n now = int(round(time.time() * 1000))\n timestamp = int(self.data['datetime_start'])\n if now < timestamp:\n timestamp = now\n\n self.cleaned_data['datetime_start'] = timestamp_to_datetime(timestamp)\n\n def save(self):\n self.clean_datetime_start()\n\n message = Message.objects.create(channel=self.channel, **self.cleaned_data)\n\n if not message.typing:\n message.datetime_sent = message.datetime_start\n message.save()\n\n return message;\n\n\nclass MessagePatchForm(MessageForm):\n datetime_sent = forms.IntegerField()\n\n def save(self, message):\n timestamp_start = datetime_to_timestamp(message.datetime_start)\n timestamp_sent = int(self.cleaned_data['datetime_sent'])\n\n if timestamp_sent < timestamp_start:\n timestamp_sent = timestamp_start\n\n message.datetime_sent = timestamp_to_datetime(timestamp_sent)\n message.text = self.cleaned_data['text']\n message.typing = self.cleaned_data.get('typing', False)\n\n message.save()\n","subject":"Add message_type as CharField in form","message":"Add message_type as CharField in form\n","lang":"Python","license":"mit","repos":"gtklocker\/ting,gtklocker\/ting,mbalamat\/ting,mbalamat\/ting,mbalamat\/ting,gtklocker\/ting,dionyziz\/ting,gtklocker\/ting,dionyziz\/ting,dionyziz\/ting,dionyziz\/ting,mbalamat\/ting"} {"commit":"5733c800c10a7546228ec4562e40b2bd06c77c7e","old_file":"models.py","new_file":"models.py","old_contents":"from django.db import models\n\n# Create your models here.\n","new_contents":"from django.db import models\nfrom django.utils import timezone\nimport datetime\n\n\nclass Poll(models.Model):\n\tquestion = models.CharField(max_length=255)\n\tpub_date = models.DateTimeField('date published')\n\tdef __unicode__(self):\n\t\treturn self.question\n\tdef was_published_recently(self):\n\t\treturn self.pub_date >= timezone.now() - datetime.timedelta(days=1)\n\twas_published_recently.admin_order_field = 'pub_date'\n\twas_published_recently.boolean = True\n\twas_published_recently.short_description = 'Published recently?'\n\nclass Choice(models.Model):\n\tpoll = models.ForeignKey(Poll)\n\tchoice_text = models.CharField(max_length=255)\n\tvotes = models.IntegerField(default=0)\n\tdef __unicode__(self):\n\t\treturn self.choice_text\n","subject":"Improve database model and apperance for admin site","message":"Improve database model and apperance for admin site\n","lang":"Python","license":"mit","repos":"egel\/polls"} {"commit":"234f61d95768a86d4e78885123c2439e675d7aab","old_file":"sigma_core\/serializers\/group.py","new_file":"sigma_core\/serializers\/group.py","old_contents":"from rest_framework import serializers\n\nfrom sigma_core.models.group import Group\n\n\nclass GroupSerializer(serializers.ModelSerializer):\n class Meta:\n model = Group\n\n visibility = serializers.SerializerMethodField()\n membership_policy = serializers.SerializerMethodField()\n validation_policy = serializers.SerializerMethodField()\n type = serializers.SerializerMethodField()\n memberships = serializers.PrimaryKeyRelatedField(read_only=True, many=True)\n\n def get_visibility(self, obj):\n return obj.get_visibility_display()\n\n def get_membership_policy(self, obj):\n return obj.get_membership_policy_display()\n\n def get_validation_policy(self, obj):\n return obj.get_validation_policy_display()\n\n def get_type(self, obj):\n return obj.get_type_display()\n","new_contents":"from rest_framework import serializers\n\nfrom sigma_core.models.group import Group\n\n\nclass GroupSerializer(serializers.ModelSerializer):\n class Meta:\n model = Group\n\n memberships = serializers.PrimaryKeyRelatedField(read_only=True, many=True)\n","subject":"Fix serializer after enum changes in 01f47a70ba4d2339bb8a85212dee8b7f1b7ee049","message":"Fix serializer after enum changes in 01f47a70ba4d2339bb8a85212dee8b7f1b7ee049\n","lang":"Python","license":"agpl-3.0","repos":"ProjetSigma\/backend,ProjetSigma\/backend"} {"commit":"12320653c58cd9e9a73a6d8d69073a5b64545e5b","old_file":"tr_init.py","new_file":"tr_init.py","old_contents":"#!flask\/bin\/python\nimport os\nimport sys\nif sys.platform == 'win32':\n pybabel = 'flask\\\\Scripts\\\\pybabel'\nelse:\n pybabel = 'flask\/bin\/pybabel'\nif len(sys.argv) != 2:\n print \"usage: tr_init \"\n sys.exit(1)\nos.system(pybabel + ' extract -F babel.cfg -k lazy_gettext -o messages.pot app')\nos.system(pybabel + ' init -i messages.pot -d app\/translations -l ' + sys.argv[1])\nos.unlink('messages.pot')","new_contents":"#!flask\/bin\/python\nimport os\nimport sys\nif sys.platform == 'win32':\n pybabel = 'flask\\\\Scripts\\\\pybabel'\nelse:\n pybabel = 'flask\/bin\/pybabel'\nif len(sys.argv) != 2:\n print(\"usage: tr_init \")\n sys.exit(1)\nos.system(pybabel + ' extract -F babel.cfg -k lazy_gettext -o messages.pot app')\nos.system(pybabel + ' init -i messages.pot -d app\/translations -l ' + sys.argv[1])\nos.unlink('messages.pot')\n","subject":"Add parentheses to the print statement to make it Python3 compatible","message":"fix: Add parentheses to the print statement to make it Python3 compatible\n","lang":"Python","license":"bsd-3-clause","repos":"stueken\/microblog,stueken\/microblog"} {"commit":"c0633bc60dda6b81e623795f2c65a1eb0ba5933d","old_file":"blinkytape\/blinkyplayer.py","new_file":"blinkytape\/blinkyplayer.py","old_contents":"import time\n\nclass BlinkyPlayer(object):\n FOREVER = -1\n\n def __init__(self, blinkytape):\n self._blinkytape = blinkytape\n\n def play(self, animation, num_cycles = FOREVER):\n finished = self._make_finished_predicate(animation, num_cycles)\n animation.begin()\n while not finished():\n pixels = animation.next_frame()\n self._blinkytape.update(pixels)\n time.sleep(animation.frame_period_sec)\n animation.end()\n\n def _make_finished_predicate(self, animation, num_cycles):\n if num_cycles < 0 and num_cycles != self.FOREVER: raise ValueError\n if num_cycles == self.FOREVER:\n predicate = lambda: False\n else:\n self._num_frames = animation.frame_count * num_cycles\n def predicate():\n finished = self._num_frames <= 0\n self._num_frames = self._num_frames - 1\n return finished\n return predicate\n","new_contents":"import time\n\nclass BlinkyPlayer(object):\n FOREVER = -1\n\n def __init__(self, blinkytape):\n self._blinkytape = blinkytape\n\n def play(self, animation, num_cycles = FOREVER):\n finished = self._finished_predicate(animation, num_cycles)\n animation.begin()\n while not finished():\n pixels = animation.next_frame()\n self._blinkytape.update(pixels)\n time.sleep(animation.frame_period_sec)\n animation.end()\n\n def _finished_predicate(self, animation, num_cycles):\n if num_cycles < 0 and num_cycles != self.FOREVER: raise ValueError\n if num_cycles == self.FOREVER:\n predicate = self._forever_predicate()\n else:\n self._num_frames = animation.frame_count * num_cycles\n predicate = self._frame_count_predicate()\n return predicate\n\n def _forever_predicate(self):\n return lambda: False\n\n def _frame_count_predicate(self):\n def predicate():\n finished = self._num_frames <= 0\n self._num_frames = self._num_frames - 1\n return finished\n return predicate\n","subject":"Clean up BlinkyPlayer a little","message":"Clean up BlinkyPlayer a little\n","lang":"Python","license":"mit","repos":"jonspeicher\/blinkyfun"} {"commit":"5bc6f65828e9fbf9d2a5b1198a9625024fd72d6e","old_file":"weather.py","new_file":"weather.py","old_contents":"from pyowm.owm import OWM\nfrom datetime import datetime, timedelta\n\nclass WeatherManager:\n def __init__(self, key, lat, lon):\n owm = OWM(key)\n self.mgr = owm.weather_manager()\n self.lat = lat\n self.lon = lon\n self.last_updated = None\n\n def load_data(self):\n self.data = self.mgr.one_call(lat=self.lat, lon=self.lon, exclude='minutely,hourly,daily,alerts')\n self.last_updated = datetime.now()\n\n def is_cloudy(self, threshold):\n # Only update every 20 minutes at most\n if not self.last_updated or datetime.now() > self.last_updated + timedelta(minutes=20):\n self.load_data()\n return self.data.current.clouds > threshold\n","new_contents":"from pyowm.owm import OWM\nfrom datetime import datetime, timedelta\n\nclass WeatherManager:\n def __init__(self, key, lat, lon):\n owm = OWM(key)\n self.mgr = owm.weather_manager()\n self.lat = lat\n self.lon = lon\n self.last_updated = None\n\n def load_data(self):\n self.data = self.mgr.one_call(lat=self.lat, lon=self.lon, exclude='minutely,hourly,daily,alerts')\n self.last_updated = datetime.now()\n\n def is_cloudy(self, threshold):\n # Only update every 20 minutes at most\n if not self.last_updated or datetime.now() > self.last_updated + timedelta(minutes=20):\n self.load_data()\n return self.data.current.clouds >= threshold\n","subject":"Make cloud check evaluate greater than or equals","message":"Make cloud check evaluate greater than or equals\n","lang":"Python","license":"mit","repos":"Nosskirneh\/SmartRemoteControl,Nosskirneh\/SmartRemoteControl,Nosskirneh\/SmartRemoteControl,Nosskirneh\/SmartRemoteControl,Nosskirneh\/SmartRemoteControl"} {"commit":"f12fe6dacd3bd9c6f606c20406184b8ef7da47b2","old_file":"src\/dymoprint\/font_config.py","new_file":"src\/dymoprint\/font_config.py","old_contents":"import os\nfrom configparser import SafeConfigParser\n\nfrom appdirs import user_config_dir\n\nimport dymoprint_fonts\n\nfrom .constants import DEFAULT_FONT_STYLE, FLAG_TO_STYLE\nfrom .utils import die\n\n\ndef font_filename(flag):\n # The directory of the dymoprints_fonts package\n DEFAULT_FONT_DIR = os.path.dirname(dymoprint_fonts.__file__)\n\n # Default values\n style_to_file = {\n \"regular\": os.path.join(DEFAULT_FONT_DIR, \"Carlito-Regular.ttf\"),\n \"bold\": os.path.join(DEFAULT_FONT_DIR, \"Carlito-Bold.ttf\"),\n \"italic\": os.path.join(DEFAULT_FONT_DIR, \"Carlito-Italic.ttf\"),\n \"narrow\": os.path.join(DEFAULT_FONT_DIR, \"Carlito-BoldItalic.ttf\"),\n }\n\n conf = SafeConfigParser(style_to_file)\n CONFIG_FILE = os.path.join(user_config_dir(), \"dymoprint.ini\")\n if conf.read(CONFIG_FILE):\n # reading FONTS section\n if not \"FONTS\" in conf.sections():\n die('! config file \"%s\" not valid. Please change or remove.' % CONFIG_FILE)\n for style in style_to_file.keys():\n style_to_file[style] = conf.get(\"FONTS\", style)\n\n return style_to_file[FLAG_TO_STYLE.get(flag, DEFAULT_FONT_STYLE)]\n","new_contents":"import os\nfrom configparser import ConfigParser\n\nfrom appdirs import user_config_dir\n\nimport dymoprint_fonts\n\nfrom .constants import DEFAULT_FONT_STYLE, FLAG_TO_STYLE\nfrom .utils import die\n\n\ndef font_filename(flag):\n # The directory of the dymoprints_fonts package\n DEFAULT_FONT_DIR = os.path.dirname(dymoprint_fonts.__file__)\n\n # Default values\n style_to_file = {\n \"regular\": os.path.join(DEFAULT_FONT_DIR, \"Carlito-Regular.ttf\"),\n \"bold\": os.path.join(DEFAULT_FONT_DIR, \"Carlito-Bold.ttf\"),\n \"italic\": os.path.join(DEFAULT_FONT_DIR, \"Carlito-Italic.ttf\"),\n \"narrow\": os.path.join(DEFAULT_FONT_DIR, \"Carlito-BoldItalic.ttf\"),\n }\n\n conf = ConfigParser(style_to_file)\n CONFIG_FILE = os.path.join(user_config_dir(), \"dymoprint.ini\")\n if conf.read(CONFIG_FILE):\n # reading FONTS section\n if not \"FONTS\" in conf.sections():\n die('! config file \"%s\" not valid. Please change or remove.' % CONFIG_FILE)\n for style in style_to_file.keys():\n style_to_file[style] = conf.get(\"FONTS\", style)\n\n return style_to_file[FLAG_TO_STYLE.get(flag, DEFAULT_FONT_STYLE)]\n","subject":"Change SafeConfigParser to ConfigParser Closes https:\/\/github.com\/computerlyrik\/dymoprint\/pull\/34","message":"Change SafeConfigParser to ConfigParser\nCloses https:\/\/github.com\/computerlyrik\/dymoprint\/pull\/34\n","lang":"Python","license":"apache-2.0","repos":"computerlyrik\/dymoprint"} {"commit":"027e78f3e88a17e05881259d1f29d472b02d0d3a","old_file":"doc\/source\/scripts\/titles.py","new_file":"doc\/source\/scripts\/titles.py","old_contents":"import shutil\nimport os\nimport re\n\nwork = os.getcwd()\nfound = []\nregex = re.compile(r'pydarkstar\\.(.*)\\.rst')\nfor root, dirs, files in os.walk(work):\n for f in files:\n m = regex.match(f)\n if m:\n found.append((root, f))\n\nfor root, f in found:\n path = os.path.join(root, f)\n with open(path, 'r') as handle:\n lines = handle.readlines()\n\n with open(path, 'w') as handle:\n for i, line in enumerate(lines):\n if i == 0:\n line = re.sub(r'\\s+package$', '', line)\n line = re.sub(r'\\s+module$', '', line)\n line = re.sub(r'^pydarkstar\\.', '', line)\n\n #print('{:2d} {}'.format(i, line.rstrip()))\n handle.write(line)\n #print('')\n\n# fix main file\nwith open('pydarkstar.rst', 'r') as handle:\n lines = handle.readlines()\n\nz = 0\nwith open('pydarkstar.rst', 'w') as handle:\n for i, line in enumerate(lines):\n if i == 0:\n line = re.sub(r'\\s+package$', '', line)\n\n if re.match(r'^\\s\\s\\spydarkstar.*$', line):\n handle.write(' {}'.format(line.lstrip()))\n else:\n handle.write(line)\n\n if '.. toctree::' in line:\n if z:\n handle.write(' :maxdepth: {}\\n'.format(z))\n else:\n z += 1\n\n","new_contents":"import shutil\nimport os\nimport re\n\nwork = os.getcwd()\nfound = []\nregex = re.compile(r'pydarkstar\\.(.*)\\.rst')\nfor root, dirs, files in os.walk(work):\n for f in files:\n m = regex.match(f)\n if m:\n found.append((root, f))\n\nfor root, f in found:\n path = os.path.join(root, f)\n with open(path, 'r') as handle:\n lines = handle.readlines()\n\n with open(path, 'w') as handle:\n for i, line in enumerate(lines):\n if i == 0:\n line = re.sub(r'\\s+package$', '', line)\n line = re.sub(r'\\s+module$', '', line)\n line = re.sub(r'^pydarkstar\\.', '', line)\n\n #print('{:2d} {}'.format(i, line.rstrip()))\n handle.write(line)\n #print('')\n\n# fix main file\nwith open('pydarkstar.rst', 'r') as handle:\n lines = handle.readlines()\n\nz = 0\nwith open('pydarkstar.rst', 'w') as handle:\n for i, line in enumerate(lines):\n if i == 0:\n line = re.sub(r'\\s+package$', '', line)\n\n if re.match(r'^\\s\\s\\spydarkstar.*$', line):\n handle.write(' {}'.format(line.lstrip()))\n else:\n handle.write(line)\n","subject":"Change to 3 spaces in front of toctree elements","message":"Change to 3 spaces in front of toctree elements\n","lang":"Python","license":"mit","repos":"AdamGagorik\/pydarkstar"} {"commit":"72f28cfa2723faaa7f7ed2b165fd99b214bc67c9","old_file":"MeetingMinutes.py","new_file":"MeetingMinutes.py","old_contents":"import sublime, sublime_plugin\nimport os\nimport re\n\nfrom .mistune import markdown\n\n\nclass CreateMinuteCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit):\n\t\tregion = sublime.Region(0, self.view.size())\n\t\tmd_source = self.view.substr(region)\n\t\tmd_source.encode(encoding='UTF-8',errors='strict')\n\t\thtml_source = '<\/head>' + markdown(md_source) + '<\/body><\/html>'\n\t\t\n\t\tfile_name = self.view.file_name()\n\t\thtml_file = self.change_extension(file_name, \".html\")\n\t\twith open(html_file, 'w+') as file_:\n\t\t\tfile_.write(html_source)\n\n\t\tprint(file_name)\n\t\tprint(html_file)\n\n\tdef change_extension(self,file_name, new_ext):\n\t\tf, ext = os.path.splitext(file_name)\n\t\tf += new_ext\n\n\t\treturn f\n\n\n","new_contents":"import sublime, sublime_plugin\nimport os\nimport re\n\nfrom .mistune import markdown\n\nHTML_START = '<\/head>'\nHTML_END = '<\/body><\/html>'\n\nclass CreateMinuteCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit):\n\t\tregion = sublime.Region(0, self.view.size())\n\t\tmd_source = self.view.substr(region)\n\t\tmd_source.encode(encoding='UTF-8',errors='strict')\n\t\thtml_source = HTML_START + markdown(md_source) + HTML_END\n\t\t\n\t\tfile_name = self.view.file_name()\n\t\thtml_file = self.change_extension(file_name, \".html\")\n\t\twith open(html_file, 'w+') as file_:\n\t\t\tfile_.write(html_source)\n\n\t\tprint(file_name)\n\t\tprint(html_file)\n\n\tdef change_extension(self,file_name, new_ext):\n\t\tf, ext = os.path.splitext(file_name)\n\t\tf += new_ext\n\n\t\treturn f\n\n\n","subject":"Create variables for HTML start and end.","message":"Create variables for HTML start and end.\n","lang":"Python","license":"mit","repos":"Txarli\/sublimetext-meeting-minutes,Txarli\/sublimetext-meeting-minutes"} {"commit":"5ede88c91f61b4aeb3a1e9b55e6b7836cf805255","old_file":"django_filepicker\/utils.py","new_file":"django_filepicker\/utils.py","old_contents":"import re\nimport urllib\nfrom os.path import basename\n\nfrom django.core.files import File\n\n\nclass FilepickerFile(object):\n filepicker_url_regex = re.compile(\n r'https?:\\\/\\\/www.filepicker.io\\\/api\\\/file\\\/.*')\n\n def __init__(self, url):\n if not self.filepicker_url_regex.match(url):\n raise ValueError('Not a filepicker.io URL: %s' % url)\n self.url = url\n\n def get_file(self):\n '''\n Downloads the file from filepicker.io and returns a\n Django File wrapper object\n '''\n filename, header = urllib.urlretrieve(self.url)\n name = basename(filename)\n disposition = header.get('Content-Disposition')\n if disposition:\n name = disposition.rpartition(\"filename=\")[2].strip('\" ')\n\n return File(open(filename, 'r'), name=name)\n","new_contents":"import re\nimport urllib\nimport os\n\nfrom django.core.files import File\n\n\nclass FilepickerFile(object):\n filepicker_url_regex = re.compile(\n r'https?:\\\/\\\/www.filepicker.io\\\/api\\\/file\\\/.*')\n\n def __init__(self, url):\n if not self.filepicker_url_regex.match(url):\n raise ValueError('Not a filepicker.io URL: %s' % url)\n self.url = url\n\n def get_file(self):\n '''\n Downloads the file from filepicker.io and returns a\n Django File wrapper object\n '''\n # clean up any old downloads that are still hanging around\n self.cleanup()\n\n # The temporary file will be created in a directory set by the\n # environment (TEMP_DIR, TEMP or TMP)\n self.filename, header = urllib.urlretrieve(self.url)\n name = os.path.basename(self.filename)\n disposition = header.get('Content-Disposition')\n if disposition:\n name = disposition.rpartition(\"filename=\")[2].strip('\" ')\n\n self.tempfile = open(self.filename, 'r')\n return File(self.tempfile, name=name)\n\n def cleanup(self):\n '''\n Removes any downloaded objects and closes open files.\n '''\n if hasattr(self, 'tempfile'):\n self.tempfile.close()\n delattr(self, 'tempfile')\n\n if hasattr(self, 'filename'):\n # the file might have been moved in the meantime so\n # check first\n if os.path.exists(self.filename):\n os.remove(self.filename)\n delattr(self, 'filename')\n\n def __enter__(self):\n '''\n Allow FilepickerFile to be used as a context manager as such:\n\n with FilepickerFile(url) as f:\n model.field.save(f.name, f.)\n '''\n return self.get_file()\n\n def __exit__(self, *args):\n self.cleanup()\n\n def __del__(self):\n self.cleanup()\n","subject":"Add context manager and destructor for cleanup","message":"Add context manager and destructor for cleanup\n\nWhen exiting the context or calling cleanup() explicitly,\nthe temporary file created after downloading is removed and\nany open files closed.\n","lang":"Python","license":"mit","repos":"FundedByMe\/filepicker-django,FundedByMe\/filepicker-django,filepicker\/filepicker-django,filepicker\/filepicker-django"} {"commit":"13d0b4b50b2eaaf5c557576b7b45a378d901c49c","old_file":"src\/zeit\/cms\/testcontenttype\/interfaces.py","new_file":"src\/zeit\/cms\/testcontenttype\/interfaces.py","old_contents":"# Copyright (c) 2007-2011 gocept gmbh & co. kg\n# See also LICENSE.txt\n# $Id$\n\"\"\"Interface definitions for the test content type.\"\"\"\n\n\nimport zope.interface\n\n\nclass ITestContentType(zope.interface.Interface):\n \"\"\"A type for testing.\"\"\"\n\n\nITestContentType.setTaggedValue('zeit.cms.type', 'testcontenttype')\n","new_contents":"# Copyright (c) 2007-2011 gocept gmbh & co. kg\n# See also LICENSE.txt\n# $Id$\n\"\"\"Interface definitions for the test content type.\"\"\"\n\n\nimport zope.interface\n\n\nclass ITestContentType(zope.interface.Interface):\n \"\"\"A type for testing.\"\"\"\n","subject":"Remove superfluous type annotation, it's done by the TypeGrokker now","message":"Remove superfluous type annotation, it's done by the TypeGrokker now\n","lang":"Python","license":"bsd-3-clause","repos":"ZeitOnline\/zeit.cms,ZeitOnline\/zeit.cms,ZeitOnline\/zeit.cms,ZeitOnline\/zeit.cms"} {"commit":"8f993412a0110085fee10331daecfb3d36973518","old_file":"__init__.py","new_file":"__init__.py","old_contents":"###\n# Copyright (c) 2012, spline\n# All rights reserved.\n#\n#\n###\n\n\"\"\"\nAdd a description of the plugin (to be presented to the user inside the wizard)\nhere. This should describe *what* the plugin does.\n\"\"\"\n\nimport supybot\nimport supybot.world as world\n\n# Use this for the version of this plugin. You may wish to put a CVS keyword\n# in here if you're keeping the plugin in CVS or some similar system.\n__version__ = \"\"\n\n# XXX Replace this with an appropriate author or supybot.Author instance.\n__author__ = supybot.authors.unknown\n\n# This is a dictionary mapping supybot.Author instances to lists of\n# contributions.\n__contributors__ = {}\n\n# This is a url where the most recent plugin package can be downloaded.\n__url__ = '' # 'http:\/\/supybot.com\/Members\/yourname\/Scores\/download'\n\nimport config\nimport plugin\nreload(plugin) # In case we're being reloaded.\n# Add more reloads here if you add third-party modules and want them to be\n# reloaded when this plugin is reloaded. Don't forget to import them as well!\n\nif world.testing:\n import test\n\nClass = plugin.Class\nconfigure = config.configure\n\n\n# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:\n","new_contents":"###\n# Copyright (c) 2012, spline\n# All rights reserved.\n#\n#\n###\n\n\"\"\"\nAdd a description of the plugin (to be presented to the user inside the wizard)\nhere. This should describe *what* the plugin does.\n\"\"\"\n\nimport supybot\nimport supybot.world as world\n\n# Use this for the version of this plugin. You may wish to put a CVS keyword\n# in here if you're keeping the plugin in CVS or some similar system.\n__version__ = \"\"\n\n# XXX Replace this with an appropriate author or supybot.Author instance.\n__author__ = supybot.authors.unknown\n\n# This is a dictionary mapping supybot.Author instances to lists of\n# contributions.\n__contributors__ = {}\n\n# This is a url where the most recent plugin package can be downloaded.\n__url__ = '' # 'http:\/\/supybot.com\/Members\/yourname\/Scores\/download'\n\nimport config\nimport plugin\nreload(config)\nreload(plugin) # In case we're being reloaded.\n# Add more reloads here if you add third-party modules and want them to be\n# reloaded when this plugin is reloaded. Don't forget to import them as well!\n\nif world.testing:\n import test\n\nClass = plugin.Class\nconfigure = config.configure\n\n\n# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:\n","subject":"Add reload to init for config","message":"Add reload to init for config\n","lang":"Python","license":"mit","repos":"reticulatingspline\/Scores,cottongin\/Scores"} {"commit":"f447e8fa50770d133d53e69477292b3925203c64","old_file":"modular_blocks\/models.py","new_file":"modular_blocks\/models.py","old_contents":"from django.db import models\n\nfrom .fields import ListTextField\n\n\nclass TwoModularColumnsMixin(models.Model):\n sidebar_left = ListTextField()\n sidebar_right = ListTextField()\n\n class Meta:\n abstract = True\n","new_contents":"from django.db import models\n\nfrom .fields import ListTextField\n\n\nclass TwoModularColumnsMixin(models.Model):\n sidebar_left = ListTextField(\n blank=True,\n null=True,\n )\n sidebar_right = ListTextField(\n lank=True,\n null=True,\n )\n\n class Meta:\n abstract = True\n","subject":"Add null and blank to sidebars","message":"Add null and blank to sidebars\n","lang":"Python","license":"agpl-3.0","repos":"rezometz\/django-modular-blocks,rezometz\/django-modular-blocks,rezometz\/django-modular-blocks"} {"commit":"b63b22678a005baa6195854b65cc1828061febba","old_file":"vx\/mode.py","new_file":"vx\/mode.py","old_contents":"import vx\n\nimport os.path\n\ndef mode_from_filename(file):\n root, ext = os.path.splitext(file)\n ext = ext if ext else root\n\n mode = None\n if ext == '.c':\n return c_mode\n\nclass mode:\n def __init__(self, window):\n self.breaks = ('_', ' ', '\\n', '\\t')\n self.keywords = ()\n\nclass python_mode(mode):\n def __init__(self, window):\n super().__init__(window)\n\n self.breaks = ('_', ' ', '\\n', '\\t', '(', ')', '{', '}', '.', ',', '#')\n\n self.keywords = ('return', 'for', 'while', 'break', 'continue', 'def')\n\nclass c_mode(mode):\n def __init__(self, window):\n super().__init__(window)\n\n self.breaks = ('_', ' ', '\\n', '\\t', '(', ')', '<', '>', '.', ',', '#')\n\n self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'\"(?:[^\"\\\\]|\\\\.)*\"')\n","new_contents":"import vx\n\nimport os.path\n\ndef mode_from_filename(file):\n root, ext = os.path.splitext(file)\n ext = ext if ext else root\n\n mode = None\n if ext == '.c':\n return c_mode\n elif ext == '.py':\n return python_mode\n\nclass mode:\n def __init__(self, window):\n self.breaks = ('_', ' ', '\\n', '\\t')\n self.keywords = ()\n\nclass python_mode(mode):\n def __init__(self, window):\n super().__init__(window)\n\n self.breaks = ('_', ' ', '\\n', '\\t', '(', ')', '{', '}', '.', ',', '#')\n\n self.keywords = ('class', 'return', 'for', 'while', 'break', 'continue', 'def', 'from', 'import')\n\nclass c_mode(mode):\n def __init__(self, window):\n super().__init__(window)\n\n self.breaks = ('_', ' ', '\\n', '\\t', '(', ')', '<', '>', '.', ',', '#')\n\n self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'\"(?:[^\"\\\\]|\\\\.)*\"')\n","subject":"Add .py extension handling and more python keywords","message":"Add .py extension handling and more python keywords\n","lang":"Python","license":"mit","repos":"philipdexter\/vx,philipdexter\/vx"} {"commit":"f62980f99654b22930cac6716410b145b590221f","old_file":"Lib\/lib-tk\/FixTk.py","new_file":"Lib\/lib-tk\/FixTk.py","old_contents":"import sys, os\nv = os.path.join(sys.prefix, \"tcl\", \"tcl8.3\")\nif os.path.exists(os.path.join(v, \"init.tcl\")):\n os.environ[\"TCL_LIBRARY\"] = v\n","new_contents":"import sys, os, _tkinter\nver = str(_tkinter.TCL_VERSION)\nv = os.path.join(sys.prefix, \"tcl\", \"tcl\"+ver)\nif os.path.exists(os.path.join(v, \"init.tcl\")):\n os.environ[\"TCL_LIBRARY\"] = v\n","subject":"Work the Tcl version number in the path we search for.","message":"Work the Tcl version number in the path we search for.\n","lang":"Python","license":"mit","repos":"sk-\/python2.7-type-annotator,sk-\/python2.7-type-annotator,sk-\/python2.7-type-annotator"} {"commit":"49b24fe2c524923e200ce8495055b0b59d83eb6d","old_file":"__init__.py","new_file":"__init__.py","old_contents":"# Copyright (c) 2015 Ultimaker B.V.\n# Cura is released under the terms of the AGPLv3 or higher.\nfrom . import OctoPrintOutputDevicePlugin\nfrom . import DiscoverOctoPrintAction\nfrom UM.i18n import i18nCatalog\ncatalog = i18nCatalog(\"cura\")\n\ndef getMetaData():\n return {\n \"type\": \"extension\",\n \"plugin\": {\n \"name\": \"OctoPrint connection\",\n \"author\": \"fieldOfView\",\n \"version\": \"2.4\",\n \"description\": catalog.i18nc(\"@info:whatsthis\", \"Allows sending prints to OctoPrint and monitoring the progress\"),\n \"api\": 3\n }\n }\n\ndef register(app):\n return {\n \"output_device\": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(),\n \"machine_action\": DiscoverOctoPrintAction.DiscoverOctoPrintAction()\n }","new_contents":"# Copyright (c) 2015 Ultimaker B.V.\n# Cura is released under the terms of the AGPLv3 or higher.\nfrom . import OctoPrintOutputDevicePlugin\nfrom . import DiscoverOctoPrintAction\nfrom UM.i18n import i18nCatalog\ncatalog = i18nCatalog(\"cura\")\n\ndef getMetaData():\n return {\n \"type\": \"extension\",\n \"plugin\": {\n \"name\": \"OctoPrint connection\",\n \"author\": \"fieldOfView\",\n \"version\": \"master\",\n \"description\": catalog.i18nc(\"@info:whatsthis\", \"Allows sending prints to OctoPrint and monitoring the progress\"),\n \"api\": 3\n }\n }\n\ndef register(app):\n return {\n \"output_device\": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(),\n \"machine_action\": DiscoverOctoPrintAction.DiscoverOctoPrintAction()\n }","subject":"Set plugin version to \"master\" to show which Cura branch this plugin branch should work with","message":"Set plugin version to \"master\" to show which Cura branch this plugin branch should work with\n","lang":"Python","license":"agpl-3.0","repos":"fieldOfView\/OctoPrintPlugin"} {"commit":"1c43affbd82f68ed8956cd407c494ff46dab9203","old_file":"examples\/IPLoM_example.py","new_file":"examples\/IPLoM_example.py","old_contents":"from pygraphc.misc.IPLoM import *\nfrom pygraphc.evaluation.ExternalEvaluation import *\n\n# set input path\nip_address = '161.166.232.17'\nstandard_path = '\/home\/hudan\/Git\/labeled-authlog\/dataset\/Hofstede2014\/dataset1\/' + ip_address\nstandard_file = standard_path + 'auth.log.anon.labeled'\nanalyzed_file = 'auth.log.anon'\nprediction_file = 'iplom-result-' + ip_address + '.txt'\nOutputPath = '.\/result'\npara = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath)\n\n# call IPLoM and get clusters\nmyparser = IPLoM(para)\ntime = myparser.main_process()\nclusters = myparser.get_clusters()\noriginal_logs = myparser.logs\n\n# set cluster label to get evaluation metrics\nExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file)\nhomogeneity_completeness_vmeasure = ExternalEvaluation.get_homogeneity_completeness_vmeasure(standard_file,\n prediction_file)\n# print evaluation result\nprint homogeneity_completeness_vmeasure\nprint ('The running time of IPLoM is', time)\n","new_contents":"from pygraphc.misc.IPLoM import *\nfrom pygraphc.evaluation.ExternalEvaluation import *\n\n# set input path\ndataset_path = '\/home\/hudan\/Git\/labeled-authlog\/dataset\/Hofstede2014\/dataset1_perday\/'\ngroundtruth_file = dataset_path + 'Dec 1.log.labeled'\nanalyzed_file = 'Dec 1.log'\nOutputPath = '\/home\/hudan\/Git\/pygraphc\/result\/misc\/'\nprediction_file = OutputPath + 'Dec 1.log.perline'\npara = Para(path=dataset_path, logname=analyzed_file, save_path=OutputPath)\n\n# call IPLoM and get clusters\nmyparser = IPLoM(para)\ntime = myparser.main_process()\nclusters = myparser.get_clusters()\noriginal_logs = myparser.logs\n\n# set cluster label to get evaluation metrics\nExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file)\n\n# get evaluation of clustering performance\nar = ExternalEvaluation.get_adjusted_rand(groundtruth_file, prediction_file)\nami = ExternalEvaluation.get_adjusted_mutual_info(groundtruth_file, prediction_file)\nnmi = ExternalEvaluation.get_normalized_mutual_info(groundtruth_file, prediction_file)\nh = ExternalEvaluation.get_homogeneity(groundtruth_file, prediction_file)\nc = ExternalEvaluation.get_completeness(groundtruth_file, prediction_file)\nv = ExternalEvaluation.get_vmeasure(groundtruth_file, prediction_file)\n\n# print evaluation result\nprint ar, ami, nmi, h, c, v\nprint ('The running time of IPLoM is', time)\n","subject":"Edit path and external evaluation","message":"Edit path and external evaluation\n","lang":"Python","license":"mit","repos":"studiawan\/pygraphc"} {"commit":"6e1126fe9a8269ff4489ee338000afc852bce922","old_file":"oidc_apis\/id_token.py","new_file":"oidc_apis\/id_token.py","old_contents":"import inspect\n\nfrom .scopes import get_userinfo_by_scopes\n\n\ndef process_id_token(payload, user, scope=None):\n if scope is None:\n # HACK: Steal the scope argument from the locals dictionary of\n # the caller, since it was not passed to us\n scope = inspect.stack()[1][0].f_locals.get('scope', [])\n\n payload.update(get_userinfo_by_scopes(user, scope))\n return payload\n","new_contents":"import inspect\n\nfrom .scopes import get_userinfo_by_scopes\n\n\ndef process_id_token(payload, user, scope=None):\n if scope is None:\n # HACK: Steal the scope argument from the locals dictionary of\n # the caller, since it was not passed to us\n scope = inspect.stack()[1][0].f_locals.get('scope', [])\n\n payload.update(get_userinfo_by_scopes(user, scope))\n payload['preferred_username'] = user.username\n return payload\n","subject":"Add username to ID Token","message":"Add username to ID Token\n","lang":"Python","license":"mit","repos":"mikkokeskinen\/tunnistamo,mikkokeskinen\/tunnistamo"} {"commit":"b47e3677120b9b2d64d38b48b0382dc7986a1b82","old_file":"opps\/core\/__init__.py","new_file":"opps\/core\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\n\n\n\ntrans_app_label = _('Opps')\nsettings.INSTALLED_APPS += ('opps.article',\n 'opps.image',\n 'opps.channel',\n 'opps.source',\n 'redactor',\n 'tagging',)\n\nsettings.REDACTOR_OPTIONS = {'lang': 'en'}\nsettings.REDACTOR_UPLOAD = 'uploads\/'\n","new_contents":"# -*- coding: utf-8 -*-\nfrom django.utils.translation import ugettext_lazy as _\n\n\n\ntrans_app_label = _('Opps')\n","subject":"Remove installed app on init opps core","message":"Remove installed app on init opps core\n","lang":"Python","license":"mit","repos":"YACOWS\/opps,williamroot\/opps,jeanmask\/opps,williamroot\/opps,williamroot\/opps,jeanmask\/opps,opps\/opps,YACOWS\/opps,jeanmask\/opps,opps\/opps,williamroot\/opps,jeanmask\/opps,opps\/opps,YACOWS\/opps,opps\/opps,YACOWS\/opps"} {"commit":"52d15d09ed079d1b8598f314524066b56273af3d","old_file":"addie\/_version.py","new_file":"addie\/_version.py","old_contents":"\n# This file was generated by 'versioneer.py' (0.15) from\n# revision-control system data, or from the parent directory name of an\n# unpacked source archive. Distribution tarballs contain a pre-generated copy\n# of this file.\n\nimport json\nimport sys\n\nversion_json = '''\n{\n \"dirty\": false,\n \"error\": null,\n \"full-revisionid\": \"aaeac9708788e1b02d6a763b86333eff9bad7122\",\n \"version\": \"5.0.4\"\n}\n''' # END VERSION_JSON\n\n\ndef get_versions():\n return json.loads(version_json)\n","new_contents":"\n# This file was generated by 'versioneer.py' (0.15) from\n# revision-control system data, or from the parent directory name of an\n# unpacked source archive. Distribution tarballs contain a pre-generated copy\n# of this file.\n\nimport json\n\nversion_json = '''\n{\n \"dirty\": false,\n \"error\": null,\n \"full-revisionid\": \"aaeac9708788e1b02d6a763b86333eff9bad7122\",\n \"version\": \"5.0.4\"\n}\n''' # END VERSION_JSON\n\n\ndef get_versions():\n return json.loads(version_json)\n","subject":"Remove sys import in versioneer file","message":"Remove sys import in versioneer file\n","lang":"Python","license":"mit","repos":"neutrons\/FastGR,neutrons\/FastGR,neutrons\/FastGR"} {"commit":"25a97de30fcc9cddd7f58cd25584fd726f0cc8e4","old_file":"guild\/commands\/packages_list.py","new_file":"guild\/commands\/packages_list.py","old_contents":"# Copyright 2017-2020 TensorHub, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport click\n\nfrom guild import click_util\n\n\n@click.command(\"list, ls\")\n@click.argument(\"terms\", metavar=\"[TERM]...\", nargs=-1)\n@click.option(\"-a\", \"--all\", help=\"Show all packages.\", is_flag=True)\n@click_util.use_args\ndef list_packages(args):\n \"\"\"List installed packages.\n\n Specify one or more `TERM` arguments to show packages matching any\n of the specified values.\n\n \"\"\"\n from . import packages_impl\n\n packages_impl.list_packages(args)\n","new_contents":"# Copyright 2017-2020 TensorHub, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport click\n\nfrom guild import click_util\n\n\n@click.command(\"list, ls\")\n@click.argument(\"terms\", metavar=\"[TERM]...\", nargs=-1)\n@click.option(\"-a\", \"--all\", help=\"Show all installed Python packages.\", is_flag=True)\n@click_util.use_args\ndef list_packages(args):\n \"\"\"List installed packages.\n\n Specify one or more `TERM` arguments to show packages matching any\n of the specified values.\n\n \"\"\"\n from . import packages_impl\n\n packages_impl.list_packages(args)\n","subject":"Clarify meaning of --all option for packages command","message":"Clarify meaning of --all option for packages command\n","lang":"Python","license":"apache-2.0","repos":"guildai\/guild,guildai\/guild,guildai\/guild,guildai\/guild"} {"commit":"ccdeb23eb54191913a97b48907e0738f6969ce58","old_file":"tests\/factories\/config.py","new_file":"tests\/factories\/config.py","old_contents":"# -*- coding: utf-8 -*-\n# Copyright (c) 2018 The Pycroft Authors. See the AUTHORS file.\n# This file is part of the Pycroft project and licensed under the terms of\n# the Apache License, Version 2.0. See the LICENSE file for details.\nfrom factory import SubFactory\n\nfrom pycroft.model.config import Config\nfrom .base import BaseFactory\nfrom .finance import AccountFactory, BankAccountFactory\nfrom .property import PropertyGroupFactory, MemberPropertyGroupFactory\n\n\nclass ConfigFactory(BaseFactory):\n \"\"\"This is a dummy Config factory, Referencing PropertyGroups with\n no a-priori property relationships and arbitrary Accounts.\n \"\"\"\n class Meta:\n model = Config\n\n id = 1\n\n # `PropertyGroup`s\n member_group = SubFactory(MemberPropertyGroupFactory)\n network_access_group = SubFactory(PropertyGroupFactory)\n violation_group = SubFactory(PropertyGroupFactory)\n cache_group = SubFactory(PropertyGroupFactory)\n traffic_limit_exceeded_group = SubFactory(PropertyGroupFactory)\n external_group = SubFactory(PropertyGroupFactory)\n payment_in_default_group = SubFactory(PropertyGroupFactory)\n blocked_group = SubFactory(PropertyGroupFactory)\n caretaker_group = SubFactory(PropertyGroupFactory)\n treasurer_group = SubFactory(PropertyGroupFactory)\n\n # `Account`s\n membership_fee_account = SubFactory(AccountFactory)\n membership_fee_bank_account = SubFactory(BankAccountFactory)\n","new_contents":"# -*- coding: utf-8 -*-\n# Copyright (c) 2018 The Pycroft Authors. See the AUTHORS file.\n# This file is part of the Pycroft project and licensed under the terms of\n# the Apache License, Version 2.0. See the LICENSE file for details.\nfrom factory import SubFactory\n\nfrom pycroft.model.config import Config\nfrom .base import BaseFactory\nfrom .finance import AccountFactory, BankAccountFactory\nfrom .property import PropertyGroupFactory, MemberPropertyGroupFactory\n\n\nclass ConfigFactory(BaseFactory):\n \"\"\"This is a dummy Config factory, Referencing PropertyGroups with\n no a-priori property relationships and arbitrary Accounts.\n \"\"\"\n class Meta:\n model = Config\n\n id = 1\n\n # `PropertyGroup`s\n member_group = SubFactory(MemberPropertyGroupFactory)\n network_access_group = SubFactory(PropertyGroupFactory)\n violation_group = SubFactory(PropertyGroupFactory)\n cache_group = SubFactory(PropertyGroupFactory)\n traffic_limit_exceeded_group = SubFactory(PropertyGroupFactory)\n external_group = SubFactory(PropertyGroupFactory)\n payment_in_default_group = SubFactory(PropertyGroupFactory,\n granted=frozenset((\"payment_in_default\",)),\n denied=frozenset((\"network_access\", \"userwww\", \"userdb\")))\n blocked_group = SubFactory(PropertyGroupFactory)\n caretaker_group = SubFactory(PropertyGroupFactory)\n treasurer_group = SubFactory(PropertyGroupFactory)\n\n # `Account`s\n membership_fee_account = SubFactory(AccountFactory)\n membership_fee_bank_account = SubFactory(BankAccountFactory)\n","subject":"Add correct properties for payment_in_default test group","message":"Add correct properties for payment_in_default test group\n\n","lang":"Python","license":"apache-2.0","repos":"agdsn\/pycroft,agdsn\/pycroft,agdsn\/pycroft,agdsn\/pycroft,agdsn\/pycroft"} {"commit":"fb9c56381d259de7d1765ca0e058f82d61e4e975","old_file":"examples\/ellipses_FreeCAD.py","new_file":"examples\/ellipses_FreeCAD.py","old_contents":"from __future__ import division\nimport numpy as np\nimport FreeCAD as FC\nimport Part\nimport Draft\nimport os\n\n\ndoc = FC.newDocument(\"ellipses\")\nfolder = os.path.dirname(__file__) + \".\\..\"\nfname = folder + \"\/vor_ellipses.txt\"\ndata = np.loadtxt(fname)\nshapes = []\narea = 0\nfor ellipse in data:\n cx, cy, b, a, ang = ellipse\n ang = ang*np.pi\/180\n place = FC.Placement()\n place.Rotation = (0, 0, np.sin(ang\/2), np.cos(ang\/2))\n place.Base = FC.Vector(100*cx, 100*cy, 0)\n ellipse = Draft.makeEllipse(100*a, 100*b, placement=place)\n shapes.append(ellipse)\n area = area + np.pi*a*b*100*100\n\nprint area, \" \", area\/500\/70\npart = Part.makeCompound(shapes)","new_contents":"from __future__ import division\nimport numpy as np\nimport FreeCAD as FC\nimport Part\nimport Draft\nimport os\n\n\ndoc = FC.newDocument(\"ellipses\")\nfolder = os.path.dirname(__file__) #+ \"\/..\"\nfname = folder + \"\/vor_ellipses.txt\"\ndata = np.loadtxt(fname)\nshapes = []\narea = 0\nradii = []\nfor ellipse in data:\n cx, cy, b, a, ang = ellipse\n ang = ang*np.pi\/180\n place = FC.Placement()\n place.Rotation = (0, 0, np.sin(ang\/2), np.cos(ang\/2))\n place.Base = FC.Vector(100*cx, 100*cy, 0)\n ellipse = Draft.makeEllipse(100*a, 100*b, placement=place)\n radii.append([100*a, 100*b])\n shapes.append(ellipse)\n area = area + np.pi*a*b*100*100\n\nprint \"area: %g \" % (area\/500\/70)\nprint \"radius: %g +\/- %g\" % (np.mean(radii), np.std(radii))\npart = Part.makeCompound(shapes)\n","subject":"Add radii mean and standard deviation","message":"Add radii mean and standard deviation\n","lang":"Python","license":"mit","repos":"nicoguaro\/ellipse_packing"} {"commit":"08de3f0bf326e8625462d9dbdb7297d8749bc416","old_file":"examples\/joystick_example.py","new_file":"examples\/joystick_example.py","old_contents":"#!\/usr\/bin\/env python3\n\"\"\"This example shows how to use the Joystick Click wrapper of the LetMeCreate.\n\nIt continuously reads the position of the joystick, prints it in the terminal\nand displays a pattern on the LED's based on the x coordinate.\n\nThe Joystick Click must be inserted in Mikrobus 1 before running this program.\n\"\"\"\n\nfrom letmecreate.core import i2c\nfrom letmecreate.core import led\nfrom letmecreate.click import joystick\n\nOFFSET = 98\nMAXIMUM = OFFSET2\n\ndef get_led_mask(perc):\n\tdiv = int((1. - perc)led.LED_CNT)\n\tif div > led.LED_CNT:\n\t\tdiv = led.LED_CNT\n\n\tmask = 0\n\tfor i in range(div):\n\t\tmask |= (1 << i)\n\n\treturn mask\n\ni2c.init()\nled.init()\n\nwhile True:\n\tpos = joystick.get_position()\n\tprint('{} {}'.format(pos[0], pos[1]))\n\tmask = get_led_mask(float(pos[0] + OFFSET)\/float(MAXIMUM))\n\tled.switch_on(mask)\n\tled.switch_off(~mask)\n\ni2c.release()\nled.release()\n","new_contents":"#!\/usr\/bin\/env python3\n\"\"\"This example shows how to use the Joystick Click wrapper of the LetMeCreate.\n\nIt continuously reads the position of the joystick, prints it in the terminal\nand displays a pattern on the LED's based on the x coordinate.\n\nThe Joystick Click must be inserted in Mikrobus 1 before running this program.\n\"\"\"\n\nfrom letmecreate.core import i2c\nfrom letmecreate.core import led\nfrom letmecreate.click import joystick\n\nOFFSET = 98\nMAXIMUM = OFFSET2\n\ndef get_led_mask(perc):\n div = int((1. - perc)led.LED_CNT)\n if div > led.LED_CNT:\n div = led.LED_CNT\n\n mask = 0\n for i in range(div):\n mask |= (1 << i)\n\n return mask\n\ni2c.init()\nled.init()\n\nwhile True:\n pos = joystick.get_position()\n print('{} {}'.format(pos[0], pos[1]))\n mask = get_led_mask(float(pos[0] + OFFSET)\/float(MAXIMUM))\n led.switch_on(mask)\n led.switch_off(~mask)\n\ni2c.release()\nled.release()\n","subject":"Replace tabs by space in example","message":"joystick: Replace tabs by space in example\n\nSigned-off-by: Francois Berder <59eaf4bb0211c66c3d7532da6d77ecf42a779d82@outlook.fr>\n","lang":"Python","license":"bsd-3-clause","repos":"francois-berder\/PyLetMeCreate"} {"commit":"98a4cd76ce9ecb81675ebaa29b249a8d80347e0d","old_file":"zc-list.py","new_file":"zc-list.py","old_contents":"#!\/usr\/bin\/env python\n\nimport client_wrap\n\nKEY_LONG = \"key1\"\nDATA_LONG = 1024\n\nKEY_DOUBLE = \"key2\"\nDATA_DOUBLE = 100.53\n\nKEY_STRING = \"key3\"\nDATA_STRING = \"test data\"\n\ndef init_data(client):\n client.WriteLong(KEY_LONG, DATA_LONG)\n client.WriteDouble(KEY_DOUBLE, DATA_DOUBLE)\n client.WriteString(KEY_STRING, DATA_STRING)\n\ndef check_data(client):\n assert DATA_LONG == client.ReadLong(KEY_LONG)\n assert DATA_DOUBLE == client.ReadDouble(KEY_DOUBLE)\n assert DATA_STRING == client.ReadString(KEY_STRING)\n\ndef main():\n client = client_wrap.ClientWrap(\"get_test.log\", \"ipc:\/\/\/var\/run\/zero-cache\/0\", 0)\n init_data(client)\n check_data(client)\n\nif __name__ == \"__main__\":\n main()\n","new_contents":"#!\/usr\/bin\/env python\n\nimport client_wrap\n\ndef main():\n client = client_wrap.ClientWrap(\"get_test.log\", \"ipc:\/\/\/var\/run\/zero-cache\/0\", 0)\n\n key_str = client.GetKeys()\n keys = key_str.split (';')\n del keys[-1]\n\n if len(keys) == 0:\n return\n\n print keys\n\nif __name__ == \"__main__\":\n main()\n","subject":"Implement displaying of the current key list","message":"Implement displaying of the current key list\n","lang":"Python","license":"agpl-3.0","repos":"ellysh\/zero-cache-utils,ellysh\/zero-cache-utils"} {"commit":"1f6c830e68aede8a2267b5749b911d87801f9e5b","old_file":"setup.py","new_file":"setup.py","old_contents":"from setuptools import setup\n\n\nsetup(\n name='django-setmagic',\n version='0.2',\n author='Evandro Myller',\n author_email='emyller@7ws.co',\n description='Magically editable settings for winged pony lovers',\n url='https:\/\/github.com\/7ws\/django-setmagic',\n install_requires=[\n 'django >= 1.5',\n ],\n packages=['setmagic'],\n keywords=['django', 'settings'],\n classifiers=[\n 'Framework :: Django',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.1',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Topic :: Software Development',\n ],\n)\n","new_contents":"from setuptools import setup\n\n\nsetup(\n name='django-setmagic',\n version='0.2.1',\n author='Evandro Myller',\n author_email='emyller@7ws.co',\n description='Magically editable settings for winged pony lovers',\n url='https:\/\/github.com\/7ws\/django-setmagic',\n install_requires=[\n 'django >= 1.5',\n ],\n packages=['setmagic'],\n include_package_data=True,\n keywords=['django', 'settings'],\n classifiers=[\n 'Framework :: Django',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.1',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Topic :: Software Development',\n ],\n)\n","subject":"Include templates and static at the installing process too","message":"Include templates and static at the installing process too\n","lang":"Python","license":"mit","repos":"7ws\/django-setmagic"} {"commit":"2049be18b864fe2dab61ca6258b2295b3270d5c2","old_file":"setup.py","new_file":"setup.py","old_contents":"import distutils.core\n\n# Uploading to PyPI\n# =================\n# $ python setup.py register -r pypi\n# $ python setup.py sdist upload -r pypi\n\nversion = '0.0'\ndistutils.core.setup(\n name='kxg',\n version=version,\n author='Kale Kundert and Alex Mitchell',\n url='https:\/\/github.com\/kxgames\/GameEngine',\n download_url='https:\/\/github.com\/kxgames\/GameEngine\/tarball\/'+version,\n license='LICENSE.txt',\n description=\"A multiplayer game engine.\",\n long_description=open('README.rst').read(),\n keywords=['game', 'network', 'gui', 'pyglet'],\n packages=['kxg'],\n requires=[\n 'pyglet',\n 'nonstdlib',\n 'linersock',\n 'vecrec',\n 'glooey',\n ],\n)\n","new_contents":"import distutils.core\n\n# Uploading to PyPI\n# =================\n# $ python setup.py register -r pypi\n# $ python setup.py sdist upload -r pypi\n\nversion = '0.0'\ndistutils.core.setup(\n name='kxg',\n version=version,\n author='Kale Kundert and Alex Mitchell',\n url='https:\/\/github.com\/kxgames\/GameEngine',\n download_url='https:\/\/github.com\/kxgames\/GameEngine\/tarball\/'+version,\n license='LICENSE.txt',\n description=\"A multiplayer game engine.\",\n long_description=open('README.rst').read(),\n keywords=['game', 'network', 'gui', 'pyglet'],\n packages=['kxg'],\n requires=[\n 'pyglet',\n 'nonstdlib',\n 'linersock',\n 'vecrec',\n 'glooey',\n 'pytest',\n ],\n)\n","subject":"Add pytest as a dependency","message":"Add pytest as a dependency\n","lang":"Python","license":"mit","repos":"kxgames\/kxg"} {"commit":"cb528fbb990e8cd3d301fcbf60069b33a68b9cac","old_file":"setup.py","new_file":"setup.py","old_contents":"#!\/usr\/bin\/env python\nfrom distribute_setup import use_setuptools\nuse_setuptools()\n\nfrom setuptools import setup, find_packages\nsetup(\n name=\"ShowTransmission\",\n version=\"0.1\",\n packages=find_packages(),\n\n author=\"Chris Scutcher\",\n author_email=\"chris.scutcher@ninebysix.co.uk\",\n description=(\"Script that monitors a ShowRSS feed and adds new torrents to transmission via \"\n \"RPC interface\"),\n install_requires=['feedparser>=5.3.1'],\n entry_points = {\n 'console_scripts': [\n 'showtransmission = showtransmission.showtransmission:run_script',\n ],\n 'setuptools.installation': [\n 'eggsecutable = showtransmission.showtransmission:run_script',\n ]\n }\n)\n","new_contents":"#!\/usr\/bin\/env python\nfrom distribute_setup import use_setuptools\nuse_setuptools()\n\nfrom setuptools import setup, find_packages\nsetup(\n name=\"ShowTransmission\",\n version=\"0.1\",\n packages=find_packages(),\n\n author=\"Chris Scutcher\",\n author_email=\"chris.scutcher@ninebysix.co.uk\",\n description=(\"Script that monitors a ShowRSS feed and adds new torrents to transmission via \"\n \"RPC interface\"),\n install_requires=['feedparser'],\n entry_points = {\n 'console_scripts': [\n 'showtransmission = showtransmission.showtransmission:run_script',\n ],\n 'setuptools.installation': [\n 'eggsecutable = showtransmission.showtransmission:run_script',\n ]\n }\n)\n","subject":"Revert \"Specify specific version of feedparser\"","message":"Revert \"Specify specific version of feedparser\"\n\nThis reverts commit e2a6bc54e404538f01a980f1573a507c224d1c31.\n","lang":"Python","license":"apache-2.0","repos":"cscutcher\/showtransmission"} {"commit":"ab82c974dae5baac854c5522a0f0e4d525f86350","old_file":"setup.py","new_file":"setup.py","old_contents":"from setuptools import setup, Extension\n\nsetup(name='python-pytun',\n author='montag451',\n author_email='montag451@laposte.net',\n maintainer='montag451',\n maintainer_email='montag451@laposte.net',\n url='https:\/\/github.com\/montag451\/pytun',\n description='Linux TUN\/TAP wrapper for Python',\n long_description=open('README.rst').read(),\n version='2.3.0',\n ext_modules=[Extension('pytun', ['pytun.c'])],\n classifiers=[\n 'Development Status :: 5 - Production\/Stable',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: C',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: System :: Networking'])\n","new_contents":"from setuptools import setup, Extension\n\nsetup(name='python-pytun',\n author='montag451',\n author_email='montag451@laposte.net',\n maintainer='montag451',\n maintainer_email='montag451@laposte.net',\n url='https:\/\/github.com\/montag451\/pytun',\n description='Linux TUN\/TAP wrapper for Python',\n long_description=open('README.rst').read(),\n version='2.4.0',\n ext_modules=[Extension('pytun', ['pytun.c'])],\n classifiers=[\n 'Development Status :: 5 - Production\/Stable',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: C',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: System :: Networking'])\n","subject":"Bump version number (2.3.0 -> 2.4.0)","message":"Bump version number (2.3.0 -> 2.4.0)\n","lang":"Python","license":"mit","repos":"montag451\/pytun,montag451\/pytun"} {"commit":"a61386cbbcbe3e68bcdf0a98c23547117a496fec","old_file":"zerver\/views\/webhooks\/github_dispatcher.py","new_file":"zerver\/views\/webhooks\/github_dispatcher.py","old_contents":"from __future__ import absolute_import\nfrom django.http import HttpRequest, HttpResponse\nfrom .github_webhook import api_github_webhook\nfrom .github import api_github_landing\n\n\ndef api_github_webhook_dispatch(request):\n # type: (HttpRequest) -> HttpResponse\n if request.META.get('HTTP_X_GITHUB_EVENT'):\n return api_github_webhook(request)\n else:\n return api_github_landing(request)\n","new_contents":"from __future__ import absolute_import\nfrom django.http import HttpRequest, HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .github_webhook import api_github_webhook\nfrom .github import api_github_landing\n\n# Since this dispatcher is an API-style endpoint, it needs to be\n# explicitly marked as CSRF-exempt\n@csrf_exempt\ndef api_github_webhook_dispatch(request):\n # type: (HttpRequest) -> HttpResponse\n if request.META.get('HTTP_X_GITHUB_EVENT'):\n return api_github_webhook(request)\n else:\n return api_github_landing(request)\n","subject":"Fix GitHub integration CSRF issue.","message":"github: Fix GitHub integration CSRF issue.\n\nThe new GitHub dispatcher integration was apparently totally broken,\nbecause we hadn't tagged the new dispatcher endpoint as exempt from\nCSRF checking. I'm not sure why the test suite didn't catch this.\n","lang":"Python","license":"apache-2.0","repos":"AZtheAsian\/zulip,dhcrzf\/zulip,JPJPJPOPOP\/zulip,christi3k\/zulip,hackerkid\/zulip,verma-varsha\/zulip,j831\/zulip,Diptanshu8\/zulip,dhcrzf\/zulip,ryanbackman\/zulip,shubhamdhama\/zulip,Galexrt\/zulip,hackerkid\/zulip,andersk\/zulip,amyliu345\/zulip,j831\/zulip,mahim97\/zulip,brainwane\/zulip,SmartPeople\/zulip,ryanbackman\/zulip,Galexrt\/zulip,dawran6\/zulip,JPJPJPOPOP\/zulip,rht\/zulip,niftynei\/zulip,vaidap\/zulip,amanharitsh123\/zulip,AZtheAsian\/zulip,shubhamdhama\/zulip,rht\/zulip,kou\/zulip,jphilipsen05\/zulip,mahim97\/zulip,verma-varsha\/zulip,isht3\/zulip,cosmicAsymmetry\/zulip,vabs22\/zulip,vabs22\/zulip,eeshangarg\/zulip,showell\/zulip,PhilSk\/zulip,timabbott\/zulip,rishig\/zulip,jrowan\/zulip,sharmaeklavya2\/zulip,aakash-cr7\/zulip,tommyip\/zulip,JPJPJPOPOP\/zulip,zulip\/zulip,ryanbackman\/zulip,jackrzhang\/zulip,jackrzhang\/zulip,rht\/zulip,cosmicAsymmetry\/zulip,brainwane\/zulip,brockwhittaker\/zulip,timabbott\/zulip,andersk\/zulip,christi3k\/zulip,rishig\/zulip,isht3\/zulip,blaze225\/zulip,punchagan\/zulip,kou\/zulip,susansls\/zulip,brainwane\/zulip,eeshangarg\/zulip,jainayush975\/zulip,brainwane\/zulip,susansls\/zulip,vabs22\/zulip,vabs22\/zulip,verma-varsha\/zulip,Diptanshu8\/zulip,rht\/zulip,punchagan\/zulip,jrowan\/zulip,sonali0901\/zulip,dawran6\/zulip,eeshangarg\/zulip,showell\/zulip,eeshangarg\/zulip,tommyip\/zulip,JPJPJPOPOP\/zulip,shubhamdhama\/zulip,showell\/zulip,shubhamdhama\/zulip,christi3k\/zulip,sonali0901\/zulip,eeshangarg\/zulip,dhcrzf\/zulip,isht3\/zulip,SmartPeople\/zulip,vaidap\/zulip,Diptanshu8\/zulip,kou\/zulip,souravbadami\/zulip,hackerkid\/zulip,tommyip\/zulip,souravbadami\/zulip,samatdav\/zulip,amyliu345\/zulip,brockwhittaker\/zulip,amanharitsh123\/zulip,ryanbackman\/zulip,j831\/zulip,SmartPeople\/zulip,synicalsyntax\/zulip,samatdav\/zulip,dawran6\/zulip,kou\/zulip,andersk\/zulip,PhilSk\/zulip,vaidap\/zulip,AZtheAsian\/zulip,jrowan\/zulip,zulip\/zulip,aakash-cr7\/zulip,christi3k\/zulip,rishig\/zulip,souravbadami\/zulip,sharmaeklavya2\/zulip,zulip\/zulip,Diptanshu8\/zulip,dawran6\/zulip,jackrzhang\/zulip,blaze225\/zulip,isht3\/zulip,brainwane\/zulip,synicalsyntax\/zulip,punchagan\/zulip,synicalsyntax\/zulip,amyliu345\/zulip,dhcrzf\/zulip,sonali0901\/zulip,zulip\/zulip,rishig\/zulip,synicalsyntax\/zulip,hackerkid\/zulip,samatdav\/zulip,susansls\/zulip,hackerkid\/zulip,susansls\/zulip,brockwhittaker\/zulip,susansls\/zulip,timabbott\/zulip,aakash-cr7\/zulip,sharmaeklavya2\/zulip,rht\/zulip,showell\/zulip,isht3\/zulip,SmartPeople\/zulip,jainayush975\/zulip,aakash-cr7\/zulip,zulip\/zulip,shubhamdhama\/zulip,brockwhittaker\/zulip,andersk\/zulip,jackrzhang\/zulip,dattatreya303\/zulip,Galexrt\/zulip,rht\/zulip,zulip\/zulip,amanharitsh123\/zulip,jackrzhang\/zulip,j831\/zulip,tommyip\/zulip,JPJPJPOPOP\/zulip,punchagan\/zulip,sharmaeklavya2\/zulip,souravbadami\/zulip,tommyip\/zulip,jphilipsen05\/zulip,timabbott\/zulip,PhilSk\/zulip,niftynei\/zulip,samatdav\/zulip,dattatreya303\/zulip,SmartPeople\/zulip,kou\/zulip,shubhamdhama\/zulip,amanharitsh123\/zulip,brainwane\/zulip,verma-varsha\/zulip,blaze225\/zulip,j831\/zulip,AZtheAsian\/zulip,eeshangarg\/zulip,Galexrt\/zulip,blaze225\/zulip,amyliu345\/zulip,verma-varsha\/zulip,tommyip\/zulip,synicalsyntax\/zulip,dawran6\/zulip,vaidap\/zulip,dhcrzf\/zulip,showell\/zulip,jphilipsen05\/zulip,ryanbackman\/zulip,sonali0901\/zulip,sonali0901\/zulip,aakash-cr7\/zulip,brainwane\/zulip,andersk\/zulip,christi3k\/zulip,jainayush975\/zulip,AZtheAsian\/zulip,j831\/zulip,rht\/zulip,AZtheAsian\/zulip,ryanbackman\/zulip,vabs22\/zulip,zulip\/zulip,shubhamdhama\/zulip,kou\/zulip,rishig\/zulip,mahim97\/zulip,hackerkid\/zulip,timabbott\/zulip,mahim97\/zulip,niftynei\/zulip,jrowan\/zulip,sharmaeklavya2\/zulip,souravbadami\/zulip,jphilipsen05\/zulip,verma-varsha\/zulip,jackrzhang\/zulip,jackrzhang\/zulip,dattatreya303\/zulip,rishig\/zulip,punchagan\/zulip,tommyip\/zulip,andersk\/zulip,jainayush975\/zulip,jphilipsen05\/zulip,blaze225\/zulip,PhilSk\/zulip,Diptanshu8\/zulip,Diptanshu8\/zulip,amyliu345\/zulip,timabbott\/zulip,dhcrzf\/zulip,cosmicAsymmetry\/zulip,amanharitsh123\/zulip,cosmicAsymmetry\/zulip,rishig\/zulip,niftynei\/zulip,showell\/zulip,isht3\/zulip,SmartPeople\/zulip,vaidap\/zulip,vaidap\/zulip,PhilSk\/zulip,andersk\/zulip,sonali0901\/zulip,aakash-cr7\/zulip,Galexrt\/zulip,jrowan\/zulip,susansls\/zulip,christi3k\/zulip,jainayush975\/zulip,niftynei\/zulip,amyliu345\/zulip,PhilSk\/zulip,brockwhittaker\/zulip,eeshangarg\/zulip,synicalsyntax\/zulip,hackerkid\/zulip,showell\/zulip,dattatreya303\/zulip,dawran6\/zulip,jainayush975\/zulip,mahim97\/zulip,cosmicAsymmetry\/zulip,punchagan\/zulip,synicalsyntax\/zulip,souravbadami\/zulip,cosmicAsymmetry\/zulip,timabbott\/zulip,dhcrzf\/zulip,dattatreya303\/zulip,vabs22\/zulip,jrowan\/zulip,niftynei\/zulip,brockwhittaker\/zulip,JPJPJPOPOP\/zulip,blaze225\/zulip,punchagan\/zulip,amanharitsh123\/zulip,samatdav\/zulip,jphilipsen05\/zulip,sharmaeklavya2\/zulip,samatdav\/zulip,Galexrt\/zulip,Galexrt\/zulip,mahim97\/zulip,dattatreya303\/zulip,kou\/zulip"} {"commit":"a7c49480e1eb530aa4df494709ec1f7edd875e1a","old_file":"devito\/ir\/clusters\/analysis.py","new_file":"devito\/ir\/clusters\/analysis.py","old_contents":"from devito.ir.support import (SEQUENTIAL, PARALLEL, PARALLEL_IF_ATOMIC, VECTOR,\n TILABLE, WRAPPABLE)\n\n__all__ = ['analyze']\n\n\ndef analyze(clusters):\n return clusters\n","new_contents":"from collections import OrderedDict\n\nfrom devito.ir.clusters.queue import Queue\nfrom devito.ir.support import (SEQUENTIAL, PARALLEL, PARALLEL_IF_ATOMIC, VECTOR,\n TILABLE, WRAPPABLE)\nfrom devito.tools import timed_pass\n\n__all__ = ['analyze']\n\n\nclass State(object):\n\n def __init__(self):\n self.properties = OrderedDict()\n self.scopes = OrderedDict()\n\n\nclass Detector(Queue):\n\n def __init__(self, state):\n super(Detector, self).__init__()\n self.state = state\n\n def callback(self, clusters, prefix):\n self._callback(clusters, prefix)\n return clusters\n\n\nclass Parallelism(Detector):\n\n def _callback(self, clusters, prefix):\n properties = OrderedDict()\n\n\ndef analyze(clusters):\n state = State()\n\n clusters = Parallelism(state).process(clusters)\n\n return clusters\n","subject":"Add machinery to detect Cluster properties","message":"ir: Add machinery to detect Cluster properties\n","lang":"Python","license":"mit","repos":"opesci\/devito,opesci\/devito"} {"commit":"db7cf53356f2109baba684ec00efdbf5c7cdde70","old_file":"eventbot\/integrations\/slack.py","new_file":"eventbot\/integrations\/slack.py","old_contents":"import requests\nimport simplejson as json\n\nfrom eventbot import settings\n\n\ndef post_form_to_webhook(form):\n \"\"\" Post the contents of a form to Slack.\n \"\"\"\n d = form.values()\n text = u\"\"\"\n '{name}' ({email}) submitted an application form.\n *Please tell us about yourself:* {bio}\n *What interests you?* {interests}\n \"\"\".format(**d)\n\n # slack_webhook_obj = {\"text\": text}\n slack_webhook_obj = {\n \"text\": \"text\",\n \"attachments\": [\n {\n \"text\": \"What action should I take?\",\n \"fallback\": \"No action chosen\",\n \"callback_id\": \"application_form_action\",\n \"color\": \"#3AA3E3\",\n \"attachment_type\": \"default\",\n \"actions\": [\n {\n \"name\": \"application_form\",\n \"text\": \"Approve\",\n \"type\": \"button\",\n \"value\": \"approve\"\n }\n ]\n }\n ]\n }\n slack_webhook_url = settings.SLACK_WEBHOOK_URL\n requests.post(slack_webhook_url, data=json.dumps(slack_webhook_obj))\n\n\ndef post_warning_to_webhook(message):\n \"\"\" Post a warning into Slack.\n \"\"\"\n text = u\"\"\"\n Warning! {message}\n \"\"\".format(**d)\n slack_webhook_obj = {\"text\": text}\n slack_webhook_url = settings.SLACK_WEBHOOK_URL\n requests.post(slack_webhook_url, data=json.dumps(slack_webhook_obj))\n","new_contents":"import requests\nimport simplejson as json\n\nfrom eventbot import settings\n\n\ndef post_form_to_webhook(form):\n \"\"\" Post the contents of a form to Slack.\n \"\"\"\n d = form.values()\n text = u\"\"\"\n '{name}' ({email}) submitted an application form.\n *Please tell us about yourself:* {bio}\n *What interests you?* {interests}\n \"\"\".format(**d)\n\n # slack_webhook_obj = {\"text\": text}\n slack_webhook_obj = {\n \"text\": text,\n \"attachments\": [\n {\n \"text\": \"What action should I take?\",\n \"fallback\": \"No action chosen\",\n \"callback_id\": \"application_form_action\",\n \"color\": \"#3AA3E3\",\n \"attachment_type\": \"default\",\n \"actions\": [\n {\n \"name\": \"application_form\",\n \"text\": \"Approve\",\n \"type\": \"button\",\n \"value\": \"approve\"\n }\n ]\n }\n ]\n }\n slack_webhook_url = settings.SLACK_WEBHOOK_URL\n requests.post(slack_webhook_url, data=json.dumps(slack_webhook_obj))\n\n\ndef post_warning_to_webhook(message):\n \"\"\" Post a warning into Slack.\n \"\"\"\n text = u\"\"\"\n Warning! {message}\n \"\"\".format(**d)\n slack_webhook_obj = {\"text\": text}\n slack_webhook_url = settings.SLACK_WEBHOOK_URL\n requests.post(slack_webhook_url, data=json.dumps(slack_webhook_obj))\n","subject":"Fix a bug where I was posting the word 'text' into the channel rather than the actual application form.","message":"Fix a bug where I was posting the word 'text' into the channel rather than the actual application form.\n","lang":"Python","license":"mit","repos":"duffj\/eventbot-web-api,duffj\/eventbot-web-api"} {"commit":"b362e6060abe631f25e5227664df4e1670f4d630","old_file":"registration\/admin.py","new_file":"registration\/admin.py","old_contents":"from django.contrib import admin\n\nfrom registration.models import RegistrationProfile\n\n\nclass RegistrationAdmin(admin.ModelAdmin):\n list_display = ('__unicode__', 'activation_key_expired')\n search_fields = ('user__username', 'user__first_name')\n\n\nadmin.site.register(RegistrationProfile, RegistrationAdmin)\n","new_contents":"from django.contrib import admin\n\nfrom registration.models import RegistrationProfile\n\n\nclass RegistrationAdmin(admin.ModelAdmin):\n list_display = ('__unicode__', 'activation_key_expired')\n raw_id_fields = ['user']\n search_fields = ('user__username', 'user__first_name')\n\n\nadmin.site.register(RegistrationProfile, RegistrationAdmin)\n","subject":"Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.","message":"Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.\n","lang":"Python","license":"bsd-3-clause","repos":"arpitremarkable\/django-registration,sergafts\/django-registration,wy123123\/django-registration,wda-hb\/test,furious-luke\/django-registration,imgmix\/django-registration,matejkloska\/django-registration,PetrDlouhy\/django-registration,pando85\/django-registration,yorkedork\/django-registration,pando85\/django-registration,percipient\/django-registration,tanjunyen\/django-registration,torchingloom\/django-registration,wy123123\/django-registration,kazitanvirahsan\/django-registration,maitho\/django-registration,kinsights\/django-registration,rulz\/django-registration,mick-t\/django-registration,ei-grad\/django-registration,nikolas\/django-registration,percipient\/django-registration,timgraham\/django-registration,ei-grad\/django-registration,mick-t\/django-registration,PetrDlouhy\/django-registration,arpitremarkable\/django-registration,tanjunyen\/django-registration,kinsights\/django-registration,stillmatic\/django-registration,torchingloom\/django-registration,matejkloska\/django-registration,imgmix\/django-registration,kazitanvirahsan\/django-registration,yorkedork\/django-registration,memnonila\/django-registration,timgraham\/django-registration,Geffersonvivan\/django-registration,alawnchen\/django-registration,alawnchen\/django-registration,erinspace\/django-registration,furious-luke\/django-registration,rulz\/django-registration,wda-hb\/test,PSU-OIT-ARC\/django-registration,Geffersonvivan\/django-registration,sergafts\/django-registration,nikolas\/django-registration,erinspace\/django-registration,PSU-OIT-ARC\/django-registration,allo-\/django-registration,allo-\/django-registration,maitho\/django-registration,stillmatic\/django-registration,memnonila\/django-registration"} {"commit":"47f2ee4587df189864029a2260b642547ea7355f","old_file":"config.py","new_file":"config.py","old_contents":"#Package startup stuff so people can start their iPython session with\n#\n#run PyQLab \/path\/to\/cfgFile and be up and running\n\n\n#Package imports\nimport numpy as np\n\n#Load the configuration from the json file and populate the global configuration dictionary\nimport json\nimport os.path\nimport sys\nPyQLabCfgFile = os.path.join(os.path.dirname( os.path.abspath(__file__) ), 'config.json')\nif PyQLabCfgFile:\n\twith open(PyQLabCfgFile, 'r') as f:\n\t\tPyQLabCfg = json.load(f)\n\n\t#pull out the variables \n\tAWGDir = PyQLabCfg['AWGDir']\n\tchannelLibFile = PyQLabCfg['ChannelLibraryFile']\n\tinstrumentLibFile = PyQLabCfg['InstrumentLibraryFile']\n\tsweepLibFile = PyQLabCfg['SweepLibraryFile']\n\tmeasurementLibFile = PyQLabCfg['MeasurementLibraryFile']\n\tquickpickFile = PyQLabCfg['QuickPickFile'] if 'QuickPickFile' in PyQLabCfg else None\n\nelse:\n\traise NameError(\"Unable to find the PyQLab configuration environment variable\")\n\n","new_contents":"#Package startup stuff so people can start their iPython session with\n#\n#run PyQLab \/path\/to\/cfgFile and be up and running\n\n\n#Package imports\nimport numpy as np\n\n#Load the configuration from the json file and populate the global configuration dictionary\nimport json\nimport os.path\nimport sys\nPyQLabCfgFile = os.path.join(os.path.dirname( os.path.abspath(__file__) ), 'config.json')\nif PyQLabCfgFile:\n\twith open(PyQLabCfgFile, 'r') as f:\n\t\tPyQLabCfg = json.load(f)\n\n\t#pull out the variables \n\tAWGDir = PyQLabCfg['AWGDir']\n\tchannelLibFile = PyQLabCfg['ChannelLibraryFile']\n\tinstrumentLibFile = PyQLabCfg['InstrumentLibraryFile']\n\tsweepLibFile = PyQLabCfg['SweepLibraryFile']\n\tmeasurementLibFile = PyQLabCfg['MeasurementLibraryFile']\n\tquickpickFile = PyQLabCfg['QuickPickFile'] if 'QuickPickFile' in PyQLabCfg else ''\n\nelse:\n\traise NameError(\"Unable to find the PyQLab configuration environment variable\")\n\n","subject":"Put empty string in for quickPickFile if it doesn't exist.","message":"Put empty string in for quickPickFile if it doesn't exist.\n","lang":"Python","license":"apache-2.0","repos":"Plourde-Research-Lab\/PyQLab,BBN-Q\/PyQLab,rmcgurrin\/PyQLab,calebjordan\/PyQLab"} {"commit":"d60b0ee8c212728721f47cc57303ae24888cc387","old_file":"models.py","new_file":"models.py","old_contents":"import datetime\nimport math\n\nfrom flask import Markup\nfrom peewee import Model, TextField, DateTimeField\n\nfrom app import db\n\n\nclass Quote(Model):\n content = TextField()\n timestamp = DateTimeField(default=datetime.datetime.now)\n\n class Meta:\n database = db\n\n def html(self):\n return Markup(self.content)\n\n @classmethod\n def paged(cls, page, page_size):\n quotes = Quote.select().order_by(Quote.timestamp.desc())\n page_count = math.ceil(quotes.count() \/ page_size)\n return quotes.offset(page * page_size).limit(page_size), page_count\n","new_contents":"import datetime\nimport math\n\nfrom flask import Markup\nfrom peewee import Model, TextField, DateTimeField\n\nfrom app import db\n\n\nclass Quote(Model):\n content = TextField()\n timestamp = DateTimeField(default=datetime.datetime.now)\n\n class Meta:\n database = db\n\n def html(self):\n return Markup(self.content.replace('\\n', '
'))\n\n @classmethod\n def paged(cls, page, page_size):\n quotes = Quote.select().order_by(Quote.timestamp.desc())\n page_count = math.ceil(quotes.count() \/ page_size)\n return quotes.offset(page * page_size).limit(page_size), page_count\n","subject":"Add support for carriage returns","message":"Add support for carriage returns\n","lang":"Python","license":"apache-2.0","repos":"agateau\/tmc2,agateau\/tmc2"} {"commit":"37333506e6866e7d0859c5068f115a3e1b9dec3a","old_file":"test\/test_coordinate.py","new_file":"test\/test_coordinate.py","old_contents":"import unittest\nfrom src import coordinate\n\nclass TestRules(unittest.TestCase):\n \"\"\" Tests for the coordinate module \"\"\"\n\n def test_get_x_board(self):\n board_location = coordinate.Coordinate(4, 6)\n expected_result = 4\n actual_result = board_location.get_x_board()\n self.assertEqual(actual_result, expected_result)\n\n def test_get_y_board(self):\n board_location = coordinate.Coordinate(4, 6)\n expected_result = 6\n actual_result = board_location.get_y_board()\n self.assertEqual(actual_result, expected_result)\n\n def test_get_x_array(self):\n board_location = coordinate.Coordinate(4, 6)\n expected_result = 3\n actual_result = board_location.get_x_array()\n self.assertEqual(actual_result, expected_result)\n\n def test_get_y_array(self):\n board_location = coordinate.Coordinate(4, 6)\n expected_result = 5\n actual_result = board_location.get_y_array()\n self.assertEqual(actual_result, expected_result)","new_contents":"import unittest\nfrom src import coordinate\n\nclass TestRules(unittest.TestCase):\n \"\"\" Tests for the coordinate module \"\"\"\n\n def test_get_x_board(self):\n board_location = coordinate.Coordinate(4, 6)\n expected_result = 4\n actual_result = board_location.get_x_board()\n self.assertEqual(actual_result, expected_result)\n\n def test_get_y_board(self):\n board_location = coordinate.Coordinate(4, 6)\n expected_result = 6\n actual_result = board_location.get_y_board()\n self.assertEqual(actual_result, expected_result)\n\n def test_get_x_array(self):\n board_location = coordinate.Coordinate(4, 6)\n expected_result = 3\n actual_result = board_location.get_x_array()\n self.assertEqual(actual_result, expected_result)\n\n def test_get_y_array(self):\n board_location = coordinate.Coordinate(4, 6)\n expected_result = 5\n actual_result = board_location.get_y_array()\n self.assertEqual(actual_result, expected_result)\n\n def test_coordinate_bad_x(self):\n self.assertRaises(TypeError, coordinate.Coordinate, \"4\", 6)\n\n def test_coordinate_bad_y(self):\n self.assertRaises(TypeError, coordinate.Coordinate, 4, \"6\")\n\n def test_coordinate_bad_location(self):\n self.assertRaises(ValueError, coordinate.Coordinate, 50, 100)\n","subject":"Add unit tests for fail fast logic in convertCharToInt()","message":"Add unit tests for fail fast logic in convertCharToInt()\n","lang":"Python","license":"mit","repos":"blairck\/jaeger"} {"commit":"4622c1d2623468503b5d51683f953b82ca611b35","old_file":"vumi\/demos\/tests\/test_static_reply.py","new_file":"vumi\/demos\/tests\/test_static_reply.py","old_contents":"from twisted.internet.defer import inlineCallbacks\n\nfrom vumi.application.tests.utils import ApplicationTestCase\nfrom vumi.demos.static_reply import StaticReplyApplication\n\n\nclass TestStaticReplyApplication(ApplicationTestCase):\n application_class = StaticReplyApplication\n\n @inlineCallbacks\n def test_receive_message(self):\n yield self.get_application(config={\n 'reply_text': 'Your message is important to us.',\n })\n yield self.dispatch(self.mkmsg_in())\n [reply] = yield self.get_dispatched_messages()\n self.assertEqual('Your message is important to us.', reply['content'])\n self.assertEqual(u'close', reply['session_event'])\n\n @inlineCallbacks\n def test_receive_message_no_reply(self):\n yield self.get_application(config={})\n yield self.dispatch(self.mkmsg_in())\n self.assertEqual([], (yield self.get_dispatched_messages()))\n","new_contents":"from twisted.internet.defer import inlineCallbacks\n\nfrom vumi.application.tests.helpers import ApplicationHelper\nfrom vumi.demos.static_reply import StaticReplyApplication\nfrom vumi.tests.helpers import VumiTestCase\n\n\nclass TestStaticReplyApplication(VumiTestCase):\n def setUp(self):\n self.app_helper = ApplicationHelper(StaticReplyApplication)\n self.add_cleanup(self.app_helper.cleanup)\n\n @inlineCallbacks\n def test_receive_message(self):\n yield self.app_helper.get_application({\n 'reply_text': 'Your message is important to us.',\n })\n yield self.app_helper.make_dispatch_inbound(\"Hello\")\n [reply] = self.app_helper.get_dispatched_outbound()\n self.assertEqual('Your message is important to us.', reply['content'])\n self.assertEqual(u'close', reply['session_event'])\n\n @inlineCallbacks\n def test_receive_message_no_reply(self):\n yield self.app_helper.get_application({})\n yield self.app_helper.make_dispatch_inbound(\"Hello\")\n self.assertEqual([], self.app_helper.get_dispatched_outbound())\n","subject":"Switch static_reply tests to new helpers.","message":"Switch static_reply tests to new helpers.\n","lang":"Python","license":"bsd-3-clause","repos":"vishwaprakashmishra\/xmatrix,TouK\/vumi,vishwaprakashmishra\/xmatrix,TouK\/vumi,vishwaprakashmishra\/xmatrix,TouK\/vumi,harrissoerja\/vumi,harrissoerja\/vumi,harrissoerja\/vumi"} {"commit":"bb04512cdf264a3ef87f3d0093db9fe10723a668","old_file":"core\/wsgi.py","new_file":"core\/wsgi.py","old_contents":"\"\"\"\nWSGI config for core project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps:\/\/docs.djangoproject.com\/en\/1.7\/howto\/deployment\/wsgi\/\n\"\"\"\n\nimport os\n\nfrom django.core.wsgi import get_wsgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"core.settings\")\n\napplication = get_wsgi_application()\n","new_contents":"\"\"\"\nWSGI config for core project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps:\/\/docs.djangoproject.com\/en\/1.7\/howto\/deployment\/wsgi\/\n\"\"\"\n\nimport os, sys, site\nsite.addsitedir('\/usr\/local\/share\/virtualenvs\/guhema\/lib\/python3.4\/site-packages')\nsys.path.append('\/var\/www\/vhosts\/guhema.com\/httpdocs\/django')\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"dpb.settings\")\n\nfrom django.core.wsgi import get_wsgi_application\napplication = get_wsgi_application()\n","subject":"Add pathts for apache deployment","message":"Add pathts for apache deployment\n","lang":"Python","license":"mit","repos":"n2o\/guhema,n2o\/guhema"} {"commit":"1c1f2cab677ead5f3cf3aa59c5094a741378e5bc","old_file":"dame\/dame.py","new_file":"dame\/dame.py","old_contents":"__author__ = \"Richard Lindsley\"\n\nimport sys\n\nimport sip\nsip.setapi('QDate', 2)\nsip.setapi('QDateTime', 2)\nsip.setapi('QString', 2)\nsip.setapi('QTextStream', 2)\nsip.setapi('QTime', 2)\nsip.setapi('QUrl', 2)\nsip.setapi('QVariant', 2)\nfrom PyQt4 import Qt\n\ndef main():\n qt_app = Qt.QApplication(sys.argv)\n label = Qt.QLabel(\"Hello, world\")\n label.show()\n qt_app.exec_()\n\nif __name__ == \"__main__\":\n main()\n","new_contents":"__author__ = \"Richard Lindsley\"\n\nimport sys\n\n#import sip\n#sip.setapi('QDate', 2)\n#sip.setapi('QDateTime', 2)\n#sip.setapi('QString', 2)\n#sip.setapi('QTextStream', 2)\n#sip.setapi('QTime', 2)\n#sip.setapi('QUrl', 2)\n#sip.setapi('QVariant', 2)\n#from PyQt4 import Qt\n\nfrom PySide.QtCore import *\nfrom PySide.QtGui import *\n\n\ndef main():\n qt_app = QApplication(sys.argv)\n label = QLabel(\"Hello, world\")\n label.show()\n qt_app.exec_()\n\nif __name__ == \"__main__\":\n main()\n","subject":"Use pyside instead of pyqt4","message":"Use pyside instead of pyqt4\n","lang":"Python","license":"mit","repos":"richli\/dame"} {"commit":"08fbd4b934bc4459bb46025620b906e93f8f293e","old_file":"voer\/settings\/dev.py","new_file":"voer\/settings\/dev.py","old_contents":"'''\nCreated on 16 Dec 2013\n\n@author: huyvq\n'''\nfrom base import *\n\n# FOR DEBUG\nDEBUG = True\nDEVELOPMENT = True\nTEMPLATE_DEBUG = DEBUG\n\n# Database\n# https:\/\/docs.djangoproject.com\/en\/1.6\/ref\/settings\/#databases\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'voer_django',\n 'USER': 'voer',\n 'PASSWORD': 'voer',\n 'HOST': '127.0.0.1',\n 'PORT': 3306,\n }\n}\n\n#VPR Address\nVPR_URL = 'http:\/\/localhost:2013\/1.0\/'\n\n#VPT Address\nVPT_URL = 'http:\/\/voer.edu.vn:6543\/'\n\nSITE_URL = 'dev.voer.vn'\n\nRECAPTCHA_PUBLIC_KEY = '6Lf__uwSAAAAAPpTMYOLUOBf25clR7fGrqWrpOn0'\nRECAPTCHA_PRIVATE_KEY = '6Lf__uwSAAAAAPlCihico8fKiAfV09_kbywiI-xx'\n\n#STATIC_ROOT = os.path.join(PROJECT_DIR, '_static')\n\n\nCOMPRESS_ENABLED = False\n","new_contents":"'''\nCreated on 16 Dec 2013\n\n@author: huyvq\n'''\nfrom base import *\n\n# FOR DEBUG\nDEBUG = True\nDEVELOPMENT = True\nTEMPLATE_DEBUG = DEBUG\n\n# Database\n# https:\/\/docs.djangoproject.com\/en\/1.6\/ref\/settings\/#databases\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'voer_django',\n 'USER': 'voer',\n 'PASSWORD': 'voer',\n 'HOST': '127.0.0.1',\n 'PORT': 3306,\n }\n}\n\n#VPR Address\nVPR_URL = 'http:\/\/voer.edu.vn:2013\/1.0\/'\n\n#VPT Address\nVPT_URL = 'http:\/\/voer.edu.vn:6543\/'\n\nSITE_URL = 'dev.voer.vn'\n\nRECAPTCHA_PUBLIC_KEY = '6Lf__uwSAAAAAPpTMYOLUOBf25clR7fGrqWrpOn0'\nRECAPTCHA_PRIVATE_KEY = '6Lf__uwSAAAAAPlCihico8fKiAfV09_kbywiI-xx'\n\n#STATIC_ROOT = os.path.join(PROJECT_DIR, '_static')\n\n\nCOMPRESS_ENABLED = False\n","subject":"Correct the VPR URL in setting","message":"Correct the VPR URL in setting\n","lang":"Python","license":"agpl-3.0","repos":"voer-platform\/vp.web,voer-platform\/vp.web,voer-platform\/vp.web,voer-platform\/vp.web"} {"commit":"06542afc4becb4cf3cf96dd15ab240ab4353bf2b","old_file":"ca\/views.py","new_file":"ca\/views.py","old_contents":"from flask import request, render_template\n\nfrom ca import app, db\nfrom ca.forms import RequestForm\nfrom ca.models import Request\n\n\n@app.route('\/', methods=['GET'])\ndef index():\n return render_template('index.html')\n\n\n@app.route('\/', methods=['POST'])\ndef post_request():\n form = RequestForm(request.form)\n if form.validate():\n req = Request(form.id.data, form.email.data)\n db.session.add(req)\n db.session.commit()\n return render_template('thanks.html')\n else:\n return render_template('index.html', form=form)\n","new_contents":"from flask import request, render_template\n\nfrom ca import app, db\nfrom ca.forms import RequestForm\nfrom ca.models import Request\n\n\n@app.route('\/', methods=['GET'])\ndef index():\n form = RequestForm()\n return render_template('index.html', form=form)\n\n\n@app.route('\/', methods=['POST'])\ndef post_request():\n form = RequestForm(request.form)\n if form.validate():\n req = Request(form.id.data, form.email.data)\n db.session.add(req)\n db.session.commit()\n return render_template('thanks.html')\n else:\n return render_template('index.html', form=form)\n","subject":"Create form on index view","message":"Create form on index view\n\n- Need to always pass a form to the view\n - make sure to create on for the `GET` view\n- Fixes #33\n","lang":"Python","license":"mit","repos":"freifunk-berlin\/ca.berlin.freifunk.net,freifunk-berlin\/ca.berlin.freifunk.net,freifunk-berlin\/ca.berlin.freifunk.net"} {"commit":"fa0f65b6b216a869cc6f1503e7af51481b570b78","old_file":"player.py","new_file":"player.py","old_contents":"\n# This is just be a base class \/ interface to be filled out by \n# human and AI players.\n\n# TODO: Undo support?\n# TODO: Resign?\n\n# super requires inheriting from object, which clashes with pickle?!\n#class Player(object):\nclass Player():\n def __init__(self, p_name):\n self.p_name = p_name\n self.remaining_time = 0\n self.total_time = 0\n\n def __repr__(self):\n return self.p_name\n\n def get_type(self):\n return \"BasePlayer\"\n\n def get_key(self):\n return self.p_key\n\n def get_name(self):\n try:\n name = self.p_name\n except AttributeError:\n name = self.name\n self.p_name = name\n del self.name\n return name\n\n def get_total_time(self):\n return self.total_time\n\n def tick(self, seconds):\n self.remaining_time -= seconds\n return self.remaining_time\n\n def set_remaining_time(self, t):\n self.remaining_time = t\n\n def prompt_for_action(self, game, gui):\n pass\n\n def get_action(self, game, gui):\n pass\n\n def rating_factor(self):\n return 1\n\n def attach_to_game(self, base_game):\n # TODO: Restore from history\n self.total_time = base_game.get_rules().time_control\n self.remaining_time = base_game.get_rules().time_control\n\n","new_contents":"\n# This is just be a base class \/ interface to be filled out by \n# human and AI players.\n\n# TODO: Undo support?\n# TODO: Resign?\n\n# super requires inheriting from object, which clashes with pickle?!\n#class Player(object):\nclass Player():\n def __init__(self, p_name):\n self.p_name = p_name\n\n def __repr__(self):\n return self.p_name\n\n def get_type(self):\n return \"BasePlayer\"\n\n def get_key(self):\n return self.p_key\n\n def get_name(self):\n try:\n name = self.p_name\n except AttributeError:\n name = self.name\n self.p_name = name\n del self.name\n return name\n\n def prompt_for_action(self, game, gui):\n pass\n\n def get_action(self, game, gui):\n pass\n\n def rating_factor(self):\n return 1\n\n def attach_to_game(self, base_game):\n pass\n\n","subject":"Remove unused time control support (better in Game)","message":"Remove unused time control support (better in Game)\n","lang":"Python","license":"mit","repos":"cropleyb\/pentai,cropleyb\/pentai,cropleyb\/pentai"} {"commit":"9605b60fb537714c295dfa0f50313e38f89d2d88","old_file":"app.py","new_file":"app.py","old_contents":"\"\"\"\nThis is a simple cheatsheet webapp.\n\"\"\"\nimport os\n\nfrom flask import Flask, send_from_directory\nfrom flask_sslify import SSLify\n\nDIR = os.path.dirname(os.path.realpath(__file__))\nROOT = os.path.join(DIR, 'docs', '_build', 'html')\n\napp = Flask(__name__)\nif 'DYNO' in os.environ:\n sslify = SSLify(app)\n\n@app.route('\/')\ndef static_proxy(path):\n \"\"\"Static files proxy\"\"\"\n return send_from_directory(ROOT, path)\n\n@app.route('\/')\ndef index_redirection():\n \"\"\"Redirecting index file\"\"\"\n return send_from_directory(ROOT, 'index.html')\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","new_contents":"\"\"\"\nThis is a simple cheatsheet webapp.\n\"\"\"\nimport os\n\nfrom flask import Flask, send_from_directory\nfrom flask_sslify import SSLify\n\nDIR = os.path.dirname(os.path.realpath(__file__))\nROOT = os.path.join(DIR, 'docs', '_build', 'html')\n\ndef find_key(token):\n if token == os.environ.get(\"ACME_TOKEN\"):\n return os.environ.get(\"ACME_KEY\")\n for k, v in os.environ.items():\n if v == token and k.startswith(\"ACME_TOKEN_\"):\n n = k.replace(\"ACME_TOKEN_\", \"\")\n return os.environ.get(\"ACME_KEY_{}\".format(n))\n\n\napp = Flask(__name__)\n\nif 'DYNO' in os.environ:\n sslify = SSLify(app, skips=['.well-known'])\n\n\n@app.route('\/')\ndef static_proxy(path):\n \"\"\"Static files proxy\"\"\"\n return send_from_directory(ROOT, path)\n\n\n@app.route('\/')\ndef index_redirection():\n \"\"\"Redirecting index file\"\"\"\n return send_from_directory(ROOT, 'index.html')\n\n\n@app.route(\"\/.well-known\/acme-challenge\/\")\ndef acme(token):\n key = find_key(token)\n if key is None: abort(404)\n return key\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","subject":"Add letsencrypt auto renew api :octocat:","message":"Add letsencrypt auto renew api :octocat:\n","lang":"Python","license":"mit","repos":"caimaoy\/pysheeet"} {"commit":"a621a7803d177e4851d229973586d9b114b0f84c","old_file":"__init__.py","new_file":"__init__.py","old_contents":"# -*- coding: utf-8 -*-\nfrom flask import Flask\nfrom flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface\nimport configparser\n\napp = Flask(__name__)\n# Security\nWTF_CSRF_ENABLED = True\napp.config['SECRET_KEY'] = '2bN9UUaBpcjrxR'\n\n# App Config\nconfig = configparser.ConfigParser()\nconfig.read('config\/config.ini')\n\napp.config['MONGODB_DB'] = config['MongoDB']['db_name']\napp.config['MONGODB_HOST'] = config['MongoDB']['host']\napp.config['MONGODB_PORT'] = int(config['MongoDB']['port'])\napp.config['MONGODB_USERNAME'] = config['MongoDB']['username']\napp.config['MONGODB_PASSWORD'] = config['MongoDB']['password']\n\ndb = MongoEngine(app)\n\ndef register_blueprints(app):\n # Prevents circular imports\n from weighttracker.views.measurement_views import measurements\n app.register_blueprint(measurements)\n from weighttracker.views.inspiration_views import inspirations\n app.register_blueprint(inspirations)\n\nregister_blueprints(app)\n\n\nif __name__ == '__main__':\n app.run()","new_contents":"# -*- coding: utf-8 -*-\nfrom flask import Flask, render_template\nfrom flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface\nimport configparser\n\napp = Flask(__name__)\n# Security\nWTF_CSRF_ENABLED = True\napp.config['SECRET_KEY'] = '2bN9UUaBpcjrxR'\n\n# App Config\nconfig = configparser.ConfigParser()\nconfig.read('config\/config.ini')\n\napp.config['MONGODB_DB'] = config['MongoDB']['db_name']\napp.config['MONGODB_HOST'] = config['MongoDB']['host']\napp.config['MONGODB_PORT'] = int(config['MongoDB']['port'])\napp.config['MONGODB_USERNAME'] = config['MongoDB']['username']\napp.config['MONGODB_PASSWORD'] = config['MongoDB']['password']\n\ndb = MongoEngine(app)\n\ndef register_blueprints(app):\n # Prevents circular imports\n from weighttracker.views.measurement_views import measurements\n app.register_blueprint(measurements)\n from weighttracker.views.inspiration_views import inspirations\n app.register_blueprint(inspirations)\n\nregister_blueprints(app)\n\n@app.route('\/', defaults={'path': ''})\n@app.route('\/')\n\ndef catch_all(path):\n return render_template('index.html')\n\n\nif __name__ == '__main__':\n app.run()","subject":"Create a catch-all route and route to the homepage.","message":"Create a catch-all route and route to the homepage.\n\nSigned-off-by: Robert Dempsey <715b5a941e732be1613fdd9d94dfd8e50c02b187@gmail.com>\n","lang":"Python","license":"mit","repos":"rdempsey\/weight-tracker,rdempsey\/weight-tracker,rdempsey\/weight-tracker"} {"commit":"01b511b1f337f00eb72530692eec202611599c5a","old_file":"tilequeue\/queue\/file.py","new_file":"tilequeue\/queue\/file.py","old_contents":"from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage\nimport threading\n\n\nclass OutputFileQueue(object):\n\n def __init__(self, fp):\n self.fp = fp\n self.lock = threading.RLock()\n\n def enqueue(self, coord):\n with self.lock:\n payload = serialize_coord(coord)\n self.fp.write(payload + '\\n')\n\n def enqueue_batch(self, coords):\n n = 0\n for coord in coords:\n self.enqueue(coord)\n n += 1\n return n, 0\n\n def read(self, max_to_read=1, timeout_seconds=20):\n with self.lock:\n coords = []\n for _ in range(max_to_read):\n coord = self.fp.readline()\n if coord:\n coords.append(CoordMessage(deserialize_coord(coord), None))\n else:\n break\n\n return coords\n\n def job_done(self, coord_message):\n pass\n\n def clear(self):\n with self.lock:\n self.fp.seek(0)\n self.fp.truncate()\n return -1\n\n def close(self):\n with self.lock:\n remaining_queue = ''.join([ln for ln in self.fp])\n self.clear()\n self.fp.write(remaining_queue)\n self.fp.close()\n","new_contents":"from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage\nimport threading\n\n\nclass OutputFileQueue(object):\n\n def __init__(self, fp):\n self.fp = fp\n self.lock = threading.RLock()\n\n def enqueue(self, coord):\n with self.lock:\n payload = serialize_coord(coord)\n self.fp.write(payload + '\\n')\n\n def enqueue_batch(self, coords):\n n = 0\n for coord in coords:\n self.enqueue(coord)\n n += 1\n return n, 0\n\n def read(self, max_to_read=1, timeout_seconds=20):\n with self.lock:\n coords = []\n for _ in range(max_to_read):\n coord = self.fp.readline()\n if coord:\n coords.append(CoordMessage(deserialize_coord(coord), None))\n else:\n break\n\n return coords\n\n def job_done(self, coord_message):\n pass\n\n def clear(self):\n with self.lock:\n self.fp.seek(0)\n self.fp.truncate()\n return -1\n\n def close(self):\n with self.lock:\n self.clear()\n self.fp.write(self.fp.read())\n self.fp.close()\n","subject":"Fix a bug in OutputFileQueue.close().","message":"Fix a bug in OutputFileQueue.close().\n\ntilequeue\/queue\/file.py\n\t-01a8fcb made `OutputFileQueue.read()` use `readline()` instead\n\tof `next()`, but didn't update `OutputFileQueue.close()`, which\n\tuses a list comprehension to grab the rest of the file. Since\n\t`.read()` no longer uses the iteration protocol, `.close()` will\n\tstart iterating from the beginning of the file. Use `.read()`\n\tinstead of a list comprehension to only grab everything after\n\twhat `.readline()` already picked up.\n","lang":"Python","license":"mit","repos":"mapzen\/tilequeue,tilezen\/tilequeue"} {"commit":"db78d24462f10561aab1bd2639042e78f07acc91","old_file":"resolwe_bio\/__about__.py","new_file":"resolwe_bio\/__about__.py","old_contents":"\"\"\"Central place for package metadata.\"\"\"\n\n# NOTE: We use __title__ instead of simply __name__ since the latter would\n# interfere with a global variable __name__ denoting object's name.\n__title__ = 'resolwe-bio'\n__summary__ = 'Bioinformatics pipelines for the Resolwe platform'\n__url__ = 'https:\/\/github.com\/genialis\/resolwe-bio'\n\n# Semantic versioning is used. For more information see:\n# https:\/\/packaging.python.org\/en\/latest\/distributing\/#semantic-versioning-preferred\n__version__ = '8.2.0a1'\n\n__author__ = 'Genialis d.o.o.'\n__email__ = 'dev-team@genialis.com'\n\n__license__ = 'Apache License (2.0)'\n__copyright__ = '2015-2018, ' + __author__\n\n__all__ = (\n \"__title__\", \"__summary__\", \"__url__\", \"__version__\", \"__author__\",\n \"__email__\", \"__license__\", \"__copyright__\",\n)\n","new_contents":"\"\"\"Central place for package metadata.\"\"\"\n\n# NOTE: We use __title__ instead of simply __name__ since the latter would\n# interfere with a global variable __name__ denoting object's name.\n__title__ = 'resolwe-bio'\n__summary__ = 'Bioinformatics pipelines for the Resolwe platform'\n__url__ = 'https:\/\/github.com\/genialis\/resolwe-bio'\n\n# Semantic versioning is used. For more information see:\n# https:\/\/packaging.python.org\/en\/latest\/distributing\/#semantic-versioning-preferred\n__version__ = '9.0.0a1'\n\n__author__ = 'Genialis d.o.o.'\n__email__ = 'dev-team@genialis.com'\n\n__license__ = 'Apache License (2.0)'\n__copyright__ = '2015-2018, ' + __author__\n\n__all__ = (\n \"__title__\", \"__summary__\", \"__url__\", \"__version__\", \"__author__\",\n \"__email__\", \"__license__\", \"__copyright__\",\n)\n","subject":"Bump version to 9.0.0a1 due to backward incompatible changes","message":"Bump version to 9.0.0a1 due to backward incompatible changes\n","lang":"Python","license":"apache-2.0","repos":"genialis\/resolwe-bio,genialis\/resolwe-bio,genialis\/resolwe-bio,genialis\/resolwe-bio"} {"commit":"7e8623f750abb9d5d46be25ca184ab0036e7a572","old_file":"runapp.py","new_file":"runapp.py","old_contents":"# Copyright 2014 Dave Kludt\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom anchor import app\n\n\nif __name__ == '__main__':\n app.run(port=5000, debug=True)\n","new_contents":"# Copyright 2014 Dave Kludt\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom anchor import app\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, debug=True)\n","subject":"Set the host to use all IPs when runap is used","message":"Set the host to use all IPs when runap is used\n","lang":"Python","license":"apache-2.0","repos":"oldarmyc\/anchor,oldarmyc\/anchor,oldarmyc\/anchor"} {"commit":"8d02d9cf5e07951a80bf424334ba59af92cfd6cc","old_file":"test\/suite\/out\/long_lines.py","new_file":"test\/suite\/out\/long_lines.py","old_contents":"if True:\n if True:\n if True:\n self.__heap.sort(\n ) # pylint: builtin sort probably faster than O(n)-time heapify\n\n if True:\n foo = '( ' + \\\n array[0] + ' '\n","new_contents":"if True:\n if True:\n if True:\n self.__heap.sort(\n ) # pylint: builtin sort probably faster than O(n)-time heapify\n\n if True:\n foo = '( ' + array[0] + ' '\n","subject":"Update due to logical line changes","message":"Update due to logical line changes\n","lang":"Python","license":"mit","repos":"vauxoo-dev\/autopep8,SG345\/autopep8,MeteorAdminz\/autopep8,Vauxoo\/autopep8,SG345\/autopep8,hhatto\/autopep8,Vauxoo\/autopep8,MeteorAdminz\/autopep8,hhatto\/autopep8,vauxoo-dev\/autopep8"} {"commit":"45c7e910f13a43427359801782eef7ce537d6f5f","old_file":"delayed_assert\/__init__.py","new_file":"delayed_assert\/__init__.py","old_contents":"from delayed_assert.delayed_assert import expect, assert_expectations","new_contents":"import sys\n\nif sys.version_info > (3, 0): # Python 3 and above\n from delayed_assert.delayed_assert import expect, assert_expectations\nelse: # for Python 2 \n from delayed_assert import expect, assert_expectations\n","subject":"Support for python 2 and 3","message":"Support for python 2 and 3","lang":"Python","license":"unlicense","repos":"pr4bh4sh\/python-delayed-assert"} {"commit":"8154b206160cde249c474f5905a60b9a8086c910","old_file":"conftest.py","new_file":"conftest.py","old_contents":"# Copyright (c) 2016,2019 MetPy Developers.\n# Distributed under the terms of the BSD 3-Clause License.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Configure pytest for metpy.\"\"\"\n\nimport os\n\nimport matplotlib\nimport matplotlib.pyplot\nimport numpy\nimport pandas\nimport pytest\nimport scipy\nimport xarray\n\nimport metpy.calc\n\n# Need to disable fallback before importing pint\nos.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = '0'\nimport pint # noqa: I100, E402\n\n\ndef pytest_report_header(config, startdir):\n \"\"\"Add dependency information to pytest output.\"\"\"\n return ('Dependencies: Matplotlib ({}), NumPy ({}), Pandas ({}), '\n 'Pint ({}), SciPy ({}), Xarray ({})'.format(matplotlib.__version__,\n numpy.__version__, pandas.__version__,\n pint.__version__, scipy.__version__,\n xarray.__version__))\n\n\n@pytest.fixture(autouse=True)\ndef doctest_available_modules(doctest_namespace):\n \"\"\"Make modules available automatically to doctests.\"\"\"\n doctest_namespace['metpy'] = metpy\n doctest_namespace['metpy.calc'] = metpy.calc\n doctest_namespace['plt'] = matplotlib.pyplot\n","new_contents":"# Copyright (c) 2016,2019 MetPy Developers.\n# Distributed under the terms of the BSD 3-Clause License.\n# SPDX-License-Identifier: BSD-3-Clause\n\"\"\"Configure pytest for metpy.\"\"\"\n\nimport os\n\nimport matplotlib\nimport matplotlib.pyplot\nimport numpy\nimport pandas\nimport pooch\nimport pytest\nimport scipy\nimport traitlets\nimport xarray\n\nimport metpy.calc\n\n# Need to disable fallback before importing pint\nos.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = '0'\nimport pint # noqa: I100, E402\n\n\ndef pytest_report_header(config, startdir):\n \"\"\"Add dependency information to pytest output.\"\"\"\n return (f'Dep Versions: Matplotlib {matplotlib.__version__}, '\n f'NumPy {numpy.__version__}, SciPy {scipy.__version__}, '\n f'Xarray {xarray.__version__}, Pint {pint.__version__}, '\n f'Pandas {pandas.__version__}, Traitlets {traitlets.__version__}, '\n f'Pooch {pooch.version.full_version}')\n\n\n@pytest.fixture(autouse=True)\ndef doctest_available_modules(doctest_namespace):\n \"\"\"Make modules available automatically to doctests.\"\"\"\n doctest_namespace['metpy'] = metpy\n doctest_namespace['metpy.calc'] = metpy.calc\n doctest_namespace['plt'] = matplotlib.pyplot\n","subject":"Print out all dependency versions at the start of pytest","message":"TST: Print out all dependency versions at the start of pytest\n","lang":"Python","license":"bsd-3-clause","repos":"Unidata\/MetPy,dopplershift\/MetPy,Unidata\/MetPy,dopplershift\/MetPy"} {"commit":"5f62f830d184c0f99b384f0653231dab52fbad50","old_file":"conftest.py","new_file":"conftest.py","old_contents":"import logging\nimport os\nimport signal\nimport subprocess\nimport time\n\nimport pytest\n\n\nlog = logging.getLogger(\"test\")\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s %(levelname)s [%(name)s] %(message)s')\n\n\n@pytest.fixture\ndef basedir(tmpdir):\n # 1. Create real file system with a special __ready__ file.\n realfs = tmpdir.mkdir(\"realfs\")\n realfs.join(\"__ready__\").write(\"\")\n\n # 2. Create slowfs mountpoint\n slowfs = tmpdir.mkdir(\"slowfs\")\n\n # 3. Start slowfs\n log.debug(\"Starting slowfs...\")\n cmd = [\".\/slowfs\", str(realfs), str(slowfs)]\n if os.environ.get(\"DEBUG\"):\n cmd.append(\"--debug\")\n p = subprocess.Popen(cmd)\n try:\n # 4. Wait until __ready__ is visible via slowfs...\n log.debug(\"Waiting until mount is ready...\")\n ready = slowfs.join(\"__ready__\")\n for i in range(10):\n time.sleep(0.1)\n log.debug(\"Checking mount...\")\n if ready.exists():\n log.debug(\"Mount is ready\")\n break\n else:\n raise RuntimeError(\"Timeout waiting for slowfs mount %r\" % slowfs)\n\n # 4. We are ready for the test\n yield tmpdir\n finally:\n # 5. Interrupt slowfs, unmounting\n log.debug(\"Stopping slowfs...\")\n p.send_signal(signal.SIGINT)\n p.wait()\n log.debug(\"Stopped\")\n","new_contents":"import logging\nimport os\nimport signal\nimport subprocess\nimport time\n\nimport pytest\n\n\nlog = logging.getLogger(\"test\")\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s %(levelname)s [%(name)s] %(message)s')\n\n\n@pytest.fixture\ndef basedir(tmpdir):\n # 1. Create real file system with a special __ready__ file.\n realfs = tmpdir.mkdir(\"realfs\")\n realfs.join(\"__ready__\").write(\"\")\n\n # 2. Create slowfs mountpoint\n slowfs = tmpdir.mkdir(\"slowfs\")\n\n # 3. Start slowfs\n log.debug(\"Starting slowfs...\")\n cmd = [\"python\", \"slowfs\", str(realfs), str(slowfs)]\n if os.environ.get(\"DEBUG\"):\n cmd.append(\"--debug\")\n p = subprocess.Popen(cmd)\n try:\n # 4. Wait until __ready__ is visible via slowfs...\n log.debug(\"Waiting until mount is ready...\")\n ready = slowfs.join(\"__ready__\")\n for i in range(10):\n time.sleep(0.1)\n log.debug(\"Checking mount...\")\n if ready.exists():\n log.debug(\"Mount is ready\")\n break\n else:\n raise RuntimeError(\"Timeout waiting for slowfs mount %r\" % slowfs)\n\n # 4. We are ready for the test\n yield tmpdir\n finally:\n # 5. Interrupt slowfs, unmounting\n log.debug(\"Stopping slowfs...\")\n p.send_signal(signal.SIGINT)\n p.wait()\n log.debug(\"Stopped\")\n","subject":"Fix tests, broken by making slowfs a script","message":"Fix tests, broken by making slowfs a script\n\nIn the tests we must run the script using python so we run with the\ncorrect python from .tox\/\/bin\/python.\n","lang":"Python","license":"bsd-2-clause","repos":"nirs\/slowfs"} {"commit":"f7fa8b72b8d8d1b7bfcd6c738520fc87cd20e320","old_file":"ixdjango\/tests\/__init__.py","new_file":"ixdjango\/tests\/__init__.py","old_contents":"\"\"\"\nHook into the test runner\n\"\"\"\n\nimport subprocess\n\nfrom django.test.simple import DjangoTestSuiteRunner\nfrom django.utils import unittest\n\nfrom ixdjango.test_suite.utils import (CoreUtilsTests)\n\n\nclass TestRunner(DjangoTestSuiteRunner):\n \"\"\"\n Place where we hook into DjangoTestSuiteRunner\n \"\"\"\n\n def setup_test_environment(self, *args, **kwargs):\n \"\"\"\n Hook to set up the test environment\n \"\"\"\n\n from django.conf import settings\n\n print \"Running hooks from %s\" % __name__\n\n username = settings.DATABASES['default']['USER']\n\n print \" - Ensure %s can create a test DB\" % username\n subprocess.call(['sudo', 'su', 'postgres', '-c',\n \"psql -c 'alter user %s with createdb;'\" % username])\n\n return super(TestRunner, self).setup_test_environment(*args, **kwargs)\n\n\ndef suite():\n \"\"\"\n Put together a suite of tests to run for the application\n \"\"\"\n loader = unittest.TestLoader()\n\n all_tests = unittest.TestSuite([\n #\n # Utilities test cases\n #\n loader.loadTestsFromTestCase(CoreUtilsTests)\n ])\n\n return all_tests\n","new_contents":"\"\"\"\nHook into the test runner\n\"\"\"\n\nimport subprocess\n\ntry:\n from django.test.runner import DiscoverRunner as BaseTestRunner\nexcept ImportError:\n from django.test.simple import DjangoTestSuiteRunner as BaseTestRunner\nfrom django.utils import unittest\n\nfrom ixdjango.test_suite.utils import (CoreUtilsTests)\n\n\nclass TestRunner(BaseTestRunner):\n \"\"\"\n Place where we hook into DjangoTestSuiteRunner\n \"\"\"\n\n def setup_test_environment(self, *args, **kwargs):\n \"\"\"\n Hook to set up the test environment\n \"\"\"\n\n from django.conf import settings\n\n print \"Running hooks from %s\" % __name__\n\n username = settings.DATABASES['default']['USER']\n\n print \" - Ensure %s can create a test DB\" % username\n subprocess.call(['sudo', 'su', 'postgres', '-c',\n \"psql -c 'alter user %s with createdb;'\" % username])\n\n return super(TestRunner, self).setup_test_environment(*args, **kwargs)\n\n\ndef suite():\n \"\"\"\n Put together a suite of tests to run for the application\n \"\"\"\n loader = unittest.TestLoader()\n\n all_tests = unittest.TestSuite([\n #\n # Utilities test cases\n #\n loader.loadTestsFromTestCase(CoreUtilsTests)\n ])\n\n return all_tests\n","subject":"Use DiscoverRunner from Django 1.6 if available","message":"Use DiscoverRunner from Django 1.6 if available\n","lang":"Python","license":"mit","repos":"infoxchange\/ixdjango"} {"commit":"4241c6cbd9625c61a32ded5725e583da2b63a377","old_file":"homedisplay\/display\/views.py","new_file":"homedisplay\/display\/views.py","old_contents":"from django.http import HttpResponseRedirect, HttpResponse, Http404\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.views.generic import View\nfrom homedisplay.utils import publish_ws\n\nclass Wrapped(View):\n def get(self, request, *args, **kwargs):\n return render_to_response(\"frame.html\", {\"frame_src\": \"\/homecontroller\/display\/content\/%s\" % kwargs.get(\"view\") }, context_instance=RequestContext(request))\n","new_contents":"from django.http import HttpResponseRedirect, HttpResponse, Http404\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.views.generic import View\nfrom homedisplay.utils import publish_ws\n\nclass Wrapped(View):\n def get(self, request, *args, **kwargs):\n return render_to_response(\"main\/frame.html\", {\"frame_src\": \"\/homecontroller\/display\/content\/%s\" % kwargs.get(\"view\") }, context_instance=RequestContext(request))\n","subject":"Use correct path for frame template","message":"Use correct path for frame template\n","lang":"Python","license":"bsd-3-clause","repos":"ojarva\/home-info-display,ojarva\/home-info-display,ojarva\/home-info-display,ojarva\/home-info-display"} {"commit":"ee03f3ae0d0501568cec87d8d4d7114441c19776","old_file":"conftest.py","new_file":"conftest.py","old_contents":"collect_ignore = [\"setup.py\"]\n","new_contents":"import tempfile\nimport shutil\n\nimport jedi\n\n\ncollect_ignore = [\"setup.py\"]\n\n\n# The following hooks (pytest_configure, pytest_unconfigure) are used\n# to modify `jedi.settings.cache_directory` because `clean_jedi_cache`\n# has no effect during doctests. Without these hooks, doctests uses\n# user's cache (e.g., ~\/.cache\/jedi\/). We should remove this\n# workaround once the problem is fixed in py.test.\n#\n# See:\n# - https:\/\/github.com\/davidhalter\/jedi\/pull\/168\n# - https:\/\/bitbucket.org\/hpk42\/pytest\/issue\/275\/\n\njedi_cache_directory_orig = None\njedi_cache_directory_temp = None\n\n\ndef pytest_configure(config):\n global jedi_cache_directory_orig, jedi_cache_directory_temp\n jedi_cache_directory_orig = jedi.settings.cache_directory\n jedi_cache_directory_temp = tempfile.mkdtemp(prefix='jedi-test-')\n jedi.settings.cache_directory = jedi_cache_directory_temp\n\n\ndef pytest_unconfigure(config):\n global jedi_cache_directory_orig, jedi_cache_directory_temp\n jedi.settings.cache_directory = jedi_cache_directory_orig\n shutil.rmtree(jedi_cache_directory_temp)\n","subject":"Use pytest_(un)configure to setup cache_directory","message":"Use pytest_(un)configure to setup cache_directory\n","lang":"Python","license":"mit","repos":"jonashaag\/jedi,jonashaag\/jedi,flurischt\/jedi,WoLpH\/jedi,tjwei\/jedi,mfussenegger\/jedi,mfussenegger\/jedi,tjwei\/jedi,dwillmer\/jedi,WoLpH\/jedi,flurischt\/jedi,dwillmer\/jedi"} {"commit":"62ad2eb82c037350f25d3e575e59f16740365159","old_file":"pies\/ast.py","new_file":"pies\/ast.py","old_contents":"from __future__ import absolute_import\n\nfrom ast import *\n\nfrom .version_info import PY2\n\nif PY2:\n Try = TryExcept\n\n def argument_names(node):\n return [isinstance(arg, Name) and arg.id or None for arg in node.args.args]\n\n def kw_only_argument_names(node):\n return []\n\n def kw_only_default_count(node):\n return 0\nelse:\n TryFinally = ()\n\n def argument_names(node):\n return [arg.arg for arg in node.args.args]\n\n def kw_only_argument_names(node):\n return [arg.arg for arg in node.args.kwonlyargs]\n\n def kw_only_default_count(node):\n return sum(1 for n in node.args.kw_defaults if n is not None)\n","new_contents":"from __future__ import absolute_import\n\nimport sys\nfrom ast import *\n\nfrom .version_info import PY2\n\nif PY2 or sys.version_info[1] <= 2:\n Try = TryExcept\nelse:\n TryFinally = ()\n\nif PY2:\n def argument_names(node):\n return [isinstance(arg, Name) and arg.id or None for arg in node.args.args]\n\n def kw_only_argument_names(node):\n return []\n\n def kw_only_default_count(node):\n return 0\nelse:\n def argument_names(node):\n return [arg.arg for arg in node.args.args]\n\n def kw_only_argument_names(node):\n return [arg.arg for arg in node.args.kwonlyargs]\n\n def kw_only_default_count(node):\n return sum(1 for n in node.args.kw_defaults if n is not None)\n","subject":"Fix small incompatibility with Python 3.2","message":"Fix small incompatibility with Python 3.2\n","lang":"Python","license":"mit","repos":"lisongmin\/pies,AbsoluteMSTR\/pies,timothycrosley\/pies,AbsoluteMSTR\/pies,timothycrosley\/pies,lisongmin\/pies"} {"commit":"edb4e28bc70e6346ab1e443c8653bdf1a16652e7","old_file":"hackernews_scraper\/__init__.py","new_file":"hackernews_scraper\/__init__.py","old_contents":"__version__ = \"0.3.1\"\n\nfrom hackernews_scraper.hnscraper import (CommentScraper, StoryScraper,\n TooManyItemsException)\n","new_contents":"__version__ = \"1.0.0\"\n\nfrom hackernews_scraper.hnscraper import (CommentScraper, StoryScraper,\n TooManyItemsException)\n","subject":"Bump to first stable release.","message":"Bump to first stable release.\n\nThis is running in production.\n","lang":"Python","license":"bsd-2-clause","repos":"NiGhTTraX\/hackernews-scraper"} {"commit":"5cbf2988e9064a49e2d745694c8233513be63a0b","old_file":"openings_mover.py","new_file":"openings_mover.py","old_contents":"import random\nimport pdb\n\nfrom defines import *\n\nclass OpeningsMover(object):\n def __init__(self, o_mgr, game):\n self.o_mgr = o_mgr\n self.game = game\n\n def get_a_good_move(self):\n wins = 0\n losses = 0\n totals = []\n\n colour = self.game.to_move_colour()\n max_rating_factor = 1\n\n move_games = self.o_mgr.get_move_games(self.game)\n \n for mg in move_games:\n move, games = mg\n for g in games:\n win_colour = g.get_won_by()\n\n if win_colour == colour:\n wins += 1\n else:\n assert(win_colour == opposite_colour(colour))\n losses += 1\n\n # Calc & save the maximum rating of the players\n # who made this move\n move_player = g.get_player(colour)\n\n if move_player:\n max_rating_factor = \\\n max(max_rating_factor, move_player.rating_factor())\n\n totals.append((move, wins, losses, max_rating_factor))\n\n total_score = 1 # For fall through to inner filter\n\n move_scores = []\n for move, wins, losses, mrf in totals:\n score = (mrf * (wins))\/(losses or .2)\n move_scores.append((move, score))\n total_score += score\n \n rand_val = random.random() * total_score\n\n for move, score in move_scores:\n if score > rand_val:\n return move\n rand_val -= score\n\n # Fall through to inner filter\n return None\n\n","new_contents":"import random\nimport pdb\n\nfrom defines import *\n\nclass OpeningsMover(object):\n def __init__(self, o_mgr, game):\n self.o_mgr = o_mgr\n self.game = game\n\n def get_a_good_move(self):\n wins = 0\n losses = 0\n totals = []\n\n colour = self.game.to_move_colour()\n max_rating_factor = 1\n\n move_games = self.o_mgr.get_move_games(self.game)\n \n for mg in move_games:\n move, games = mg\n for pg in games:\n win_colour = pg.won_by\n\n if win_colour == colour:\n wins += 1\n elif win_colour == opposite_colour(colour):\n losses += 1\n # else ignore draws and unfinished games (latter shouldn't get here)\n\n move_rating = pg.get_rating(colour)\n\n # TODO: More smarts here\n max_rating_factor = \\\n max(max_rating_factor, move_rating)\n\n\n totals.append((move, wins, losses, max_rating_factor))\n\n total_score = 1 # For fall through to inner filter\n\n move_scores = []\n for move, wins, losses, mrf in totals:\n score = (mrf * (wins))\/(losses or .2)\n move_scores.append((move, score))\n total_score += score\n \n rand_val = random.random() * total_score\n\n for move, score in move_scores:\n if score > rand_val:\n return move\n rand_val -= score\n\n # Fall through to inner filter\n return None\n\n","subject":"Use preserved games for opening move selection","message":"Use preserved games for opening move selection\n","lang":"Python","license":"mit","repos":"cropleyb\/pentai,cropleyb\/pentai,cropleyb\/pentai"} {"commit":"99bcbd8795f3e2b1a10ac8fa81dd69d1cad7c022","old_file":"yunity\/api\/serializers.py","new_file":"yunity\/api\/serializers.py","old_contents":"def user(model):\n if not model.is_authenticated():\n return {}\n\n return {\n 'id': model.id,\n 'display_name': model.display_name,\n 'first_name': model.first_name,\n 'last_name': model.last_name,\n }\n\n\ndef category(model):\n return {\n 'id': model.id,\n 'name': model.name,\n 'parent': model.parent_id,\n }\n\n\ndef conversation(model):\n participants = [_['id'] for _ in model.participants.order_by('id').values('id')]\n newest_message = model.messages.order_by('-created_at').first()\n return {\n 'id': model.id,\n 'name': model.name,\n 'participants': participants,\n 'message': conversation_message(newest_message),\n }\n\n\ndef conversation_message(model):\n return {\n 'id': model.id,\n 'sender': model.sent_by_id,\n 'created_at': model.created_at.isoformat(),\n 'content': model.content,\n }\n","new_contents":"def user(model):\n if not model.is_authenticated():\n return {}\n\n return {\n 'id': model.id,\n 'display_name': model.display_name,\n 'first_name': model.first_name,\n 'last_name': model.last_name,\n }\n\n\ndef category(model):\n return {\n 'id': model.id,\n 'name': model.name,\n 'parent': model.parent_id,\n }\n\n\ndef conversation(model):\n participants = [_['id'] for _ in model.participants.order_by('id').values('id')]\n newest_message = model.messages.order_by('-created_at').first()\n return {\n 'id': model.id,\n 'name': model.name,\n 'participants': participants,\n 'message': conversation_message(newest_message),\n }\n\n\ndef conversation_message(model):\n if model:\n return {\n 'id': model.id,\n 'sender': model.sent_by_id,\n 'created_at': model.created_at.isoformat(),\n 'content': model.content,\n }\n else:\n return None\n","subject":"Allow empty conversations to be serialized","message":"Allow empty conversations to be serialized\n\nA conversation may exist without any content. The serializer then\nreturns an empty message value.\n","lang":"Python","license":"agpl-3.0","repos":"yunity\/foodsaving-backend,yunity\/yunity-core,yunity\/foodsaving-backend,yunity\/foodsaving-backend,yunity\/yunity-core"} {"commit":"d6f2b132844d1923932447c0ce67c581f723f433","old_file":"wagtail\/wagtailadmin\/menu.py","new_file":"wagtail\/wagtailadmin\/menu.py","old_contents":"from __future__ import unicode_literals\n\nfrom six import text_type\n\nfrom django.utils.text import slugify\nfrom django.utils.html import format_html\n\n\nclass MenuItem(object):\n def __init__(self, label, url, name=None, classnames='', order=1000):\n self.label = label\n self.url = url\n self.classnames = classnames\n self.name = (name or slugify(text_type(label)))\n self.order = order\n\n def render_html(self):\n return format_html(\n \"\"\"
  • {3}<\/a><\/li>\"\"\",\n self.name, self.url, self.classnames, self.label)\n","new_contents":"from __future__ import unicode_literals\n\nfrom six import text_type\n\ntry:\n # renamed util -> utils in Django 1.7; try the new name first\n from django.forms.utils import flatatt\nexcept ImportError:\n from django.forms.util import flatatt\n\nfrom django.utils.text import slugify\nfrom django.utils.html import format_html\n\n\nclass MenuItem(object):\n def __init__(self, label, url, name=None, classnames='', attrs=None, order=1000):\n self.label = label\n self.url = url\n self.classnames = classnames\n self.name = (name or slugify(text_type(label)))\n self.order = order\n\n if attrs:\n self.attr_string = flatatt(attrs)\n else:\n self.attr_string = \"\"\n\n def render_html(self):\n return format_html(\n \"\"\"
  • {4}<\/a><\/li>\"\"\",\n self.name, self.url, self.classnames, self.attr_string, self.label)\n","subject":"Support passing html attributes into MenuItem","message":"Support passing html attributes into MenuItem\n","lang":"Python","license":"bsd-3-clause","repos":"JoshBarr\/wagtail,m-sanders\/wagtail,hamsterbacke23\/wagtail,benemery\/wagtail,jordij\/wagtail,nutztherookie\/wagtail,mixxorz\/wagtail,nutztherookie\/wagtail,dresiu\/wagtail,serzans\/wagtail,mixxorz\/wagtail,bjesus\/wagtail,nrsimha\/wagtail,nilnvoid\/wagtail,inonit\/wagtail,torchbox\/wagtail,wagtail\/wagtail,dresiu\/wagtail,davecranwell\/wagtail,timorieber\/wagtail,kurtrwall\/wagtail,Pennebaker\/wagtail,kaedroho\/wagtail,kurtrwall\/wagtail,thenewguy\/wagtail,jnns\/wagtail,nealtodd\/wagtail,rsalmaso\/wagtail,taedori81\/wagtail,mephizzle\/wagtail,stevenewey\/wagtail,quru\/wagtail,marctc\/wagtail,tangentlabs\/wagtail,Klaudit\/wagtail,quru\/wagtail,gogobook\/wagtail,kurtrwall\/wagtail,takeshineshiro\/wagtail,rsalmaso\/wagtail,quru\/wagtail,wagtail\/wagtail,thenewguy\/wagtail,benjaoming\/wagtail,mixxorz\/wagtail,taedori81\/wagtail,nrsimha\/wagtail,taedori81\/wagtail,nilnvoid\/wagtail,zerolab\/wagtail,mephizzle\/wagtail,rjsproxy\/wagtail,darith27\/wagtail,benjaoming\/wagtail,iho\/wagtail,jnns\/wagtail,rv816\/wagtail,nealtodd\/wagtail,torchbox\/wagtail,serzans\/wagtail,mephizzle\/wagtail,WQuanfeng\/wagtail,takeflight\/wagtail,mjec\/wagtail,thenewguy\/wagtail,torchbox\/wagtail,rjsproxy\/wagtail,jorge-marques\/wagtail,m-sanders\/wagtail,iho\/wagtail,benemery\/wagtail,serzans\/wagtail,stevenewey\/wagtail,janusnic\/wagtail,JoshBarr\/wagtail,chimeno\/wagtail,Tivix\/wagtail,chimeno\/wagtail,nilnvoid\/wagtail,Klaudit\/wagtail,chrxr\/wagtail,marctc\/wagtail,KimGlazebrook\/wagtail-experiment,gogobook\/wagtail,zerolab\/wagtail,dresiu\/wagtail,takeflight\/wagtail,nimasmi\/wagtail,nimasmi\/wagtail,JoshBarr\/wagtail,Pennebaker\/wagtail,hanpama\/wagtail,davecranwell\/wagtail,iansprice\/wagtail,kaedroho\/wagtail,inonit\/wagtail,mixxorz\/wagtail,rv816\/wagtail,KimGlazebrook\/wagtail-experiment,stevenewey\/wagtail,inonit\/wagtail,jordij\/wagtail,kurtw\/wagtail,bjesus\/wagtail,mephizzle\/wagtail,jorge-marques\/wagtail,torchbox\/wagtail,nilnvoid\/wagtail,chimeno\/wagtail,gasman\/wagtail,mjec\/wagtail,dresiu\/wagtail,hanpama\/wagtail,hamsterbacke23\/wagtail,rv816\/wagtail,KimGlazebrook\/wagtail-experiment,tangentlabs\/wagtail,mayapurmedia\/wagtail,willcodefortea\/wagtail,FlipperPA\/wagtail,FlipperPA\/wagtail,gogobook\/wagtail,timorieber\/wagtail,jnns\/wagtail,m-sanders\/wagtail,nutztherookie\/wagtail,nimasmi\/wagtail,hamsterbacke23\/wagtail,mjec\/wagtail,thenewguy\/wagtail,wagtail\/wagtail,kaedroho\/wagtail,willcodefortea\/wagtail,willcodefortea\/wagtail,bjesus\/wagtail,gasman\/wagtail,chrxr\/wagtail,gogobook\/wagtail,zerolab\/wagtail,rjsproxy\/wagtail,wagtail\/wagtail,nrsimha\/wagtail,Klaudit\/wagtail,iho\/wagtail,mjec\/wagtail,chrxr\/wagtail,timorieber\/wagtail,FlipperPA\/wagtail,benemery\/wagtail,mikedingjan\/wagtail,mikedingjan\/wagtail,gasman\/wagtail,janusnic\/wagtail,Toshakins\/wagtail,WQuanfeng\/wagtail,rv816\/wagtail,takeflight\/wagtail,WQuanfeng\/wagtail,janusnic\/wagtail,rjsproxy\/wagtail,nutztherookie\/wagtail,janusnic\/wagtail,iansprice\/wagtail,JoshBarr\/wagtail,jnns\/wagtail,takeshineshiro\/wagtail,kaedroho\/wagtail,willcodefortea\/wagtail,taedori81\/wagtail,bjesus\/wagtail,jorge-marques\/wagtail,Tivix\/wagtail,darith27\/wagtail,marctc\/wagtail,mayapurmedia\/wagtail,gasman\/wagtail,mayapurmedia\/wagtail,tangentlabs\/wagtail,dresiu\/wagtail,iansprice\/wagtail,kaedroho\/wagtail,kurtw\/wagtail,inonit\/wagtail,benjaoming\/wagtail,Tivix\/wagtail,zerolab\/wagtail,stevenewey\/wagtail,mayapurmedia\/wagtail,davecranwell\/wagtail,jorge-marques\/wagtail,darith27\/wagtail,chimeno\/wagtail,Toshakins\/wagtail,rsalmaso\/wagtail,nrsimha\/wagtail,gasman\/wagtail,Tivix\/wagtail,nealtodd\/wagtail,Pennebaker\/wagtail,rsalmaso\/wagtail,jordij\/wagtail,jorge-marques\/wagtail,benemery\/wagtail,iho\/wagtail,hamsterbacke23\/wagtail,FlipperPA\/wagtail,hanpama\/wagtail,takeshineshiro\/wagtail,kurtw\/wagtail,nimasmi\/wagtail,iansprice\/wagtail,kurtrwall\/wagtail,nealtodd\/wagtail,davecranwell\/wagtail,rsalmaso\/wagtail,timorieber\/wagtail,Pennebaker\/wagtail,Klaudit\/wagtail,serzans\/wagtail,m-sanders\/wagtail,marctc\/wagtail,taedori81\/wagtail,darith27\/wagtail,thenewguy\/wagtail,chimeno\/wagtail,zerolab\/wagtail,takeflight\/wagtail,chrxr\/wagtail,mikedingjan\/wagtail,Toshakins\/wagtail,mikedingjan\/wagtail,KimGlazebrook\/wagtail-experiment,quru\/wagtail,Toshakins\/wagtail,tangentlabs\/wagtail,WQuanfeng\/wagtail,kurtw\/wagtail,mixxorz\/wagtail,hanpama\/wagtail,takeshineshiro\/wagtail,benjaoming\/wagtail,jordij\/wagtail,wagtail\/wagtail"} {"commit":"a056c630a197a070e55cce9f76124d56ba781e52","old_file":"app\/views\/main.py","new_file":"app\/views\/main.py","old_contents":"from flask import Blueprint, render_template\nfrom flask_login import login_required\n\nmain = Blueprint(\"main\", __name__)\n\n\n@main.route(\"\/\")\n@main.route(\"\/index\")\n@login_required\ndef index():\n return \"Logged in\"\n\n\n@main.route(\"\/login\")\ndef login():\n return render_template(\"login.html\")","new_contents":"from flask import Blueprint, render_template, g, redirect, url_for\nfrom flask_login import login_required, current_user, logout_user\n\nmain = Blueprint(\"main\", __name__)\n\n\n@main.route(\"\/\")\n@main.route(\"\/index\")\n@login_required\ndef index():\n return \"Logged in\"\n\n\n@main.route(\"\/login\")\ndef login():\n if g.user.is_authenticated:\n return redirect(url_for(\"main.index\"))\n\n return render_template(\"login.html\")\n\n\n@main.route(\"\/logout\")\ndef logout():\n logout_user()\n return redirect(url_for(\"main.login\"))\n\n\n@main.before_request\ndef before_request():\n g.user = current_user","subject":"Add logout and auth checks","message":"Add logout and auth checks\n","lang":"Python","license":"mit","repos":"Encrylize\/MyDictionary,Encrylize\/MyDictionary,Encrylize\/MyDictionary"} {"commit":"9c07f8fdb9c955f49cf6ff92a25b1c0629157811","old_file":"assembler6502.py","new_file":"assembler6502.py","old_contents":"#! \/usr\/bin\/env python\n\nimport sys\nimport assembler6502_tokenizer as tokenizer\nimport assembler6502_parser as parser\n\ndef output_byte(hexcode):\n sys.stdout.write(hexcode)\n #sys.stdout.write(chr(int(hexcode, 16)))\n\ndef main():\n code = \"\"\"\n; sample code\nbeginning:\n sty $44,X\n \"\"\"\n for line in code.split(\"\\n\"):\n hexcodes = parser.parse_line(line)\n for hexcode in hexcodes:\n output_byte(hexcode)\n print\n\nif __name__ == \"__main__\":\n main()\n\n","new_contents":"#! \/usr\/bin\/env python\n\nimport sys\nimport assembler6502_tokenizer as tokenizer\nimport assembler6502_parser as parser\n\ndef output_byte(hexcode):\n sys.stdout.write(hexcode + \"\\n\")\n #sys.stdout.write(chr(int(hexcode, 16)))\n\ndef main():\n code = sys.stdin.read()\n for line in code.split(\"\\n\"):\n hexcodes = parser.parse_line(line)\n for hexcode in hexcodes:\n output_byte(hexcode)\n\nif __name__ == \"__main__\":\n main()\n\n","subject":"Use stdin for assembler input","message":"Use stdin for assembler input\n","lang":"Python","license":"mit","repos":"technetia\/project-tdm,technetia\/project-tdm,technetia\/project-tdm"} {"commit":"358df6514b19424d5576d7a0a74ea15d71a3565b","old_file":"canaryd\/subprocess.py","new_file":"canaryd\/subprocess.py","old_contents":"import os\nimport shlex\nimport sys\n\nfrom canaryd_packages import six\n# Not ideal but using the vendored in (to requests) chardet package\nfrom canaryd_packages.requests.packages import chardet\n\nfrom canaryd.log import logger\n\n\nif os.name == 'posix' and sys.version_info[0] < 3:\n from canaryd_packages.subprocess32 import * # noqa\nelse:\n from subprocess import * # noqa\n\n\ndef get_command_output(command, *args, **kwargs):\n logger.debug('Executing command: {0}'.format(command))\n\n if (\n not kwargs.get('shell', False)\n and not isinstance(command, (list, tuple))\n ):\n command = shlex.split(command)\n\n output = check_output( # noqa\n command,\n close_fds=True,\n stderr=STDOUT, # noqa\n *args, **kwargs\n )\n\n if isinstance(output, six.binary_type):\n encoding = chardet.detect(output)['encoding']\n output = output.decode(encoding=encoding)\n\n return output\n","new_contents":"import os\nimport shlex\nimport sys\n\nfrom canaryd_packages import six\n# Not ideal but using the vendored in (to requests) chardet package\nfrom canaryd_packages.requests.packages import chardet\n\nfrom canaryd.log import logger\n\n\nif os.name == 'posix' and sys.version_info[0] < 3:\n from canaryd_packages.subprocess32 import * # noqa\nelse:\n from subprocess import * # noqa\n\n\ndef get_command_output(command, *args, **kwargs):\n logger.debug('Executing command: {0}'.format(command))\n\n if (\n not kwargs.get('shell', False)\n and not isinstance(command, (list, tuple))\n ):\n command = shlex.split(command)\n\n output = check_output( # noqa\n command,\n close_fds=True,\n stderr=STDOUT, # noqa\n *args, **kwargs\n )\n\n if isinstance(output, six.binary_type):\n encoding = chardet.detect(output)['encoding']\n output = output.decode(encoding)\n\n return output\n","subject":"Fix for python2.6: decode doesn't take keyword arguments.","message":"Fix for python2.6: decode doesn't take keyword arguments.\n","lang":"Python","license":"mit","repos":"Oxygem\/canaryd,Oxygem\/canaryd"} {"commit":"391ff28186e40bee9ba7966b739090d67d61b2a6","old_file":"APITaxi\/models\/security.py","new_file":"APITaxi\/models\/security.py","old_contents":"# -*- coding: utf8 -*-\nfrom flask.ext.security import UserMixin, RoleMixin\nfrom ..models import db\n\nroles_users = db.Table('roles_users',\n db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),\n db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))\n\nclass Role(db.Model, RoleMixin):\n id = db.Column(db.Integer(), primary_key=True)\n name = db.Column(db.String(80), unique=True)\n description = db.Column(db.String(255))\n\nclass User(db.Model, UserMixin):\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(255), unique=True)\n password = db.Column(db.String(255))\n active = db.Column(db.Boolean())\n confirmed_at = db.Column(db.DateTime())\n roles = db.relationship('Role', secondary=roles_users,\n backref=db.backref('users', lazy='dynamic'))\n apikey = db.Column(db.String(36), nullable=False)\n\n def get_user_from_api_key(self, apikey):\n user = self.user_model.query.filter_by(apikey=apikey)\n return user.get() or None\n","new_contents":"# -*- coding: utf8 -*-\nfrom flask.ext.security import UserMixin, RoleMixin\nfrom ..models import db\nfrom uuid import uuid4\n\n\nroles_users = db.Table('roles_users',\n db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),\n db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))\n\nclass Role(db.Model, RoleMixin):\n id = db.Column(db.Integer(), primary_key=True)\n name = db.Column(db.String(80), unique=True)\n description = db.Column(db.String(255))\n\nclass User(db.Model, UserMixin):\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(255), unique=True)\n password = db.Column(db.String(255))\n active = db.Column(db.Boolean())\n confirmed_at = db.Column(db.DateTime())\n roles = db.relationship('Role', secondary=roles_users,\n backref=db.backref('users', lazy='dynamic'))\n apikey = db.Column(db.String(36), nullable=False)\n\n def __init__(self, *args, **kwargs):\n kwargs['apikey'] = str(uuid4())\n super(self.__class__, self).__init__(**kwargs)\n\n def get_user_from_api_key(self, apikey):\n user = self.user_model.query.filter_by(apikey=apikey)\n return user.get() or None\n","subject":"Add apikey when creating a user","message":"Add apikey when creating a user\n","lang":"Python","license":"agpl-3.0","repos":"odtvince\/APITaxi,l-vincent-l\/APITaxi,l-vincent-l\/APITaxi,openmaraude\/APITaxi,odtvince\/APITaxi,odtvince\/APITaxi,odtvince\/APITaxi,openmaraude\/APITaxi"} {"commit":"8090fa9c072656497ff383e9b76d49af2955e420","old_file":"examples\/hopv\/hopv_graph_conv.py","new_file":"examples\/hopv\/hopv_graph_conv.py","old_contents":"\"\"\"\nScript that trains graph-conv models on HOPV dataset.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport numpy as np\n\nfrom models import GraphConvTensorGraph\n\nnp.random.seed(123)\nimport tensorflow as tf\ntf.set_random_seed(123)\nimport deepchem as dc\nfrom deepchem.molnet import load_hopv\n\n# Load HOPV dataset\nhopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv')\ntrain_dataset, valid_dataset, test_dataset = hopv_datasets\n\n# Fit models\nmetric = [\n dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode=\"regression\"),\n dc.metrics.Metric(\n dc.metrics.mean_absolute_error, np.mean, mode=\"regression\")\n]\n\n# Number of features on conv-mols\nn_feat = 75\n# Batch size of models\nbatch_size = 50\nmodel = GraphConvTensorGraph(\n len(hopv_tasks), batch_size=batch_size, mode='regression')\n\n# Fit trained model\nmodel.fit(train_dataset, nb_epoch=25)\n\nprint(\"Evaluating model\")\ntrain_scores = model.evaluate(train_dataset, metric, transformers)\nvalid_scores = model.evaluate(valid_dataset, metric, transformers)\n\nprint(\"Train scores\")\nprint(train_scores)\n\nprint(\"Validation scores\")\nprint(valid_scores)\n","new_contents":"\"\"\"\nScript that trains graph-conv models on HOPV dataset.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport numpy as np\n\nfrom models import GraphConvModel\n\nnp.random.seed(123)\nimport tensorflow as tf\ntf.set_random_seed(123)\nimport deepchem as dc\nfrom deepchem.molnet import load_hopv\n\n# Load HOPV dataset\nhopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv')\ntrain_dataset, valid_dataset, test_dataset = hopv_datasets\n\n# Fit models\nmetric = [\n dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode=\"regression\"),\n dc.metrics.Metric(\n dc.metrics.mean_absolute_error, np.mean, mode=\"regression\")\n]\n\n# Number of features on conv-mols\nn_feat = 75\n# Batch size of models\nbatch_size = 50\nmodel = GraphConvModel(\n len(hopv_tasks), batch_size=batch_size, mode='regression')\n\n# Fit trained model\nmodel.fit(train_dataset, nb_epoch=25)\n\nprint(\"Evaluating model\")\ntrain_scores = model.evaluate(train_dataset, metric, transformers)\nvalid_scores = model.evaluate(valid_dataset, metric, transformers)\n\nprint(\"Train scores\")\nprint(train_scores)\n\nprint(\"Validation scores\")\nprint(valid_scores)\n","subject":"Fix GraphConvTensorGraph to GraphConvModel in hopv example","message":"Fix GraphConvTensorGraph to GraphConvModel in hopv example\n","lang":"Python","license":"mit","repos":"Agent007\/deepchem,lilleswing\/deepchem,lilleswing\/deepchem,Agent007\/deepchem,peastman\/deepchem,miaecle\/deepchem,peastman\/deepchem,ktaneishi\/deepchem,miaecle\/deepchem,Agent007\/deepchem,deepchem\/deepchem,ktaneishi\/deepchem,deepchem\/deepchem,ktaneishi\/deepchem,miaecle\/deepchem,lilleswing\/deepchem"} {"commit":"66f06164a5654f2925fb16a1ce28638fd57e3a9e","old_file":"issue_tracker\/accounts\/urls.py","new_file":"issue_tracker\/accounts\/urls.py","old_contents":"from django.conf.urls.defaults import *\nfrom django.contrib.auth.views import logout_then_login, login\nfrom django.contrib.auth.forms import AuthenticationForm\n\nurlpatterns = patterns('',\n (r'^login\/$', login, {}, 'login' ),\n (r'^logout\/$', logout_then_login, {}, 'logout'),\n)\n","new_contents":"from django.conf.urls.defaults import *\nfrom django.contrib.auth.views import logout_then_login, login\nfrom accounts.views import register\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.forms import AuthenticationForm\n\nurlpatterns = patterns('',\n (r'^register\/$', register, {}, 'register' ),\n (r'^login\/$', login, {}, 'login' ),\n (r'^logout\/$', logout_then_login, {}, 'logout'),\n)\n","subject":"Add url mapping to register.","message":"Add url mapping to register.\n","lang":"Python","license":"mit","repos":"hfrequency\/django-issue-tracker"} {"commit":"e0d510b51f44b421696958660f2ca32ee41413bd","old_file":"click\/globals.py","new_file":"click\/globals.py","old_contents":"from threading import local\n\n\n_local = local()\n\n\ndef get_current_context(silent=False):\n \"\"\"Returns the current click context. This can be used as a way to\n access the current context object from anywhere. This is a more implicit\n alternative to the :func:`pass_context` decorator. This function is\n primarily useful for helpers such as :func:`echo` which might be\n interested in changing its behavior based on the current context.\n\n To push the current context, :meth:`Context.scope` can be used.\n\n .. versionadded:: 5.0\n\n :param silent: is set to `True` the return value is `None` if no context\n is available. The default behavior is to raise a\n :exc:`RuntimeError`.\n \"\"\"\n try:\n return getattr(_local, 'stack')[-1]\n except (AttributeError, IndexError):\n if not silent:\n raise RuntimeError('There is no active click context.')\n\n\ndef push_context(ctx):\n \"\"\"Pushes a new context to the current stack.\"\"\"\n _local.__dict__.setdefault('stack', []).append(ctx)\n\n\ndef pop_context():\n \"\"\"Removes the top level from the stack.\"\"\"\n _local.stack.pop()\n\n\ndef resolve_color_default(color=None):\n \"\"\"\"Internal helper to get the default value of the color flag. If a\n value is passed it's returned unchanged, otherwise it's looked up from\n the current context.\n \"\"\"\n if color is not None:\n return color\n ctx = get_current_context(silent=True)\n if ctx is not None:\n return ctx.color\n","new_contents":"from threading import local\n\n\n_local = local()\n\n\ndef get_current_context(silent=False):\n \"\"\"Returns the current click context. This can be used as a way to\n access the current context object from anywhere. This is a more implicit\n alternative to the :func:`pass_context` decorator. This function is\n primarily useful for helpers such as :func:`echo` which might be\n interested in changing its behavior based on the current context.\n\n To push the current context, :meth:`Context.scope` can be used.\n\n .. versionadded:: 5.0\n\n :param silent: if set to `True` the return value is `None` if no context\n is available. The default behavior is to raise a\n :exc:`RuntimeError`.\n \"\"\"\n try:\n return getattr(_local, 'stack')[-1]\n except (AttributeError, IndexError):\n if not silent:\n raise RuntimeError('There is no active click context.')\n\n\ndef push_context(ctx):\n \"\"\"Pushes a new context to the current stack.\"\"\"\n _local.__dict__.setdefault('stack', []).append(ctx)\n\n\ndef pop_context():\n \"\"\"Removes the top level from the stack.\"\"\"\n _local.stack.pop()\n\n\ndef resolve_color_default(color=None):\n \"\"\"\"Internal helper to get the default value of the color flag. If a\n value is passed it's returned unchanged, otherwise it's looked up from\n the current context.\n \"\"\"\n if color is not None:\n return color\n ctx = get_current_context(silent=True)\n if ctx is not None:\n return ctx.color\n","subject":"Fix get_current_context typo in docstring","message":"Fix get_current_context typo in docstring\n","lang":"Python","license":"bsd-3-clause","repos":"pallets\/click,mitsuhiko\/click"} {"commit":"1ad453f6d01d4007662fa63d59508d27bac029d5","old_file":"keras\/utils\/model_utils.py","new_file":"keras\/utils\/model_utils.py","old_contents":"from __future__ import print_function\nimport numpy as np\nimport theano\n\n\ndef print_layer_shapes(model, input_shape):\n \"\"\"\n Utility function that prints the shape of the output at each layer.\n\n Arguments:\n model: An instance of models.Model\n input_shape: The shape of the input you will provide to the model.\n \"\"\"\n input_var = model.get_input(train=False)\n input_tmp = np.zeros(input_shape, dtype=np.float32)\n print(\"input shape : \", input_shape)\n for l in model.layers:\n shape_f = theano.function([input_var], l.get_output(train=False).shape)\n out_shape = shape_f(input_tmp)\n print('shape after', l.get_config()['name'], \":\", out_shape)\n","new_contents":"from __future__ import print_function\nimport numpy as np\nimport theano\n\n\ndef print_layer_shapes(model, input_shape):\n \"\"\"\n Utility function that prints the shape of the output at each layer.\n\n Arguments:\n model: An instance of models.Model\n input_shape: The shape of the input you will provide to the model.\n \"\"\"\n # This is to handle the case where a model has been connected to a previous\n # layer (and therefore get_input would recurse into previous layer's\n # output).\n if hasattr(model.layers[0], 'previous'):\n # TODO: If the model is used as a part of another model, get_input will\n # return the input of the whole model and this won't work. So this is\n # not handled yet\n raise Exception(\"This function doesn't work on model used as subparts \"\n \" for other models\")\n\n input_var = model.get_input(train=False)\n input_tmp = np.zeros(input_shape, dtype=np.float32)\n print(\"input shape : \", input_shape)\n for l in model.layers:\n shape_f = theano.function([input_var], l.get_output(train=False).shape)\n out_shape = shape_f(input_tmp)\n print('shape after', l.get_config()['name'], \":\", out_shape)\n","subject":"Add check to print_layer_shapes to fail explicitely on model used connected to other models.","message":"Add check to print_layer_shapes to fail explicitely on model used connected to other models.","lang":"Python","license":"apache-2.0","repos":"asampat3090\/keras,xurantju\/keras,keras-team\/keras,cheng6076\/keras,rudaoshi\/keras,bottler\/keras,ashhher3\/keras,wxs\/keras,nzer0\/keras,rodrigob\/keras,pthaike\/keras,EderSantana\/keras,zxsted\/keras,abayowbo\/keras,zxytim\/keras,danielforsyth\/keras,hhaoyan\/keras,jalexvig\/keras,chenych11\/keras,brainwater\/keras,amy12xx\/keras,daviddiazvico\/keras,vseledkin\/keras,wubr2000\/keras,jasonyaw\/keras,fmacias64\/keras,jbolinge\/keras,pjadzinsky\/keras,LIBOTAO\/keras,dxj19831029\/keras,nebw\/keras,MagicSen\/keras,kuza55\/keras,Smerity\/keras,untom\/keras,nt\/keras,zhangxujinsh\/keras,marchick209\/keras,ml-lab\/keras,why11002526\/keras,iamtrask\/keras,DeepGnosis\/keras,keskarnitish\/keras,dribnet\/keras,zhmz90\/keras,stephenbalaban\/keras,iScienceLuvr\/keras,jiumem\/keras,JasonTam\/keras,xiaoda99\/keras,3dconv\/keras,tencrance\/keras,cvfish\/keras,navyjeff\/keras,Aureliu\/keras,florentchandelier\/keras,gamer13\/keras,kod3r\/keras,rlkelly\/keras,saurav111\/keras,relh\/keras,mikekestemont\/keras,eulerreich\/keras,sjuvekar\/keras,jimgoo\/keras,meanmee\/keras,happyboy310\/keras,gavinmh\/keras,Cadene\/keras,DLlearn\/keras,ogrisel\/keras,llcao\/keras,bboalimoe\/keras,printedheart\/keras,kemaswill\/keras,johmathe\/keras,Yingmin-Li\/keras,ledbetdr\/keras,ekamioka\/keras,imcomking\/Convolutional-GRU-keras-extension-,dhruvparamhans\/keras,dolaameng\/keras,jayhetee\/keras,yingzha\/keras,OlafLee\/keras,keras-team\/keras,nehz\/keras,harshhemani\/keras"} {"commit":"fb1422c22e570da21279edee0ea79605e74f7a92","old_file":"crispy\/__init__.py","new_file":"crispy\/__init__.py","old_contents":"import logging\n\nlogging.basicConfig(level=logging.WARNING)\n","new_contents":"import logging\n\n# These are required to activate the cx_Freeze hooks\nimport matplotlib\nimport matplotlib.backends.backend_qt5agg\nimport PyQt5.QtPrintSupport\n\nlogging.basicConfig(level=logging.WARNING)\n","subject":"Add imports imports to trigger cx_Freeze hooks","message":"Add imports imports to trigger cx_Freeze hooks\n","lang":"Python","license":"mit","repos":"mretegan\/crispy,mretegan\/crispy"} {"commit":"d6a03fad6c9280981ae3beee24de89bd6361bcc9","old_file":"dumbrepl.py","new_file":"dumbrepl.py","old_contents":"if __name__ == \"__main__\":\n import pycket.test.testhelper as th\n th.dumb_repl()\n\n","new_contents":"if __name__ == \"__main__\":\n import pycket.values\n import pycket.config\n from pycket.env import w_global_config\n #w_global_config.set_linklet_mode_off()\n import pycket.test.testhelper as th\n th.dumb_repl()\n\n","subject":"Make sure things are loaded right.","message":"Make sure things are loaded right.\n","lang":"Python","license":"mit","repos":"samth\/pycket,pycket\/pycket,pycket\/pycket,samth\/pycket,samth\/pycket,pycket\/pycket"} {"commit":"bd69ad0bf57876cef01cc8f7cdce49a301eb2444","old_file":"bin\/remotePush.py","new_file":"bin\/remotePush.py","old_contents":"import json,httplib\n\nconfig_data = json.load(open('conf\/net\/ext_service\/parse.json'))\n\nsilent_push_msg = {\n \"where\": {\n \"deviceType\": \"ios\"\n },\n \"data\": {\n # \"alert\": \"The Mets scored! The game is now tied 1-1.\",\n \"content-available\": 1,\n \"sound\": \"\",\n }\n}\n\nparse_headers = {\n \"X-Parse-Application-Id\": config_data[\"emission_id\"],\n \"X-Parse-REST-API-Key\": config_data[\"emission_key\"],\n \"Content-Type\": \"application\/json\"\n}\n\nconnection = httplib.HTTPSConnection('api.parse.com', 443)\nconnection.connect()\n\nconnection.request('POST', '\/1\/push', json.dumps(silent_push_msg), parse_headers)\n\nresult = json.loads(connection.getresponse().read())\nprint result\n\n","new_contents":"import json,httplib\nimport sys\n\nconfig_data = json.load(open('conf\/net\/ext_service\/parse.json'))\n\ninterval = sys.argv[1]\nprint \"pushing for interval %s\" % interval\n\nsilent_push_msg = {\n \"where\": {\n \"deviceType\": \"ios\"\n },\n \"channels\": [\n interval\n ],\n \"data\": {\n # \"alert\": \"The Mets scored! The game is now tied 1-1.\",\n \"content-available\": 1,\n \"sound\": \"\",\n }\n}\n\nparse_headers = {\n \"X-Parse-Application-Id\": config_data[\"emission_id\"],\n \"X-Parse-REST-API-Key\": config_data[\"emission_key\"],\n \"Content-Type\": \"application\/json\"\n}\n\nconnection = httplib.HTTPSConnection('api.parse.com', 443)\nconnection.connect()\n\nconnection.request('POST', '\/1\/push', json.dumps(silent_push_msg), parse_headers)\n\nresult = json.loads(connection.getresponse().read())\nprint result\n\n\n","subject":"Make the remote push script take in the interval as an argument","message":"Make the remote push script take in the interval as an argument\n\nWe will use the interval as the channel\n","lang":"Python","license":"bsd-3-clause","repos":"shankari\/e-mission-server,sunil07t\/e-mission-server,e-mission\/e-mission-server,e-mission\/e-mission-server,e-mission\/e-mission-server,sunil07t\/e-mission-server,sunil07t\/e-mission-server,yw374cornell\/e-mission-server,yw374cornell\/e-mission-server,shankari\/e-mission-server,e-mission\/e-mission-server,shankari\/e-mission-server,yw374cornell\/e-mission-server,yw374cornell\/e-mission-server,shankari\/e-mission-server,sunil07t\/e-mission-server"} {"commit":"3794fe611e5fbbe55506a7d2e59b2f3f872d8733","old_file":"backend\/controllers\/file_controller.py","new_file":"backend\/controllers\/file_controller.py","old_contents":"import os\nfrom werkzeug.utils import secure_filename\nimport config\nfrom flask_restful import Resource\nfrom flask import request, abort\n\n\ndef allowed_file(filename):\n return ('.' in filename and\n filename.rsplit('.', 1)[1].lower() in config.ALLOWED_EXTENSIONS)\n\n\nclass File(Resource):\n def post(self):\n if 'uploaded_data' not in request.files:\n abort(500)\n file = request.files['uploaded_data']\n if file.filename == '':\n abort(500)\n if allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(config.UPLOAD_FOLDER, filename))\n return {'response': 'File uploaded successfully'}\n\n def delete(self):\n filename = request.args.get('filename')\n os.remove(os.path.join(config.UPLOAD_FOLDER, filename))\n return {'response': 'File deleted successfully'}\n","new_contents":"import os\nfrom werkzeug.utils import secure_filename\nimport config\nfrom flask_restful import Resource\nfrom flask import request, abort\n\n\ndef allowed_file(filename):\n return ('.' in filename and\n filename.rsplit('.', 1)[1].lower() in config.ALLOWED_EXTENSIONS)\n\n\nclass File(Resource):\n def post(self):\n if 'uploaded_data' not in request.files:\n abort(400, 'Uploaded_data is required for the request')\n file = request.files['uploaded_data']\n if file.filename == '':\n abort(400, 'Filename cannot be empty')\n if allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(config.UPLOAD_FOLDER, filename))\n return {'response': 'File uploaded successfully'}\n else:\n abort(415, 'File type is not supported')\n\n def delete(self):\n filename = secure_filename(request.args.get('filename'))\n os.remove(os.path.join(config.UPLOAD_FOLDER, filename))\n return {'response': 'File deleted successfully'}\n","subject":"Change status codes and messages","message":"Change status codes and messages\n","lang":"Python","license":"apache-2.0","repos":"googleinterns\/inventory-visualizer,googleinterns\/inventory-visualizer,googleinterns\/inventory-visualizer,googleinterns\/inventory-visualizer,googleinterns\/inventory-visualizer"} {"commit":"123875153e81253a44d0e8b2d8de5abee195362a","old_file":"backend\/shmitter\/tweets\/serializers.py","new_file":"backend\/shmitter\/tweets\/serializers.py","old_contents":"from rest_framework import serializers\n\nfrom shmitter.likes import services as likes_services\nfrom .models import Tweet\nfrom . import services as tweets_services\n\n\nclass TweetSerializer(serializers.ModelSerializer):\n owner = serializers.ReadOnlyField(source='owner.username')\n\n is_fan = serializers.SerializerMethodField()\n is_retweeted = serializers.SerializerMethodField()\n\n class Meta:\n model = Tweet\n fields = (\n 'id',\n 'owner',\n 'body',\n 'is_fan',\n 'is_retweeted',\n 'total_likes',\n 'created',\n )\n\n def get_is_fan(self, obj) -> bool:\n \"\"\"\n Check if a `request.user` has liked this tweet (`obj`).\n \"\"\"\n user = self.context.get('request').user\n return likes_services.is_fan(obj, user)\n\n def get_is_retweeted(self, obj) -> bool:\n \"\"\"\n Check if a `request.user` has retweeted this tweet (`obj`).\n \"\"\"\n user = self.context.get('request').user\n return tweets_services.is_retweeted(obj, user)\n","new_contents":"from rest_framework import serializers\n\nfrom shmitter.likes import services as likes_services\nfrom .models import Tweet\nfrom . import services as tweets_services\n\n\nclass TweetSerializer(serializers.ModelSerializer):\n owner = serializers.ReadOnlyField(source='owner.username')\n\n is_fan = serializers.SerializerMethodField()\n is_retweeted = serializers.SerializerMethodField()\n\n class Meta:\n model = Tweet\n fields = (\n 'id',\n 'owner',\n 'body',\n 'is_fan',\n 'is_retweeted',\n 'total_likes',\n 'total_retweets',\n 'created',\n )\n\n def get_is_fan(self, obj) -> bool:\n \"\"\"\n Check if a `request.user` has liked this tweet (`obj`).\n \"\"\"\n user = self.context.get('request').user\n return likes_services.is_fan(obj, user)\n\n def get_is_retweeted(self, obj) -> bool:\n \"\"\"\n Check if a `request.user` has retweeted this tweet (`obj`).\n \"\"\"\n user = self.context.get('request').user\n return tweets_services.is_retweeted(obj, user)\n","subject":"Add total retweets to the serializer","message":"Add total retweets to the serializer\n","lang":"Python","license":"mit","repos":"apirobot\/shmitter,apirobot\/shmitter,apirobot\/shmitter"} {"commit":"28a4f4ab9d6b7c3ea14d48c002273acfe05d7246","old_file":"bumblebee\/util.py","new_file":"bumblebee\/util.py","old_contents":"import shlex\nimport exceptions\nimport subprocess\n\ndef bytefmt(num):\n for unit in [ \"\", \"Ki\", \"Mi\", \"Gi\" ]:\n if num < 1024.0:\n return \"{:.2f}{}B\".format(num, unit)\n num \/= 1024.0\n return \"{:05.2f%}{}GiB\".format(num)\n\ndef durationfmt(duration):\n minutes, seconds = divmod(duration, 60)\n hours, minutes = divmod(minutes, 60)\n res = \"{:02d}:{:02d}\".format(minutes, seconds)\n if hours > 0: res = \"{:02d}:{}\".format(hours, res)\n\n return res\n\ndef execute(cmd):\n args = shlex.split(cmd)\n p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n out = p.communicate()\n\n if p.returncode != 0:\n raise exceptions.RuntimeError(\"{} exited with {}\".format(cmd, p.returncode))\n","new_contents":"import shlex\nimport subprocess\ntry:\n from exceptions import RuntimeError\nexcept ImportError:\n # Python3 doesn't require this anymore\n pass\n\ndef bytefmt(num):\n for unit in [ \"\", \"Ki\", \"Mi\", \"Gi\" ]:\n if num < 1024.0:\n return \"{:.2f}{}B\".format(num, unit)\n num \/= 1024.0\n return \"{:05.2f%}{}GiB\".format(num)\n\ndef durationfmt(duration):\n minutes, seconds = divmod(duration, 60)\n hours, minutes = divmod(minutes, 60)\n res = \"{:02d}:{:02d}\".format(minutes, seconds)\n if hours > 0: res = \"{:02d}:{}\".format(hours, res)\n\n return res\n\ndef execute(cmd):\n args = shlex.split(cmd)\n p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n out = p.communicate()\n\n if p.returncode != 0:\n raise RuntimeError(\"{} exited with {}\".format(cmd, p.returncode))\n","subject":"Fix import error for Python3","message":"[core] Fix import error for Python3\n\nImport exceptions module only for Python2.\n\nfixes #22\n","lang":"Python","license":"mit","repos":"tobi-wan-kenobi\/bumblebee-status,tobi-wan-kenobi\/bumblebee-status"} {"commit":"81b7089633b9d43b05566a1e23f93fb59678fe1e","old_file":"plugins\/unicode_plugin.py","new_file":"plugins\/unicode_plugin.py","old_contents":"import string\nimport textwrap\nimport binascii\nfrom veryprettytable import VeryPrettyTable\nfrom plugins import BasePlugin\n\n__author__ = 'peter'\n\n\nclass DecodeHexPlugin(BasePlugin):\n short_description = 'Decode hex string to encodings:'\n default = True\n description = textwrap.dedent('''\n This plugin tries to decode the given hexstring with some common encodings, then print it\n '''.strip())\n\n def sentinel(self):\n return all(not len(x) % 2 for x in self.args['STRING'])\n\n def handle(self):\n result = ''\n for s in self.args['STRING']:\n if len(self.args['STRING']) > 1:\n result += '{0}:\\n'.format(s)\n binary = binascii.unhexlify(s)\n\n result += self._decode('UTF8', 'utf8', binary)\n result += self._decode('iso-8859-1 (Cyrillic)', 'iso-8859-1', binary)\n\n return result\n\n @staticmethod\n def _decode(name, encoding, binary):\n try:\n s = binary.decode(encoding)\n except UnicodeDecodeError:\n s = ''\n return '{0}: \"{1}\"\\n'.format(name, s)","new_contents":"import string\nimport textwrap\nimport binascii\nimport unicodedata\nfrom veryprettytable import VeryPrettyTable\nfrom plugins import BasePlugin\n\n__author__ = 'peter'\n\n\nclass DecodeHexPlugin(BasePlugin):\n short_description = 'Decode hex string to encodings:'\n default = True\n description = textwrap.dedent('''\n This plugin tries to decode the given hexstring with some common encodings, then print it.\n It tries to remove control characters from the string after decoding to prevent terminal breakage.\n '''.strip())\n\n def sentinel(self):\n return all(not len(x) % 2 for x in self.args['STRING'])\n\n def handle(self):\n result = ''\n for s in self.args['STRING']:\n if len(self.args['STRING']) > 1:\n result += '{0}:\\n'.format(s)\n binary = binascii.unhexlify(s)\n\n result += self._decode('UTF8', 'utf8', binary)\n result += self._decode('iso-8859-1 (Cyrillic)', 'iso-8859-1', binary)\n\n return result\n\n def _decode(self, name, encoding, binary):\n try:\n s = self._clean(binary.decode(encoding))\n except UnicodeDecodeError:\n s = ''\n return '{0}: \"{1}\"\\n'.format(name, s)\n\n @staticmethod\n def _clean(s):\n return \"\".join(ch for ch in s if unicodedata.category(ch)[0] != \"C\")\n","subject":"Remove control characters from printed string to prevent terminal breakage","message":"Remove control characters from printed string to prevent terminal breakage\n","lang":"Python","license":"mit","repos":"Sakartu\/stringinfo"} {"commit":"e999e9b9480d31c45bf13882081e36bd7e2c4c63","old_file":"download.py","new_file":"download.py","old_contents":"#!\/usr\/bin\/env python\n\nimport data\n\n\ns = data.Session()\nfor video in s.query(data.Video):\n print u'+++ Downloading {} +++'.format(video.title)\n video.download()\ndel s\n","new_contents":"#!\/usr\/bin\/env python\n\nimport data\n\n\ns = data.Session()\nfor video in s.query(data.Video):\n print u'+++ Downloading \"{}\" +++'.format(video.title)\n video.download()\ndel s\n","subject":"Print video title in quotes","message":"Print video title in quotes\n","lang":"Python","license":"mit","repos":"drkitty\/metatube,drkitty\/metatube"} {"commit":"c0596310d9281fc07d4db6e6fd2ed8433335edb9","old_file":"examples\/build_examples.py","new_file":"examples\/build_examples.py","old_contents":"#!\/usr\/bin\/env python\n\nimport glob\nimport os\nimport platform\nimport subprocess\nimport sys\n\ncx_path = sys.argv[1] if len(sys.argv) > 1 else \"cx\"\n\nos.chdir(os.path.dirname(__file__))\n\nfor file in glob.glob(\"*.cx\"):\n if platform.system() == \"Windows\" and file == \"tree.cx\":\n continue\n\n extension = \".out\" if platform.system() != \"Windows\" else \".exe\"\n output = os.path.splitext(file)[0] + extension\n exit_status = subprocess.call([cx_path, file, \"-o\", output])\n if exit_status != 0:\n sys.exit(1)\n\nprint(\"All examples built successfully.\")\n","new_contents":"#!\/usr\/bin\/env python\n\nimport glob\nimport os\nimport platform\nimport subprocess\nimport sys\n\ncx_path = sys.argv[1] if len(sys.argv) > 1 else \"cx\"\n\nos.chdir(os.path.dirname(__file__))\n\nfor file in glob.glob(\"*.cx\"):\n if platform.system() == \"Windows\" and file == \"tree.cx\":\n continue\n\n extension = \".out\" if platform.system() != \"Windows\" else \".exe\"\n output = os.path.splitext(file)[0] + extension\n exit_status = subprocess.call([cx_path, file, \"-o\", output, \"-Werror\"])\n if exit_status != 0:\n sys.exit(1)\n\nprint(\"All examples built successfully.\")\n","subject":"Use -Werror for code examples","message":"Use -Werror for code examples\n","lang":"Python","license":"mit","repos":"delta-lang\/delta,delta-lang\/delta,delta-lang\/delta,delta-lang\/delta"} {"commit":"19326b0b96e053c4b4fab402a379a03c39fbe46d","old_file":"apps\/homepage\/templatetags\/homepage_tags.py","new_file":"apps\/homepage\/templatetags\/homepage_tags.py","old_contents":"from django import template\n\nfrom homepage.models import Tab\n\nregister = template.Library()\n\n@register.tag(name=\"get_tabs\")\ndef get_tabs(parser, token):\n \n return GetElementNode()\n \nclass GetElementNode(template.Node):\n \n def __init__(self):\n pass\n \n def render(self, context):\n context['tabs'] = Tab.objects.all()\n return ''","new_contents":"from django import template\n\nfrom homepage.models import Tab\n\nregister = template.Library()\n\n@register.tag(name=\"get_tabs\")\ndef get_tabs(parser, token):\n \n return GetElementNode()\n \nclass GetElementNode(template.Node):\n \n def __init__(self):\n pass\n \n def render(self, context):\n context['tabs'] = Tab.objects.all().select_related('grid')\n return ''","subject":"Reduce queries on all pages by using select_related in the get_tabs template tag.","message":"Reduce queries on all pages by using select_related in the get_tabs template tag.\n","lang":"Python","license":"mit","repos":"cartwheelweb\/packaginator,nanuxbe\/djangopackages,miketheman\/opencomparison,audreyr\/opencomparison,audreyr\/opencomparison,cartwheelweb\/packaginator,QLGu\/djangopackages,pydanny\/djangopackages,cartwheelweb\/packaginator,benracine\/opencomparison,nanuxbe\/djangopackages,pydanny\/djangopackages,pydanny\/djangopackages,QLGu\/djangopackages,nanuxbe\/djangopackages,miketheman\/opencomparison,benracine\/opencomparison,QLGu\/djangopackages"} {"commit":"6b0049978f2a7e59146abbc9b6a265061bbe00c4","old_file":"conda_verify\/errors.py","new_file":"conda_verify\/errors.py","old_contents":"","new_contents":"from collections import namedtuple\n\n\nclass Error(namedtuple('Error', ['file', 'line_number', 'code', 'message'])):\n \"\"\"Error class creates error codes to be shown to the user.\"\"\"\n\n def __repr__(self):\n \"\"\"Override namedtuple's __repr__ so that error codes are readable.\"\"\"\n return '{}:{}: {} {}' .format(self.file, self.line_number, self.code, self.message)\n","subject":"Add Error class as base for error codes","message":"Add Error class as base for error codes\n\nAdd docstrings to error class\n","lang":"Python","license":"bsd-3-clause","repos":"mandeep\/conda-verify"} {"commit":"5aff8defb8baf83176ea861b03de04a9d6ac8a31","old_file":"bundles\/views.py","new_file":"bundles\/views.py","old_contents":"from django.views.generic import DetailView, ListView\n\nfrom rest_framework import filters, generics, permissions\nfrom rest_framework.response import Response\n\nfrom . import models, serializers\n\n\nclass BundleList(ListView):\n model = models.Bundle\n context_object_name = 'bundles'\n paginate_by = 25\n\n\nclass BundleDetail(DetailView):\n model = models.Bundle\n context_object_name = 'bundle'\n\n\nclass BundleView(generics.RetrieveAPIView):\n serializer_class = serializers.BundleSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n def get(self, request, slug):\n try:\n bundle = models.Bundle.objects.get(slug=slug)\n except models.Bundle.DoesNotExist:\n return Response(status=404)\n serializer = serializers.BundleSerializer(bundle)\n return Response(serializer.data)\n","new_contents":"from django.views.generic import DetailView, ListView\n\nfrom rest_framework import filters, generics, permissions\nfrom rest_framework.response import Response\n\nfrom . import models, serializers\n\n\nclass BundleList(ListView):\n model = models.Bundle\n context_object_name = 'bundles'\n paginate_by = 25\n\n\nclass BundleDetail(DetailView):\n model = models.Bundle\n context_object_name = 'bundle'\n\n\nclass BundleView(generics.RetrieveAPIView):\n serializer_class = serializers.BundleSerializer\n\n def get(self, request, slug):\n try:\n bundle = models.Bundle.objects.get(slug=slug)\n except models.Bundle.DoesNotExist:\n return Response(status=404)\n serializer = serializers.BundleSerializer(bundle)\n return Response(serializer.data)\n","subject":"Make bundle view accessible to anyone","message":"Make bundle view accessible to anyone\n","lang":"Python","license":"agpl-3.0","repos":"lutris\/website,lutris\/website,lutris\/website,lutris\/website"} {"commit":"b3391187cb87ae33d4b8dd6e55f5edfdb695ea53","old_file":"mapbox_vector_tile\/__init__.py","new_file":"mapbox_vector_tile\/__init__.py","old_contents":"from . import encoder\nfrom . import decoder\n\n\ndef decode(tile, y_coord_down=False):\n vector_tile = decoder.TileData()\n message = vector_tile.getMessage(tile, y_coord_down)\n return message\n\n\ndef encode(layers, quantize_bounds=None, y_coord_down=False, extents=4096,\n on_invalid_geometry=None, round_fn=None, check_winding_order=True):\n vector_tile = encoder.VectorTile(extents, on_invalid_geometry,\n round_fn=round_fn,\n check_winding_order=check_winding_order)\n if (isinstance(layers, list)):\n for layer in layers:\n vector_tile.addFeatures(layer['features'], layer['name'],\n quantize_bounds, y_coord_down)\n else:\n vector_tile.addFeatures(layers['features'], layers['name'],\n quantize_bounds, y_coord_down)\n\n return vector_tile.tile.SerializeToString()\n","new_contents":"from . import encoder\nfrom . import decoder\n\n\n# Enable Shapely \"speedups\" if available\n# http:\/\/toblerity.org\/shapely\/manual.html#performance\nfrom shapely import speedups\nif speedups.available:\n speedups.enable()\n\n\ndef decode(tile, y_coord_down=False):\n vector_tile = decoder.TileData()\n message = vector_tile.getMessage(tile, y_coord_down)\n return message\n\n\ndef encode(layers, quantize_bounds=None, y_coord_down=False, extents=4096,\n on_invalid_geometry=None, round_fn=None, check_winding_order=True):\n vector_tile = encoder.VectorTile(extents, on_invalid_geometry,\n round_fn=round_fn,\n check_winding_order=check_winding_order)\n if (isinstance(layers, list)):\n for layer in layers:\n vector_tile.addFeatures(layer['features'], layer['name'],\n quantize_bounds, y_coord_down)\n else:\n vector_tile.addFeatures(layers['features'], layers['name'],\n quantize_bounds, y_coord_down)\n\n return vector_tile.tile.SerializeToString()\n","subject":"Enable Shapely speedups when available.","message":"Enable Shapely speedups when available.\n\nhttp:\/\/toblerity.org\/shapely\/manual.html#performance\n","lang":"Python","license":"mit","repos":"mapzen\/mapbox-vector-tile"} {"commit":"3db77e04ec3ed0250c96b7f40d19ae459329d217","old_file":"configs\/merge_day\/b2g_tag.py","new_file":"configs\/merge_day\/b2g_tag.py","old_contents":"LIVE_B2G_BRANCHES = {\n \"mozilla-b2g37_v2_2\": {\n \"gaia_branch\": \"v2.2\",\n \"tag_name\": \"B2G_2_2_%(DATE)s_MERGEDAY\",\n },\n}\n\nconfig = {\n \"log_name\": \"b2g_tag\",\n\n \"gaia_mapper_base_url\": \"http:\/\/cruncher\/mapper\/gaia\/git\",\n \"gaia_url\": \"git@github.com:mozilla-b2g\/gaia.git\",\n \"hg_base_pull_url\": \"https:\/\/hg.mozilla.org\/releases\",\n \"hg_base_push_url\": \"ssh:\/\/hg.mozilla.org\/releases\",\n \"b2g_branches\": LIVE_B2G_BRANCHES,\n\n # Disallow sharing, since we want pristine .hg directories.\n \"vcs_share_base\": None,\n \"hg_share_base\": None,\n\n # any hg command line options\n \"exes\": {\n \"hg\": [\n \"hg\", \"--config\",\n \"hostfingerprints.hg.mozilla.org=af:27:b9:34:47:4e:e5:98:01:f6:83:2b:51:c9:aa:d8:df:fb:1a:27\",\n ],\n }\n}\n","new_contents":"LIVE_B2G_BRANCHES = {\n \"mozilla-b2g37_v2_2\": {\n \"gaia_branch\": \"v2.2\",\n \"tag_name\": \"B2G_2_2_%(DATE)s_MERGEDAY\",\n },\n \"mozilla-b2g37_v2_2r\": {\n \"gaia_branch\": \"v2.2r\",\n \"tag_name\": \"B2G_2_2r_%(DATE)s_MERGEDAY\",\n },\n}\n\nconfig = {\n \"log_name\": \"b2g_tag\",\n\n \"gaia_mapper_base_url\": \"http:\/\/cruncher\/mapper\/gaia\/git\",\n \"gaia_url\": \"git@github.com:mozilla-b2g\/gaia.git\",\n \"hg_base_pull_url\": \"https:\/\/hg.mozilla.org\/releases\",\n \"hg_base_push_url\": \"ssh:\/\/hg.mozilla.org\/releases\",\n \"b2g_branches\": LIVE_B2G_BRANCHES,\n\n # Disallow sharing, since we want pristine .hg directories.\n \"vcs_share_base\": None,\n \"hg_share_base\": None,\n\n # any hg command line options\n \"exes\": {\n \"hg\": [\n \"hg\", \"--config\",\n \"hostfingerprints.hg.mozilla.org=af:27:b9:34:47:4e:e5:98:01:f6:83:2b:51:c9:aa:d8:df:fb:1a:27\",\n ],\n }\n}\n","subject":"Revert Bug 1237985 - Disable b2g37_v2.2R automation, r=rail","message":"Revert Bug 1237985 - Disable b2g37_v2.2R automation, r=rail\n","lang":"Python","license":"mpl-2.0","repos":"mozilla\/build-mozharness,mozilla\/build-mozharness"} {"commit":"e53e214b97a9a4c7ad2dbca88b01798dcc614b6a","old_file":"auth0\/v2\/authentication\/social.py","new_file":"auth0\/v2\/authentication\/social.py","old_contents":"from .base import AuthenticationBase\n\n\nclass Social(AuthenticationBase):\n\n def __init__(self, domain):\n self.domain = domain\n\n def login(self, client_id, access_token, connection):\n \"\"\"Login using a social provider's access token\n\n Given the social provider's access_token and the connection specified,\n it will do the authentication on the provider and return a dict with\n the access_token and id_token. Currently, this endpoint only works for\n Facebook, Google, Twitter and Weibo.\n\n Args:\n client_id (str): client name.\n\n access_token (str): social provider's access_token.\n\n connection (str): connection type (e.g: 'facebook')\n\n Returns:\n A dict with 'access_token' and 'id_token' keys.\n \"\"\"\n\n return self.post(\n 'https:\/\/%s\/oauth\/access_token' % self.domain,\n data={\n 'client_id': client_id,\n 'access_token': access_token,\n 'connection': connection,\n 'scope': 'openid',\n },\n headers={'Content-Type': 'application\/json'}\n )\n","new_contents":"from .base import AuthenticationBase\n\n\nclass Social(AuthenticationBase):\n\n \"\"\"Social provider's endpoints.\n\n Args:\n domain (str): Your auth0 domain (e.g: username.auth0.com)\n \"\"\"\n\n def __init__(self, domain):\n self.domain = domain\n\n def login(self, client_id, access_token, connection):\n \"\"\"Login using a social provider's access token\n\n Given the social provider's access_token and the connection specified,\n it will do the authentication on the provider and return a dict with\n the access_token and id_token. Currently, this endpoint only works for\n Facebook, Google, Twitter and Weibo.\n\n Args:\n client_id (str): client name.\n\n access_token (str): social provider's access_token.\n\n connection (str): connection type (e.g: 'facebook')\n\n Returns:\n A dict with 'access_token' and 'id_token' keys.\n \"\"\"\n\n return self.post(\n 'https:\/\/%s\/oauth\/access_token' % self.domain,\n data={\n 'client_id': client_id,\n 'access_token': access_token,\n 'connection': connection,\n 'scope': 'openid',\n },\n headers={'Content-Type': 'application\/json'}\n )\n","subject":"Add class docstring to Social","message":"Add class docstring to Social\n","lang":"Python","license":"mit","repos":"auth0\/auth0-python,auth0\/auth0-python"} {"commit":"1608134ea633c0fe8cd4636b11dc5a931d02e024","old_file":"intercom.py","new_file":"intercom.py","old_contents":"import configparser\nimport time\nimport RPIO as GPIO\n\nfrom client import MumbleClient\n\nclass InterCom:\n\n def __init__(self):\n config = configparser.ConfigParser()\n config.read('intercom.ini')\n self.mumble_client = MumbleClient(config['mumbleclient'])\n self.exit = False\n self.send_input = False\n\n if config['general']['gpiotype'] == 'BCM':\n GPIO.setmode(GPIO.BCM)\n\n self.button = int(config['general']['button'])\n GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\n def run(self):\n while not self.exit:\n if GPIO.input(self.button):\n self.mumble_client.send_input_audio()\n\nif __name__ == '__main__':\n InterCom().run()\n","new_contents":"import configparser\nimport time\nimport RPi.GPIO as GPIO\n\nfrom client import MumbleClient\n\nclass InterCom:\n\n def __init__(self):\n config = configparser.ConfigParser()\n config.read('intercom.ini')\n self.mumble_client = MumbleClient(config['mumbleclient'])\n self.exit = False\n self.send_input = False\n\n\n if config['general']['gpiotype'] == 'BCM':\n GPIO.setmode(GPIO.BCM)\n\n self.button = int(config['general']['button'])\n GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\n def run(self):\n while not self.exit:\n if GPIO.input(self.button):\n self.mumble_client.send_input_audio()\n\nif __name__ == '__main__':\n try:\n InterCom().run()\n except Exception as e:\n raise e\n finally:\n GPIO.cleanup()\n","subject":"Change to rpio and add clean","message":"Change to rpio and add clean\n","lang":"Python","license":"mit","repos":"pkronstrom\/intercom"} {"commit":"05e568571c2f6891ed7be6198b8cf5e4e540d674","old_file":"dev_tools\/run_tests.py","new_file":"dev_tools\/run_tests.py","old_contents":"#!\/usr\/bin\/env python3\n\"\"\"Run tests under a consistent environment...\n\nWhether run from the terminal, in CI or from the editor this file makes sure\nthe tests are run in a consistent environment.\n\"\"\"\n\n#------------------------------------------------------------------------------\n# Py2C - A Python to C++ compiler\n# Copyright (C) 2014 Pradyun S. Gedam\n#------------------------------------------------------------------------------\n\nimport sys\nfrom os.path import join, realpath, dirname\n\n# Local modules\nimport cleanup\ncleanup.REMOVE_GENERATED_AST = False\ncleanup.PRINT_OUTPUT = False\ncleanup.main()\n\n# Third Party modules\nimport nose\nimport coverage\n\nbase_dir = realpath(dirname(__file__))\nroot_dir = join(dirname(base_dir), \"py2c\")\n\nREPORT = True\nif \"--dont-report\" in sys.argv:\n sys.argv.remove(\"--dont-report\")\n REPORT = False\n\ncov = coverage.coverage(config_file=join(base_dir, \".coveragerc\"))\ncov.start()\nsuccess = nose.run(\n env={\n \"NOSE_INCLUDE_EXE\": \"True\",\n \"NOSE_WITH_HTML_REPORT\": \"True\",\n \"NOSE_WITH_SPECPLUGIN\": \"True\"\n },\n defaultTest=root_dir,\n)\ncov.stop()\ncov.save()\n\nif success and REPORT:\n cov.html_report()\n cov.report()\n\nsys.exit(0 if success else 1)\n","new_contents":"#!\/usr\/bin\/env python3\n\"\"\"Run tests under a consistent environment...\n\nWhether run from the terminal, in CI or from the editor this file makes sure\nthe tests are run in a consistent environment.\n\"\"\"\n\n#------------------------------------------------------------------------------\n# Py2C - A Python to C++ compiler\n# Copyright (C) 2014 Pradyun S. Gedam\n#------------------------------------------------------------------------------\n\n# Local modules\nimport cleanup\n\n# Standard library\nimport sys\nfrom os.path import join, realpath, dirname\n\n# Third Party modules\nimport nose\nimport coverage\n\ncleanup.REMOVE_GENERATED_AST = False\ncleanup.main()\n\nbase_dir = realpath(dirname(__file__))\nroot_dir = join(dirname(base_dir), \"py2c\")\n\nREPORT = True\nif \"--dont-report\" in sys.argv:\n sys.argv.remove(\"--dont-report\")\n REPORT = False\n\ncov = coverage.coverage(config_file=join(base_dir, \".coveragerc\"))\ncov.start()\nsuccess = nose.run(\n env={\n \"NOSE_INCLUDE_EXE\": \"True\",\n \"NOSE_WITH_HTML_REPORT\": \"True\",\n \"NOSE_WITH_SPECPLUGIN\": \"True\"\n },\n defaultTest=root_dir,\n)\ncov.stop()\ncov.save()\n\nif success and REPORT:\n cov.html_report()\n cov.report()\n\nsys.exit(0 if success else 1)\n","subject":"Move all imports to top-of-module, don't hide cleanup output.","message":"[RUN_TESTS] Move all imports to top-of-module, don't hide cleanup output.\n","lang":"Python","license":"bsd-3-clause","repos":"pradyunsg\/Py2C,pradyunsg\/Py2C"} {"commit":"0fe30bb04e9b3d981cd1f6264485d98ca56a2fb8","old_file":"events\/migrations\/0035_add_n_events_to_keyword.py","new_file":"events\/migrations\/0035_add_n_events_to_keyword.py","old_contents":"# -*- coding: utf-8 -*-\n# Generated by Django 1.9.11 on 2016-12-02 15:46\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\ndef forward(apps, schema_editor):\n Keyword = apps.get_model('events', 'Keyword')\n for keyword in Keyword.objects.exclude(events=None) | Keyword.objects.exclude(audience_events=None):\n n_events = (keyword.events.all() | keyword.audience_events.all()).distinct().count()\n if n_events != keyword.n_events:\n keyword.n_events = n_events\n keyword.save(update_fields=(\"n_events\",))\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('events', '0034_add_keyword_deprecated'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='keyword',\n name='n_events',\n field=models.IntegerField(db_index=True, default=0, editable=False, help_text='number of events with this keyword', verbose_name='event count'),\n ),\n migrations.AlterField(\n model_name='event',\n name='audience',\n field=models.ManyToManyField(blank=True, related_name='audience_events', to='events.Keyword'),\n ),\n migrations.AlterField(\n model_name='event',\n name='keywords',\n field=models.ManyToManyField(related_name='events', to='events.Keyword'),\n ),\n migrations.RunPython(forward, migrations.RunPython.noop)\n ]\n","new_contents":"# -*- coding: utf-8 -*-\n# Generated by Django 1.9.11 on 2016-12-02 15:46\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\ndef forward(apps, schema_editor):\n Keyword = apps.get_model('events', 'Keyword')\n for keyword in Keyword.objects.exclude(events=None) | Keyword.objects.exclude(audience_events=None):\n n_events = (keyword.events.all() | keyword.audience_events.all()).distinct().count()\n if n_events != keyword.n_events:\n print(\"Updating event number for \" + str(keyword.name))\n keyword.n_events = n_events\n keyword.save(update_fields=(\"n_events\",))\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('events', '0034_add_keyword_deprecated'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='keyword',\n name='n_events',\n field=models.IntegerField(db_index=True, default=0, editable=False, help_text='number of events with this keyword', verbose_name='event count'),\n ),\n migrations.AlterField(\n model_name='event',\n name='audience',\n field=models.ManyToManyField(blank=True, related_name='audience_events', to='events.Keyword'),\n ),\n migrations.AlterField(\n model_name='event',\n name='keywords',\n field=models.ManyToManyField(related_name='events', to='events.Keyword'),\n ),\n migrations.RunPython(forward, migrations.RunPython.noop)\n ]\n","subject":"Add logging to keyword data migration","message":"Add logging to keyword data migration\n","lang":"Python","license":"mit","repos":"City-of-Helsinki\/linkedevents,City-of-Helsinki\/linkedevents,City-of-Helsinki\/linkedevents"} {"commit":"887597d31dec7fe1f49402e44691c1e745d22968","old_file":"cellcounter\/wsgi.py","new_file":"cellcounter\/wsgi.py","old_contents":"\"\"\"\nWSGI config for cellcounter project.\n\nThis module contains the WSGI application used by Django's development server\nand any production WSGI deployments. It should expose a module-level variable\nnamed ``application``. Django's ``runserver`` and ``runfcgi`` commands discover\nthis application via the ``WSGI_APPLICATION`` setting.\n\nUsually you will have the standard Django WSGI application here, but it also\nmight make sense to replace the whole Django WSGI application with a custom one\nthat later delegates to the Django one. For example, you could introduce WSGI\nmiddleware here, or combine a Django application with an application of another\nframework.\n\n\"\"\"\nimport os\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"cellcounter.settings\")\n\n# This application object is used by any WSGI server configured to use this\n# file. This includes Django's development server, if the WSGI_APPLICATION\n# setting points here.\nfrom django.core.wsgi import get_wsgi_application\napplication = get_wsgi_application()\n\n# Apply WSGI middleware here.\n# from helloworld.wsgi import HelloWorldApplication\n# application = HelloWorldApplication(application)\n","new_contents":"\"\"\"\nWSGI config for cellcounter project.\n\nThis module contains the WSGI application used by Django's development server\nand any production WSGI deployments. It should expose a module-level variable\nnamed ``application``. Django's ``runserver`` and ``runfcgi`` commands discover\nthis application via the ``WSGI_APPLICATION`` setting.\n\nUsually you will have the standard Django WSGI application here, but it also\nmight make sense to replace the whole Django WSGI application with a custom one\nthat later delegates to the Django one. For example, you could introduce WSGI\nmiddleware here, or combine a Django application with an application of another\nframework.\n\n\"\"\"\nimport os\nimport site\nfrom distutils.sysconfig import get_python_lib\n\n#ensure the venv is being loaded correctly\nsite.addsitedir(get_python_lib())\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"cellcounter.settings\")\n\n#import the DATABASE_URL from an Apache environment variable\n#this allows per-vhost database configuration to be passed in\nimport django.core.handlers.wsgi\n_application = django.core.handlers.wsgi.WSGIHandler()\n\ndef application(environ, start_response):\n os.environ['DATABASE_URL'] = environ['DATABASE_URL']\n return _application(environ, start_response)\n\n# Apply WSGI middleware here.\n# from helloworld.wsgi import HelloWorldApplication\n# application = HelloWorldApplication(application)\n","subject":"Improve WSGI file for apache deployment\/database configuration management","message":"Improve WSGI file for apache deployment\/database configuration management\n","lang":"Python","license":"mit","repos":"cellcounter\/cellcounter,cellcounter\/cellcounter,cellcounter\/cellcounter,oghm2\/hackdayoxford,oghm2\/hackdayoxford,haematologic\/cellcounter,haematologic\/cellcounter,haematologic\/cellcounter,cellcounter\/cellcounter"} {"commit":"25712b9c94062f41c50a8611c5b7069bde7e1c8f","old_file":"ibmcnx\/cnx\/VersionStamp.py","new_file":"ibmcnx\/cnx\/VersionStamp.py","old_contents":"######\n# Set the Version Stamp to actual time and date\n#\n# Author: Christoph Stoettner\n# Mail: christoph.stoettner@stoeps.de\n# Documentation: http:\/\/scripting101.stoeps.de\n#\n# Version: 2.0\n# Date: 2014-06-04\n#\n# License: Apache 2.0\n#\n\nprint \"\\nSet Version Stamp in LotusConnections-config.xml to actual Date and Time\\n\"\n\npath = raw_input( \"Path and Folder where config is temporarily stored: \" )\n\nexecfile(\"connectionsConfig.py\")\nLCConfigService.checkOutConfig(path,AdminControl.getCell())\nLCConfigService.updateConfig(\"versionStamp\",\"\")\nLCConfigService.checkInConfig(path,AdminControl.getCell())\nsynchAllNodes()\n","new_contents":"######\n# Set the Version Stamp to actual time and date\n#\n# Author: Christoph Stoettner\n# Mail: christoph.stoettner@stoeps.de\n# Documentation: http:\/\/scripting101.stoeps.de\n#\n# Version: 2.0\n# Date: 2014-06-04\n#\n# License: Apache 2.0\n#\n\nimport ibmcnx.functions\n\nprint \"\\nSet Version Stamp in LotusConnections-config.xml to actual Date and Time\\n\"\n\n# Check properties if temppath is defined\nif ( ibmcnx.functions.tempPath() == '' ):\n path = raw_input( \"Path and Folder where config is temporarily stored: \" )\nelse:\n path = ibmcnx.functions.tempPath()\n\nexecfile(\"connectionsConfig.py\")\nLCConfigService.checkOutConfig(path,AdminControl.getCell())\nLCConfigService.updateConfig(\"versionStamp\",\"\")\nLCConfigService.checkInConfig(path,AdminControl.getCell())\nsynchAllNodes()\n","subject":"Add option to get temppath from properties file","message":"Add option to get temppath from properties file\n","lang":"Python","license":"apache-2.0","repos":"stoeps13\/ibmcnx2,stoeps13\/ibmcnx2"} {"commit":"e5656674eab83f7005c70d901187fd89027efeba","old_file":"allaccess\/management\/commands\/migrate_social_providers.py","new_file":"allaccess\/management\/commands\/migrate_social_providers.py","old_contents":"from __future__ import unicode_literals\n\nfrom django.core.management.base import NoArgsCommand, CommandError\n\nfrom allaccess.models import Provider \n\n\nclass Command(NoArgsCommand):\n \"Convert existing providers from django-social-auth to django-all-access.\"\n\n def handle_noargs(self, **options):\n verbosity = int(options.get('verbosity'))\n try:\n from social_auth.backends import get_backends, BaseOAuth\n except ImportError: # pragma: no cover\n raise CommandError(\"django-social-auth is not installed.\")\n for name, backend in get_backends(force_load=True).items():\n if issubclass(backend, BaseOAuth) and backend.enabled():\n # Create providers if they don't already exist\n key, secret = backend.get_key_and_secret()\n defaults = {\n 'request_token_url': getattr(backend, 'REQUEST_TOKEN_URL', ''),\n 'authorization_url': getattr(backend, 'AUTHORIZATION_URL', ''),\n 'access_token_url': getattr(backend, 'ACCESS_TOKEN_URL', ''),\n 'profile_url': '',\n 'key': key or None,\n 'secret': secret or None,\n }\n provider, created = Provider.objects.get_or_create(name=name, defaults=defaults)\n if created and verbosity > 0:\n self.stdout.write('New provider created from \"%s\" backend.\\n' % name)\n","new_contents":"from __future__ import unicode_literals\n\nfrom django.core.management.base import NoArgsCommand, CommandError\n\nfrom allaccess.models import Provider \n\n\nclass Command(NoArgsCommand):\n \"Convert existing providers from django-social-auth to django-all-access.\"\n\n def handle_noargs(self, **options):\n verbosity = int(options.get('verbosity'))\n try:\n from social_auth.backends import get_backends, BaseOAuth\n except ImportError: # pragma: no cover\n raise CommandError(\"django-social-auth is not installed.\")\n for name, backend in get_backends().items():\n if issubclass(backend, BaseOAuth) and backend.enabled():\n # Create providers if they don't already exist\n key, secret = backend.get_key_and_secret()\n defaults = {\n 'request_token_url': getattr(backend, 'REQUEST_TOKEN_URL', ''),\n 'authorization_url': getattr(backend, 'AUTHORIZATION_URL', ''),\n 'access_token_url': getattr(backend, 'ACCESS_TOKEN_URL', ''),\n 'profile_url': '',\n 'key': key or None,\n 'secret': secret or None,\n }\n provider, created = Provider.objects.get_or_create(name=name, defaults=defaults)\n if created and verbosity > 0:\n self.stdout.write('New provider created from \"%s\" backend.\\n' % name)\n","subject":"Remove force_load which was added in later versions.","message":"Remove force_load which was added in later versions.\n","lang":"Python","license":"bsd-2-clause","repos":"iXioN\/django-all-access,vyscond\/django-all-access,dpoirier\/django-all-access,dpoirier\/django-all-access,mlavin\/django-all-access,iXioN\/django-all-access,vyscond\/django-all-access,mlavin\/django-all-access"} {"commit":"3faf3a9debc0fad175ca032f3eb0880defbd0cdb","old_file":"akaudit\/clidriver.py","new_file":"akaudit\/clidriver.py","old_contents":"#!\/usr\/bin\/env python\n\nimport sys\nimport argparse\nfrom akaudit.audit import Auditer\n\ndef main(argv = sys.argv, log = sys.stderr):\n\tparser = argparse.ArgumentParser(description='Audit who has access to your homes.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\tparser.add_argument('-l', '--log', default='info', help='Log level')\n\targs = parser.parse_args()\n\tauditer = Auditer()\n\tauditer.run_audit(args)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","new_contents":"#!\/usr\/bin\/env python\n\nimport sys\nimport argparse\nfrom akaudit.audit import Auditer\n\ndef main(argv = sys.argv, log = sys.stderr):\n\tparser = argparse.ArgumentParser(description='Audit who has access to your homes.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\tparser.add_argument('-l', '--log', default='info', help='Log level')\n\tparser.add_argument('-i', '--interactive', help='Interactive mode (prompts asking if to delete each key)', action=\"store_true\")\n\targs = parser.parse_args()\n\n\tauditer = Auditer()\n\tauditer.run_audit(args)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","subject":"Add argument option for --interactive.","message":"Add argument option for --interactive.\n","lang":"Python","license":"apache-2.0","repos":"flaccid\/akaudit"} {"commit":"766a2fa8a1256946af9bc3b20b98a9a6ac7e1080","old_file":"amaranth\/__init__.py","new_file":"amaranth\/__init__.py","old_contents":"\"\"\"This is the top-level amaranth module init file.\n\nThe only current use of this class is to define common constants.\n\"\"\"\n\nLOW_CALORIE_THRESHOLD = 100\nHIGH_CALORIE_THRESHOLD = 500\n","new_contents":"\"\"\"This is the top-level amaranth module init file.\n\nThe only current use of this class is to define common constants.\n\"\"\"\n\nLOW_CALORIE_THRESHOLD = 100\nHIGH_CALORIE_THRESHOLD = 300\n","subject":"Change high calorie threshold to 300","message":"Change high calorie threshold to 300\n","lang":"Python","license":"apache-2.0","repos":"googleinterns\/amaranth,googleinterns\/amaranth"} {"commit":"572a84ae4fe7ce464fe66b6462a80b09b20f8f1c","old_file":"fireplace\/cards\/gvg\/neutral_epic.py","new_file":"fireplace\/cards\/gvg\/neutral_epic.py","old_contents":"from ..utils import *\n\n\n##\n# Minions\n\n# Hobgoblin\nclass GVG_104:\n\tdef OWN_CARD_PLAYED(self, card):\n\t\tif card.type == CardType.MINION and card.atk == 1:\n\t\t\treturn [Buff(card, \"GVG_104a\")]\n","new_contents":"from ..utils import *\n\n\n##\n# Minions\n\n# Hobgoblin\nclass GVG_104:\n\tdef OWN_CARD_PLAYED(self, card):\n\t\tif card.type == CardType.MINION and card.atk == 1:\n\t\t\treturn [Buff(card, \"GVG_104a\")]\n\n\n# Piloted Sky Golem\nclass GVG_105:\n\tdef deathrattle(self):\n\t\treturn [Summon(CONTROLLER, randomCollectible(type=CardType.MINION, cost=4))]\n\n\n# Junkbot\nclass GVG_106:\n\tdef OWN_MINION_DESTROY(self, minion):\n\t\tif minion.race == Race.MECHANICAL:\n\t\t\treturn [Buff(SELF, \"GVG_106e\")]\n\n\n# Enhance-o Mechano\nclass GVG_107:\n\tdef action(self):\n\t\tfor target in self.controller.field:\n\t\t\ttag = random.choice((GameTag.WINDFURY, GameTag.TAUNT, GameTag.DIVINE_SHIELD))\n\t\t\tyield SetTag(target, {tag: True})\n","subject":"Implement Piloted Sky Golem, Junkbot and Enhance-o Mechano","message":"Implement Piloted Sky Golem, Junkbot and Enhance-o Mechano\n","lang":"Python","license":"agpl-3.0","repos":"NightKev\/fireplace,Ragowit\/fireplace,liujimj\/fireplace,Meerkov\/fireplace,smallnamespace\/fireplace,amw2104\/fireplace,oftc-ftw\/fireplace,beheh\/fireplace,smallnamespace\/fireplace,oftc-ftw\/fireplace,butozerca\/fireplace,Meerkov\/fireplace,jleclanche\/fireplace,amw2104\/fireplace,butozerca\/fireplace,Ragowit\/fireplace,liujimj\/fireplace"} {"commit":"1d6984d31aaa87b5ed781e188b8b42221602cd3f","old_file":"tests\/conftest.py","new_file":"tests\/conftest.py","old_contents":"# -*- coding: utf-8 -*-\npytest_plugins = 'pytester'\n","new_contents":"# -*- coding: utf-8 -*-\nimport os\nimport warnings\n\nimport pytest\n\npytest_plugins = 'pytester'\n\n\n@pytest.fixture(scope='session', autouse=True)\ndef verify_target_path():\n import pytest_testdox\n\n current_path_root = os.path.dirname(\n os.path.dirname(os.path.realpath(__file__))\n )\n if current_path_root not in pytest_testdox.__file__:\n warnings.warn(\n 'pytest-testdox was not imported from your repository. '\n 'You might be testing the wrong code '\n '-- More: https:\/\/github.com\/renanivo\/pytest-testdox\/issues\/13',\n UserWarning\n )\n","subject":"Add warning on running repository's tests with pytest-testdox installed","message":"Add warning on running repository's tests with pytest-testdox installed\n\nFix #13\n","lang":"Python","license":"mit","repos":"renanivo\/pytest-testdox"} {"commit":"dc1cedc1720886dcc3c3bd3da02c7aff58e5eb90","old_file":"tests\/runTests.py","new_file":"tests\/runTests.py","old_contents":"import os\nimport os.path\nimport configparser\nimport shutil\nimport subprocess\n\n# Setup\nprint(\"Setting up...\")\nif os.path.isfile(\"..\/halite.ini\"):\n shutil.copyfile(\"..\/halite.ini\", \"temp.ini\")\n\nshutil.copyfile(\"tests.ini\", \"..\/halite.ini\")\nparser = configparser.ConfigParser()\nparser.read(\"..\/halite.ini\")\n\n# Website tests\nprint(\"Beginning website backend tests\")\nos.system(\"mysql -u \"+parser[\"database\"][\"username\"]+\" -p\"+parser[\"database\"][\"password\"]+\" < ..\/website\/sql\/Database.sql\")\nsubprocess.call([\"phpunit\", \"--stderr\", \"website\/\"])\n\n# Environment tests.\nprint(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))\n\n# Tear down\nprint(\"Almost done...\")\nif os.path.isfile(\"..\/temp.ini\"):\n shutil.copyfile(\"temp.ini\", \"..\/halite.ini\")\n","new_contents":"import os\nimport os.path\nimport configparser\nimport shutil\nimport subprocess\n\n# Setup\nprint(\"Setting up...\")\nif os.path.isfile(\"..\/halite.ini\"):\n shutil.copyfile(\"..\/halite.ini\", \"temp.ini\")\n\nshutil.copyfile(\"tests.ini\", \"..\/halite.ini\")\nparser = configparser.ConfigParser()\nparser.read(\"..\/halite.ini\")\n\n# Website tests\nprint(\"Beginning website backend tests\")\npasswordField = \"\" if parser[\"database\"][\"password\"] == \"\" else \"-p\"+parser[\"database\"][\"password\"]\nos.system(\"mysql -u \"+parser[\"database\"][\"username\"]+\" \"+passwordField+\" < ..\/website\/sql\/Database.sql\")\nsubprocess.call([\"phpunit\", \"--stderr\", \"website\/\"])\n\n# Environment tests.\nprint(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))\n\n# Tear down\nprint(\"Almost done...\")\nif os.path.isfile(\"..\/temp.ini\"):\n shutil.copyfile(\"temp.ini\", \"..\/halite.ini\")\n","subject":"Make test runner work with blank mysql password","message":"Make test runner work with blank mysql password\n","lang":"Python","license":"mit","repos":"HaliteChallenge\/Halite,lanyudhy\/Halite-II,HaliteChallenge\/Halite-II,yangle\/HaliteIO,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite,HaliteChallenge\/Halite,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite,HaliteChallenge\/Halite-II,yangle\/HaliteIO,yangle\/HaliteIO,HaliteChallenge\/Halite,lanyudhy\/Halite-II,lanyudhy\/Halite-II,HaliteChallenge\/Halite-II,yangle\/HaliteIO,HaliteChallenge\/Halite,HaliteChallenge\/Halite-II,lanyudhy\/Halite-II,HaliteChallenge\/Halite,yangle\/HaliteIO,HaliteChallenge\/Halite,HaliteChallenge\/Halite-II,lanyudhy\/Halite-II,lanyudhy\/Halite-II,HaliteChallenge\/Halite,lanyudhy\/Halite-II,lanyudhy\/Halite-II,yangle\/HaliteIO,lanyudhy\/Halite-II,HaliteChallenge\/Halite-II,yangle\/HaliteIO,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite,yangle\/HaliteIO,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite,yangle\/HaliteIO,yangle\/HaliteIO,HaliteChallenge\/Halite-II,yangle\/HaliteIO,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,yangle\/HaliteIO,lanyudhy\/Halite-II,HaliteChallenge\/Halite-II,lanyudhy\/Halite-II,HaliteChallenge\/Halite-II"} {"commit":"a69e8d0d179f12fd42eadd85eca8e0c968d67c91","old_file":"tests\/runTests.py","new_file":"tests\/runTests.py","old_contents":"import os\nimport os.path\nimport configparser\nimport shutil\nimport subprocess\n\n# Setup\nprint(\"Setting up...\")\nif os.path.isfile(\"..\/halite.ini\"):\n shutil.copyfile(\"..\/halite.ini\", \"temp.ini\")\n\nshutil.copyfile(\"tests.ini\", \"..\/halite.ini\")\nparser = configparser.ConfigParser()\nparser.read(\"..\/halite.ini\")\n\n# Website tests\nprint(\"Beginning website backend tests\")\nos.system(\"mysql -u \"+parser[\"database\"][\"username\"]+\" -p\"+parser[\"database\"][\"password\"]+\" < ..\/website\/sql\/Database.sql\")\nsubprocess.call([\"phpunit\", \"--stderr\", \"website\/\"])\n\n# Environment tests.\nprint(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))\n\n# Tear down\nprint(\"Almost done...\")\nif os.path.isfile(\"..\/temp.ini\"):\n shutil.copyfile(\"temp.ini\", \"..\/halite.ini\")\n","new_contents":"import os\nimport os.path\nimport configparser\nimport shutil\nimport subprocess\n\n# Setup\nprint(\"Setting up...\")\nif os.path.isfile(\"..\/halite.ini\"):\n shutil.copyfile(\"..\/halite.ini\", \"temp.ini\")\n\nshutil.copyfile(\"tests.ini\", \"..\/halite.ini\")\nparser = configparser.ConfigParser()\nparser.read(\"..\/halite.ini\")\n\n# Website tests\nprint(\"Beginning website backend tests\")\npasswordField = \"\" if parser[\"database\"][\"password\"] == \"\" else \"-p\"+parser[\"database\"][\"password\"]\nos.system(\"mysql -u \"+parser[\"database\"][\"username\"]+\" \"+passwordField+\" < ..\/website\/sql\/Database.sql\")\nsubprocess.call([\"phpunit\", \"--stderr\", \"website\/\"])\n\n# Environment tests.\nprint(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))\n\n# Tear down\nprint(\"Almost done...\")\nif os.path.isfile(\"..\/temp.ini\"):\n shutil.copyfile(\"temp.ini\", \"..\/halite.ini\")\n","subject":"Make test runner work with blank mysql password","message":"Make test runner work with blank mysql password\n","lang":"Python","license":"mit","repos":"HaliteChallenge\/Halite-II,yangle\/HaliteIO,yangle\/HaliteIO,HaliteChallenge\/Halite,HaliteChallenge\/Halite,yangle\/HaliteIO,lanyudhy\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite,yangle\/HaliteIO,lanyudhy\/Halite-II,HaliteChallenge\/Halite-II,yangle\/HaliteIO,lanyudhy\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite,HaliteChallenge\/Halite-II,lanyudhy\/Halite-II,HaliteChallenge\/Halite,lanyudhy\/Halite-II,yangle\/HaliteIO,lanyudhy\/Halite-II,yangle\/HaliteIO,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite,HaliteChallenge\/Halite,lanyudhy\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite,HaliteChallenge\/Halite-II,yangle\/HaliteIO,HaliteChallenge\/Halite-II,yangle\/HaliteIO,yangle\/HaliteIO,yangle\/HaliteIO,lanyudhy\/Halite-II,HaliteChallenge\/Halite,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite,HaliteChallenge\/Halite-II,yangle\/HaliteIO,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite-II,HaliteChallenge\/Halite,HaliteChallenge\/Halite-II,lanyudhy\/Halite-II,HaliteChallenge\/Halite,lanyudhy\/Halite-II,lanyudhy\/Halite-II,HaliteChallenge\/Halite-II"} {"commit":"030de1eccb4819c175b2d8d43dc16c878bb689c9","old_file":"engines\/empy_engine.py","new_file":"engines\/empy_engine.py","old_contents":"#!\/usr\/bin\/env python\n\"\"\"Provide the empy templating engine.\"\"\"\n\nfrom __future__ import print_function\n\n\nimport em\n\nfrom . import Engine\n\n\nclass EmpyEngine(Engine):\n\n \"\"\"Empy templating engine.\"\"\"\n\n handle = 'empy'\n\n def __init__(self, template, **kwargs):\n \"\"\"Initialize empy template.\"\"\"\n super(EmpyEngine, self).__init__(**kwargs)\n\n self.template = template\n\n def apply(self, mapping):\n \"\"\"Apply a mapping of name-value-pairs to a template.\"\"\"\n return em.expand(self.template, mapping)\n","new_contents":"#!\/usr\/bin\/env python\n\"\"\"Provide the empy templating engine.\"\"\"\n\nfrom __future__ import print_function\n\nimport os.path\n\nimport em\n\nfrom . import Engine\n\n\nclass SubsystemWrapper(em.Subsystem):\n\n \"\"\"Wrap EmPy's Subsystem class.\n\n Allows to open files relative to a base directory.\n \"\"\"\n\n def __init__(self, basedir=None, **kwargs):\n \"\"\"Initialize Subsystem plus a possible base directory.\"\"\"\n super(SubsystemWrapper, self).__init__(**kwargs)\n\n self.basedir = basedir\n\n def open(self, name, *args, **kwargs):\n \"\"\"Open file, possibly relative to a base directory.\"\"\"\n if self.basedir is not None:\n name = os.path.join(self.basedir, name)\n\n return super(SubsystemWrapper, self).open(name, *args, **kwargs)\n\n\nclass EmpyEngine(Engine):\n\n \"\"\"Empy templating engine.\"\"\"\n\n handle = 'empy'\n\n def __init__(self, template, dirname=None, **kwargs):\n \"\"\"Initialize empy template.\"\"\"\n super(EmpyEngine, self).__init__(**kwargs)\n\n if dirname is not None:\n # FIXME: This is a really bad idea, as it works like a global.\n # Blame EmPy.\n em.theSubsystem = SubsystemWrapper(basedir=dirname)\n\n self.template = template\n\n def apply(self, mapping):\n \"\"\"Apply a mapping of name-value-pairs to a template.\"\"\"\n return em.expand(self.template, mapping)\n","subject":"Add base directory capability to empy engine.","message":"Add base directory capability to empy engine.\n","lang":"Python","license":"mit","repos":"blubberdiblub\/eztemplate"} {"commit":"7172962abf0d5d5aad02c632944ed8cb33ca9bae","old_file":"django\/books\/admin.py","new_file":"django\/books\/admin.py","old_contents":"from django.contrib import admin\n\nfrom .models import Author, Book, Note, Tag, Section\n\n\n@admin.register(Author)\nclass AuthorAdmin(admin.ModelAdmin):\n list_display = ['name', 'goodreads_id']\n prepopulated_fields = {'slug': ('name',), }\n\n\n@admin.register(Section)\nclass SectionAdmin(admin.ModelAdmin):\n list_display = ['title', 'subtitle', 'get_page_display', 'book']\n list_filter = ['book']\n\n\n@admin.register(Book)\nclass BookAdmin(admin.ModelAdmin):\n list_display = ['title', 'slug']\n\n\n@admin.register(Note)\nclass NoteAdmin(admin.ModelAdmin):\n list_display = ['subject', 'section', 'book', 'get_page_display']\n search_fields = ['subject', 'quote', 'comment']\n\n\n@admin.register(Tag)\nclass TagAdmin(admin.ModelAdmin):\n list_display = ['slug', 'description', 'colour']\n","new_contents":"from django.contrib import admin\n\nfrom .models import Author, Book, Note, Tag, Section\n\n\n@admin.register(Author)\nclass AuthorAdmin(admin.ModelAdmin):\n list_display = ['name', 'goodreads_id']\n prepopulated_fields = {'slug': ('name',), }\n search_fields = ['name']\n\n\n@admin.register(Section)\nclass SectionAdmin(admin.ModelAdmin):\n list_display = ['title', 'subtitle', 'get_page_display', 'book']\n list_filter = ['book']\n\n\n@admin.register(Book)\nclass BookAdmin(admin.ModelAdmin):\n list_display = ['title', 'slug']\n\n\n@admin.register(Note)\nclass NoteAdmin(admin.ModelAdmin):\n list_display = ['subject', 'section', 'book', 'get_page_display']\n search_fields = ['subject', 'quote', 'comment']\n\n\n@admin.register(Tag)\nclass TagAdmin(admin.ModelAdmin):\n list_display = ['slug', 'description', 'colour']\n","subject":"Allow searching by name in AuthorAdmin","message":"Allow searching by name in AuthorAdmin\n","lang":"Python","license":"mit","repos":"dellsystem\/bookmarker,dellsystem\/bookmarker,dellsystem\/bookmarker"} {"commit":"23f404b61f2c9b89bb631ad0e60edf4416500f28","old_file":"django_split\/utils.py","new_file":"django_split\/utils.py","old_contents":"def overlapping(interval_a, interval_b):\n al, ah = interval_a\n bl, bh = interval_b\n\n if al > ah:\n raise ValueError(\"Interval A bounds are inverted\")\n\n if bl > bh:\n raise ValueError(\"Interval B bounds are inverted\")\n\n return ah >= bl and bh >= al\n","new_contents":"from __future__ import division\n\nimport scipy\nimport scipy.stats\n\ndef overlapping(interval_a, interval_b):\n al, ah = interval_a\n bl, bh = interval_b\n\n if al > ah:\n raise ValueError(\"Interval A bounds are inverted\")\n\n if bl > bh:\n raise ValueError(\"Interval B bounds are inverted\")\n\n return ah >= bl and bh >= al\n\ndef compute_normal_ppf(data_points):\n mean, var = scipy.mean(data_points), scipy.var(data_points)\n return scipy.stats.norm(mean, var).ppf\n\ndef compute_binomial_rate_ppf(hits, total):\n if total == 0:\n return lambda p: 0\n\n distribution = scipy.binom((hits \/ total), total)\n\n return lambda p: distribution.ppf(p) \/ total\n\ndef compute_poisson_daily_rate_ppf(start_date, end_date, hits):\n days = (end_date - start_date).days\n return scipy.poisson(hits \/ days).ppf\n","subject":"Add utilities for computing metrics","message":"Add utilities for computing metrics\n","lang":"Python","license":"mit","repos":"prophile\/django_split"} {"commit":"dd269cea5623450c3c608d10b8ddce1ae6c9e84a","old_file":"project_one\/project_one.py","new_file":"project_one\/project_one.py","old_contents":"# System imports first\nimport sys\n\n# Module (local) imports\nfrom import_data import import_data\nfrom process import process_data, normalize, rotate_data\nfrom output import plot_data\n\n\ndef main(argv=None):\n \"\"\" Main function, executed when running 'project_one'. \"\"\"\n # Read the data\n data = import_data('data.txt')\n data = process_data(data)\n # data = normalize(data)\n # data = rotate_data(data)\n plot_data(data)\n\n# If we're being run with `python project_one.py`, execute main() and exit\n# afterwards with the return value of main().\nif __name__ == \"__main__\":\n sys.exit(main())\n","new_contents":"# System imports first\nimport sys\nimport argparse\n\n# Module (local) imports\nfrom import_data import import_data\nfrom process import process_data, normalize, rotate_data\nfrom output import plot_data\n\n\ndef main(argv=None):\n \"\"\" Main function, executed when running 'project_one'. \"\"\"\n # Parse command-line arguments, this allows the input to be\n # configured from the command line.\n parser = argparse.ArgumentParser(\n description='Import, process and plot test data.'\n )\n parser.add_argument('data_file', type=str)\n\n args = parser.parse_args(argv)\n\n # Read the data\n data = import_data(args.data_file)\n data = process_data(data)\n # data = normalize(data)\n # data = rotate_data(data)\n plot_data(data)\n\n# If we're being run with `python project_one.py`, execute main() and exit\n# afterwards with the return value of main().\nif __name__ == \"__main__\":\n sys.exit(main())\n","subject":"Use command-line argument to specify data.","message":"Use command-line argument to specify data.","lang":"Python","license":"bsd-3-clause","repos":"dokterbob\/slf-project-one"} {"commit":"2c05dba69c838cfd3808d8e03dbea3cc56d4f6d2","old_file":"pyinfra_kubernetes\/__init__.py","new_file":"pyinfra_kubernetes\/__init__.py","old_contents":"from .configure import configure_kubeconfig, configure_kubernetes_component\nfrom .install import install_kubernetes\n\n\ndef deploy_kubernetes_master(etcd_nodes):\n # Install server components\n install_kubernetes(components=(\n 'kube-apiserver', 'kube-scheduler', 'kube-controller-manager',\n ))\n\n # Configure the API server, passing in our etcd nodes\n configure_kubernetes_component('kube-apiserver', etcd_nodes=etcd_nodes)\n\n configure_kubernetes_component('kube-scheduler')\n configure_kubernetes_component('kube-controller-manager')\n\n\ndef deploy_kubernetes_node(master_address):\n # Install node components\n install_kubernetes(components=(\n 'kubelet', 'kube-proxy',\n ))\n\n # Setup the kubeconfig for kubelet & kube-proxy to use\n configure_kubeconfig(master_address)\n\n configure_kubernetes_component('kubelet')\n configure_kubernetes_component('kube-proxy')\n","new_contents":"from pyinfra.api import deploy\n\nfrom .configure import configure_kubeconfig, configure_kubernetes_component\nfrom .install import install_kubernetes\n\n\n@deploy('Deploy Kubernetes master')\ndef deploy_kubernetes_master(\n state, host,\n etcd_nodes,\n):\n # Install server components\n install_kubernetes(components=(\n 'kube-apiserver', 'kube-scheduler', 'kube-controller-manager',\n ))\n\n # Configure the API server, passing in our etcd nodes\n configure_kubernetes_component('kube-apiserver', etcd_nodes=etcd_nodes)\n\n configure_kubernetes_component('kube-scheduler')\n configure_kubernetes_component('kube-controller-manager')\n\n\n@deploy('Deploy Kubernetes node')\ndef deploy_kubernetes_node(\n state, host,\n master_address,\n):\n # Install node components\n install_kubernetes(components=(\n 'kubelet', 'kube-proxy',\n ))\n\n # Setup the kubeconfig for kubelet & kube-proxy to use\n configure_kubeconfig(master_address)\n\n configure_kubernetes_component('kubelet')\n configure_kubernetes_component('kube-proxy')\n","subject":"Make helper functions full `@deploy`s so they support global pyinfra kwargs.","message":"Make helper functions full `@deploy`s so they support global pyinfra kwargs.\n","lang":"Python","license":"mit","repos":"EDITD\/pyinfra-kubernetes,EDITD\/pyinfra-kubernetes"} {"commit":"de3f84934d86e48bf89822828df3eb9c3bd8e1e1","old_file":"test\/test_examples.py","new_file":"test\/test_examples.py","old_contents":"import glob\nfrom libmproxy import utils, script\nfrom libmproxy.proxy import config\nimport tservers\n\ndef test_load_scripts():\n example_dir = utils.Data(\"libmproxy\").path(\"..\/examples\")\n scripts = glob.glob(\"%s\/*.py\" % example_dir)\n\n tmaster = tservers.TestMaster(config.ProxyConfig())\n\n for f in scripts:\n if \"har_extractor\" in f:\n f += \" -\"\n if \"iframe_injector\" in f:\n f += \" foo\" # one argument required\n if \"modify_response_body\" in f:\n f += \" foo bar\" # two arguments required\n s = script.Script(f, tmaster) # Loads the script file.\n s.unload()","new_contents":"import glob\nfrom libmproxy import utils, script\nfrom libmproxy.proxy import config\nimport tservers\n\n\ndef test_load_scripts():\n example_dir = utils.Data(\"libmproxy\").path(\"..\/examples\")\n scripts = glob.glob(\"%s\/*.py\" % example_dir)\n\n tmaster = tservers.TestMaster(config.ProxyConfig())\n\n for f in scripts:\n if \"har_extractor\" in f:\n f += \" -\"\n if \"iframe_injector\" in f:\n f += \" foo\" # one argument required\n if \"modify_response_body\" in f:\n f += \" foo bar\" # two arguments required\n try:\n s = script.Script(f, tmaster) # Loads the script file.\n except Exception, v:\n if not \"ImportError\" in str(v):\n raise\n else:\n s.unload()\n","subject":"Test suite should pass even if example dependencies are not present","message":"Test suite should pass even if example dependencies are not present\n","lang":"Python","license":"mit","repos":"ryoqun\/mitmproxy,ryoqun\/mitmproxy,xaxa89\/mitmproxy,guiquanz\/mitmproxy,ccccccccccc\/mitmproxy,ADemonisis\/mitmproxy,jpic\/mitmproxy,pombredanne\/mitmproxy,noikiy\/mitmproxy,xaxa89\/mitmproxy,fimad\/mitmproxy,onlywade\/mitmproxy,dxq-git\/mitmproxy,inscriptionweb\/mitmproxy,sethp-jive\/mitmproxy,ParthGanatra\/mitmproxy,cortesi\/mitmproxy,byt3bl33d3r\/mitmproxy,dufferzafar\/mitmproxy,mhils\/mitmproxy,owers19856\/mitmproxy,zlorb\/mitmproxy,fimad\/mitmproxy,claimsmall\/mitmproxy,sethp-jive\/mitmproxy,tekii\/mitmproxy,xaxa89\/mitmproxy,ParthGanatra\/mitmproxy,0xwindows\/InfoLeak,ujjwal96\/mitmproxy,vhaupert\/mitmproxy,rauburtin\/mitmproxy,Kriechi\/mitmproxy,MatthewShao\/mitmproxy,zlorb\/mitmproxy,ccccccccccc\/mitmproxy,elitest\/mitmproxy,zbuc\/mitmproxy,jpic\/mitmproxy,StevenVanAcker\/mitmproxy,rauburtin\/mitmproxy,jvillacorta\/mitmproxy,tdickers\/mitmproxy,macmantrl\/mitmproxy,ryoqun\/mitmproxy,meizhoubao\/mitmproxy,mosajjal\/mitmproxy,pombredanne\/mitmproxy,dufferzafar\/mitmproxy,owers19856\/mitmproxy,onlywade\/mitmproxy,mitmproxy\/mitmproxy,Fuzion24\/mitmproxy,mitmproxy\/mitmproxy,dweinstein\/mitmproxy,vhaupert\/mitmproxy,MatthewShao\/mitmproxy,inscriptionweb\/mitmproxy,dufferzafar\/mitmproxy,devasia1000\/mitmproxy,liorvh\/mitmproxy,syjzwjj\/mitmproxy,macmantrl\/mitmproxy,0xwindows\/InfoLeak,noikiy\/mitmproxy,dweinstein\/mitmproxy,ZeYt\/mitmproxy,devasia1000\/mitmproxy,dxq-git\/mitmproxy,StevenVanAcker\/mitmproxy,mitmproxy\/mitmproxy,Kriechi\/mitmproxy,inscriptionweb\/mitmproxy,tekii\/mitmproxy,laurmurclar\/mitmproxy,ryoqun\/mitmproxy,Endika\/mitmproxy,cortesi\/mitmproxy,vhaupert\/mitmproxy,ikoz\/mitmproxy,zbuc\/mitmproxy,scriptmediala\/mitmproxy,tfeagle\/mitmproxy,guiquanz\/mitmproxy,zbuc\/mitmproxy,dwfreed\/mitmproxy,guiquanz\/mitmproxy,azureplus\/mitmproxy,fimad\/mitmproxy,azureplus\/mitmproxy,mosajjal\/mitmproxy,mosajjal\/mitmproxy,onlywade\/mitmproxy,meizhoubao\/mitmproxy,claimsmall\/mitmproxy,scriptmediala\/mitmproxy,noikiy\/mitmproxy,xbzbing\/mitmproxy,Fuzion24\/mitmproxy,zlorb\/mitmproxy,dxq-git\/mitmproxy,ikoz\/mitmproxy,Endika\/mitmproxy,MatthewShao\/mitmproxy,zbuc\/mitmproxy,liorvh\/mitmproxy,Kriechi\/mitmproxy,fimad\/mitmproxy,bazzinotti\/mitmproxy,meizhoubao\/mitmproxy,ikoz\/mitmproxy,tdickers\/mitmproxy,tfeagle\/mitmproxy,syjzwjj\/mitmproxy,gzzhanghao\/mitmproxy,scriptmediala\/mitmproxy,gzzhanghao\/mitmproxy,bazzinotti\/mitmproxy,tfeagle\/mitmproxy,ddworken\/mitmproxy,dweinstein\/mitmproxy,mhils\/mitmproxy,mitmproxy\/mitmproxy,byt3bl33d3r\/mitmproxy,Fuzion24\/mitmproxy,Kriechi\/mitmproxy,dxq-git\/mitmproxy,dwfreed\/mitmproxy,owers19856\/mitmproxy,legendtang\/mitmproxy,tdickers\/mitmproxy,liorvh\/mitmproxy,byt3bl33d3r\/mitmproxy,macmantrl\/mitmproxy,ujjwal96\/mitmproxy,pombredanne\/mitmproxy,mhils\/mitmproxy,onlywade\/mitmproxy,mosajjal\/mitmproxy,ddworken\/mitmproxy,ADemonisis\/mitmproxy,legendtang\/mitmproxy,dwfreed\/mitmproxy,ccccccccccc\/mitmproxy,meizhoubao\/mitmproxy,ccccccccccc\/mitmproxy,ADemonisis\/mitmproxy,syjzwjj\/mitmproxy,sethp-jive\/mitmproxy,tekii\/mitmproxy,Endika\/mitmproxy,xbzbing\/mitmproxy,byt3bl33d3r\/mitmproxy,liorvh\/mitmproxy,devasia1000\/mitmproxy,gzzhanghao\/mitmproxy,jvillacorta\/mitmproxy,syjzwjj\/mitmproxy,xaxa89\/mitmproxy,scriptmediala\/mitmproxy,sethp-jive\/mitmproxy,bazzinotti\/mitmproxy,legendtang\/mitmproxy,dweinstein\/mitmproxy,xbzbing\/mitmproxy,bazzinotti\/mitmproxy,0xwindows\/InfoLeak,jpic\/mitmproxy,ikoz\/mitmproxy,mhils\/mitmproxy,xbzbing\/mitmproxy,gzzhanghao\/mitmproxy,Fuzion24\/mitmproxy,rauburtin\/mitmproxy,noikiy\/mitmproxy,elitest\/mitmproxy,claimsmall\/mitmproxy,jvillacorta\/mitmproxy,ujjwal96\/mitmproxy,elitest\/mitmproxy,ujjwal96\/mitmproxy,StevenVanAcker\/mitmproxy,pombredanne\/mitmproxy,tdickers\/mitmproxy,jpic\/mitmproxy,laurmurclar\/mitmproxy,0xwindows\/InfoLeak,tfeagle\/mitmproxy,owers19856\/mitmproxy,laurmurclar\/mitmproxy,mitmproxy\/mitmproxy,macmantrl\/mitmproxy,tekii\/mitmproxy,mhils\/mitmproxy,ZeYt\/mitmproxy,StevenVanAcker\/mitmproxy,ParthGanatra\/mitmproxy,azureplus\/mitmproxy,Endika\/mitmproxy,ZeYt\/mitmproxy,MatthewShao\/mitmproxy,ZeYt\/mitmproxy,rauburtin\/mitmproxy,laurmurclar\/mitmproxy,ddworken\/mitmproxy,claimsmall\/mitmproxy,ParthGanatra\/mitmproxy,vhaupert\/mitmproxy,devasia1000\/mitmproxy,ddworken\/mitmproxy,cortesi\/mitmproxy,dufferzafar\/mitmproxy,ADemonisis\/mitmproxy,legendtang\/mitmproxy,dwfreed\/mitmproxy,zlorb\/mitmproxy,jvillacorta\/mitmproxy,inscriptionweb\/mitmproxy,azureplus\/mitmproxy,cortesi\/mitmproxy,elitest\/mitmproxy,guiquanz\/mitmproxy"} {"commit":"92d7a3cf2ec3ae669fab17906b10b784525a134a","old_file":"pyinduct\/tests\/__init__.py","new_file":"pyinduct\/tests\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\nimport sys\n\nif any([arg in {'discover', 'setup.py', 'test'} for arg in sys.argv]):\n test_examples = True\n test_all_examples = False\n show_plots = False\nelif any(['sphinx-build' in arg for arg in sys.argv]):\n test_examples = False\n test_all_examples = False\n show_plots = False\nelse:\n test_examples = True\n test_all_examples = True\n show_plots = True\n # Do not want to see plots or test all examples while test run?\n # Then force it and uncomment the respective line:\n # test_all_examples = False\n show_plots = False\n","new_contents":"# -*- coding: utf-8 -*-\nimport sys\n\nif any([arg in {'discover', 'setup.py', 'test'} for arg in sys.argv]):\n test_examples = True\n test_all_examples = False\n show_plots = False\nelif any(['sphinx-build' in arg for arg in sys.argv]):\n test_examples = False\n test_all_examples = False\n show_plots = False\nelse:\n test_examples = True\n test_all_examples = True\n show_plots = True\n # Do not want to see plots or test all examples while test run?\n # Then force it and uncomment the respective line:\n # test_all_examples = False\n # show_plots = False\n","subject":"Revert commit of local changes","message":"Revert commit of local changes\n","lang":"Python","license":"bsd-3-clause","repos":"cklb\/pyinduct,riemarc\/pyinduct,pyinduct\/pyinduct"} {"commit":"c55243d591793a9213d27126a3c240bb47c5f82b","old_file":"cartoframes\/core\/cartodataframe.py","new_file":"cartoframes\/core\/cartodataframe.py","old_contents":"from geopandas import GeoDataFrame\n\nfrom ..utils.geom_utils import generate_index, generate_geometry\n\n\nclass CartoDataFrame(GeoDataFrame):\n\n def __init__(self, *args, **kwargs):\n super(CartoDataFrame, self).__init__(*args, **kwargs)\n\n @staticmethod\n def from_carto(*args, **kwargs):\n from ..io.carto import read_carto\n return read_carto(*args, **kwargs)\n\n @classmethod\n def from_file(cls, filename, **kwargs):\n gdf = GeoDataFrame.from_file(filename, **kwargs)\n return cls(gdf)\n\n @classmethod\n def from_features(cls, features, **kwargs):\n gdf = GeoDataFrame.from_features(features, **kwargs)\n return cls(gdf)\n\n def to_carto(self, *args, **kwargs):\n from ..io.carto import to_carto\n return to_carto(self, *args, **kwargs)\n\n def convert(self, index_column=None, geom_column=None, lnglat_columns=None,\n drop_index=True, drop_geom=True, drop_lnglat=True):\n # Magic function\n generate_index(self, index_column, drop_index)\n generate_geometry(self, geom_column, lnglat_columns, drop_geom, drop_lnglat)\n return self\n\n def visualize(self, *args, **kwargs):\n from ..viz import Map, Layer\n return Map(Layer(self, *args, **kwargs))\n\n viz = visualize\n","new_contents":"from geopandas import GeoDataFrame\n\nfrom ..utils.geom_utils import generate_index, generate_geometry\n\n\nclass CartoDataFrame(GeoDataFrame):\n\n def __init__(self, *args, **kwargs):\n super(CartoDataFrame, self).__init__(*args, **kwargs)\n\n @staticmethod\n def from_carto(*args, **kwargs):\n from ..io.carto import read_carto\n return read_carto(*args, **kwargs)\n\n @classmethod\n def from_file(cls, filename, **kwargs):\n gdf = GeoDataFrame.from_file(filename, **kwargs)\n return cls(gdf)\n\n @classmethod\n def from_features(cls, features, **kwargs):\n gdf = GeoDataFrame.from_features(features, **kwargs)\n return cls(gdf)\n\n def to_carto(self, *args, **kwargs):\n from ..io.carto import to_carto\n return to_carto(self, *args, **kwargs)\n\n def convert(self, index_column=None, geom_column=None, lnglat_columns=None,\n drop_index=True, drop_geom=True, drop_lnglat=True):\n # Magic function\n generate_index(self, index_column, drop_index)\n generate_geometry(self, geom_column, lnglat_columns, drop_geom, drop_lnglat)\n return self\n\n def viz(self, *args, **kwargs):\n from ..viz import Map, Layer\n return Map(Layer(self, *args, **kwargs))\n","subject":"Rename visualize to viz in CDF","message":"Rename visualize to viz in CDF\n","lang":"Python","license":"bsd-3-clause","repos":"CartoDB\/cartoframes,CartoDB\/cartoframes"} {"commit":"a0a98f374a66093ad3c35a2e185ac9b48d8b3f2d","old_file":"lib\/reinteract\/__init__.py","new_file":"lib\/reinteract\/__init__.py","old_contents":"","new_contents":"import gobject\n\n# https:\/\/bugzilla.gnome.org\/show_bug.cgi?id=644039\ndef fixed_default_setter(self, instance, value):\n setattr(instance, '_property_helper_'+self.name, value)\n\ndef fixed_default_getter(self, instance):\n return getattr(instance, '_property_helper_'+self.name, self.default)\n\ndef monkey_patch_gobject_property():\n p = gobject.property()\n if hasattr(p, '_values'):\n gobject.propertyhelper.property._default_setter = fixed_default_setter\n gobject.propertyhelper.property._default_getter = fixed_default_getter\n\nmonkey_patch_gobject_property()\n","subject":"Work around leak in older pygobject","message":"Work around leak in older pygobject\n\nWith older pygobject, any use of the default getter\/setters\ngenerated by gobject.property() would leak. If we detect this\nis the case, monkey patch in the fixed version of the default\ngetters\/setters.\n(See https:\/\/bugzilla.gnome.org\/show_bug.cgi?id=644039)\n","lang":"Python","license":"bsd-2-clause","repos":"alexey4petrov\/reinteract,alexey4petrov\/reinteract,alexey4petrov\/reinteract"} {"commit":"a2aa2ea452c7fb2f3a83a13f000a51223cb3d13f","old_file":"client\/sources\/doctest\/__init__.py","new_file":"client\/sources\/doctest\/__init__.py","old_contents":"from client.sources.common import importing\nfrom client.sources.doctest import models\nimport logging\nimport os\n\nlog = logging.getLogger(__name__)\n\ndef load(file, name, args):\n \"\"\"Loads doctests from a specified filepath.\n\n PARAMETERS:\n file -- str; a filepath to a Python module containing OK-style\n tests.\n\n RETURNS:\n Test\n \"\"\"\n if not os.path.isfile(file) or not file.endswith('.py'):\n log.info('Cannot import doctests from {}'.format(file))\n # TODO(albert): raise appropriate error\n raise Exception\n\n module = importing.load_module(file)\n if not hasattr(module, name):\n # TODO(albert): raise appropriate error\n raise Exception\n func = getattr(module, name)\n if not callable(func):\n # TODO(albert): raise appropriate error\n raise Exception\n return models.Doctest(file, args.verbose, args.interactive, args.timeout,\n name=name, points=1, docstring=func.__doc__)\n","new_contents":"from client.sources.common import importing\nfrom client.sources.doctest import models\nimport logging\nimport os\n\nlog = logging.getLogger(__name__)\n\ndef load(file, name, args):\n \"\"\"Loads doctests from a specified filepath.\n\n PARAMETERS:\n file -- str; a filepath to a Python module containing OK-style\n tests.\n\n RETURNS:\n Test\n \"\"\"\n if not os.path.isfile(file) or not file.endswith('.py'):\n log.info('Cannot import doctests from {}'.format(file))\n # TODO(albert): raise appropriate error\n raise Exception('Cannot import doctests from {}'.format(file))\n\n module = importing.load_module(file)\n if not hasattr(module, name):\n # TODO(albert): raise appropriate error\n raise Exception('Module {} has no function {}'.format(module.__name__, name))\n func = getattr(module, name)\n if not callable(func):\n # TODO(albert): raise appropriate error\n raise Exception\n return models.Doctest(file, args.verbose, args.interactive, args.timeout,\n name=name, points=1, docstring=func.__doc__)\n","subject":"Add a few exception strings","message":"Add a few exception strings\n","lang":"Python","license":"apache-2.0","repos":"jackzhao-mj\/ok-client,Cal-CS-61A-Staff\/ok-client,jathak\/ok-client"} {"commit":"fc5ae93998045f340e44e267f409a7bdf534c756","old_file":"website_slides\/__init__.py","new_file":"website_slides\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\n# ##############################################################################\n#\n# Odoo, Open Source Management Solution\n# Copyright (C) 2014-TODAY Odoo SA ().\n#\n# This program is free software: you can redistribute it and\/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nimport controllers\nimport models\n","new_contents":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nimport controllers\nimport models\n","subject":"Use global LICENSE\/COPYRIGHT files, remove boilerplate text","message":"[LEGAL] Use global LICENSE\/COPYRIGHT files, remove boilerplate text\n\n- Preserved explicit 3rd-party copyright notices\n- Explicit boilerplate should not be necessary - copyright law applies\n automatically in all countries thanks to Berne Convention + WTO rules,\n and a reference to the applicable license is clear enough.\n","lang":"Python","license":"agpl-3.0","repos":"Endika\/website,Yajo\/website,kaerdsar\/website,brain-tec\/website,kaerdsar\/website,gfcapalbo\/website,pedrobaeza\/website,Antiun\/website,open-synergy\/website,LasLabs\/website,open-synergy\/website,brain-tec\/website,nuobit\/website,acsone\/website,nuobit\/website,xpansa\/website,acsone\/website,Antiun\/website,Antiun\/website,pedrobaeza\/website,LasLabs\/website,brain-tec\/website,gfcapalbo\/website,Endika\/website,Endika\/website,pedrobaeza\/website,pedrobaeza\/website,gfcapalbo\/website,Yajo\/website,nuobit\/website,brain-tec\/website,Endika\/website,open-synergy\/website,acsone\/website,xpansa\/website,kaerdsar\/website,xpansa\/website,Antiun\/website,nuobit\/website,xpansa\/website,Yajo\/website,LasLabs\/website,acsone\/website,open-synergy\/website,gfcapalbo\/website,LasLabs\/website,Yajo\/website"} {"commit":"403278510197a0ccdb0d2bb52d46a997e722d460","old_file":"ncbi_genome_download\/__init__.py","new_file":"ncbi_genome_download\/__init__.py","old_contents":"\"\"\"Download genome files from the NCBI\"\"\"\nfrom .config import (\n SUPPORTED_TAXONOMIC_GROUPS,\n NgdConfig\n)\nfrom .core import (\n args_download,\n download,\n argument_parser,\n)\n\n__version__ = '0.2.6'\n__all__ = [\n 'download',\n 'args_download',\n 'SUPPORTED_TAXONOMIC_GROUPS',\n 'NgdConfig',\n 'argument_parser'\n]\n","new_contents":"\"\"\"Download genome files from the NCBI\"\"\"\nfrom .config import (\n SUPPORTED_TAXONOMIC_GROUPS,\n NgdConfig\n)\nfrom .core import (\n args_download,\n download,\n argument_parser,\n)\n\n__version__ = '0.2.7'\n__all__ = [\n 'download',\n 'args_download',\n 'SUPPORTED_TAXONOMIC_GROUPS',\n 'NgdConfig',\n 'argument_parser'\n]\n","subject":"Bump version number to 0.2.7","message":"Bump version number to 0.2.7\n\nSigned-off-by: Kai Blin \n","lang":"Python","license":"apache-2.0","repos":"kblin\/ncbi-genome-download,kblin\/ncbi-genome-download"} {"commit":"ee6f71ba0e548fdb08a3f1b065cd081b2431caa6","old_file":"lc0222_count_complete_tree_nodes.py","new_file":"lc0222_count_complete_tree_nodes.py","old_contents":"\"\"\"Leetcode 222. Count Complete Tree Nodes\nMedium\n\nURL: https:\/\/leetcode.com\/problems\/count-complete-tree-nodes\/\n\nGiven a complete binary tree, count the number of nodes.\n\nNote:\n\nDefinition of a complete binary tree from Wikipedia:\nIn a complete binary tree every level, except possibly the last,\nis completely filled, and all nodes in the last level are as far left as\npossible. It can have between 1 and 2h nodes inclusive at the last level h.\n\nExample:\nInput: \n 1\n \/ \\\n 2 3\n \/ \\ \/\n4 5 6\nOutput: 6\n\"\"\"\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def countNodes(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n pass\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n","new_contents":"\"\"\"Leetcode 222. Count Complete Tree Nodes\nMedium\n\nURL: https:\/\/leetcode.com\/problems\/count-complete-tree-nodes\/\n\nGiven a complete binary tree, count the number of nodes.\n\nNote:\n\nDefinition of a complete binary tree from Wikipedia:\nIn a complete binary tree every level, except possibly the last,\nis completely filled, and all nodes in the last level are as far left as\npossible. It can have between 1 and 2h nodes inclusive at the last level h.\n\nExample:\nInput: \n 1\n \/ \\\n 2 3\n \/ \\ \/\n4 5 6\nOutput: 6\n\"\"\"\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n\nclass SolutionPreorderRecur(object):\n def _preorder(self, root):\n if not root:\n return None\n \n self.n_nodes += 1\n self._preorder(root.left)\n self._preorder(root.right)\n\n def countNodes(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n\n Time complexity: O(n).\n Space complexity: O(1).\n \"\"\"\n self.n_nodes = 0\n self._preorder(root)\n return self.n_nodes\n\n\ndef main():\n # Input: \n # 1\n # \/ \\\n # 2 3\n # \/ \\ \/\n # 4 5 6\n # Output: 6\n root = TreeNode(1)\n root.left = TreeNode(2)\n root.right = TreeNode(3)\n root.left.left = TreeNode(4)\n root.left.right = TreeNode(5)\n root.right.left = TreeNode(6)\n print SolutionPreorderRecur().countNodes(root)\n\n\nif __name__ == '__main__':\n main()\n","subject":"Complete preorder recur sol w\/ time\/space complexity","message":"Complete preorder recur sol w\/ time\/space complexity\n","lang":"Python","license":"bsd-2-clause","repos":"bowen0701\/algorithms_data_structures"} {"commit":"8c819a1cb9df54c00b7246a07e2ba832b763876d","old_file":"stream_django\/templatetags\/activity_tags.py","new_file":"stream_django\/templatetags\/activity_tags.py","old_contents":"from django import template\nfrom django.template import Context, loader\nfrom stream_django.exceptions import MissingDataException\nimport logging\n\n\nlogger = logging.getLogger(__name__)\nregister = template.Library()\n\nLOG = 'warn'\nIGNORE = 'ignore'\nFAIL = 'fail'\n\nmissing_data_policies = [LOG, IGNORE, FAIL]\n\n\ndef handle_not_enriched_data(activity, policy):\n message = 'could not enrich field(s) %r for activity #%s' % (activity.not_enriched_data, activity.get('id'))\n if policy == IGNORE:\n pass\n elif policy == FAIL:\n raise MissingDataException(message)\n elif policy == LOG:\n logger.warn(message)\n else:\n raise TypeError('%s is not a valid missing_data_policy' % policy)\n\n\ndef render_activity(context, activity, template_prefix='', missing_data_policy=LOG):\n if hasattr(activity, 'enriched') and not activity.enriched:\n handle_not_enriched_data(activity, missing_data_policy)\n return ''\n\n if template_prefix != '':\n template_prefix = '%s_' % template_prefix\n\n if 'activities' in activity:\n template_name = \"activity\/aggregated\/%s%s.html\" % (template_prefix, activity['verb'])\n else:\n template_name = \"activity\/%s%s.html\" % (template_prefix, activity['verb'])\n\n tmpl = loader.get_template(template_name)\n context['activity'] = activity\n context = Context(context)\n return tmpl.render(context)\n\n\nregister.simple_tag(takes_context=True)(render_activity)\n","new_contents":"from django import template\nfrom django.template import loader\nfrom stream_django.exceptions import MissingDataException\nimport logging\n\n\nlogger = logging.getLogger(__name__)\nregister = template.Library()\n\nLOG = 'warn'\nIGNORE = 'ignore'\nFAIL = 'fail'\n\nmissing_data_policies = [LOG, IGNORE, FAIL]\n\n\ndef handle_not_enriched_data(activity, policy):\n message = 'could not enrich field(s) %r for activity #%s' % (activity.not_enriched_data, activity.get('id'))\n if policy == IGNORE:\n pass\n elif policy == FAIL:\n raise MissingDataException(message)\n elif policy == LOG:\n logger.warn(message)\n else:\n raise TypeError('%s is not a valid missing_data_policy' % policy)\n\n\ndef render_activity(context, activity, template_prefix='', missing_data_policy=LOG):\n if hasattr(activity, 'enriched') and not activity.enriched:\n handle_not_enriched_data(activity, missing_data_policy)\n return ''\n\n if template_prefix != '':\n template_prefix = '%s_' % template_prefix\n\n if 'activities' in activity:\n template_name = \"activity\/aggregated\/%s%s.html\" % (template_prefix, activity['verb'])\n else:\n template_name = \"activity\/%s%s.html\" % (template_prefix, activity['verb'])\n\n tmpl = loader.get_template(template_name)\n context['activity'] = activity\n return tmpl.render(context)\n\n\nregister.simple_tag(takes_context=True)(render_activity)\n","subject":"Use dict as a context object for Django 1.11 compatibility","message":"Use dict as a context object for Django 1.11 compatibility\n\nDjango’s template rendering in 1.11 needs a dictionary as the context\ninstead of the object Context, otherwise the following error is raised:\ncontext must be a dict rather than Context.\n","lang":"Python","license":"bsd-3-clause","repos":"GetStream\/stream-django,GetStream\/stream-django"} {"commit":"6727bb98c91f1185042d08f3ff2a4c5ef625cae4","old_file":"mjstat\/languages\/__init__.py","new_file":"mjstat\/languages\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\n\"\"\"__init__.py: Language-dependent features.\n\"\"\"\n\nmodule_cache = {}\n\ndef get_language(lang_code):\n \"\"\"Return module with language localizations.\n\n This is a poor copy of the language framework of Docutils.\n \"\"\"\n\n if lang_code in module_cache:\n return module_cache[lang_code]\n\n for i in (1, 0):\n try:\n module = __import__(lang_code, globals(), locals(), level=i)\n break\n except ImportError:\n continue\n else:\n module = __import__('en', globals(), locals(), level=1)\n\n module_cache[lang_code] = module\n return module\n","new_contents":"# -*- coding: utf-8 -*-\n\"\"\"__init__.py: Language-dependent features.\n\"\"\"\n\nfrom importlib import import_module\n\nmodule_cache = {}\n\ndef get_language(lang_code):\n \"\"\"Return module with language localizations.\n\n This is a revamped version of function docutils.languages.get_language.\n \"\"\"\n\n if lang_code in module_cache:\n return module_cache[lang_code]\n\n try:\n module = import_module('.' + lang_code, __name__)\n except ImportError:\n from . import en\n module = en\n\n module_cache[lang_code] = module\n return module\n","subject":"Use importlib.import_module instead of built-in __import__.","message":"Use importlib.import_module instead of built-in __import__.\n","lang":"Python","license":"mit","repos":"showa-yojyo\/bin,showa-yojyo\/bin"} {"commit":"030d425bb2b9b552516957277aebb22806bfc699","old_file":"bills\/redis_queue.py","new_file":"bills\/redis_queue.py","old_contents":"# -*- coding: utf-8 -*-\n\nimport redis\n\nclass RedisQueue(object):\n \"\"\"Simple Queue with Redis Backend\"\"\"\n def __init__(self, name, namespace='queue', **redis_kwargs):\n \"\"\"The default connection parameters are: host='localhost', port=6379, db=0\"\"\"\n self.db = redis.Redis(**redis_kwargs)\n self.key = '%s:%s' %(namespace, name)\n\n def qsize(self):\n \"\"\"Return the approximate size of the queue.\"\"\"\n return self.db.llen(self.key)\n\n def empty(self):\n \"\"\"Return True if the queue is empty, False otherwise.\"\"\"\n return self.qsize() == 0\n\n def put(self, item):\n \"\"\"Put item into the queue.\"\"\"\n self.db.rpush(self.key, item)\n\n def get(self, block=True, timeout=None):\n \"\"\"Remove and return an item from the queue.\n\n If optional args block is true and timeout is None (the default), block\n if necessary until an item is available.\"\"\"\n if block:\n item = self.db.blpop(self.key, timeout=timeout)\n else:\n item = self.db.lpop(self.key)\n\n if item:\n item = item[1]\n return item\n\n def get_nowait(self):\n \"\"\"Equivalent to get(False).\"\"\"\n return self.get(False)\n\n def __iter__(self):\n return self\n\n def next(self):\n item = self.get(False)\n if item is None:\n raise StopIteration\n return item\n\n","new_contents":"# -*- coding: utf-8 -*-\n\nimport redis\n\nclass RedisQueue(object):\n \"\"\"Simple Queue with Redis Backend\"\"\"\n def __init__(self, name, namespace='queue', **redis_kwargs):\n \"\"\"The default connection parameters are: host='localhost', port=6379, db=0\"\"\"\n self.db = redis.Redis(**redis_kwargs)\n self.key = '%s:%s' %(namespace, name)\n\n def qsize(self):\n \"\"\"Return the approximate size of the queue.\"\"\"\n return self.db.llen(self.key)\n\n def empty(self):\n \"\"\"Return True if the queue is empty, False otherwise.\"\"\"\n return self.qsize() == 0\n\n def put(self, item):\n \"\"\"Put item into the queue.\"\"\"\n self.db.rpush(self.key, item)\n\n def get(self, block=True, timeout=None):\n \"\"\"Remove and return an item from the queue.\n\n If optional args block is true and timeout is None (the default), block\n if necessary until an item is available.\"\"\"\n if block:\n item = self.db.blpop(self.key, timeout=timeout)\n if item:\n item = item[1]\n else:\n item = self.db.lpop(self.key)\n\n return item\n\n def get_nowait(self):\n \"\"\"Equivalent to get(False).\"\"\"\n return self.get(False)\n\n def __iter__(self):\n return self\n\n def next(self):\n item = self.get(False)\n if item is None:\n raise StopIteration\n return item\n\n","subject":"Fix a bug in redis queue","message":"Fix a bug in redis queue\n","lang":"Python","license":"agpl-3.0","repos":"teampopong\/crawlers,majorika\/crawlers,majorika\/crawlers,lexifdev\/crawlers,lexifdev\/crawlers,teampopong\/crawlers"} {"commit":"6a1d9a327ebf64acba9bd02330bfa047e8137337","old_file":"bmi_live\/__init__.py","new_file":"bmi_live\/__init__.py","old_contents":"\"\"\"BMI Live clinic\"\"\"\nimport os\n\n\npkg_directory = os.path.dirname(__file__)\ndata_directory = os.path.join(pkg_directory, 'data')\n","new_contents":"\"\"\"BMI Live clinic\"\"\"\nimport os\nfrom .diffusion import Diffusion\nfrom .bmi_diffusion import BmiDiffusion\n\n\n__all__ = ['Diffusion', 'BmiDiffusion']\n\npkg_directory = os.path.dirname(__file__)\ndata_directory = os.path.join(pkg_directory, 'data')\n","subject":"Include classes in package definition","message":"Include classes in package definition\n","lang":"Python","license":"mit","repos":"csdms\/bmi-live,csdms\/bmi-live"} {"commit":"1648e071fe69ba159261f27e4b2d0e2b977d6d83","old_file":"zou\/app\/models\/working_file.py","new_file":"zou\/app\/models\/working_file.py","old_contents":"from sqlalchemy_utils import UUIDType\n\nfrom zou.app import db\nfrom zou.app.models.serializer import SerializerMixin\nfrom zou.app.models.base import BaseMixin\n\n\nclass WorkingFile(db.Model, BaseMixin, SerializerMixin):\n shotgun_id = db.Column(db.Integer())\n\n name = db.Column(db.String(250))\n description = db.Column(db.String(200))\n comment = db.Column(db.Text())\n revision = db.Column(db.Integer())\n size = db.Column(db.Integer())\n checksum = db.Column(db.Integer())\n\n task_id = db.Column(UUIDType(binary=False), db.ForeignKey(\"task.id\"))\n entity_id = db.Column(UUIDType(binary=False), db.ForeignKey(\"entity.id\"))\n person_id = \\\n db.Column(UUIDType(binary=False), db.ForeignKey(\"person.id\"))\n\n __table_args__ = (\n db.UniqueConstraint(\n \"name\",\n \"task_id\",\n \"entity_id\",\n \"revision\",\n name=\"working_file_uc\"\n ),\n )\n\n def __repr__(self):\n return \"\" % self.id\n","new_contents":"from sqlalchemy.orm import relationship\nfrom sqlalchemy_utils import UUIDType\n\nfrom zou.app import db\nfrom zou.app.models.serializer import SerializerMixin\nfrom zou.app.models.base import BaseMixin\n\n\nclass WorkingFile(db.Model, BaseMixin, SerializerMixin):\n shotgun_id = db.Column(db.Integer())\n\n name = db.Column(db.String(250))\n description = db.Column(db.String(200))\n comment = db.Column(db.Text())\n revision = db.Column(db.Integer())\n size = db.Column(db.Integer())\n checksum = db.Column(db.Integer())\n path = db.Column(db.String(400))\n\n task_id = db.Column(UUIDType(binary=False), db.ForeignKey(\"task.id\"))\n entity_id = db.Column(UUIDType(binary=False), db.ForeignKey(\"entity.id\"))\n person_id = \\\n db.Column(UUIDType(binary=False), db.ForeignKey(\"person.id\"))\n software_id = \\\n db.Column(UUIDType(binary=False), db.ForeignKey(\"software.id\"))\n outputs = relationship(\n \"OutputFile\",\n back_populates=\"source_file\"\n )\n\n __table_args__ = (\n db.UniqueConstraint(\n \"name\",\n \"task_id\",\n \"entity_id\",\n \"revision\",\n name=\"working_file_uc\"\n ),\n )\n\n def __repr__(self):\n return \"\" % self.id\n","subject":"Add fields to working file model","message":"Add fields to working file model\n\n* Software\n* List of output files generated\n* Path used to store the working file\n","lang":"Python","license":"agpl-3.0","repos":"cgwire\/zou"} {"commit":"afb195b1ca647d776f29fbc1d68a495190caec59","old_file":"astropy\/time\/setup_package.py","new_file":"astropy\/time\/setup_package.py","old_contents":"import os\nimport numpy\nfrom distutils.extension import Extension\n\nTIMEROOT = os.path.relpath(os.path.dirname(__file__))\n\n\ndef get_extensions():\n time_ext = Extension(\n name=\"astropy.time.sofa_time\",\n sources=[os.path.join(TIMEROOT, \"sofa_time.pyx\"), \"cextern\/sofa\/sofa.c\"],\n include_dirs=[numpy.get_include(), 'cextern\/sofa'],\n language=\"c\",)\n return [time_ext]\n","new_contents":"import os\nfrom distutils.extension import Extension\n\nTIMEROOT = os.path.relpath(os.path.dirname(__file__))\n\n\ndef get_extensions():\n time_ext = Extension(\n name=\"astropy.time.sofa_time\",\n sources=[os.path.join(TIMEROOT, \"sofa_time.pyx\"), \"cextern\/sofa\/sofa.c\"],\n include_dirs=['numpy', 'cextern\/sofa'],\n language=\"c\",)\n return [time_ext]\n","subject":"Fix remaining include_dirs that imported numpy ('numpy' gets replaced at build-time). This is necessary for egg_info to work.","message":"Fix remaining include_dirs that imported numpy ('numpy' gets replaced at build-time). This is necessary for egg_info to work.","lang":"Python","license":"bsd-3-clause","repos":"kelle\/astropy,AustereCuriosity\/astropy,joergdietrich\/astropy,stargaser\/astropy,astropy\/astropy,bsipocz\/astropy,bsipocz\/astropy,kelle\/astropy,larrybradley\/astropy,StuartLittlefair\/astropy,DougBurke\/astropy,mhvk\/astropy,stargaser\/astropy,aleksandr-bakanov\/astropy,tbabej\/astropy,dhomeier\/astropy,lpsinger\/astropy,DougBurke\/astropy,astropy\/astropy,funbaker\/astropy,pllim\/astropy,pllim\/astropy,tbabej\/astropy,dhomeier\/astropy,aleksandr-bakanov\/astropy,larrybradley\/astropy,MSeifert04\/astropy,pllim\/astropy,DougBurke\/astropy,DougBurke\/astropy,AustereCuriosity\/astropy,lpsinger\/astropy,mhvk\/astropy,funbaker\/astropy,bsipocz\/astropy,astropy\/astropy,funbaker\/astropy,lpsinger\/astropy,saimn\/astropy,saimn\/astropy,astropy\/astropy,AustereCuriosity\/astropy,MSeifert04\/astropy,joergdietrich\/astropy,dhomeier\/astropy,MSeifert04\/astropy,larrybradley\/astropy,kelle\/astropy,saimn\/astropy,mhvk\/astropy,tbabej\/astropy,kelle\/astropy,kelle\/astropy,joergdietrich\/astropy,astropy\/astropy,joergdietrich\/astropy,dhomeier\/astropy,larrybradley\/astropy,aleksandr-bakanov\/astropy,bsipocz\/astropy,stargaser\/astropy,saimn\/astropy,mhvk\/astropy,funbaker\/astropy,stargaser\/astropy,dhomeier\/astropy,pllim\/astropy,AustereCuriosity\/astropy,pllim\/astropy,StuartLittlefair\/astropy,StuartLittlefair\/astropy,mhvk\/astropy,StuartLittlefair\/astropy,saimn\/astropy,joergdietrich\/astropy,aleksandr-bakanov\/astropy,StuartLittlefair\/astropy,larrybradley\/astropy,lpsinger\/astropy,tbabej\/astropy,AustereCuriosity\/astropy,MSeifert04\/astropy,lpsinger\/astropy,tbabej\/astropy"} {"commit":"55d22f95301c4c96c42e30fa037df5bc957dc7b4","old_file":"incunafein\/module\/page\/extensions\/prepared_date.py","new_file":"incunafein\/module\/page\/extensions\/prepared_date.py","old_contents":"from django.db import models\n\ndef register(cls, admin_cls):\n cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))\n\n","new_contents":"from django.db import models\n\ndef get_prepared_date(cls):\n return cls.prepared_date or cls.parent.prepared_date\n\ndef register(cls, admin_cls):\n cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))\n cls.add_to_class('get_prepared_date', get_prepared_date)\n\n","subject":"Add a get prepared date method","message":"Add a get prepared date method\n\nChild pages won't necessarily have a prepared date and it makes sense to\nuse the parent date to avoid repetition.\n","lang":"Python","license":"bsd-2-clause","repos":"incuna\/incuna-feincms,incuna\/incuna-feincms,incuna\/incuna-feincms"} {"commit":"0fdb33dc0da1aa953e91e71b0e0cfa75fca3d639","old_file":"skylines\/views\/__init__.py","new_file":"skylines\/views\/__init__.py","old_contents":"from flask import redirect\n\nfrom skylines import app\n\nimport skylines.views.i18n\nimport skylines.views.login\nimport skylines.views.search\n\nfrom skylines.views.about import about_blueprint\nfrom skylines.views.api import api_blueprint\nfrom skylines.views.flights import flights_blueprint\nfrom skylines.views.notifications import notifications_blueprint\nfrom skylines.views.ranking import ranking_blueprint\nfrom skylines.views.statistics import statistics_blueprint\nfrom skylines.views.upload import upload_blueprint\nfrom skylines.views.users import users_blueprint\n\napp.register_blueprint(about_blueprint, url_prefix='\/about')\napp.register_blueprint(api_blueprint, url_prefix='\/api')\napp.register_blueprint(flights_blueprint, url_prefix='\/flights')\napp.register_blueprint(notifications_blueprint, url_prefix='\/notifications')\napp.register_blueprint(ranking_blueprint, url_prefix='\/ranking')\napp.register_blueprint(statistics_blueprint, url_prefix='\/statistics')\napp.register_blueprint(upload_blueprint, url_prefix='\/flights\/upload')\napp.register_blueprint(users_blueprint, url_prefix='\/users')\n\n\n@app.route('\/')\ndef index():\n return redirect('\/flights\/latest')\n","new_contents":"from flask import redirect, url_for\n\nfrom skylines import app\n\nimport skylines.views.i18n\nimport skylines.views.login\nimport skylines.views.search\n\nfrom skylines.views.about import about_blueprint\nfrom skylines.views.api import api_blueprint\nfrom skylines.views.flights import flights_blueprint\nfrom skylines.views.notifications import notifications_blueprint\nfrom skylines.views.ranking import ranking_blueprint\nfrom skylines.views.statistics import statistics_blueprint\nfrom skylines.views.upload import upload_blueprint\nfrom skylines.views.users import users_blueprint\n\napp.register_blueprint(about_blueprint, url_prefix='\/about')\napp.register_blueprint(api_blueprint, url_prefix='\/api')\napp.register_blueprint(flights_blueprint, url_prefix='\/flights')\napp.register_blueprint(notifications_blueprint, url_prefix='\/notifications')\napp.register_blueprint(ranking_blueprint, url_prefix='\/ranking')\napp.register_blueprint(statistics_blueprint, url_prefix='\/statistics')\napp.register_blueprint(upload_blueprint, url_prefix='\/flights\/upload')\napp.register_blueprint(users_blueprint, url_prefix='\/users')\n\n\n@app.route('\/')\ndef index():\n return redirect(url_for('flights.latest'))\n","subject":"Use url_for for base redirection","message":"views: Use url_for for base redirection\n","lang":"Python","license":"agpl-3.0","repos":"shadowoneau\/skylines,Turbo87\/skylines,snip\/skylines,shadowoneau\/skylines,Harry-R\/skylines,TobiasLohner\/SkyLines,RBE-Avionik\/skylines,RBE-Avionik\/skylines,kerel-fs\/skylines,Turbo87\/skylines,snip\/skylines,kerel-fs\/skylines,skylines-project\/skylines,RBE-Avionik\/skylines,TobiasLohner\/SkyLines,skylines-project\/skylines,RBE-Avionik\/skylines,skylines-project\/skylines,Harry-R\/skylines,Turbo87\/skylines,Harry-R\/skylines,Turbo87\/skylines,kerel-fs\/skylines,shadowoneau\/skylines,skylines-project\/skylines,shadowoneau\/skylines,TobiasLohner\/SkyLines,snip\/skylines,Harry-R\/skylines"} {"commit":"217829993e108fb4f5c17ae2bbc80151418cf733","old_file":"Mobiles_Stadtgedaechtnis\/urls.py","new_file":"Mobiles_Stadtgedaechtnis\/urls.py","old_contents":"from django.conf.urls import patterns, include, url\n\nimport stadtgedaechtnis_backend.admin\nimport settings\nfrom thread import start_new_thread\n\njs_info_dict = {\n 'packages': ('stadtgedaechtnis_backend',),\n}\n\nurlpatterns = patterns(\n '',\n url(r'^', include('stadtgedaechtnis_backend.urls', namespace=\"stadtgedaechtnis_backend\")),\n url(r'^', include('stadtgedaechtnis_frontend.urls', namespace=\"stadtgedaechtnis_frontend\")),\n url(r'^admin\/', include(stadtgedaechtnis_backend.admin.site.urls)),\n url(r'^i18n\/', include('django.conf.urls.i18n')),\n url(r'^media\/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, }),\n)\n\n\ndef run_cronjobs():\n \"\"\"\n Runs the cronjobs. Needs to be called in a seperate thread or the main thread will be blocked.\n :return:\n \"\"\"\n import schedule\n import time\n from stadtgedaechtnis_backend.import_entries.importers import do_silent_json_import\n from stadtgedaechtnis_backend.import_entries.urls import JSON_URL\n\n schedule.every().day.at(\"23:00\").do(do_silent_json_import, JSON_URL)\n\n while True:\n schedule.run_pending()\n time.sleep(1)\n\nstart_new_thread(run_cronjobs, [])\n","new_contents":"from django.conf.urls import patterns, include, url\n\nimport stadtgedaechtnis_backend.admin\nimport settings\nfrom thread import start_new_thread\n\njs_info_dict = {\n 'packages': ('stadtgedaechtnis_backend',),\n}\n\nurlpatterns = patterns(\n '',\n url(r'^', include('stadtgedaechtnis_backend.urls', namespace=\"stadtgedaechtnis_backend\")),\n url(r'^', include('stadtgedaechtnis_frontend.urls', namespace=\"stadtgedaechtnis_frontend\")),\n url(r'^admin\/', include(stadtgedaechtnis_backend.admin.site.urls)),\n url(r'^i18n\/', include('django.conf.urls.i18n')),\n url(r'^media\/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, }),\n)\n\n\ndef run_cronjobs():\n \"\"\"\n Runs the cronjobs. Needs to be called in a seperate thread or the main thread will be blocked.\n :return:\n \"\"\"\n import schedule\n import time\n from stadtgedaechtnis_backend.import_entries.importers import do_silent_json_import\n from stadtgedaechtnis_backend.import_entries.urls import JSON_URL\n\n schedule.every().day.at(\"23:00\").do(do_silent_json_import, JSON_URL)\n\n while True:\n schedule.run_pending()\n time.sleep(1)\n\nstart_new_thread(run_cronjobs, ())\n","subject":"Replace list with tuple in start new thread","message":"Replace list with tuple in start new thread\n","lang":"Python","license":"mit","repos":"fraunhoferfokus\/mobile-city-memory,fraunhoferfokus\/mobile-city-memory,jessepeng\/coburg-city-memory,jessepeng\/coburg-city-memory"} {"commit":"cc3ab3af17e30e7dd9991d68f01eaa4535b64e6b","old_file":"djangae\/models.py","new_file":"djangae\/models.py","old_contents":"from django.db import models\n\nclass CounterShard(models.Model):\n count = models.PositiveIntegerField()\n","new_contents":"from django.db import models\n\nclass CounterShard(models.Model):\n count = models.PositiveIntegerField()\n\n\n#Apply our django patches\nfrom .patches import *","subject":"Patch update_contenttypes so that it's less likely to fail due to eventual consistency","message":"Patch update_contenttypes so that it's less likely to fail due to eventual consistency\n","lang":"Python","license":"bsd-3-clause","repos":"nealedj\/djangae,martinogden\/djangae,grzes\/djangae,stucox\/djangae,asendecka\/djangae,trik\/djangae,trik\/djangae,wangjun\/djangae,armirusco\/djangae,b-cannon\/my_djae,jscissr\/djangae,grzes\/djangae,wangjun\/djangae,chargrizzle\/djangae,chargrizzle\/djangae,leekchan\/djangae,kirberich\/djangae,martinogden\/djangae,pablorecio\/djangae,nealedj\/djangae,armirusco\/djangae,asendecka\/djangae,nealedj\/djangae,jscissr\/djangae,stucox\/djangae,potatolondon\/djangae,leekchan\/djangae,grzes\/djangae,jscissr\/djangae,asendecka\/djangae,kirberich\/djangae,leekchan\/djangae,SiPiggles\/djangae,kirberich\/djangae,martinogden\/djangae,armirusco\/djangae,SiPiggles\/djangae,chargrizzle\/djangae,pablorecio\/djangae,stucox\/djangae,SiPiggles\/djangae,trik\/djangae,potatolondon\/djangae,wangjun\/djangae,pablorecio\/djangae"} {"commit":"776c3b0df6136606b8b7474418fd5d078457bd0a","old_file":"test\/persistence_test.py","new_file":"test\/persistence_test.py","old_contents":"from os.path import exists, join\nimport shutil\nimport tempfile\nimport time\n\nfrom lwr.managers.queued import QueueManager\nfrom lwr.managers.stateful import StatefulManagerProxy\nfrom lwr.tools.authorization import get_authorizer\nfrom .test_utils import TestDependencyManager\n\nfrom galaxy.util.bunch import Bunch\n\n\ndef test_persistence():\n \"\"\"\n Tests persistence of a managers jobs.\n \"\"\"\n staging_directory = tempfile.mkdtemp()\n try:\n app = Bunch(staging_directory=staging_directory,\n persistence_directory=staging_directory,\n authorizer=get_authorizer(None),\n dependency_manager=TestDependencyManager(),\n )\n assert not exists(join(staging_directory, \"queued_jobs\"))\n queue1 = StatefulManagerProxy(QueueManager('test', app, num_concurrent_jobs=0))\n job_id = queue1.setup_job('4', 'tool1', '1.0.0')\n touch_file = join(staging_directory, 'ran')\n queue1.launch(job_id, 'touch %s' % touch_file)\n time.sleep(.4)\n assert (not(exists(touch_file)))\n queue1.shutdown()\n queue2 = StatefulManagerProxy(QueueManager('test', app, num_concurrent_jobs=1))\n time.sleep(1)\n assert exists(touch_file)\n finally:\n shutil.rmtree(staging_directory)\n try:\n queue2.shutdown()\n except:\n pass\n","new_contents":"from os.path import exists, join\nimport shutil\nimport tempfile\nimport time\n\nfrom lwr.managers.queued import QueueManager\nfrom lwr.managers.stateful import StatefulManagerProxy\nfrom lwr.tools.authorization import get_authorizer\nfrom .test_utils import TestDependencyManager\n\nfrom galaxy.util.bunch import Bunch\nfrom galaxy.jobs.metrics import NULL_JOB_INSTRUMENTER\n\n\ndef test_persistence():\n \"\"\"\n Tests persistence of a managers jobs.\n \"\"\"\n staging_directory = tempfile.mkdtemp()\n try:\n app = Bunch(staging_directory=staging_directory,\n persistence_directory=staging_directory,\n authorizer=get_authorizer(None),\n dependency_manager=TestDependencyManager(),\n job_metrics=Bunch(default_job_instrumenter=NULL_JOB_INSTRUMENTER),\n )\n assert not exists(join(staging_directory, \"queued_jobs\"))\n queue1 = StatefulManagerProxy(QueueManager('test', app, num_concurrent_jobs=0))\n job_id = queue1.setup_job('4', 'tool1', '1.0.0')\n touch_file = join(staging_directory, 'ran')\n queue1.launch(job_id, 'touch %s' % touch_file)\n time.sleep(.4)\n assert (not(exists(touch_file)))\n queue1.shutdown()\n queue2 = StatefulManagerProxy(QueueManager('test', app, num_concurrent_jobs=1))\n time.sleep(1)\n assert exists(touch_file)\n finally:\n shutil.rmtree(staging_directory)\n try:\n queue2.shutdown()\n except:\n pass\n","subject":"Fix another failing unit test (from metrics work).","message":"Fix another failing unit test (from metrics work).\n","lang":"Python","license":"apache-2.0","repos":"jmchilton\/lwr,natefoo\/pulsar,natefoo\/pulsar,jmchilton\/pulsar,galaxyproject\/pulsar,jmchilton\/pulsar,ssorgatem\/pulsar,galaxyproject\/pulsar,ssorgatem\/pulsar,jmchilton\/lwr"} {"commit":"3ee7d716f0eb3202ccf7ca213747eb903f9bb471","old_file":"__init__.py","new_file":"__init__.py","old_contents":"from .Averager import Averager\nfrom .Config import Config\nfrom .RateTicker import RateTicker\nfrom .Ring import Ring\nfrom .SortedList import SortedList\nfrom .String import string2time, time2string\nfrom .Timer import Timer\nfrom .UserInput import user_input\n","new_contents":"from .Averager import Averager\nfrom .Config import Config\nfrom .RateTicker import RateTicker\nfrom .Ring import Ring\nfrom .SortedList import SortedList\nfrom .String import string2time, time2string, time2levels, time2dir, time2fname\nfrom .Timer import Timer\nfrom .UserInput import user_input\n","subject":"Add missing names to module namespace.","message":"Add missing names to module namespace.\n","lang":"Python","license":"mit","repos":"vmlaker\/coils"} {"commit":"c05fc3ae4d6ac0ed459150acf2c19fd892c2ea9f","old_file":"bumblebee\/modules\/caffeine.py","new_file":"bumblebee\/modules\/caffeine.py","old_contents":"#pylint: disable=C0111,R0903\n\n\"\"\"Enable\/disable automatic screen locking.\n\nRequires the following executables:\n * xdg-screensaver\n * notify-send\n\"\"\"\n\nimport bumblebee.input\nimport bumblebee.output\nimport bumblebee.engine\n\nclass Module(bumblebee.engine.Module):\n def __init__(self, engine, config):\n super(Module, self).__init__(engine, config,\n bumblebee.output.Widget(full_text=\"\")\n )\n self._active = False\n self.interval(1)\n \n engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE,\n cmd=self._toggle\n )\n\n def state(self, widget):\n if self._active:\n return \"activated\"\n return \"deactivated\"\n\n def _toggle(self, event):\n self._active = not self._active\n if self._active:\n bumblebee.util.execute(\"xdg-screensaver reset\")\n bumblebee.util.execute(\"notify-send \\\"Consuming caffeine\\\"\")\n else:\n bumblebee.util.execute(\"notify-send \\\"Out of coffee\\\"\")\n\n def update(self, widgets):\n if self._active:\n bumblebee.util.execute(\"xdg-screensaver reset\")\n\n\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n","new_contents":"#pylint: disable=C0111,R0903\n\n\"\"\"Enable\/disable automatic screen locking.\n\nRequires the following executables:\n * xdg-screensaver\n * notify-send\n\"\"\"\n\nimport bumblebee.input\nimport bumblebee.output\nimport bumblebee.engine\n\nclass Module(bumblebee.engine.Module):\n def __init__(self, engine, config):\n super(Module, self).__init__(engine, config,\n bumblebee.output.Widget(full_text=\"\")\n )\n self._active = False\n self.interval(1)\n \n engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE,\n cmd=self._toggle\n )\n\n def state(self, widget):\n if self._active:\n return \"activated\"\n return \"deactivated\"\n\n def _toggle(self, event):\n self._active = not self._active\n try:\n if self._active:\n bumblebee.util.execute(\"xdg-screensaver reset\")\n bumblebee.util.execute(\"notify-send \\\"Consuming caffeine\\\"\")\n else:\n bumblebee.util.execute(\"notify-send \\\"Out of coffee\\\"\")\n except:\n self._active = not self._active\n\n def update(self, widgets):\n if self._active:\n bumblebee.util.execute(\"xdg-screensaver reset\")\n\n\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n","subject":"Add some basic error handling in case the executables don't exist","message":"Add some basic error handling in case the executables don't exist\n","lang":"Python","license":"mit","repos":"tobi-wan-kenobi\/bumblebee-status,tobi-wan-kenobi\/bumblebee-status"} {"commit":"ffadde617db8ac3d0d5362b4a521dd4e9839710f","old_file":"order\/order_2_login_system_by_https.py","new_file":"order\/order_2_login_system_by_https.py","old_contents":"import json\nimport requests\n\n\"\"\" Order 2: Login system by https\n\n```\ncurl -k https:\/\/192.168.105.88\/axapi\/v3\/auth -H \"Content-type:application\/json\" -d '{\n \"credentials\": {\n \"username\": \"admin\", \n \"password\": \"a10\"\n }\n}'\n```\n\"\"\"\n\n\nclass LoginSystemByHttps(object):\n login_url = 'http:\/\/192.168.105.88\/axapi\/v3\/auth'\n\n def login(self):\n \"\"\"\n Note: the dict playload must be use json.dumps() to turn to str.\n :return: Result string data\n \"\"\"\n payload = {'credentials': {'username': \"admin\", 'password': \"a10\"}}\n headers = {'content-type': 'application\/json', 'Connection': 'keep-alive'}\n response = requests.post(self.login_url, data=json.dumps(payload), verify=False, headers=headers)\n print(response.text)\n return response.text\n\n\n# login = LoginSystemByHttps()\n# login.login()\n","new_contents":"import json\nimport requests\n\n\"\"\" Order 2: Login system by https\n\nThis is the code which use curl to login system\n```\ncurl -k https:\/\/192.168.105.88\/axapi\/v3\/auth -H \"Content-type:application\/json\" -d '{\n \"credentials\": {\n \"username\": \"admin\", \n \"password\": \"a10\"\n }\n}'\n```\n\"\"\"\n\n\nclass LoginSystemByHttps(object):\n login_url = 'http:\/\/192.168.105.88\/axapi\/v3\/auth'\n\n def login(self):\n \"\"\"\n Note: the dict playload must be use json.dumps() to turn to str.\n :return: Result string data\n \"\"\"\n payload = {'credentials': {'username': \"admin\", 'password': \"a10\"}}\n headers = {'content-type': 'application\/json', 'Connection': 'keep-alive'}\n response = requests.post(self.login_url, data=json.dumps(payload), verify=False, headers=headers)\n print(response.text)\n return response.text\n\n\n# login = LoginSystemByHttps()\n# login.login()\n","subject":"Order 2: Login system by https","message":"[Order] Order 2: Login system by https\n","lang":"Python","license":"mit","repos":"flyingSprite\/spinelle"} {"commit":"646a248d59f835264729b48a0116d51089f6113e","old_file":"oscar\/templatetags\/currency_filters.py","new_file":"oscar\/templatetags\/currency_filters.py","old_contents":"from decimal import Decimal as D, InvalidOperation\n\nfrom django import template\nfrom django.conf import settings\nfrom babel.numbers import format_currency\n\nregister = template.Library()\n\n\n@register.filter(name='currency')\ndef currency(value):\n \"\"\"\n Format decimal value as currency\n \"\"\"\n try:\n value = D(value)\n except (TypeError, InvalidOperation):\n return u\"\"\n # Using Babel's currency formatting\n # http:\/\/packages.python.org\/Babel\/api\/babel.numbers-module.html#format_currency\n kwargs = {\n 'currency': settings.OSCAR_DEFAULT_CURRENCY,\n 'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)}\n locale = getattr(settings, 'OSCAR_CURRENCY_LOCALE', None)\n if locale:\n kwargs['locale'] = locale\n return format_currency(value, **kwargs)\n","new_contents":"from decimal import Decimal as D, InvalidOperation\n\nfrom django import template\nfrom django.conf import settings\nfrom babel.numbers import format_currency\n\nregister = template.Library()\n\n\n@register.filter(name='currency')\ndef currency(value):\n \"\"\"\n Format decimal value as currency\n \"\"\"\n try:\n value = D(value)\n except (TypeError, InvalidOperation):\n return u\"\"\n # Using Babel's currency formatting\n # http:\/\/babel.pocoo.org\/docs\/api\/numbers\/#babel.numbers.format_currency\n kwargs = {\n 'currency': settings.OSCAR_DEFAULT_CURRENCY,\n 'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)}\n locale = getattr(settings, 'OSCAR_CURRENCY_LOCALE', None)\n if locale:\n kwargs['locale'] = locale\n return format_currency(value, **kwargs)\n","subject":"Replace broken babel documentation link","message":"Replace broken babel documentation link\n\nAccording to Babel's PyPI package page, http:\/\/babel.pocoo.org\/docs\/ is\nthe official documentation website.\n","lang":"Python","license":"bsd-3-clause","repos":"lijoantony\/django-oscar,faratro\/django-oscar,michaelkuty\/django-oscar,MatthewWilkes\/django-oscar,django-oscar\/django-oscar,dongguangming\/django-oscar,taedori81\/django-oscar,pasqualguerrero\/django-oscar,marcoantoniooliveira\/labweb,faratro\/django-oscar,Jannes123\/django-oscar,binarydud\/django-oscar,Jannes123\/django-oscar,solarissmoke\/django-oscar,faratro\/django-oscar,pdonadeo\/django-oscar,ademuk\/django-oscar,vovanbo\/django-oscar,michaelkuty\/django-oscar,okfish\/django-oscar,thechampanurag\/django-oscar,sasha0\/django-oscar,rocopartners\/django-oscar,binarydud\/django-oscar,pdonadeo\/django-oscar,elliotthill\/django-oscar,john-parton\/django-oscar,adamend\/django-oscar,ahmetdaglarbas\/e-commerce,mexeniz\/django-oscar,Jannes123\/django-oscar,monikasulik\/django-oscar,rocopartners\/django-oscar,josesanch\/django-oscar,QLGu\/django-oscar,Bogh\/django-oscar,dongguangming\/django-oscar,spartonia\/django-oscar,bschuon\/django-oscar,vovanbo\/django-oscar,marcoantoniooliveira\/labweb,WadeYuChen\/django-oscar,manevant\/django-oscar,anentropic\/django-oscar,django-oscar\/django-oscar,thechampanurag\/django-oscar,Jannes123\/django-oscar,solarissmoke\/django-oscar,marcoantoniooliveira\/labweb,jinnykoo\/wuyisj,monikasulik\/django-oscar,Bogh\/django-oscar,bnprk\/django-oscar,lijoantony\/django-oscar,adamend\/django-oscar,okfish\/django-oscar,itbabu\/django-oscar,jinnykoo\/wuyisj,kapt\/django-oscar,jinnykoo\/wuyisj.com,pasqualguerrero\/django-oscar,MatthewWilkes\/django-oscar,anentropic\/django-oscar,DrOctogon\/unwash_ecom,josesanch\/django-oscar,WadeYuChen\/django-oscar,makielab\/django-oscar,WillisXChen\/django-oscar,manevant\/django-oscar,faratro\/django-oscar,john-parton\/django-oscar,itbabu\/django-oscar,spartonia\/django-oscar,kapari\/django-oscar,WillisXChen\/django-oscar,ademuk\/django-oscar,thechampanurag\/django-oscar,kapari\/django-oscar,saadatqadri\/django-oscar,machtfit\/django-oscar,makielab\/django-oscar,sonofatailor\/django-oscar,jinnykoo\/christmas,michaelkuty\/django-oscar,makielab\/django-oscar,okfish\/django-oscar,manevant\/django-oscar,DrOctogon\/unwash_ecom,taedori81\/django-oscar,Idematica\/django-oscar,Idematica\/django-oscar,nickpack\/django-oscar,jinnykoo\/christmas,ahmetdaglarbas\/e-commerce,mexeniz\/django-oscar,vovanbo\/django-oscar,jinnykoo\/wuyisj.com,okfish\/django-oscar,mexeniz\/django-oscar,jinnykoo\/wuyisj.com,machtfit\/django-oscar,itbabu\/django-oscar,bschuon\/django-oscar,dongguangming\/django-oscar,MatthewWilkes\/django-oscar,anentropic\/django-oscar,machtfit\/django-oscar,Idematica\/django-oscar,michaelkuty\/django-oscar,jinnykoo\/wuyisj.com,sasha0\/django-oscar,amirrpp\/django-oscar,monikasulik\/django-oscar,bnprk\/django-oscar,elliotthill\/django-oscar,spartonia\/django-oscar,lijoantony\/django-oscar,jinnykoo\/wuyisj,nickpack\/django-oscar,sonofatailor\/django-oscar,nfletton\/django-oscar,jmt4\/django-oscar,ka7eh\/django-oscar,WadeYuChen\/django-oscar,WillisXChen\/django-oscar,eddiep1101\/django-oscar,rocopartners\/django-oscar,saadatqadri\/django-oscar,binarydud\/django-oscar,jlmadurga\/django-oscar,django-oscar\/django-oscar,itbabu\/django-oscar,ademuk\/django-oscar,jmt4\/django-oscar,sasha0\/django-oscar,nfletton\/django-oscar,DrOctogon\/unwash_ecom,taedori81\/django-oscar,Bogh\/django-oscar,ahmetdaglarbas\/e-commerce,anentropic\/django-oscar,binarydud\/django-oscar,WadeYuChen\/django-oscar,jlmadurga\/django-oscar,makielab\/django-oscar,marcoantoniooliveira\/labweb,nfletton\/django-oscar,manevant\/django-oscar,nickpack\/django-oscar,lijoantony\/django-oscar,taedori81\/django-oscar,sonofatailor\/django-oscar,ahmetdaglarbas\/e-commerce,kapari\/django-oscar,ka7eh\/django-oscar,saadatqadri\/django-oscar,bnprk\/django-oscar,solarissmoke\/django-oscar,john-parton\/django-oscar,solarissmoke\/django-oscar,QLGu\/django-oscar,kapt\/django-oscar,john-parton\/django-oscar,WillisXChen\/django-oscar,jlmadurga\/django-oscar,elliotthill\/django-oscar,pdonadeo\/django-oscar,pasqualguerrero\/django-oscar,amirrpp\/django-oscar,nickpack\/django-oscar,bschuon\/django-oscar,kapari\/django-oscar,sasha0\/django-oscar,MatthewWilkes\/django-oscar,Bogh\/django-oscar,nfletton\/django-oscar,pasqualguerrero\/django-oscar,dongguangming\/django-oscar,amirrpp\/django-oscar,saadatqadri\/django-oscar,josesanch\/django-oscar,QLGu\/django-oscar,monikasulik\/django-oscar,ademuk\/django-oscar,spartonia\/django-oscar,jlmadurga\/django-oscar,jinnykoo\/christmas,ka7eh\/django-oscar,rocopartners\/django-oscar,sonofatailor\/django-oscar,eddiep1101\/django-oscar,QLGu\/django-oscar,jmt4\/django-oscar,adamend\/django-oscar,adamend\/django-oscar,eddiep1101\/django-oscar,bnprk\/django-oscar,jinnykoo\/wuyisj,WillisXChen\/django-oscar,amirrpp\/django-oscar,eddiep1101\/django-oscar,vovanbo\/django-oscar,bschuon\/django-oscar,kapt\/django-oscar,mexeniz\/django-oscar,WillisXChen\/django-oscar,ka7eh\/django-oscar,thechampanurag\/django-oscar,pdonadeo\/django-oscar,jmt4\/django-oscar,django-oscar\/django-oscar"} {"commit":"315b581b9b0438389c7f4eb651d2893b805a2369","old_file":"translit.py","new_file":"translit.py","old_contents":"class Transliterator(object):\n\n def __init__(self, mapping, invert=False):\n self.mapping = [\n (v, k) if invert else (k, v)\n for k, v in mapping.items()\n ]\n\n self._rules = sorted(\n self.mapping,\n key=lambda item: len(item[0]),\n reverse=True,\n )\n\n @property\n def rules(self):\n for r in self._rules:\n yield r\n\n # Handle the case when one source upper char is represented by\n # several latin chars, all uppercase. i.e. \"CH\" instead of \"Ch\"\n k, v = r\n if len(k) > 1 and k[0].isupper():\n yield (k.upper(), v.upper())\n\n def convert(self, input_string):\n \"\"\"Transliterate input string.\"\"\"\n for (source_char, translit_char) in self.rules:\n input_string = input_string.replace(source_char, translit_char)\n\n return input_string\n","new_contents":"class Transliterator(object):\n\n def __init__(self, mapping, invert=False):\n self.mapping = [\n (v, k) if invert else (k, v)\n for k, v in mapping.items()\n ]\n\n self._rules = sorted(\n self.mapping,\n key=lambda item: len(item[0]),\n reverse=True,\n )\n\n @property\n def rules(self):\n for r in self._rules:\n k, v = r\n if len(k) == 0:\n continue # for case when char is removed and mapping inverted\n\n yield r\n\n # Handle the case when one source upper char is represented by\n # several latin chars, all uppercase. i.e. \"CH\" instead of \"Ch\"\n if len(k) > 1 and k[0].isupper():\n yield (k.upper(), v.upper())\n\n def convert(self, input_string):\n \"\"\"Transliterate input string.\"\"\"\n for (source_char, translit_char) in self.rules:\n input_string = input_string.replace(source_char, translit_char)\n\n return input_string\n","subject":"Handle case when char is mapped to empty (removed) and table is inverted","message":"Handle case when char is mapped to empty (removed) and table is inverted\n","lang":"Python","license":"mit","repos":"malexer\/SublimeTranslit"} {"commit":"6f8f449316a71dd284d2661d206d88d35c01ea54","old_file":"TrevorNet\/tests\/test_idx.py","new_file":"TrevorNet\/tests\/test_idx.py","old_contents":"from .. import idx\nimport os\n\ndef test__find_depth():\n yield check__find_depth, 9, 0\n yield check__find_depth, [1, 2], 1\n yield check__find_depth, [[1, 2], [3, 6, 2]], 2\n yield check__find_depth, [[[1,2], [2]]], 3\n\ndef check__find_depth(lst, i):\n assert idx._find_dimensions(lst) == i\n\n# these two are equivalent according to the format on http:\/\/yann.lecun.com\/exdb\/mnist\/\n_somelist = [[1, 2], [3, 4]]\n_somebytes = '\\x00\\x00\\x0C\\x02' + '\\x01\\x02\\x03\\x04'\n\n_testfolder = os.path.dirname(os.path.realpath(__file__))\n_somepath = os.path.join(_testfolder, 'test_idx_file')\n\ndef test_list_to_idx():\n idx.list_to_idx(_somelist, _somepath, 'i')\n with open(_somepath, 'rb') as f:\n data = f.read() \n os.remove(_somepath)\n\n assert data == _somebytes\n\ndef test_idx_to_list():\n with open(_somepath, 'wb') as f:\n f.write(_somebytes)\n lst = idx.idx_to_list(_somepath)\n os.remove(_somepath)\n\n assert lst == _somelist\n","new_contents":"from .. import idx\nimport os\n\ndef test__count_dimensions():\n yield check__count_dimensions, 9, 0\n yield check__count_dimensions, [1, 2], 1\n yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2\n yield check__count_dimensions, [[[1,2], [2]]], 3\n\ndef check__count_dimensions(lst, i):\n assert idx._count_dimensions(lst) == i\n\n# these two are equivalent according to the format on http:\/\/yann.lecun.com\/exdb\/mnist\/\n_somelist = [[1, 2], [3, 4]]\n_somebytes = b'\\x00\\x00\\x0C\\x02' + b'\\x01\\x02\\x03\\x04'\n\ndef test_list_to_idx():\n data = idx.list_to_idx(_somelist, 'i')\n assert data == _somebytes\n\ndef test_idx_to_list():\n lst = idx.idx_to_list(_somebytes)\n assert lst == _somelist\n","subject":"Update for python 3 and new idx design","message":"Update for python 3 and new idx design\n\nidx no longer writes to files, it only processes bytes\n","lang":"Python","license":"mit","repos":"tmerr\/trevornet"} {"commit":"c5b130444e2061ae1c6bdf16ebc14d08817a8aea","old_file":"dsub\/_dsub_version.py","new_file":"dsub\/_dsub_version.py","old_contents":"# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Single source of truth for dsub's version.\n\nThis must remain small and dependency-free so that any dsub module may\nimport it without creating circular dependencies. Note that this module\nis parsed as a text file by setup.py and changes to the format of this\nfile could break setup.py.\n\nThe version should follow formatting requirements specified in PEP-440.\n - https:\/\/www.python.org\/dev\/peps\/pep-0440\n\nA typical release sequence will be versioned as:\n 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...\n\"\"\"\n\nDSUB_VERSION = '0.3.10.dev0'\n","new_contents":"# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Single source of truth for dsub's version.\n\nThis must remain small and dependency-free so that any dsub module may\nimport it without creating circular dependencies. Note that this module\nis parsed as a text file by setup.py and changes to the format of this\nfile could break setup.py.\n\nThe version should follow formatting requirements specified in PEP-440.\n - https:\/\/www.python.org\/dev\/peps\/pep-0440\n\nA typical release sequence will be versioned as:\n 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...\n\"\"\"\n\nDSUB_VERSION = '0.3.10'\n","subject":"Update dsub version to 0.3.10","message":"Update dsub version to 0.3.10\n\nPiperOrigin-RevId: 324884094\n","lang":"Python","license":"apache-2.0","repos":"DataBiosphere\/dsub,DataBiosphere\/dsub"} {"commit":"564075cbb66c6e79a6225d7f678aea804075b966","old_file":"api\/urls.py","new_file":"api\/urls.py","old_contents":"from django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'fbxnano.views.home', name='home'),\n # url(r'^blog\/', include('blog.urls')),\n\n url('^status$', TemplateView.as_view(template_name='api\/status.html'), name='status'),\n)\n","new_contents":"from django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\n\n\nfrom .views import StatusView\n\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'fbxnano.views.home', name='home'),\n # url(r'^blog\/', include('blog.urls')),\n\n url('^status$', StatusView.as_view(), name='status'),\n)\n","subject":"Switch from generic TemplateView to new StatusView","message":"Switch from generic TemplateView to new StatusView\n","lang":"Python","license":"mit","repos":"Kromey\/fbxnano,Kromey\/akwriters,Kromey\/akwriters,Kromey\/akwriters,Kromey\/akwriters,Kromey\/fbxnano,Kromey\/fbxnano,Kromey\/fbxnano"} {"commit":"e615e2ebf3f364ba093c48d6fb0c988f0b97bc13","old_file":"nyuki\/workflow\/tasks\/__init__.py","new_file":"nyuki\/workflow\/tasks\/__init__.py","old_contents":"from .factory import FactoryTask\nfrom .report import ReportTask\nfrom .sleep import SleepTask\n\n\n# Generic schema to reference a task ID\nTASKID_SCHEMA = {\n 'type': 'string',\n 'description': 'task_id'\n}\n","new_contents":"from .factory import FactoryTask\nfrom .report import ReportTask\nfrom .sleep import SleepTask\n\n\n# Generic schema to reference a task ID\nTASKID_SCHEMA = {\n 'type': 'string',\n 'description': 'task_id',\n 'maxLength': 128\n}\n","subject":"Add maxlength to taskid schema","message":"Add maxlength to taskid schema\n","lang":"Python","license":"apache-2.0","repos":"gdraynz\/nyuki,optiflows\/nyuki,gdraynz\/nyuki,optiflows\/nyuki"} {"commit":"9e035f05a2df345674362b38130c7c3a2d4800cc","old_file":"filer\/__init__.py","new_file":"filer\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\n\n# version string following pep-0396 and pep-0386\n__version__ = '1.2.9.dev' # pragma: nocover\n\ndefault_app_config = 'filer.apps.FilerConfig'\n","new_contents":"# -*- coding: utf-8 -*-\n\n# version string following pep-0396 and pep-0386\n__version__ = '1.3.0.dev' # pragma: nocover\n\ndefault_app_config = 'filer.apps.FilerConfig'\n","subject":"Bump develop version to 1.3.0.dev","message":"Bump develop version to 1.3.0.dev","lang":"Python","license":"bsd-3-clause","repos":"webu\/django-filer,skirsdeda\/django-filer,webu\/django-filer,stefanfoulis\/django-filer,divio\/django-filer,divio\/django-filer,divio\/django-filer,skirsdeda\/django-filer,stefanfoulis\/django-filer,divio\/django-filer,webu\/django-filer,skirsdeda\/django-filer,stefanfoulis\/django-filer,stefanfoulis\/django-filer,stefanfoulis\/django-filer,webu\/django-filer,skirsdeda\/django-filer,skirsdeda\/django-filer"} {"commit":"fe4ce6dfa26c60747b6024fa9f6d991aa3b95614","old_file":"scripts\/codegen_driverwrappers\/generate_driver_wrappers.py","new_file":"scripts\/codegen_driverwrappers\/generate_driver_wrappers.py","old_contents":"#!\/usr\/bin\/env python3\n\nimport sys\nimport json\nimport os\nimport jinja2\n\ndef render(tpl_path):\n path, filename = os.path.split(tpl_path)\n return jinja2.Environment(\n loader=jinja2.FileSystemLoader(path or '.\/')\n ).get_template(filename).render()\n\nn = len(sys.argv)\nif ( n != 3 ):\n sys.exit(\"The template file name and output file name are expected as arguments\")\n# set template file name, output file name\ndriver_wrapper_template_filename = sys.argv[1]\ndriver_wrapper_output_filename = sys.argv[2]\n\n# render the template\nresult = render(driver_wrapper_template_filename)\n\n# write output to file\noutFile = open(driver_wrapper_output_filename,\"w\")\noutFile.write(result)\noutFile.close()\n","new_contents":"#!\/usr\/bin\/env python3\n\nimport sys\nimport json\nimport os\nimport jinja2\n\ndef render(tpl_path):\n path, filename = os.path.split(tpl_path)\n return jinja2.Environment(\n loader=jinja2.FileSystemLoader(path or '.\/'),\n keep_trailing_newline=True,\n ).get_template(filename).render()\n\nn = len(sys.argv)\nif ( n != 3 ):\n sys.exit(\"The template file name and output file name are expected as arguments\")\n# set template file name, output file name\ndriver_wrapper_template_filename = sys.argv[1]\ndriver_wrapper_output_filename = sys.argv[2]\n\n# render the template\nresult = render(driver_wrapper_template_filename)\n\n# write output to file\noutFile = open(driver_wrapper_output_filename,\"w\")\noutFile.write(result)\noutFile.close()\n","subject":"Fix trailing newline getting dropped","message":"Fix trailing newline getting dropped\n\nSigned-off-by: Gilles Peskine \n","lang":"Python","license":"apache-2.0","repos":"Mbed-TLS\/mbedtls,NXPmicro\/mbedtls,NXPmicro\/mbedtls,Mbed-TLS\/mbedtls,NXPmicro\/mbedtls,NXPmicro\/mbedtls,ARMmbed\/mbedtls,Mbed-TLS\/mbedtls,ARMmbed\/mbedtls,ARMmbed\/mbedtls,Mbed-TLS\/mbedtls,ARMmbed\/mbedtls"} {"commit":"c264e4b19505bfb0ccebc1551c7b82e96b6a2882","old_file":"amqpy\/tests\/test_version.py","new_file":"amqpy\/tests\/test_version.py","old_contents":"class TestVersion:\n def test_version_is_consistent(self):\n from .. import VERSION\n\n with open('README.rst') as f:\n readme = f.read().split('\\n')\n version_list = readme[3].split(':')[2].strip().split('.')\n version_list = [int(i) for i in version_list]\n readme_version = tuple(version_list)\n\n assert VERSION == readme_version\n","new_contents":"import re\n\n\ndef get_field(doc: str, name: str):\n match = re.search(':{}: (.*)$'.format(name), doc, re.IGNORECASE | re.MULTILINE)\n if match:\n return match.group(1).strip()\n\n\nclass TestVersion:\n def test_version_is_consistent(self):\n from .. import VERSION\n\n with open('README.rst') as f:\n readme = f.read()\n\n version = get_field(readme, 'version')\n version = version.split('.')\n version = [int(i) for i in version]\n version = tuple(version)\n\n assert VERSION == version\n","subject":"Clean up test for version number","message":"Clean up test for version number\n\nA new function is implemented to cleanly extract the version field from the\nREADME.rst field list.\n","lang":"Python","license":"mit","repos":"veegee\/amqpy,gst\/amqpy"} {"commit":"a7830d85c6966732e46da63903c04234d8d16c39","old_file":"admin\/nodes\/serializers.py","new_file":"admin\/nodes\/serializers.py","old_contents":"import json\n\nfrom website.util.permissions import reduce_permissions\n\nfrom admin.users.serializers import serialize_simple_node\n\n\ndef serialize_node(node):\n embargo = node.embargo\n if embargo is not None:\n embargo = node.embargo.end_date\n\n return {\n 'id': node._id,\n 'title': node.title,\n 'public': node.is_public,\n 'parent': node.parent_id,\n 'root': node.root._id,\n 'is_registration': node.is_registration,\n 'date_created': node.date_created,\n 'withdrawn': node.is_retracted,\n 'embargo': embargo,\n 'contributors': [serialize_simple_user_and_node_permissions(node, user) for user in node.contributors],\n 'children': map(serialize_simple_node, node.nodes),\n 'deleted': node.is_deleted,\n 'pending_registration': node.is_pending_registration,\n 'creator': node.creator._id,\n 'spam_status': node.spam_status,\n 'spam_pro_tip': node.spam_pro_tip,\n 'spam_data': json.dumps(node.spam_data, indent=4),\n 'is_public': node.is_public,\n }\n\n\ndef serialize_simple_user_and_node_permissions(node, user):\n return {\n 'id': user._id,\n 'name': user.fullname,\n 'permission': reduce_permissions(node.get_permissions(user))\n }\n","new_contents":"import json\n\nfrom website.util.permissions import reduce_permissions\n\nfrom admin.users.serializers import serialize_simple_node\n\n\ndef serialize_node(node):\n embargo = node.embargo\n if embargo is not None:\n embargo = node.embargo.end_date\n\n return {\n 'id': node._id,\n 'title': node.title,\n 'public': node.is_public,\n 'parent': node.parent_id,\n 'root': node.root._id,\n 'is_registration': node.is_registration,\n 'date_created': node.date_created,\n 'withdrawn': node.is_retracted,\n 'embargo': embargo,\n 'contributors': [serialize_simple_user_and_node_permissions(node, user) for user in node.contributors],\n 'children': map(serialize_simple_node, node.nodes),\n 'deleted': node.is_deleted,\n 'pending_registration': node.is_pending_registration,\n 'registered_date': node.registered_date,\n 'creator': node.creator._id,\n 'spam_status': node.spam_status,\n 'spam_pro_tip': node.spam_pro_tip,\n 'spam_data': json.dumps(node.spam_data, indent=4),\n 'is_public': node.is_public,\n }\n\n\ndef serialize_simple_user_and_node_permissions(node, user):\n return {\n 'id': user._id,\n 'name': user.fullname,\n 'permission': reduce_permissions(node.get_permissions(user))\n }\n","subject":"Add date_registered to node serializer","message":"Add date_registered to node serializer\n\n[#OSF-7230]\n","lang":"Python","license":"apache-2.0","repos":"mattclark\/osf.io,laurenrevere\/osf.io,brianjgeiger\/osf.io,saradbowman\/osf.io,mattclark\/osf.io,caseyrollins\/osf.io,chennan47\/osf.io,adlius\/osf.io,leb2dg\/osf.io,Johnetordoff\/osf.io,cslzchen\/osf.io,brianjgeiger\/osf.io,hmoco\/osf.io,CenterForOpenScience\/osf.io,adlius\/osf.io,chennan47\/osf.io,hmoco\/osf.io,caneruguz\/osf.io,mfraezz\/osf.io,caneruguz\/osf.io,cslzchen\/osf.io,sloria\/osf.io,caneruguz\/osf.io,felliott\/osf.io,Nesiehr\/osf.io,icereval\/osf.io,mattclark\/osf.io,binoculars\/osf.io,aaxelb\/osf.io,cwisecarver\/osf.io,cwisecarver\/osf.io,leb2dg\/osf.io,Johnetordoff\/osf.io,HalcyonChimera\/osf.io,erinspace\/osf.io,icereval\/osf.io,sloria\/osf.io,chennan47\/osf.io,pattisdr\/osf.io,HalcyonChimera\/osf.io,Nesiehr\/osf.io,chrisseto\/osf.io,TomBaxter\/osf.io,CenterForOpenScience\/osf.io,leb2dg\/osf.io,brianjgeiger\/osf.io,baylee-d\/osf.io,erinspace\/osf.io,caseyrollins\/osf.io,HalcyonChimera\/osf.io,CenterForOpenScience\/osf.io,pattisdr\/osf.io,aaxelb\/osf.io,binoculars\/osf.io,crcresearch\/osf.io,felliott\/osf.io,cwisecarver\/osf.io,Nesiehr\/osf.io,TomBaxter\/osf.io,baylee-d\/osf.io,caneruguz\/osf.io,caseyrollins\/osf.io,adlius\/osf.io,chrisseto\/osf.io,binoculars\/osf.io,sloria\/osf.io,HalcyonChimera\/osf.io,Johnetordoff\/osf.io,leb2dg\/osf.io,laurenrevere\/osf.io,felliott\/osf.io,mfraezz\/osf.io,cslzchen\/osf.io,hmoco\/osf.io,Nesiehr\/osf.io,mfraezz\/osf.io,crcresearch\/osf.io,aaxelb\/osf.io,chrisseto\/osf.io,crcresearch\/osf.io,cwisecarver\/osf.io,cslzchen\/osf.io,icereval\/osf.io,felliott\/osf.io,adlius\/osf.io,hmoco\/osf.io,CenterForOpenScience\/osf.io,baylee-d\/osf.io,erinspace\/osf.io,saradbowman\/osf.io,TomBaxter\/osf.io,Johnetordoff\/osf.io,aaxelb\/osf.io,brianjgeiger\/osf.io,mfraezz\/osf.io,chrisseto\/osf.io,laurenrevere\/osf.io,pattisdr\/osf.io"} {"commit":"f625cac0a49bafc96403f5b34c2e138f8d2cfbea","old_file":"dev\/lint.py","new_file":"dev\/lint.py","old_contents":"# coding: utf-8\nfrom __future__ import unicode_literals, division, absolute_import, print_function\n\nimport os\n\nfrom flake8.engine import get_style_guide\n\n\ncur_dir = os.path.dirname(__file__)\nconfig_file = os.path.join(cur_dir, '..', 'tox.ini')\n\n\ndef run():\n \"\"\"\n Runs flake8 lint\n\n :return:\n A bool - if flake8 did not find any errors\n \"\"\"\n\n print('Running flake8')\n\n flake8_style = get_style_guide(config_file=config_file)\n\n paths = []\n for root, _, filenames in os.walk('asn1crypto'):\n for filename in filenames:\n if not filename.endswith('.py'):\n continue\n paths.append(os.path.join(root, filename))\n report = flake8_style.check_files(paths)\n success = report.total_errors == 0\n if success:\n print('OK')\n return success\n","new_contents":"# coding: utf-8\nfrom __future__ import unicode_literals, division, absolute_import, print_function\n\nimport os\n\nimport flake8\nif flake8.__version_info__ < (3,):\n from flake8.engine import get_style_guide\nelse:\n from flake8.api.legacy import get_style_guide\n\n\ncur_dir = os.path.dirname(__file__)\nconfig_file = os.path.join(cur_dir, '..', 'tox.ini')\n\n\ndef run():\n \"\"\"\n Runs flake8 lint\n\n :return:\n A bool - if flake8 did not find any errors\n \"\"\"\n\n print('Running flake8')\n\n flake8_style = get_style_guide(config_file=config_file)\n\n paths = []\n for root, _, filenames in os.walk('asn1crypto'):\n for filename in filenames:\n if not filename.endswith('.py'):\n continue\n paths.append(os.path.join(root, filename))\n report = flake8_style.check_files(paths)\n success = report.total_errors == 0\n if success:\n print('OK')\n return success\n","subject":"Add support for flake8 3.0","message":"Add support for flake8 3.0\n","lang":"Python","license":"mit","repos":"wbond\/asn1crypto"} {"commit":"573718a17e5e2d3fe23b1c8cd128a9b46d6076e6","old_file":"example-theme.py","new_file":"example-theme.py","old_contents":"# Supported 16 color values:\n# 'h0' (color number 0) through 'h15' (color number 15)\n# or\n# 'default' (use the terminal's default foreground),\n# 'black', 'dark red', 'dark green', 'brown', 'dark blue',\n# 'dark magenta', 'dark cyan', 'light gray', 'dark gray',\n# 'light red', 'light green', 'yellow', 'light blue',\n# 'light magenta', 'light cyan', 'white'\n#\n# Supported 256 color values:\n# 'h0' (color number 0) through 'h255' (color number 255)\n#\n# 256 color chart: http:\/\/en.wikipedia.org\/wiki\/File:Xterm_color_chart.png\n#\n# \"setting_name\": (foreground_color, background_color),\n\npalette.update({\n \"source\": (add_setting(\"black\", \"underline\"), \"dark green\"),\n \"comment\": (\"h250\", \"default\")\n })\n","new_contents":"# Supported 16 color values:\n# 'h0' (color number 0) through 'h15' (color number 15)\n# or\n# 'default' (use the terminal's default foreground),\n# 'black', 'dark red', 'dark green', 'brown', 'dark blue',\n# 'dark magenta', 'dark cyan', 'light gray', 'dark gray',\n# 'light red', 'light green', 'yellow', 'light blue',\n# 'light magenta', 'light cyan', 'white'\n#\n# Supported 256 color values:\n# 'h0' (color number 0) through 'h255' (color number 255)\n#\n# 256 color chart: http:\/\/en.wikipedia.org\/wiki\/File:Xterm_color_chart.png\n#\n# \"setting_name\": (foreground_color, background_color),\n\n# See this URL to see what keys there are:\n# https:\/\/github.com\/inducer\/pudb\/blob\/master\/pudb\/theme.py\n\npalette.update({\n \"source\": (add_setting(\"black\", \"underline\"), \"dark green\"),\n \"comment\": (\"h250\", \"default\")\n })\n","subject":"Add link to defined colors to example theme","message":"Add link to defined colors to example theme\n","lang":"Python","license":"mit","repos":"amigrave\/pudb,albfan\/pudb,amigrave\/pudb,albfan\/pudb"} {"commit":"a45f5ca2e92cfaa4478d632ada3889b81fef5f53","old_file":"features\/urls.py","new_file":"features\/urls.py","old_contents":"from django.conf.urls import url, include\nfrom django.views.generic import TemplateView\nfrom rest_framework import routers\n\nfrom .views import FeatureRequestViewSet, ClientViewSet, ProductAreaViewSet\n\nrouter = routers.DefaultRouter()\n\nrouter.register(r'features', FeatureRequestViewSet)\nrouter.register(r'client', ClientViewSet)\nrouter.register(r'productarea', ProductAreaViewSet)\n\nurlpatterns = [\n url(r'^', TemplateView.as_view(template_name='features\/index.html')),\n url(r'^api\/', include(router.urls)),\n url(r'api-auth\/', include('rest_framework.urls', namespace='rest_framework')),\n]\n","new_contents":"from django.conf.urls import url, include\nfrom django.views.generic import TemplateView\nfrom rest_framework import routers\n\nfrom .views import FeatureRequestViewSet, ClientViewSet, ProductAreaViewSet\n\nrouter = routers.DefaultRouter()\n\nrouter.register(r'features', FeatureRequestViewSet)\nrouter.register(r'client', ClientViewSet)\nrouter.register(r'productarea', ProductAreaViewSet)\n\nurlpatterns = [\n url(r'^$', TemplateView.as_view(template_name='features\/index.html')),\n url(r'^api\/', include(router.urls)),\n url(r'api-auth\/', include('rest_framework.urls', namespace='rest_framework')),\n]\n","subject":"Index route should only match on '\/'","message":"BUGFIX: Index route should only match on '\/'\n","lang":"Python","license":"mit","repos":"wkevina\/feature-requests-app,wkevina\/feature-requests-app,wkevina\/feature-requests-app"} {"commit":"72c122d8ff580a4c0c5fa4554844c73c657a6581","old_file":"apnsclient\/__init__.py","new_file":"apnsclient\/__init__.py","old_contents":"# Copyright 2013 Getlogic BV, Sardar Yumatov\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n__title__ = 'APNS client'\n__version__ = \"0.1.1\"\n__author__ = \"Sardar Yumatov\"\n__contact__ = \"ja.doma@gmail.com\"\n__license__ = \"Apache 2.0\"\n__homepage__ = \"https:\/\/bitbucket.org\/sardarnl\/apns-client\/\"\n__copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov'\n\n\nfrom apnsclient.apns import *\n\n","new_contents":"# Copyright 2013 Getlogic BV, Sardar Yumatov\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n__title__ = 'APNS client'\n__version__ = \"0.1.5\"\n__author__ = \"Sardar Yumatov\"\n__contact__ = \"ja.doma@gmail.com\"\n__license__ = \"Apache 2.0\"\n__homepage__ = \"https:\/\/bitbucket.org\/sardarnl\/apns-client\/\"\n__copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov'\n\n\nfrom apnsclient.apns import *\n\n","subject":"Adjust the module __version__ to match the version advertised in PyPI.","message":"Adjust the module __version__ to match the version advertised in PyPI.\n\n--HG--\nbranch : intellectronica\/adjust-the-module-__version__-to-match-t-1371450045566\n","lang":"Python","license":"apache-2.0","repos":"marcinkaszynski\/apnsclient"} {"commit":"efd64433fab0cae0aaffbd30864c9271c0627502","old_file":"packages\/fsharp-3.1.py","new_file":"packages\/fsharp-3.1.py","old_contents":"\nclass Fsharp31Package(GitHubTarballPackage):\n\tdef __init__(self):\n\t\tGitHubTarballPackage.__init__(self,\n\t\t\t'fsharp', 'fsharp',\n\t\t\t'3.1.1.31',\n\t\t\t'1f79c0455fb8b5ec816985f922413894ce19359a',\n\t\t\tconfigure = '')\n\t\tself.sources.extend ([\n\t\t\t'fsharp-fix-net45-profile.patch')\n\n\tdef prep(self):\n\t\tPackage.prep (self)\n\n\t\tfor p in range (1, len (self.sources)):\n\t\t\t\tself.sh ('patch -p1 < \"%{sources[' + str (p) + ']}\"')\n\n\n\tdef build(self):\n\t\tself.sh ('autoreconf')\n\t\tself.sh ('.\/configure --prefix=\"%{prefix}\"')\n\t\tself.sh ('make')\n\nFsharp31Package()\n","new_contents":"\nclass Fsharp31Package(GitHubTarballPackage):\n\tdef __init__(self):\n\t\tGitHubTarballPackage.__init__(self,\n\t\t\t'fsharp', 'fsharp',\n\t\t\t'3.1.1.31',\n\t\t\t'1f79c0455fb8b5ec816985f922413894ce19359a',\n\t\t\tconfigure = '')\n\t\tself.sources.extend ([\n\t\t\t'patches\/fsharp-fix-net45-profile.patch'])\n\n\tdef prep(self):\n\t\tPackage.prep (self)\n\n\t\tfor p in range (1, len (self.sources)):\n\t\t\t\tself.sh ('patch -p1 < \"%{sources[' + str (p) + ']}\"')\n\n\n\tdef build(self):\n\t\tself.sh ('autoreconf')\n\t\tself.sh ('.\/configure --prefix=\"%{prefix}\"')\n\t\tself.sh ('make')\n\nFsharp31Package()\n","subject":"Fix the typos, fix the build.","message":"Fix the typos, fix the build.\n","lang":"Python","license":"mit","repos":"mono\/bockbuild,BansheeMediaPlayer\/bockbuild,BansheeMediaPlayer\/bockbuild,BansheeMediaPlayer\/bockbuild,mono\/bockbuild"} {"commit":"b50b7143185131a81e84f0659ff6405317f7d36f","old_file":"resolwe\/flow\/execution_engines\/base.py","new_file":"resolwe\/flow\/execution_engines\/base.py","old_contents":"\"\"\"Workflow execution engines.\"\"\"\nfrom resolwe.flow.engine import BaseEngine\n\n\nclass BaseExecutionEngine(BaseEngine):\n \"\"\"A workflow execution engine.\"\"\"\n\n def evaluate(self, data):\n \"\"\"Return the code needed to compute a given Data object.\"\"\"\n raise NotImplementedError\n\n def get_expression_engine(self, name):\n \"\"\"Return an expression engine by its name.\"\"\"\n return self.manager.get_expression_engine(name)\n\n def get_output_schema(self, process):\n \"\"\"Return any additional output schema for the process.\"\"\"\n return []\n\n def discover_process(self, path):\n \"\"\"Perform process discovery in given path.\n\n This method will be called during process registration and\n should return a list of dictionaries with discovered process\n schemas.\n \"\"\"\n return []\n\n def prepare_runtime(self, runtime_dir, data):\n \"\"\"Prepare runtime directory.\n\n This method should return a dictionary of volume maps, where\n keys are files or directories relative the the runtime directory\n and values are paths under which these should be made available\n to the executing program. All volumes will be read-only.\n \"\"\"\n","new_contents":"\"\"\"Workflow execution engines.\"\"\"\nfrom resolwe.flow.engine import BaseEngine\n\n\nclass BaseExecutionEngine(BaseEngine):\n \"\"\"A workflow execution engine.\"\"\"\n\n def evaluate(self, data):\n \"\"\"Return the code needed to compute a given Data object.\"\"\"\n raise NotImplementedError\n\n def get_expression_engine(self, name):\n \"\"\"Return an expression engine by its name.\"\"\"\n return self.manager.get_expression_engine(name)\n\n def get_output_schema(self, process):\n \"\"\"Return any additional output schema for the process.\"\"\"\n return []\n\n def discover_process(self, path):\n \"\"\"Perform process discovery in given path.\n\n This method will be called during process registration and\n should return a list of dictionaries with discovered process\n schemas.\n \"\"\"\n return []\n\n def prepare_runtime(self, runtime_dir, data):\n \"\"\"Prepare runtime directory.\n\n This method should return a dictionary of volume maps, where\n keys are files or directories relative the the runtime directory\n and values are paths under which these should be made available\n to the executing program. All volumes will be read-only.\n \"\"\"\n return {}\n","subject":"Return empty dictionary instead of None","message":"Return empty dictionary instead of None\n","lang":"Python","license":"apache-2.0","repos":"genialis\/resolwe,genialis\/resolwe"} {"commit":"b62f52a30404901ff3ffa7af90a3f1bdd7d05401","old_file":"project\/hhlcallback\/utils.py","new_file":"project\/hhlcallback\/utils.py","old_contents":"# -*- coding: utf-8 -*-\nimport environ\nenv = environ.Env()\nHOLVI_CNC = False\n\ndef get_holvi_singleton():\n global HOLVI_CNC\n if HOLVI_CNC:\n return HOLVI_CNC\n holvi_pool = env('HOLVI_POOL', default=None)\n holvi_key = env('HOLVI_APIKEY', default=None)\n if not holvi_pool or not holvi_key:\n return False\n import holviapi\n HOLVI_CNC = holviapi.Connection(holvi_pool, holvi_key)\n return HOLVI_CNC\n","new_contents":"# -*- coding: utf-8 -*-\nimport holviapi.utils\n\ndef get_nordea_payment_reference(member_id, number):\n base = member_id + 1000\n return holviapi.utils.int2fin_reference(int(\"%s%s\" % (base, number)))\n","subject":"Remove copy-pasted code, add helper for making legacy reference number for payments","message":"Remove copy-pasted code, add helper for making legacy reference number for payments\n","lang":"Python","license":"mit","repos":"HelsinkiHacklab\/asylum,HelsinkiHacklab\/asylum,HelsinkiHacklab\/asylum,HelsinkiHacklab\/asylum"} {"commit":"6f30aed2b5f157bb22c8761a92464302ec5d8911","old_file":"DebianChangesBot\/utils\/__init__.py","new_file":"DebianChangesBot\/utils\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\n\nimport email.quoprimime\n\ndef quoted_printable(val):\n try:\n if type(val) is str:\n return email.quoprimime.header_decode(val)\n else:\n return unicode(email.quoprimime.header_decode(str(val)), 'utf-8')\n\n except Exception, e:\n # We ignore errors here. Most of these originate from a spam\n # report adding a synopsis of a message with broken encodings.\n pass\n\n return val\n\nfrom parse_mail import parse_mail\n","new_contents":"# -*- coding: utf-8 -*-\n\nimport email\nimport re\n\ndef header_decode(s):\n def unquote_match(match):\n s = match.group(0)\n return chr(int(s[1:3], 16))\n\n s = s.replace('_', ' ')\n return re.sub(r'=\\w{2}', unquote_match, s)\n\ndef quoted_printable(val):\n try:\n if type(val) is str:\n save = header_decode(val)\n val = ' '.join([chunk.decode(encoding or 'ascii', 'replace') for chunk, encoding in\n email.Header.decode_header(val)])\n\n if len(val) > len(save):\n val = unicode(save, 'utf-8', 'replace')\n\n else:\n return unicode(email.quoprimime.header_decode(str(val)), 'utf-8', 'replace')\n\n except Exception, e:\n # We ignore errors here. Most of these originate from a spam\n # report adding a synopsis of a message with broken encodings.\n pass\n\n return val\n\nfrom parse_mail import parse_mail\n","subject":"Update header_decode to handle bare and non-bare quoted-printable chars","message":"Update header_decode to handle bare and non-bare quoted-printable chars\n\nSigned-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>\n","lang":"Python","license":"agpl-3.0","repos":"xtaran\/debian-devel-changes-bot,xtaran\/debian-devel-changes-bot,lamby\/debian-devel-changes-bot,lamby\/debian-devel-changes-bot,sebastinas\/debian-devel-changes-bot,lamby\/debian-devel-changes-bot"} {"commit":"b5b17c5152e969ed4e629a5df8dd296cde164f9b","old_file":"polymer_states\/__init__.py","new_file":"polymer_states\/__init__.py","old_contents":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.","new_contents":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n# Link states\nUP, DOWN = (0, 1), (0, -1)\nLEFT, RIGHT = (-1, 0), (1, 0)\nSLACK = (0, 0)","subject":"Add link states to polymer_states","message":"Add link states to polymer_states\n","lang":"Python","license":"mpl-2.0","repos":"szabba\/applied-sims"} {"commit":"656c0a9b91ee6f6f3f9811b16ab75dc8003402ad","old_file":"altair\/examples\/line_chart_with_generator.py","new_file":"altair\/examples\/line_chart_with_generator.py","old_contents":"\"\"\"\nLine Chart with Sequence Generator\n----------------------------------\nThis examples shows how to create multiple lines using the sequence generator.\n\"\"\"\n# category: line charts\n\nimport altair as alt\n\nsource = alt.sequence(start=0, stop=12.7, step=0.1, as_='x')\n\nalt.Chart(source).mark_line().transform_calculate(\n sin='sin(datum.x)'\n).transform_calculate(\n cos='cos(datum.x)'\n).transform_fold(\n ['sin', 'cos']\n).encode(\n x='x:Q', \n y='value:Q', \n color='key:N'\n)\n","new_contents":"\"\"\"\nLine Chart with Sequence Generator\n----------------------------------\nThis examples shows how to create multiple lines using the sequence generator.\n\"\"\"\n# category: line charts\n\nimport altair as alt\n\nsource = alt.sequence(start=0, stop=12.7, step=0.1, as_='x')\n\nalt.Chart(source).mark_line().transform_calculate(\n sin='sin(datum.x)',\n cos='cos(datum.x)'\n).transform_fold(\n ['sin', 'cos']\n).encode(\n x='x:Q', \n y='value:Q', \n color='key:N'\n)\n","subject":"Modify generator example to use single calculation transform","message":"DOC: Modify generator example to use single calculation transform\n","lang":"Python","license":"bsd-3-clause","repos":"jakevdp\/altair,altair-viz\/altair"} {"commit":"4d1dc36e7426a13906dd1b75eda2c8bff94c88b4","old_file":"pwm_server\/__init__.py","new_file":"pwm_server\/__init__.py","old_contents":"from flask import Flask\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom logging import getLogger\nimport os\nimport pwm\n\ndb = SQLAlchemy()\n_logger = getLogger('pwm_server')\n\nclass PWMApp(Flask):\n\n def bootstrap(self):\n \"\"\" Initialize database tables for both pwm_server and pwm. \"\"\"\n from .models import Certificate\n with self.app_context():\n db.metadata.create_all(db.engine, tables=[Certificate.__table__, pwm.Domain.__table__])\n\n\ndef create_app(config_file=None):\n app = PWMApp(__name__)\n app.config['WTF_CSRF_ENABLED'] = False\n\n if config_file:\n config_path = os.path.join(os.getcwd(), config_file)\n _logger.debug('Loading config from %s', config_path)\n app.config.from_pyfile(config_path)\n else:\n _logger.debug('Loading config from envvar, file %s', os.environ['PWM_SERVER_CONFIG_FILE'])\n app.config.from_envvar('PWM_SERVER_CONFIG_FILE')\n\n from . import views\n app.register_blueprint(views.mod)\n\n db.init_app(app)\n\n return app\n","new_contents":"from flask import Flask\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom logging import getLogger\nimport os\nimport pwm\n\ndb = SQLAlchemy()\n_logger = getLogger('pwm_server')\n\nclass PWMApp(Flask):\n\n def bootstrap(self):\n \"\"\" Initialize database tables for both pwm_server and pwm. \"\"\"\n from .models import Certificate\n with self.app_context():\n db.metadata.create_all(db.engine, tables=[Certificate.__table__, pwm.Domain.__table__])\n\n\ndef create_app(config_file=None):\n app = PWMApp(__name__)\n app.config['WTF_CSRF_ENABLED'] = False\n\n if config_file:\n config_path = os.path.join(os.getcwd(), config_file)\n _logger.debug('Loading config from %s', config_path)\n else:\n _logger.debug('Loading config from envvar, file %s', os.environ['PWM_SERVER_CONFIG_FILE'])\n config_path = os.path.join(os.getcwd(), os.environ['PWM_SERVER_CONFIG_FILE'])\n app.config.from_pyfile(config_path)\n\n from . import views\n app.register_blueprint(views.mod)\n\n db.init_app(app)\n\n return app\n","subject":"Resolve config from envvar relative to cwd","message":"Resolve config from envvar relative to cwd\n","lang":"Python","license":"mit","repos":"thusoy\/pwm-server,thusoy\/pwm-server"} {"commit":"7319ac2eb5d31b14c731371a82102c90d8ec3979","old_file":"tests\/test_reflection_views.py","new_file":"tests\/test_reflection_views.py","old_contents":"from sqlalchemy import MetaData, Table, inspect\nfrom sqlalchemy.schema import CreateTable\n\nfrom rs_sqla_test_utils.utils import clean, compile_query\n\n\ndef table_to_ddl(engine, table):\n return str(CreateTable(table)\n .compile(engine))\n\n\ndef test_view_reflection(redshift_engine):\n table_ddl = \"CREATE TABLE my_table (col1 INTEGER, col2 INTEGER)\"\n view_query = \"SELECT my_table.col1, my_table.col2 FROM my_table\"\n view_ddl = \"CREATE VIEW my_view AS %s\" % view_query\n conn = redshift_engine.connect()\n conn.execute(table_ddl)\n conn.execute(view_ddl)\n insp = inspect(redshift_engine)\n view_definition = insp.get_view_definition('my_view')\n assert(clean(compile_query(view_definition)) == clean(view_query))\n view = Table('my_view', MetaData(),\n autoload=True, autoload_with=redshift_engine)\n assert(len(view.columns) == 2)\n","new_contents":"from sqlalchemy import MetaData, Table, inspect\nfrom sqlalchemy.schema import CreateTable\n\nfrom rs_sqla_test_utils.utils import clean, compile_query\n\n\ndef table_to_ddl(engine, table):\n return str(CreateTable(table)\n .compile(engine))\n\n\ndef test_view_reflection(redshift_engine):\n table_ddl = \"CREATE TABLE my_table (col1 INTEGER, col2 INTEGER)\"\n view_query = \"SELECT my_table.col1, my_table.col2 FROM my_table\"\n view_ddl = \"CREATE VIEW my_view AS %s\" % view_query\n conn = redshift_engine.connect()\n conn.execute(table_ddl)\n conn.execute(view_ddl)\n insp = inspect(redshift_engine)\n view_definition = insp.get_view_definition('my_view')\n assert(clean(compile_query(view_definition)) == clean(view_query))\n view = Table('my_view', MetaData(),\n autoload=True, autoload_with=redshift_engine)\n assert(len(view.columns) == 2)\n\n\ndef test_late_binding_view_reflection(redshift_engine):\n table_ddl = \"CREATE TABLE my_table (col1 INTEGER, col2 INTEGER)\"\n view_query = \"SELECT my_table.col1, my_table.col2 FROM public.my_table\"\n view_ddl = (\"CREATE VIEW my_late_view AS \"\n \"%s WITH NO SCHEMA BINDING\" % view_query)\n conn = redshift_engine.connect()\n conn.execute(table_ddl)\n conn.execute(view_ddl)\n insp = inspect(redshift_engine)\n view_definition = insp.get_view_definition('my_late_view')\n\n # For some reason, Redshift returns the entire DDL for late binding views.\n assert(clean(compile_query(view_definition)) == clean(view_ddl))\n view = Table('my_late_view', MetaData(),\n autoload=True, autoload_with=redshift_engine)\n assert(len(view.columns) == 2)\n","subject":"Add test for late-binding views","message":"Add test for late-binding views\n","lang":"Python","license":"mit","repos":"sqlalchemy-redshift\/sqlalchemy-redshift,sqlalchemy-redshift\/sqlalchemy-redshift,graingert\/redshift_sqlalchemy"} {"commit":"e051c915d72b76a189c16de6ff82bcebdab9f881","old_file":"caffe2\/python\/layers\/__init__.py","new_file":"caffe2\/python\/layers\/__init__.py","old_contents":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom importlib import import_module\nimport pkgutil\nimport sys\nimport inspect\nfrom . import layers\n\n\ndef import_recursive(package, clsmembers):\n \"\"\"\n Takes a package and imports all modules underneath it\n \"\"\"\n\n pkg_dir = package.__path__\n module_location = package.__name__\n for (_module_loader, name, ispkg) in pkgutil.iter_modules(pkg_dir):\n module_name = \"{}.{}\".format(module_location, name) # Module\/package\n module = import_module(module_name)\n clsmembers += [cls[1] for cls in inspect.getmembers(module, inspect.isclass)]\n if ispkg:\n import_recursive(module, clsmembers)\n\n\nclsmembers = []\nimport_recursive(sys.modules[__name__], clsmembers)\n\nfor cls in clsmembers:\n if issubclass(cls, layers.ModelLayer) and cls is not layers.ModelLayer:\n layers.register_layer(cls.__name__, cls)\n","new_contents":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom importlib import import_module\nimport pkgutil\nimport sys\nfrom . import layers\n\n\ndef import_recursive(package):\n \"\"\"\n Takes a package and imports all modules underneath it\n \"\"\"\n\n pkg_dir = package.__path__\n module_location = package.__name__\n for (_module_loader, name, ispkg) in pkgutil.iter_modules(pkg_dir):\n module_name = \"{}.{}\".format(module_location, name) # Module\/package\n module = import_module(module_name)\n if ispkg:\n import_recursive(module)\n\n\ndef find_subclasses_recursively(base_cls, sub_cls):\n cur_sub_cls = base_cls.__subclasses__()\n sub_cls.update(cur_sub_cls)\n for cls in cur_sub_cls:\n find_subclasses_recursively(cls, sub_cls)\n\n\nimport_recursive(sys.modules[__name__])\n\nmodel_layer_subcls = set()\nfind_subclasses_recursively(layers.ModelLayer, model_layer_subcls)\n\nfor cls in list(model_layer_subcls):\n layers.register_layer(cls.__name__, cls)\n","subject":"Allow to import subclasses of layers","message":"Allow to import subclasses of layers\n\nSummary:\nWe want it to be able to register children of layers who\nare not direct children of ModelLayer.\nThis requires us to find subclasses of ModelLayer recursively.\n\nReviewed By: kittipatv, kennyhorror\n\nDifferential Revision: D5397120\n\nfbshipit-source-id: cb1e03d72e3bedb960b1b865877a76e413218a71\n","lang":"Python","license":"apache-2.0","repos":"Yangqing\/caffe2,xzturn\/caffe2,sf-wind\/caffe2,pietern\/caffe2,pietern\/caffe2,davinwang\/caffe2,sf-wind\/caffe2,davinwang\/caffe2,sf-wind\/caffe2,caffe2\/caffe2,Yangqing\/caffe2,bwasti\/caffe2,Yangqing\/caffe2,bwasti\/caffe2,xzturn\/caffe2,pietern\/caffe2,davinwang\/caffe2,bwasti\/caffe2,bwasti\/caffe2,sf-wind\/caffe2,sf-wind\/caffe2,bwasti\/caffe2,pietern\/caffe2,Yangqing\/caffe2,davinwang\/caffe2,xzturn\/caffe2,Yangqing\/caffe2,xzturn\/caffe2,davinwang\/caffe2,pietern\/caffe2,xzturn\/caffe2"} {"commit":"b99770a7c55cd6951df872793a54bfa260b145f9","old_file":"basics\/test\/module-test.py","new_file":"basics\/test\/module-test.py","old_contents":"from unittest import TestCase\n\nfrom basics import BaseCharacter\nfrom basics import BaseAttachment\n\n\nclass ModuleTest(TestCase):\n\n def test_character_attach_attachment(self):\n character = BaseCharacter().save()\n attachment = BaseAttachment().save()\n\n # Attachment should not be among the character's attachments\n self.assertNotIn(attachment.id, character.attachments())\n\n # Attach the attachment\n character.attach(attachment)\n\n # Attachment should be among the character's attachments\n self.assertIn(attachment.id, character.attachments())\n\n def test_container_containment(self):\n self.fail(\"Test unwritten\")\n","new_contents":"from unittest import TestCase\n\nfrom basics import BaseCharacter\nfrom basics import BaseAttachment\nfrom basics import BaseThing\n\n\nclass ModuleTest(TestCase):\n\n def test_character_attach_attachment(self):\n character = BaseCharacter().save()\n attachment = BaseAttachment().save()\n\n # Attachment should not be among the character's attachments\n self.assertNotIn(attachment.id, character.attachments())\n\n # Attach the attachment\n character.attach(attachment)\n\n # Attachment should be among the character's attachments\n self.assertIn(attachment.id, character.attachments())\n\n def test_container_containment(self):\n thing_a = BaseThing().save()\n thing_b = BaseThing().save()\n\n # thing_b should not be among thing_a's stuff\n self.assertNotIn(thing_b.id, thing_a.stuff())\n\n # thing_b aint contained\n self.assertIsNone(thing_b.container())\n\n # Move thing_b into thing_a\n thing_b.move_to(thing_a)\n\n # thing_b should be among thing_a's stuff\n self.assertIn(thing_b.id, thing_a.stuff())\n\n # thing_b is contained by thing_a\n self.assertEqual(thing_a, thing_b.container())\n\n","subject":"Write test for container containment.","message":"Write test for container containment.\n","lang":"Python","license":"apache-2.0","repos":"JASchilz\/RoverMUD"} {"commit":"b506b6796a8ed9e778f69ddc7718a8ea3b0f9e7a","old_file":"flynn\/__init__.py","new_file":"flynn\/__init__.py","old_contents":"# coding: utf-8\n\nimport flynn.decoder\nimport flynn.encoder\n\ndef dump(obj, fp):\n\treturn flynn.encoder.encode(fp, obj)\n\ndef dumps(obj):\n\treturn flynn.encoder.encode_str(obj)\n\ndef dumph(obj):\n\treturn \"\".join(hex(n)[2:].rjust(2, \"0\") for n in dumps(obj))\n\ndef load(s):\n\treturn flynn.decoder.decode(s)\n\ndef loads(s):\n\treturn flynn.decoder.decode(s)\n\ndef loadh(s):\n\treturn flynn.decoder.decode(s)\n\n","new_contents":"# coding: utf-8\n\nimport base64\n\nimport flynn.decoder\nimport flynn.encoder\n\n__all__ = [\n\t\"decoder\",\n\t\"encoder\",\n\t\"dump\",\n\t\"dumps\",\n\t\"dumph\",\n\t\"load\",\n\t\"loads\",\n\t\"loadh\"\n]\n\ndef dump(obj, fp):\n\treturn flynn.encoder.encode(fp, obj)\n\ndef dumps(obj):\n\treturn flynn.encoder.encode_str(obj)\n\ndef dumph(obj):\n\treturn base64.b16encode(dumps(obj)).decode(\"utf-8\")\n\ndef load(s):\n\treturn flynn.decoder.decode(s)\n\ndef loads(s):\n\treturn flynn.decoder.decode(s)\n\ndef loadh(s):\n\treturn flynn.decoder.decode(s)\n\n","subject":"Use base64 module to convert between bytes and base16 string","message":"Use base64 module to convert between bytes and base16 string\n","lang":"Python","license":"mit","repos":"fritz0705\/flynn"} {"commit":"7b71425a4434ac2544340d651f52c0d87ff37132","old_file":"web\/impact\/impact\/v1\/helpers\/refund_code_helper.py","new_file":"web\/impact\/impact\/v1\/helpers\/refund_code_helper.py","old_contents":"# MIT License\n# Copyright (c) 2017 MassChallenge, Inc.\n\nfrom impact.models import RefundCode\nfrom impact.v1.helpers.model_helper import(\n INTEGER_ARRAY_FIELD,\n INTEGER_FIELD,\n ModelHelper,\n PK_FIELD,\n STRING_FIELD,\n)\n\n\nPROGRAMS_FIELD = {\n \"json-schema\": {\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n },\n \"POST\": {\"required\": False},\n \"PATCH\": {\"required\": False},\n}\n\nREFUND_CODE_FIELDS = {\n \"id\": PK_FIELD,\n \"issued_to\": INTEGER_FIELD,\n \"created_at\": STRING_FIELD,\n \"unique_code\": STRING_FIELD,\n \"discount\": INTEGER_FIELD,\n \"maximum_uses\": INTEGER_FIELD,\n \"programs\": INTEGER_ARRAY_FIELD,\n}\n\n\nclass RefundCodeHelper(ModelHelper):\n model = RefundCode\n\n @classmethod\n def fields(self):\n return REFUND_CODE_FIELDS\n\n @property\n def issued_to(self):\n return self.field_pk(\"issued_to\")\n\n @property\n def programs(self):\n if hasattr(self.subject, \"programs\"):\n programs = self.subject.programs\n if programs:\n return [program.pk for program in programs.all()]\n\n","new_contents":"# MIT License\n# Copyright (c) 2017 MassChallenge, Inc.\n\nfrom impact.models import RefundCode\nfrom impact.v1.helpers.model_helper import(\n BOOLEAN_FIELD,\n INTEGER_ARRAY_FIELD,\n INTEGER_FIELD,\n ModelHelper,\n PK_FIELD,\n STRING_FIELD,\n)\n\n\nPROGRAMS_FIELD = {\n \"json-schema\": {\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n },\n \"POST\": {\"required\": False},\n \"PATCH\": {\"required\": False},\n}\n\nREFUND_CODE_FIELDS = {\n \"id\": PK_FIELD,\n \"issued_to\": INTEGER_FIELD,\n \"created_at\": STRING_FIELD,\n \"unique_code\": STRING_FIELD,\n \"discount\": INTEGER_FIELD,\n \"maximum_uses\": INTEGER_FIELD,\n \"programs\": INTEGER_ARRAY_FIELD,\n \"notes\": STRING_FIELD,\n \"internal\": BOOLEAN_FIELD,\n}\n\n\nclass RefundCodeHelper(ModelHelper):\n model = RefundCode\n\n @classmethod\n def fields(self):\n return REFUND_CODE_FIELDS\n\n @property\n def issued_to(self):\n return self.field_pk(\"issued_to\")\n\n @property\n def programs(self):\n if hasattr(self.subject, \"programs\"):\n programs = self.subject.programs\n if programs:\n return [program.pk for program in programs.all()]\n\n","subject":"Add Notes and Internal Fields","message":"[AC-5291] Add Notes and Internal Fields\n","lang":"Python","license":"mit","repos":"masschallenge\/impact-api,masschallenge\/impact-api,masschallenge\/impact-api,masschallenge\/impact-api"} {"commit":"c1f71014218d9b6cdb6c45d9d1ce0cc0424f70f8","old_file":"doc\/pyplots\/stylesheet_gallery.py","new_file":"doc\/pyplots\/stylesheet_gallery.py","old_contents":"# -*- coding: utf-8 -*-\n\"\"\"Generate a gallery to compare all available typhon styles.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom typhon.plots import styles\n\n\ndef simple_plot(stylename):\n \"\"\"Generate a simple plot using a given matplotlib style.\"\"\"\n x = np.linspace(0, np.pi, 20)\n\n fig, ax = plt.subplots()\n for s in np.linspace(0, np.pi \/ 2, 12):\n ax.plot(x, np.sin(x+s),\n label=r'$\\Delta\\omega = {:.2f}$'.format(s),\n marker='.',\n )\n ax.set_ylabel('y-axis')\n ax.set_xlabel('x-axis')\n ax.set_title(stylename)\n ax.grid()\n ax.legend()\n\n\n# Create plot using default styles.\nsimple_plot('matplotlib 2.0')\n\n# Create a plot for each available typhon style.\nfor style_name in styles.available:\n with plt.style.context(styles(style_name)):\n simple_plot(style_name)\n\nplt.show()\n","new_contents":"# -*- coding: utf-8 -*-\n\"\"\"Generate a gallery to compare all available typhon styles.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom typhon.plots import styles\n\n\ndef simple_plot(stylename):\n \"\"\"Generate a simple plot using a given matplotlib style.\"\"\"\n if stylename == 'typhon-dark':\n # TODO: Sphinx build is broken for non-white figure facecolor.\n return\n\n x = np.linspace(0, np.pi, 20)\n\n fig, ax = plt.subplots()\n for s in np.linspace(0, np.pi \/ 2, 12):\n ax.plot(x, np.sin(x+s),\n label=r'$\\Delta\\omega = {:.2f}$'.format(s),\n marker='.',\n )\n ax.set_ylabel('y-axis')\n ax.set_xlabel('x-axis')\n ax.set_title(stylename)\n ax.grid()\n ax.legend()\n\n\n# Create plot using default styles.\nsimple_plot('matplotlib 2.0')\n\n# Create a plot for each available typhon style.\nfor style_name in styles.available:\n with plt.style.context(styles(style_name)):\n simple_plot(style_name)\n\nplt.show()\n","subject":"Exclude dark-colored theme from stylesheet gallery.","message":"Exclude dark-colored theme from stylesheet gallery.\n","lang":"Python","license":"mit","repos":"atmtools\/typhon,atmtools\/typhon"} {"commit":"41fbd5b92ac04c3a4ca0e33204bb08b12a533052","old_file":"ibmcnx\/doc\/DataSources.py","new_file":"ibmcnx\/doc\/DataSources.py","old_contents":"######\n# Check ExId (GUID) by Email through JDBC\n#\n# Author: Christoph Stoettner\n# Mail: christoph.stoettner@stoeps.de\n# Documentation: http:\/\/scripting101.stoeps.de\n#\n# Version: 2.0\n# Date: 2014-06-04\n#\n# License: Apache 2.0\n#\n# Check ExId of a User in all Connections Applications\n\nimport ibmcnx.functions\n\ncell = AdminConfig.getid( '\"\/Cell:' + AdminControl.getCell() + '\/\"' )\ndbs = AdminConfig.list( 'DataSource', cell )\n\nfor db in dbs:\n t1 = ibmcnx.functions.getDSId( db )\n AdminConfig.list( t1 )","new_contents":"######\n# Check ExId (GUID) by Email through JDBC\n#\n# Author: Christoph Stoettner\n# Mail: christoph.stoettner@stoeps.de\n# Documentation: http:\/\/scripting101.stoeps.de\n#\n# Version: 2.0\n# Date: 2014-06-04\n#\n# License: Apache 2.0\n#\n# Check ExId of a User in all Connections Applications\n\nimport ibmcnx.functions\n\ncell = \"'\/Cell:\" + AdminControl.getCell() + \"\/'\"\nprint cell\ncellid = AdminConfig.getid( )\ndbs = AdminConfig.list( 'DataSource', cellid )\n\nfor db in dbs:\n t1 = ibmcnx.functions.getDSId( db )\n AdminConfig.list( t1 )","subject":"Create script to save documentation to a file","message":"4: Create script to save documentation to a file \n\nTask-Url: http:\/\/github.com\/stoeps13\/ibmcnx2\/issues\/issue\/4","lang":"Python","license":"apache-2.0","repos":"stoeps13\/ibmcnx2,stoeps13\/ibmcnx2"} {"commit":"4a04fb836afe157ddd3d929a91305d00a6c11993","old_file":"main\/modelx.py","new_file":"main\/modelx.py","old_contents":"# -*- coding: utf-8 -*-\n\nfrom google.appengine.ext import ndb\nimport md5\nimport util\n\n\nclass BaseX(object):\n @classmethod\n def retrieve_one_by(cls, name, value):\n cls_db_list = cls.query(getattr(cls, name) == value).fetch(1)\n if cls_db_list:\n return cls_db_list[0]\n return None\n\n\nclass ConfigX(object):\n @classmethod\n def get_master_db(cls):\n return cls.get_or_insert('master')\n\n\nclass UserX(object):\n @property\n def avatar_url(self):\n return 'http:\/\/www.gravatar.com\/avatar\/%s?d=identicon&r=x' % (\n md5.new(self.email or self.name).hexdigest().lower()\n )\n","new_contents":"# -*- coding: utf-8 -*-\n\nfrom google.appengine.ext import ndb\nimport md5\nimport util\n\n\nclass BaseX(object):\n @classmethod\n def retrieve_one_by(cls, name, value):\n cls_db_list = cls.query(getattr(cls, name) == value).fetch(1)\n if cls_db_list:\n return cls_db_list[0]\n return None\n\n\nclass ConfigX(object):\n @classmethod\n def get_master_db(cls):\n return cls.get_or_insert('master')\n\n\nclass UserX(object):\n @property\n def avatar_url(self):\n return 'http:\/\/www.gravatar.com\/avatar\/%s?d=identicon&r=x' % (\n md5.new((self.email or self.name).encode('utf-8')).hexdigest().lower()\n )\n","subject":"Fix generate md5 from unicode name and international email (http:\/\/en.wikipedia.org\/wiki\/International_email).","message":"Fix generate md5 from unicode name and international email (http:\/\/en.wikipedia.org\/wiki\/International_email).\n","lang":"Python","license":"mit","repos":"antotodd\/lab5,gae-init\/gae-init-debug,gae-init\/gae-init-babel,lipis\/life-line,lipis\/meet-notes,lipis\/meet-notes,mdxs\/gae-init,NeftaliYagua\/gae-init,lovesoft\/gae-init,wilfriedE\/gae-init,gae-init\/gae-init,tonyin\/optionstg,wodore\/wodore-gae,dhstack\/gae-init,jakedotio\/gae-init,wodore\/wodore-gae,lipis\/github-stats,lipis\/the-smallest-creature,gae-init\/gae-init-docs,d4rr3ll\/gae-init-docker,topless\/gae-init-upload,dhstack\/gae-init,gae-init\/gae-init-docs,gmist\/alice-box,vanessa-bell\/hd-kiosk-v2,georgekis\/salary,gmist\/nashi-5studio,gmist\/my-gae-init-auth,tkstman\/lab5,mdxs\/gae-init-babel,lipis\/meet-notes,jakedotio\/gae-init,gmist\/1businka2,georgekis\/salary,gmist\/1businka2,lipis\/hurry-app,tiberiucorbu\/av-website,gae-init\/gae-init-babel,wodore\/wodore-gae,gae-init\/gae-init,carylF\/lab5,JoeyCodinja\/INFO3180LAB3,gmist\/ctm-5studio,gae-init\/gae-init-debug,gae-init\/gae-init-debug,gmist\/my-gae-init,vanessa-bell\/hd-kiosk-v2,gae-init\/gae-init-upload,jaja14\/lab5,gmist\/five-studio2,georgekis\/salary,chineyting\/lab5-Info3180,michals\/hurry-app,wilfriedE\/gae-init,gae-init\/gae-init-babel,Kingclove\/lab5info3180,topless\/gae-init,vanessa-bell\/hd-kiosk-v2,mdxs\/gae-init-babel,CLOUGH\/info3180-lab5,d4rr3ll\/gae-init-docker,gmist\/five-studio2,gmist\/ctm-5studio,topless\/gae-init,lipis\/guestbook,michals\/hurry-app,gmist\/my-gae-init,lipis\/gae-init,gae-init\/gae-init-debug,gmist\/five-studio2,lipis\/github-stats,lipis\/github-stats,lipis\/electron-crash-reporter,NeftaliYagua\/gae-init,gmist\/five-studio2,topless\/gae-init-upload,tkstman\/lab5,gmist\/1businka2,dhstack\/gae-init,chineyting\/lab5-Info3180,gae-init\/gae-init,vanessa-bell\/hd-kiosk-v2,gmist\/ctm-5studio,gmist\/alice-box,mdxs\/gae-init,gae-init\/gae-init-upload,mdxs\/gae-init-docs,mdxs\/gae-init,tiberiucorbu\/av-website,tiberiucorbu\/av-website,jaja14\/lab5,gmist\/nashi-5studio,lipis\/the-smallest-creature,jakedotio\/gae-init,topless\/gae-init-upload,gmist\/nashi-5studio,lipis\/gae-init,gmist\/fix-5studio,wodore\/wodore-gae,mdxs\/gae-init,lipis\/hurry-app,mdxs\/gae-init-babel,lovesoft\/gae-init,lipis\/life-line,CLOUGH\/info3180-lab5,terradigital\/gae-init,lipis\/the-smallest-creature,carylF\/lab5,Kingclove\/lab5info3180,gae-init\/gae-init,gae-init\/gae-init-docs,gmist\/my-gae-init,gmist\/fix-5studio,gae-init\/phonebook,JoeyCodinja\/INFO3180LAB3,JoeyCodinja\/INFO3180LAB3,gmist\/my-gae-init,lipis\/gae-init,d4rr3ll\/gae-init-docker,gae-init\/gae-init-docs,gae-init\/gae-init-upload,terradigital\/gae-init,lipis\/electron-crash-reporter,gae-init\/gae-init-upload,lipis\/electron-crash-reporter,jakedotio\/gae-init,NeftaliYagua\/gae-init,topless\/gae-init,JoeyCodinja\/INFO3180LAB3,gmist\/fix-5studio,antotodd\/lab5,lipis\/github-stats,lovesoft\/gae-init,gae-init\/gae-init-babel,lipis\/life-line,tonyin\/optionstg,wilfriedE\/gae-init,d4rr3ll\/gae-init-docker,michals\/hurry-app,lipis\/gae-init,gmist\/fix-5studio,lipis\/hurry-app,terradigital\/gae-init,topless\/gae-init,gmist\/ctm-5studio"} {"commit":"07c3c7e00a4c2733a3233ff483797c798451a87f","old_file":"apps\/predict\/mixins.py","new_file":"apps\/predict\/mixins.py","old_contents":"\"\"\"\nBasic view mixins for predict views\n\"\"\"\n\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import login_required\n\nfrom .models import PredictDataset\n\nclass PredictMixin(object):\n \"\"\"The baseline predict view\"\"\"\n slug_field = 'md5'\n\n @method_decorator(login_required)\n def dispatch(self, request, *args, **kwargs):\n \"\"\"Only allow a logged in users to view\"\"\"\n return super(PredictMixin, self).dispatch(request, *args, **kwargs)\n\n def get_queryset(self):\n \"\"\"Limit queryset to the user's own predictions only\"\"\"\n qs = PredictDataset.objects.all()\n if 'slug' not in self.kwargs:\n # Limit to my own predictions unless I have the md5\n qs = qs.filter(user_id=self.request.user.pk)\n return qs\n\n","new_contents":"\"\"\"\nBasic view mixins for predict views\n\"\"\"\n\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import login_required\n\nfrom .models import PredictDataset\n\nclass PredictMixin(object):\n \"\"\"The baseline predict view\"\"\"\n slug_field = 'md5'\n\n @method_decorator(login_required)\n def dispatch(self, request, *args, **kwargs):\n \"\"\"Only allow a logged in users to view\"\"\"\n return super(PredictMixin, self).dispatch(request, *args, **kwargs)\n\n def get_queryset(self):\n \"\"\"Limit queryset to the user's own predictions only\"\"\"\n qset = PredictDataset.objects.all()\n if 'slug' not in self.kwargs:\n # Limit to my own predictions unless I have the md5\n qset = qset.filter(user_id=self.request.user.pk)\n return qset.prefetch_related('strains', 'strains__piperun', 'strains__piperun__programs')\n\n","subject":"Improve prefetch speed in predict listing pages","message":"Improve prefetch speed in predict listing pages\n","lang":"Python","license":"agpl-3.0","repos":"IQSS\/gentb-site,IQSS\/gentb-site,IQSS\/gentb-site,IQSS\/gentb-site,IQSS\/gentb-site,IQSS\/gentb-site,IQSS\/gentb-site,IQSS\/gentb-site"} {"commit":"324941bb4946cea19800fb1102035bd32e8028db","old_file":"apps\/profiles\/views.py","new_file":"apps\/profiles\/views.py","old_contents":"from django.views.generic import DetailView, UpdateView\nfrom django.contrib.auth.views import redirect_to_login\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import redirect\n\nfrom braces.views import LoginRequiredMixin\n\nfrom .models import User\n\n\nclass ProfileDetailView(DetailView):\n '''\n Displays the user profile information\n '''\n model = User\n slug_field = 'username'\n slug_url_kwarg = 'username'\n\n def get(self, request, *args, **kwargs):\n user = request.user\n username = self.kwargs.get(self.slug_url_kwarg)\n\n if user.is_authenticated() and not username:\n return redirect('profile_detail', username=user.username)\n elif not user.is_authenticated() and not username:\n return redirect_to_login(reverse('profile_detail_me'))\n\n return super(ProfileDetailView, self).get(request, *args, **kwargs)\n\n\nclass ProfileUpdateView(LoginRequiredMixin, UpdateView):\n model = User\n slug_field = 'username'\n slug_url_kwarg = 'username'\n","new_contents":"from django.views.generic import DetailView, UpdateView\nfrom django.contrib.auth.views import redirect_to_login\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import redirect\n\nfrom braces.views import LoginRequiredMixin\n\nfrom .models import User\n\n\nclass ProfileDetailView(DetailView):\n '''\n Displays the user profile information\n '''\n queryset = User.objects.select_related('location', 'location__country')\n slug_field = 'username'\n slug_url_kwarg = 'username'\n\n def get(self, request, *args, **kwargs):\n user = request.user\n username = self.kwargs.get(self.slug_url_kwarg)\n\n if user.is_authenticated() and not username:\n return redirect('profile_detail', username=user.username)\n elif not user.is_authenticated() and not username:\n return redirect_to_login(reverse('profile_detail_me'))\n\n return super(ProfileDetailView, self).get(request, *args, **kwargs)\n\n\nclass ProfileUpdateView(LoginRequiredMixin, UpdateView):\n model = User\n slug_field = 'username'\n slug_url_kwarg = 'username'\n","subject":"Use select_related in user profile detail view","message":"Use select_related in user profile detail view\n","lang":"Python","license":"mit","repos":"SoPR\/horas,SoPR\/horas,SoPR\/horas,SoPR\/horas"} {"commit":"3e842228beba066000eac536635e7e9d4d87c8e2","old_file":"instruments\/Instrument.py","new_file":"instruments\/Instrument.py","old_contents":"from traits.api import HasTraits\n\nimport json\n\nclass Instrument(HasTraits):\n\t\"\"\"\n\tMain super-class for all instruments.\n\t\"\"\"\n\n\tdef get_settings(self):\n\t\treturn self.__getstate__()\n\n\tdef set_settings(self, settings):\n\t\tfor key,value in settings.items():\n\t\t\tsetattr(self, key, value)\n","new_contents":"from traits.api import HasTraits, Bool\n\nimport json\n\nclass Instrument(HasTraits):\n\t\"\"\"\n\tMain super-class for all instruments.\n\t\"\"\"\n\tenabled = Bool(True, desc='Whether the unit is used\/enabled.')\n\n\tdef get_settings(self):\n\t\treturn self.__getstate__()\n\n\tdef set_settings(self, settings):\n\t\tfor key,value in settings.items():\n\t\t\tsetattr(self, key, value)\n","subject":"Add enabled to top-level instrument class.","message":"Add enabled to top-level instrument class.\n","lang":"Python","license":"apache-2.0","repos":"Plourde-Research-Lab\/PyQLab,rmcgurrin\/PyQLab,calebjordan\/PyQLab,BBN-Q\/PyQLab"} {"commit":"cfe594ec7576ba36e93762981067ad02176a585e","old_file":"instruments\/Instrument.py","new_file":"instruments\/Instrument.py","old_contents":"from traits.api import HasTraits\n\nimport json\n\nclass Instrument(HasTraits):\n\t\"\"\"\n\tMain super-class for all instruments.\n\t\"\"\"\n\n\tdef get_settings(self):\n\t\treturn self.__getstate__()\n\n\tdef set_settings(self, settings):\n\t\tfor key,value in settings.items():\n\t\t\tsetattr(self, key, value)\n","new_contents":"from traits.api import HasTraits, Bool\n\nimport json\n\nclass Instrument(HasTraits):\n\t\"\"\"\n\tMain super-class for all instruments.\n\t\"\"\"\n\tenabled = Bool(True, desc='Whether the unit is used\/enabled.')\n\n\tdef get_settings(self):\n\t\treturn self.__getstate__()\n\n\tdef set_settings(self, settings):\n\t\tfor key,value in settings.items():\n\t\t\tsetattr(self, key, value)\n","subject":"Add enabled to top-level instrument class.","message":"Add enabled to top-level instrument class.\n","lang":"Python","license":"apache-2.0","repos":"Plourde-Research-Lab\/PyQLab,BBN-Q\/PyQLab,calebjordan\/PyQLab,rmcgurrin\/PyQLab"} {"commit":"8776bb36fac2e9702b47bebe81f4fd4e2cec0102","old_file":"filer\/__init__.py","new_file":"filer\/__init__.py","old_contents":"#-*- coding: utf-8 -*-\n# version string following pep-0396 and pep-0386\n__version__ = '0.9pbs.34' # pragma: nocover\n","new_contents":"#-*- coding: utf-8 -*-\n# version string following pep-0396 and pep-0386\n__version__ = '0.9pbs.35' # pragma: nocover\n","subject":"Bump version as instructed by bamboo.","message":"Bump version as instructed by bamboo.\n","lang":"Python","license":"bsd-3-clause","repos":"pbs\/django-filer,pbs\/django-filer,pbs\/django-filer,pbs\/django-filer,pbs\/django-filer"} {"commit":"413413ac7b2f5a953443bdd08d625a55bd890938","old_file":"flaws\/__init__.py","new_file":"flaws\/__init__.py","old_contents":"#!\/usr\/bin\/env python\nimport sys\n\nfrom funcy import split, map\n\nfrom .analysis import global_usage, local_usage, FileSet\n\n\ndef main():\n command = sys.argv[1]\n opts, args = split(r'^--', sys.argv[2:])\n opts = dict(map(r'^--(\\w+)(?:=(.+))?', opts))\n\n # Run ipdb on exception\n if 'ipdb' in opts:\n import ipdb, traceback\n\n def info(type, value, tb):\n traceback.print_exception(type, value, tb)\n print\n ipdb.pm()\n\n sys.excepthook = info\n\n # Register plugins\n from .ext import django\n django.register(args, opts)\n\n # Do the job\n files = FileSet(args, base=opts.get('base'), ignore=opts.get('ignore'))\n if command == 'global':\n global_usage(files)\n elif command == 'local':\n local_usage(files)\n else:\n print 'Unknown command', command\n\n\nif __name__ == '__main__':\n main()\n","new_contents":"#!\/usr\/bin\/env python\nimport sys\n\nfrom funcy import split, map\n\nfrom .analysis import global_usage, local_usage, FileSet\n\n\ndef main():\n command = sys.argv[1]\n opts, args = split(r'^--', sys.argv[2:])\n opts = dict(map(r'^--(\\w+)(?:=(.+))?', opts))\n\n # Run ipdb on exception\n if 'ipdb' in opts:\n import ipdb, traceback\n\n def info(type, value, tb):\n traceback.print_exception(type, value, tb)\n print\n # Insert look-around helpers into the frame\n import inspect, ast\n from .asttools import to_source\n frame = inspect.getinnerframes(tb)[-1][0]\n frame.f_globals.setdefault('ast', ast)\n frame.f_globals.setdefault('to_source', to_source)\n # Run debugger\n ipdb.pm()\n\n sys.excepthook = info\n\n # Register plugins\n from .ext import django\n django.register(args, opts)\n\n # Do the job\n files = FileSet(args, base=opts.get('base'), ignore=opts.get('ignore'))\n if command == 'global':\n global_usage(files)\n elif command == 'local':\n local_usage(files)\n else:\n print 'Unknown command', command\n\n\nif __name__ == '__main__':\n main()\n","subject":"Insert look-around helpers into ipdb context","message":"Insert look-around helpers into ipdb context\n\nThese are `ast` and `to_source`.\n","lang":"Python","license":"bsd-2-clause","repos":"Suor\/flaws"} {"commit":"8beb6ddd2e58d6a3e54ab297d490c6650fb85a9d","old_file":"logya\/generate.py","new_file":"logya\/generate.py","old_contents":"# -*- coding: utf-8 -*-\nimport os\nimport shutil\n\nfrom logya.core import Logya\nfrom logya.fs import copytree\nfrom logya.writer import DocWriter\n\n\nclass Generate(Logya):\n \"\"\"Generate a Web site to deploy from current directory as source.\"\"\"\n\n def __init__(self, **kwargs):\n\n super(self.__class__, self).__init__(**kwargs)\n self.init_env()\n\n # Init writer before executing scripts, so they can use it.\n self.writer = DocWriter(self.dir_deploy, self.template)\n\n if not kwargs['keep']:\n self.info('Remove existing deploy directory')\n shutil.rmtree(self.dir_deploy, True)\n\n self.info('Generating site in directory: {}'.format(self.dir_deploy))\n\n if os.path.exists(self.dir_static):\n self.info('Copy static files')\n copytree(self.dir_static, self.dir_deploy)\n\n self.info('Build document index')\n self.build_index()\n\n self.info('Write documents')\n for doc in self.docs.values():\n self.writer.write(doc, self.get_doc_template(doc))\n self.info(\n 'Written {:d} documents to deploy directory'\n .format(len(self.docs)))\n\n self.info('Write index files')\n self.write_index_files()\n self.info(\n 'Written {:d} index files to deploy directory'\n .format(len(self.index)))\n","new_contents":"# -*- coding: utf-8 -*-\nimport os\nimport shutil\n\nfrom logya.core import Logya\nfrom logya.fs import copytree\nfrom logya.writer import DocWriter\n\n\nclass Generate(Logya):\n \"\"\"Generate a Web site to deploy from current directory as source.\"\"\"\n\n def __init__(self, **kwargs):\n super(self.__class__, self).__init__(**kwargs)\n self.init_env()\n self.writer = DocWriter(self.dir_deploy, self.template)\n\n if not kwargs['keep']:\n self.info('Remove existing deploy directory')\n shutil.rmtree(self.dir_deploy, True)\n\n self.info('Generate site in directory: {}'.format(self.dir_deploy))\n if os.path.exists(self.dir_static):\n self.info('Copy static files')\n copytree(self.dir_static, self.dir_deploy)\n\n self.build()\n self.write()\n\n def build(self):\n self.info('Build document index')\n self.build_index()\n\n def write(self):\n self.info('Write documents')\n for doc in self.docs.values():\n self.writer.write(doc, self.get_doc_template(doc))\n self.info(\n 'Written {:d} documents to deploy directory'\n .format(len(self.docs)))\n\n self.info('Write index files')\n self.write_index_files()\n self.info(\n 'Written {:d} index files to deploy directory'\n .format(len(self.index)))\n","subject":"Add build and write function to make it easy to subclass Generate and overwrite build step","message":"Add build and write function to make it easy to subclass Generate and overwrite build step\n","lang":"Python","license":"mit","repos":"elaOnMars\/logya,elaOnMars\/logya,elaOnMars\/logya,yaph\/logya,yaph\/logya"} {"commit":"9971e5424b998f45e26b9da8288f20d641885043","old_file":"massa\/__init__.py","new_file":"massa\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\n\nfrom flask import Flask, render_template, g\nfrom flask.ext.appconfig import AppConfig\n\n\ndef create_app(configfile=None):\n app = Flask('massa')\n AppConfig(app, configfile)\n\n @app.route('\/')\n def index():\n return render_template('index.html')\n\n from .container import build\n sl = build(app.config)\n\n from .api import bp\n app.register_blueprint(bp, url_prefix='\/api')\n\n @app.before_request\n def globals():\n g.sl = sl\n\n return app\n","new_contents":"# -*- coding: utf-8 -*-\n\nfrom flask import Flask, render_template, g\nfrom flask.ext.appconfig import AppConfig\nfrom .container import build\nfrom .api import bp as api\n\n\ndef create_app(configfile=None):\n app = Flask('massa')\n AppConfig(app, configfile)\n\n @app.route('\/')\n def index():\n return render_template('index.html')\n\n sl = build(app.config)\n\n app.register_blueprint(api, url_prefix='\/api')\n\n @app.before_request\n def globals():\n g.sl = sl\n\n return app\n","subject":"Move import statements to the top.","message":"Move import statements to the top.","lang":"Python","license":"mit","repos":"jaapverloop\/massa"} {"commit":"12c97be97a8816720899531b932be99743b6d90d","old_file":"rest_framework_plist\/__init__.py","new_file":"rest_framework_plist\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\nfrom distutils import version\n\n__version__ = '0.2.0'\nversion_info = version.StrictVersion(__version__).version\n","new_contents":"# -*- coding: utf-8 -*-\nfrom distutils import version\n\n__version__ = '0.2.0'\nversion_info = version.StrictVersion(__version__).version\n\nfrom .parsers import PlistParser # NOQA\nfrom .renderers import PlistRenderer # NOQA\n","subject":"Make parser and renderer available at package root","message":"Make parser and renderer available at package root\n","lang":"Python","license":"bsd-2-clause","repos":"lpomfrey\/django-rest-framework-plist,pombredanne\/django-rest-framework-plist"} {"commit":"3f7371c796a420cc077cf79b210d401c77b77815","old_file":"rest_framework\/response.py","new_file":"rest_framework\/response.py","old_contents":"from django.core.handlers.wsgi import STATUS_CODE_TEXT\nfrom django.template.response import SimpleTemplateResponse\n\n\nclass Response(SimpleTemplateResponse):\n \"\"\"\n An HttpResponse that allows it's data to be rendered into\n arbitrary media types.\n \"\"\"\n\n def __init__(self, data=None, status=None, headers=None,\n renderer=None, accepted_media_type=None):\n \"\"\"\n Alters the init arguments slightly.\n For example, drop 'template_name', and instead use 'data'.\n\n Setting 'renderer' and 'media_type' will typically be defered,\n For example being set automatically by the `APIView`.\n \"\"\"\n super(Response, self).__init__(None, status=status)\n self.data = data\n self.headers = headers and headers[:] or []\n self.renderer = renderer\n self.accepted_media_type = accepted_media_type\n\n @property\n def rendered_content(self):\n self['Content-Type'] = self.renderer.media_type\n if self.data is None:\n return self.renderer.render()\n render_media_type = self.accepted_media_type or self.renderer.media_type\n return self.renderer.render(self.data, render_media_type)\n\n @property\n def status_text(self):\n \"\"\"\n Returns reason text corresponding to our HTTP response status code.\n Provided for convenience.\n \"\"\"\n return STATUS_CODE_TEXT.get(self.status_code, '')\n","new_contents":"from django.core.handlers.wsgi import STATUS_CODE_TEXT\nfrom django.template.response import SimpleTemplateResponse\n\n\nclass Response(SimpleTemplateResponse):\n \"\"\"\n An HttpResponse that allows it's data to be rendered into\n arbitrary media types.\n \"\"\"\n\n def __init__(self, data=None, status=None, headers=None,\n renderer=None, accepted_media_type=None):\n \"\"\"\n Alters the init arguments slightly.\n For example, drop 'template_name', and instead use 'data'.\n\n Setting 'renderer' and 'media_type' will typically be defered,\n For example being set automatically by the `APIView`.\n \"\"\"\n super(Response, self).__init__(None, status=status)\n self.data = data\n self.headers = headers and headers[:] or []\n self.renderer = renderer\n\n # Accepted media type is the portion of the request Accept header\n # that the renderer satisfied. It could be '*\/*', or somthing like\n # 'application\/json; indent=4'\n #\n # This is NOT the value that will be returned in the 'Content-Type'\n # header, but we do need to know the value in case there are\n # any specific parameters which affect the rendering process.\n self.accepted_media_type = accepted_media_type\n\n @property\n def rendered_content(self):\n self['Content-Type'] = self.renderer.media_type\n if self.data is None:\n return self.renderer.render()\n render_media_type = self.accepted_media_type or self.renderer.media_type\n return self.renderer.render(self.data, render_media_type)\n\n @property\n def status_text(self):\n \"\"\"\n Returns reason text corresponding to our HTTP response status code.\n Provided for convenience.\n \"\"\"\n return STATUS_CODE_TEXT.get(self.status_code, '')\n","subject":"Tweak media_type -> accepted_media_type. Need to document, but marginally less confusing","message":"Tweak media_type -> accepted_media_type. Need to document, but marginally less confusing\n","lang":"Python","license":"bsd-2-clause","repos":"kylefox\/django-rest-framework,cyberj\/django-rest-framework,vstoykov\/django-rest-framework,wedaly\/django-rest-framework,canassa\/django-rest-framework,tomchristie\/django-rest-framework,linovia\/django-rest-framework,cheif\/django-rest-framework,nhorelik\/django-rest-framework,jpulec\/django-rest-framework,James1345\/django-rest-framework,ashishfinoit\/django-rest-framework,ticosax\/django-rest-framework,rubendura\/django-rest-framework,d0ugal\/django-rest-framework,ashishfinoit\/django-rest-framework,werthen\/django-rest-framework,adambain-vokal\/django-rest-framework,jpadilla\/django-rest-framework,kgeorgy\/django-rest-framework,ebsaral\/django-rest-framework,jerryhebert\/django-rest-framework,VishvajitP\/django-rest-framework,edx\/django-rest-framework,pombredanne\/django-rest-framework,douwevandermeij\/django-rest-framework,douwevandermeij\/django-rest-framework,maryokhin\/django-rest-framework,nryoung\/django-rest-framework,jness\/django-rest-framework,rafaelang\/django-rest-framework,wzbozon\/django-rest-framework,johnraz\/django-rest-framework,ossanna16\/django-rest-framework,maryokhin\/django-rest-framework,VishvajitP\/django-rest-framework,agconti\/django-rest-framework,kennydude\/django-rest-framework,brandoncazander\/django-rest-framework,callorico\/django-rest-framework,antonyc\/django-rest-framework,alacritythief\/django-rest-framework,wangpanjun\/django-rest-framework,rhblind\/django-rest-framework,iheitlager\/django-rest-framework,bluedazzle\/django-rest-framework,atombrella\/django-rest-framework,gregmuellegger\/django-rest-framework,paolopaolopaolo\/django-rest-framework,elim\/django-rest-framework,kgeorgy\/django-rest-framework,nryoung\/django-rest-framework,kezabelle\/django-rest-framework,cheif\/django-rest-framework,aericson\/django-rest-framework,xiaotangyuan\/django-rest-framework,tigeraniya\/django-rest-framework,nhorelik\/django-rest-framework,YBJAY00000\/django-rest-framework,sheppard\/django-rest-framework,jpulec\/django-rest-framework,wangpanjun\/django-rest-framework,justanr\/django-rest-framework,agconti\/django-rest-framework,hunter007\/django-rest-framework,sbellem\/django-rest-framework,canassa\/django-rest-framework,abdulhaq-e\/django-rest-framework,AlexandreProenca\/django-rest-framework,elim\/django-rest-framework,arpheno\/django-rest-framework,werthen\/django-rest-framework,potpath\/django-rest-framework,damycra\/django-rest-framework,delinhabit\/django-rest-framework,ticosax\/django-rest-framework,ticosax\/django-rest-framework,rafaelang\/django-rest-framework,HireAnEsquire\/django-rest-framework,wzbozon\/django-rest-framework,raphaelmerx\/django-rest-framework,hnakamur\/django-rest-framework,edx\/django-rest-framework,buptlsl\/django-rest-framework,yiyocx\/django-rest-framework,potpath\/django-rest-framework,wwj718\/django-rest-framework,hunter007\/django-rest-framework,jness\/django-rest-framework,fishky\/django-rest-framework,andriy-s\/django-rest-framework,antonyc\/django-rest-framework,ajaali\/django-rest-framework,damycra\/django-rest-framework,yiyocx\/django-rest-framework,qsorix\/django-rest-framework,buptlsl\/django-rest-framework,abdulhaq-e\/django-rest-framework,buptlsl\/django-rest-framework,dmwyatt\/django-rest-framework,yiyocx\/django-rest-framework,aericson\/django-rest-framework,jness\/django-rest-framework,uruz\/django-rest-framework,ambivalentno\/django-rest-framework,dmwyatt\/django-rest-framework,MJafarMashhadi\/django-rest-framework,adambain-vokal\/django-rest-framework,kylefox\/django-rest-framework,thedrow\/django-rest-framework-1,canassa\/django-rest-framework,zeldalink0515\/django-rest-framework,sehmaschine\/django-rest-framework,paolopaolopaolo\/django-rest-framework,aericson\/django-rest-framework,agconti\/django-rest-framework,nhorelik\/django-rest-framework,xiaotangyuan\/django-rest-framework,zeldalink0515\/django-rest-framework,krinart\/django-rest-framework,bluedazzle\/django-rest-framework,rafaelcaricio\/django-rest-framework,leeahoward\/django-rest-framework,iheitlager\/django-rest-framework,raphaelmerx\/django-rest-framework,jpadilla\/django-rest-framework,abdulhaq-e\/django-rest-framework,hunter007\/django-rest-framework,kennydude\/django-rest-framework,davesque\/django-rest-framework,iheitlager\/django-rest-framework,ebsaral\/django-rest-framework,ebsaral\/django-rest-framework,akalipetis\/django-rest-framework,tcroiset\/django-rest-framework,wedaly\/django-rest-framework,James1345\/django-rest-framework,xiaotangyuan\/django-rest-framework,sehmaschine\/django-rest-framework,cyberj\/django-rest-framework,mgaitan\/django-rest-framework,tigeraniya\/django-rest-framework,mgaitan\/django-rest-framework,hnakamur\/django-rest-framework,MJafarMashhadi\/django-rest-framework,MJafarMashhadi\/django-rest-framework,alacritythief\/django-rest-framework,rafaelang\/django-rest-framework,simudream\/django-rest-framework,zeldalink0515\/django-rest-framework,simudream\/django-rest-framework,d0ugal\/django-rest-framework,kylefox\/django-rest-framework,ezheidtmann\/django-rest-framework,ajaali\/django-rest-framework,leeahoward\/django-rest-framework,sbellem\/django-rest-framework,waytai\/django-rest-framework,rafaelcaricio\/django-rest-framework,mgaitan\/django-rest-framework,tomchristie\/django-rest-framework,hnakamur\/django-rest-framework,uploadcare\/django-rest-framework,cheif\/django-rest-framework,pombredanne\/django-rest-framework,sheppard\/django-rest-framework,wwj718\/django-rest-framework,tcroiset\/django-rest-framework,krinart\/django-rest-framework,atombrella\/django-rest-framework,lubomir\/django-rest-framework,AlexandreProenca\/django-rest-framework,brandoncazander\/django-rest-framework,raphaelmerx\/django-rest-framework,arpheno\/django-rest-framework,delinhabit\/django-rest-framework,brandoncazander\/django-rest-framework,waytai\/django-rest-framework,ajaali\/django-rest-framework,gregmuellegger\/django-rest-framework,leeahoward\/django-rest-framework,paolopaolopaolo\/django-rest-framework,HireAnEsquire\/django-rest-framework,arpheno\/django-rest-framework,jpadilla\/django-rest-framework,jerryhebert\/django-rest-framework,andriy-s\/django-rest-framework,krinart\/django-rest-framework,ezheidtmann\/django-rest-framework,davesque\/django-rest-framework,vstoykov\/django-rest-framework,tomchristie\/django-rest-framework,ezheidtmann\/django-rest-framework,simudream\/django-rest-framework,thedrow\/django-rest-framework-1,ambivalentno\/django-rest-framework,rubendura\/django-rest-framework,adambain-vokal\/django-rest-framework,justanr\/django-rest-framework,johnraz\/django-rest-framework,fishky\/django-rest-framework,jpulec\/django-rest-framework,kezabelle\/django-rest-framework,d0ugal\/django-rest-framework,ossanna16\/django-rest-framework,wwj718\/django-rest-framework,uploadcare\/django-rest-framework,fishky\/django-rest-framework,douwevandermeij\/django-rest-framework,lubomir\/django-rest-framework,YBJAY00000\/django-rest-framework,linovia\/django-rest-framework,lubomir\/django-rest-framework,ashishfinoit\/django-rest-framework,vstoykov\/django-rest-framework,ossanna16\/django-rest-framework,linovia\/django-rest-framework,antonyc\/django-rest-framework,wedaly\/django-rest-framework,rhblind\/django-rest-framework,sehmaschine\/django-rest-framework,YBJAY00000\/django-rest-framework,potpath\/django-rest-framework,thedrow\/django-rest-framework-1,delinhabit\/django-rest-framework,VishvajitP\/django-rest-framework,elim\/django-rest-framework,jtiai\/django-rest-framework,rafaelcaricio\/django-rest-framework,sbellem\/django-rest-framework,callorico\/django-rest-framework,pombredanne\/django-rest-framework,andriy-s\/django-rest-framework,kgeorgy\/django-rest-framework,sheppard\/django-rest-framework,akalipetis\/django-rest-framework,tigeraniya\/django-rest-framework,hnarayanan\/django-rest-framework,cyberj\/django-rest-framework,atombrella\/django-rest-framework,dmwyatt\/django-rest-framework,HireAnEsquire\/django-rest-framework,waytai\/django-rest-framework,wangpanjun\/django-rest-framework,damycra\/django-rest-framework,ambivalentno\/django-rest-framework,AlexandreProenca\/django-rest-framework,nryoung\/django-rest-framework,gregmuellegger\/django-rest-framework,hnarayanan\/django-rest-framework,johnraz\/django-rest-framework,James1345\/django-rest-framework,tcroiset\/django-rest-framework,uruz\/django-rest-framework,uploadcare\/django-rest-framework,werthen\/django-rest-framework,davesque\/django-rest-framework,bluedazzle\/django-rest-framework,qsorix\/django-rest-framework,alacritythief\/django-rest-framework,callorico\/django-rest-framework,jerryhebert\/django-rest-framework,jtiai\/django-rest-framework,jtiai\/django-rest-framework,rubendura\/django-rest-framework,kennydude\/django-rest-framework,qsorix\/django-rest-framework,uruz\/django-rest-framework,edx\/django-rest-framework,justanr\/django-rest-framework,akalipetis\/django-rest-framework,rhblind\/django-rest-framework,hnarayanan\/django-rest-framework,wzbozon\/django-rest-framework,kezabelle\/django-rest-framework,maryokhin\/django-rest-framework"} {"commit":"7a1254fa530b02d32f39e2210ec864f78dd9504a","old_file":"groundstation\/transfer\/response_handlers\/describeobjects.py","new_file":"groundstation\/transfer\/response_handlers\/describeobjects.py","old_contents":"from groundstation import logger\nlog = logger.getLogger(__name__)\n\n\ndef handle_describeobjects(self):\n if not self.payload:\n log.info(\"station %s sent empty DESCRIVEOBJECTS payload - new database?\" % (str(self.origin)))\n return\n for obj in self.payload.split(chr(0)):\n if obj not in self.station or True:\n request = self._Request(\"FETCHOBJECT\", payload=obj)\n self.stream.enqueue(request)\n else:\n log.debug(\"Not fetching already present object %s\" % (str(obj)))\n","new_contents":"from groundstation import logger\nlog = logger.getLogger(__name__)\n\n\ndef handle_describeobjects(self):\n if not self.payload:\n log.info(\"station %s sent empty DESCRIVEOBJECTS payload - new database?\" % (str(self.origin)))\n return\n for obj in self.payload.split(chr(0)):\n if obj not in self.station:\n request = self._Request(\"FETCHOBJECT\", payload=obj)\n self.stream.enqueue(request)\n else:\n log.debug(\"Not fetching already present object %s\" % (str(obj)))\n","subject":"Remove hook that snuck in","message":"Remove hook that snuck in\n","lang":"Python","license":"mit","repos":"richo\/groundstation,richo\/groundstation,richo\/groundstation,richo\/groundstation,richo\/groundstation"} {"commit":"b11a0197bbecbbdb6e5f3c82285f6b749596947d","old_file":"api\/oauth2_urls.py","new_file":"api\/oauth2_urls.py","old_contents":"from django.conf.urls import url\nfrom oauth2_provider import views\n\nurlpatterns = (\n url(r'^authorize\/$', views.AuthorizationView.as_view(\n template_name='accounts\/authorize_client.html',\n ), name=\"authorize\"),\n url(r'^token\/$', views.TokenView.as_view(), name=\"token\"),\n url(r'^revoke_token\/$', views.RevokeTokenView.as_view(), name=\"revoke-token\"),\n)\n","new_contents":"from django.conf.urls import url\nfrom oauth2_provider import views\n\nurlpatterns = (\n url(r'^authorize\/?$', views.AuthorizationView.as_view(\n template_name='accounts\/authorize_client.html',\n ), name=\"authorize\"),\n url(r'^token\/?$', views.TokenView.as_view(), name=\"token\"),\n url(r'^revoke_token\/?$', views.RevokeTokenView.as_view(), name=\"revoke-token\"),\n)\n","subject":"Make trailing slash optional in API oauth URL patterns","message":"Make trailing slash optional in API oauth URL patterns\n\nhttps:\/\/github.com\/AudioCommons\/ac-mediator\/issues\/19\n","lang":"Python","license":"apache-2.0","repos":"AudioCommons\/ac-mediator,AudioCommons\/ac-mediator,AudioCommons\/ac-mediator"} {"commit":"eb763a7c7048b857d408825241ed3de6b68b88f6","old_file":"1\/sumofmultiplesof3and5.py","new_file":"1\/sumofmultiplesof3and5.py","old_contents":"# Project Euler - Problem 1\nsum = 0\nfor i in xrange(1, 1001):\n if i % 3 == 0 or i % 5 == 0:\n sum = sum + i\n\nprint \"The sum is: {}\".format(sum)\n","new_contents":"# Project Euler - Problem 1\n# If we list all the natural numbers below 10 that are multiples of 3 or 5, \n# we get 3, 5, 6 and 9. The sum of these multiples is 23.\n# Find the sum of all the multiples of 3 or 5 below 1000.\n\ndef main(limit):\n sum = 0\n for i in xrange(1, limit):\n if i % 3 == 0 or i % 5 == 0:\n sum = sum + i\n\n print \"The sum of all multiples of 3 and 5 below {} is: {}\".format(limit, sum)\n\nif __name__ == \"__main__\":\n main(10)\n main(1001)\n","subject":"Clean up problem 1 solution a bit.","message":"Clean up problem 1 solution a bit.\n","lang":"Python","license":"mit","repos":"gregmojonnier\/ProjectEuler"} {"commit":"1179d825cafb512119906894527de801e43ed906","old_file":"metatlas\/tests\/test_query.py","new_file":"metatlas\/tests\/test_query.py","old_contents":"from __future__ import print_function\n\nfrom metatlas.mzml_loader import mzml_to_hdf, get_test_data\nfrom metatlas.h5_query import get_XICof, get_data\n\n\ndef rmse(target, predictions):\n target = target \/ target.max()\n predictions = predictions \/ predictions.max()\n\n return np.sqrt(((predictions - targets) ** 2).mean())\n\n\ndef test_xicof():\n return\n fid = tables.open_file('140808_1_RCH2_neg.h5')\n x, y = get_XICof(fid, 1, 1000, 1, 0)\n \n xicof_scidb = np.load('xicof_scidb.npy')\n\n assert rmse(y, xicof_scidb[:, 1]) < 0.01\n\n data = get_data(fid, 1, 0, mz_min=1, mz_max=1000)\n assert x.sum() == data['i'].sum()\n assert y[0] == data['rt'][0]\n assert y[-1] == data['rt'][-1]\n","new_contents":"from __future__ import print_function\n\nfrom metatlas.mzml_loader import mzml_to_hdf, get_test_data\nfrom metatlas.h5_query import get_XIC, get_data\n\n\ndef rmse(target, predictions):\n target = target \/ target.max()\n predictions = predictions \/ predictions.max()\n\n return np.sqrt(((predictions - targets) ** 2).mean())\n\n\ndef test_xicof():\n return\n fid = tables.open_file('140808_1_RCH2_neg.h5')\n x, y = get_XICof(fid, 1, 1000, 1, 0)\n \n xicof_scidb = np.load('xicof_scidb.npy')\n\n assert rmse(y, xicof_scidb[:, 1]) < 0.01\n\n data = get_data(fid, 1, 0, mz_min=1, mz_max=1000)\n assert x.sum() == data['i'].sum()\n assert y[0] == data['rt'][0]\n assert y[-1] == data['rt'][-1]\n","subject":"Fix another import in test","message":"Fix another import in test\n","lang":"Python","license":"bsd-3-clause","repos":"biorack\/metatlas,biorack\/metatlas,metabolite-atlas\/metatlas,aitatanit\/metatlas,metabolite-atlas\/metatlas,aitatanit\/metatlas,aitatanit\/metatlas,metabolite-atlas\/metatlas"} {"commit":"d05c68b110e4adf5f411816196cf1f457e51951e","old_file":"nbrmd\/__init__.py","new_file":"nbrmd\/__init__.py","old_contents":"\"\"\"R markdown notebook format for Jupyter\n\nUse this module to read or write Jupyter notebooks as Rmd documents (methods 'read', 'reads', 'write', 'writes')\n\nUse the 'pre_save_hook' method (see its documentation) to automatically dump your Jupyter notebooks as a Rmd file, in addition\nto the ipynb file.\n\nUse the 'nbrmd' conversion script to convert Jupyter notebooks from\/to R markdown notebooks.\n\"\"\"\n\nfrom .nbrmd import read, reads, readf, write, writes, writef\nfrom .hooks import update_rmd, update_ipynb, update_rmd_and_ipynb, update_selected_formats\nfrom .cm import RmdFileContentsManager\n","new_contents":"\"\"\"R markdown notebook format for Jupyter\n\nUse this module to read or write Jupyter notebooks as Rmd documents (methods 'read', 'reads', 'write', 'writes')\n\nUse the 'pre_save_hook' method (see its documentation) to automatically dump your Jupyter notebooks as a Rmd file, in addition\nto the ipynb file.\n\nUse the 'nbrmd' conversion script to convert Jupyter notebooks from\/to R markdown notebooks.\n\"\"\"\n\nfrom .nbrmd import read, reads, readf, write, writes, writef\nfrom .hooks import update_rmd, update_ipynb, update_rmd_and_ipynb, update_selected_formats\ntry:\n from .cm import RmdFileContentsManager\nexcept ImportError as e:\n RmdFileContentsManager = e.message\n","subject":"Allow import in case of missing notebook package","message":"Allow import in case of missing notebook package","lang":"Python","license":"mit","repos":"mwouts\/jupytext,mwouts\/jupytext,mwouts\/jupytext,mwouts\/jupytext,mwouts\/jupytext,mwouts\/jupytext,mwouts\/jupytext,mwouts\/jupytext,mwouts\/jupytext,mwouts\/jupytext"} {"commit":"a918dbdb18f579543916da8dfc14e7d3d06237ae","old_file":"logtacts\/prod_settings\/__init__.py","new_file":"logtacts\/prod_settings\/__init__.py","old_contents":"from logtacts.settings import *\nimport dj_database_url\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nDATABASES['default'] = dj_database_url.parse(get_env_variable('LOGTACTS_DB_URL'))\n\nSECRET_KEY = get_env_variable(\"LOGTACTS_SECRET_KEY\")\n\nALLOWED_HOSTS = [\n 'localhost',\n '127.0.0.1',\n '.pebble.ink',\n '.logtacts.com',\n '.contactotter.com',\n]\n\nSECURE_SSL_REDIRECT = True\nSECURE_HSTS_SECONDS = 3600\nSECURE_FRAME_DENY = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\nSECURE_BROWSER_XSS_FILTER = True\nSESSION_COOKIE_SECURE = True\nSESSION_COOKIE_HTTPONLY = True\n\nSTATIC_URL = '\/\/logtacts.s3.amazonaws.com\/assets\/'\n\nINSTALLED_APPS += (\n 'gunicorn',\n 'opbeat.contrib.django',\n)\n\nMIDDLEWARE_CLASSES = (\n 'opbeat.contrib.django.middleware.OpbeatAPMMiddleware',\n) + MIDDLEWARE_CLASSES\n\nOPBEAT = {\n 'ORGANIZATION_ID': get_env_variable(\"OPBEAT_ORG_ID\"),\n 'APP_ID': get_env_variable(\"OPBEAT_APP_ID\"),\n 'SECRET_TOKEN': get_env_variable(\"OPBEAT_SECRET_KEY\"),\n}\n","new_contents":"from logtacts.settings import *\nimport dj_database_url\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nDATABASES['default'] = dj_database_url.parse(get_env_variable('LOGTACTS_DB_URL'))\n\nSECRET_KEY = get_env_variable(\"LOGTACTS_SECRET_KEY\")\n\nALLOWED_HOSTS = [\n 'localhost',\n '127.0.0.1',\n '.pebble.ink',\n '.logtacts.com',\n '.contactotter.com',\n '.herokuapp.com',\n]\n\nSECURE_SSL_REDIRECT = True\nSECURE_HSTS_SECONDS = 3600\nSECURE_FRAME_DENY = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\nSECURE_BROWSER_XSS_FILTER = True\nSESSION_COOKIE_SECURE = True\nSESSION_COOKIE_HTTPONLY = True\n\nSTATIC_URL = '\/\/logtacts.s3.amazonaws.com\/assets\/'\n\nINSTALLED_APPS += (\n 'gunicorn',\n 'opbeat.contrib.django',\n)\n\nMIDDLEWARE_CLASSES = (\n 'opbeat.contrib.django.middleware.OpbeatAPMMiddleware',\n) + MIDDLEWARE_CLASSES\n\nOPBEAT = {\n 'ORGANIZATION_ID': get_env_variable(\"OPBEAT_ORG_ID\"),\n 'APP_ID': get_env_variable(\"OPBEAT_APP_ID\"),\n 'SECRET_TOKEN': get_env_variable(\"OPBEAT_SECRET_KEY\"),\n}\n","subject":"Make sure heroku is in accepted hosts","message":"Make sure heroku is in accepted hosts\n","lang":"Python","license":"mit","repos":"phildini\/logtacts,phildini\/logtacts,phildini\/logtacts,phildini\/logtacts,phildini\/logtacts"} {"commit":"802626461779e4de34e7994c88ab698495dfca59","old_file":"docs\/source\/conf.py","new_file":"docs\/source\/conf.py","old_contents":"# Copyright (c) 2014, German Neuroinformatics Node (G-Node)\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted under the terms of the BSD License. See\n# LICENSE file in the root of the Project.\n\n# general config\nextensions = ['sphinx.ext.autodoc']\nsource_suffix = '.rst'\nmaster_doc = 'index'\nproject = 'NIX Python bindings'\ncopyright = '2014, German Neuroinformatics Node, Adrian Stoewer, Christian Kellner'\nexclude_patterns = []\npygments_style = 'sphinx'\n\n# html options\nhtml_theme = 'default'\nhtmlhelp_basename = 'nix'\n","new_contents":"# Copyright (c) 2014, German Neuroinformatics Node (G-Node)\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted under the terms of the BSD License. See\n# LICENSE file in the root of the Project.\n\n# general config\nextensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']\nsource_suffix = '.rst'\nmaster_doc = 'index'\nproject = 'NIX Python bindings'\ncopyright = '2014, German Neuroinformatics Node, Adrian Stoewer, Christian Kellner'\nexclude_patterns = []\npygments_style = 'sphinx'\n\n# html options\nhtml_theme = 'default'\nhtmlhelp_basename = 'nix'\n\n# intersphinx configuration\nintersphinx_mapping = {\n 'http:\/\/docs.python.org\/2.7' : None,\n 'http:\/\/docs.scipy.org\/doc\/numpy': None\n}\n","subject":"Enable intersphinx and add mapping for py2.7 + numpy","message":"[doc] Enable intersphinx and add mapping for py2.7 + numpy\n","lang":"Python","license":"bsd-3-clause","repos":"stoewer\/nixpy,stoewer\/nixpy"} {"commit":"40af69656b71cda7f775cface3478106f070ed35","old_file":"numba\/__init__.py","new_file":"numba\/__init__.py","old_contents":"import sys\nimport logging\n\n# NOTE: Be sure to keep the logging level commented out before commiting. See:\n# https:\/\/github.com\/numba\/numba\/issues\/31\n# A good work around is to make your tests handle a debug flag, per\n# numba.tests.test_support.main().\nlogging.basicConfig(#level=logging.DEBUG,\n format=\"\\n\\033[1m%(levelname)s -- %(module)s:%(lineno)d:%(funcName)s\\033[0m\\n%(message)s\")\n\ntry:\n from . import minivect\nexcept ImportError:\n print(logging.error(\"Did you forget to update submodule minivect?\"))\n print(logging.error(\"Run 'git submodule init' followed by 'git submodule update'\"))\n raise\n\nfrom . import _numba_types\nfrom ._numba_types import *\nfrom . import decorators\nfrom .decorators import *\n\ndef test():\n raise Exception(\"run nosetests from the numba directory\")\n\n\n__all__ = _numba_types.__all__ + decorators.__all__\n","new_contents":"import sys\nimport logging\n\n# NOTE: Be sure to keep the logging level commented out before commiting. See:\n# https:\/\/github.com\/numba\/numba\/issues\/31\n# A good work around is to make your tests handle a debug flag, per\n# numba.tests.test_support.main().\n\nclass _RedirectingHandler(logging.Handler):\n '''\n A log hanlder that applies its formatter and redirect the emission\n to a parent handler.\n '''\n def set_handler(self, handler):\n self.handler = handler\n\n def emit(self, record):\n # apply our own formatting\n record.msg = self.format(record)\n record.args = [] # clear the args\n # use parent handler to emit record\n self.handler.emit(record)\n\ndef _config_logger():\n root = logging.getLogger(__name__)\n format = \"\\n\\033[1m%(levelname)s -- \"\\\n \"%(module)s:%(lineno)d:%(funcName)s\\033[0m\\n%(message)s\"\n try:\n parent_hldr = root.parent.handlers[0]\n except IndexError: # parent handler is not initialized?\n # build our own handler --- uses sys.stderr by default.\n parent_hldr = logging.StreamHandler()\n hldr = _RedirectingHandler()\n hldr.set_handler(parent_hldr)\n fmt = logging.Formatter(format)\n hldr.setFormatter(fmt)\n root.addHandler(hldr)\n root.propagate = False # do not propagate to the root logger\n\n_config_logger()\n\ntry:\n from . import minivect\nexcept ImportError:\n print(logging.error(\"Did you forget to update submodule minivect?\"))\n print(logging.error(\"Run 'git submodule init' followed by 'git submodule update'\"))\n raise\n\nfrom . import _numba_types\nfrom ._numba_types import *\nfrom . import decorators\nfrom .decorators import *\n\ndef test():\n raise Exception(\"run nosetests from the numba directory\")\n\n\n__all__ = _numba_types.__all__ + decorators.__all__\n","subject":"Update logging facility. Don't overide root logger with basicConfig.","message":"Update logging facility. Don't overide root logger with basicConfig.\n","lang":"Python","license":"bsd-2-clause","repos":"numba\/numba,stefanseefeld\/numba,pitrou\/numba,stonebig\/numba,ssarangi\/numba,ssarangi\/numba,seibert\/numba,gmarkall\/numba,seibert\/numba,pombredanne\/numba,sklam\/numba,shiquanwang\/numba,stefanseefeld\/numba,cpcloud\/numba,gmarkall\/numba,numba\/numba,jriehl\/numba,cpcloud\/numba,seibert\/numba,jriehl\/numba,jriehl\/numba,pitrou\/numba,GaZ3ll3\/numba,pitrou\/numba,IntelLabs\/numba,IntelLabs\/numba,seibert\/numba,jriehl\/numba,gdementen\/numba,sklam\/numba,GaZ3ll3\/numba,stefanseefeld\/numba,shiquanwang\/numba,gmarkall\/numba,GaZ3ll3\/numba,pitrou\/numba,stonebig\/numba,gmarkall\/numba,gmarkall\/numba,ssarangi\/numba,seibert\/numba,stefanseefeld\/numba,stuartarchibald\/numba,gdementen\/numba,numba\/numba,cpcloud\/numba,GaZ3ll3\/numba,stefanseefeld\/numba,gdementen\/numba,stuartarchibald\/numba,stonebig\/numba,pombredanne\/numba,stuartarchibald\/numba,sklam\/numba,ssarangi\/numba,pitrou\/numba,numba\/numba,stuartarchibald\/numba,shiquanwang\/numba,pombredanne\/numba,stonebig\/numba,pombredanne\/numba,sklam\/numba,cpcloud\/numba,sklam\/numba,stonebig\/numba,IntelLabs\/numba,gdementen\/numba,jriehl\/numba,IntelLabs\/numba,pombredanne\/numba,stuartarchibald\/numba,IntelLabs\/numba,ssarangi\/numba,numba\/numba,GaZ3ll3\/numba,cpcloud\/numba,gdementen\/numba"} {"commit":"4aa9e487cceccf81608dfb4ac9a1f85587298415","old_file":"edit.py","new_file":"edit.py","old_contents":"# request handler for editing page (\/edit) goes here\n# assume admin login has already been handled\n\nimport cgi\nfrom google.appengine.api import users\nimport webapp2\n\nclass DateHandler(webapp2.RequestHandler):\n \n def get(self):\n \n template_values = { \n \n }\n \n template = jinja_environment.get_template('dates.html')\n self.response.out.write(template.render(template_values))\n\nclass EditHandler(webapp2.RequestHandler):\n \n def get(self):\n \n template_values = { \n \n }\n \n template = jinja_environment.get_template('edit.html')\n self.response.out.write(template.render(template_values))\n\napp = webapp2.WSGIApplication([\n ('\/date', DateHandler)\n ('\/edit', EditHandler)\n], debug=True)","new_contents":"# request handler for editing page (\/edit) goes here\n# assume admin login has already been handled\n\nimport cgi\nfrom google.appengine.api import users\nimport webapp2\n\nclass DateHandler(webapp2.RequestHandler):\n \n def get(self):\n date = self.request.get(date)\n template_values = { \n \n }\n \n template = jinja_environment.get_template('dates.html')\n self.response.out.write(template.render(template_values))\n\nclass EditHandler(webapp2.RequestHandler):\n \n def get(self):\n \n template_values = { \n \n }\n \n template = jinja_environment.get_template('edit.html')\n self.response.out.write(template.render(template_values))\n\napp = webapp2.WSGIApplication([\n ('\/date', DateHandler)\n ('\/edit', EditHandler)\n], debug=True)","subject":"Put in date = self.request.get(date) in order to call the date from the HTML.","message":"Put in date = self.request.get(date) in order to call the date from the HTML.\n","lang":"Python","license":"mit","repos":"shickey\/BearStatus,shickey\/BearStatus,shickey\/BearStatus"} {"commit":"eee35fdd148c825c492333d933eaaf8503bb09f2","old_file":"pydrm\/image.py","new_file":"pydrm\/image.py","old_contents":"from .format import DrmFormat\nfrom .framebuffer import DrmFramebuffer\nfrom .buffer import DrmDumbBuffer\n\n\nclass DrmImageFramebuffer(DrmFramebuffer):\n def __init__(self, drm=None, format_=None, width=None, height=None, bo=None):\n if drm and format_ and width and height and bo is None:\n bo = DrmDumbBuffer(drm, format_, width, height)\n elif (drm or format_ or width or height) and bo is None:\n raise TypeError()\n super(DrmImageFramebuffer, self).__init__(bo)\n self._setup()\n\n def _setup(self):\n from PIL import Image\n self.bo.mmap()\n if self.format.name == 'XR24':\n # didn't find an XRGB format\n self.image = Image.new(\"RGBX\", (self.width, self.height))\n else:\n raise ValueError(\"DrmImageFramebuffer does not support format '%s'\" % self.format.name)\n\n def flush(self, x1=None, y1=None, x2=None, y2=None):\n # FIXME: Revisit and see if this can be sped up and support big endian\n # Convert RGBX -> Little Endian XRGB\n b = bytearray(self.image.tobytes())\n b[0::4], b[2::4] = b[2::4], b[0::4]\n self.bo.map[:] = str(b)\n super(DrmImageFramebuffer, self).flush(x1, y1, x2, y2)\n","new_contents":"from .format import DrmFormat\nfrom .framebuffer import DrmFramebuffer\nfrom .buffer import DrmDumbBuffer\n\n\nclass DrmImageFramebuffer(DrmFramebuffer):\n def __init__(self, drm=None, format_=None, width=None, height=None, bo=None):\n if drm and format_ and width and height and bo is None:\n bo = DrmDumbBuffer(drm, format_, width, height)\n elif (drm or format_ or width or height) and bo is None:\n raise TypeError()\n super(DrmImageFramebuffer, self).__init__(bo)\n self._setup()\n\n def _setup(self):\n from PIL import Image\n self.bo.mmap()\n if self.format.name == 'XR24':\n # didn't find an XRGB format\n self.image = Image.new(\"RGBX\", (self.width, self.height))\n else:\n raise ValueError(\"DrmImageFramebuffer does not support format '%s'\" % self.format.name)\n\n def flush(self, x1=None, y1=None, x2=None, y2=None):\n # FIXME: Revisit and see if this can be sped up and support big endian\n # Convert RGBX -> Little Endian XRGB\n b = bytearray(self.image.tobytes())\n b[0::4], b[2::4] = b[2::4], b[0::4]\n self.bo.map[:] = bytes(b)\n super(DrmImageFramebuffer, self).flush(x1, y1, x2, y2)\n","subject":"Write bytes object to mmap instead of string","message":"Write bytes object to mmap instead of string\n\nThis fixes compatibility with python3","lang":"Python","license":"mit","repos":"notro\/pydrm"} {"commit":"e75cba739b92a7209cee87f66d2c8c9df3f97799","old_file":"bumper_kilt\/scripts\/run_kilt.py","new_file":"bumper_kilt\/scripts\/run_kilt.py","old_contents":"#!\/usr\/bin\/python\nimport time\nimport serial\n\n# configure the serial connections (the parameters differs on the\n# device you are connecting to)\n\nclass Bumper(object):\n\n def __init__(self):\n try:\n self.ser = serial.Serial(\n port=\"\/dev\/ttyS0\",\n baudrate=9600,\n parity=serial.PARITY_ODD,\n stopbits=serial.STOPBITS_TWO,\n bytesize=serial.SEVENBITS\n )\n except Exception:\n print(\"Bad initialisation! Check the configuration of \"\n \"the serial port!\")\n exit()\n self.ser.open()\n self.ser.isOpen()\n\n def loop(self):\n input=1\n while 1 :\n # get keyboard input\n input = raw_input(\">> \")\n # Python 3 users\n # input = input(\">> \")\n if input == \"exit\":\n self.ser.close()\n exit()\n else:\n # send the character to the device\n # (note that I happend a \\r\\n carriage return and line feed to\n # the characters - this is requested by my device)\n self.ser.write(input + \"\\r\\n\")\n out = \"\"\n # let's wait one second before reading output (let's give\n # device time to answer)\n time.sleep(1)\n while self.ser.inWaiting() > 0:\n out += self.ser.read(1)\n\n if out != \"\":\n print \">> \" + out\n\n\ndef main():\n b = Bumper()\n b.loop()\n\n\n\nif __name__ == \"__main__\":\n main()\n","new_contents":"#!\/usr\/bin\/python\nimport time\nimport serial\n\n# configure the serial connections (the parameters differs on the\n# device you are connecting to)\n\nclass Bumper(object):\n\n def __init__(self):\n try:\n self.ser = serial.Serial(\n port=\"\/dev\/ttyS0\",\n baudrate=38400,\n parity=serial.PARITY_ODD,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS\n )\n except Exception:\n print(\"Bad initialisation! Check the configuration of \"\n \"the serial port!\")\n exit()\n self.ser.open()\n self.ser.isOpen()\n\n def loop(self):\n input=1\n while 1 :\n # get keyboard input\n input = raw_input(\">> \")\n # Python 3 users\n # input = input(\">> \")\n if input == \"exit\":\n self.ser.close()\n exit()\n else:\n # send the character to the device\n # (note that I happend a \\r\\n carriage return and line feed to\n # the characters - this is requested by my device)\n self.ser.write(input + \"\\r\\n\")\n out = \"\"\n # let's wait one second before reading output (let's give\n # device time to answer)\n time.sleep(1)\n while self.ser.inWaiting() > 0:\n out += self.ser.read(1)\n\n if out != \"\":\n print \">> \" + out\n\n\ndef main():\n b = Bumper()\n b.loop()\n\n\n\nif __name__ == \"__main__\":\n main()\n","subject":"Set parameters of serial class to match with kilt","message":"Set parameters of serial class to match with kilt\n","lang":"Python","license":"mit","repos":"ipab-rad\/rad_youbot_stack,ipab-rad\/rad_youbot_stack,ipab-rad\/rad_youbot_stack,ipab-rad\/rad_youbot_stack"} {"commit":"be03e3d6c1323e8c750afc1d4e80997f3d9d52f3","old_file":"cyder\/cydhcp\/interface\/dynamic_intr\/forms.py","new_file":"cyder\/cydhcp\/interface\/dynamic_intr\/forms.py","old_contents":"from django import forms\nfrom cyder.cydhcp.interface.dynamic_intr.models import (DynamicInterface,\n DynamicIntrKeyValue)\nfrom cyder.base.mixins import UsabilityFormMixin\nfrom cyder.cydhcp.forms import RangeWizard\n\n\nclass DynamicInterfaceForm(RangeWizard, UsabilityFormMixin):\n\n def __init__(self, *args, **kwargs):\n super(DynamicInterfaceForm, self).__init__(*args, **kwargs)\n self.fields.keyOrder = ['system', 'domain', 'mac', 'vrf',\n 'site', 'range', 'workgroup', 'dhcp_enabled',\n 'dns_enabled', 'ctnr']\n\n class Meta:\n model = DynamicInterface\n exclude = ('last_seen')\n\n\nclass DynamicIntrKeyValueForm(forms.ModelForm):\n dynamic_interface = forms.ModelChoiceField(\n queryset=DynamicInterface.objects.all(),\n widget=forms.HiddenInput())\n\n class Meta:\n model = DynamicIntrKeyValue\n exclude = ('is_option', 'is_statement', 'is_quoted',)\n","new_contents":"from django import forms\nfrom cyder.cydhcp.interface.dynamic_intr.models import (DynamicInterface,\n DynamicIntrKeyValue)\nfrom cyder.base.mixins import UsabilityFormMixin\nfrom cyder.cydhcp.forms import RangeWizard\n\n\nclass DynamicInterfaceForm(RangeWizard, UsabilityFormMixin):\n\n def __init__(self, *args, **kwargs):\n super(DynamicInterfaceForm, self).__init__(*args, **kwargs)\n self.fields.keyOrder = ['system', 'domain', 'mac', 'vrf',\n 'site', 'range', 'workgroup', 'dhcp_enabled',\n 'dns_enabled', 'ctnr']\n self.fields['range'].required = True\n\n class Meta:\n model = DynamicInterface\n exclude = ('last_seen')\n\n\nclass DynamicIntrKeyValueForm(forms.ModelForm):\n dynamic_interface = forms.ModelChoiceField(\n queryset=DynamicInterface.objects.all(),\n widget=forms.HiddenInput())\n\n class Meta:\n model = DynamicIntrKeyValue\n exclude = ('is_option', 'is_statement', 'is_quoted',)\n","subject":"Reset range to be required in dynamic intr form","message":"Reset range to be required in dynamic intr form\n","lang":"Python","license":"bsd-3-clause","repos":"akeym\/cyder,akeym\/cyder,OSU-Net\/cyder,akeym\/cyder,zeeman\/cyder,zeeman\/cyder,murrown\/cyder,OSU-Net\/cyder,drkitty\/cyder,drkitty\/cyder,zeeman\/cyder,murrown\/cyder,drkitty\/cyder,OSU-Net\/cyder,murrown\/cyder,akeym\/cyder,drkitty\/cyder,OSU-Net\/cyder,murrown\/cyder,zeeman\/cyder"} {"commit":"bda8f2a258023c14849119b6ac2856253e9c68b4","old_file":"herd-code\/herd-tools\/herd-content-loader\/herdcl\/logger.py","new_file":"herd-code\/herd-tools\/herd-content-loader\/herdcl\/logger.py","old_contents":"\"\"\"\n Copyright 2015 herd contributors\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n# Standard library imports\nimport logging, logging.handlers\nimport sys\n\n\ndef get_logger(name):\n \"\"\"\n Get logger to output to file and stdout\n\n :param name: name of module calling method\n :return: the logger\n \"\"\"\n\n log_format = logging.Formatter(\"%(asctime)s - %(module)s - Line %(lineno)d - %(levelname)s \\n%(message)s\",\n \"%Y-%m-%d %H:%M:%S\")\n\n log_handler = logging.handlers.RotatingFileHandler('debug.log', mode='a', maxBytes=1024 * 1024)\n log_handler.setFormatter(log_format)\n\n stream_handler = logging.StreamHandler(sys.stdout)\n stream_handler.setFormatter(log_format)\n\n logger = logging.getLogger(name)\n logger.setLevel(logging.INFO)\n logger.addHandler(log_handler)\n logger.addHandler(stream_handler)\n return logger\n","new_contents":"\"\"\"\n Copyright 2015 herd contributors\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n# Standard library imports\nimport logging, logging.handlers\nimport sys\n\n\ndef get_logger(name):\n \"\"\"\n Get logger to output to file and stdout\n\n :param name: name of module calling method\n :return: the logger\n \"\"\"\n\n log_format = logging.Formatter(\"%(asctime)s - %(module)s - Line %(lineno)d - %(levelname)s \\n%(message)s\",\n \"%Y-%m-%d %H:%M:%S\")\n\n log_handler = logging.handlers.RotatingFileHandler('debug.log', mode='a', maxBytes=50 * 1024, backupCount=1)\n log_handler.setFormatter(log_format)\n\n stream_handler = logging.StreamHandler(sys.stdout)\n stream_handler.setFormatter(log_format)\n\n logger = logging.getLogger(name)\n logger.setLevel(logging.INFO)\n logger.addHandler(log_handler)\n logger.addHandler(stream_handler)\n return logger\n","subject":"Manage Content Loader as Herd\/DM tool - Lower log size cap","message":"DM-12174: Manage Content Loader as Herd\/DM tool\n- Lower log size cap\n","lang":"Python","license":"apache-2.0","repos":"FINRAOS\/herd,FINRAOS\/herd,FINRAOS\/herd,FINRAOS\/herd,FINRAOS\/herd"} {"commit":"f67abceeae7716cd385a308b26ce447e0277518f","old_file":"tests\/git_wrapper_integration_tests.py","new_file":"tests\/git_wrapper_integration_tests.py","old_contents":"import unittest\nimport util\nfrom git_wrapper import GitWrapper\n\nclass GitWrapperIntegrationTest(util.RepoTestCase):\n def test_paths(self):\n self.open_tar_repo('project01')\n assert('test_file.txt' in self.repo.paths)\n assert('hello_world.rb' in self.repo.paths)\n\n def test_stage(self):\n self.open_tar_repo('project02')\n assert('not_committed_file.txt' in self.repo.stage)\n assert('second_not_committed_file.txt' in self.repo.stage)\n\n def test_paths_external_git_folder(self):\n self.open_tar_repo('project03', '..\/project03.git')\n assert('test_file.txt' in self.repo.paths)\n assert('hello_world.rb' in self.repo.paths)\n\n def test_stage_external_git_folder(self):\n self.open_tar_repo('project04', '..\/project04.git')\n assert('not_committed_file.txt' in self.repo.stage)\n assert('second_not_committed_file.txt' in self.repo.stage)\n","new_contents":"import unittest\nimport util\nfrom git_wrapper import GitWrapper\n\nclass GitWrapperIntegrationTest(util.RepoTestCase):\n def test_paths(self):\n self.open_tar_repo('project01')\n assert('test_file.txt' in self.repo.paths)\n assert('hello_world.rb' in self.repo.paths)\n\n def test_stage(self):\n self.open_tar_repo('project02')\n assert('not_committed_file.txt' in self.repo.stage)\n assert('second_not_committed_file.txt' in self.repo.stage)\n\nclass GitWrapperIntegrationTestExternalGitFolder(util.RepoTestCase):\n def test_paths_external(self):\n self.open_tar_repo('project03', '..\/project03.git')\n assert('test_file.txt' in self.repo.paths)\n assert('hello_world.rb' in self.repo.paths)\n\n def test_stage_external(self):\n self.open_tar_repo('project04', '..\/project04.git')\n assert('not_committed_file.txt' in self.repo.stage)\n assert('second_not_committed_file.txt' in self.repo.stage)\n","subject":"Move external git folder integration tests to a separate class","message":"Move external git folder integration tests to a separate class\n","lang":"Python","license":"mit","repos":"siu\/git_repo"} {"commit":"feef7985133241c5e11622b0932d3eb629e7fbfe","old_file":"craigschart\/craigschart.py","new_file":"craigschart\/craigschart.py","old_contents":"\ndef main():\n print('Hello, World.')\n\nif __name__ == '__main__':\n main()\n\n","new_contents":"from bs4 import BeautifulSoup\nimport requests\n\ndef get_html():\n r = requests.get('http:\/\/vancouver.craigslist.ca\/search\/cto?query=Expedition')\n print(r.status_code)\n print(r.text)\n return r.text\n\ndef main():\n html = get_html()\n\n soup = BeautifulSoup(html, 'lxml')\n print(soup.prettify())\n mydivs = soup.findAll('a', {'class': 'hdrlnk'})\n for t in mydivs:\n print(t)\n\n print('Hello, World.')\n\nif __name__ == '__main__':\n main()\n\n","subject":"Add soup extraction of links in results page","message":"Add soup extraction of links in results page\n","lang":"Python","license":"mit","repos":"supermitch\/craigschart"} {"commit":"8c6b4396047736d5caf00ec30b4283ee7cdc793e","old_file":"lighty\/wsgi\/decorators.py","new_file":"lighty\/wsgi\/decorators.py","old_contents":"'''\n'''\nimport functools\nimport operator\nfrom .. import monads\n\n\ndef view(func, **constraints):\n '''Functions that decorates a view. This function can also checks the\n argument values\n '''\n func.is_view = True\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n try:\n if not functools.reduce(operator.__and__,\n [constraints[arg](kwargs[arg])\n for arg in constraints]):\n return monads.NoneMonad(ValueError(\n 'Wrong view argument value'))\n return monads.ValueMonad(func(*args, **kwargs))\n except Exception as e:\n return monads.NoneMonad(e)\n return wrapper\n","new_contents":"'''\n'''\nimport functools\nimport operator\nfrom .. import monads\n\n\ndef view(func, **constraints):\n '''Functions that decorates a view. This function can also checks the\n argument values\n '''\n func.is_view = True\n @functools.wraps(func)\n @monads.handle_exception\n def wrapper(*args, **kwargs):\n if not functools.reduce(operator.__and__, \n [constraints[arg](kwargs[arg])\n for arg in constraints]):\n return monads.NoneMonad(ValueError('Wrong view argument value'))\n return monads.ValueMonad(func(*args, **kwargs))\n return wrapper\n","subject":"Use exception handling with decorator","message":"Use exception handling with decorator\n","lang":"Python","license":"bsd-3-clause","repos":"GrAndSE\/lighty"} {"commit":"7ef1717f34360ae48f640439fd6d6706ae755e90","old_file":"functional_tests\/base.py","new_file":"functional_tests\/base.py","old_contents":"from selenium import webdriver\n\nfrom django.contrib.staticfiles.testing import StaticLiveServerTestCase\nfrom django.core.cache import cache\n\n\nclass BrowserTest(StaticLiveServerTestCase):\n def setUp(self):\n self.browser = webdriver.PhantomJS()\n self.browser.set_window_size(1024, 768)\n\n def tearDown(self):\n self.browser.quit()\n cache.clear()\n","new_contents":"from selenium.webdriver.chrome.webdriver import WebDriver\nfrom selenium.webdriver.chrome.options import Options\nfrom django.contrib.staticfiles.testing import StaticLiveServerTestCase\nfrom django.core.cache import cache\n\n\nclass BrowserTest(StaticLiveServerTestCase):\n def setUp(self):\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--window-size=1920x1080\")\n self.browser = WebDriver(chrome_options=chrome_options)\n self.browser.set_window_size(1024, 768)\n\n def tearDown(self):\n self.browser.quit()\n cache.clear()\n","subject":"Use headless chrome for functional test","message":"Use headless chrome for functional test\n","lang":"Python","license":"mit","repos":"essanpupil\/cashflow,essanpupil\/cashflow"} {"commit":"9fdea42df37c722aefb5e8fb7c04c45c06c20f17","old_file":"tests\/test_client_users.py","new_file":"tests\/test_client_users.py","old_contents":"import pydle\nfrom .fixtures import with_client\nfrom .mocks import Mock\n\n\n@with_client()\ndef test_user_creation(server, client):\n client._create_user('WiZ')\n assert 'WiZ' in client.users\n assert client.users['WiZ']['nickname'] == 'WiZ'\n\n@with_client()\ndef test_user_renaming(server, client):\n client._create_user('WiZ')\n client._rename_user('WiZ', 'jilles')\n\n assert 'WiZ' not in client.users\n assert 'jilles' in client.users\n assert client.users['jilles']['nickname'] == 'jilles'\n\n@with_client()\ndef test_user_deletion(server, client):\n client._create_user('WiZ')\n client._destroy_user('WiZ')\n\n assert 'WiZ' not in client.users\n","new_contents":"import pydle\nfrom .fixtures import with_client\n\n\n@with_client()\ndef test_client_same_nick(server, client):\n assert client.is_same_nick('WiZ', 'WiZ')\n assert not client.is_same_nick('WiZ', 'jilles')\n assert not client.is_same_nick('WiZ', 'wiz')\n\n@with_client()\ndef test_user_creation(server, client):\n client._create_user('WiZ')\n assert 'WiZ' in client.users\n assert client.users['WiZ']['nickname'] == 'WiZ'\n\n@with_client()\ndef test_user_invalid_creation(server, client):\n client._create_user('irc.fbi.gov')\n assert 'irc.fbi.gov' not in client.users\n\n@with_client()\ndef test_user_renaming(server, client):\n client._create_user('WiZ')\n client._rename_user('WiZ', 'jilles')\n\n assert 'WiZ' not in client.users\n assert 'jilles' in client.users\n assert client.users['jilles']['nickname'] == 'jilles'\n\n@with_client()\ndef test_user_renaming_creation(server, client):\n client._rename_user('null', 'WiZ')\n\n assert 'WiZ' in client.users\n assert 'null' not in client.users\n\n@with_client()\ndef test_user_deletion(server, client):\n client._create_user('WiZ')\n client._destroy_user('WiZ')\n\n assert 'WiZ' not in client.users\n\n@with_client()\ndef test_user_synchronization(server, client):\n client._create_user('WiZ')\n client._sync_user('WiZ', { 'hostname': 'og.irc.developer' })\n\n assert client.users['WiZ']['hostname'] == 'og.irc.developer'\n\n@with_client()\ndef test_user_synchronization_creation(server, client):\n client._sync_user('WiZ', {})\n assert 'WiZ' in client.users\n\n@with_client()\ndef test_user_invalid_synchronization(server, client):\n client._sync_user('irc.fbi.gov', {})\n assert 'irc.fbi.gov' not in client.users\n","subject":"Extend client:users tests to renaming and synchronization.","message":"tests: Extend client:users tests to renaming and synchronization.\n","lang":"Python","license":"bsd-3-clause","repos":"Shizmob\/pydle"} {"commit":"b5fc673d44624dfddfbdd98c9806b7e7e2f67331","old_file":"simplekv\/memory\/memcachestore.py","new_file":"simplekv\/memory\/memcachestore.py","old_contents":"#!\/usr\/bin\/env python\n# coding=utf8\n\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\nfrom .. import KeyValueStore\n\n\nclass MemcacheStore(KeyValueStore):\n def __contains__(self, key):\n try:\n return key in self.mc\n except TypeError:\n raise IOError('memcache implementation does not support '\\\n '__contains__')\n\n def __init__(self, mc):\n self.mc = mc\n\n def _delete(self, key):\n self.mc.delete(key)\n\n def _get(self, key):\n rv = self.mc.get(key)\n if None == rv:\n raise KeyError(key)\n return rv\n\n def _get_file(self, key, file):\n file.write(self._get(key))\n\n def _open(self, key):\n return StringIO(self._get(key))\n\n def _put(self, key, data):\n self.mc.set(key, data)\n return key\n\n def _put_file(self, key, file):\n self.mc.set(key, file.read())\n return key\n\n def keys(self):\n raise IOError('Memcache does not support listing keys.')\n\n def iter_keys(self):\n raise IOError('Memcache does not support key iteration.')\n","new_contents":"#!\/usr\/bin\/env python\n# coding=utf8\n\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\nfrom .. import KeyValueStore\n\n\nclass MemcacheStore(KeyValueStore):\n def __contains__(self, key):\n try:\n return key in self.mc\n except TypeError:\n raise IOError('memcache implementation does not support '\\\n '__contains__')\n\n def __init__(self, mc):\n self.mc = mc\n\n def _delete(self, key):\n if not self.mc.delete(key):\n raise IOError('Error deleting key')\n\n def _get(self, key):\n rv = self.mc.get(key)\n if None == rv:\n raise KeyError(key)\n return rv\n\n def _get_file(self, key, file):\n file.write(self._get(key))\n\n def _open(self, key):\n return StringIO(self._get(key))\n\n def _put(self, key, data):\n if not self.mc.set(key, data):\n if len(data) >= 1024 * 1023:\n raise IOError('Failed to store data, probably too large. '\\\n 'memcached limit is 1M')\n raise IOError('Failed to store data')\n return key\n\n def _put_file(self, key, file):\n return self._put(key, file.read())\n\n def keys(self):\n raise IOError('Memcache does not support listing keys.')\n\n def iter_keys(self):\n raise IOError('Memcache does not support key iteration.')\n","subject":"Check if putting\/getting was actually successful.","message":"Check if putting\/getting was actually successful.\n","lang":"Python","license":"mit","repos":"fmarczin\/simplekv,fmarczin\/simplekv,karteek\/simplekv,mbr\/simplekv,karteek\/simplekv,mbr\/simplekv"} {"commit":"67710f78677c4ad2737504d9815154c8e9f3bb18","old_file":"django_prometheus\/utils.py","new_file":"django_prometheus\/utils.py","old_contents":"import time\nfrom prometheus_client import _INF\n\n# TODO(korfuri): if python>3.3, use perf_counter() or monotonic().\n\n\ndef Time():\n \"\"\"Returns some representation of the current time.\n\n This wrapper is meant to take advantage of a higher time\n resolution when available. Thus, its return value should be\n treated as an opaque object. It can be compared to the current\n time with TimeSince().\n \"\"\"\n return time.time()\n\n\ndef TimeSince(t):\n \"\"\"Compares a value returned by Time() to the current time.\n\n Returns:\n the time since t, in fractional seconds.\n \"\"\"\n return time.time() - t\n\n\ndef PowersOf(logbase, count, lower=0, include_zero=True):\n \"\"\"Returns a list of count powers of logbase (from logbase**lower).\"\"\"\n if not include_zero:\n return [logbase ** i for i in range(lower, count)] + [_INF]\n else:\n return [0] + [logbase ** i for i in range(lower, count)] + [_INF]\n","new_contents":"import time\nfrom prometheus_client import _INF\n\n# TODO(korfuri): if python>3.3, use perf_counter() or monotonic().\n\n\ndef Time():\n \"\"\"Returns some representation of the current time.\n\n This wrapper is meant to take advantage of a higher time\n resolution when available. Thus, its return value should be\n treated as an opaque object. It can be compared to the current\n time with TimeSince().\n \"\"\"\n return time.time()\n\n\ndef TimeSince(t):\n \"\"\"Compares a value returned by Time() to the current time.\n\n Returns:\n the time since t, in fractional seconds.\n \"\"\"\n return time.time() - t\n\n\ndef PowersOf(logbase, count, lower=0, include_zero=True):\n \"\"\"Returns a list of count powers of logbase (from logbase**lower).\"\"\"\n if not include_zero:\n return [logbase ** i for i in range(lower, count+lower)] + [_INF]\n else:\n return [0] + [logbase ** i for i in range(lower, count+lower)] + [_INF]\n","subject":"Fix PowersOf to return `count` items, not \"numbers up to base**count\".","message":"Fix PowersOf to return `count` items, not \"numbers up to base**count\".\n","lang":"Python","license":"apache-2.0","repos":"obytes\/django-prometheus,wangwanzhong\/django-prometheus,wangwanzhong\/django-prometheus,korfuri\/django-prometheus,obytes\/django-prometheus,korfuri\/django-prometheus,DingaGa\/django-prometheus,DingaGa\/django-prometheus"} {"commit":"ef576a884bd4155fbc8bec8615c25544e74b98c3","old_file":"samsungctl\/__init__.py","new_file":"samsungctl\/__init__.py","old_contents":"\"\"\"Remote control Samsung televisions via TCP\/IP connection\"\"\"\n\nfrom .remote import Remote\n\n__title__ = \"samsungctl\"\n__version__ = \"0.6.0-git\"\n__url__ = \"https:\/\/github.com\/Ape\/samsungctl\"\n__author__ = \"Lauri Niskanen\"\n__author_email__ = \"ape@ape3000.com\"\n__license__ = \"MIT\"\n","new_contents":"\"\"\"Remote control Samsung televisions via TCP\/IP connection\"\"\"\n\nfrom .remote import Remote\n\n__title__ = \"samsungctl\"\n__version__ = \"0.6.0+1\"\n__url__ = \"https:\/\/github.com\/Ape\/samsungctl\"\n__author__ = \"Lauri Niskanen\"\n__author_email__ = \"ape@ape3000.com\"\n__license__ = \"MIT\"\n","subject":"Use PEP 440 compatible local version identifier","message":"Use PEP 440 compatible local version identifier\n","lang":"Python","license":"mit","repos":"Ape\/samsungctl"} {"commit":"c037b0a9ef8424737b978dda0400a1c31d5cb300","old_file":"app\/state.py","new_file":"app\/state.py","old_contents":"import multiprocessing\nimport unicornhat\nimport importlib\nimport sys\nimport os\n\n\nclass State:\n ''' Handles the Unicorn HAT state'''\n\n def __init__(self):\n self.process = None\n\n def start_program(self, name, params={}):\n self.stop_program()\n\n if \"brightness\" in params:\n unicornhat.brightness(float(params[\"brightness\"]))\n\n if \"rotation\" in params:\n unicornhat.rotation(int(params[\"rotation\"]))\n\n program = importlib.import_module(\"app.programs.\" + name)\n self.process = multiprocessing.Process(target=program.run, args=(params,))\n self.process.start()\n\n def stop_program(self):\n if self.process is not None:\n self.process.terminate()\n unicornhat.show()\n\n\nstate = State()","new_contents":"import multiprocessing\nimport unicornhat\nimport importlib\nimport sys\nimport os\n\n\nclass State:\n ''' Handles the Unicorn HAT state'''\n\n def __init__(self):\n self._process = None\n\n def start_program(self, name, params={}):\n self.stop_program()\n\n if \"brightness\" in params:\n unicornhat.brightness(float(params[\"brightness\"]))\n\n if \"rotation\" in params:\n unicornhat.rotation(int(params[\"rotation\"]))\n\n program = importlib.import_module(\"app.programs.\" + name)\n self._process = multiprocessing.Process(target=program.run, args=(params,))\n self._process.start()\n\n def stop_program(self):\n if self._process is not None:\n self._process.terminate()\n unicornhat.show()\n\n\nstate = State()","subject":"Mark process member variable for internal use","message":"Mark process member variable for internal use\n","lang":"Python","license":"mit","repos":"njbbaer\/unicorn-remote,njbbaer\/unicorn-remote,njbbaer\/unicorn-remote"} {"commit":"f4c99f4a1b3e49e0768af1b4b6444ee33bef49ac","old_file":"microauth\/urls.py","new_file":"microauth\/urls.py","old_contents":"\"\"\"microauth URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https:\/\/docs.djangoproject.com\/en\/1.9\/topics\/http\/urls\/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog\/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nurlpatterns = [\n url(r'^admin\/', admin.site.urls),\n\n # django-oauth-toolkit\n url(r'^oauth2\/', include('oauth2_provider.urls', namespace='oauth2_provider')),\n url(r'^', include('apps.authentication.urls', namespace='microauth_authentication')),\n url(r'^api\/', include('apps.api.urls', namespace='microauth_api')),\n]\n\nurlpatterns += staticfiles_urlpatterns()\n","new_contents":"\"\"\"microauth URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https:\/\/docs.djangoproject.com\/en\/1.9\/topics\/http\/urls\/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog\/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nurlpatterns = [\n url(r'^admin\/', admin.site.urls),\n\n # django-oauth-toolkit\n url(r'^oauth2\/', include('oauth2_provider.urls', namespace='oauth2_provider')),\n url(r'^', include('apps.authentication.urls', namespace='microauth_authentication')),\n url(r'^api\/', include('apps.api.urls', namespace='microauth_api')),\n url(r'^accounts\/login\/$', 'django.contrib.auth.views.login', {'template_name': 'admin\/login.html'}),\n\n]\n\nurlpatterns += staticfiles_urlpatterns()\n","subject":"Add a missing route leading to the login page.","message":"Add a missing route leading to the login page.\n","lang":"Python","license":"mit","repos":"microserv\/microauth,microserv\/microauth,microserv\/microauth"} {"commit":"49f332149ae8a9a3b5faf82bc20b46dfaeb0a3ad","old_file":"indra\/sources\/ctd\/api.py","new_file":"indra\/sources\/ctd\/api.py","old_contents":"import pandas\nfrom .processor import CTDChemicalDiseaseProcessor, \\\n CTDGeneDiseaseProcessor, CTDChemicalGeneProcessor\n\nbase_url = 'http:\/\/ctdbase.org\/reports\/'\n\nurls = {\n 'chemical_gene': base_url + 'CTD_chem_gene_ixns.tsv.gz',\n 'chemical_disease': base_url + 'CTD_chemicals_diseases.tsv.gz',\n 'gene_disease': base_url + 'CTD_genes_diseases.tsv.gz',\n}\n\nprocessors = {\n 'chemical_gene': CTDChemicalGeneProcessor,\n 'chemical_disease': CTDChemicalDiseaseProcessor,\n 'gene_disease': CTDGeneDiseaseProcessor,\n}\n\n\ndef process_from_web(subset):\n if subset not in urls:\n raise ValueError('%s is not a valid CTD subset.')\n df = pandas.read_csv(urls[subset], sep='\\t', comment='#',\n header=None)\n return process_dataframe(df)\n\n\ndef process_tsv(fname, subset):\n df = pandas.read_csv(fname, sep='\\t', comment='#', header=None)\n return process_dataframe(df, subset)\n\n\ndef process_dataframe(df, subset):\n if subset not in processors:\n raise ValueError('%s is not a valid CTD subset.')\n cp = processors[subset](df)\n cp.extract_statements()\n return cp\n","new_contents":"import pandas\nfrom .processor import CTDChemicalDiseaseProcessor, \\\n CTDGeneDiseaseProcessor, CTDChemicalGeneProcessor\n\nbase_url = 'http:\/\/ctdbase.org\/reports\/'\n\nurls = {\n 'chemical_gene': base_url + 'CTD_chem_gene_ixns.tsv.gz',\n 'chemical_disease': base_url + 'CTD_chemicals_diseases.tsv.gz',\n 'gene_disease': base_url + 'CTD_genes_diseases.tsv.gz',\n}\n\nprocessors = {\n 'chemical_gene': CTDChemicalGeneProcessor,\n 'chemical_disease': CTDChemicalDiseaseProcessor,\n 'gene_disease': CTDGeneDiseaseProcessor,\n}\n\n\ndef process_from_web(subset, url=None):\n if subset not in urls:\n raise ValueError('%s is not a valid CTD subset.' % subset)\n url = url if url else urls[subset]\n return _process_url_or_file(url, subset)\n\n\ndef process_tsv(fname, subset):\n return _process_url_or_file(fname, subset)\n\n\ndef _process_url_or_file(path, subset):\n df = pandas.read_csv(path, sep='\\t', comment='#',\n header=None, dtype=str, keep_default_na=False)\n return process_dataframe(df, subset)\n\n\ndef process_dataframe(df, subset):\n if subset not in processors:\n raise ValueError('%s is not a valid CTD subset.' % subset)\n cp = processors[subset](df)\n cp.extract_statements()\n return cp\n","subject":"Refactor API to have single pandas load","message":"Refactor API to have single pandas load\n","lang":"Python","license":"bsd-2-clause","repos":"sorgerlab\/indra,bgyori\/indra,johnbachman\/indra,bgyori\/indra,sorgerlab\/belpy,sorgerlab\/belpy,johnbachman\/belpy,bgyori\/indra,johnbachman\/indra,sorgerlab\/belpy,johnbachman\/belpy,johnbachman\/indra,johnbachman\/belpy,sorgerlab\/indra,sorgerlab\/indra"} {"commit":"d7e0fd7027f4a4a5024d136c0ab96b244d761c99","old_file":"pucas\/__init__.py","new_file":"pucas\/__init__.py","old_contents":"default_app_config = 'pucas.apps.PucasConfig'\n\n__version_info__ = (0, 5, 1, None)\n\n# Dot-connect all but the last. Last is dash-connected if not None.\n__version__ = '.'.join([str(i) for i in __version_info__[:-1]])\nif __version_info__[-1] is not None:\n __version__ += ('-%s' % (__version_info__[-1],))\n","new_contents":"default_app_config = 'pucas.apps.PucasConfig'\n\n__version_info__ = (0, 6, 0, 'dev')\n\n# Dot-connect all but the last. Last is dash-connected if not None.\n__version__ = '.'.join([str(i) for i in __version_info__[:-1]])\nif __version_info__[-1] is not None:\n __version__ += ('-%s' % (__version_info__[-1],))\n","subject":"Set develop version back to 0.6-dev","message":"Set develop version back to 0.6-dev\n","lang":"Python","license":"apache-2.0","repos":"Princeton-CDH\/django-pucas,Princeton-CDH\/django-pucas"} {"commit":"71cdbeada7e11634e1168ca2e825167cbe87b4de","old_file":"spacy\/lang\/de\/norm_exceptions.py","new_file":"spacy\/lang\/de\/norm_exceptions.py","old_contents":"# coding: utf8\nfrom __future__ import unicode_literals\n\n# Here we only want to include the absolute most common words. Otherwise,\n# this list would get impossibly long for German – especially considering the\n# old vs. new spelling rules, and all possible cases.\n\n\n_exc = {\n \"daß\": \"dass\"\n}\n\n\nNORM_EXCEPTIONS = {}\n\nfor string, norm in _exc.items():\n NORM_EXCEPTIONS[string] = norm\n NORM_EXCEPTIONS[string.title()] = norm\n","new_contents":"# coding: utf8\nfrom __future__ import unicode_literals\n\n# Here we only want to include the absolute most common words. Otherwise,\n# this list would get impossibly long for German – especially considering the\n# old vs. new spelling rules, and all possible cases.\n\n\n_exc = {\n \"daß\": \"dass\"\n}\n\n\nNORM_EXCEPTIONS = {}\n\nfor string, norm in _exc.items():\n NORM_EXCEPTIONS[string.title()] = norm\n","subject":"Revert \"Also include lowercase norm exceptions\"","message":"Revert \"Also include lowercase norm exceptions\"\n\nThis reverts commit 70f4e8adf37cfcfab60be2b97d6deae949b30e9e.\n","lang":"Python","license":"mit","repos":"aikramer2\/spaCy,spacy-io\/spaCy,aikramer2\/spaCy,recognai\/spaCy,honnibal\/spaCy,spacy-io\/spaCy,aikramer2\/spaCy,recognai\/spaCy,aikramer2\/spaCy,honnibal\/spaCy,aikramer2\/spaCy,spacy-io\/spaCy,honnibal\/spaCy,explosion\/spaCy,spacy-io\/spaCy,honnibal\/spaCy,explosion\/spaCy,spacy-io\/spaCy,recognai\/spaCy,aikramer2\/spaCy,recognai\/spaCy,recognai\/spaCy,spacy-io\/spaCy,explosion\/spaCy,explosion\/spaCy,recognai\/spaCy,explosion\/spaCy,explosion\/spaCy"} {"commit":"a3689129e2938dd7f2213ea11ac36a854cc0a31e","old_file":"test\/test_jarvis.py","new_file":"test\/test_jarvis.py","old_contents":"import unittest\nfrom collections import namedtuple\n# TODO: Move this code to a module so we don't depend on PYTHONPATH and that sort\n# of ugliness.\nfrom jarvis import convert_file_to_json, get_tags\n\nJarvisSettings = namedtuple('JarvisSettings', ['tags_directory'])\n\nclass TestJarvis(unittest.TestCase):\n\n def setUp(self):\n with open('fixtures\/test_log.md', 'r') as f:\n self.test_log = f.read()\n\n self.js = JarvisSettings('fixtures\/tags')\n\n def test_convert_log(self):\n try:\n j = convert_file_to_json(self.test_log)\n # Version 0.2.0\n expected_keys = sorted(['version', 'created', 'body', 'tags',\n 'occurred', 'author'])\n actual_keys = sorted(j.keys())\n self.assertListEqual(expected_keys, actual_keys)\n except Exception as e:\n self.fail(\"Unexpected error while parsing test_log\")\n\n def test_get_tags(self):\n expected_tags = ['TestA', 'TestB&C']\n actual_tags = get_tags(self.js)\n self.assertListEqual(expected_tags, actual_tags)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n To run:\n export PYTHONPATH=\"$HOME\/oz\/workspace\/Jarvis\/bin\"\n\n python -m unittest test_jarvis.py\n \"\"\"\n unittest.main()\n","new_contents":"import unittest\nfrom collections import namedtuple\n# TODO: Move this code to a module so we don't depend on PYTHONPATH and that sort\n# of ugliness.\nfrom jarvis import convert_file_to_json, get_tags\n\nJarvisSettings = namedtuple('JarvisSettings', ['tags_directory'])\n\nclass TestJarvis(unittest.TestCase):\n\n def setUp(self):\n with open('fixtures\/test_log.md', 'r') as f:\n self.test_log = f.read()\n\n self.js = JarvisSettings('fixtures\/tags')\n\n def test_convert_file_to_json(self):\n try:\n j = convert_file_to_json(self.test_log)\n # Version 0.2.0\n expected_keys = sorted(['version', 'created', 'body', 'tags',\n 'occurred', 'author'])\n actual_keys = sorted(j.keys())\n self.assertListEqual(expected_keys, actual_keys)\n except Exception as e:\n self.fail(\"Unexpected error while parsing test_log\")\n\n def test_get_tags(self):\n expected_tags = ['TestA', 'TestB&C']\n actual_tags = get_tags(self.js)\n self.assertListEqual(expected_tags, actual_tags)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n To run:\n export PYTHONPATH=\"$HOME\/oz\/workspace\/Jarvis\/bin\"\n\n python -m unittest test_jarvis.py\n \"\"\"\n unittest.main()\n","subject":"Change test method name to better match","message":"Change test method name to better match\n","lang":"Python","license":"apache-2.0","repos":"clb6\/jarvis-cli"} {"commit":"346f726a12078e7667ef32808feda0618f568839","old_file":"lino_extjs6\/projects\/mysite\/settings\/demo.py","new_file":"lino_extjs6\/projects\/mysite\/settings\/demo.py","old_contents":"import datetime\n\nfrom lino_extjs6.projects.mysite.settings import *\n\n\nclass Site(Site):\n project_name = 'extjs_demo'\n is_demo_site = True\n # ignore_dates_after = datetime.date(2019, 05, 22)\n the_demo_date = datetime.date(2015, 03, 12)\n\nSITE = Site(globals())\n\nSECRET_KEY = \"1234\"\n# ALLOWED_HOSTS = ['*']\nDEBUG = True\n","new_contents":"import datetime\n\nfrom lino_extjs6.projects.mysite.settings import *\n\n\nclass Site(Site):\n project_name = 'extjs_demo'\n is_demo_site = True\n # ignore_dates_after = datetime.date(2019, 05, 22)\n the_demo_date = datetime.date(2015, 3, 12)\n\nSITE = Site(globals())\n\nSECRET_KEY = \"1234\"\n# ALLOWED_HOSTS = ['*']\nDEBUG = True\n","subject":"Add support to Py3 for datetime","message":"Add support to Py3 for datetime\n","lang":"Python","license":"agpl-3.0","repos":"lino-framework\/extjs6,lsaffre\/lino_extjs6,lsaffre\/lino_extjs6,lsaffre\/lino_extjs6,lsaffre\/lino_extjs6,lino-framework\/extjs6,lsaffre\/lino_extjs6,lino-framework\/extjs6"} {"commit":"f5c74e6869b54bf6d16bb8493d3c76e9fb65bec5","old_file":"createdb.py","new_file":"createdb.py","old_contents":"#!\/usr\/bin\/env python\nimport sys\n\nimport fedmsg.config\nimport fmn.lib.models\n\nconfig = fedmsg.config.load_config()\nuri = config.get('fmn.sqlalchemy.uri')\nif not uri:\n raise ValueError(\"fmn.sqlalchemy.uri must be present\")\n\nif '-h' in sys.argv or '--help'in sys.argv:\n print \"createdb.py [--with-dev-data]\"\n sys.exit(0)\n\nsession = fmn.lib.models.init(uri, debug=True, create=True)\n\nif '--with-dev-data' in sys.argv:\n context1 = fmn.lib.models.Context.create(\n session, name=\"irc\", description=\"Internet Relay Chat\",\n detail_name=\"irc nick\", icon=\"user\",\n placeholder=\"z3r0_c00l\",\n )\n context2 = fmn.lib.models.Context.create(\n session, name=\"email\", description=\"Electronic Mail\",\n detail_name=\"email address\", icon=\"envelope\",\n placeholder=\"jane@fedoraproject.org\",\n )\n context3 = fmn.lib.models.Context.create(\n session, name=\"android\", description=\"Google Cloud Messaging\",\n detail_name=\"registration id\", icon=\"phone\",\n placeholder=\"laksdjfasdlfkj183097falkfj109f\"\n )\n session.commit()\n","new_contents":"#!\/usr\/bin\/env python\nimport sys\n\nimport fedmsg.config\nimport fmn.lib.models\n\nconfig = fedmsg.config.load_config()\nuri = config.get('fmn.sqlalchemy.uri')\nif not uri:\n raise ValueError(\"fmn.sqlalchemy.uri must be present\")\n\nif '-h' in sys.argv or '--help'in sys.argv:\n print \"createdb.py [--with-dev-data]\"\n sys.exit(0)\n\nsession = fmn.lib.models.init(uri, debug=True, create=True)\n\nif '--with-dev-data' in sys.argv:\n context1 = fmn.lib.models.Context.create(\n session, name=\"irc\", description=\"Internet Relay Chat\",\n detail_name=\"irc nick\", icon=\"user\",\n placeholder=\"z3r0_c00l\",\n )\n context2 = fmn.lib.models.Context.create(\n session, name=\"email\", description=\"Electronic Mail\",\n detail_name=\"email address\", icon=\"envelope\",\n placeholder=\"jane@fedoraproject.org\",\n )\n context3 = fmn.lib.models.Context.create(\n session, name=\"android\", description=\"Google Cloud Messaging\",\n detail_name=\"registration id\", icon=\"phone\",\n placeholder=\"laksdjfasdlfkj183097falkfj109f\"\n )\n context4 = fmn.lib.models.Context.create(\n session, name=\"desktop\", description=\"fedmsg-notify\",\n detail_name=\"None\", icon=\"console\",\n placeholder=\"There's no need to put a value here\"\n )\n session.commit()\n","subject":"Add the desktop context to the setup script.","message":"Add the desktop context to the setup script.\n","lang":"Python","license":"lgpl-2.1","repos":"jeremycline\/fmn,jeremycline\/fmn,jeremycline\/fmn"} {"commit":"e8795b5f45ea67c83f7e99c54b04e0dceb1fee34","old_file":"run-cron.py","new_file":"run-cron.py","old_contents":"#!\/usr\/bin\/env python\n\"\"\"Executes a Django cronjob\"\"\"\n\nimport os\n\n# Activate the virtualenv\npath = os.path.dirname(os.path.abspath( __file__ ))\nactivate_this = os.path.join(path, 'env\/bin\/activate_this.py')\nexecfile(activate_this, dict(__file__=activate_this))\n\nimport sys\nimport logging\nfrom django.core.management import setup_environ\nimport settings\n\nsetup_environ(settings)\n\nlogging.basicConfig(level=logging.DEBUG)\nlog = logging.getLogger('runcron')\n\ntry:\n mod = __import__(sys.argv[1])\nexcept ImportError:\n raise Exception('Error creating service')\n\nfor i in sys.argv[1].split(\".\")[1:]:\n mod = getattr(mod, i)\ncron_class = getattr(mod, sys.argv[2])()\n\nlog.info(\"Starting Job %s in %s\" % (sys.argv[2], sys.argv[1]))\n\n#try:\ncron_class.job()\n#except:\n# log.error(\"Error executing job, aborting.\")\n\nlog.info(\"Job complete\")\n","new_contents":"#!\/usr\/bin\/env python\n\"\"\"Executes a Django cronjob\"\"\"\n\nimport os\n\n# Activate the virtualenv\npath = os.path.dirname(os.path.abspath( __file__ ))\nos.chdir(path)\nactivate_this = os.path.join(path, 'env\/bin\/activate_this.py')\nexecfile(activate_this, dict(__file__=activate_this))\n\nimport sys\nimport logging\nfrom django.core.management import setup_environ\nimport settings\n\nsetup_environ(settings)\n\nlogging.basicConfig(level=logging.DEBUG)\nlog = logging.getLogger('runcron')\n\ntry:\n mod = __import__(sys.argv[1])\nexcept ImportError:\n raise Exception('Error creating service')\n\nfor i in sys.argv[1].split(\".\")[1:]:\n mod = getattr(mod, i)\ncron_class = getattr(mod, sys.argv[2])()\n\nlog.info(\"Starting Job %s in %s\" % (sys.argv[2], sys.argv[1]))\n\n#try:\ncron_class.job()\n#except:\n# log.error(\"Error executing job, aborting.\")\n\nlog.info(\"Job complete\")\n","subject":"Change to the root directory before executing (stops Mumble ICE file errors)","message":"Change to the root directory before executing (stops Mumble ICE file errors)\n\nThis was causing the SSO job to fail, thanks for psu3d0 for pointing it out.\n","lang":"Python","license":"bsd-3-clause","repos":"nikdoof\/test-auth"} {"commit":"cd944a2606159c8ea11ffe8075ce4ec186fd799c","old_file":"tests\/basic_test.py","new_file":"tests\/basic_test.py","old_contents":"import unittest\nfrom either_or import either_or\n\nclass nxppyTests(unittest.TestCase):\n \"\"\"Basic tests for the NXP Read Library python wrapper.\"\"\"\n\n def test_import(self):\n \"\"\"Test that it can be imported\"\"\"\n import nxppy\n\n @either_or('detect')\n def test_detect_mifare_present(self):\n \"\"\"Test that we can read the UID from a present Mifare card.\n \n Either this test or the \"absent\" test below will pass, but never both.\n \"\"\"\n import nxppy\n self.assertIsInstance(nxppy.read_mifare(), str, \"Card UID is not a string\")\n\n @either_or('detect')\n def test_detect_mifare_absent(self):\n \"\"\"Test that an absent card results in a None response.\n \n Either this test or the \"present\" test above will pass, but never both.\n \"\"\"\n import nxppy\n self.assertIsNone(nxppy.read_mifare(), \"Card UID is not None\")\n","new_contents":"import unittest\nfrom tests.either_or import either_or\n\nclass nxppyTests(unittest.TestCase):\n \"\"\"Basic tests for the NXP Read Library python wrapper.\"\"\"\n\n def test_import(self):\n \"\"\"Test that it can be imported\"\"\"\n import nxppy\n\n @either_or('detect')\n def test_detect_mifare_present(self):\n \"\"\"Test that we can read the UID from a present Mifare card.\n \n Either this test or the \"absent\" test below will pass, but never both.\n \"\"\"\n import nxppy\n reader = nxppy.Mifare()\n self.assertIsInstance(reader, nxppy.Mifare)\n self.assertIsInstance(reader.select(), str, \"Card UID is not a string\")\n\n @either_or('detect')\n def test_detect_mifare_absent(self):\n \"\"\"Test that an absent card results in a None response.\n \n Either this test or the \"present\" test above will pass, but never both.\n \"\"\"\n import nxppy\n reader = nxppy.Mifare()\n self.assertIsInstance(reader, nxppy.Mifare)\n self.assertIsNone(reader.select(), \"Card UID is not None\")\n","subject":"Update tests to use class-based interface","message":"Update tests to use class-based interface\n","lang":"Python","license":"mit","repos":"AlterCodex\/nxppy,Schoberm\/nxppy,AlterCodex\/nxppy,tuvaergun\/nxppy,Schoberm\/nxppy,tuvaergun\/nxppy,Schoberm\/nxppy,tuvaergun\/nxppy,AlterCodex\/nxppy"} {"commit":"eb03de241f3d47173381ee22f85b5cdf5d9c1fb4","old_file":"examples\/monitoring\/worker.py","new_file":"examples\/monitoring\/worker.py","old_contents":"import random\nimport time\nfrom os import getenv\n\nfrom aiographite.aiographite import connect\nfrom aiographite.protocol import PlaintextProtocol\n\nGRAPHITE_HOST = getenv('GRAPHITE_HOST', 'localhost')\n\n\nasync def run(worker, *args, **kwargs):\n value = random.randrange(10)\n try:\n \tconnection = await connect(GRAPHITE_HOST, 2003, PlaintextProtocol(), loop=worker.loop)\n \tawait connection.send('workers.worker', value, time.time())\n \tawait connection.close()\n except Exception as e:\n \tworker.logger.error('Cannot connect to graphite')\n","new_contents":"import random\nimport time\nfrom os import getenv\n\nfrom aiographite.aiographite import connect\nfrom aiographite.protocol import PlaintextProtocol\n\nGRAPHITE_HOST = getenv('GRAPHITE_HOST', 'localhost')\n\n\nasync def run(worker, *args, **kwargs):\n value = random.randrange(10)\n try:\n connection = await connect(GRAPHITE_HOST, 2003, PlaintextProtocol(), loop=worker.loop)\n await connection.send('workers.worker', value, time.time())\n await connection.close()\n except Exception:\n worker.logger.error('Cannot connect to graphite')\n","subject":"Fix flake8 issues in examples","message":"Fix flake8 issues in examples\n","lang":"Python","license":"apache-2.0","repos":"aioworkers\/aioworkers"} {"commit":"d799b3fdf6365fb54f0a1553b9a68c4334dd5482","old_file":"examples\/project_one\/input.py","new_file":"examples\/project_one\/input.py","old_contents":"","new_contents":"def read_file(filename):\n # Open the file\n file_obj = open(filename)\n\n # Iterate over lines in the file\n for line in file_obj:\n\n # Split line by spaces (creates a list)\n # Alternatives: split(',')\n numbers = line.split()\n\n if len(numbers) != 2:\n # Convert strings to numbers\n\n numbers2 = []\n for number in numbers:\n # Convert number to float\n number = float(number)\n\n # Append to temperary list\n numbers2.append(number)\n\n # Replace numbers by numbers2\n numbers = numbers2\n\n else:\n # We're processing a header\n print 'Skipping header line'\n\n return contents\n\n# Just for debugging purposes\nread_file('data.txt')\n","subject":"Convert list, for later reference.","message":"Convert list, for later reference.\n","lang":"Python","license":"mit","repos":"dokterbob\/slf-programming-workshops,dokterbob\/slf-programming-workshops,dokterbob\/slf-programming-workshops,dokterbob\/slf-programming-workshops"} {"commit":"8396ac44d434a06c410c516b6109ec6ace030601","old_file":"examples\/pyuv_cffi_example.py","new_file":"examples\/pyuv_cffi_example.py","old_contents":"\"\"\"A simple example demonstrating basic usage of pyuv_cffi\n\nThis example creates a timer handle and a signal handle, then starts the loop. The timer callback is\nrun after 1 second, and repeating every 1 second thereafter. The signal handle registers a listener\nfor the INT signal and allows us to exit the loop by pressing ctrl-c.\n\"\"\"\nimport signal\n\nfrom pyuv_cffi import Loop, Timer, Signal\n\n\ndef sig_cb(sig_h, sig_num):\n print('\\nsig_cb({}, {})'.format(sig_h, sig_num))\n sig_h.stop()\n sig_h.loop.stop()\n\n\ndef timer_cb(timer_h):\n print('timer_cb({})'.format(timer_h))\n\n\ndef run():\n loop = Loop()\n\n timer_h = Timer(loop)\n timer_h.start(timer_cb, 1, 1)\n\n sig_h = Signal(loop)\n sig_h.start(sig_cb, signal.SIGINT)\n\n status = loop.run()\n\n timer_h.close() # stop and free any timers before freeing the loop\n print('loop.run() -> ', status)\n\n\ndef main():\n run()\n\n\nif __name__ == '__main__':\n main()\n","new_contents":"\"\"\"A simple example demonstrating basic usage of pyuv_cffi\n\nThis example creates a timer handle and a signal handle, then starts the loop. The timer callback is\nrun after 1 second, and repeating every 1 second thereafter. The signal handle registers a listener\nfor the INT signal and allows us to exit the loop by pressing ctrl-c.\n\"\"\"\nimport signal\n\nfrom pyuv_cffi import Loop, Timer, Signal\n\n\ndef sig_cb(sig_h, sig_num):\n print('\\nsig_cb({}, {})'.format(sig_h, sig_num))\n sig_h.stop()\n sig_h.loop.stop()\n\n\ndef timer_cb(timer_h):\n print('timer_cb({})'.format(timer_h))\n\n\ndef run():\n loop = Loop()\n\n timer_h = Timer(loop)\n timer_h.start(timer_cb, 1, 1)\n\n sig_h = Signal(loop)\n sig_h.start(sig_cb, signal.SIGINT)\n\n status = loop.run()\n\n timer_h.close() # we must stop and free any other handles before freeing the loop\n print('loop.run() -> ', status)\n\n # all handles in pyuv_cffi (including the loop) are automatically freed when they go out of\n # scope\n\n\ndef main():\n run()\n\n\nif __name__ == '__main__':\n main()\n","subject":"Add inline comment regarding freeing resources","message":"Add inline comment regarding freeing resources\n","lang":"Python","license":"mit","repos":"veegee\/guv,veegee\/guv"} {"commit":"c28ae7e4b0637a2c4db120d9add13d5589ddca40","old_file":"runtests.py","new_file":"runtests.py","old_contents":"#!\/usr\/bin\/env python\nimport os\nimport sys\n\n\ndef runtests():\n test_dir = os.path.dirname(__file__)\n sys.path.insert(0, test_dir)\n os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'\n\n import django\n from django.test.utils import get_runner\n from django.conf import settings\n\n try:\n django.setup()\n except AttributeError: # 1.6 or lower\n pass\n\n TestRunner = get_runner(settings)\n test_runner = TestRunner(verbosity=1, interactive=True)\n failures = test_runner.run_tests(['.'])\n sys.exit(failures)\n\n\nif __name__ == '__main__':\n runtests()\n","new_contents":"#!\/usr\/bin\/env python\nimport os\nimport sys\n\n\ndef runtests():\n test_dir = os.path.dirname(__file__)\n sys.path.insert(0, test_dir)\n os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'\n\n import django\n from django.test.utils import get_runner\n from django.conf import settings\n\n django.setup()\n\n TestRunner = get_runner(settings)\n test_runner = TestRunner(verbosity=1, interactive=True)\n failures = test_runner.run_tests(['.'])\n sys.exit(failures)\n\n\nif __name__ == '__main__':\n runtests()\n","subject":"Remove compat shim as it doesn't apply","message":"Remove compat shim as it doesn't apply\n","lang":"Python","license":"mit","repos":"sergei-maertens\/django-systemjs,sergei-maertens\/django-systemjs,sergei-maertens\/django-systemjs,sergei-maertens\/django-systemjs"} {"commit":"0dddfcbdb46ac91ddc0bfed4482bce049a8593c2","old_file":"lazyblacksmith\/views\/blueprint.py","new_file":"lazyblacksmith\/views\/blueprint.py","old_contents":"# -*- encoding: utf-8 -*-\nfrom flask import Blueprint\nfrom flask import render_template\n\nfrom lazyblacksmith.models import Activity\nfrom lazyblacksmith.models import Item\nfrom lazyblacksmith.models import Region\n\nblueprint = Blueprint('blueprint', __name__)\n\n\n@blueprint.route('\/manufacturing\/')\ndef manufacturing(item_id):\n \"\"\"\n Display the manufacturing page with all data\n \"\"\"\n item = Item.query.get(item_id)\n activity = item.activities.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()\n materials = item.activity_materials.filter_by(activity=Activity.ACTIVITY_MANUFACTURING)\n product = item.activity_products.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()\n regions = Region.query.filter_by(wh=False)\n\n # is any of the materials manufactured ?\n has_manufactured_components = False\n\n for material in materials:\n if material.material.is_manufactured():\n has_manufactured_components = True\n break\n\n return render_template('blueprint\/manufacturing.html', **{\n 'blueprint': item,\n 'materials': materials,\n 'activity': activity,\n 'product': product,\n 'regions': regions,\n 'has_manufactured_components': has_manufactured_components,\n })\n\n\n@blueprint.route('\/')\ndef search():\n return render_template('blueprint\/search.html')\n","new_contents":"# -*- encoding: utf-8 -*-\nimport config\n\nfrom flask import Blueprint\nfrom flask import render_template\nfrom lazyblacksmith.models import Activity\nfrom lazyblacksmith.models import Item\nfrom lazyblacksmith.models import Region\n\nblueprint = Blueprint('blueprint', __name__)\n\n\n@blueprint.route('\/manufacturing\/')\ndef manufacturing(item_id):\n \"\"\"\n Display the manufacturing page with all data\n \"\"\"\n item = Item.query.get(item_id)\n activity = item.activities.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()\n materials = item.activity_materials.filter_by(activity=Activity.ACTIVITY_MANUFACTURING)\n product = item.activity_products.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()\n regions = Region.query.filter(\n Region.id.in_(config.CREST_REGION_PRICE)\n ).filter_by(\n wh=False\n )\n\n # is any of the materials manufactured ?\n has_manufactured_components = False\n\n for material in materials:\n if material.material.is_manufactured():\n has_manufactured_components = True\n break\n\n return render_template('blueprint\/manufacturing.html', **{\n 'blueprint': item,\n 'materials': materials,\n 'activity': activity,\n 'product': product,\n 'regions': regions,\n 'has_manufactured_components': has_manufactured_components,\n })\n\n\n@blueprint.route('\/')\ndef search():\n return render_template('blueprint\/search.html')\n","subject":"Change region list to match config","message":"Change region list to match config\n","lang":"Python","license":"bsd-3-clause","repos":"Kyria\/LazyBlacksmith,Kyria\/LazyBlacksmith,Kyria\/LazyBlacksmith,Kyria\/LazyBlacksmith"} {"commit":"b097a538ab4da1812ac73fe2d7f63fab6b351e5c","old_file":"fastapi\/__init__.py","new_file":"fastapi\/__init__.py","old_contents":"\"\"\"FastAPI framework, high performance, easy to learn, fast to code, ready for production\"\"\"\n\n__version__ = \"0.1.11\"\n\nfrom .applications import FastAPI\nfrom .routing import APIRouter\nfrom .params import Body, Path, Query, Header, Cookie, Form, File, Security, Depends\n","new_contents":"\"\"\"FastAPI framework, high performance, easy to learn, fast to code, ready for production\"\"\"\n\n__version__ = \"0.1.12\"\n\nfrom .applications import FastAPI\nfrom .routing import APIRouter\nfrom .params import Body, Path, Query, Header, Cookie, Form, File, Security, Depends\n","subject":"Bump version, after fix for email_validator and docs","message":":bookmark: Bump version, after fix for email_validator and docs\n","lang":"Python","license":"mit","repos":"tiangolo\/fastapi,tiangolo\/fastapi,tiangolo\/fastapi"} {"commit":"563220ef19395201aed7f6392519f84db4ec7a77","old_file":"tests\/test_midas.py","new_file":"tests\/test_midas.py","old_contents":"import datetime\n\nfrom midas import mix\nfrom midas.midas import estimate, forecast\n\n\ndef test_estimate(gdp_data, farmpay_data):\n\n y, yl, x, yf, ylf, xf = mix.mix_freq(gdp_data.gdp, farmpay_data.farmpay, 3, 1, 1,\n start_date=datetime.datetime(1985, 1, 1),\n end_date=datetime.datetime(2009, 1, 1))\n\n res = estimate(y, yl, x)\n\n fc = forecast(xf, ylf, res)\n\n print(fc)\n\n assert False\n","new_contents":"import datetime\nimport numpy as np\n\nfrom midas import mix\nfrom midas.midas import estimate, forecast\n\n\ndef test_estimate(gdp_data, farmpay_data):\n\n y, yl, x, yf, ylf, xf = mix.mix_freq(gdp_data.gdp, farmpay_data.farmpay, 3, 1, 1,\n start_date=datetime.datetime(1985, 1, 1),\n end_date=datetime.datetime(2009, 1, 1))\n\n res = estimate(y, yl, x)\n\n fc = forecast(xf, ylf, res)\n\n print(fc)\n\n assert np.isclose(fc.loc['2011-04-01'][0], 1.336844, rtol=1e-6)\n","subject":"Add assertion for forecast test","message":"Add assertion for forecast test\n","lang":"Python","license":"mit","repos":"mikemull\/midaspy"} {"commit":"1f9a11640463df94166be8dffa824e57485154f8","old_file":"tests\/vaspy_test.py","new_file":"tests\/vaspy_test.py","old_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nimport unittest\n\nfrom arc_test import ArcTest\nfrom incar_test import InCarTest\nfrom oszicar_test import OsziCarTest\nfrom outcar_test import OutCarTest\nfrom xsd_test import XsdTest\nfrom xtd_test import XtdTest\nfrom poscar_test import PosCarTest\nfrom xyzfile_test import XyzFileTest\nfrom cif_test import CifFileTest\n\ndef suite():\n suite = unittest.TestSuite([\n unittest.TestLoader().loadTestsFromTestCase(ArcTest),\n unittest.TestLoader().loadTestsFromTestCase(InCarTest),\n unittest.TestLoader().loadTestsFromTestCase(OsziCarTest),\n unittest.TestLoader().loadTestsFromTestCase(OutCarTest),\n unittest.TestLoader().loadTestsFromTestCase(XsdTest),\n unittest.TestLoader().loadTestsFromTestCase(XtdTest),\n unittest.TestLoader().loadTestsFromTestCase(PosCarTest),\n unittest.TestLoader().loadTestsFromTestCase(XyzFileTest),\n unittest.TestLoader().loadTestsFromTestCase(CifFileTest),\n ])\n\n return suite\n\nif \"__main__\" == __name__:\n result = unittest.TextTestRunner(verbosity=2).run(suite())\n\n if result.errors or result.failures:\n raise ValueError(\"Get errors and failures.\")\n\n","new_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nimport unittest\n\nfrom arc_test import ArcTest\nfrom incar_test import InCarTest\nfrom oszicar_test import OsziCarTest\nfrom outcar_test import OutCarTest\nfrom xsd_test import XsdTest\nfrom xtd_test import XtdTest\nfrom poscar_test import PosCarTest\nfrom xyzfile_test import XyzFileTest\nfrom cif_test import CifFileTest\nfrom ani_test import AniFileTest\n\ndef suite():\n suite = unittest.TestSuite([\n unittest.TestLoader().loadTestsFromTestCase(ArcTest),\n unittest.TestLoader().loadTestsFromTestCase(InCarTest),\n unittest.TestLoader().loadTestsFromTestCase(OsziCarTest),\n unittest.TestLoader().loadTestsFromTestCase(OutCarTest),\n unittest.TestLoader().loadTestsFromTestCase(XsdTest),\n unittest.TestLoader().loadTestsFromTestCase(XtdTest),\n unittest.TestLoader().loadTestsFromTestCase(PosCarTest),\n unittest.TestLoader().loadTestsFromTestCase(XyzFileTest),\n unittest.TestLoader().loadTestsFromTestCase(CifFileTest),\n unittest.TestLoader().loadTestsFromTestCase(AniFileTest),\n ])\n\n return suite\n\nif \"__main__\" == __name__:\n result = unittest.TextTestRunner(verbosity=2).run(suite())\n\n if result.errors or result.failures:\n raise ValueError(\"Get errors and failures.\")\n\n","subject":"Add test for animation file.","message":"Add test for animation file.\n","lang":"Python","license":"mit","repos":"PytLab\/VASPy,PytLab\/VASPy"} {"commit":"b8a22c1dfe58802665231e8a82bb546bfd1dbbc8","old_file":"pybossa\/sentinel\/__init__.py","new_file":"pybossa\/sentinel\/__init__.py","old_contents":"from redis import sentinel\n\n\nclass Sentinel(object):\n\n def __init__(self, app=None):\n self.app = app\n if app is not None: # pragma: no cover\n self.init_app(app)\n\n def init_app(self, app):\n self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],\n socket_timeout=0.1)\n self.master = self.connection.master_for('mymaster')\n self.slave = self.connection.slave_for('mymaster')\n","new_contents":"from redis import sentinel\n\n\nclass Sentinel(object):\n\n def __init__(self, app=None):\n self.app = app\n if app is not None: # pragma: no cover\n self.init_app(app)\n\n def init_app(self, app):\n self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],\n socket_timeout=0.1)\n redis_db = app.config['REDIS_DB'] or 0\n print \"Redis db is \", redis_db\n self.master = self.connection.master_for('mymaster', db=redis_db)\n self.slave = self.connection.slave_for('mymaster', db=redis_db)\n","subject":"Use config redis database in sentinel connections","message":"Use config redis database in sentinel connections\n","lang":"Python","license":"agpl-3.0","repos":"inteligencia-coletiva-lsd\/pybossa,geotagx\/pybossa,jean\/pybossa,PyBossa\/pybossa,PyBossa\/pybossa,stefanhahmann\/pybossa,OpenNewsLabs\/pybossa,OpenNewsLabs\/pybossa,stefanhahmann\/pybossa,Scifabric\/pybossa,geotagx\/pybossa,jean\/pybossa,Scifabric\/pybossa,inteligencia-coletiva-lsd\/pybossa"} {"commit":"695dad10b6d27e2b45a7b98abad29b9d922b976f","old_file":"pylisp\/packet\/ip\/protocol.py","new_file":"pylisp\/packet\/ip\/protocol.py","old_contents":"'''\nCreated on 11 jan. 2013\n\n@author: sander\n'''\nfrom abc import abstractmethod, ABCMeta\n\n\nclass Protocol(object):\n __metaclass__ = ABCMeta\n\n header_type = None\n\n @abstractmethod\n def __init__(self, next_header=None, payload=''):\n '''\n Constructor\n '''\n self.next_header = next_header\n self.payload = payload\n\n def __repr__(self):\n # This works as long as we accept all properties as paramters in the\n # constructor\n params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]\n return '%s(%s)' % (self.__class__.__name__,\n ', '.join(params))\n\n @abstractmethod\n def sanitize(self):\n '''\n Check and optionally fix properties\n '''\n\n @classmethod\n @abstractmethod\n def from_bytes(cls, bitstream):\n '''\n Parse the given packet and update properties accordingly\n '''\n\n @abstractmethod\n def to_bytes(self):\n '''\n Create bytes from properties\n '''\n\n def __str__(self):\n return str(self.to_bytes())\n\n def __bytes__(self):\n return bytes(self.to_bytes())\n","new_contents":"'''\nCreated on 11 jan. 2013\n\n@author: sander\n'''\nfrom abc import abstractmethod, ABCMeta\n\n\nclass ProtocolElement(object):\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def __init__(self):\n '''\n Constructor\n '''\n\n def __repr__(self):\n # This works as long as we accept all properties as paramters in the\n # constructor\n params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]\n return '%s(%s)' % (self.__class__.__name__,\n ', '.join(params))\n\n def __str__(self):\n return str(self.to_bytes())\n\n def __bytes__(self):\n return self.to_bytes()\n\n @abstractmethod\n def sanitize(self):\n '''\n Check and optionally fix properties\n '''\n\n @classmethod\n @abstractmethod\n def from_bytes(cls, bitstream):\n '''\n Parse the given packet and update properties accordingly\n '''\n\n @abstractmethod\n def to_bytes(self):\n '''\n Create bytes from properties\n '''\n\n\nclass Protocol(ProtocolElement):\n __metaclass__ = ABCMeta\n\n header_type = None\n\n @abstractmethod\n def __init__(self, next_header=None, payload=''):\n '''\n Constructor\n '''\n super(Protocol, self).__init__()\n self.next_header = next_header\n self.payload = payload\n","subject":"Split Protocol class in Protocol and ProtocolElement","message":"Split Protocol class in Protocol and ProtocolElement\n","lang":"Python","license":"bsd-3-clause","repos":"steffann\/pylisp"} {"commit":"90d1a40175675b2950cb41b85434b522d6e21c4d","old_file":"mass\/cli.py","new_file":"mass\/cli.py","old_contents":"#!\/usr\/bin\/env python3\n# -*- coding: utf-8 -*-\n# vim: set hls is ai et sw=4 sts=4 ts=8 nu ft=python:\n\n# built-in modules\n\n# 3rd-party modules\nimport click\n\n# local modules\nfrom mass.monitor.app import app\nfrom mass.scheduler.swf import utils\nfrom mass.scheduler.swf import SWFWorker\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\ndef init():\n utils.register_domain()\n utils.register_workflow_type()\n utils.register_activity_type()\n\n\n@cli.group()\ndef worker():\n pass\n\n\n@cli.group()\ndef job():\n pass\n\n\n@cli.group()\ndef monitor():\n pass\n\n\n@worker.command('start')\ndef worker_start():\n worker = SWFWorker()\n worker.start()\n\n\n@job.command('submit')\n@click.option('-j', '--json', help='Job Description in JSON.')\n@click.option('-a', '--alfscript', help='Job Description in alfscript.')\ndef job_submit(json_script, alf_script):\n pass\n\n\n@monitor.command('start')\ndef monitor_start():\n monitor = app.run(debug=True)\n\ncli.add_command(init)\ncli.add_command(worker)\ncli.add_command(job)\ncli.add_command(monitor)\n","new_contents":"#!\/usr\/bin\/env python3\n# -*- coding: utf-8 -*-\n# vim: set hls is ai et sw=4 sts=4 ts=8 nu ft=python:\n\n# built-in modules\n\n# 3rd-party modules\nimport click\n\n# local modules\nfrom mass.monitor.app import app\nfrom mass.scheduler.swf import utils\nfrom mass.scheduler.swf import SWFWorker\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\n@click.option('-d', '--domain', help='Amazon SWF Domain.')\n@click.option('-r', '--region', help='Amazon Region.')\ndef init(domain, region):\n utils.register_domain(domain, region)\n utils.register_workflow_type(domain, region)\n utils.register_activity_type(domain, region)\n\n\n@cli.group()\ndef worker():\n pass\n\n\n@cli.group()\ndef job():\n pass\n\n\n@cli.group()\ndef monitor():\n pass\n\n\n@worker.command('start')\ndef worker_start():\n worker = SWFWorker()\n worker.start()\n\n\n@job.command('submit')\n@click.option('-j', '--json', help='Job Description in JSON.')\n@click.option('-a', '--alfscript', help='Job Description in alfscript.')\ndef job_submit(json_script, alf_script):\n pass\n\n\n@monitor.command('start')\ndef monitor_start():\n monitor = app.run(debug=True)\n\ncli.add_command(init)\ncli.add_command(worker)\ncli.add_command(job)\ncli.add_command(monitor)\n","subject":"Add arguments --domain and --region to mass init.","message":"Add arguments --domain and --region to mass init.\n","lang":"Python","license":"apache-2.0","repos":"badboy99tw\/mass,KKBOX\/mass,badboy99tw\/mass,badboy99tw\/mass,KKBOX\/mass,KKBOX\/mass"} {"commit":"75457e90381b6ff38becfed0befe214c9d6c0fc1","old_file":"skyscanner\/__init__.py","new_file":"skyscanner\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\n__author__ = 'Ardy Dedase'\n__email__ = 'ardy.dedase@skyscanner.net'\n__version__ = '1.1.3'\n__copyright__ = \"Copyright (C) 2016 Skyscanner Ltd\"\n__license__ = \"\"\"\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\neither express or implied. See the License for the specific\nlanguage governing permissions and limitations under the License.\n\"\"\"\n","new_contents":"# -*- coding: utf-8 -*-\n__author__ = 'Ardy Dedase'\n__email__ = 'ardy.dedase@skyscanner.net'\n__version__ = '1.1.4'\n__copyright__ = \"Copyright (C) 2016 Skyscanner Ltd\"\n__license__ = \"\"\"\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\neither express or implied. See the License for the specific\nlanguage governing permissions and limitations under the License.\n\"\"\"\n","subject":"Include skyscanner version to be used by doc.","message":"Include skyscanner version to be used by doc.\n","lang":"Python","license":"apache-2.0","repos":"Skyscanner\/skyscanner-python-sdk"} {"commit":"a1c7773eb889ece3233b910c559b4e22ade3bb32","old_file":"timpani\/settings.py","new_file":"timpani\/settings.py","old_contents":"from . import database\n\ndef getAllSettings():\n\tdatabaseConnection = database.ConnectionManager.getConnection(\"main\")\n\tquery = databaseConnection.session.query(database.tables.Setting)\n\tsettings = query.all()\n\treturn {setting.name: setting.value for setting in settings}\n\ndef getSettingValue(name):\n\tdatabaseConnection = database.ConnectionManager.getConnection(\"main\")\n\tquery = (databaseConnection.session\n\t\t.query(database.tables.Setting)\n\t\t.filter(database.tables.Setting.name == name))\n\tif query.count() > 0:\n\t\treturn query.first().value\n\treturn None\n\ndef setSettingValue(name, value):\n\tdatabaseConnection = database.ConnectionManager.getConnection(\"main\")\n\tsettingObj = database.tables.Setting(name = name, value = value)\n\tdatabaseConnection.session.merge(settingObj)\n\tdatabaseConnection.session.commit()\ndef validateSetting(name, value):\n\tif name == \"title\":\n\t\treturn len(value) > 0\n","new_contents":"from . import database\n\ndef getAllSettings():\n\tdatabaseConnection = database.ConnectionManager.getConnection(\"main\")\n\tquery = databaseConnection.session.query(database.tables.Setting)\n\tsettings = query.all()\n\treturn {setting.name: setting.value for setting in settings}\n\ndef getSettingValue(name):\n\tdatabaseConnection = database.ConnectionManager.getConnection(\"main\")\n\tquery = (databaseConnection.session\n\t\t.query(database.tables.Setting)\n\t\t.filter(database.tables.Setting.name == name))\n\tif query.count() > 0:\n\t\treturn query.first().value\n\treturn None\n\ndef setSettingValue(name, value):\n\tvalid = validateSetting(name, value)\n\tif valid:\n\t\tdatabaseConnection = database.ConnectionManager.getConnection(\"main\")\n\t\tsettingObj = database.tables.Setting(name = name, value = value)\n\t\tdatabaseConnection.session.merge(settingObj)\n\t\tdatabaseConnection.session.commit()\n\t\treturn True\n\treturn False\n\ndef validateSetting(name, value):\n\tif name == \"title\":\n\t\treturn len(value) > 0\n","subject":"Use setting validation function in setSettingValue","message":"Use setting validation function in setSettingValue\n","lang":"Python","license":"mit","repos":"ollien\/Timpani,ollien\/Timpani,ollien\/Timpani"} {"commit":"d6224333a8c815086cf8f10b0bb9ee23f7aec3ef","old_file":"numpy\/fft\/info.py","new_file":"numpy\/fft\/info.py","old_contents":"\"\"\"\\\nCore FFT routines\n==================\n\n Standard FFTs\n\n fft\n ifft\n fft2\n ifft2\n fftn\n ifftn\n\n Real FFTs\n\n refft\n irefft\n refft2\n irefft2\n refftn\n irefftn\n\n Hermite FFTs\n\n hfft\n ihfft\n\"\"\"\n\ndepends = ['core']\n","new_contents":"\"\"\"\\\nCore FFT routines\n==================\n\n Standard FFTs\n\n fft\n ifft\n fft2\n ifft2\n fftn\n ifftn\n\n Real FFTs\n\n rfft\n irfft\n rfft2\n irfft2\n rfftn\n irfftn\n\n Hermite FFTs\n\n hfft\n ihfft\n\"\"\"\n\ndepends = ['core']\n","subject":"Fix documentation of fft sub-package to eliminate references to refft.","message":"Fix documentation of fft sub-package to eliminate references to refft.\n\ngit-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@3226 94b884b6-d6fd-0310-90d3-974f1d3f35e1\n","lang":"Python","license":"bsd-3-clause","repos":"illume\/numpy3k,Ademan\/NumPy-GSoC,jasonmccampbell\/numpy-refactor-sprint,jasonmccampbell\/numpy-refactor-sprint,illume\/numpy3k,illume\/numpy3k,chadnetzer\/numpy-gaurdro,teoliphant\/numpy-refactor,jasonmccampbell\/numpy-refactor-sprint,efiring\/numpy-work,efiring\/numpy-work,chadnetzer\/numpy-gaurdro,teoliphant\/numpy-refactor,efiring\/numpy-work,teoliphant\/numpy-refactor,Ademan\/NumPy-GSoC,teoliphant\/numpy-refactor,illume\/numpy3k,Ademan\/NumPy-GSoC,teoliphant\/numpy-refactor,efiring\/numpy-work,chadnetzer\/numpy-gaurdro,chadnetzer\/numpy-gaurdro,Ademan\/NumPy-GSoC,jasonmccampbell\/numpy-refactor-sprint"} {"commit":"ee99527185268ac386aad0c54056ac640c197e42","old_file":"dbmigrator\/commands\/init.py","new_file":"dbmigrator\/commands\/init.py","old_contents":"# -*- coding: utf-8 -*-\n# ###\n# Copyright (c) 2015, Rice University\n# This software is subject to the provisions of the GNU Affero General\n# Public License version 3 (AGPLv3).\n# See LICENCE.txt for details.\n# ###\n\nfrom .. import utils\n\n\n__all__ = ('cli_loader',)\n\n\n@utils.with_cursor\ndef cli_command(cursor, migrations_directory='', version=None, **kwargs):\n cursor.execute(\"\"\"\\\n CREATE TABLE IF NOT EXISTS schema_migrations (\n version TEXT NOT NULL,\n applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP\n )\"\"\")\n cursor.execute(\"\"\"\\\n DELETE FROM schema_migrations\"\"\")\n versions = []\n if version is None:\n timestamp = utils.timestamp()\n else:\n timestamp = str(version)\n for version, name in utils.get_migrations(migrations_directory):\n if version <= timestamp:\n versions.append((version,))\n cursor.executemany(\"\"\"\\\n INSERT INTO schema_migrations VALUES (%s)\n \"\"\", versions)\n print('Schema migrations initialized.')\n\n\ndef cli_loader(parser):\n parser.add_argument('--version', type=int,\n help='Set the schema version to VERSION, '\n 'default current timestamp')\n return cli_command\n","new_contents":"# -*- coding: utf-8 -*-\n# ###\n# Copyright (c) 2015, Rice University\n# This software is subject to the provisions of the GNU Affero General\n# Public License version 3 (AGPLv3).\n# See LICENCE.txt for details.\n# ###\n\nfrom .. import utils\n\n\n__all__ = ('cli_loader',)\n\n\n@utils.with_cursor\ndef cli_command(cursor, migrations_directory='', version=None, **kwargs):\n cursor.execute(\"\"\"\\\n SELECT 1 FROM information_schema.tables\n WHERE table_name = 'schema_migrations'\"\"\")\n table_exists = cursor.fetchone()\n if table_exists:\n print('Schema migrations already initialized.')\n return\n\n cursor.execute(\"\"\"\\\n CREATE TABLE schema_migrations (\n version TEXT NOT NULL,\n applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP\n )\"\"\")\n versions = []\n if version is None:\n timestamp = utils.timestamp()\n else:\n timestamp = str(version)\n for version, name in utils.get_migrations(migrations_directory):\n if version <= timestamp:\n versions.append((version,))\n cursor.executemany(\"\"\"\\\n INSERT INTO schema_migrations VALUES (%s)\n \"\"\", versions)\n print('Schema migrations initialized.')\n\n\ndef cli_loader(parser):\n parser.add_argument('--version', type=int,\n help='Set the schema version to VERSION, '\n 'default current timestamp')\n return cli_command\n","subject":"Stop changing schema_migrations data if the table already exists","message":"Stop changing schema_migrations data if the table already exists\n","lang":"Python","license":"agpl-3.0","repos":"karenc\/db-migrator"} {"commit":"30f03692eff862f1456b9c376c21fe8e57de7eaa","old_file":"dbt\/clients\/agate_helper.py","new_file":"dbt\/clients\/agate_helper.py","old_contents":"\nimport agate\n\nDEFAULT_TYPE_TESTER = agate.TypeTester(types=[\n agate.data_types.Number(),\n agate.data_types.Date(),\n agate.data_types.DateTime(),\n agate.data_types.Boolean(),\n agate.data_types.Text()\n])\n\n\ndef table_from_data(data, column_names):\n \"Convert list of dictionaries into an Agate table\"\n\n # The agate table is generated from a list of dicts, so the column order\n # from `data` is not preserved. We can use `select` to reorder the columns\n #\n # If there is no data, create an empty table with the specified columns\n\n if len(data) == 0:\n return agate.Table([], column_names=column_names)\n else:\n table = agate.Table.from_object(data, column_types=DEFAULT_TYPE_TESTER)\n return table.select(column_names)\n\n\ndef empty_table():\n \"Returns an empty Agate table. To be used in place of None\"\n\n return agate.Table(rows=[])\n\n\ndef as_matrix(table):\n \"Return an agate table as a matrix of data sans columns\"\n\n return [r.values() for r in table.rows.values()]\n\n\ndef from_csv(abspath):\n return agate.Table.from_csv(abspath, column_types=DEFAULT_TYPE_TESTER)\n","new_contents":"\nimport agate\n\nDEFAULT_TYPE_TESTER = agate.TypeTester(types=[\n agate.data_types.Boolean(true_values=('true',),\n false_values=('false',),\n null_values=('null',)),\n agate.data_types.Number(null_values=('null',)),\n agate.data_types.TimeDelta(null_values=('null',)),\n agate.data_types.Date(null_values=('null',)),\n agate.data_types.DateTime(null_values=('null',)),\n agate.data_types.Text(null_values=('null',))\n])\n\n\ndef table_from_data(data, column_names):\n \"Convert list of dictionaries into an Agate table\"\n\n # The agate table is generated from a list of dicts, so the column order\n # from `data` is not preserved. We can use `select` to reorder the columns\n #\n # If there is no data, create an empty table with the specified columns\n\n if len(data) == 0:\n return agate.Table([], column_names=column_names)\n else:\n table = agate.Table.from_object(data, column_types=DEFAULT_TYPE_TESTER)\n return table.select(column_names)\n\n\ndef empty_table():\n \"Returns an empty Agate table. To be used in place of None\"\n\n return agate.Table(rows=[])\n\n\ndef as_matrix(table):\n \"Return an agate table as a matrix of data sans columns\"\n\n return [r.values() for r in table.rows.values()]\n\n\ndef from_csv(abspath):\n return agate.Table.from_csv(abspath, column_types=DEFAULT_TYPE_TESTER)\n","subject":"Make the agate table type tester more restrictive on what counts as null\/true\/false","message":"Make the agate table type tester more restrictive on what counts as null\/true\/false\n","lang":"Python","license":"apache-2.0","repos":"analyst-collective\/dbt,nave91\/dbt,nave91\/dbt,fishtown-analytics\/dbt,fishtown-analytics\/dbt,fishtown-analytics\/dbt,analyst-collective\/dbt"} {"commit":"52fa6cff088e2032fc8a3a9d732bf8affb9bccae","old_file":"config\/template.py","new_file":"config\/template.py","old_contents":"DB_USER = ''\nDB_HOST = ''\nDB_PASSWORD = ''\nDB_NAME = ''\n","new_contents":"DB_USER = ''\nDB_HOST = ''\nDB_PASSWORD = ''\nDB_NAME = ''\n\nTWILIO_NUMBERS = ['']\n","subject":"Allow for representative view display with sample configuration","message":"Allow for representative view display with sample configuration\n","lang":"Python","license":"mit","repos":"AKVorrat\/ueberwachungspaket.at,AKVorrat\/ueberwachungspaket.at,AKVorrat\/ueberwachungspaket.at"} {"commit":"068862dc72fa82ec35e7fabc6a0a99dc10f7f034","old_file":"octavia\/common\/service.py","new_file":"octavia\/common\/service.py","old_contents":"# Copyright 2014 Rackspace\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom oslo_config import cfg\nfrom oslo_log import log\n\nfrom octavia.common import config\nfrom octavia.i18n import _LI\n\nLOG = log.getLogger(__name__)\n\n\ndef prepare_service(argv=None):\n \"\"\"Sets global config from config file and sets up logging.\"\"\"\n argv = argv or []\n config.init(argv[1:])\n LOG.info(_LI('Starting Octavia API server'))\n log.set_defaults()\n config.setup_logging(cfg.CONF)\n","new_contents":"# Copyright 2014 Rackspace\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom oslo_config import cfg\nfrom oslo_log import log\n\nfrom octavia.common import config\n\nLOG = log.getLogger(__name__)\n\n\ndef prepare_service(argv=None):\n \"\"\"Sets global config from config file and sets up logging.\"\"\"\n argv = argv or []\n config.init(argv[1:])\n log.set_defaults()\n config.setup_logging(cfg.CONF)\n","subject":"Remove bad INFO log \"Starting Octavia API server\"","message":"Remove bad INFO log \"Starting Octavia API server\"\n\nThis log is also display for health_manager and house_keeping service.\nApi service already display \"Starting API server on...\" in INFO level.\n\nChange-Id: I0a3ff91b556accdfadbad797488d17ae7a95d85b\n","lang":"Python","license":"apache-2.0","repos":"openstack\/octavia,openstack\/octavia,openstack\/octavia"} {"commit":"d568e040293da3438293fb007a762fd35b8c7483","old_file":"extras\/client.py","new_file":"extras\/client.py","old_contents":"import os\nfrom email.utils import formatdate\nfrom datetime import datetime\nfrom time import mktime\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keybar.settings')\n\nimport django\ndjango.setup()\n\nfrom django.conf import settings\nfrom httpsig.requests_auth import HTTPSignatureAuth\nimport requests\n\nfrom keybar.models.user import User\n\n# TODO: Use a secret RSA key as secret.\nsecret = open('example_keys\/private_key.pem', 'rb').read()\nuser = User.objects.get(username='admin')\n\nsignature_headers = ['(request-target)', 'accept', 'date', 'host']\n\nnow = datetime.now()\nstamp = mktime(now.timetuple())\n\nheaders = {\n 'Host': 'keybar.local:8443',\n 'Method': 'GET',\n 'Path': '\/api\/v1\/users\/',\n 'Accept': 'application\/json',\n 'X-Api-Key': user.api_key.hex,\n 'Date': formatdate(timeval=stamp, localtime=False, usegmt=True)\n}\n\nauth = HTTPSignatureAuth(\n key_id=user.api_key.hex,\n secret=secret,\n headers=signature_headers,\n algorithm='hmac-sha256')\n\nresponse = requests.get(\n 'https:\/\/keybar.local:8443\/api\/v1\/users\/',\n auth=auth,\n headers=headers,\n verify=settings.KEYBAR_CA_BUNDLE)\n\nprint(response.content)\n","new_contents":"import os\nfrom email.utils import formatdate\nfrom datetime import datetime\nfrom time import mktime\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keybar.settings')\n\nimport django\ndjango.setup()\n\nfrom django.conf import settings\nfrom httpsig.requests_auth import HTTPSignatureAuth\nimport requests\n\nfrom keybar.models.user import User\n\n# TODO: Use a secret RSA key as secret.\nsecret = open('extras\/example_keys\/private_key.pem', 'rb').read()\nuser = User.objects.get(username='admin')\n\nsignature_headers = ['(request-target)', 'accept', 'date', 'host']\n\nnow = datetime.now()\nstamp = mktime(now.timetuple())\n\nheaders = {\n 'Host': 'keybar.local:8443',\n 'Method': 'GET',\n 'Path': '\/api\/v1\/users\/',\n 'Accept': 'application\/json',\n 'X-Api-Key': user.api_key.hex,\n 'Date': formatdate(timeval=stamp, localtime=False, usegmt=True)\n}\n\nauth = HTTPSignatureAuth(\n key_id=user.api_key.hex,\n secret=secret,\n headers=signature_headers,\n algorithm='rsa-sha256')\n\nresponse = requests.get(\n 'https:\/\/keybar.local:8443\/api\/v1\/users\/',\n auth=auth,\n headers=headers,\n verify=settings.KEYBAR_CA_BUNDLE)\n\nprint(response.content)\n","subject":"Fix path, use rsa-sha256 algorithm to actually use the rsa-base verification","message":"Fix path, use rsa-sha256 algorithm to actually use the rsa-base verification\n","lang":"Python","license":"bsd-3-clause","repos":"keybar\/keybar"} {"commit":"41c6b1820e8b23079d9098526854c9a60859d128","old_file":"gcloud_expenses\/test_views.py","new_file":"gcloud_expenses\/test_views.py","old_contents":"import unittest\n\n\nclass ViewTests(unittest.TestCase):\n def setUp(self):\n from pyramid import testing\n self.config = testing.setUp()\n\n def tearDown(self):\n from pyramid import testing\n testing.tearDown()\n\n def test_my_view(self):\n from pyramid import testing\n from .views import my_view\n request = testing.DummyRequest()\n info = my_view(request)\n self.assertEqual(info['project'], 'foo')\n","new_contents":"import unittest\n\n\nclass ViewTests(unittest.TestCase):\n def setUp(self):\n from pyramid import testing\n self.config = testing.setUp()\n\n def tearDown(self):\n from pyramid import testing\n testing.tearDown()\n\n def test_home_page(self):\n from pyramid import testing\n from .views import home_page\n request = testing.DummyRequest()\n info = home_page(request)\n self.assertEqual(info, {})\n","subject":"Fix test broken in rename.","message":"Fix test broken in rename.\n","lang":"Python","license":"apache-2.0","repos":"GoogleCloudPlatform\/google-cloud-python-expenses-demo,GoogleCloudPlatform\/google-cloud-python-expenses-demo"} {"commit":"4691e024986a24930c88646cf3a3ae95683dc880","old_file":"main.py","new_file":"main.py","old_contents":"\"\"\"pluss, a feed proxy for G+\"\"\"\nimport logging\n\nfrom pluss.app import app\n\n@app.before_first_request\ndef setup_logging():\n if not app.debug:\n # In production mode, add log handler to sys.stderr.\n handler = logging.StreamHandler()\n handler.setFormatter(logging.Formatter(\n \"%(asctime)s [%(process)d] [%(levelname)s] %(pathname)s:%(lineno)d %(message)s\",\n \"%Y-%m-%d %H:%M:%S\",\n ))\n app.logger.addHandler(handler)\n app.logger.setLevel(logging.WARNING)\n\nif __name__ == '__main__':\n app.run(host='pluss.aiiane.com', port=54321, debug=True)\n\n# vim: set ts=4 sts=4 sw=4 et:\n","new_contents":"\"\"\"pluss, a feed proxy for G+\"\"\"\nimport logging\n\nfrom pluss.app import app\nfrom werkzeug.contrib.fixers import ProxyFix\napp.wsgi_app = ProxyFix(app.wsgi_app)\n\n@app.before_first_request\ndef setup_logging():\n if not app.debug:\n # In production mode, add log handler to sys.stderr.\n handler = logging.StreamHandler()\n handler.setFormatter(logging.Formatter(\n \"%(asctime)s [%(process)d] [%(levelname)s] %(pathname)s:%(lineno)d %(message)s\",\n \"%Y-%m-%d %H:%M:%S\",\n ))\n app.logger.addHandler(handler)\n app.logger.setLevel(logging.WARNING)\n\nif __name__ == '__main__':\n app.run(host='pluss.aiiane.com', port=54321, debug=True)\n\n# vim: set ts=4 sts=4 sw=4 et:\n","subject":"Add proxyfix for X-Forwarded-For header","message":"Add proxyfix for X-Forwarded-For header\n","lang":"Python","license":"mit","repos":"ayust\/pluss,ayust\/pluss"} {"commit":"769c83564d5f2272837c2fbea6d781110b71b8ca","old_file":"main.py","new_file":"main.py","old_contents":"from sys import argv, stderr\nfrom drawer import *\nfrom kmeans import kmeans\n\n\ndef read_vectors(file_name):\n result = None\n with open(file_name, 'r') as f:\n vector_length = int(f.readline())\n vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))\n if all((len(x) == vector_length for x in vectors)):\n result = vectors\n return result\n\n\ndef main():\n vectors = read_vectors(argv[1])\n clusters_count = int(argv[2])\n if vectors:\n if len(vectors[0]) == 2:\n display_source(vectors)\n clusters = kmeans(vectors, clusters_count=clusters_count)\n display_result(vectors, clusters)\n else:\n print('Invalid input', file=stderr)\n\n\nif __name__ == '__main__':\n main()\n\n\n","new_contents":"from sys import argv, stderr\nfrom drawer import *\nfrom kmeans import kmeans\n\n\ndef read_vectors(file_name):\n result = None\n with open(file_name, 'r') as f:\n vector_length = int(f.readline())\n vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))\n if all((len(x) == vector_length for x in vectors)):\n result = vectors\n return result\n\n\ndef main():\n vectors = read_vectors(argv[1])\n clusters_count = int(argv[2])\n if vectors:\n clusters = kmeans(vectors, clusters_count=clusters_count)\n if len(vectors[0]) == 2:\n display_source(vectors)\n display_result(vectors, clusters)\n else:\n print('Invalid input', file=stderr)\n\n\nif __name__ == '__main__':\n main()\n\n\n","subject":"Fix trying to display result in case of not 2D vectors","message":"Fix trying to display result in case of not 2D vectors\n","lang":"Python","license":"mit","repos":"vanashimko\/k-means"} {"commit":"03430a5b0abbd051e878274a669edf5afaa656b3","old_file":"sc2\/helpers\/control_group.py","new_file":"sc2\/helpers\/control_group.py","old_contents":"class ControlGroup(set):\n def __init__(self, units):\n super().__init__({unit.tag for unit in units})\n\n def __hash__(self):\n return hash(tuple(sorted(list(self))))\n\n def select_units(self, units):\n return units.filter(lambda unit: unit.tag in self)\n\n def missing_unit_tags(self, units):\n return {t for t in self if units.find_by_tag(t) is None}\n\n @property\n def empty(self):\n return self.amount == 0\n","new_contents":"class ControlGroup(set):\n def __init__(self, units):\n super().__init__({unit.tag for unit in units})\n\n def __hash__(self):\n return hash(tuple(sorted(list(self))))\n\n def select_units(self, units):\n return units.filter(lambda unit: unit.tag in self)\n\n def missing_unit_tags(self, units):\n return {t for t in self if units.find_by_tag(t) is None}\n\n @property\n def empty(self):\n return self.amount == 0\n\n def add_unit(self, units):\n self.add(unit.tag)\n\n def add_units(self, units):\n for unit in units:\n self.add_unit(unit)\n\n def remove_unit(self, units):\n self.remove(unit.tag)\n\n def remove_units(self, units):\n for unit in units:\n self.remove(unit.tag)\n","subject":"Add modification operations to control groups","message":"Add modification operations to control groups\n","lang":"Python","license":"mit","repos":"Dentosal\/python-sc2"} {"commit":"6820de9ccdb7cc7263142108881cf98aab85adb1","old_file":"space-age\/space_age.py","new_file":"space-age\/space_age.py","old_contents":"# File: space_age.py\n# Purpose: Write a program that, given an age in seconds, calculates\n# how old someone is in terms of a given planet's solar years.\n# Programmer: Amal Shehu\n# Course: Exercism\n# Date: Saturday 17 September 2016, 06:09 PM\n\n\nclass SpaceAge(object):\n \"\"\"docstring for SpaceAge.\"\"\"\n def __init__(self, _seconds):\n self._seconds = _seconds\n\n def on_earth(self):\n return round((self._seconds \/ 31557600), 2)\n\n def on_mercury(self):\n return round((self._seconds \/ 31557600) * 0.240846, 2)\n\nobj = SpaceAge(1e6)\nprint (obj.on_earth())\nprint (obj.on_mercury())\n","new_contents":"# File: space_age.py\n# Purpose: Write a program that, given an age in seconds, calculates\n# how old someone is in terms of a given planet's solar years.\n# Programmer: Amal Shehu\n# Course: Exercism\n# Date: Saturday 17 September 2016, 06:09 PM\n\n\nclass SpaceAge(object):\n \"\"\"docstring for SpaceAge.\"\"\"\n def __init__(self, _seconds):\n self._seconds = _seconds\n\n def on_earth(self):\n return round((self._seconds \/ 31557600), 2)\n\n def on_mercury(self):\n planet = self.on_earth() * 0.2408467\n return planet\n\n def on_venus(self):\n planet = self.on_earth() * 0.61519726\n return planet\n def on_mars(self):\n planet = self.on_earth() * 1.8808158\n return planet\n\n def on_jupiter(self):\n planet = self.on_earth() * 11.862615\n return planet\n\n def on_saturn(self):\n planet = self.on_earth() * 29.447498\n return planet\n\n def on_uranus(self):\n planet = self.on_earth() * 84.016846\n return planet\n\n def on_neptune(self):\n planet = self.on_earth() * 164.79132\n return planet\n\n\nobj = SpaceAge(1e6)\nprint (obj.on_earth())\nprint (obj.on_mercury())\n","subject":"Add other planets age function","message":"Add other planets age function\n","lang":"Python","license":"mit","repos":"amalshehu\/exercism-python"} {"commit":"2b52549bf31eae58ddbeeaf7351305204ab8bb4f","old_file":"helpers\/python\/sqid\/config.py","new_file":"helpers\/python\/sqid\/config.py","old_contents":"DUMP_BASENAME = 'wikidata-{date}-all.json.gz'\nDUMP_LOCATION = '\/public\/dumps\/public\/wikidatawiki\/entities\/'\nDUMP_LINK = '\/data\/project\/sqid\/projects\/dumpfiles\/wikidatawiki\/json-{date}\/{date}.json.gz'\nGRID_SUBMIT = '\/usr\/bin\/jsub'\nGRID_MEMORY = '-mem'\nGRID_NAME = '-N'\nGRID_ONCE = '-once'\nDUMP_PROCESS_MEMORY = '20g'\nSTATISTICS_PROCESS_MEMORY = '2g'\nJAVA_BASEDIR = '\/data\/project\/sqid\/projects'\nJAR = 'org.wikidata.sqid.helper-0.10.0.jar'\nJAVA_MEMORY = '4g'\nJAVA_ARGS = ['-Xmx{memory}'.format(memory=JAVA_MEMORY),\n '-jar', JAR,\n '-a', 'sqid', '-n']\nRESULTS_LOCATION = '\/data\/project\/sqid\/projects\/results\/wikidatawiki-{date}'\nRESULTS_NAMES = ['classes.json', 'properties.json', 'statistics.json']\n","new_contents":"DUMP_BASENAME = 'wikidata-{date}-all.json.gz'\nDUMP_LOCATION = '\/public\/dumps\/public\/wikidatawiki\/entities\/'\nDUMP_LINK = '\/data\/project\/sqid\/projects\/dumpfiles\/wikidatawiki\/json-{date}\/{date}.json.gz'\nGRID_SUBMIT = '\/usr\/bin\/jsub'\nGRID_MEMORY = '-mem'\nGRID_NAME = '-N'\nGRID_ONCE = '-once'\nDUMP_PROCESS_MEMORY = '21g'\nSTATISTICS_PROCESS_MEMORY = '2g'\nJAVA_BASEDIR = '\/data\/project\/sqid\/projects'\nJAR = 'org.wikidata.sqid.helper-0.10.0.jar'\nJAVA_MEMORY = '5g'\nJAVA_ARGS = ['-Xmx{memory}'.format(memory=JAVA_MEMORY),\n '-jar', JAR,\n '-a', 'sqid', '-n']\nRESULTS_LOCATION = '\/data\/project\/sqid\/projects\/results\/wikidatawiki-{date}'\nRESULTS_NAMES = ['classes.json', 'properties.json', 'statistics.json']\n","subject":"Bump heap size in helper","message":"Bump heap size in helper\n","lang":"Python","license":"apache-2.0","repos":"Wikidata\/SQID,Wikidata\/SQID,Wikidata\/SQID,Wikidata\/SQID,Wikidata\/WikidataClassBrowser,Wikidata\/SQID,Wikidata\/WikidataClassBrowser,Wikidata\/SQID,Wikidata\/SQID,Wikidata\/WikidataClassBrowser"} {"commit":"eb2b91d30244fd44b45ffc21b963256150b59152","old_file":"frappe\/patches\/v11_0\/reload_and_rename_view_log.py","new_file":"frappe\/patches\/v11_0\/reload_and_rename_view_log.py","old_contents":"import frappe\n\ndef execute():\n\tif frappe.db.exists('DocType', 'View log'):\n\t\tfrappe.reload_doc('core', 'doctype', 'view_log', force=True)\n\t\tfrappe.db.sql(\"INSERT INTO `tabView Log` SELECT * from `tabView log`\")\n\t\tfrappe.delete_doc('DocType', 'View log')\n\t\tfrappe.reload_doc('core', 'doctype', 'view_log', force=True)\n\telse:\n\t\tfrappe.reload_doc('core', 'doctype', 'view_log')\n","new_contents":"import frappe\n\ndef execute():\n\tif frappe.db.exists('DocType', 'View log'):\n\t\t# for mac users direct renaming would not work since mysql for mac saves table name in lower case\n\t\t# so while renaming `tabView log` to `tabView Log` we get \"Table 'tabView Log' already exists\" error\n\t\t# more info https:\/\/stackoverflow.com\/a\/44753093\/5955589 ,\n\t\t# https:\/\/dev.mysql.com\/doc\/refman\/8.0\/en\/server-system-variables.html#sysvar_lower_case_table_names\n\n\t\t# here we are creating a temp table to store view log data\n\t\tfrappe.db.sql(\"CREATE TABLE `ViewLogTemp` AS SELECT * FROM `tabView log`\")\n\n\t\t# deleting old View log table\n\t\tfrappe.db.sql(\"DROP table `tabView log`\")\n\t\tfrappe.delete_doc('DocType', 'View log')\n\n\t\t# reloading view log doctype to create `tabView Log` table\n\t\tfrappe.reload_doc('core', 'doctype', 'view_log')\n\t\tfrappe.db.commit()\n\n\t\t# Move the data to newly created `tabView Log` table\n\t\tfrappe.db.sql(\"INSERT INTO `tabView Log` SELECT * FROM `ViewLogTemp`\")\n\n\t\t# Delete temporary table\n\t\tfrappe.db.sql(\"DROP table `ViewLogTemp`\")\n\telse:\n\t\tfrappe.reload_doc('core', 'doctype', 'view_log')\n","subject":"Fix rename view log patch for mac users","message":"Fix rename view log patch for mac users\n\nfor mac users direct renaming would not work\nsince mysql for mac saves table name in lower case,\nso while renaming `tabView log` to `tabView Log` we get\n\"Table 'tabView Log' already exists\" error\n\n# more info https:\/\/stackoverflow.com\/a\/44753093\/5955589\nhttps:\/\/dev.mysql.com\/doc\/refman\/8.0\/en\/server-system-variables.html#sysvar_lower_case_table_names\n","lang":"Python","license":"mit","repos":"mhbu50\/frappe,yashodhank\/frappe,vjFaLk\/frappe,adityahase\/frappe,mhbu50\/frappe,almeidapaulopt\/frappe,saurabh6790\/frappe,adityahase\/frappe,vjFaLk\/frappe,yashodhank\/frappe,saurabh6790\/frappe,frappe\/frappe,frappe\/frappe,vjFaLk\/frappe,yashodhank\/frappe,almeidapaulopt\/frappe,almeidapaulopt\/frappe,StrellaGroup\/frappe,mhbu50\/frappe,StrellaGroup\/frappe,yashodhank\/frappe,vjFaLk\/frappe,mhbu50\/frappe,adityahase\/frappe,StrellaGroup\/frappe,almeidapaulopt\/frappe,saurabh6790\/frappe,frappe\/frappe,saurabh6790\/frappe,adityahase\/frappe"} {"commit":"53c39934e19fdad7926a8ad7833cd1737b47cf58","old_file":"utilities\/errors.py","new_file":"utilities\/errors.py","old_contents":"import os\nimport simulators\nimport numpy as np\nimport json\n\n\"\"\"Calculate Errors on the Spectrum.\n\n For a first go using an fixed SNR of 200 for all observations.\n\"\"\"\n\n\ndef get_snrinfo(star, obs_num, chip):\n \"\"\"Load SNR info from json file.\"\"\"\n snr_file = os.path.join(simulators.paths[\"spectra\"], \"detector_snrs.json\")\n with open(snr_file, \"r\") as f:\n snr_data = json.load(f)\n try:\n return snr_data[str(star)][str(obs_num)][str(chip)]\n except KeyError as e:\n print(\"No snr data present for {0}-{1}_{2}\".format(star, obs_num, chip))\n raise e\n\n\ndef spectrum_error(star, obs_num, chip, error_off=False):\n \"\"\"Return the spectrum error.\n\n errors = None will perform a normal chi**2 statistic.\n \"\"\"\n if error_off:\n errors = None\n else:\n snr = get_snrinfo(star, obs_num, chip)\n if len(snr) == 1:\n errors = 1 \/ np.float(snr[0])\n else:\n raise NotImplementedError(\"Haven't checked if an error array can be handled yet.\")\n return errors\n","new_contents":"import os\nimport simulators\nimport numpy as np\nimport json\nimport warnings\n\n\"\"\"Calculate Errors on the Spectrum.\n\n For a first go using an fixed SNR of 200 for all observations.\n\"\"\"\n\n\ndef get_snrinfo(star, obs_num, chip):\n \"\"\"Load SNR info from json file.\"\"\"\n snr_file = os.path.join(simulators.paths[\"spectra\"], \"detector_snrs.json\")\n with open(snr_file, \"r\") as f:\n snr_data = json.load(f)\n try:\n return snr_data[str(star)][str(obs_num)][str(chip)]\n except KeyError as e:\n warnings.warn(\"No snr data present for {0}-{1}_{2}. \"\n \"Setting error to None instead\".format(star, obs_num, chip))\n return None\n\n\ndef spectrum_error(star, obs_num, chip, error_off=False):\n \"\"\"Return the spectrum error.\n\n errors = None will perform a normal chi**2 statistic.\n \"\"\"\n if error_off:\n errors = None\n else:\n snr = get_snrinfo(star, obs_num, chip)\n if snr is None:\n errors = None\n elif len(snr) == 1:\n errors = 1 \/ np.float(snr[0])\n else:\n raise NotImplementedError(\"Haven't checked if an error array can be handled yet.\")\n return errors\n","subject":"Handle no snr information in snr file. (for fake simualtions mainly)","message":"Handle no snr information in snr file. (for fake simualtions mainly)\n","lang":"Python","license":"mit","repos":"jason-neal\/companion_simulations,jason-neal\/companion_simulations"} {"commit":"f1cabc889dd93e26295501097ac9cbf90890a1cd","old_file":"solvent\/config.py","new_file":"solvent\/config.py","old_contents":"import yaml\nimport os\n\nLOCAL_OSMOSIS = 'localhost:1010'\nOFFICIAL_OSMOSIS = None\nOFFICIAL_BUILD = False\nWITH_OFFICIAL_OBJECT_STORE = True\nCLEAN = False\n\n\ndef load(filename):\n with open(filename) as f:\n data = yaml.load(f.read())\n if data is None:\n raise Exception(\"Configuration file must not be empty\")\n globals().update(data)\n if 'SOLVENT_CONFIG' in os.environ:\n data = yaml.load(os.environ['SOLVENT_CONFIG'])\n globals().update(data)\n if 'SOLVENT_CLEAN' in os.environ:\n global CLEAN\n CLEAN = True\n if WITH_OFFICIAL_OBJECT_STORE and OFFICIAL_OSMOSIS is None:\n raise Exception(\"Configuration file must contain 'OFFICIAL_OSMOSIS' field\")\n\n\ndef objectStoresOsmosisParameter():\n if WITH_OFFICIAL_OBJECT_STORE:\n return LOCAL_OSMOSIS + \"+\" + OFFICIAL_OSMOSIS\n else:\n return LOCAL_OSMOSIS\n","new_contents":"import yaml\nimport os\n\nLOCAL_OSMOSIS_IF_ROOT = 'localhost:1010'\nLOCAL_OSMOSIS_IF_NOT_ROOT = 'localhost:1010'\nLOCAL_OSMOSIS = None\nOFFICIAL_OSMOSIS = None\nOFFICIAL_BUILD = False\nWITH_OFFICIAL_OBJECT_STORE = True\nCLEAN = False\n\n\ndef load(filename):\n with open(filename) as f:\n data = yaml.load(f.read())\n if data is None:\n raise Exception(\"Configuration file must not be empty\")\n globals().update(data)\n if 'SOLVENT_CONFIG' in os.environ:\n data = yaml.load(os.environ['SOLVENT_CONFIG'])\n globals().update(data)\n if 'SOLVENT_CLEAN' in os.environ:\n global CLEAN\n CLEAN = True\n if WITH_OFFICIAL_OBJECT_STORE and OFFICIAL_OSMOSIS is None:\n raise Exception(\"Configuration file must contain 'OFFICIAL_OSMOSIS' field\")\n global LOCAL_OSMOSIS\n if LOCAL_OSMOSIS is None:\n if os.getuid() == 0:\n LOCAL_OSMOSIS = LOCAL_OSMOSIS_IF_ROOT\n else:\n LOCAL_OSMOSIS = LOCAL_OSMOSIS_IF_NOT_ROOT\n\n\ndef objectStoresOsmosisParameter():\n if WITH_OFFICIAL_OBJECT_STORE:\n return LOCAL_OSMOSIS + \"+\" + OFFICIAL_OSMOSIS\n else:\n return LOCAL_OSMOSIS\n","subject":"Select local osmosis depends if user is root, to avoid permission denied on \/var\/lib\/osmosis","message":"Bugfix: Select local osmosis depends if user is root, to avoid permission denied on \/var\/lib\/osmosis\n","lang":"Python","license":"apache-2.0","repos":"Stratoscale\/solvent,Stratoscale\/solvent"} {"commit":"536801f970702792b0b23e4795929746ae2f92f8","old_file":"src\/ggrc\/settings\/default.py","new_file":"src\/ggrc\/settings\/default.py","old_contents":"\n# Copyright (C) 2013 Google Inc., authors, and contributors \n# Licensed under http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \n# Created By:\n# Maintained By:\n\nDEBUG = False\nTESTING = False\nAUTOBUILD_ASSETS = False\nENABLE_JASMINE = False\nFULLTEXT_INDEXER = None\n\n# Deployment-specific variables\nCOMPANY = \"Company, Inc.\"\nCOMPANY_LOGO_TEXT = \"Company GRC\"\nVERSION = \"s4\"\n\n# Initialize from environment if present\nimport os\nSQLALCHEMY_DATABASE_URI = os.environ.get('GGRC_DATABASE_URI', '')\nSECRET_KEY = os.environ.get('GGRC_SECRET_KEY', 'Replace-with-something-secret')\n","new_contents":"# Copyright (C) 2013 Google Inc., authors, and contributors \n# Licensed under http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \n# Created By: dan@reciprocitylabs.com\n# Maintained By: dan@reciprocitylabs.com\n\nDEBUG = False\nTESTING = False\n\n# Flask-SQLAlchemy fix to be less than `wait_time` in \/etc\/mysql\/my.cnf\nSQLALCHEMY_POOL_RECYCLE = 120\n\n# Settings in app.py\nAUTOBUILD_ASSETS = False\nENABLE_JASMINE = False\nFULLTEXT_INDEXER = None\n\n# Deployment-specific variables\nCOMPANY = \"Company, Inc.\"\nCOMPANY_LOGO_TEXT = \"Company GRC\"\nVERSION = \"s4\"\n\n# Initialize from environment if present\nimport os\nSQLALCHEMY_DATABASE_URI = os.environ.get('GGRC_DATABASE_URI', '')\nSECRET_KEY = os.environ.get('GGRC_SECRET_KEY', 'Replace-with-something-secret')\n","subject":"Set SQLALCHEMY_POOL_RECYCLE to be less than `wait_time`","message":"Set SQLALCHEMY_POOL_RECYCLE to be less than `wait_time`\n\n* should fix \"MySQL server has gone away\" errors in development mode\n","lang":"Python","license":"apache-2.0","repos":"j0gurt\/ggrc-core,vladan-m\/ggrc-core,jmakov\/ggrc-core,AleksNeStu\/ggrc-core,andrei-karalionak\/ggrc-core,AleksNeStu\/ggrc-core,AleksNeStu\/ggrc-core,2947721120\/sagacious-capsicum,prasannav7\/ggrc-core,hasanalom\/ggrc-core,kr41\/ggrc-core,2947721120\/sagacious-capsicum,VinnieJohns\/ggrc-core,selahssea\/ggrc-core,VinnieJohns\/ggrc-core,j0gurt\/ggrc-core,andrei-karalionak\/ggrc-core,hamyuan\/ggrc-self-test,hyperNURb\/ggrc-core,kr41\/ggrc-core,prasannav7\/ggrc-core,ankit-collective\/ggrc-core,andrei-karalionak\/ggrc-core,edofic\/ggrc-core,uskudnik\/ggrc-core,uskudnik\/ggrc-core,selahssea\/ggrc-core,josthkko\/ggrc-core,NejcZupec\/ggrc-core,ankit-collective\/ggrc-core,plamut\/ggrc-core,hyperNURb\/ggrc-core,jmakov\/ggrc-core,vladan-m\/ggrc-core,2947721120\/sagacious-capsicum,hamyuan\/ggrc-self-test,edofic\/ggrc-core,prasannav7\/ggrc-core,kr41\/ggrc-core,NejcZupec\/ggrc-core,selahssea\/ggrc-core,jmakov\/ggrc-core,vladan-m\/ggrc-core,hasanalom\/ggrc-core,j0gurt\/ggrc-core,plamut\/ggrc-core,uskudnik\/ggrc-core,edofic\/ggrc-core,josthkko\/ggrc-core,2947721120\/sagacious-capsicum,prasannav7\/ggrc-core,ankit-collective\/ggrc-core,hyperNURb\/ggrc-core,hyperNURb\/ggrc-core,VinnieJohns\/ggrc-core,josthkko\/ggrc-core,selahssea\/ggrc-core,hamyuan\/ggrc-self-test,hasanalom\/ggrc-core,2947721120\/sagacious-capsicum,plamut\/ggrc-core,VinnieJohns\/ggrc-core,ankit-collective\/ggrc-core,hasanalom\/ggrc-core,jmakov\/ggrc-core,edofic\/ggrc-core,NejcZupec\/ggrc-core,NejcZupec\/ggrc-core,hamyuan\/ggrc-self-test,ankit-collective\/ggrc-core,hyperNURb\/ggrc-core,kr41\/ggrc-core,jmakov\/ggrc-core,hasanalom\/ggrc-core,hamyuan\/ggrc-self-test,plamut\/ggrc-core,AleksNeStu\/ggrc-core,vladan-m\/ggrc-core,vladan-m\/ggrc-core,andrei-karalionak\/ggrc-core,josthkko\/ggrc-core,j0gurt\/ggrc-core,uskudnik\/ggrc-core,uskudnik\/ggrc-core"} {"commit":"967240f95edb300d731f24cfb259a1fe4f3bdae5","old_file":"webapp_health_monitor\/management\/commands\/verify.py","new_file":"webapp_health_monitor\/management\/commands\/verify.py","old_contents":"import importlib\nimport sys\n\nfrom django.apps import apps\nfrom django.core.management.base import BaseCommand\n\nfrom webapp_health_monitor.verification_suit import VerificationSuit\n\n\nclass Command(BaseCommand):\n SUBMODULE_NAME = 'verificators'\n\n def handle(self, *args, **options):\n submodules = self._get_verificator_modules()\n for submodule in submodules:\n try:\n importlib.import_module(submodule)\n except ImportError as e:\n if str(e) != \"No module named '{}'\".format(submodule):\n raise e\n result = VerificationSuit().run()\n self.stdout.write('{}\\n'.format(result.report()))\n sys.exit(result.has_failed())\n\n def _get_verificator_modules(self):\n for app in apps.get_app_configs():\n yield '.'.join([app.module.__name__, self.SUBMODULE_NAME])\n","new_contents":"import importlib\nimport sys\n\nfrom django.apps import apps\nfrom django.core.management.base import BaseCommand\n\nfrom webapp_health_monitor.verification_suit import VerificationSuit\n\n\nclass Command(BaseCommand):\n SUBMODULE_NAME = 'verificators'\n\n def handle(self, *args, **options):\n submodules = self._get_verificator_modules()\n for submodule in submodules:\n try:\n importlib.import_module(submodule)\n except ImportError as e:\n if not self._import_error_concerns_verificator(submodule, e):\n raise e\n result = VerificationSuit().run()\n self.stdout.write('{}\\n'.format(result.report()))\n sys.exit(result.has_failed())\n\n def _get_verificator_modules(self):\n for app in apps.get_app_configs():\n yield '.'.join([app.module.__name__, self.SUBMODULE_NAME])\n\n def _import_error_concerns_verificator(self, submodule, error):\n if sys.version_info >= (3, 0):\n return str(error) == \"No module named '{}'\".format(submodule)\n else:\n return error.message == \"No module named {}\".format(\n self.SUBMODULE_NAME)\n","subject":"Fix python2 django module importerror.","message":"Fix python2 django module importerror.\n","lang":"Python","license":"mit","repos":"pozytywnie\/webapp-health-monitor"} {"commit":"80529d5032b6728adcaad426310c30b5e6366ad4","old_file":"solution.py","new_file":"solution.py","old_contents":"class Kiosk():\n def __init__(self, visit_cost, location):\n self.visit_cost = visit_cost\n self.location = location\n print 'initializing Kiosk'\n\n #patient shold be Person\n def visit(self, patient):\n if not patient.location == self.location:\n print 'patient not in correct location'\n return False\n if not patient.money>self.visit_cost:\n print 'patient cannot afford treatment'\n\n #patient should be Person\n def visit(self, patient):\n patient.money -= visit_cost\n #improve patient.diabetes\n #improve patient.cardio\n return True\n\n #Patient should be from class Person\n def filter(self, patient):\n if not patient.location == self.location:\n print \"patient not at proper location\"\n return False\n if not patient.money>self.visit_cost:\n print \"patient cannot afford treatment\"\n return False\n visit(self,patient)\n","new_contents":"class Kiosk():\n def __init__(self, location, visit_cost, diabetes_threshold,\n cardio_threshold):\n self.location = location\n self.visit_cost = visit_cost\n self.diabetes_threshold = diabetes_threshold\n self.cardio_threshold = cardio_threshold\n #Initial cost to create kiosk: $5000. We are measuring in rupees\n self.money = -309900\n print 'initializing Kiosk'\n\n #patient shold be Person\n def visit(self, patient):\n if not patient.location == self.location:\n print 'patient not in correct location'\n return False\n if not patient.money>self.visit_cost:\n print 'patient cannot afford treatment'\n patient.money -= visit_cost\n kiosk.money += visit_cost\n \n #If we diagnose diabetes\n if patient.diabetes %t\/lit.site.cfg\n# RUN: %{lit} %t\n# RUN: FileCheck %s < %t\/Output\/Shared\/SHARED.tmp\n# RUN: FileCheck -check-prefix=NEGATIVE %s < %t\/Output\/Shared\/SHARED.tmp\n# RUN: FileCheck -check-prefix=OTHER %s < %t\/Output\/Shared\/OTHER.tmp\n\n# CHECK-DAG: primary\n# CHECK-DAG: secondary\n# CHECK-DAG: sub\n\n# NEGATIVE-NOT: other\n# OTHER: other\n","new_contents":"# RUN: rm -rf %t && mkdir -p %t\n# RUN: echo 'lit_config.load_config(config, os.path.join(\"%{inputs}\", \"shared-output\", \"lit.cfg\"))' > %t\/lit.site.cfg\n# RUN: %{lit} %t\n# RUN: FileCheck %s < %t\/Output\/Shared\/SHARED.tmp\n# RUN: FileCheck -check-prefix=NEGATIVE %s < %t\/Output\/Shared\/SHARED.tmp\n# RUN: FileCheck -check-prefix=OTHER %s < %t\/Output\/Shared\/OTHER.tmp\n\n# CHECK-DAG: primary\n# CHECK-DAG: secondary\n# CHECK-DAG: sub\n\n# NEGATIVE-NOT: other\n# OTHER: other\n","subject":"Fix new test for systems that don't use \/ as os.path.sep","message":"lit.py: Fix new test for systems that don't use \/ as os.path.sep\n\ngit-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@315773 91177308-0d34-0410-b5e6-96231b3b80d8\n","lang":"Python","license":"apache-2.0","repos":"apple\/swift-llvm,llvm-mirror\/llvm,apple\/swift-llvm,apple\/swift-llvm,GPUOpen-Drivers\/llvm,llvm-mirror\/llvm,llvm-mirror\/llvm,GPUOpen-Drivers\/llvm,apple\/swift-llvm,llvm-mirror\/llvm,llvm-mirror\/llvm,GPUOpen-Drivers\/llvm,GPUOpen-Drivers\/llvm,apple\/swift-llvm,llvm-mirror\/llvm,apple\/swift-llvm,apple\/swift-llvm,llvm-mirror\/llvm,GPUOpen-Drivers\/llvm,apple\/swift-llvm,GPUOpen-Drivers\/llvm,llvm-mirror\/llvm,llvm-mirror\/llvm,GPUOpen-Drivers\/llvm,GPUOpen-Drivers\/llvm"} {"commit":"5867a09fb43f8c4480d7aef89a200e952406a648","old_file":"dbaas\/integrations\/credentials\/admin\/__init__.py","new_file":"dbaas\/integrations\/credentials\/admin\/__init__.py","old_contents":"# -*- coding:utf-8 -*-\nfrom django.contrib import admin\nfrom .. import models\n\nadmin.site.register(models.IntegrationType, )\nadmin.site.register(models.IntegrationCredential, )\n","new_contents":"# -*- coding:utf-8 -*-\nfrom django.contrib import admin\nfrom .integration_credential import IntegrationCredentialAdmin\nfrom .integration_type import IntegrationTypeAdmin\nfrom .. import models\n\nadmin.site.register(models.IntegrationType, IntegrationTypeAdmin)\nadmin.site.register(models.IntegrationCredential, IntegrationCredentialAdmin)\n","subject":"Enable integration credential and integration type admin","message":"Enable integration credential and integration type admin\n","lang":"Python","license":"bsd-3-clause","repos":"globocom\/database-as-a-service,globocom\/database-as-a-service,globocom\/database-as-a-service,globocom\/database-as-a-service"} {"commit":"c08c437b22982667e8ed413739147caec6c5d1ca","old_file":"api\/preprints\/urls.py","new_file":"api\/preprints\/urls.py","old_contents":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),\n url(r'^(?P\\w+)\/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),\n url(r'^(?P\\w+)\/contributors\/$', views.PreprintContributorsList.as_view(), name=views.PreprintContributorsList.view_name),\n]\n","new_contents":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),\n url(r'^(?P\\w+)\/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),\n url(r'^(?P\\w+)\/contributors\/$', views.PreprintContributorsList.as_view(), name=views.PreprintContributorsList.view_name),\n url(r'^(?P\\w+)\/relationships\/preprint_provider\/$', views.PreprintToPreprintProviderRelationship.as_view(), name=views.PreprintToPreprintProviderRelationship.view_name),\n]\n","subject":"Add URL route for updating provider relationship","message":"Add URL route for updating provider relationship\n","lang":"Python","license":"apache-2.0","repos":"mluo613\/osf.io,rdhyee\/osf.io,samchrisinger\/osf.io,leb2dg\/osf.io,cslzchen\/osf.io,chrisseto\/osf.io,leb2dg\/osf.io,binoculars\/osf.io,mluo613\/osf.io,Nesiehr\/osf.io,Johnetordoff\/osf.io,laurenrevere\/osf.io,emetsger\/osf.io,monikagrabowska\/osf.io,rdhyee\/osf.io,CenterForOpenScience\/osf.io,binoculars\/osf.io,icereval\/osf.io,binoculars\/osf.io,cslzchen\/osf.io,caneruguz\/osf.io,samchrisinger\/osf.io,baylee-d\/osf.io,TomBaxter\/osf.io,crcresearch\/osf.io,icereval\/osf.io,laurenrevere\/osf.io,CenterForOpenScience\/osf.io,chennan47\/osf.io,samchrisinger\/osf.io,caseyrollins\/osf.io,cslzchen\/osf.io,mfraezz\/osf.io,mattclark\/osf.io,cwisecarver\/osf.io,chennan47\/osf.io,aaxelb\/osf.io,erinspace\/osf.io,emetsger\/osf.io,rdhyee\/osf.io,monikagrabowska\/osf.io,alexschiller\/osf.io,HalcyonChimera\/osf.io,leb2dg\/osf.io,brianjgeiger\/osf.io,caneruguz\/osf.io,saradbowman\/osf.io,mfraezz\/osf.io,erinspace\/osf.io,sloria\/osf.io,HalcyonChimera\/osf.io,Johnetordoff\/osf.io,chennan47\/osf.io,Johnetordoff\/osf.io,aaxelb\/osf.io,hmoco\/osf.io,pattisdr\/osf.io,caneruguz\/osf.io,HalcyonChimera\/osf.io,saradbowman\/osf.io,brianjgeiger\/osf.io,baylee-d\/osf.io,acshi\/osf.io,sloria\/osf.io,mluo613\/osf.io,Nesiehr\/osf.io,alexschiller\/osf.io,aaxelb\/osf.io,TomBaxter\/osf.io,mluo613\/osf.io,brianjgeiger\/osf.io,Nesiehr\/osf.io,pattisdr\/osf.io,leb2dg\/osf.io,adlius\/osf.io,caseyrollins\/osf.io,chrisseto\/osf.io,mfraezz\/osf.io,caseyrollins\/osf.io,crcresearch\/osf.io,alexschiller\/osf.io,felliott\/osf.io,alexschiller\/osf.io,alexschiller\/osf.io,monikagrabowska\/osf.io,adlius\/osf.io,Johnetordoff\/osf.io,monikagrabowska\/osf.io,monikagrabowska\/osf.io,CenterForOpenScience\/osf.io,acshi\/osf.io,rdhyee\/osf.io,hmoco\/osf.io,baylee-d\/osf.io,cwisecarver\/osf.io,mattclark\/osf.io,cslzchen\/osf.io,emetsger\/osf.io,CenterForOpenScience\/osf.io,brianjgeiger\/osf.io,cwisecarver\/osf.io,samchrisinger\/osf.io,felliott\/osf.io,caneruguz\/osf.io,Nesiehr\/osf.io,acshi\/osf.io,mattclark\/osf.io,felliott\/osf.io,TomBaxter\/osf.io,crcresearch\/osf.io,acshi\/osf.io,hmoco\/osf.io,HalcyonChimera\/osf.io,adlius\/osf.io,mfraezz\/osf.io,acshi\/osf.io,emetsger\/osf.io,sloria\/osf.io,laurenrevere\/osf.io,felliott\/osf.io,chrisseto\/osf.io,chrisseto\/osf.io,aaxelb\/osf.io,adlius\/osf.io,icereval\/osf.io,erinspace\/osf.io,hmoco\/osf.io,cwisecarver\/osf.io,mluo613\/osf.io,pattisdr\/osf.io"} {"commit":"597f586d2cf42f31a0179efc7ac8441f33b3d637","old_file":"lib\/mysql.py","new_file":"lib\/mysql.py","old_contents":"import pymysql\n\nclass MySQL():\n\n def __init__(self, host, user, password, port):\n self._host = host\n self._user = user\n self._password = password\n self._conn = pymysql.connect(host=host, port=port,\n user=user, passwd=password)\n self._cursor = self._conn.cursor()\n\n def execute(self, query):\n try:\n self._cursor.execute(query=query)\n except (AttributeError, pymysql.OperationalError):\n self.__reconnect__()\n self._cursor.execute(query=query)\n\n def fetchone(self):\n return self._cursor.fetchone()\n\n def commit(self):\n return self._conn.commit()\n\n def __reconnect__(self):\n self._conn = pymysql.connect(host=self._host, port=self._port, user=self._user, passwd=self._password)\n self._cursor = self._conn.cursor()\n","new_contents":"import pymysql\n\nclass MySQL():\n\n def __init__(self, host, user, password, port):\n self._host = host\n self._user = user\n self._password = password\n self._port = port\n self._conn = pymysql.connect(host=host, port=port,\n user=user, passwd=password)\n self._cursor = self._conn.cursor()\n\n def execute(self, query):\n try:\n self._cursor.execute(query=query)\n except (AttributeError, pymysql.OperationalError):\n self.__reconnect__()\n self._cursor.execute(query=query)\n\n def fetchone(self):\n return self._cursor.fetchone()\n\n def commit(self):\n return self._conn.commit()\n\n def __reconnect__(self):\n self._conn = pymysql.connect(host=self._host, port=self._port, user=self._user, passwd=self._password)\n self._cursor = self._conn.cursor()\n","subject":"Define the port variable for reconnection","message":"Define the port variable for reconnection","lang":"Python","license":"mit","repos":"ImShady\/Tubey"} {"commit":"999752ec378bbf6d3017f7afc964090c6871b7d4","old_file":"app\/user_administration\/tests.py","new_file":"app\/user_administration\/tests.py","old_contents":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.test import TestCase\n\n\nclass LoginRequiredTest(TestCase):\n def test_login_required(self):\n response = self.client.get('\/')\n self.assertEqual(\n response.status_code,\n 302,\n msg=\"Login Required Validation Failed, Received code {0} instead of 302\".format(response.status_code)\n )\n self.assertEqual(\n response.url,\n '\/login?next=\/',\n msg=\"Login Required Redirection Failed, Received url {0} instead of \/login?next=\/\".format(response.url)\n )\n","new_contents":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.test import TestCase\nfrom django.contrib.auth.models import User\nfrom .models import Clients\n\n\nclass LoginRequiredTest(TestCase):\n def test_login_required(self):\n response = self.client.get('\/')\n self.assertEqual(\n response.status_code,\n 302,\n msg=\"Login Required Validation Failed, Received code {0} instead of 302\".format(response.status_code)\n )\n self.assertEqual(\n response.url,\n '\/login?next=\/',\n msg=\"Login Required Redirection Failed, Received url {0} instead of \/login?next=\/\".format(response.url)\n )\n\n\nclass LoginSetup(TestCase):\n def setUp(self):\n self.user = User.objects.create(username='testUser', is_active=True, is_superuser=True)\n self.user.set_password('RHChallenge')\n self.user.save()\n self.client.force_login(self.user)\n\n\nclass ClientsViewTest(LoginSetup):\n def setUp(self):\n super(ClientsViewTest, self).setUp()\n self.custom_client = Clients.objects.create(first_name='RH', last_name='CH', iban='IBAN')\n\n def test_client_create(self):\n data = {'first_name': 'Rexhep', 'last_name': 'Berlajolli', 'iban': 'XK051506001004471930'}\n self.client.post('\/add', data=data)\n clients_count = Clients.objects.count()\n self.assertEqual(\n clients_count,\n 2,\n msg=\"Create client failed, received {0} clients instead of 2\".format(clients_count)\n )\n\n def test_client_create_validation(self):\n data = {'first_name': 'Invalid', 'last_name': 'Data', 'iban': 'INVALID_IBAN'}\n self.client.post('\/add', data=data)\n clients_count = Clients.objects.count()\n self.assertEqual(\n clients_count,\n 1,\n msg=\"Insertion of invalid data succeeded, received {0} clients instead of 1\".format(clients_count)\n )\n\n def test_get_clients(self):\n response = self.client.get('\/')\n clients = response.context_data['clients']\n self.assertEqual(\n list(clients),\n list(Clients.objects.all()),\n msg=\"Get clients failed, received clients {0} instead of {1}\".format(clients, [self.custom_client])\n )\n","subject":"Add TestCase for ClientListView and ClientCreateView","message":"Add TestCase for ClientListView and ClientCreateView\n","lang":"Python","license":"mit","repos":"rexhepberlajolli\/RHChallenge,rexhepberlajolli\/RHChallenge"} {"commit":"912c8f8f3626c7da92b6864e02dfc2534f4f7873","old_file":"exercises\/leap\/leap_test.py","new_file":"exercises\/leap\/leap_test.py","old_contents":"import unittest\n\nfrom leap import is_leap_year\n\n\n# Tests adapted from `problem-specifications\/\/canonical-data.json` @ v1.5.1\n\nclass LeapTest(unittest.TestCase):\n def test_year_not_divisible_by_4(self):\n self.assertIs(is_leap_year(2015), False)\n\n def year_divisible_by_2_not_divisible_by_4(self):\n self.assertIs(is_leap_year(1970), False)\n\n def test_year_divisible_by_4_not_divisible_by_100(self):\n self.assertIs(is_leap_year(1996), True)\n\n def test_year_divisible_by_100_not_divisible_by_400(self):\n self.assertIs(is_leap_year(2100), False)\n\n def test_year_divisible_by_400(self):\n self.assertIs(is_leap_year(2000), True)\n\n def test_year_divisible_by_200_not_divisible_by_400(self):\n self.assertIs(is_leap_year(1800), False)\n\n\nif __name__ == '__main__':\n unittest.main()\n","new_contents":"import unittest\n\nfrom leap import is_leap_year\n\n\n# Tests adapted from `problem-specifications\/\/canonical-data.json` @ v1.5.1\n\n\nclass LeapTest(unittest.TestCase):\n def test_year_not_divisible_by_4(self):\n self.assertIs(is_leap_year(2015), False)\n\n def test_year_divisible_by_2_not_divisible_by_4(self):\n self.assertIs(is_leap_year(1970), False)\n\n def test_year_divisible_by_4_not_divisible_by_100(self):\n self.assertIs(is_leap_year(1996), True)\n\n def test_year_divisible_by_100_not_divisible_by_400(self):\n self.assertIs(is_leap_year(2100), False)\n\n def test_year_divisible_by_400(self):\n self.assertIs(is_leap_year(2000), True)\n\n def test_year_divisible_by_200_not_divisible_by_400(self):\n self.assertIs(is_leap_year(1800), False)\n\n\nif __name__ == '__main__':\n unittest.main()\n","subject":"Stop leep test being ignored","message":"Stop leep test being ignored\n","lang":"Python","license":"mit","repos":"N-Parsons\/exercism-python,exercism\/python,behrtam\/xpython,exercism\/xpython,jmluy\/xpython,smalley\/python,exercism\/xpython,behrtam\/xpython,N-Parsons\/exercism-python,jmluy\/xpython,exercism\/python,smalley\/python"} {"commit":"8b07dde78e753f6dce663481a68856024ed2fc49","old_file":"plutokore\/__init__.py","new_file":"plutokore\/__init__.py","old_contents":"from .environments.makino import MakinoProfile\nfrom .environments.king import KingProfile\nfrom .jet import AstroJet\n\nfrom . import luminosity\nfrom . import plotting\nfrom . import simulations\nfrom . import helpers\nfrom . import io\n\n__all__ = [\n 'environments',\n 'luminosity',\n 'plotting',\n 'simulations',\n 'jet',\n 'helpers',\n 'io',\n]\n","new_contents":"from .environments.makino import MakinoProfile\nfrom .environments.king import KingProfile\nfrom .jet import AstroJet\n\nfrom . import luminosity\nfrom . import plotting\nfrom . import simulations\nfrom . import helpers\nfrom . import io\nfrom . import configuration\n\n__all__ = [\n 'environments',\n 'luminosity',\n 'plotting',\n 'simulations',\n 'jet',\n 'helpers',\n 'io',\n 'configuration',\n]\n","subject":"Add configuration module to package exports","message":"Add configuration module to package exports\n","lang":"Python","license":"mit","repos":"opcon\/plutokore,opcon\/plutokore"} {"commit":"fcd2328549dcec2986e3b972f1a8bcfb0cf2e21b","old_file":"rst2pdf\/utils.py","new_file":"rst2pdf\/utils.py","old_contents":"# -*- coding: utf-8 -*-\r\n# See LICENSE.txt for licensing terms\r\n#$HeadURL$\r\n#$LastChangedDate$\r\n#$LastChangedRevision$\r\n\r\nimport shlex\r\n\r\nfrom reportlab.platypus import Spacer\r\n\r\nfrom flowables import *\r\n\r\n\r\ndef parseRaw(data):\r\n \"\"\"Parse and process a simple DSL to handle creation of flowables.\r\n\r\n Supported (can add others on request):\r\n\r\n * PageBreak\r\n\r\n * Spacer width, height\r\n\r\n \"\"\"\r\n elements = []\r\n lines = data.splitlines()\r\n for line in lines:\r\n lexer = shlex.shlex(line)\r\n lexer.whitespace += ','\r\n tokens = list(lexer)\r\n command = tokens[0]\r\n if command == 'PageBreak':\r\n if len(tokens) == 1:\r\n elements.append(MyPageBreak())\r\n else:\r\n elements.append(MyPageBreak(tokens[1]))\r\n if command == 'Spacer':\r\n elements.append(Spacer(int(tokens[1]), int(tokens[2])))\r\n if command == 'Transition':\r\n elements.append(Transition(*tokens[1:]))\r\n return elements\r\n\r\n\r\n# Looks like this is not used anywhere now:\r\n# def depth(node):\r\n# if node.parent == None:\r\n# return 0\r\n# else:\r\n# return 1 + depth(node.parent)\r\n","new_contents":"# -*- coding: utf-8 -*-\r\n# See LICENSE.txt for licensing terms\r\n#$HeadURL$\r\n#$LastChangedDate$\r\n#$LastChangedRevision$\r\n\r\nimport shlex\r\n\r\nfrom reportlab.platypus import Spacer\r\n\r\nfrom flowables import *\r\nfrom styles import adjustUnits\r\n\r\ndef parseRaw(data):\r\n \"\"\"Parse and process a simple DSL to handle creation of flowables.\r\n\r\n Supported (can add others on request):\r\n\r\n * PageBreak\r\n\r\n * Spacer width, height\r\n\r\n \"\"\"\r\n elements = []\r\n lines = data.splitlines()\r\n for line in lines:\r\n lexer = shlex.shlex(line)\r\n lexer.whitespace += ','\r\n tokens = list(lexer)\r\n command = tokens[0]\r\n if command == 'PageBreak':\r\n if len(tokens) == 1:\r\n elements.append(MyPageBreak())\r\n else:\r\n elements.append(MyPageBreak(tokens[1]))\r\n if command == 'Spacer':\r\n elements.append(Spacer(adjustUnits(tokens[1]), \r\n adjustUnits(tokens[2])))\r\n if command == 'Transition':\r\n elements.append(Transition(*tokens[1:]))\r\n return elements\r\n\r\n\r\n# Looks like this is not used anywhere now:\r\n# def depth(node):\r\n# if node.parent == None:\r\n# return 0\r\n# else:\r\n# return 1 + depth(node.parent)\r\n","subject":"Add unit support for spacers","message":"Add unit support for spacers","lang":"Python","license":"mit","repos":"pombreda\/rst2pdf,liuyi1112\/rst2pdf,pombreda\/rst2pdf,liuyi1112\/rst2pdf,rst2pdf\/rst2pdf,rst2pdf\/rst2pdf"} {"commit":"c5780adeecfbd85a80b5aa7130dd86e78b23e497","old_file":"django\/__init__.py","new_file":"django\/__init__.py","old_contents":"VERSION = (1, 7, 1, 'alpha', 0)\n\n\ndef get_version(*args, **kwargs):\n # Don't litter django\/__init__.py with all the get_version stuff.\n # Only import if it's actually called.\n from django.utils.version import get_version\n return get_version(*args, **kwargs)\n\n\ndef setup():\n \"\"\"\n Configure the settings (this happens as a side effect of accessing the\n first setting), configure logging and populate the app registry.\n \"\"\"\n from django.apps import apps\n from django.conf import settings\n from django.utils.log import configure_logging\n\n configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)\n apps.populate(settings.INSTALLED_APPS)\n","new_contents":"VERSION = (1, 7, 1, 'final', 0)\n\n\ndef get_version(*args, **kwargs):\n # Don't litter django\/__init__.py with all the get_version stuff.\n # Only import if it's actually called.\n from django.utils.version import get_version\n return get_version(*args, **kwargs)\n\n\ndef setup():\n \"\"\"\n Configure the settings (this happens as a side effect of accessing the\n first setting), configure logging and populate the app registry.\n \"\"\"\n from django.apps import apps\n from django.conf import settings\n from django.utils.log import configure_logging\n\n configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)\n apps.populate(settings.INSTALLED_APPS)\n","subject":"Bump version number for bugfix release.","message":"[1.7.x] Bump version number for bugfix release.\n","lang":"Python","license":"bsd-3-clause","repos":"jyotsna1820\/django,jyotsna1820\/django,oscaro\/django,oscaro\/django,jyotsna1820\/django,oscaro\/django,jyotsna1820\/django,oscaro\/django"} {"commit":"6b0167514bb41f877945b408638fab72873f2da8","old_file":"postgres_copy\/__init__.py","new_file":"postgres_copy\/__init__.py","old_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.db import connection\nfrom .copy_from import CopyMapping\nfrom .copy_to import SQLCopyToCompiler, CopyToQuery\n__version__ = '2.0.0'\n\n\nclass CopyQuerySet(models.QuerySet):\n \"\"\"\n Subclass of QuerySet that adds from_csv and to_csv methods.\n \"\"\"\n def from_csv(self, csv_path, mapping, **kwargs):\n \"\"\"\n Copy CSV file from the provided path to the current model using the provided mapping.\n \"\"\"\n mapping = CopyMapping(self.model, csv_path, mapping, **kwargs)\n mapping.save(silent=True)\n\n def to_csv(self, csv_path, *fields):\n \"\"\"\n Copy current QuerySet to CSV at provided path.\n \"\"\"\n query = self.query.clone(CopyToQuery)\n query.copy_to_fields = fields\n compiler = query.get_compiler(self.db, connection=connection)\n compiler.execute_sql(csv_path)\n\n\nCopyManager = models.Manager.from_queryset(CopyQuerySet)\n\n\n__all__ = (\n 'CopyMapping',\n 'SQLCopyToCompiler',\n 'CopyToQuery',\n 'CopyManager',\n)\n","new_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.db import connection\nfrom .copy_from import CopyMapping\nfrom .copy_to import SQLCopyToCompiler, CopyToQuery\n__version__ = '2.0.0'\n\n\nclass CopyQuerySet(models.QuerySet):\n \"\"\"\n Subclass of QuerySet that adds from_csv and to_csv methods.\n \"\"\"\n def from_csv(self, csv_path, mapping, **kwargs):\n \"\"\"\n Copy CSV file from the provided path to the current model using the provided mapping.\n \"\"\"\n mapping = CopyMapping(self.model, csv_path, mapping, **kwargs)\n mapping.save(silent=True)\n\n def to_csv(self, csv_path, *fields):\n \"\"\"\n Copy current QuerySet to CSV at provided path.\n \"\"\"\n query = self.query.clone(CopyToQuery)\n query.copy_to_fields = fields\n compiler = query.get_compiler(self.db, connection=connection)\n compiler.execute_sql(csv_path)\n\n\nCopyManager = models.Manager.from_queryset(CopyQuerySet)\n\n\n__all__ = (\n 'CopyManager',\n 'CopyMapping',\n 'CopyToQuery',\n 'CopyToQuerySet',\n 'SQLCopyToCompiler',\n)\n","subject":"Add CopyToQuerySet to available imports","message":"Add CopyToQuerySet to available imports\n","lang":"Python","license":"mit","repos":"california-civic-data-coalition\/django-postgres-copy"} {"commit":"639032215f7a51ca146810e8261448f4d0a318aa","old_file":"downstream_node\/models.py","new_file":"downstream_node\/models.py","old_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nfrom downstream_node.startup import db\n\n\nclass Files(db.Model):\n __tablename__ = 'files'\n\n id = db.Column(db.Integer(), primary_key=True, autoincrement=True)\n filepath = db.Column('filepath', db.String())\n\n\nclass Challenges(db.Model):\n __tablename__ = 'challenges'\n\n id = db.Column(db.Integer(), primary_key=True, autoincrement=True)\n filepath = db.Column(db.ForeignKey('files.filepath'))\n block = db.Column('block', db.String())\n seed = db.Column('seed', db.String())\n response = db.Column('response', db.String(), nullable=True)\n","new_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nfrom downstream_node.startup import db\n\n\nclass Files(db.Model):\n __tablename__ = 'files'\n\n id = db.Column(db.Integer(), primary_key=True, autoincrement=True)\n filepath = db.Column('filepath', db.String())\n\n\nclass Challenges(db.Model):\n __tablename__ = 'challenges'\n\n id = db.Column(db.Integer(), primary_key=True, autoincrement=True)\n filepath = db.Column(db.ForeignKey('files.filepath'))\n root_seed = db.Column(db.String())\n block = db.Column(db.String())\n seed = db.Column(db.String())\n response = db.Column(db.String(), nullable=True)\n","subject":"Add root seed to model","message":"Add root seed to model\n","lang":"Python","license":"mit","repos":"Storj\/downstream-node,Storj\/downstream-node"} {"commit":"c11fd9f792afb71e01224f149121bc13a6a9bed8","old_file":"scripts\/utils.py","new_file":"scripts\/utils.py","old_contents":"#!\/usr\/bin\/env python3\n\n# Touhou Community Reliant Automatic Patcher\n# Scripts\n#\n# ----\n#\n\"\"\"Utility functions shared among all the scripts.\"\"\"\n\nimport json\nimport os\n\njson_dump_params = {\n 'ensure_ascii': False,\n 'indent': '\\t',\n 'separators': (',', ': '),\n 'sort_keys': True\n}\n\n# Default parameters for JSON input and output\ndef json_load(fn):\n with open(fn, 'r', encoding='utf-8') as file:\n return json.load(file)\n\n\ndef json_store(fn, obj, dirs=['']):\n \"\"\"Saves the JSON object [obj] to [fn], creating all necessary\n directories in the process. If [dirs] is given, the function is\n executed for every root directory in the array.\"\"\"\n for i in dirs:\n full_fn = os.path.join(i, fn)\n os.makedirs(os.path.dirname(full_fn), exist_ok=True)\n with open(full_fn, 'w', encoding='utf-8') as file:\n json.dump(obj, file, **json_dump_params)\n file.write('\\n')\n","new_contents":"#!\/usr\/bin\/env python3\n\n# Touhou Community Reliant Automatic Patcher\n# Scripts\n#\n# ----\n#\n\"\"\"Utility functions shared among all the scripts.\"\"\"\n\nfrom collections import OrderedDict\nimport json\nimport os\n\njson_load_params = {\n 'object_pairs_hook': OrderedDict\n}\n\njson_dump_params = {\n 'ensure_ascii': False,\n 'indent': '\\t',\n 'separators': (',', ': '),\n 'sort_keys': True\n}\n\n# Default parameters for JSON input and output\ndef json_load(fn):\n with open(fn, 'r', encoding='utf-8') as file:\n return json.load(file, **json_load_params)\n\n\ndef json_store(fn, obj, dirs=['']):\n \"\"\"Saves the JSON object [obj] to [fn], creating all necessary\n directories in the process. If [dirs] is given, the function is\n executed for every root directory in the array.\"\"\"\n for i in dirs:\n full_fn = os.path.join(i, fn)\n os.makedirs(os.path.dirname(full_fn), exist_ok=True)\n with open(full_fn, 'w', encoding='utf-8') as file:\n json.dump(obj, file, **json_dump_params)\n file.write('\\n')\n","subject":"Use the OrderedDict class for JSON objects.","message":"scripts: Use the OrderedDict class for JSON objects.\n","lang":"Python","license":"unlicense","repos":"thpatch\/thcrap,thpatch\/thcrap,VBChunguk\/thcrap,thpatch\/thcrap,VBChunguk\/thcrap,thpatch\/thcrap,thpatch\/thcrap,VBChunguk\/thcrap"} {"commit":"0e22a642526612ff9d19d1b421a1aacea4109f15","old_file":"pylearn2\/datasets\/hdf5.py","new_file":"pylearn2\/datasets\/hdf5.py","old_contents":"\"\"\"Objects for datasets serialized in HDF5 format (.h5).\"\"\"\nimport h5py\nfrom pylearn2.datasets.dense_design_matrix import DenseDesignMatrix\n\nclass HDF5Dataset(DenseDesignMatrix):\n \"\"\"Dense dataset loaded from an HDF5 file.\"\"\"\n def __init__(self, filename, key):\n with h5py.File(filename) as f:\n data = f[key][:]\n if data.ndim == 2:\n super(HDF5Dataset, self).__init__(X=data)\n else:\n super(HDF5Dataset, self).__init__(topo_view=data)\n","new_contents":"\"\"\"Objects for datasets serialized in HDF5 format (.h5).\"\"\"\nimport h5py\nfrom pylearn2.datasets.dense_design_matrix import DenseDesignMatrix\n\nclass HDF5Dataset(DenseDesignMatrix):\n \"\"\"Dense dataset loaded from an HDF5 file.\"\"\"\n def __init__(self, filename, X=None, topo_view=None, y=None, **kwargs):\n \"\"\"\n Loads data and labels from HDF5 file.\n\n Parameters\n ----------\n filename: str\n HDF5 file name.\n X: str\n Key into HDF5 file for dataset design matrix.\n topo_view: str\n Key into HDF5 file for topological view of dataset.\n y: str\n Key into HDF5 file for dataset targets.\n \"\"\"\n with h5py.File(filename) as f:\n if X is not None:\n X = f[X][:]\n if topo_view is not None:\n topo_view = f[topo_view][:]\n if y is not None:\n y = f[y][:]\n super(HDF5Dataset, self).__init__(X, topo_view, y, **kwargs)\n","subject":"Support for targets in HDF5 datasets","message":"Support for targets in HDF5 datasets\n","lang":"Python","license":"bsd-3-clause","repos":"alexjc\/pylearn2,pombredanne\/pylearn2,kose-y\/pylearn2,TNick\/pylearn2,lancezlin\/pylearn2,theoryno3\/pylearn2,aalmah\/pylearn2,se4u\/pylearn2,woozzu\/pylearn2,daemonmaker\/pylearn2,daemonmaker\/pylearn2,goodfeli\/pylearn2,JesseLivezey\/pylearn2,nouiz\/pylearn2,ddboline\/pylearn2,CIFASIS\/pylearn2,w1kke\/pylearn2,lamblin\/pylearn2,kastnerkyle\/pylearn2,KennethPierce\/pylearnk,mclaughlin6464\/pylearn2,woozzu\/pylearn2,woozzu\/pylearn2,hantek\/pylearn2,mkraemer67\/pylearn2,cosmoharrigan\/pylearn2,sandeepkbhat\/pylearn2,fulmicoton\/pylearn2,skearnes\/pylearn2,ddboline\/pylearn2,daemonmaker\/pylearn2,fulmicoton\/pylearn2,KennethPierce\/pylearnk,jamessergeant\/pylearn2,nouiz\/pylearn2,mclaughlin6464\/pylearn2,caidongyun\/pylearn2,lamblin\/pylearn2,caidongyun\/pylearn2,ashhher3\/pylearn2,sandeepkbhat\/pylearn2,chrish42\/pylearn,pkainz\/pylearn2,se4u\/pylearn2,se4u\/pylearn2,goodfeli\/pylearn2,Refefer\/pylearn2,lunyang\/pylearn2,msingh172\/pylearn2,jeremyfix\/pylearn2,junbochen\/pylearn2,shiquanwang\/pylearn2,matrogers\/pylearn2,KennethPierce\/pylearnk,w1kke\/pylearn2,w1kke\/pylearn2,shiquanwang\/pylearn2,kastnerkyle\/pylearn2,cosmoharrigan\/pylearn2,jeremyfix\/pylearn2,chrish42\/pylearn,skearnes\/pylearn2,nouiz\/pylearn2,ashhher3\/pylearn2,sandeepkbhat\/pylearn2,lancezlin\/pylearn2,aalmah\/pylearn2,jamessergeant\/pylearn2,pombredanne\/pylearn2,lancezlin\/pylearn2,TNick\/pylearn2,ddboline\/pylearn2,theoryno3\/pylearn2,fishcorn\/pylearn2,chrish42\/pylearn,bartvm\/pylearn2,chrish42\/pylearn,hyqneuron\/pylearn2-maxsom,aalmah\/pylearn2,fishcorn\/pylearn2,fulmicoton\/pylearn2,hantek\/pylearn2,mclaughlin6464\/pylearn2,woozzu\/pylearn2,JesseLivezey\/plankton,pkainz\/pylearn2,lisa-lab\/pylearn2,pkainz\/pylearn2,lisa-lab\/pylearn2,jamessergeant\/pylearn2,pkainz\/pylearn2,JesseLivezey\/plankton,sandeepkbhat\/pylearn2,mkraemer67\/pylearn2,KennethPierce\/pylearnk,Refefer\/pylearn2,lunyang\/pylearn2,caidongyun\/pylearn2,alexjc\/pylearn2,bartvm\/pylearn2,bartvm\/pylearn2,lancezlin\/pylearn2,JesseLivezey\/plankton,jamessergeant\/pylearn2,shiquanwang\/pylearn2,lisa-lab\/pylearn2,msingh172\/pylearn2,kastnerkyle\/pylearn2,goodfeli\/pylearn2,goodfeli\/pylearn2,fyffyt\/pylearn2,mkraemer67\/pylearn2,cosmoharrigan\/pylearn2,msingh172\/pylearn2,kastnerkyle\/pylearn2,JesseLivezey\/pylearn2,mclaughlin6464\/pylearn2,fishcorn\/pylearn2,jeremyfix\/pylearn2,caidongyun\/pylearn2,hyqneuron\/pylearn2-maxsom,hyqneuron\/pylearn2-maxsom,matrogers\/pylearn2,theoryno3\/pylearn2,CIFASIS\/pylearn2,hantek\/pylearn2,junbochen\/pylearn2,Refefer\/pylearn2,matrogers\/pylearn2,JesseLivezey\/plankton,ashhher3\/pylearn2,Refefer\/pylearn2,cosmoharrigan\/pylearn2,fyffyt\/pylearn2,junbochen\/pylearn2,abergeron\/pylearn2,fishcorn\/pylearn2,abergeron\/pylearn2,abergeron\/pylearn2,skearnes\/pylearn2,CIFASIS\/pylearn2,msingh172\/pylearn2,lunyang\/pylearn2,ashhher3\/pylearn2,aalmah\/pylearn2,shiquanwang\/pylearn2,junbochen\/pylearn2,lamblin\/pylearn2,matrogers\/pylearn2,lunyang\/pylearn2,mkraemer67\/pylearn2,fyffyt\/pylearn2,lisa-lab\/pylearn2,hyqneuron\/pylearn2-maxsom,alexjc\/pylearn2,daemonmaker\/pylearn2,fulmicoton\/pylearn2,TNick\/pylearn2,skearnes\/pylearn2,kose-y\/pylearn2,hantek\/pylearn2,kose-y\/pylearn2,fyffyt\/pylearn2,nouiz\/pylearn2,CIFASIS\/pylearn2,w1kke\/pylearn2,bartvm\/pylearn2,pombredanne\/pylearn2,lamblin\/pylearn2,theoryno3\/pylearn2,abergeron\/pylearn2,alexjc\/pylearn2,ddboline\/pylearn2,JesseLivezey\/pylearn2,TNick\/pylearn2,kose-y\/pylearn2,se4u\/pylearn2,JesseLivezey\/pylearn2,pombredanne\/pylearn2,jeremyfix\/pylearn2"} {"commit":"b824cadfe61de19b5ff0f7391fe2b21b034c71b4","old_file":"readdata.py","new_file":"readdata.py","old_contents":"import os,sys\nimport json\nimport csv\nimport soundfile as sf\nfrom scipy.fftpack import dct\nfrom features import mfcc,fbank,sigproc,logfbank\n\ndef parseJSON(directory, filename):\n data=[]\n jsonMeta=[]\n #open all files that end with .json in directory\n #and store certain attributes\n try:\n json_data=open(os.path.join(directory, filename))\n except(IOError, RuntimeError ):\n print(\"Cannot open \", filename)\n\n data=json.load(json_data)\n jsonMeta.append(data['filesize'])\n jsonMeta.append(data['duration'])\n jsonMeta.append(data['samplerate'])\n jsonMeta.append(data['tags'])\n jsonMeta.append(data['type'])\n\n return jsonMeta\n\ndef parseCSV(directory, filename):\n with open(os.path.join(directory, filename)) as csvfile:\n csvMeta = csv.reader(csvfile, delimiter=\",\")\n return list(csvMeta)[0]\n\n\n#returns a vector with (currently) 4 features\ndef extractFeatures(directory,filename):\n\ttry:\n\t\tdata,samplerate=sf.read(os.path.join(directory, filename))\n\texcept (IOError, RuntimeError):\n\t\tprint(\"Could not open file \", filename)\n\t\tprint(\"Exiting...\")\n\t\tsys.exit()\n\t#if file was opened succesfully proceed with feature extraction\n\t#win is the size of window for mfcc extraction AND step size\n\twin=data.size\/(4*samplerate)\n\tfeatureVector=mfcc(data,samplerate,win,win,1)\n\t#featureVector is of type numpy_array\n\treturn featureVector\n","new_contents":"import os,sys\nimport json\nimport csv\nfrom yaafelib import *\n\ndef parseJSON(directory, filename):\n data=[]\n jsonMeta=[]\n #open all files that end with .json in directory\n #and store certain attributes\n try:\n json_data=open(os.path.join(directory, filename))\n except(IOError, RuntimeError ):\n print(\"Cannot open \", filename)\n\n data=json.load(json_data)\n jsonMeta.append(data['filesize'])\n jsonMeta.append(data['duration'])\n jsonMeta.append(data['samplerate'])\n jsonMeta.append(data['tags'])\n jsonMeta.append(data['type'])\n\n return jsonMeta\n\ndef parseCSV(directory, filename):\n with open(os.path.join(directory, filename)) as csvfile:\n csvMeta = csv.reader(csvfile, delimiter=\",\")\n return list(csvMeta)[0]\n\n\n#returns a vector with 2 features\ndef extractFeatures(directory,filename):\n # yaaaaafe\n fp = FeaturePlan(sample_rate=44100, resample=True)\n fp.addFeature('mfcc: MFCC blockSize=512 stepSize=256 CepsNbCoeffs=1')\n fp.addFeature('psp: PerceptualSpread blockSize=512 stepSize=256')\n df = fp.getDataFlow()\n engine = Engine()\n engine.load(df)\n afp = AudioFileProcessor()\n\n afp.processFile(engine,os.path.join(directory, filename))\n featureVector = engine.readAllOutputs()\n\n return featureVector\n","subject":"Use yaafe for feature extraction","message":"Use yaafe for feature extraction\n\nRight now we extract two features (mfcc and perceptual spread)\nbut there is a lot of work to be done on the feature extraction method\nso this is probably going to change\n","lang":"Python","license":"mit","repos":"lOStres\/JaFEM"} {"commit":"b0d9a11292b6d6b17fe8b72d7735d26c47599187","old_file":"linkatos\/printer.py","new_file":"linkatos\/printer.py","old_contents":"def bot_says(channel, text, slack_client):\n return slack_client.api_call(\"chat.postMessage\",\n channel=channel,\n text=text,\n as_user=True)\n\n\ndef compose_explanation(url):\n return \"If you would like {} to be stored please react to it with a :+1:, \\\nif you would like it to be ignored use :-1:\".format(url)\n\n\ndef ask_confirmation(message, slack_client):\n bot_says(message['channel'],\n compose_explanation(message['url']),\n slack_client)\n\n\ndef compose_url_list(url_cache_list):\n if len(url_cache_list) == 0:\n return \"The list is empty\"\n\n list_message = \"The list of urls to be confirmed is: \\n\"\n\n for index in range(0, len(url_cache_list)):\n extra = \"{} - {} \\n\".format(index, url_cache_list[index]['url'])\n list_message = list_message + extra\n\n return list_message\n\n\ndef list_cached_urls(url_cache_list, channel, slack_client):\n bot_says(channel,\n compose_url_list(url_cache_list),\n slack_client)\n","new_contents":"def bot_says(channel, text, slack_client):\n return slack_client.api_call(\"chat.postMessage\",\n channel=channel,\n text=text,\n as_user=True)\n\n\ndef compose_explanation(url):\n return \"If you would like {} to be stored please react to it with a :+1:, \\\nif you would like it to be ignored use :-1:\".format(url)\n\n\ndef ask_confirmation(message, slack_client):\n bot_says(message['channel'],\n compose_explanation(message['url']),\n slack_client)\n\n\ndef compose_url_list(url_cache_list):\n if len(url_cache_list) == 0:\n return \"The list is empty\"\n\n intro = \"The list of urls to be confirmed is: \\n\"\n options = [\"{} - {}\".format(i, v['url']) for i, v in enumerate(url_cache_list)]\n\n return intro + \"\\n\".join(options)\n\n\ndef list_cached_urls(url_cache_list, channel, slack_client):\n bot_says(channel,\n compose_url_list(url_cache_list),\n slack_client)\n","subject":"Change iteration over a collection based on ags suggestion","message":"refactor: Change iteration over a collection based on ags suggestion\n","lang":"Python","license":"mit","repos":"iwi\/linkatos,iwi\/linkatos"} {"commit":"547725be668e1e639ec0e6569e18a1e8bf03585c","old_file":"tictactoe\/settings_production.py","new_file":"tictactoe\/settings_production.py","old_contents":"from django.core.exceptions import ImproperlyConfigured\n\nfrom .settings import *\n\n\ndef get_env_variable(var_name):\n \"\"\"\n Get the environment variable or return exception.\n \"\"\"\n try:\n return os.environ[var_name]\n except KeyError:\n error_msg = 'Set the %s environment variable' % var_name\n raise ImproperlyConfigured(error_msg)\n\n\nDEBUG = False\n\n# TODO: temporarily disabled to test Heroku\n# ALLOWED_HOSTS = ['tictactoe.zupec.net']\n\nSECRET_KEY = get_env_variable('SECRET_KEY')\n\nMIDDLEWARE_CLASSES += (\n # Simplified static file serving.\n # https:\/\/warehouse.python.org\/project\/whitenoise\/\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n)\n\n# TODO: temporarily disabled to test Heroku\n# DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.postgresql',\n# 'NAME': get_env_variable(\"DATABASE_NAME\"),\n# 'USER': get_env_variable(\"DATABASE_USER\"),\n# 'PASSWORD': get_env_variable(\"DATABASE_PASSWORD\"),\n# 'HOST': get_env_variable(\"DATABASE_HOST\"),\n# 'PORT': '5432',\n# },\n# }\n\n","new_contents":"from django.core.exceptions import ImproperlyConfigured\n\nfrom .settings import *\n\n\ndef get_env_variable(var_name):\n \"\"\"\n Get the environment variable or return exception.\n \"\"\"\n try:\n return os.environ[var_name]\n except KeyError:\n error_msg = 'Set the %s environment variable' % var_name\n raise ImproperlyConfigured(error_msg)\n\n\nDEBUG = False\n\nALLOWED_HOSTS = [\n 'tictactoe.zupec.net',\n 'tictactoe-zupec.herokuapp.com',\n]\n\nSECRET_KEY = get_env_variable('SECRET_KEY')\n\nMIDDLEWARE_CLASSES += (\n # Simplified static file serving.\n # https:\/\/warehouse.python.org\/project\/whitenoise\/\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n)\n\n# TODO: temporarily disabled to test Heroku\n# DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.postgresql',\n# 'NAME': get_env_variable(\"DATABASE_NAME\"),\n# 'USER': get_env_variable(\"DATABASE_USER\"),\n# 'PASSWORD': get_env_variable(\"DATABASE_PASSWORD\"),\n# 'HOST': get_env_variable(\"DATABASE_HOST\"),\n# 'PORT': '5432',\n# },\n# }\n\n","subject":"Add Heroku DNS to allowed hosts","message":"Add Heroku DNS to allowed hosts\n","lang":"Python","license":"apache-2.0","repos":"NejcZupec\/tictactoe,NejcZupec\/tictactoe,NejcZupec\/tictactoe"} {"commit":"221f77cfba10cb52ab9fbb639cc948d7a61beb98","old_file":"electionleaflets\/settings\/zappa.py","new_file":"electionleaflets\/settings\/zappa.py","old_contents":"import os\n\nfrom .base import *\n\n# GEOS_LIBRARY_PATH = '\/var\/task\/libgeos_c.so'\n\nALLOWED_HOSTS = ['*']\n\n# Override the database name and user if needed\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.contrib.gis.db.backends.postgis',\n 'HOST': os.environ.get('DATABASE_HOST'),\n 'USER': os.environ.get('DATABASE_USER'),\n 'PORT': '5432',\n 'NAME': os.environ.get('DATABASE_NAME'),\n 'PASSWORD': os.environ.get('DATABASE_PASS')\n }\n}\n\nDEFAULT_FILE_STORAGE = 's3_lambda_storage.S3LambdaStorage'\nSTATICFILES_STORAGE = 's3_lambda_storage.S3StaticLambdaStorage'\nAWS_STORAGE_BUCKET_NAME = \"data.electionleaflets.org\"\nAWS_S3_SECURE_URLS = True\nAWS_S3_HOST = 's3-eu-west-1.amazonaws.com'\nAWS_S3_CUSTOM_DOMAIN = \"data.electionleaflets.org\"\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',\n 'LOCATION': 'el_cache',\n }\n}\n\nTHUMBNAIL_KVSTORE ='sorl.thumbnail.kvstores.cached_db_kvstore.KVStore'\n\nCSRF_TRUSTED_ORIGINS = ['.electionleaflets.org']\n","new_contents":"import os\n\nfrom .base import *\n\nGEOS_LIBRARY_PATH = '\/var\/task\/libgeos_c.so'\n\nALLOWED_HOSTS = ['*']\n\n# Override the database name and user if needed\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.contrib.gis.db.backends.postgis',\n 'HOST': os.environ.get('DATABASE_HOST'),\n 'USER': os.environ.get('DATABASE_USER'),\n 'PORT': '5432',\n 'NAME': os.environ.get('DATABASE_NAME'),\n 'PASSWORD': os.environ.get('DATABASE_PASS')\n }\n}\n\nDEFAULT_FILE_STORAGE = 's3_lambda_storage.S3LambdaStorage'\nSTATICFILES_STORAGE = 's3_lambda_storage.S3StaticLambdaStorage'\nAWS_STORAGE_BUCKET_NAME = \"data.electionleaflets.org\"\nAWS_S3_SECURE_URLS = True\nAWS_S3_HOST = 's3-eu-west-1.amazonaws.com'\nAWS_S3_CUSTOM_DOMAIN = \"data.electionleaflets.org\"\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',\n 'LOCATION': 'el_cache',\n }\n}\n\nTHUMBNAIL_KVSTORE ='sorl.thumbnail.kvstores.cached_db_kvstore.KVStore'\n\nCSRF_TRUSTED_ORIGINS = ['.electionleaflets.org']\n","subject":"Fix the geos library location","message":"Fix the geos library location\n","lang":"Python","license":"mit","repos":"DemocracyClub\/electionleaflets,DemocracyClub\/electionleaflets,DemocracyClub\/electionleaflets"} {"commit":"32e2d6e866cee45d4955aa020d9b9bd3c0a2b700","old_file":"pudb\/__init__.py","new_file":"pudb\/__init__.py","old_contents":"VERSION = \"0.91.2\"\n\n\n\n\nCURRENT_DEBUGGER = [None]\ndef set_trace():\n if CURRENT_DEBUGGER[0] is None:\n from pudb.debugger import Debugger\n dbg = Debugger()\n CURRENT_DEBUGGER[0] = dbg\n\n import sys\n dbg.set_trace(sys._getframe().f_back)\n\n\n\n\ndef post_mortem(t):\n p = Debugger()\n p.reset()\n while t.tb_next is not None:\n t = t.tb_next\n p.interaction(t.tb_frame, t)\n\n\n\n\ndef pm():\n import sys\n post_mortem(sys.last_traceback)\n","new_contents":"VERSION = \"0.91.2\"\n\n\n\n\nCURRENT_DEBUGGER = [None]\ndef set_trace():\n if CURRENT_DEBUGGER[0] is None:\n from pudb.debugger import Debugger\n dbg = Debugger()\n CURRENT_DEBUGGER[0] = dbg\n\n import sys\n dbg.set_trace(sys._getframe().f_back)\n\n\n\n\ndef post_mortem(t):\n p = Debugger()\n p.reset()\n while t.tb_next is not None:\n t = t.tb_next\n p.interaction(t.tb_frame, t)\n\n\n\n\ndef pm():\n import sys\n post_mortem(sys.last_traceback)\n\n\n\n\nif __name__ == \"__main__\":\n print \"To keep Python 2.6 happy, you now need to type 'python -m pudb.run'.\"\n print \"Sorry for the inconvenience.\"\n","subject":"Print a warning about the move to '-m pudb.run'.","message":"Print a warning about the move to '-m pudb.run'.\n","lang":"Python","license":"mit","repos":"amigrave\/pudb,albfan\/pudb,amigrave\/pudb,albfan\/pudb"} {"commit":"bace1847cb9479bfeb271f38eef502f8d3ac240a","old_file":"qipr\/registry\/forms\/facet_form.py","new_file":"qipr\/registry\/forms\/facet_form.py","old_contents":"from registry.models import *\nfrom operator import attrgetter\n\nfacet_Models = [\n BigAim,\n Category,\n ClinicalArea,\n ClinicalSetting,\n Keyword,\n SafetyTarget,\n]\n\nclass FacetForm:\n def __init__(self):\n self.facet_categories = [model.__name__ for model in facet_Models]\n for model in facet_Models:\n models = list(model.objects.all())\n models.sort(key=lambda m : m.project_set.count(), reverse=True)\n setattr(self, model.__name__, models)\n\n","new_contents":"from registry.models import *\nfrom operator import attrgetter\n\nfacet_Models = [\n BigAim,\n ClinicalArea,\n ClinicalSetting,\n Keyword,\n]\n\nclass FacetForm:\n def __init__(self):\n self.facet_categories = [model.__name__ for model in facet_Models]\n for model in facet_Models:\n models = list(model.objects.all())\n models.sort(key=lambda m : m.project_set.count(), reverse=True)\n setattr(self, model.__name__, models)\n\n","subject":"Remove facets from main registry project page","message":"Remove facets from main registry project page\n","lang":"Python","license":"apache-2.0","repos":"ctsit\/qipr,ctsit\/qipr,ctsit\/qipr,ctsit\/qipr,ctsit\/qipr"} {"commit":"4792515739c4ee671b86aeed39022ad8934d5d7c","old_file":"artie\/applications.py","new_file":"artie\/applications.py","old_contents":"import os\nimport re\nimport sys\n\nimport settings\n\ntriggers = set()\ntimers = set()\n\nclass BadApplicationError(Exception): pass\n\ndef trigger(expression):\n def decorator(func):\n triggers.add((re.compile(expression), func))\n return decorator\n\ndef timer(time):\n def decorator(func):\n timers.add((time, func))\n return decorator\n\nsys.path.insert(0, settings.APPLICATION_PATH)\n\nfor filename in os.listdir(settings.APPLICATION_PATH):\n if filename != '__init__.py' and filename[-3:] == '.py':\n if filename == 'triggers.py':\n raise BadApplicationException(\n \"Application file can't be called triggers.py\"\n )\n module = filename[:-3]\n if module in sys.modules:\n reload(sys.modules[module])\n else:\n __import__(module, locals(), globals())\n","new_contents":"import os\nimport re\nimport sys\n\nimport settings\n\ntriggers = set()\ntimers = set()\n\nclass BadApplicationError(Exception): pass\n\ndef trigger(expression):\n def decorator(func):\n triggers.add((re.compile(expression), func))\n return decorator\n\ndef timer(time):\n def decorator(func):\n timers.add((time, func))\n return decorator\n\nsys.path.insert(0, settings.APPLICATION_PATH)\n\nfor filename in os.listdir(settings.APPLICATION_PATH):\n if filename != '__init__.py' and filename.endswith('.py'):\n if filename == 'triggers.py':\n raise BadApplicationException(\n \"Application file can't be called triggers.py\"\n )\n module = filename[:-3]\n if module in sys.modules:\n reload(sys.modules[module])\n else:\n __import__(module, locals(), globals())\n","subject":"Use `endswith` instead of string indeces.","message":"Use `endswith` instead of string indeces.\n","lang":"Python","license":"mit","repos":"sumeet\/artie"} {"commit":"46e1672bb0226ae8157d63a2d73edbfefcd644e9","old_file":"src\/test\/test_google_maps.py","new_file":"src\/test\/test_google_maps.py","old_contents":"import unittest\nimport googlemaps\nfrom pyrules2.googlemaps import driving_roundtrip\n\nCOP = 'Copenhagen, Denmark'\nMAD = 'Madrid, Spain'\nBER = 'Berlin, Germany'\nLIS = 'Lisbon, Portugal'\n\nKM = 1000\n\n\nclass Test(unittest.TestCase):\n def setUp(self):\n # TODO: Sane way to import key\n with open('\/Users\/nhc\/git\/pyrules\/google-maps-api-key.txt') as f:\n self.key = f.read()\n\n def test_roundtrip(self):\n c = googlemaps.Client(key=self.key)\n r = driving_roundtrip(c, COP, MAD, BER, LIS)\n self.assertGreater(r.distance(), 10000 * KM) # Bad\n min_dist, best_itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives()))\n self.assertLess(min_dist, 6500 * KM) # Good\n self.assertListEqual([COP, LIS, MAD, BER, COP], best_itinerary)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","new_contents":"from os import environ\nimport unittest\nimport googlemaps\nfrom pyrules2.googlemaps import driving_roundtrip\n\nCOP = 'Copenhagen, Denmark'\nMAD = 'Madrid, Spain'\nBER = 'Berlin, Germany'\nLIS = 'Lisbon, Portugal'\n\nKM = 1000\n\n\nclass Test(unittest.TestCase):\n def setUp(self):\n try:\n key = environ['GOOGLE_MAPS_API_KEY']\n except KeyError:\n self.fail('This test requires an API key for Google Maps in the environment variable GOOGLE_MAPS_API_KEY')\n self.client = googlemaps.Client(key=key)\n\n def test_roundtrip(self):\n r = driving_roundtrip(self.client, COP, MAD, BER, LIS)\n self.assertGreater(r.distance(), 10000 * KM) # Bad\n min_dist, itinerary = min(((a.distance(), a.itinerary()) for a in r.alternatives()))\n self.assertLess(min_dist, 6500 * KM) # Good\n self.assertListEqual([COP, LIS, MAD, BER, COP], itinerary)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","subject":"Move API key to environment variable","message":"Move API key to environment variable\n","lang":"Python","license":"mit","repos":"mr-niels-christensen\/pyrules"} {"commit":"1bc3bd857e6b62d9cd63c6b2edfd7003dd8110b4","old_file":"modules\/apis\/sr_com.py","new_file":"modules\/apis\/sr_com.py","old_contents":"#! \/usr\/bin\/env python2.7\n\nimport modules.apis.api_base as api\n\nclass SRcomAPI(api.API):\n\n def __init(self, session = None):\n super(SRcomAPI, self).__init__(\"http:\/\/www.speedrun.com\/api\/v1\", session)\n\n def get_user_pbs(self, user, embeds = \"\", **kwargs):\n # Embeds should be list of parameters\n endpoint = \"\/users\/{0}\/personal-bests?embed={1}\".format(user, \",\".join(embeds))\n success, response = self.get(endpoint, **kwargs)\n return success, response\n","new_contents":"#! \/usr\/bin\/env python2.7\n\nimport modules.apis.api_base as api\n\nclass SRcomAPI(api.API):\n\n def __init__(self, session = None):\n super(SRcomAPI, self).__init__(\"http:\/\/www.speedrun.com\/api\/v1\", session)\n\n def get_user_pbs(self, user, embeds = \"\", **kwargs):\n # Embeds should be list of parameters\n endpoint = \"\/users\/{0}\/personal-bests?embed={1}\".format(user, \",\".join(embeds))\n success, response = self.get(endpoint, **kwargs)\n return success, response\n","subject":"Fix forgotten __ for init","message":"Fix forgotten __ for init\n","lang":"Python","license":"mit","repos":"BatedUrGonnaDie\/salty_bot"} {"commit":"51d1701bbc8b25bfd7b4f70c83fec7a46d965bef","old_file":"fireplace\/cards\/brawl\/decks_assemble.py","new_file":"fireplace\/cards\/brawl\/decks_assemble.py","old_contents":"\"\"\"\nDecks Assemble\n\"\"\"\n\nfrom ..utils import *\n\n\n# Tarnished Coin\nclass TB_011:\n\tplay = ManaThisTurn(CONTROLLER, 1)\n","new_contents":"\"\"\"\nDecks Assemble\n\"\"\"\n\nfrom ..utils import *\n\n\n# Deckbuilding Enchant\nclass TB_010:\n\tevents = (\n\t\tOWN_TURN_BEGIN.on(Discover(CONTROLLER, RandomCollectible())),\n\t\tPlay(CONTROLLER).on(Shuffle(CONTROLLER, Copy(Play.CARD))),\n\t\tOWN_TURN_END.on(Shuffle(CONTROLLER, FRIENDLY_HAND))\n\t)\n\n# Tarnished Coin\nclass TB_011:\n\tplay = ManaThisTurn(CONTROLLER, 1)\n","subject":"Implement Decks Assemble brawl rules on the Deckbuilding Enchant","message":"Implement Decks Assemble brawl rules on the Deckbuilding Enchant\n","lang":"Python","license":"agpl-3.0","repos":"Ragowit\/fireplace,NightKev\/fireplace,beheh\/fireplace,smallnamespace\/fireplace,Ragowit\/fireplace,jleclanche\/fireplace,smallnamespace\/fireplace"} {"commit":"3f4415bd551b52418a5999a1ea64e31d15097802","old_file":"framework\/transactions\/commands.py","new_file":"framework\/transactions\/commands.py","old_contents":"# -*- coding: utf-8 -*-\n\nfrom framework.mongo import database as proxy_database\n\n\ndef begin(database=None):\n database = database or proxy_database\n database.command('beginTransaction')\n\n\ndef rollback(database=None):\n database = database or proxy_database\n database.command('rollbackTransaction')\n\n\ndef commit(database=None):\n database = database or proxy_database\n database.command('commitTransaction')\n\n\ndef show_live(database=None):\n database = database or proxy_database\n return database.command('showLiveTransactions')\n","new_contents":"# -*- coding: utf-8 -*-\n\nfrom framework.mongo import database as proxy_database\nfrom pymongo.errors import OperationFailure\n\n\ndef begin(database=None):\n database = database or proxy_database\n database.command('beginTransaction')\n\n\ndef rollback(database=None):\n database = database or proxy_database\n try:\n database.command('rollbackTransaction')\n except OperationFailure:\n pass\n\n\ndef commit(database=None):\n database = database or proxy_database\n database.command('commitTransaction')\n\n\ndef show_live(database=None):\n database = database or proxy_database\n return database.command('showLiveTransactions')\n","subject":"Fix rollback transaction issue bby adding except for Operation Failure to rollback","message":"Fix rollback transaction issue bby adding except for Operation Failure to rollback\n","lang":"Python","license":"apache-2.0","repos":"erinspace\/osf.io,doublebits\/osf.io,brandonPurvis\/osf.io,brandonPurvis\/osf.io,kwierman\/osf.io,GageGaskins\/osf.io,hmoco\/osf.io,amyshi188\/osf.io,brandonPurvis\/osf.io,felliott\/osf.io,cosenal\/osf.io,abought\/osf.io,kch8qx\/osf.io,haoyuchen1992\/osf.io,himanshuo\/osf.io,sbt9uc\/osf.io,bdyetton\/prettychart,samchrisinger\/osf.io,monikagrabowska\/osf.io,mluo613\/osf.io,TomHeatwole\/osf.io,bdyetton\/prettychart,CenterForOpenScience\/osf.io,bdyetton\/prettychart,laurenrevere\/osf.io,haoyuchen1992\/osf.io,leb2dg\/osf.io,binoculars\/osf.io,njantrania\/osf.io,wearpants\/osf.io,ZobairAlijan\/osf.io,TomHeatwole\/osf.io,icereval\/osf.io,mattclark\/osf.io,monikagrabowska\/osf.io,jeffreyliu3230\/osf.io,samanehsan\/osf.io,caseyrygt\/osf.io,billyhunt\/osf.io,adlius\/osf.io,RomanZWang\/osf.io,cldershem\/osf.io,arpitar\/osf.io,caneruguz\/osf.io,mluo613\/osf.io,chrisseto\/osf.io,cslzchen\/osf.io,caneruguz\/osf.io,lyndsysimon\/osf.io,emetsger\/osf.io,ckc6cz\/osf.io,RomanZWang\/osf.io,RomanZWang\/osf.io,caseyrygt\/osf.io,caseyrygt\/osf.io,jolene-esposito\/osf.io,asanfilippo7\/osf.io,monikagrabowska\/osf.io,alexschiller\/osf.io,caneruguz\/osf.io,CenterForOpenScience\/osf.io,kwierman\/osf.io,dplorimer\/osf,lamdnhan\/osf.io,billyhunt\/osf.io,aaxelb\/osf.io,sloria\/osf.io,ticklemepierce\/osf.io,crcresearch\/osf.io,alexschiller\/osf.io,SSJohns\/osf.io,ZobairAlijan\/osf.io,brianjgeiger\/osf.io,MerlinZhang\/osf.io,lyndsysimon\/osf.io,alexschiller\/osf.io,fabianvf\/osf.io,saradbowman\/osf.io,pattisdr\/osf.io,arpitar\/osf.io,mfraezz\/osf.io,KAsante95\/osf.io,petermalcolm\/osf.io,DanielSBrown\/osf.io,kushG\/osf.io,billyhunt\/osf.io,DanielSBrown\/osf.io,icereval\/osf.io,Johnetordoff\/osf.io,baylee-d\/osf.io,haoyuchen1992\/osf.io,zachjanicki\/osf.io,Nesiehr\/osf.io,laurenrevere\/osf.io,chrisseto\/osf.io,Johnetordoff\/osf.io,cslzchen\/osf.io,reinaH\/osf.io,KAsante95\/osf.io,fabianvf\/osf.io,abought\/osf.io,felliott\/osf.io,GageGaskins\/osf.io,SSJohns\/osf.io,adlius\/osf.io,Ghalko\/osf.io,binoculars\/osf.io,acshi\/osf.io,revanthkolli\/osf.io,adlius\/osf.io,petermalcolm\/osf.io,samanehsan\/osf.io,lamdnhan\/osf.io,asanfilippo7\/osf.io,erinspace\/osf.io,acshi\/osf.io,mattclark\/osf.io,mluo613\/osf.io,jnayak1\/osf.io,chennan47\/osf.io,saradbowman\/osf.io,leb2dg\/osf.io,DanielSBrown\/osf.io,TomHeatwole\/osf.io,himanshuo\/osf.io,KAsante95\/osf.io,chennan47\/osf.io,acshi\/osf.io,hmoco\/osf.io,pattisdr\/osf.io,revanthkolli\/osf.io,zachjanicki\/osf.io,ckc6cz\/osf.io,icereval\/osf.io,HarryRybacki\/osf.io,kch8qx\/osf.io,HalcyonChimera\/osf.io,brianjgeiger\/osf.io,jnayak1\/osf.io,brandonPurvis\/osf.io,rdhyee\/osf.io,sbt9uc\/osf.io,MerlinZhang\/osf.io,sbt9uc\/osf.io,danielneis\/osf.io,caseyrollins\/osf.io,doublebits\/osf.io,SSJohns\/osf.io,leb2dg\/osf.io,aaxelb\/osf.io,mluke93\/osf.io,rdhyee\/osf.io,kushG\/osf.io,revanthkolli\/osf.io,Nesiehr\/osf.io,HalcyonChimera\/osf.io,adlius\/osf.io,cosenal\/osf.io,danielneis\/osf.io,hmoco\/osf.io,GaryKriebel\/osf.io,haoyuchen1992\/osf.io,barbour-em\/osf.io,jeffreyliu3230\/osf.io,njantrania\/osf.io,sloria\/osf.io,wearpants\/osf.io,GageGaskins\/osf.io,wearpants\/osf.io,jolene-esposito\/osf.io,alexschiller\/osf.io,emetsger\/osf.io,Nesiehr\/osf.io,abought\/osf.io,abought\/osf.io,leb2dg\/osf.io,zkraime\/osf.io,Ghalko\/osf.io,zachjanicki\/osf.io,GaryKriebel\/osf.io,ckc6cz\/osf.io,Ghalko\/osf.io,mfraezz\/osf.io,rdhyee\/osf.io,TomBaxter\/osf.io,pattisdr\/osf.io,mluo613\/osf.io,ticklemepierce\/osf.io,reinaH\/osf.io,jolene-esposito\/osf.io,cslzchen\/osf.io,crcresearch\/osf.io,barbour-em\/osf.io,njantrania\/osf.io,kch8qx\/osf.io,barbour-em\/osf.io,samchrisinger\/osf.io,cwisecarver\/osf.io,zamattiac\/osf.io,monikagrabowska\/osf.io,cwisecarver\/osf.io,samchrisinger\/osf.io,hmoco\/osf.io,fabianvf\/osf.io,reinaH\/osf.io,erinspace\/osf.io,zamattiac\/osf.io,TomHeatwole\/osf.io,revanthkolli\/osf.io,amyshi188\/osf.io,brianjgeiger\/osf.io,njantrania\/osf.io,RomanZWang\/osf.io,alexschiller\/osf.io,lamdnhan\/osf.io,monikagrabowska\/osf.io,mluke93\/osf.io,samchrisinger\/osf.io,GageGaskins\/osf.io,cosenal\/osf.io,HalcyonChimera\/osf.io,caseyrollins\/osf.io,HarryRybacki\/osf.io,Nesiehr\/osf.io,doublebits\/osf.io,GaryKriebel\/osf.io,cldershem\/osf.io,mfraezz\/osf.io,HalcyonChimera\/osf.io,aaxelb\/osf.io,binoculars\/osf.io,lyndsysimon\/osf.io,jnayak1\/osf.io,wearpants\/osf.io,cosenal\/osf.io,fabianvf\/osf.io,zkraime\/osf.io,aaxelb\/osf.io,mattclark\/osf.io,jinluyuan\/osf.io,rdhyee\/osf.io,kushG\/osf.io,jmcarp\/osf.io,emetsger\/osf.io,mluke93\/osf.io,kushG\/osf.io,ckc6cz\/osf.io,jeffreyliu3230\/osf.io,doublebits\/osf.io,petermalcolm\/osf.io,zachjanicki\/osf.io,acshi\/osf.io,billyhunt\/osf.io,caseyrygt\/osf.io,ticklemepierce\/osf.io,reinaH\/osf.io,Johnetordoff\/osf.io,zamattiac\/osf.io,ZobairAlijan\/osf.io,asanfilippo7\/osf.io,Johnetordoff\/osf.io,emetsger\/osf.io,amyshi188\/osf.io,KAsante95\/osf.io,ZobairAlijan\/osf.io,jinluyuan\/osf.io,petermalcolm\/osf.io,TomBaxter\/osf.io,ticklemepierce\/osf.io,cldershem\/osf.io,SSJohns\/osf.io,jeffreyliu3230\/osf.io,sloria\/osf.io,GaryKriebel\/osf.io,baylee-d\/osf.io,kch8qx\/osf.io,laurenrevere\/osf.io,jinluyuan\/osf.io,lyndsysimon\/osf.io,amyshi188\/osf.io,mluke93\/osf.io,Ghalko\/osf.io,himanshuo\/osf.io,GageGaskins\/osf.io,kwierman\/osf.io,samanehsan\/osf.io,jnayak1\/osf.io,arpitar\/osf.io,jmcarp\/osf.io,zkraime\/osf.io,zamattiac\/osf.io,crcresearch\/osf.io,himanshuo\/osf.io,felliott\/osf.io,jmcarp\/osf.io,HarryRybacki\/osf.io,mluo613\/osf.io,HarryRybacki\/osf.io,acshi\/osf.io,bdyetton\/prettychart,danielneis\/osf.io,cldershem\/osf.io,jolene-esposito\/osf.io,jinluyuan\/osf.io,kch8qx\/osf.io,danielneis\/osf.io,caneruguz\/osf.io,asanfilippo7\/osf.io,samanehsan\/osf.io,cwisecarver\/osf.io,billyhunt\/osf.io,jmcarp\/osf.io,CenterForOpenScience\/osf.io,MerlinZhang\/osf.io,sbt9uc\/osf.io,brianjgeiger\/osf.io,zkraime\/osf.io,TomBaxter\/osf.io,chrisseto\/osf.io,chennan47\/osf.io,mfraezz\/osf.io,felliott\/osf.io,doublebits\/osf.io,brandonPurvis\/osf.io,baylee-d\/osf.io,MerlinZhang\/osf.io,cwisecarver\/osf.io,cslzchen\/osf.io,kwierman\/osf.io,DanielSBrown\/osf.io,arpitar\/osf.io,barbour-em\/osf.io,chrisseto\/osf.io,caseyrollins\/osf.io,KAsante95\/osf.io,CenterForOpenScience\/osf.io,RomanZWang\/osf.io,lamdnhan\/osf.io,dplorimer\/osf,dplorimer\/osf,dplorimer\/osf"} {"commit":"7076e7eb0fcce37159aa58c2c0699674434115d9","old_file":"relaygram\/http_server.py","new_file":"relaygram\/http_server.py","old_contents":"import http.server\nfrom threading import Thread\nimport os.path\n\n\nclass HTTPHandler:\n def __init__(self, config):\n self.config = config\n\n handler = HTTPHandler.make_http_handler(self.config['media_dir'])\n self.httpd = http.server.HTTPServer(('', self.config['media']['port']), handler)\n\n self.thread = Thread(target=self.main_loop)\n\n def run(self):\n self.thread.start()\n return self\n\n def main_loop(self):\n self.httpd.serve_forever()\n\n @staticmethod\n def make_http_handler(root_path):\n class RelayGramHTTPHandler(http.server.BaseHTTPRequestHandler):\n def __init__(self, *args, **kwargs):\n super(RelayGramHTTPHandler, self).__init__(*args, **kwargs)\n\n def do_GET(self):\n file_path = os.path.abspath(root_path + self.path)\n\n if os.path.commonpath([root_path, file_path]) != os.path.abspath(root_path): # Detect path traversal attempt\n self.send_error(501, \"Nice try\")\n else:\n if not os.path.exists(file_path) or not os.path.isfile(file_path):\n self.send_error(404, 'File Not Found')\n else:\n self.send_response(200)\n self.wfile.write(open(file_path, mode='rb').read())\n\n return RelayGramHTTPHandler\n","new_contents":"import http.server\nfrom threading import Thread\nimport os.path\n\n\nclass HTTPHandler:\n def __init__(self, config):\n self.config = config\n\n handler = HTTPHandler.make_http_handler(self.config['media_dir'])\n self.httpd = http.server.HTTPServer(('', self.config['media']['port']), handler)\n\n self.thread = Thread(target=self.main_loop)\n\n def run(self):\n self.thread.start()\n return self\n\n def main_loop(self):\n self.httpd.serve_forever()\n\n @staticmethod\n def make_http_handler(root_path):\n class RelayGramHTTPHandler(http.server.BaseHTTPRequestHandler):\n def __init__(self, *args, **kwargs):\n super(RelayGramHTTPHandler, self).__init__(*args, **kwargs)\n\n def do_GET(self):\n file_path = os.path.abspath(root_path + self.path)\n\n if os.path.commonprefix([root_path, file_path]) != os.path.abspath(root_path): # Detect path traversal attempt\n self.send_error(501, \"Nice try\")\n else:\n if not os.path.exists(file_path) or not os.path.isfile(file_path):\n self.send_error(404, 'File Not Found')\n else:\n self.send_response(200)\n self.wfile.write(open(file_path, mode='rb').read())\n\n return RelayGramHTTPHandler\n","subject":"Use commonprefix to break dep on 3.5","message":"Use commonprefix to break dep on 3.5\n","lang":"Python","license":"mit","repos":"Surye\/relaygram"} {"commit":"43dca4ad969e44bb753c152e8f7768febea6fb68","old_file":"quantecon\/__init__.py","new_file":"quantecon\/__init__.py","old_contents":"\"\"\"\nImport the main names to top level.\n\"\"\"\n\nfrom .compute_fp import compute_fixed_point\nfrom .discrete_rv import DiscreteRV\nfrom .ecdf import ECDF\nfrom .estspec import smooth, periodogram, ar_periodogram\nfrom .graph_tools import DiGraph\nfrom .gridtools import cartesian, mlinspace\nfrom .kalman import Kalman\nfrom .lae import LAE\nfrom .arma import ARMA\nfrom .lqcontrol import LQ\nfrom .lqnash import nnash\nfrom .lss import LinearStateSpace\nfrom .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati\nfrom .quadsums import var_quadratic_sum, m_quadratic_sum\n#->Propose Delete From Top Level\nfrom .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen \t #Promote to keep current examples working\nfrom .markov import mc_compute_stationary, mc_sample_path \t\t\t\t\t\t\t#Imports that Should be Deprecated with markov package\n#<-\nfrom .rank_nullspace import rank_est, nullspace\nfrom .robustlq import RBLQ\nfrom . import quad as quad\nfrom .util import searchsorted\n\n#Add Version Attribute\nfrom .version import version as __version__\n","new_contents":"\"\"\"\nImport the main names to top level.\n\"\"\"\n\ntry:\n\timport numba\nexcept:\n\traise ImportError(\"Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.\")\n\nfrom .compute_fp import compute_fixed_point\nfrom .discrete_rv import DiscreteRV\nfrom .ecdf import ECDF\nfrom .estspec import smooth, periodogram, ar_periodogram\nfrom .graph_tools import DiGraph\nfrom .gridtools import cartesian, mlinspace\nfrom .kalman import Kalman\nfrom .lae import LAE\nfrom .arma import ARMA\nfrom .lqcontrol import LQ\nfrom .lqnash import nnash\nfrom .lss import LinearStateSpace\nfrom .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati\nfrom .quadsums import var_quadratic_sum, m_quadratic_sum\n#->Propose Delete From Top Level\nfrom .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen \t #Promote to keep current examples working\nfrom .markov import mc_compute_stationary, mc_sample_path \t\t\t\t\t\t\t#Imports that Should be Deprecated with markov package\n#<-\nfrom .rank_nullspace import rank_est, nullspace\nfrom .robustlq import RBLQ\nfrom . import quad as quad\nfrom .util import searchsorted\n\n#Add Version Attribute\nfrom .version import version as __version__\n","subject":"Add Check for numba in base anaconda distribution. If not found issue meaningful warning message","message":"Add Check for numba in base anaconda distribution. If not found issue meaningful warning message\n","lang":"Python","license":"bsd-3-clause","repos":"oyamad\/QuantEcon.py,QuantEcon\/QuantEcon.py,QuantEcon\/QuantEcon.py,oyamad\/QuantEcon.py"} {"commit":"191812e1e16aea352c1a47cd5bd6cd3f0ed67802","old_file":"runtests.py","new_file":"runtests.py","old_contents":"#!\/usr\/bin\/env python\nimport sys\nfrom django.conf import settings\nfrom django.core.management import execute_from_command_line\n\nif not settings.configured:\n settings.configure(\n DEBUG = True,\n TEMPLATE_DEBUG = True,\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memory:'\n }\n },\n TEMPLATE_LOADERS = (\n 'django.template.loaders.app_directories.Loader',\n ),\n INSTALLED_APPS = (\n 'template_analyzer',\n )\n )\n\ndef runtests():\n argv = sys.argv[:1] + ['test', 'template_analyzer', '--traceback'] + sys.argv[1:]\n execute_from_command_line(argv)\n\nif __name__ == '__main__':\n runtests()\n","new_contents":"#!\/usr\/bin\/env python\nimport sys\nfrom django.conf import settings\nfrom django.core.management import execute_from_command_line\n\nif not settings.configured:\n settings.configure(\n DEBUG = True,\n TEMPLATE_DEBUG = True,\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memory:'\n }\n },\n TEMPLATE_LOADERS = (\n 'django.template.loaders.app_directories.Loader',\n ),\n INSTALLED_APPS = (\n 'template_analyzer',\n ),\n MIDDLEWARE_CLASSES = (),\n )\n\ndef runtests():\n argv = sys.argv[:1] + ['test', 'template_analyzer', '--traceback'] + sys.argv[1:]\n execute_from_command_line(argv)\n\nif __name__ == '__main__':\n runtests()\n","subject":"Remove warning for Django 1.7","message":"Remove warning for Django 1.7\n","lang":"Python","license":"bsd-3-clause","repos":"edoburu\/django-template-analyzer,edoburu\/django-template-analyzer"} {"commit":"37fcbbe7bb8a46bd32fc92341d1b42f2400abc9b","old_file":"runtests.py","new_file":"runtests.py","old_contents":"#!\/usr\/bin\/python\nimport unittest\nfrom firmant.utils import get_module\n# Import this now to avoid it throwing errors.\nimport pytz\n\nfrom firmant.configuration import settings\nfrom test.configuration import suite as configuration_tests\nfrom test.datasource.atom import suite as atom_tests\nfrom test.plugins.datasource.flatfile.atom import suite as flatfile_atom_tests\nfrom test.resolvers import suite as resolvers_tests\n\nif __name__ == '__main__':\n settings.reconfigure('test_settings')\n for plugin in settings['PLUGINS']:\n try:\n mod = get_module(plugin)\n except ImportError:\n raise\n suite = unittest.TestSuite()\n suite.addTests(configuration_tests)\n suite.addTests(atom_tests)\n suite.addTests(flatfile_atom_tests)\n suite.addTests(resolvers_tests)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","new_contents":"#!\/usr\/bin\/python\nimport unittest\nfrom firmant.utils import get_module\n# Import this now to avoid it throwing errors.\nimport pytz\n\nfrom firmant.configuration import settings\nfrom test.configuration import suite as configuration_tests\nfrom test.datasource.atom import suite as atom_tests\nfrom test.plugins.datasource.flatfile.atom import suite as flatfile_atom_tests\nfrom test.resolvers import suite as resolvers_tests\n\nif __name__ == '__main__':\n settings.reconfigure('test_settings')\n for plugin in settings['PLUGINS']:\n try:\n mod = get_module(plugin)\n except ImportError:\n raise\n suite = unittest.TestSuite()\n suite.addTests(configuration_tests)\n suite.addTests(atom_tests)\n #suite.addTests(flatfile_atom_tests)\n suite.addTests(resolvers_tests)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","subject":"Disable flatfile tests until atom tests complete.","message":"Disable flatfile tests until atom tests complete.\n","lang":"Python","license":"bsd-3-clause","repos":"rescrv\/firmant"} {"commit":"2a5b81ff6272f346bcca3bdc97e3d6d9dfe2b017","old_file":"src\/mmw\/apps\/bigcz\/models.py","new_file":"src\/mmw\/apps\/bigcz\/models.py","old_contents":"# -*- coding: utf-8 -*-\nfrom django.contrib.gis.geos import Polygon\n\n\nclass ResourceLink(object):\n def __init__(self, type, href):\n self.type = type\n self.href = href\n\n\nclass Resource(object):\n def __init__(self, id, description, author, links, title,\n created_at, updated_at, geom):\n self.id = id\n self.title = title\n self.description = description\n self.author = author\n self.links = links\n self.created_at = created_at\n self.updated_at = updated_at\n self.geom = geom\n\n\nclass ResourceList(object):\n def __init__(self, api_url, catalog, count, results):\n self.api_url = api_url\n self.catalog = catalog\n self.count = count\n self.results = results\n\n\nclass BBox(object):\n \"\"\"\n Bounding box from incoming search API request.\n \"\"\"\n def __init__(self, xmin, ymin, xmax, ymax):\n self.xmin = xmin\n self.xmax = xmax\n self.ymin = ymin\n self.ymax = ymax\n\n def area(self):\n polygon = Polygon.from_bbox((\n self.xmin, self.ymin,\n self.xmax, self.ymax))\n polygon.set_srid(4326)\n\n return polygon.transform(5070, clone=True).area\n","new_contents":"# -*- coding: utf-8 -*-\nfrom django.contrib.gis.geos import Polygon\n\n\nclass ResourceLink(object):\n def __init__(self, type, href):\n self.type = type\n self.href = href\n\n\nclass Resource(object):\n def __init__(self, id, description, author, links, title,\n created_at, updated_at, geom):\n self.id = id\n self.title = title\n self.description = description\n self.author = author\n self.links = links\n self.created_at = created_at\n self.updated_at = updated_at\n self.geom = geom\n\n\nclass ResourceList(object):\n def __init__(self, api_url, catalog, count, results):\n self.api_url = api_url\n self.catalog = catalog\n self.count = count\n self.results = results\n\n\nclass BBox(object):\n \"\"\"\n Bounding box from incoming search API request.\n \"\"\"\n def __init__(self, xmin, ymin, xmax, ymax):\n self.xmin = xmin\n self.xmax = xmax\n self.ymin = ymin\n self.ymax = ymax\n\n def area(self):\n polygon = Polygon.from_bbox((\n self.xmin, self.ymin,\n self.xmax, self.ymax))\n polygon.srid = 4326\n\n return polygon.transform(5070, clone=True).area\n","subject":"Set SRID the new way","message":"Set SRID the new way\n","lang":"Python","license":"apache-2.0","repos":"WikiWatershed\/model-my-watershed,WikiWatershed\/model-my-watershed,WikiWatershed\/model-my-watershed,WikiWatershed\/model-my-watershed,WikiWatershed\/model-my-watershed"} {"commit":"9d3d2beab6ec06ce13126b818029258a66f450f6","old_file":"babelfish\/__init__.py","new_file":"babelfish\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2013 the BabelFish authors. All rights reserved.\n# Use of this source code is governed by the 3-clause BSD license\n# that can be found in the LICENSE file.\n#\n__title__ = 'babelfish'\n__version__ = '0.4.1'\n__author__ = 'Antoine Bertin'\n__license__ = 'BSD'\n__copyright__ = 'Copyright 2013 the BabelFish authors'\n\nfrom .converters import (LanguageConverter, LanguageReverseConverter, LanguageEquivalenceConverter, CountryConverter,\n CountryReverseConverter)\nfrom .country import country_converters, COUNTRIES, COUNTRY_MATRIX, Country\nfrom .exceptions import Error, LanguageConvertError, LanguageReverseError, CountryConvertError, CountryReverseError\nfrom .language import language_converters, LANGUAGES, LANGUAGE_MATRIX, Language\nfrom .script import SCRIPTS, Script\n","new_contents":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2013 the BabelFish authors. All rights reserved.\n# Use of this source code is governed by the 3-clause BSD license\n# that can be found in the LICENSE file.\n#\n__title__ = 'babelfish'\n__version__ = '0.4.1'\n__author__ = 'Antoine Bertin'\n__license__ = 'BSD'\n__copyright__ = 'Copyright 2013 the BabelFish authors'\n\nfrom .converters import (LanguageConverter, LanguageReverseConverter, LanguageEquivalenceConverter, CountryConverter,\n CountryReverseConverter)\nfrom .country import country_converters, COUNTRIES, COUNTRY_MATRIX, Country\nfrom .exceptions import Error, LanguageConvertError, LanguageReverseError, CountryConvertError, CountryReverseError\nfrom .language import language_converters, LANGUAGES, LANGUAGE_MATRIX, Language\nfrom .script import SCRIPTS, SCRIPT_MATRIX, Script\n","subject":"Add SCRIPT_MATRIX to babelfish module imports","message":"Add SCRIPT_MATRIX to babelfish module imports\n","lang":"Python","license":"bsd-3-clause","repos":"Diaoul\/babelfish"} {"commit":"2ad21d67ccde2e25ea5c6d64cdee36dbc6425cbc","old_file":"construct\/tests\/test_mapping.py","new_file":"construct\/tests\/test_mapping.py","old_contents":"import unittest\n\nfrom construct import Flag\n\nclass TestFlag(unittest.TestCase):\n\n def test_parse(self):\n flag = Flag(\"flag\")\n self.assertTrue(flag.parse(\"\\x01\"))\n\n def test_parse_flipped(self):\n flag = Flag(\"flag\", truth=0, falsehood=1)\n self.assertFalse(flag.parse(\"\\x01\"))\n\n def test_build(self):\n flag = Flag(\"flag\")\n self.assertEqual(flag.build(True), \"\\x01\")\n\n def test_build_flipped(self):\n flag = Flag(\"flag\", truth=0, falsehood=1)\n self.assertEqual(flag.build(True), \"\\x00\")\n","new_contents":"import unittest\n\nfrom construct import Flag\n\nclass TestFlag(unittest.TestCase):\n\n def test_parse(self):\n flag = Flag(\"flag\")\n self.assertTrue(flag.parse(\"\\x01\"))\n\n def test_parse_flipped(self):\n flag = Flag(\"flag\", truth=0, falsehood=1)\n self.assertFalse(flag.parse(\"\\x01\"))\n\n def test_parse_default(self):\n flag = Flag(\"flag\")\n self.assertFalse(flag.parse(\"\\x02\"))\n\n def test_parse_default_true(self):\n flag = Flag(\"flag\", default=True)\n self.assertTrue(flag.parse(\"\\x02\"))\n\n def test_build(self):\n flag = Flag(\"flag\")\n self.assertEqual(flag.build(True), \"\\x01\")\n\n def test_build_flipped(self):\n flag = Flag(\"flag\", truth=0, falsehood=1)\n self.assertEqual(flag.build(True), \"\\x00\")\n","subject":"Add a couple more Flag tests.","message":"tests: Add a couple more Flag tests.\n","lang":"Python","license":"mit","repos":"riggs\/construct,mosquito\/construct,gkonstantyno\/construct,MostAwesomeDude\/construct,0000-bigtree\/construct,riggs\/construct,mosquito\/construct,0000-bigtree\/construct,gkonstantyno\/construct,MostAwesomeDude\/construct"} {"commit":"b2dd21b2240eec28881d6162f9e35b16df906219","old_file":"arris_cli.py","new_file":"arris_cli.py","old_contents":"#!\/usr\/bin\/env python\n\n# CLI frontend to Arris modem stat scraper library arris_scraper.py\n\nimport argparse\nimport arris_scraper\nimport json\nimport pprint\n\ndefault_url = 'http:\/\/192.168.100.1\/cgi-bin\/status_cgi'\n\nparser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status pages.')\nparser.add_argument('-f', '--format', choices=['ascii', 'json', 'pprint'], default='ascii', dest='output_format', help='output format')\nparser.add_argument('-u', '--url', default=default_url, help='url of modem status page')\nargs = parser.parse_args()\n\nif args.output_format == 'ascii':\n print(\"ASCII output not yet implemented\")\nelif args.output_format == 'json':\n result = arris_scraper.get_status(args.url)\n print(json.dumps(result))\nelif args.output_format == 'pprint':\n result = arris_scraper.get_status(args.url)\n pprint.pprint(result)\nelse:\n print(\"How in the world did you get here?\")","new_contents":"#!\/usr\/bin\/env python\n\n# CLI frontend to Arris modem stat scraper library arris_scraper.py\n\nimport argparse\nimport arris_scraper\nimport json\nimport pprint\n\ndefault_url = 'http:\/\/192.168.100.1\/cgi-bin\/status_cgi'\n\nparser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status pages.')\nparser.add_argument('-f',\n '--format',\n choices=['ascii', 'json', 'pprint'],\n default='ascii', dest='output_format',\n help='output format')\nparser.add_argument('-u',\n '--url',\n default=default_url,\n help='url of modem status page')\nargs = parser.parse_args()\n\nif args.output_format == 'ascii':\n print(\"ASCII output not yet implemented\")\nelif args.output_format == 'json':\n result = arris_scraper.get_status(args.url)\n print(json.dumps(result))\nelif args.output_format == 'pprint':\n result = arris_scraper.get_status(args.url)\n pprint.pprint(result)\nelse:\n print(\"How in the world did you get here?\")","subject":"Tweak formatting of argparse section to minimize lines extending past 80 chars.","message":"Tweak formatting of argparse section to minimize lines extending past 80 chars.\n","lang":"Python","license":"mit","repos":"wolrah\/arris_stats"} {"commit":"df113db3bfc0ac8774cfe18a7abe7683e7359274","old_file":"slim\/__init__.py","new_file":"slim\/__init__.py","old_contents":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\n\nfrom . import views\n\n\n__version__ = '0.9.0.dev0'\n","new_contents":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\n\nfrom . import views\n\n\n__version__ = '0.9.0'\n","subject":"Update version number for release 0.9","message":"Update version number for release 0.9\n","lang":"Python","license":"mit","repos":"avalentino\/slim,avalentino\/slim"} {"commit":"4d7dff1c335a49d13d420f3c62b1a2d2382351dd","old_file":"trajprocess\/tests\/utils.py","new_file":"trajprocess\/tests\/utils.py","old_contents":"\"\"\"Tools for setting up a fake directory structure for processing.\"\"\"\n\nfrom tempfile import mkdtemp\nimport os\nimport shutil\nimport json\n\nfrom pkg_resources import resource_filename\n\n\ndef write_run_clone(proj, run, clone, gens=None):\n if gens is None:\n gens = [0, 1]\n\n rc = \"data\/PROJ{proj}\/RUN{run}\/CLONE{clone}\/\".format(proj=proj, run=run,\n clone=clone)\n os.makedirs(rc, exist_ok=True)\n tpr_fn = resource_filename(__name__, 'topol.tpr')\n shutil.copy(tpr_fn, \"{}\/frame0.tpr\".format(rc))\n for gen in gens:\n shutil.copy(resource_filename(__name__,\n \"traj_comp.part{:04d}.xtc\".format(\n gen + 1)),\n \"{}\/frame{}.xtc\".format(rc, gen))\n\n\ndef generate_project():\n global wd\n wd = mkdtemp()\n os.chdir(wd)\n write_run_clone(1234, 5, 7)\n write_run_clone(1234, 6, 0)\n with open('structs-p1234.json', 'w') as f:\n json.dump({\n 5: {'struct': 'stru1', 'fext': 'pdb'},\n 6: {'struct': 'stru2', 'fext': 'pdb'}\n }, f)\n\n\ndef cleanup():\n shutil.rmtree(wd)\n","new_contents":"\"\"\"Tools for setting up a fake directory structure for processing.\"\"\"\n\nfrom tempfile import mkdtemp\nimport os\nimport shutil\nimport json\n\nfrom pkg_resources import resource_filename\n\n\n# command for generating reference data:\n# gmx mdrun -nsteps 5000 -s frame0.tpr -cpi -noappend\n#\n# Do that three times.\n\n\ndef write_run_clone(proj, run, clone, gens=None):\n if gens is None:\n gens = [0, 1]\n\n rc = \"data\/PROJ{proj}\/RUN{run}\/CLONE{clone}\/\".format(proj=proj, run=run,\n clone=clone)\n os.makedirs(rc, exist_ok=True)\n tpr_fn = resource_filename(__name__, 'topol.tpr')\n shutil.copy(tpr_fn, \"{}\/frame0.tpr\".format(rc))\n for gen in gens:\n shutil.copy(resource_filename(__name__,\n \"traj_comp.part{:04d}.xtc\".format(\n gen + 1)),\n \"{}\/frame{}.xtc\".format(rc, gen))\n\n\ndef generate_project():\n global wd\n wd = mkdtemp()\n os.chdir(wd)\n write_run_clone(1234, 5, 7)\n write_run_clone(1234, 6, 0)\n with open('structs-p1234.json', 'w') as f:\n json.dump({\n 5: {'struct': 'stru1', 'fext': 'pdb'},\n 6: {'struct': 'stru2', 'fext': 'pdb'}\n }, f)\n\n\ndef cleanup():\n shutil.rmtree(wd)\n","subject":"Add note about how to generate trajectories","message":"Add note about how to generate trajectories\n","lang":"Python","license":"mit","repos":"mpharrigan\/trajprocess,mpharrigan\/trajprocess"} {"commit":"a465922385ef12cf01f2a8a75928470c33f39569","old_file":"snakepit\/directory.py","new_file":"snakepit\/directory.py","old_contents":"\"\"\"\nHiveDB client access via SQLAlchemy\n\"\"\"\n\nimport sqlalchemy as sq\n\nmetadata = sq.MetaData()\n\nhive_primary = sq.Table(\n 'hive_primary_DIMENSION',\n metadata,\n sq.Column('id', sq.Integer,\n nullable=False,\n index=True,\n ),\n sq.Column('node', sq.SmallInteger,\n nullable=False,\n index=True,\n ),\n sq.Column('secondary_index_count', sq.Integer, nullable=False),\n # Hive_ERD.png says \"date\", but I think you want time too\n sq.Column('last_updated', sq.DateTime,\n nullable=False,\n index=True,\n ),\n sq.Column('read_only', sq.Boolean, nullable=False, default=False),\n\n sq.UniqueConstraint('id', 'node'),\n )\n\nhive_secondary = sq.Table(\n 'hive_secondary_RESOURCE_COLUMN',\n metadata,\n sq.Column('id', sq.Integer,\n nullable=True,\n index=True,\n ),\n sq.Column('pkey', sq.Integer,\n sq.ForeignKey(\"hive_primary_TODO.id\"),\n nullable=False,\n index=True,\n ),\n )\n\ndef dynamic_table(table, metadata, name):\n \"\"\"\n Access C{table} under new C{metadata} with new C{name}.\n \"\"\"\n new = metadata.tables.get(name, None)\n if new is not None:\n return new\n\n new = sq.Table(\n name,\n metadata,\n *[c.copy() for c in table.columns])\n return new\n","new_contents":"\"\"\"\nHiveDB client access via SQLAlchemy\n\"\"\"\n\nimport sqlalchemy as sq\n\nmetadata = sq.MetaData()\n\nhive_primary = sq.Table(\n 'hive_primary_DIMENSION',\n metadata,\n sq.Column('id', sq.Integer, primary_key=True),\n sq.Column('node', sq.SmallInteger,\n nullable=False,\n index=True,\n ),\n sq.Column('secondary_index_count', sq.Integer, nullable=False),\n # Hive_ERD.png says \"date\", but I think you want time too\n sq.Column('last_updated', sq.DateTime,\n nullable=False,\n index=True,\n ),\n sq.Column('read_only', sq.Boolean, nullable=False, default=False),\n\n sq.UniqueConstraint('id', 'node'),\n )\n\nhive_secondary = sq.Table(\n 'hive_secondary_RESOURCE_COLUMN',\n metadata,\n sq.Column('id', sq.Integer,\n nullable=True,\n index=True,\n ),\n sq.Column('pkey', sq.Integer,\n sq.ForeignKey(\"hive_primary_TODO.id\"),\n nullable=False,\n index=True,\n ),\n )\n\ndef dynamic_table(table, metadata, name):\n \"\"\"\n Access C{table} under new C{metadata} with new C{name}.\n \"\"\"\n new = metadata.tables.get(name, None)\n if new is not None:\n return new\n\n new = sq.Table(\n name,\n metadata,\n *[c.copy() for c in table.columns])\n return new\n","subject":"Make hive_primary_DIMENSION.id primary key, so autoincrement works.","message":"Make hive_primary_DIMENSION.id primary key, so autoincrement works.\n","lang":"Python","license":"mit","repos":"tv42\/snakepit,tv42\/snakepit"} {"commit":"6f22416734525376b0a2143972b9546df3164751","old_file":"databaker\/databaker_nbconvert.py","new_file":"databaker\/databaker_nbconvert.py","old_contents":"#!\/usr\/bin\/env python\nimport os\nimport subprocess\nimport sys\n\n\ndef main(argv):\n if len(argv) == 0 or len(argv) > 2:\n print(\"Usage: databaker_process.py \")\n print()\n print(\" is optional; it replaces DATABAKER_INPUT_FILE\")\n print(\"in the notebook.\")\n print(\"The input file should also be in the same directory as the\")\n print(\"notebook.\")\n sys.exit(1)\n\n process_env = os.environ.copy()\n\n if len(argv) == 2:\n process_env['DATABAKER_INPUT_FILE'] = argv[1]\n\n # TODO get custom templates working; according to this:\n # https:\/\/github.com\/jupyter\/nbconvert\/issues\/391\n # they should work, but I get TemplateNotFound when using absolute path\n # for template.\n cmd_line = ['jupyter', 'nbconvert', '--to', 'html', '--execute', argv[0]]\n print(\"Running:\", ' '.join(cmd_line))\n subprocess.call(args=cmd_line, env=process_env)\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","new_contents":"#!\/usr\/bin\/env python\nimport os\nimport subprocess\nimport sys\n\n\ndef main(argv=None):\n if argv is None or len(argv) == 0 or len(argv) > 2:\n print(\"Usage: databaker_process.py \")\n print()\n print(\" is optional; it replaces DATABAKER_INPUT_FILE\")\n print(\"in the notebook.\")\n print(\"The input file should also be in the same directory as the\")\n print(\"notebook.\")\n sys.exit(1)\n\n process_env = os.environ.copy()\n\n if len(argv) == 2:\n process_env['DATABAKER_INPUT_FILE'] = argv[1]\n\n # TODO get custom templates working; according to this:\n # https:\/\/github.com\/jupyter\/nbconvert\/issues\/391\n # they should work, but I get TemplateNotFound when using absolute path\n # for template.\n cmd_line = ['jupyter', 'nbconvert', '--to', 'html', '--execute', argv[0]]\n print(\"Running:\", ' '.join(cmd_line))\n subprocess.call(args=cmd_line, env=process_env)\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","subject":"Set default argv to None","message":"Set default argv to None\n","lang":"Python","license":"agpl-3.0","repos":"scraperwiki\/databaker,scraperwiki\/databaker"} {"commit":"34d1bbc36f7d5c66000eec0d6debfd3ede74366f","old_file":"bottle_auth\/custom.py","new_file":"bottle_auth\/custom.py","old_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nimport logging\nfrom bottle import redirect\n\n\nlog = logging.getLogger('bottle-auth.custom')\n\n\nclass Custom(object):\n def __init__(self, login_url=\"\/login\",\n callback_url=\"http:\/\/127.0.0.1:8000\"):\n self.login_url = login_url\n self.callback_url = callback_url\n\n def redirect(self, environ):\n return redirect(self.login_url)\n\n def get_user(self, environ):\n session = environ.get('beaker.session')\n if session.get(\"username\", None) and session.get(\"apikey\", None):\n return session\n return {}\n","new_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nimport logging\nfrom bottle import redirect\n\n\nlog = logging.getLogger('bottle-auth.custom')\n\n\nclass Custom(object):\n def __init__(self, login_url=\"\/login\",\n callback_url=\"http:\/\/127.0.0.1:8000\"):\n self.login_url = login_url\n self.callback_url = callback_url\n\n def redirect(self, environ):\n return redirect(self.login_url)\n\n def get_user(self, environ):\n session = environ.get('beaker.session')\n if session.get(\"username\", None) and session.get(\"apikey\", None):\n return session\n self.redirect(environ)\n","subject":"Fix Custom class, user exit in beaker.session redirect to login page","message":"Fix Custom class, user exit in beaker.session\nredirect to login page\n","lang":"Python","license":"mit","repos":"avelino\/bottle-auth"} {"commit":"66edf9f04c1b23681fae4234a8b297868e66b7aa","old_file":"osmaxx-py\/osmaxx\/excerptexport\/models\/excerpt.py","new_file":"osmaxx-py\/osmaxx\/excerptexport\/models\/excerpt.py","old_contents":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass Excerpt(models.Model):\n name = models.CharField(max_length=128, verbose_name=_('name'), blank=False)\n is_public = models.BooleanField(default=False, verbose_name=_('is public'))\n is_active = models.BooleanField(default=True, verbose_name=_('is active'))\n\n owner = models.ForeignKey(User, related_name='excerpts', verbose_name=_('owner'))\n bounding_geometry = models.OneToOneField('BoundingGeometry', verbose_name=_('bounding geometry'))\n\n @property\n def type_of_geometry(self):\n return self.bounding_geometry.type_of_geometry\n\n @property\n def extent(self):\n return self.bounding_geometry.extent\n\n def __str__(self):\n return self.name\n\n\ndef _active_excerpts():\n return Excerpt.objects.filter(is_active=True).filter(\n bounding_geometry__bboxboundinggeometry__isnull=False\n )\n\n\ndef private_user_excerpts(user):\n return _active_excerpts().filter(is_public=False, owner=user)\n\n\ndef public_user_excerpts(user):\n return _active_excerpts().filter(is_public=True, owner=user)\n\n\ndef other_users_public_excerpts(user):\n return _active_excerpts().filter(is_public=True).exclude(owner=user)\n","new_contents":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass Excerpt(models.Model):\n name = models.CharField(max_length=128, verbose_name=_('name'))\n is_public = models.BooleanField(default=False, verbose_name=_('is public'))\n is_active = models.BooleanField(default=True, verbose_name=_('is active'))\n\n owner = models.ForeignKey(User, related_name='excerpts', verbose_name=_('owner'))\n bounding_geometry = models.OneToOneField('BoundingGeometry', verbose_name=_('bounding geometry'))\n\n @property\n def type_of_geometry(self):\n return self.bounding_geometry.type_of_geometry\n\n @property\n def extent(self):\n return self.bounding_geometry.extent\n\n def __str__(self):\n return self.name\n\n\ndef _active_excerpts():\n return Excerpt.objects.filter(is_active=True).filter(\n bounding_geometry__bboxboundinggeometry__isnull=False\n )\n\n\ndef private_user_excerpts(user):\n return _active_excerpts().filter(is_public=False, owner=user)\n\n\ndef public_user_excerpts(user):\n return _active_excerpts().filter(is_public=True, owner=user)\n\n\ndef other_users_public_excerpts(user):\n return _active_excerpts().filter(is_public=True).exclude(owner=user)\n","subject":"Remove value which is already default","message":"Remove value which is already default\n","lang":"Python","license":"mit","repos":"geometalab\/osmaxx,geometalab\/drf-utm-zone-info,geometalab\/osmaxx,geometalab\/osmaxx-frontend,geometalab\/osmaxx-frontend,geometalab\/osmaxx-frontend,geometalab\/osmaxx,geometalab\/osmaxx-frontend,geometalab\/drf-utm-zone-info,geometalab\/osmaxx"} {"commit":"e0a9b97792f48efdfb166b785a8ba1fd2448a171","old_file":"cref\/structure\/__init__.py","new_file":"cref\/structure\/__init__.py","old_contents":"","new_contents":"# import porter_paleale\n\n\ndef predict_secondary_structure(sequence):\n \"\"\"\n Predict the secondary structure of a given sequence\n\n :param sequence: Amino acid sequence\n\n :return: Secondary structure prediction as a string\n H = helix\n E = Strand\n C =r coil\n \"\"\"\n # return porter_paleale.predict(sequence)\n return \"C\" * len(sequence)\n\n\ndef write_pdb(aa_sequence, fragment_angles, gap_length, filepath):\n \"\"\"\n Generate pdb file with results\n\n :param aa_sequence: Amino acid sequence\n :param fragment_angles: Backbone torsion angles\n :param gap_length: Length of the gap at the sequence start and end\n :param filepath: Path to the file to save the pdb\n \"\"\"\n pass\n","subject":"Add skeleton for secondary structure and write pdb module","message":"Add skeleton for secondary structure and write pdb module\n","lang":"Python","license":"mit","repos":"mchelem\/cref2,mchelem\/cref2,mchelem\/cref2"} {"commit":"cddb0309eaa0c31569f791b8b9f2c8666b65b8b4","old_file":"openrcv\/test\/test_models.py","new_file":"openrcv\/test\/test_models.py","old_contents":"\nfrom openrcv.models import ContestInfo\nfrom openrcv.utiltest.helpers import UnitCase\n\n\nclass ContestInfoTest(UnitCase):\n\n def test_get_candidates(self):\n contest = ContestInfo()\n contest.candidates = [\"Alice\", \"Bob\", \"Carl\"]\n self.assertEqual(contest.get_candidates(), range(1, 4))\n","new_contents":"\nfrom textwrap import dedent\n\nfrom openrcv.models import BallotsResource, BallotStreamResource, ContestInfo\nfrom openrcv.utils import StringInfo\nfrom openrcv.utiltest.helpers import UnitCase\n\n\nclass BallotsResourceTest(UnitCase):\n\n def test(self):\n ballots = [1, 3, 2]\n ballot_resource = BallotsResource(ballots)\n with ballot_resource() as ballots:\n ballots = list(ballots)\n self.assertEqual(ballots, [1, 3, 2])\n\n\nclass BallotStreamResourceTest(UnitCase):\n\n def test(self):\n ballot_info = StringInfo(\"2 1 2\\n3 1\\n\")\n ballot_resource = BallotStreamResource(ballot_info)\n with ballot_resource() as ballots:\n ballots = list(ballots)\n self.assertEqual(ballots, ['2 1 2\\n', '3 1\\n'])\n\n def test_parse_default(self):\n ballot_info = StringInfo(\"2 1 2\\n3 1\\n\")\n parse = lambda line: line.strip()\n ballot_resource = BallotStreamResource(ballot_info, parse=parse)\n with ballot_resource() as ballots:\n ballots = list(ballots)\n self.assertEqual(ballots, ['2 1 2', '3 1'])\n\n\nclass ContestInfoTest(UnitCase):\n\n def test_get_candidates(self):\n contest = ContestInfo()\n contest.candidates = [\"Alice\", \"Bob\", \"Carl\"]\n self.assertEqual(contest.get_candidates(), range(1, 4))\n","subject":"Add tests for ballots resource classes.","message":"Add tests for ballots resource classes.\n","lang":"Python","license":"mit","repos":"cjerdonek\/open-rcv,cjerdonek\/open-rcv"} {"commit":"1a65ebc4a36da37840b3bd74666bf7f607ed190b","old_file":"oshot\/context_processors.py","new_file":"oshot\/context_processors.py","old_contents":"from django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.sites.models import get_current_site\nfrom django.conf import settings\n\nfrom haystack.forms import SearchForm\nfrom entities.models import Entity\n\nfrom oshot.forms import EntityChoiceForm\n\ndef forms(request):\n context = {\"search_form\": SearchForm()}\n kwargs = request.resolver_match.kwargs\n if 'entity_slug' in kwargs:\n entity = Entity.objects.get(slug=kwargs['entity_slug'])\n initial = {'entity': entity.id}\n elif 'entity_id' in kwargs:\n entity = Entity.objects.get(id=kwargs['entity_id'])\n initial = {'entity': entity.id}\n else:\n initial = {}\n context['entity_form'] = EntityChoiceForm(initial=initial, auto_id=False)\n\n if not request.user.is_authenticated():\n context[\"login_form\"] = AuthenticationForm()\n # TODO: remove\n context[\"site\"] = get_current_site(request)\n context[\"ANALYTICS_ID\"] = getattr(settings, 'ANALYTICS_ID', False)\n return context\n\n\n","new_contents":"from django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.sites.models import get_current_site\nfrom django.conf import settings\n\nfrom haystack.forms import SearchForm\nfrom entities.models import Entity\n\nfrom oshot.forms import EntityChoiceForm\n\ndef forms(request):\n context = {\"search_form\": SearchForm()}\n try:\n kwargs = request.resolver_match.kwargs\n if 'entity_slug' in kwargs:\n entity = Entity.objects.get(slug=kwargs['entity_slug'])\n initial = {'entity': entity.id}\n elif 'entity_id' in kwargs:\n entity = Entity.objects.get(id=kwargs['entity_id'])\n initial = {'entity': entity.id}\n else:\n initial = {}\n context['entity_form'] = EntityChoiceForm(initial=initial, auto_id=False)\n except AttributeError:\n pass\n\n if not request.user.is_authenticated():\n context[\"login_form\"] = AuthenticationForm()\n # TODO: remove\n context[\"site\"] = get_current_site(request)\n context[\"ANALYTICS_ID\"] = getattr(settings, 'ANALYTICS_ID', False)\n return context\n\n\n","subject":"Clean bug with static file serving","message":"Clean bug with static file serving\n","lang":"Python","license":"bsd-3-clause","repos":"hasadna\/open-shot,hasadna\/open-shot,hasadna\/open-shot"} {"commit":"771f429433d201463ab94439870d1bc803022722","old_file":"nap\/auth.py","new_file":"nap\/auth.py","old_contents":"from __future__ import unicode_literals\n\n# Authentication and Authorisation\nfrom functools import wraps\n\nfrom . import http\n\n\ndef permit(test_func, response_class=http.Forbidden):\n '''Decorate a handler to control access'''\n def decorator(view_func):\n @wraps(view_func)\n def _wrapped_view(self, *args, **kwargs):\n if test_func(self, *args, **kwargs):\n return view_func(self, *args, **kwargs)\n return response_class()\n return _wrapped_view\n return decorator\n\npermit_logged_in = permit(\n lambda self, *args, **kwargs: self.request.user.is_authenticated()\n)\n\npermit_staff = permit(\n lambda self, *args, **kwargs: self.request.user.is_staff\n)\n\n\ndef permit_groups(*groups):\n def in_groups(self, *args, **kwargs):\n return self.request.user.groups.filter(name__in=groups).exists()\n return permit(in_groups)\n","new_contents":"from __future__ import unicode_literals\n\n# Authentication and Authorisation\nfrom functools import wraps\n\nfrom . import http\n\n\ndef permit(test_func, response_class=http.Forbidden):\n '''Decorate a handler to control access'''\n def decorator(view_func):\n @wraps(view_func)\n def _wrapped_view(self, *args, **kwargs):\n if test_func(self, *args, **kwargs):\n return view_func(self, *args, **kwargs)\n return response_class()\n return _wrapped_view\n return decorator\n\n\n# Helpers for people wanting to control response class\ndef test_logged_in(self, *args, **kwargs):\n return self.request.user.is_authenticated()\n\n\ndef test_staff(self, *args, **kwargs):\n return self.request.user.is_staff\n\npermit_logged_in = permit(test_logged_in)\npermit_staff = permit(test_staff)\n\n\ndef permit_groups(*groups, response_class=http.Forbidden):\n def in_groups(self, *args, **kwargs):\n return self.request.user.groups.filter(name__in=groups).exists()\n return permit(in_groups, response_class=response_class)\n","subject":"Make it DRYer for people","message":"Make it DRYer for people\n","lang":"Python","license":"bsd-3-clause","repos":"limbera\/django-nap"} {"commit":"a3a9da03da0691af53526096992a56fcaeecb642","old_file":"py\/test\/selenium\/webdriver\/common\/proxy_tests.py","new_file":"py\/test\/selenium\/webdriver\/common\/proxy_tests.py","old_contents":"#!\/usr\/bin\/python\n\n# Copyright 2012 Software Freedom Conservancy.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS.\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport unittest\nfrom selenium.webdriver.common.proxy import Proxy\n\n\nclass ProxyTests(unittest.TestCase):\n\n def testCanAddToDesiredCapabilities(self):\n desired_capabilities = {}\n proxy = Proxy()\n proxy.http_proxy = 'some.url:1234'\n\n proxy.add_to_capabilities(desired_capabilities)\n\n expected_capabilities = {\n 'proxy': {\n 'proxyType': 'manual',\n 'httpProxy': 'some.url:1234'\n }\n }\n\n self.assertEqual(expected_capabilities, desired_capabilities)\n","new_contents":"#!\/usr\/bin\/python\n\n# Copyright 2012 Software Freedom Conservancy.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS.\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport unittest\nfrom selenium.webdriver.common.proxy import Proxy\n\n\nclass ProxyTests(unittest.TestCase):\n\n def testCanAddToDesiredCapabilities(self):\n desired_capabilities = {}\n proxy = Proxy()\n proxy.http_proxy = 'some.url:1234'\n\n proxy.add_to_capabilities(desired_capabilities)\n\n expected_capabilities = {\n 'proxy': {\n 'proxyType': 'MANUAL',\n 'httpProxy': 'some.url:1234'\n }\n }\n\n self.assertEqual(expected_capabilities, desired_capabilities)\n","subject":"Fix test as well :)","message":"DanielWagnerHall: Fix test as well :)\n\ngit-svn-id: aa1aa1384423cb28c2b1e29129bb3a91de1d9196@17825 07704840-8298-11de-bf8c-fd130f914ac9\n","lang":"Python","license":"apache-2.0","repos":"jmt4\/Selenium2,jmt4\/Selenium2,yumingjuan\/selenium,jmt4\/Selenium2,jmt4\/Selenium2,yumingjuan\/selenium,jmt4\/Selenium2,yumingjuan\/selenium,yumingjuan\/selenium,yumingjuan\/selenium,yumingjuan\/selenium,jmt4\/Selenium2,jmt4\/Selenium2,yumingjuan\/selenium,jmt4\/Selenium2,yumingjuan\/selenium,jmt4\/Selenium2,yumingjuan\/selenium"} {"commit":"483800541ee66de006392c361e06177bc9db4784","old_file":"kboard\/board\/urls.py","new_file":"kboard\/board\/urls.py","old_contents":"# Created by JHJ on 2016. 10. 5.\n\nfrom django.conf.urls import url\n\nfrom . import views\n\napp_name = 'board'\nurlpatterns = [\n url(r'^$', views.board_list, name='board_list'),\n url(r'^(?P[-a-z]+)\/$', views.post_list, name='post_list'),\n url(r'^(?P[-a-z]+)\/new\/$', views.new_post, name='new_post'),\n url(r'^(?P\\d+)\/delete\/$', views.delete_post, name='delete_post'),\n url(r'^(?P\\d+)\/like\/$', views.like_post, name='like_post'),\n url(r'^(?P\\d+)\/edit\/$', views.edit_post, name='edit_post'),\n url(r'^(?P\\d+)\/$', views.view_post, name='view_post'),\n url(r'^(?P\\d+)\/comment\/new\/$', views.new_comment, name='new_comment'),\n url(r'^(?P\\d+)\/comment\/(?P\\d+)\/delete\/$', views.delete_comment, name='delete_comment'),\n]\n","new_contents":"# Created by JHJ on 2016. 10. 5.\n\nfrom django.conf.urls import url\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom . import views\n\napp_name = 'board'\nurlpatterns = [\n url(r'^$', views.board_list, name='board_list'),\n url(r'^(?P[-a-z]+)\/$', views.post_list, name='post_list'),\n url(r'^(?P[-a-z]+)\/new\/$', views.new_post, name='new_post'),\n url(r'^(?P\\d+)\/delete\/$', views.delete_post, name='delete_post'),\n url(r'^(?P\\d+)\/like\/$', views.like_post, name='like_post'),\n url(r'^(?P\\d+)\/edit\/$', views.edit_post, name='edit_post'),\n url(r'^(?P\\d+)\/$', views.view_post, name='view_post'),\n url(r'^(?P\\d+)\/comment\/new\/$', views.new_comment, name='new_comment'),\n url(r'^(?P\\d+)\/comment\/(?P\\d+)\/delete\/$', views.delete_comment, name='delete_comment'),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","subject":"Set url to serve uploaded file during development","message":"Set url to serve uploaded file during development\n","lang":"Python","license":"mit","repos":"guswnsxodlf\/k-board,kboard\/kboard,cjh5414\/kboard,kboard\/kboard,hyesun03\/k-board,hyesun03\/k-board,hyesun03\/k-board,guswnsxodlf\/k-board,cjh5414\/kboard,darjeeling\/k-board,cjh5414\/kboard,kboard\/kboard,guswnsxodlf\/k-board"} {"commit":"e09214068a12768e9aafd04363d353359ca7e1f3","old_file":"src\/actions\/actions\/timetracking\/__init__.py","new_file":"src\/actions\/actions\/timetracking\/__init__.py","old_contents":"#!\/usr\/bin\/python\n######################################################################\n# Cloud Routes Bridge\n# -------------------------------------------------------------------\n# Actions Module\n######################################################################\n\nimport stathat\nimport time\nimport syslog\n\ndef action(**kwargs):\n ''' This method is called to action a reaction '''\n updateStathat(kwargs['jdata'])\n return True\n\n\ndef updateStathat(jdata):\n ''' This method will be called to update a stathat Statistic '''\n ez_key = jdata['time_tracking']['ez_key']\n stat_name = \"[%s] End to End Monitor transaction time\" % jdata[\n 'time_tracking']['env']\n value = time.time() - jdata['time_tracking']['control']\n stathat.ez_value(ez_key, stat_name, value)\n line = \"timetracker: Sent stat to StatHat for %s\" % jdata['cid']\n syslog.syslog(syslog.LOG_INFO, line)\n","new_contents":"#!\/usr\/bin\/python\n######################################################################\n# Cloud Routes Bridge\n# -------------------------------------------------------------------\n# Actions Module\n######################################################################\n\nimport stathat\nimport time\n\ndef action(**kwargs):\n ''' This method is called to action a reaction '''\n logger = kwargs['logger']\n updateStathat(kwargs['jdata'], logger)\n return True\n\n\ndef updateStathat(jdata, logger):\n ''' This method will be called to update a stathat Statistic '''\n ez_key = jdata['time_tracking']['ez_key']\n stat_name = \"[%s] End to End Monitor transaction time\" % jdata[\n 'time_tracking']['env']\n value = time.time() - jdata['time_tracking']['control']\n stathat.ez_value(ez_key, stat_name, value)\n line = \"timetracker: Sent stat to StatHat for %s\" % jdata['cid']\n logger.info(line)\n","subject":"Convert reactions syslog to logger: timetracking","message":"Convert reactions syslog to logger: timetracking\n","lang":"Python","license":"unknown","repos":"dethos\/cloudroutes-service,asm-products\/cloudroutes-service,rbramwell\/runbook,codecakes\/cloudroutes-service,codecakes\/cloudroutes-service,asm-products\/cloudroutes-service,madflojo\/cloudroutes-service,Runbook\/runbook,codecakes\/cloudroutes-service,asm-products\/cloudroutes-service,codecakes\/cloudroutes-service,madflojo\/cloudroutes-service,rbramwell\/runbook,madflojo\/cloudroutes-service,Runbook\/runbook,rbramwell\/runbook,rbramwell\/runbook,Runbook\/runbook,dethos\/cloudroutes-service,madflojo\/cloudroutes-service,dethos\/cloudroutes-service,asm-products\/cloudroutes-service,Runbook\/runbook,dethos\/cloudroutes-service"} {"commit":"e399c0b1988ed8b2981ddc684a0a3652a73ea31e","old_file":"pavelib\/utils\/test\/utils.py","new_file":"pavelib\/utils\/test\/utils.py","old_contents":"\"\"\"\nHelper functions for test tasks\n\"\"\"\nfrom paver.easy import sh, task\nfrom pavelib.utils.envs import Env\n\n__test__ = False # do not collect\n\n\n@task\ndef clean_test_files():\n \"\"\"\n Clean fixture files used by tests and .pyc files\n \"\"\"\n sh(\"git clean -fqdx test_root\/logs test_root\/data test_root\/staticfiles test_root\/uploads\")\n sh(\"find . -type f -name \\\"*.pyc\\\" -delete\")\n sh(\"rm -rf test_root\/log\/auto_screenshots\/*\")\n\n\ndef clean_dir(directory):\n \"\"\"\n Clean coverage files, to ensure that we don't use stale data to generate reports.\n \"\"\"\n # We delete the files but preserve the directory structure\n # so that coverage.py has a place to put the reports.\n sh('find {dir} -type f -delete'.format(dir=directory))\n\n\n@task\ndef clean_reports_dir():\n \"\"\"\n Clean coverage files, to ensure that we don't use stale data to generate reports.\n \"\"\"\n # We delete the files but preserve the directory structure\n # so that coverage.py has a place to put the reports.\n reports_dir = Env.REPORT_DIR.makedirs_p()\n clean_dir(reports_dir)\n\n\n@task\ndef clean_mongo():\n \"\"\"\n Clean mongo test databases\n \"\"\"\n sh(\"mongo {repo_root}\/scripts\/delete-mongo-test-dbs.js\".format(repo_root=Env.REPO_ROOT))\n","new_contents":"\"\"\"\nHelper functions for test tasks\n\"\"\"\nfrom paver.easy import sh, task\nfrom pavelib.utils.envs import Env\n\n__test__ = False # do not collect\n\n\n@task\ndef clean_test_files():\n \"\"\"\n Clean fixture files used by tests and .pyc files\n \"\"\"\n sh(\"git clean -fqdx test_root\/logs test_root\/data test_root\/staticfiles test_root\/uploads\")\n sh(\"find . -type f -name \\\"*.pyc\\\" -delete\")\n sh(\"rm -rf test_root\/log\/auto_screenshots\/*\")\n sh(\"rm -rf \/tmp\/mako_[cl]ms\")\n\n\ndef clean_dir(directory):\n \"\"\"\n Clean coverage files, to ensure that we don't use stale data to generate reports.\n \"\"\"\n # We delete the files but preserve the directory structure\n # so that coverage.py has a place to put the reports.\n sh('find {dir} -type f -delete'.format(dir=directory))\n\n\n@task\ndef clean_reports_dir():\n \"\"\"\n Clean coverage files, to ensure that we don't use stale data to generate reports.\n \"\"\"\n # We delete the files but preserve the directory structure\n # so that coverage.py has a place to put the reports.\n reports_dir = Env.REPORT_DIR.makedirs_p()\n clean_dir(reports_dir)\n\n\n@task\ndef clean_mongo():\n \"\"\"\n Clean mongo test databases\n \"\"\"\n sh(\"mongo {repo_root}\/scripts\/delete-mongo-test-dbs.js\".format(repo_root=Env.REPO_ROOT))\n","subject":"Clean out the mako temp dirs before running tests","message":"Clean out the mako temp dirs before running tests\n","lang":"Python","license":"agpl-3.0","repos":"zofuthan\/edx-platform,eemirtekin\/edx-platform,TeachAtTUM\/edx-platform,synergeticsedx\/deployment-wipro,doismellburning\/edx-platform,OmarIthawi\/edx-platform,jolyonb\/edx-platform,appliedx\/edx-platform,philanthropy-u\/edx-platform,msegado\/edx-platform,pepeportela\/edx-platform,JCBarahona\/edX,lduarte1991\/edx-platform,jamesblunt\/edx-platform,vasyarv\/edx-platform,valtech-mooc\/edx-platform,jonathan-beard\/edx-platform,beacloudgenius\/edx-platform,DefyVentures\/edx-platform,sameetb-cuelogic\/edx-platform-test,rismalrv\/edx-platform,zubair-arbi\/edx-platform,ampax\/edx-platform-backup,chauhanhardik\/populo,ovnicraft\/edx-platform,synergeticsedx\/deployment-wipro,antoviaque\/edx-platform,Lektorium-LLC\/edx-platform,marcore\/edx-platform,Endika\/edx-platform,vikas1885\/test1,unicri\/edx-platform,Edraak\/edraak-platform,Endika\/edx-platform,ampax\/edx-platform,motion2015\/edx-platform,EDUlib\/edx-platform,mtlchun\/edx,shabab12\/edx-platform,ESOedX\/edx-platform,chrisndodge\/edx-platform,antonve\/s4-project-mooc,CredoReference\/edx-platform,dkarakats\/edx-platform,cecep-edu\/edx-platform,polimediaupv\/edx-platform,chauhanhardik\/populo,4eek\/edx-platform,wwj718\/ANALYSE,ahmadiga\/min_edx,appsembler\/edx-platform,antonve\/s4-project-mooc,gsehub\/edx-platform,jazkarta\/edx-platform-for-isc,xuxiao19910803\/edx,ahmedaljazzar\/edx-platform,dkarakats\/edx-platform,LearnEra\/LearnEraPlaftform,kursitet\/edx-platform,shubhdev\/edxOnBaadal,dsajkl\/123,defance\/edx-platform,angelapper\/edx-platform,edx\/edx-platform,devs1991\/test_edx_docmode,jamiefolsom\/edx-platform,jzoldak\/edx-platform,doismellburning\/edx-platform,nanolearningllc\/edx-platform-cypress,xuxiao19910803\/edx-platform,franosincic\/edx-platform,DefyVentures\/edx-platform,ferabra\/edx-platform,cselis86\/edx-platform,hastexo\/edx-platform,UXE\/local-edx,mjirayu\/sit_academy,valtech-mooc\/edx-platform,dsajkl\/reqiop,cecep-edu\/edx-platform,marcore\/edx-platform,hamzehd\/edx-platform,atsolakid\/edx-platform,bdero\/edx-platform,mitocw\/edx-platform,philanthropy-u\/edx-platform,SivilTaram\/edx-platform,playm2mboy\/edx-platform,zadgroup\/edx-platform,cyanna\/edx-platform,cyanna\/edx-platform,olexiim\/edx-platform,don-github\/edx-platform,Stanford-Online\/edx-platform,xinjiguaike\/edx-platform,fintech-circle\/edx-platform,benpatterson\/edx-platform,adoosii\/edx-platform,xuxiao19910803\/edx-platform,doismellburning\/edx-platform,ovnicraft\/edx-platform,motion2015\/a3,naresh21\/synergetics-edx-platform,tiagochiavericosta\/edx-platform,shurihell\/testasia,dcosentino\/edx-platform,AkA84\/edx-platform,ubc\/edx-platform,andyzsf\/edx,gsehub\/edx-platform,xinjiguaike\/edx-platform,ubc\/edx-platform,JCBarahona\/edX,ampax\/edx-platform,4eek\/edx-platform,TeachAtTUM\/edx-platform,Edraak\/edx-platform,andyzsf\/edx,edx\/edx-platform,cognitiveclass\/edx-platform,EDUlib\/edx-platform,AkA84\/edx-platform,olexiim\/edx-platform,cognitiveclass\/edx-platform,mahendra-r\/edx-platform,franosincic\/edx-platform,miptliot\/edx-platform,jruiperezv\/ANALYSE,jolyonb\/edx-platform,vikas1885\/test1,Lektorium-LLC\/edx-platform,simbs\/edx-platform,BehavioralInsightsTeam\/edx-platform,jamesblunt\/edx-platform,Softmotions\/edx-platform,amir-qayyum-khan\/edx-platform,unicri\/edx-platform,waheedahmed\/edx-platform,xinjiguaike\/edx-platform,rhndg\/openedx,arifsetiawan\/edx-platform,etzhou\/edx-platform,xinjiguaike\/edx-platform,MakeHer\/edx-platform,gsehub\/edx-platform,jelugbo\/tundex,jazkarta\/edx-platform-for-isc,ovnicraft\/edx-platform,hamzehd\/edx-platform,xingyepei\/edx-platform,ferabra\/edx-platform,Kalyzee\/edx-platform,LearnEra\/LearnEraPlaftform,procangroup\/edx-platform,CredoReference\/edx-platform,appsembler\/edx-platform,benpatterson\/edx-platform,kxliugang\/edx-platform,jazztpt\/edx-platform,dsajkl\/123,wwj718\/edx-platform,Kalyzee\/edx-platform,ahmadio\/edx-platform,J861449197\/edx-platform,jazztpt\/edx-platform,Edraak\/circleci-edx-platform,utecuy\/edx-platform,zerobatu\/edx-platform,beni55\/edx-platform,knehez\/edx-platform,edry\/edx-platform,zubair-arbi\/edx-platform,bigdatauniversity\/edx-platform,kursitet\/edx-platform,rhndg\/openedx,pabloborrego93\/edx-platform,simbs\/edx-platform,alexthered\/kienhoc-platform,cpennington\/edx-platform,gymnasium\/edx-platform,zadgroup\/edx-platform,fly19890211\/edx-platform,martynovp\/edx-platform,hamzehd\/edx-platform,shurihell\/testasia,Shrhawk\/edx-platform,zubair-arbi\/edx-platform,LearnEra\/LearnEraPlaftform,alu042\/edx-platform,chand3040\/cloud_that,ahmedaljazzar\/edx-platform,ferabra\/edx-platform,ubc\/edx-platform,shubhdev\/edx-platform,fintech-circle\/edx-platform,zerobatu\/edx-platform,waheedahmed\/edx-platform,jonathan-beard\/edx-platform,shabab12\/edx-platform,ak2703\/edx-platform,nanolearningllc\/edx-platform-cypress-2,jzoldak\/edx-platform,franosincic\/edx-platform,proversity-org\/edx-platform,UOMx\/edx-platform,defance\/edx-platform,leansoft\/edx-platform,Edraak\/circleci-edx-platform,cselis86\/edx-platform,DNFcode\/edx-platform,mitocw\/edx-platform,SravanthiSinha\/edx-platform,motion2015\/a3,devs1991\/test_edx_docmode,synergeticsedx\/deployment-wipro,synergeticsedx\/deployment-wipro,motion2015\/edx-platform,chauhanhardik\/populo_2,xingyepei\/edx-platform,beni55\/edx-platform,nttks\/jenkins-test,DefyVentures\/edx-platform,knehez\/edx-platform,rismalrv\/edx-platform,nanolearningllc\/edx-platform-cypress-2,chauhanhardik\/populo_2,solashirai\/edx-platform,ESOedX\/edx-platform,etzhou\/edx-platform,doismellburning\/edx-platform,jamiefolsom\/edx-platform,halvertoluke\/edx-platform,peterm-itr\/edx-platform,shubhdev\/openedx,marcore\/edx-platform,inares\/edx-platform,vismartltd\/edx-platform,chauhanhardik\/populo,jamesblunt\/edx-platform,JCBarahona\/edX,bdero\/edx-platform,lduarte1991\/edx-platform,openfun\/edx-platform,ahmedaljazzar\/edx-platform,arbrandes\/edx-platform,a-parhom\/edx-platform,Semi-global\/edx-platform,B-MOOC\/edx-platform,shubhdev\/openedx,chrisndodge\/edx-platform,4eek\/edx-platform,SivilTaram\/edx-platform,jbassen\/edx-platform,kamalx\/edx-platform,longmen21\/edx-platform,CredoReference\/edx-platform,waheedahmed\/edx-platform,doganov\/edx-platform,ZLLab-Mooc\/edx-platform,jbzdak\/edx-platform,openfun\/edx-platform,jazkarta\/edx-platform,philanthropy-u\/edx-platform,adoosii\/edx-platform,proversity-org\/edx-platform,zofuthan\/edx-platform,bitifirefly\/edx-platform,OmarIthawi\/edx-platform,eemirtekin\/edx-platform,Edraak\/edx-platform,antoviaque\/edx-platform,jamiefolsom\/edx-platform,shubhdev\/edxOnBaadal,eduNEXT\/edunext-platform,chand3040\/cloud_that,shabab12\/edx-platform,fly19890211\/edx-platform,Ayub-Khan\/edx-platform,mahendra-r\/edx-platform,ahmadio\/edx-platform,deepsrijit1105\/edx-platform,inares\/edx-platform,shurihell\/testasia,eemirtekin\/edx-platform,kamalx\/edx-platform,kmoocdev\/edx-platform,etzhou\/edx-platform,don-github\/edx-platform,amir-qayyum-khan\/edx-platform,mcgachey\/edx-platform,beni55\/edx-platform,DefyVentures\/edx-platform,chudaol\/edx-platform,sameetb-cuelogic\/edx-platform-test,polimediaupv\/edx-platform,RPI-OPENEDX\/edx-platform,nanolearningllc\/edx-platform-cypress-2,cselis86\/edx-platform,caesar2164\/edx-platform,leansoft\/edx-platform,longmen21\/edx-platform,itsjeyd\/edx-platform,franosincic\/edx-platform,prarthitm\/edxplatform,jamiefolsom\/edx-platform,mushtaqak\/edx-platform,jswope00\/griffinx,ahmadiga\/min_edx,cyanna\/edx-platform,appsembler\/edx-platform,adoosii\/edx-platform,lduarte1991\/edx-platform,ampax\/edx-platform,iivic\/BoiseStateX,polimediaupv\/edx-platform,nttks\/edx-platform,edx-solutions\/edx-platform,DNFcode\/edx-platform,stvstnfrd\/edx-platform,jelugbo\/tundex,motion2015\/edx-platform,nttks\/jenkins-test,jazkarta\/edx-platform,IndonesiaX\/edx-platform,vasyarv\/edx-platform,Endika\/edx-platform,philanthropy-u\/edx-platform,10clouds\/edx-platform,jruiperezv\/ANALYSE,Kalyzee\/edx-platform,ak2703\/edx-platform,fly19890211\/edx-platform,fly19890211\/edx-platform,Shrhawk\/edx-platform,beni55\/edx-platform,nikolas\/edx-platform,alexthered\/kienhoc-platform,MSOpenTech\/edx-platform,appliedx\/edx-platform,waheedahmed\/edx-platform,openfun\/edx-platform,marcore\/edx-platform,Lektorium-LLC\/edx-platform,edx-solutions\/edx-platform,y12uc231\/edx-platform,wwj718\/edx-platform,don-github\/edx-platform,eemirtekin\/edx-platform,deepsrijit1105\/edx-platform,mushtaqak\/edx-platform,a-parhom\/edx-platform,shashank971\/edx-platform,vikas1885\/test1,martynovp\/edx-platform,zerobatu\/edx-platform,Ayub-Khan\/edx-platform,chand3040\/cloud_that,shubhdev\/edx-platform,tiagochiavericosta\/edx-platform,MakeHer\/edx-platform,vasyarv\/edx-platform,jzoldak\/edx-platform,Edraak\/circleci-edx-platform,analyseuc3m\/ANALYSE-v1,kxliugang\/edx-platform,Endika\/edx-platform,jonathan-beard\/edx-platform,Shrhawk\/edx-platform,TeachAtTUM\/edx-platform,antonve\/s4-project-mooc,ahmadio\/edx-platform,chudaol\/edx-platform,don-github\/edx-platform,andyzsf\/edx,romain-li\/edx-platform,iivic\/BoiseStateX,hastexo\/edx-platform,unicri\/edx-platform,stvstnfrd\/edx-platform,dsajkl\/reqiop,chand3040\/cloud_that,utecuy\/edx-platform,shashank971\/edx-platform,shashank971\/edx-platform,JioEducation\/edx-platform,SivilTaram\/edx-platform,zhenzhai\/edx-platform,benpatterson\/edx-platform,ovnicraft\/edx-platform,bigdatauniversity\/edx-platform,nanolearningllc\/edx-platform-cypress-2,itsjeyd\/edx-platform,chrisndodge\/edx-platform,Stanford-Online\/edx-platform,alu042\/edx-platform,Kalyzee\/edx-platform,prarthitm\/edxplatform,10clouds\/edx-platform,xingyepei\/edx-platform,nanolearningllc\/edx-platform-cypress,jbzdak\/edx-platform,LearnEra\/LearnEraPlaftform,mahendra-r\/edx-platform,xuxiao19910803\/edx,utecuy\/edx-platform,cyanna\/edx-platform,UXE\/local-edx,ahmadiga\/min_edx,pomegranited\/edx-platform,peterm-itr\/edx-platform,gymnasium\/edx-platform,adoosii\/edx-platform,mcgachey\/edx-platform,tanmaykm\/edx-platform,zerobatu\/edx-platform,ahmadiga\/min_edx,louyihua\/edx-platform,franosincic\/edx-platform,gymnasium\/edx-platform,jazkarta\/edx-platform-for-isc,arifsetiawan\/edx-platform,xuxiao19910803\/edx,doganov\/edx-platform,IONISx\/edx-platform,eestay\/edx-platform,angelapper\/edx-platform,solashirai\/edx-platform,tiagochiavericosta\/edx-platform,zofuthan\/edx-platform,jazkarta\/edx-platform-for-isc,Edraak\/edx-platform,openfun\/edx-platform,tanmaykm\/edx-platform,solashirai\/edx-platform,ESOedX\/edx-platform,knehez\/edx-platform,xuxiao19910803\/edx,UOMx\/edx-platform,a-parhom\/edx-platform,playm2mboy\/edx-platform,edx-solutions\/edx-platform,gsehub\/edx-platform,cognitiveclass\/edx-platform,JioEducation\/edx-platform,itsjeyd\/edx-platform,wwj718\/edx-platform,Stanford-Online\/edx-platform,defance\/edx-platform,JioEducation\/edx-platform,doganov\/edx-platform,mitocw\/edx-platform,hastexo\/edx-platform,kxliugang\/edx-platform,dsajkl\/reqiop,zhenzhai\/edx-platform,zofuthan\/edx-platform,Semi-global\/edx-platform,MSOpenTech\/edx-platform,olexiim\/edx-platform,msegado\/edx-platform,simbs\/edx-platform,cpennington\/edx-platform,mjirayu\/sit_academy,vikas1885\/test1,jjmiranda\/edx-platform,UOMx\/edx-platform,tanmaykm\/edx-platform,jbzdak\/edx-platform,EDUlib\/edx-platform,eduNEXT\/edunext-platform,longmen21\/edx-platform,zhenzhai\/edx-platform,msegado\/edx-platform,eduNEXT\/edx-platform,Kalyzee\/edx-platform,ovnicraft\/edx-platform,sudheerchintala\/LearnEraPlatForm,jazztpt\/edx-platform,beacloudgenius\/edx-platform,Semi-global\/edx-platform,4eek\/edx-platform,bigdatauniversity\/edx-platform,motion2015\/a3,Livit\/Livit.Learn.EdX,J861449197\/edx-platform,xuxiao19910803\/edx-platform,wwj718\/ANALYSE,ahmadio\/edx-platform,Ayub-Khan\/edx-platform,OmarIthawi\/edx-platform,xuxiao19910803\/edx,mcgachey\/edx-platform,shubhdev\/openedx,playm2mboy\/edx-platform,eduNEXT\/edx-platform,ahmedaljazzar\/edx-platform,fintech-circle\/edx-platform,nttks\/jenkins-test,DefyVentures\/edx-platform,mjirayu\/sit_academy,longmen21\/edx-platform,rue89-tech\/edx-platform,J861449197\/edx-platform,J861449197\/edx-platform,nanolearningllc\/edx-platform-cypress,chand3040\/cloud_that,peterm-itr\/edx-platform,shashank971\/edx-platform,bigdatauniversity\/edx-platform,Softmotions\/edx-platform,rue89-tech\/edx-platform,atsolakid\/edx-platform,raccoongang\/edx-platform,shubhdev\/edxOnBaadal,vismartltd\/edx-platform,knehez\/edx-platform,RPI-OPENEDX\/edx-platform,mtlchun\/edx,antonve\/s4-project-mooc,martynovp\/edx-platform,analyseuc3m\/ANALYSE-v1,IndonesiaX\/edx-platform,ESOedX\/edx-platform,kamalx\/edx-platform,kmoocdev2\/edx-platform,alexthered\/kienhoc-platform,CredoReference\/edx-platform,bigdatauniversity\/edx-platform,angelapper\/edx-platform,caesar2164\/edx-platform,romain-li\/edx-platform,RPI-OPENEDX\/edx-platform,xuxiao19910803\/edx-platform,bitifirefly\/edx-platform,B-MOOC\/edx-platform,utecuy\/edx-platform,kamalx\/edx-platform,leansoft\/edx-platform,louyihua\/edx-platform,cpennington\/edx-platform,kmoocdev2\/edx-platform,jbassen\/edx-platform,rismalrv\/edx-platform,y12uc231\/edx-platform,ampax\/edx-platform,DNFcode\/edx-platform,shubhdev\/openedx,jruiperezv\/ANALYSE,rue89-tech\/edx-platform,mtlchun\/edx,doismellburning\/edx-platform,gymnasium\/edx-platform,jolyonb\/edx-platform,procangroup\/edx-platform,chauhanhardik\/populo_2,pabloborrego93\/edx-platform,stvstnfrd\/edx-platform,edry\/edx-platform,chauhanhardik\/populo_2,teltek\/edx-platform,xingyepei\/edx-platform,leansoft\/edx-platform,mbareta\/edx-platform-ft,kxliugang\/edx-platform,zadgroup\/edx-platform,caesar2164\/edx-platform,analyseuc3m\/ANALYSE-v1,IONISx\/edx-platform,kmoocdev\/edx-platform,jazkarta\/edx-platform,shubhdev\/edx-platform,beacloudgenius\/edx-platform,Semi-global\/edx-platform,vasyarv\/edx-platform,polimediaupv\/edx-platform,shubhdev\/edx-platform,Softmotions\/edx-platform,nikolas\/edx-platform,playm2mboy\/edx-platform,dcosentino\/edx-platform,kmoocdev2\/edx-platform,vikas1885\/test1,tanmaykm\/edx-platform,motion2015\/edx-platform,SravanthiSinha\/edx-platform,4eek\/edx-platform,dsajkl\/reqiop,jswope00\/griffinx,nagyistoce\/edx-platform,motion2015\/edx-platform,ZLLab-Mooc\/edx-platform,hamzehd\/edx-platform,BehavioralInsightsTeam\/edx-platform,valtech-mooc\/edx-platform,rismalrv\/edx-platform,halvertoluke\/edx-platform,antoviaque\/edx-platform,shurihell\/testasia,devs1991\/test_edx_docmode,edx\/edx-platform,Livit\/Livit.Learn.EdX,lduarte1991\/edx-platform,shubhdev\/edxOnBaadal,cyanna\/edx-platform,devs1991\/test_edx_docmode,miptliot\/edx-platform,iivic\/BoiseStateX,nikolas\/edx-platform,jonathan-beard\/edx-platform,ampax\/edx-platform-backup,Shrhawk\/edx-platform,inares\/edx-platform,jazkarta\/edx-platform-for-isc,devs1991\/test_edx_docmode,ak2703\/edx-platform,UXE\/local-edx,nttks\/edx-platform,JCBarahona\/edX,cecep-edu\/edx-platform,mjirayu\/sit_academy,nikolas\/edx-platform,jazkarta\/edx-platform,motion2015\/a3,mitocw\/edx-platform,Softmotions\/edx-platform,kmoocdev2\/edx-platform,sameetb-cuelogic\/edx-platform-test,rismalrv\/edx-platform,cselis86\/edx-platform,solashirai\/edx-platform,inares\/edx-platform,beacloudgenius\/edx-platform,Ayub-Khan\/edx-platform,hamzehd\/edx-platform,shubhdev\/edx-platform,jamesblunt\/edx-platform,atsolakid\/edx-platform,wwj718\/ANALYSE,raccoongang\/edx-platform,CourseTalk\/edx-platform,edry\/edx-platform,edry\/edx-platform,iivic\/BoiseStateX,pomegranited\/edx-platform,nttks\/edx-platform,IndonesiaX\/edx-platform,tiagochiavericosta\/edx-platform,msegado\/edx-platform,jbassen\/edx-platform,dkarakats\/edx-platform,JCBarahona\/edX,DNFcode\/edx-platform,10clouds\/edx-platform,martynovp\/edx-platform,ubc\/edx-platform,appliedx\/edx-platform,jruiperezv\/ANALYSE,beni55\/edx-platform,mcgachey\/edx-platform,amir-qayyum-khan\/edx-platform,sudheerchintala\/LearnEraPlatForm,wwj718\/edx-platform,edx-solutions\/edx-platform,proversity-org\/edx-platform,angelapper\/edx-platform,pabloborrego93\/edx-platform,arifsetiawan\/edx-platform,zubair-arbi\/edx-platform,pomegranited\/edx-platform,ampax\/edx-platform-backup,jelugbo\/tundex,prarthitm\/edxplatform,AkA84\/edx-platform,dcosentino\/edx-platform,jruiperezv\/ANALYSE,romain-li\/edx-platform,eestay\/edx-platform,UXE\/local-edx,leansoft\/edx-platform,RPI-OPENEDX\/edx-platform,TeachAtTUM\/edx-platform,B-MOOC\/edx-platform,tiagochiavericosta\/edx-platform,jjmiranda\/edx-platform,devs1991\/test_edx_docmode,dsajkl\/123,rhndg\/openedx,OmarIthawi\/edx-platform,prarthitm\/edxplatform,jamiefolsom\/edx-platform,sameetb-cuelogic\/edx-platform-test,Edraak\/edraak-platform,jswope00\/griffinx,xingyepei\/edx-platform,utecuy\/edx-platform,mushtaqak\/edx-platform,jbassen\/edx-platform,louyihua\/edx-platform,mbareta\/edx-platform-ft,eduNEXT\/edx-platform,jonathan-beard\/edx-platform,ubc\/edx-platform,JioEducation\/edx-platform,cecep-edu\/edx-platform,nagyistoce\/edx-platform,vasyarv\/edx-platform,bitifirefly\/edx-platform,shubhdev\/edxOnBaadal,ahmadio\/edx-platform,SravanthiSinha\/edx-platform,nanolearningllc\/edx-platform-cypress-2,eestay\/edx-platform,adoosii\/edx-platform,mjirayu\/sit_academy,mushtaqak\/edx-platform,antonve\/s4-project-mooc,a-parhom\/edx-platform,bitifirefly\/edx-platform,IONISx\/edx-platform,atsolakid\/edx-platform,y12uc231\/edx-platform,bdero\/edx-platform,shubhdev\/openedx,fly19890211\/edx-platform,jbassen\/edx-platform,alu042\/edx-platform,naresh21\/synergetics-edx-platform,Edraak\/circleci-edx-platform,sudheerchintala\/LearnEraPlatForm,dcosentino\/edx-platform,unicri\/edx-platform,alexthered\/kienhoc-platform,knehez\/edx-platform,nikolas\/edx-platform,rue89-tech\/edx-platform,SravanthiSinha\/edx-platform,longmen21\/edx-platform,pepeportela\/edx-platform,rue89-tech\/edx-platform,miptliot\/edx-platform,nanolearningllc\/edx-platform-cypress,inares\/edx-platform,Edraak\/edraak-platform,sameetb-cuelogic\/edx-platform-test,eduNEXT\/edunext-platform,defance\/edx-platform,procangroup\/edx-platform,MakeHer\/edx-platform,dsajkl\/123,Edraak\/edraak-platform,kmoocdev\/edx-platform,itsjeyd\/edx-platform,vismartltd\/edx-platform,eduNEXT\/edunext-platform,pepeportela\/edx-platform,SravanthiSinha\/edx-platform,kmoocdev\/edx-platform,ahmadiga\/min_edx,Edraak\/edx-platform,edx\/edx-platform,zerobatu\/edx-platform,J861449197\/edx-platform,arbrandes\/edx-platform,nagyistoce\/edx-platform,shurihell\/testasia,y12uc231\/edx-platform,kursitet\/edx-platform,mahendra-r\/edx-platform,procangroup\/edx-platform,fintech-circle\/edx-platform,zadgroup\/edx-platform,DNFcode\/edx-platform,halvertoluke\/edx-platform,xinjiguaike\/edx-platform,jazkarta\/edx-platform,iivic\/BoiseStateX,pomegranited\/edx-platform,ZLLab-Mooc\/edx-platform,y12uc231\/edx-platform,martynovp\/edx-platform,dkarakats\/edx-platform,kxliugang\/edx-platform,Edraak\/circleci-edx-platform,wwj718\/ANALYSE,nttks\/jenkins-test,mbareta\/edx-platform-ft,andyzsf\/edx,MakeHer\/edx-platform,chauhanhardik\/populo,dsajkl\/123,ampax\/edx-platform-backup,zhenzhai\/edx-platform,benpatterson\/edx-platform,miptliot\/edx-platform,jelugbo\/tundex,beacloudgenius\/edx-platform,proversity-org\/edx-platform,chauhanhardik\/populo,B-MOOC\/edx-platform,nttks\/jenkins-test,teltek\/edx-platform,UOMx\/edx-platform,arifsetiawan\/edx-platform,jelugbo\/tundex,AkA84\/edx-platform,jjmiranda\/edx-platform,arifsetiawan\/edx-platform,msegado\/edx-platform,jbzdak\/edx-platform,kamalx\/edx-platform,BehavioralInsightsTeam\/edx-platform,mbareta\/edx-platform-ft,etzhou\/edx-platform,kmoocdev2\/edx-platform,nttks\/edx-platform,halvertoluke\/edx-platform,naresh21\/synergetics-edx-platform,jolyonb\/edx-platform,MSOpenTech\/edx-platform,mahendra-r\/edx-platform,ZLLab-Mooc\/edx-platform,devs1991\/test_edx_docmode,arbrandes\/edx-platform,cselis86\/edx-platform,IndonesiaX\/edx-platform,B-MOOC\/edx-platform,chudaol\/edx-platform,Ayub-Khan\/edx-platform,hastexo\/edx-platform,Semi-global\/edx-platform,Shrhawk\/edx-platform,jamesblunt\/edx-platform,EDUlib\/edx-platform,nanolearningllc\/edx-platform-cypress,devs1991\/test_edx_docmode,chudaol\/edx-platform,halvertoluke\/edx-platform,CourseTalk\/edx-platform,mtlchun\/edx,MSOpenTech\/edx-platform,jbzdak\/edx-platform,kmoocdev\/edx-platform,shashank971\/edx-platform,jazztpt\/edx-platform,jjmiranda\/edx-platform,ferabra\/edx-platform,romain-li\/edx-platform,jswope00\/griffinx,wwj718\/edx-platform,playm2mboy\/edx-platform,antoviaque\/edx-platform,polimediaupv\/edx-platform,zubair-arbi\/edx-platform,naresh21\/synergetics-edx-platform,ak2703\/edx-platform,zofuthan\/edx-platform,Livit\/Livit.Learn.EdX,AkA84\/edx-platform,simbs\/edx-platform,olexiim\/edx-platform,vismartltd\/edx-platform,mtlchun\/edx,valtech-mooc\/edx-platform,rhndg\/openedx,alu042\/edx-platform,romain-li\/edx-platform,rhndg\/openedx,eduNEXT\/edx-platform,teltek\/edx-platform,pomegranited\/edx-platform,vismartltd\/edx-platform,amir-qayyum-khan\/edx-platform,edry\/edx-platform,raccoongang\/edx-platform,eestay\/edx-platform,appliedx\/edx-platform,solashirai\/edx-platform,bdero\/edx-platform,ferabra\/edx-platform,louyihua\/edx-platform,CourseTalk\/edx-platform,wwj718\/ANALYSE,kursitet\/edx-platform,chrisndodge\/edx-platform,cecep-edu\/edx-platform,pabloborrego93\/edx-platform,dcosentino\/edx-platform,kursitet\/edx-platform,caesar2164\/edx-platform,etzhou\/edx-platform,MSOpenTech\/edx-platform,deepsrijit1105\/edx-platform,10clouds\/edx-platform,cognitiveclass\/edx-platform,SivilTaram\/edx-platform,deepsrijit1105\/edx-platform,eemirtekin\/edx-platform,jazztpt\/edx-platform,motion2015\/a3,eestay\/edx-platform,pepeportela\/edx-platform,ampax\/edx-platform-backup,appliedx\/edx-platform,alexthered\/kienhoc-platform,jzoldak\/edx-platform,RPI-OPENEDX\/edx-platform,IONISx\/edx-platform,CourseTalk\/edx-platform,analyseuc3m\/ANALYSE-v1,chudaol\/edx-platform,nttks\/edx-platform,Livit\/Livit.Learn.EdX,waheedahmed\/edx-platform,Lektorium-LLC\/edx-platform,cognitiveclass\/edx-platform,doganov\/edx-platform,MakeHer\/edx-platform,ZLLab-Mooc\/edx-platform,nagyistoce\/edx-platform,shabab12\/edx-platform,atsolakid\/edx-platform,Edraak\/edx-platform,zhenzhai\/edx-platform,cpennington\/edx-platform,peterm-itr\/edx-platform,Softmotions\/edx-platform,openfun\/edx-platform,dkarakats\/edx-platform,arbrandes\/edx-platform,IndonesiaX\/edx-platform,jswope00\/griffinx,ak2703\/edx-platform,simbs\/edx-platform,IONISx\/edx-platform,Stanford-Online\/edx-platform,valtech-mooc\/edx-platform,BehavioralInsightsTeam\/edx-platform,teltek\/edx-platform,mushtaqak\/edx-platform,don-github\/edx-platform,zadgroup\/edx-platform,stvstnfrd\/edx-platform,unicri\/edx-platform,bitifirefly\/edx-platform,appsembler\/edx-platform,benpatterson\/edx-platform,xuxiao19910803\/edx-platform,doganov\/edx-platform,SivilTaram\/edx-platform,nagyistoce\/edx-platform,mcgachey\/edx-platform,sudheerchintala\/LearnEraPlatForm,raccoongang\/edx-platform,olexiim\/edx-platform,chauhanhardik\/populo_2"} {"commit":"f931a434839222bb00282a432d6d6a0c2c52eb7d","old_file":"numpy\/array_api\/_typing.py","new_file":"numpy\/array_api\/_typing.py","old_contents":"\"\"\"\nThis file defines the types for type annotations.\n\nThese names aren't part of the module namespace, but they are used in the\nannotations in the function signatures. The functions in the module are only\nvalid for inputs that match the given type annotations.\n\"\"\"\n\n__all__ = [\n \"Array\",\n \"Device\",\n \"Dtype\",\n \"SupportsDLPack\",\n \"SupportsBufferProtocol\",\n \"PyCapsule\",\n]\n\nimport sys\nfrom typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING, TypeVar\n\nfrom ._array_object import Array\nfrom numpy import (\n dtype,\n int8,\n int16,\n int32,\n int64,\n uint8,\n uint16,\n uint32,\n uint64,\n float32,\n float64,\n)\n\n# This should really be recursive, but that isn't supported yet. See the\n# similar comment in numpy\/typing\/_array_like.py\n_T = TypeVar(\"_T\")\nNestedSequence = Sequence[Sequence[_T]]\n\nDevice = Literal[\"cpu\"]\nif TYPE_CHECKING or sys.version_info >= (3, 9):\n Dtype = dtype[Union[\n int8,\n int16,\n int32,\n int64,\n uint8,\n uint16,\n uint32,\n uint64,\n float32,\n float64,\n ]]\nelse:\n Dtype = dtype\n\nSupportsDLPack = Any\nSupportsBufferProtocol = Any\nPyCapsule = Any\n","new_contents":"\"\"\"\nThis file defines the types for type annotations.\n\nThese names aren't part of the module namespace, but they are used in the\nannotations in the function signatures. The functions in the module are only\nvalid for inputs that match the given type annotations.\n\"\"\"\n\nfrom __future__ import annotations\n\n__all__ = [\n \"Array\",\n \"Device\",\n \"Dtype\",\n \"SupportsDLPack\",\n \"SupportsBufferProtocol\",\n \"PyCapsule\",\n]\n\nimport sys\nfrom typing import (\n Any,\n Literal,\n Sequence,\n Type,\n Union,\n TYPE_CHECKING,\n TypeVar,\n Protocol,\n)\n\nfrom ._array_object import Array\nfrom numpy import (\n dtype,\n int8,\n int16,\n int32,\n int64,\n uint8,\n uint16,\n uint32,\n uint64,\n float32,\n float64,\n)\n\n_T_co = TypeVar(\"_T_co\", covariant=True)\n\nclass NestedSequence(Protocol[_T_co]):\n def __getitem__(self, key: int, \/) -> _T_co | NestedSequence[_T_co]: ...\n def __len__(self, \/) -> int: ...\n\nDevice = Literal[\"cpu\"]\nif TYPE_CHECKING or sys.version_info >= (3, 9):\n Dtype = dtype[Union[\n int8,\n int16,\n int32,\n int64,\n uint8,\n uint16,\n uint32,\n uint64,\n float32,\n float64,\n ]]\nelse:\n Dtype = dtype\n\nSupportsDLPack = Any\nSupportsBufferProtocol = Any\nPyCapsule = Any\n","subject":"Replace `NestedSequence` with a proper nested sequence protocol","message":"ENH: Replace `NestedSequence` with a proper nested sequence protocol\n","lang":"Python","license":"bsd-3-clause","repos":"numpy\/numpy,endolith\/numpy,charris\/numpy,rgommers\/numpy,numpy\/numpy,jakirkham\/numpy,seberg\/numpy,mattip\/numpy,jakirkham\/numpy,endolith\/numpy,rgommers\/numpy,mattip\/numpy,mattip\/numpy,seberg\/numpy,pdebuyl\/numpy,pdebuyl\/numpy,endolith\/numpy,endolith\/numpy,mattip\/numpy,jakirkham\/numpy,charris\/numpy,seberg\/numpy,mhvk\/numpy,pdebuyl\/numpy,rgommers\/numpy,mhvk\/numpy,numpy\/numpy,jakirkham\/numpy,mhvk\/numpy,mhvk\/numpy,charris\/numpy,anntzer\/numpy,pdebuyl\/numpy,charris\/numpy,jakirkham\/numpy,numpy\/numpy,rgommers\/numpy,anntzer\/numpy,anntzer\/numpy,anntzer\/numpy,seberg\/numpy,mhvk\/numpy"} {"commit":"718a04f14f3ede084a2d9391e187b4d943463c6f","old_file":"yanico\/session\/__init__.py","new_file":"yanico\/session\/__init__.py","old_contents":"\"\"\"Handle nicovideo.jp user_session.\"\"\"\n# Copyright 2015-2016 Masayuki Yamamoto\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nclass UserSessionNotFoundError(Exception):\n \"\"\"Firefox profile exists, buf user_session is not found.\"\"\"\n","new_contents":"\"\"\"Handle nicovideo.jp user_session.\"\"\"\n# Copyright 2015-2016 Masayuki Yamamoto\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nclass UserSessionNotFoundError(Exception):\n \"\"\"Profile exists, but user_session is not found.\"\"\"\n","subject":"Fix a typo of class docstring","message":"Fix a typo of class docstring\n","lang":"Python","license":"apache-2.0","repos":"ma8ma\/yanico"} {"commit":"889eed552f4e17797764a9d9a2da6bbaa6d5dd33","old_file":"admin_panel\/views.py","new_file":"admin_panel\/views.py","old_contents":"from django.views import View\nfrom django.views.generic import TemplateView\nfrom django.contrib import auth\nfrom django.contrib import messages\nfrom django import http\n\n\nclass LoginView(TemplateView):\n template_name = \"admin\/login.html\"\n\n def post(self, request):\n username = request.POST['username']\n password = request.POST['password']\n user_object = auth.authenticate(request, username=username, password=password)\n if user_object is None:\n messages.error(request, \"Invalid credentials\")\n return self.get(request)\n auth.login(request, user_object)\n messages.success(request, \"You've been logged in\")\n return http.HttpResponseRedirect(self.get_next_url(request))\n\n def get_next_url(self, request):\n if \"next\" in request.GET:\n return request.GET['next']\n else:\n return \"\/administration\/panel\"\n\n\nclass Panel(TemplateView):\n template_name = \"admin\/panel.html\"\n\n\nclass LogoutView(View):\n def get(self, request):\n auth.logout(request)\n return http.HttpResponseRedirect(\"\/administration\/login\")\n\n","new_contents":"from django.views import View\nfrom django.views.generic import TemplateView\nfrom django.contrib import auth\nfrom django.contrib import messages\nfrom django import http\nfrom django.urls import reverse\n\n\nclass LoginView(TemplateView):\n template_name = \"admin\/login.html\"\n\n def post(self, request):\n username = request.POST['username']\n password = request.POST['password']\n user_object = auth.authenticate(request, username=username, password=password)\n if user_object is None:\n messages.error(request, \"Invalid credentials\")\n return self.get(request)\n auth.login(request, user_object)\n messages.success(request, \"You've been logged in\")\n return http.HttpResponseRedirect(self.get_next_url(request))\n\n def get_next_url(self, request):\n if \"next\" in request.GET:\n return request.GET['next']\n else:\n return reverse(\"admin:Panel\")\n\n\nclass Panel(TemplateView):\n template_name = \"admin\/panel.html\"\n\n\nclass LogoutView(View):\n def get(self, request):\n auth.logout(request)\n return http.HttpResponseRedirect(\"\/administration\/login\")\n\n","subject":"Use django reverse function to obtain url instead of hard-coding","message":"Use django reverse function to obtain url instead of hard-coding\n","lang":"Python","license":"mpl-2.0","repos":"Apo11onian\/Apollo-Blog,Apo11onian\/Apollo-Blog,Apo11onian\/Apollo-Blog"} {"commit":"bb732b97536bd1bec605c96440ce1f18d5edb59a","old_file":"features\/steps\/install_steps.py","new_file":"features\/steps\/install_steps.py","old_contents":"from behave import given\n\nfrom captainhook.checkers.utils import bash\n\n\n@given('I have installed captainhook')\ndef step_impl(context):\n bash('captainhook')\n","new_contents":"from behave import given\n\nfrom captainhook.checkers.utils import bash\n\n\n@given('I have installed captainhook')\ndef step_impl(context):\n bash('captainhook install')\n","subject":"Fix behave tests to use install command.","message":"Fix behave tests to use install command.\n","lang":"Python","license":"bsd-3-clause","repos":"Friz-zy\/captainhook,alexcouper\/captainhook,pczerkas\/captainhook"} {"commit":"0f35ed05d335e7c126675bc913b72aac3ac916df","old_file":"project\/apps\/api\/signals.py","new_file":"project\/apps\/api\/signals.py","old_contents":"from django.db.models.signals import (\n post_save,\n)\n\nfrom django.dispatch import receiver\n\nfrom rest_framework.authtoken.models import Token\n\nfrom django.conf import settings\n\nfrom .models import (\n Contest,\n)\n\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef user_post_save(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance)\n\n\n@receiver(post_save, sender=Contest)\ndef contest_post_save(sender, instance=None, created=False, **kwargs):\n if created:\n instance.build()\n instance.save()\n","new_contents":"from django.db.models.signals import (\n post_save,\n)\n\nfrom django.dispatch import receiver\n\nfrom rest_framework.authtoken.models import Token\n\nfrom django.conf import settings\n\nfrom .models import (\n Contest,\n)\n\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef user_post_save(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance)\n\n\n@receiver(post_save, sender=Contest)\ndef contest_post_save(sender, instance=None, created=False, raw=False, **kwargs):\n if not raw:\n if created:\n instance.build()\n instance.save()\n","subject":"Add check for fixture loading","message":"Add check for fixture loading\n","lang":"Python","license":"bsd-2-clause","repos":"barberscore\/barberscore-api,dbinetti\/barberscore-django,dbinetti\/barberscore,barberscore\/barberscore-api,dbinetti\/barberscore,barberscore\/barberscore-api,dbinetti\/barberscore-django,barberscore\/barberscore-api"} {"commit":"f277007e46b7c6d8c978011d7356b7527ba91133","old_file":"axes\/utils.py","new_file":"axes\/utils.py","old_contents":"from axes.models import AccessAttempt\n\n\ndef reset(ip=None, username=None):\n \"\"\"Reset records that match ip or username, and\n return the count of removed attempts.\n \"\"\"\n count = 0\n\n attempts = AccessAttempt.objects.all()\n if ip:\n attempts = attempts.filter(ip_address=ip)\n if username:\n attempts = attempts.filter(username=username)\n\n if attempts:\n count = attempts.count()\n attempts.delete()\n\n return count\n\n\ndef iso8601(timestamp):\n \"\"\"Returns datetime.timedelta translated to ISO 8601 formatted duration.\n \"\"\"\n seconds = timestamp.total_seconds()\n minutes, seconds = divmod(seconds, 60)\n hours, minutes = divmod(minutes, 60)\n days, hours = divmod(hours, 24)\n\n date = '{:.0f}D'.format(days) if days else ''\n\n time_values = hours, minutes, seconds\n time_designators = 'H', 'M', 'S'\n\n time = ''.join([\n ('{:.0f}'.format(value) + designator)\n for value, designator in zip(time_values, time_designators)\n if value]\n )\n return u'P' + date + (u'T' + time if time else '')\n","new_contents":"from django.core.cache import cache\n\nfrom axes.models import AccessAttempt\n\n\ndef reset(ip=None, username=None):\n \"\"\"Reset records that match ip or username, and\n return the count of removed attempts.\n \"\"\"\n count = 0\n\n attempts = AccessAttempt.objects.all()\n if ip:\n attempts = attempts.filter(ip_address=ip)\n if username:\n attempts = attempts.filter(username=username)\n\n if attempts:\n count = attempts.count()\n from axes.decorators import get_cache_key\n for attempt in attempts:\n cache_hash_key = get_cache_key(attempt)\n if cache.get(cache_hash_key):\n cache.delete(cache_hash_key)\n\n attempts.delete()\n return count\n\n\ndef iso8601(timestamp):\n \"\"\"Returns datetime.timedelta translated to ISO 8601 formatted duration.\n \"\"\"\n seconds = timestamp.total_seconds()\n minutes, seconds = divmod(seconds, 60)\n hours, minutes = divmod(minutes, 60)\n days, hours = divmod(hours, 24)\n\n date = '{:.0f}D'.format(days) if days else ''\n\n time_values = hours, minutes, seconds\n time_designators = 'H', 'M', 'S'\n\n time = ''.join([\n ('{:.0f}'.format(value) + designator)\n for value, designator in zip(time_values, time_designators)\n if value]\n )\n return u'P' + date + (u'T' + time if time else '')\n","subject":"Delete cache key in reset command line","message":"Delete cache key in reset command line\n","lang":"Python","license":"mit","repos":"jazzband\/django-axes,django-pci\/django-axes"} {"commit":"a3c131776678b8e91e1179cd0f3c3b4b3fbbf6fb","old_file":"openid_provider\/tests\/test_code_flow.py","new_file":"openid_provider\/tests\/test_code_flow.py","old_contents":"from django.core.urlresolvers import reverse\nfrom django.test import RequestFactory\nfrom django.test import TestCase\nfrom openid_provider.tests.utils import *\nfrom openid_provider.views import *\n\n\nclass CodeFlowTestCase(TestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n self.user = create_fake_user()\n self.client = create_fake_client(response_type='code')\n\n def test_authorize_invalid_parameters(self):\n \"\"\"\n If the request fails due to a missing, invalid, or mismatching\n redirection URI, or if the client identifier is missing or invalid,\n the authorization server SHOULD inform the resource owner of the error.\n\n See: https:\/\/tools.ietf.org\/html\/rfc6749#section-4.1.2.1\n \"\"\"\n url = reverse('openid_provider:authorize')\n request = self.factory.get(url)\n\n response = AuthorizeView.as_view()(request)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(bool(response.content), True)","new_contents":"from django.core.urlresolvers import reverse\nfrom django.test import RequestFactory\nfrom django.test import TestCase\nfrom openid_provider.tests.utils import *\nfrom openid_provider.views import *\nimport urllib\n\n\nclass CodeFlowTestCase(TestCase):\n\n def setUp(self):\n self.factory = RequestFactory()\n self.user = create_fake_user()\n self.client = create_fake_client(response_type='code')\n\n def test_authorize_invalid_parameters(self):\n \"\"\"\n If the request fails due to a missing, invalid, or mismatching\n redirection URI, or if the client identifier is missing or invalid,\n the authorization server SHOULD inform the resource owner of the error.\n\n See: https:\/\/tools.ietf.org\/html\/rfc6749#section-4.1.2.1\n \"\"\"\n url = reverse('openid_provider:authorize')\n request = self.factory.get(url)\n\n response = AuthorizeView.as_view()(request)\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(bool(response.content), True)\n\n def test_authorize_invalid_response_type(self):\n \"\"\"\n The OP informs the RP by using the Error Response parameters defined\n in Section 4.1.2.1 of OAuth 2.0.\n\n See: http:\/\/openid.net\/specs\/openid-connect-core-1_0.html#AuthError\n \"\"\"\n # Create an authorize request with an unsupported response_type.\n url = reverse('openid_provider:authorize')\n url += '?client_id={0}&response_type=code%20id_token&scope=openid%20email' \\\n '&redirect_uri={1}&state=abcdefg'.format(\n self.client.client_id,\n urllib.quote(self.client.default_redirect_uri),\n )\n request = self.factory.get(url)\n\n response = AuthorizeView.as_view()(request)\n\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response.has_header('Location'), True)\n\n # Check query component in the redirection URI.\n correct_query = 'error=' in response['Location']\n self.assertEqual(correct_query, True)","subject":"Add another test for Code Flow.","message":"Add another test for Code Flow.\n","lang":"Python","license":"mit","repos":"wayward710\/django-oidc-provider,bunnyinc\/django-oidc-provider,wayward710\/django-oidc-provider,juanifioren\/django-oidc-provider,ByteInternet\/django-oidc-provider,wojtek-fliposports\/django-oidc-provider,ByteInternet\/django-oidc-provider,django-py\/django-openid-provider,torreco\/django-oidc-provider,django-py\/django-openid-provider,torreco\/django-oidc-provider,wojtek-fliposports\/django-oidc-provider,nmohoric\/django-oidc-provider,Sjord\/django-oidc-provider,Sjord\/django-oidc-provider,juanifioren\/django-oidc-provider,nmohoric\/django-oidc-provider,bunnyinc\/django-oidc-provider"} {"commit":"15c0ecf0e8ecd71017d8a1f2414204944b134fbd","old_file":"lib\/jasy\/__init__.py","new_file":"lib\/jasy\/__init__.py","old_contents":"#\n# Jasy - JavaScript Tooling Refined\n# Copyright 2010 Sebastian Werner\n#\n\n#\n# Configure logging\n#\n\nimport logging\n\nlogging.basicConfig(filename=\"log.txt\", level=logging.INFO, format=\"%(asctime)s - %(levelname)s - %(message)s\")\n\n# Define a Handler which writes INFO messages or higher to the sys.stderr\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\nconsole.setFormatter(logging.Formatter('>>> %(message)s', '%H:%M:%S'))\nlogging.getLogger('').addHandler(console)\n\n\n\n#\n# Import core classes\n#\n\nfrom jasy.Session import *\nfrom jasy.Project import *\nfrom jasy.Resolver import *\nfrom jasy.Sorter import *\nfrom jasy.Combiner import *\nfrom jasy.Assets import * \nfrom jasy.Optimization import *\nfrom jasy.Format import *\nfrom jasy.File import *\nfrom jasy.Task import *\n","new_contents":"#\n# Jasy - JavaScript Tooling Refined\n# Copyright 2010 Sebastian Werner\n#\n\n#\n# Configure logging\n#\n\nimport logging\n\nlogging.basicConfig(filename=\"log.txt\", level=logging.DEBUG, format=\"%(asctime)s - %(levelname)s - %(message)s\")\n\n# Define a Handler which writes INFO messages or higher to the sys.stderr\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\nconsole.setFormatter(logging.Formatter('>>> %(message)s', '%H:%M:%S'))\nlogging.getLogger('').addHandler(console)\n\n\n\n#\n# Import core classes\n#\n\nfrom jasy.Session import *\nfrom jasy.Project import *\nfrom jasy.Resolver import *\nfrom jasy.Sorter import *\nfrom jasy.Combiner import *\nfrom jasy.Assets import * \nfrom jasy.Optimization import *\nfrom jasy.Format import *\nfrom jasy.File import *\nfrom jasy.Task import *\n","subject":"Enable debug level for log file","message":"Enable debug level for log file\n","lang":"Python","license":"mit","repos":"sebastian-software\/jasy,zynga\/jasy,sebastian-software\/jasy,zynga\/jasy"} {"commit":"aaaaa179f43b720d207377cf17dcd6cec0c19321","old_file":"falcom\/tree\/mutable_tree.py","new_file":"falcom\/tree\/mutable_tree.py","old_contents":"# Copyright (c) 2017 The Regents of the University of Michigan.\n# All Rights Reserved. Licensed according to the terms of the Revised\n# BSD License. See LICENSE.txt for details.\n\nclass MutableTree:\n\n def __init__ (self, value = None):\n self.child = None\n self.children = [ ]\n self.value = value\n\n @property\n def value (self):\n return self.__value\n\n @value.setter\n def value (self, x):\n self.__value = x\n\n def __len__ (self):\n return 0 if self.child is None else 1\n\n def full_length (self):\n return len(self)\n\n def __iter__ (self):\n if self:\n return iter((self.child,))\n\n else:\n return iter(())\n\n def walk (self):\n return iter(self)\n\n def __getitem__ (self, index):\n if self and index == 0:\n return self.child\n\n else:\n raise IndexError(\"tree index out of range\")\n\n def insert (self, index, node):\n self.child = node\n self.children.insert(index, node)\n\n def __repr__ (self):\n debug = self.__class__.__name__\n\n if self.value is not None:\n debug += \" \" + repr(self.value)\n\n return \"<{}>\".format(debug)\n","new_contents":"# Copyright (c) 2017 The Regents of the University of Michigan.\n# All Rights Reserved. Licensed according to the terms of the Revised\n# BSD License. See LICENSE.txt for details.\n\nclass MutableTree:\n\n def __init__ (self, value = None):\n self.child = None\n self.children = [ ]\n self.value = value\n\n @property\n def value (self):\n return self.__value\n\n @value.setter\n def value (self, x):\n self.__value = x\n\n def __len__ (self):\n return 0 if self.child is None else 1\n\n def full_length (self):\n return len(self)\n\n def __iter__ (self):\n if self:\n return iter((self.child,))\n\n else:\n return iter(())\n\n def walk (self):\n return iter(self)\n\n def __getitem__ (self, index):\n if self and index == 0:\n return self.child\n\n else:\n raise IndexError(\"tree index out of range\")\n\n def insert (self, index, node):\n self.child = node\n self.children.insert(index, node)\n\n def __repr__ (self):\n debug = self.__class__.__name__\n\n if self.value is not None:\n debug += \" \" + repr(self.value)\n\n return \"<{} {}>\".format(debug, repr(self.children))\n","subject":"Add children to debug str","message":"Add children to debug str\n","lang":"Python","license":"bsd-3-clause","repos":"mlibrary\/image-conversion-and-validation,mlibrary\/image-conversion-and-validation"} {"commit":"4a38d0df3d72494e2a96ac776f13ce685b537561","old_file":"lokar\/bib.py","new_file":"lokar\/bib.py","old_contents":"# coding=utf-8\n\nfrom __future__ import unicode_literals\n\nfrom io import BytesIO\n\nfrom .marc import Record\nfrom .util import etree, parse_xml, show_diff\n\n\nclass Bib(object):\n \"\"\" An Alma Bib record \"\"\"\n\n def __init__(self, alma, xml):\n self.alma = alma\n self.orig_xml = xml.encode('utf-8')\n self.init(xml)\n\n def init(self, xml):\n self.doc = parse_xml(xml)\n self.mms_id = self.doc.findtext('mms_id')\n self.marc_record = Record(self.doc.find('record'))\n self.cz_link = self.doc.findtext('linked_record_id[@type=\"CZ\"]') or None\n\n def save(self, diff=False, dry_run=False):\n # Save record back to Alma\n\n post_data = (''.encode('utf-8') +\n etree.tostring(self.doc, encoding='UTF-8'))\n\n if diff:\n show_diff(self.orig_xml, post_data)\n\n if not dry_run:\n response = self.alma.put('\/bibs\/{}'.format(self.mms_id),\n data=BytesIO(post_data),\n headers={'Content-Type': 'application\/xml'})\n self.init(response)\n\n def dump(self, filename):\n # Dump record to file\n with open(filename, 'wb') as f:\n f.write(etree.tostring(self.doc, pretty_print=True))\n","new_contents":"# coding=utf-8\n\nfrom __future__ import unicode_literals\n\nfrom io import BytesIO\n\nfrom .marc import Record\nfrom .util import etree, parse_xml, show_diff\n\n\nclass Bib(object):\n \"\"\" An Alma Bib record \"\"\"\n\n def __init__(self, alma, xml):\n self.alma = alma\n self.orig_xml = xml\n self.init(xml)\n\n def init(self, xml):\n self.doc = parse_xml(xml)\n self.mms_id = self.doc.findtext('mms_id')\n self.marc_record = Record(self.doc.find('record'))\n self.cz_link = self.doc.findtext('linked_record_id[@type=\"CZ\"]') or None\n\n def save(self, diff=False, dry_run=False):\n # Save record back to Alma\n\n post_data = ('' +\n etree.tounicode(self.doc))\n\n if diff:\n show_diff(self.orig_xml, post_data)\n\n if not dry_run:\n response = self.alma.put('\/bibs\/{}'.format(self.mms_id),\n data=BytesIO(post_data.encode('utf-8')),\n headers={'Content-Type': 'application\/xml'})\n self.init(response)\n\n def dump(self, filename):\n # Dump record to file\n with open(filename, 'wb') as f:\n f.write(etree.tostring(self.doc, pretty_print=True))\n","subject":"Fix diffing on Py3 by comparing unicode strings","message":"Fix diffing on Py3 by comparing unicode strings\n","lang":"Python","license":"agpl-3.0","repos":"scriptotek\/almar,scriptotek\/lokar"} {"commit":"f4eff6d839d05731a6e29d3e769363e981a32739","old_file":"test\/run.py","new_file":"test\/run.py","old_contents":"#!\/bin\/env python2.7\n\nimport argparse\nimport os\n\nparser = argparse.ArgumentParser(description=\"Run unit tests\")\nparser.add_argument(\"-g\", \"--gui\", help=\"start in GUI mode\",\n action=\"store_true\")\nparser.add_argument(\"-t\", \"--test\", help=\"run only selected test(s)\",\n action=\"append\")\nargs = parser.parse_args()\n\ncommand = ['runSVUnit']\ncommand.append('-s ius')\n\nif args.gui:\n command.append('-c -linedebug')\n command.append('-r -gui')\n\nif args.test:\n for test in args.test:\n command.append('-t ' + test)\n\nos.system(' '.join(command))\n","new_contents":"#!\/bin\/env python2.7\n\nimport argparse\nimport os\n\nparser = argparse.ArgumentParser(description=\"Run unit tests\")\nparser.add_argument(\"-g\", \"--gui\", help=\"start in GUI mode\",\n action=\"store_true\")\nparser.add_argument(\"-t\", \"--test\", help=\"run only selected test(s)\",\n action=\"append\")\nparser.add_argument(\"--uvm-version\", help=\"run with selected UVM version (only supported for ius and xcelium\",\n choices=['1.1d', '1.2'])\nargs = parser.parse_args()\n\ncommand = ['runSVUnit']\ncommand.append('-s ius')\n\nif args.gui:\n command.append('-c -linedebug')\n command.append('-r -gui')\n \nif args.uvm_version:\n print(args.uvm_version)\n print(args.test)\n command.append('-r \"-uvmhome CDNS-{version}\"'.format(version=args.uvm_version))\n\nif args.test:\n for test in args.test:\n command.append('-t ' + test)\n\nprint(' '.join(command))\n\nos.system(' '.join(command))\n","subject":"Add ability to select UVM version in unit tests","message":"Add ability to select UVM version in unit tests\n","lang":"Python","license":"apache-2.0","repos":"tudortimi\/vgm_svunit_utils,tudortimi\/vgm_svunit_utils"} {"commit":"842441bebc328329caef0a7e7aae6d8594318097","old_file":"tests\/test_error_handling.py","new_file":"tests\/test_error_handling.py","old_contents":"import unittest\n\nfrom flask import Flask\nfrom flask_selfdoc import Autodoc\n\n\nclass TestErrorHandling(unittest.TestCase):\n def test_app_not_initialized(self):\n app = Flask(__name__)\n autodoc = Autodoc()\n with app.app_context():\n self.assertRaises(RuntimeError, lambda: autodoc.html())\n","new_contents":"import unittest\n\nfrom flask import Flask\nfrom flask_selfdoc import Autodoc\n\n\nclass TestErrorHandling(unittest.TestCase):\n def test_app_not_initialized(self):\n app = Flask(__name__)\n autodoc = Autodoc()\n with app.app_context():\n self.assertRaises(RuntimeError, lambda: autodoc.html())\n\n def test_app_initialized_by_ctor(self):\n app = Flask(__name__)\n autodoc = Autodoc(app)\n with app.app_context():\n autodoc.html()\n\n def test_app_initialized_by_init_app(self):\n app = Flask(__name__)\n autodoc = Autodoc()\n autodoc.init_app(app)\n with app.app_context():\n autodoc.html()\n","subject":"Add a test that these calls dont fail.","message":"Add a test that these calls dont fail.\n","lang":"Python","license":"mit","repos":"jwg4\/flask-autodoc,jwg4\/flask-autodoc"} {"commit":"1312dc95d9c25897c11c8e818edcb9cd2b6a32f7","old_file":"ecommerce\/extensions\/app.py","new_file":"ecommerce\/extensions\/app.py","old_contents":"from oscar import app\n\n\nclass EdxShop(app.Shop):\n # URLs are only visible to users with staff permissions\n default_permissions = 'is_staff'\n\n\napplication = EdxShop()\n","new_contents":"from oscar import app\nfrom oscar.core.application import Application\n\n\nclass EdxShop(app.Shop):\n # URLs are only visible to users with staff permissions\n default_permissions = 'is_staff'\n\n # Override core app instances with blank application instances to exclude their URLs.\n promotions_app = Application()\n catalogue_app = Application()\n offer_app = Application()\n search_app = Application()\n\n\napplication = EdxShop()\n","subject":"Move the security fix into Eucalyptus","message":"Move the security fix into Eucalyptus\n","lang":"Python","license":"agpl-3.0","repos":"mferenca\/HMS-ecommerce,mferenca\/HMS-ecommerce,mferenca\/HMS-ecommerce"} {"commit":"286422d95355fc55c1745731732d763ca1bdb7e5","old_file":"shap\/__init__.py","new_file":"shap\/__init__.py","old_contents":"# flake8: noqa\n\n__version__ = '0.28.5k'\n\nfrom .explainers.kernel import KernelExplainer, kmeans\nfrom .explainers.sampling import SamplingExplainer\nfrom .explainers.tree import TreeExplainer, Tree\nfrom .explainers.deep import DeepExplainer\nfrom .explainers.gradient import GradientExplainer\nfrom .explainers.linear import LinearExplainer\nfrom .plots.summary import summary_plot\nfrom .plots.dependence import dependence_plot\nfrom .plots.force import force_plot, initjs, save_html\nfrom .plots.image import image_plot\nfrom .plots.monitoring import monitoring_plot\nfrom .plots.embedding import embedding_plot\nfrom . import datasets\nfrom . import benchmark\nfrom .explainers import other\nfrom .common import approximate_interactions, hclust_ordering\n","new_contents":"# flake8: noqa\n\n__version__ = '0.28.6'\n\nfrom .explainers.kernel import KernelExplainer, kmeans\nfrom .explainers.sampling import SamplingExplainer\nfrom .explainers.tree import TreeExplainer, Tree\nfrom .explainers.deep import DeepExplainer\nfrom .explainers.gradient import GradientExplainer\nfrom .explainers.linear import LinearExplainer\nfrom .plots.summary import summary_plot\nfrom .plots.dependence import dependence_plot\nfrom .plots.force import force_plot, initjs, save_html\nfrom .plots.image import image_plot\nfrom .plots.monitoring import monitoring_plot\nfrom .plots.embedding import embedding_plot\nfrom . import datasets\nfrom . import benchmark\nfrom .explainers import other\nfrom .common import approximate_interactions, hclust_ordering\n","subject":"Tag new version with bug fixes.","message":"Tag new version with bug fixes.\n","lang":"Python","license":"mit","repos":"slundberg\/shap,slundberg\/shap,slundberg\/shap,slundberg\/shap"} {"commit":"1f8895c4e2f9189032383771d322afdbfdac5e37","old_file":"pathvalidate\/variable\/_elasticsearch.py","new_file":"pathvalidate\/variable\/_elasticsearch.py","old_contents":"# encoding: utf-8\n\n\"\"\"\n.. codeauthor:: Tsuyoshi Hombashi \n\"\"\"\n\nfrom __future__ import absolute_import, unicode_literals\n\nimport re\n\nfrom ._base import VarNameSanitizer\n\n\nclass ElasticsearchIndexNameSanitizer(VarNameSanitizer):\n\n __RE_INVALID_INDEX_NAME = re.compile(\"[\" + re.escape('\\\\\/*?\"<>|,\"') + \"\\s]+\")\n __RE_INVALID_INDEX_NAME_HEAD = re.compile(\"^[_]+\")\n\n @property\n def reserved_keywords(self):\n return []\n\n @property\n def _invalid_var_name_head_re(self):\n return self.__RE_INVALID_INDEX_NAME_HEAD\n\n @property\n def _invalid_var_name_re(self):\n return self.__RE_INVALID_INDEX_NAME\n","new_contents":"# encoding: utf-8\n\n\"\"\"\n.. codeauthor:: Tsuyoshi Hombashi \n\"\"\"\n\nfrom __future__ import absolute_import, unicode_literals\n\nimport re\n\nfrom ._base import VarNameSanitizer\n\n\nclass ElasticsearchIndexNameSanitizer(VarNameSanitizer):\n\n __RE_INVALID_INDEX_NAME = re.compile(\"[\" + re.escape('\\\\\/*?\"<>|,\"') + r\"\\s]+\")\n __RE_INVALID_INDEX_NAME_HEAD = re.compile(\"^[_]+\")\n\n @property\n def reserved_keywords(self):\n return []\n\n @property\n def _invalid_var_name_head_re(self):\n return self.__RE_INVALID_INDEX_NAME_HEAD\n\n @property\n def _invalid_var_name_re(self):\n return self.__RE_INVALID_INDEX_NAME\n","subject":"Change to avoid \"DeprecationWarning: invalid escape sequence\"","message":"Change to avoid \"DeprecationWarning: invalid escape sequence\"\n","lang":"Python","license":"mit","repos":"thombashi\/pathvalidate"} {"commit":"1958165c7bf3b9fa45972658b980cefe6a742164","old_file":"myhpom\/validators.py","new_file":"myhpom\/validators.py","old_contents":"import re\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import EmailValidator, RegexValidator\nfrom django.contrib.auth.models import User\n\n# First Name, Last Name: At least one alphanumeric character.\nname_validator = RegexValidator(\n regex=r'\\w',\n flags=re.U,\n message='Please enter your name'\n)\n\n# Email: valid email address\nemail_validator = EmailValidator()\n\n# Email is not already taken\ndef email_not_taken_validator(email):\n if len(User.objects.filter(email=email)) > 0:\n raise ValidationError(u'Email already in use.')\n\n# Password: At least 8 chars total, 1 uppercase, lowercase, digit, special char.\ndef password_validator(password):\n errors = []\n if len(password) < 8:\n errors.append(u'8 characters total')\n if re.search(r\"[a-z]\", password) is None:\n errors.append(u'1 lowercase letter (a-z)')\n if re.search(r\"[A-Z]\", password) is None:\n errors.append(u'1 uppercase letter (A-Z)')\n if re.search(r\"\\d\", password) is None:\n errors.append(u'1 number (0-9)')\n if re.search(r\"[!\\@\\#\\$\\%\\^\\*\\(\\)\\_\\+\\-\\=]\", password) is None:\n errors.append(u'1 special character (! @ # $ % ^ * ( ) _ + - =)')\n if len(errors) > 0:\n raise ValidationError(u'Please enter a password with at least ' + u', '.join(errors))\n\n","new_contents":"import re\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import EmailValidator, RegexValidator\n\n# First Name, Last Name: At least one alphanumeric character.\nname_validator = RegexValidator(\n regex=r'\\w',\n flags=re.U,\n message='Please enter your name'\n)\n\n# Email: valid email address\nemail_validator = EmailValidator()\n\n# Email is not already taken\ndef email_not_taken_validator(email):\n from myhpom.models import User\n if len(User.objects.filter(email=email)) > 0:\n raise ValidationError(u'Email already in use.')\n\n# Password: At least 8 chars total, 1 uppercase, lowercase, digit, special char.\ndef password_validator(password):\n errors = []\n if len(password) < 8:\n errors.append(u'8 characters total')\n if re.search(r\"[a-z]\", password) is None:\n errors.append(u'1 lowercase letter (a-z)')\n if re.search(r\"[A-Z]\", password) is None:\n errors.append(u'1 uppercase letter (A-Z)')\n if re.search(r\"\\d\", password) is None:\n errors.append(u'1 number (0-9)')\n if re.search(r\"[!\\@\\#\\$\\%\\^\\*\\(\\)\\_\\+\\-\\=]\", password) is None:\n errors.append(u'1 special character (! @ # $ % ^ * ( ) _ + - =)')\n if len(errors) > 0:\n raise ValidationError(u'Please enter a password with at least ' + u', '.join(errors))\n\n","subject":"Revert \"[mh-14] \"This import is ultimately just from django.contrib.auth.models import User - using that directly would probably address whatever circular import required that this import get put here, and make it clearer which model User is.\"-Dane\"","message":"Revert \"[mh-14] \"This import is ultimately just from django.contrib.auth.models import User - using that directly would probably address whatever circular import required that this import get put here, and make it clearer which model User is.\"-Dane\"\n\nThis reverts commit 7350c56339acaef416d03b6d7ae0e818ab8db182.\n","lang":"Python","license":"bsd-3-clause","repos":"ResearchSoftwareInstitute\/MyHPOM,ResearchSoftwareInstitute\/MyHPOM,ResearchSoftwareInstitute\/MyHPOM,ResearchSoftwareInstitute\/MyHPOM,ResearchSoftwareInstitute\/MyHPOM"} {"commit":"906950ec1bd1f5d0980116d10344f9f1b7d844ed","old_file":"Importacions_F1_Q1\/Fact_impF1_eliminar_Ja_existeix.py","new_file":"Importacions_F1_Q1\/Fact_impF1_eliminar_Ja_existeix.py","old_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nfrom ooop import OOOP\nimport configdb\n\nO = OOOP(**configdb.ooop)\n\nimp_obj = O.GiscedataFacturacioImportacioLinia\n\nimp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',\"Aquest fitxer XML ja s'ha processat en els següents IDs\")])\n#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')])\nimp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',\"XML no es correspon al tipus F1\")])\nimp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',\"Document invàlid\")])\n\ntotal = len(imp_del_ids)\nn = 0\n\nfor imp_del_id in imp_del_ids:\n try:\n imp_obj.unlink([imp_del_id])\n n +=1\n print \"%d\/%d\" % (n,total)\n except Exception, e:\n print e \n","new_contents":"#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nfrom ooop import OOOP\nimport configdb\n\nO = OOOP(**configdb.ooop)\n\nimp_obj = O.GiscedataFacturacioImportacioLinia\n\nimp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',\"Aquest fitxer XML ja s'ha processat en els següents IDs\")])\nimp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',\"Ja existeix una factura amb el mateix origen\")])\n#imp_del_ids += imp_obj.search([('state','=','erroni'),('info','like','XML erroni')])\nimp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',\"XML no es correspon al tipus F1\")])\nimp_del_ids += imp_obj.search([('state','=','erroni'),('info','like',\"Document invàlid\")])\n\ntotal = len(imp_del_ids)\nn = 0\n\nfor imp_del_id in imp_del_ids:\n try:\n imp_obj.unlink([imp_del_id])\n n +=1\n print \"%d\/%d\" % (n,total)\n except Exception, e:\n print e \n","subject":"Kill \"Ja existeix una factura amb el mateix..\" too","message":"Kill \"Ja existeix una factura amb el mateix..\" too\n","lang":"Python","license":"agpl-3.0","repos":"Som-Energia\/invoice-janitor"} {"commit":"cca5b6355a376cb1f51a45a3fac5ca5e4b96f5c7","old_file":"pyflation\/configuration.py","new_file":"pyflation\/configuration.py","old_contents":"\"\"\"Configuration file for harness.py\n\nAuthor: Ian Huston\nFor license and copyright information see LICENSE.txt which was distributed with this file.\n\n\n\"\"\"\nimport logging\n\n##################################################\n# debug logging control\n# 0 for off, 1 for on\n##################################################\n_debug = 1\n\n#This is the default log level which can be overridden in run_config.\n# The logging level changes how much is saved to logging files. \n# Choose from logging.DEBUG, .INFO, .WARN, .ERROR, .CRITICAL in decreasing order of verbosity\nLOGLEVEL = logging.INFO\n\n# Directory structure\n# Change the names of various directories\n#Change to using the base run directory with bin, pyflation, scripts immediately below.\nCODEDIRNAME = \".\" \nRUNDIRNAME = \"runs\"\nRESULTSDIRNAME = \"results\"\nLOGDIRNAME = \"applogs\"\nQSUBSCRIPTSDIRNAME = \"qsubscripts\"\nQSUBLOGSDIRNAME = \"qsublogs\"\nRUNCONFIGTEMPLATE = \"run_config.template\"\n\n#Name of provenance file which records the code revisions and results files added\nprovenancefilename = \"provenance.log\"\n\n# Compression type to be used with PyTables:\n# PyTables stores results in HDF5 files. The compression it uses can be \n# selected here. For maximum compatibility with other HDF5 utilities use \"zlib\".\n# For maximum efficiency in both storage space and recall time use \"blosc\".\nhdf5complib = \"blosc\"\nhdf5complevel = 2\n\n\n\n\n\n\n","new_contents":"\"\"\"Configuration file for harness.py\n\nAuthor: Ian Huston\nFor license and copyright information see LICENSE.txt which was distributed with this file.\n\nThe main configuration options are for logging. By changing _debug to 1 (default\nis 0) much more debugging information will be added to the log files. \nThe overall logging level can also be set using the LOGLEVEL variable. This\nlevel can be overridden using command line options to the scripts.\n\n\"\"\"\nimport logging\n\n##################################################\n# debug logging control\n# 0 for off, 1 for on\n##################################################\n_debug = 1\n\n#This is the default log level which can be overridden in run_config.\n# The logging level changes how much is saved to logging files. \n# Choose from logging.DEBUG, .INFO, .WARN, .ERROR, .CRITICAL in decreasing order of verbosity\nLOGLEVEL = logging.INFO\n\n# Directory structure\n# Change the names of various directories\n#Change to using the base run directory with bin, pyflation, scripts immediately below.\nCODEDIRNAME = \".\" \nRUNDIRNAME = \"runs\"\nRESULTSDIRNAME = \"results\"\nLOGDIRNAME = \"applogs\"\nQSUBSCRIPTSDIRNAME = \"qsubscripts\"\nQSUBLOGSDIRNAME = \"qsublogs\"\nRUNCONFIGTEMPLATE = \"run_config.template\"\n\n#Name of provenance file which records the code revisions and results files added\nprovenancefilename = \"provenance.log\"\n\n# Compression type to be used with PyTables:\n# PyTables stores results in HDF5 files. The compression it uses can be \n# selected here. For maximum compatibility with other HDF5 utilities use \"zlib\".\n# For maximum efficiency in both storage space and recall time use \"blosc\".\nhdf5complib = \"blosc\"\nhdf5complevel = 2\n\n\n\n\n\n\n","subject":"Add some explanation of logging options.","message":"Add some explanation of logging options.\n","lang":"Python","license":"bsd-3-clause","repos":"ihuston\/pyflation,ihuston\/pyflation"} {"commit":"1f112cb553b0170eb948cfb53883913dc2f3b0b3","old_file":"index.py","new_file":"index.py","old_contents":"from gevent import monkey\nmonkey.patch_all()\n\nimport time\nfrom threading import Thread\nimport settings\nimport requests\nfrom flask import Flask\nfrom flask.ext.socketio import SocketIO, emit\n\napp = Flask(__name__)\napp.config.from_object('settings')\napp.debug = True\n\nif not app.debug:\n import logging\n file_handler = logging.FileHandler('production.log')\n file_handler.setLevel(logging.WARNING)\n app.logger.addHandler(file_handler)\n\nsocketio = SocketIO(app)\nthread = None\n\nclass StorjAPI:\n\t@staticmethod\n\tdef getNodeStatus():\n\t\tr = requests.get(app.config['NODE_URL'] + '\/api\/status')\n\t\treturn r.json()\n\ndef status_thread():\n while True:\n time.sleep(5)\n socketio.emit('status', StorjAPI.getNodeStatus(), namespace='\/metadisk')\n\n@socketio.on('status')\ndef node_status():\n\tsocketio.emit('status', StorjAPI.getNodeStatus())\n\n@socketio.on('connect', namespace='\/metadisk')\ndef metadisk_connect():\n\tglobal thread\n\tif thread is None:\n\t\tthread = Thread(target=status_thread)\n\t\tthread.start()\n\tprint('Client has connected.')\n\n@socketio.on('disconnect', namespace='\/metadisk')\ndef metadisk_disconnect():\n print('Client has disconnected.')\n\nif __name__ == '__main__':\n\tsocketio.run(app)","new_contents":"from gevent import monkey\nmonkey.patch_all()\n\nimport time\nfrom threading import Thread\nimport settings\nimport requests\nfrom flask import Flask\nfrom flask.ext.socketio import SocketIO, emit\n\napp = Flask(__name__)\napp.config.from_object('settings')\napp.debug = True\n\nif not app.debug:\n import logging\n file_handler = logging.FileHandler('production.log')\n file_handler.setLevel(logging.WARNING)\n app.logger.addHandler(file_handler)\n\nsocketio = SocketIO(app)\nthread = None\n\nclass StorjAPI:\n\t@staticmethod\n\tdef getNodeStatus():\n\t\tr = requests.get(app.config['NODE_URL'] + '\/api\/status')\n\t\treturn r.json()\n\ndef status_thread():\n while True:\n time.sleep(5)\n socketio.emit('status', StorjAPI.getNodeStatus(), namespace='\/metadisk')\n\n@socketio.on('connect', namespace='\/metadisk')\ndef metadisk_connect():\n\tglobal thread\n\tif thread is None:\n\t\tthread = Thread(target=status_thread)\n\t\tthread.start()\n\tprint('Client has connected.')\n\n@socketio.on('disconnect', namespace='\/metadisk')\ndef metadisk_disconnect():\n print('Client has disconnected.')\n\nif __name__ == '__main__':\n\tsocketio.run(app)","subject":"Remove manual emit on status","message":"Remove manual emit on status\n","lang":"Python","license":"mit","repos":"Storj\/metadisk-websockets"} {"commit":"2e99893065abef2f751e3fb5f19a59bfee79a756","old_file":"language_model_transcription.py","new_file":"language_model_transcription.py","old_contents":"import metasentence\nimport language_model\nimport standard_kaldi\n\nimport diff_align\n\nimport json\nimport os\nimport sys\n\n\nvocab = metasentence.load_vocabulary('PROTO_LANGDIR\/graphdir\/words.txt')\n\ndef lm_transcribe(audio_f, text_f):\n\n ms = metasentence.MetaSentence(open(text_f).read(), vocab)\n model_dir = language_model.getLanguageModel(ms.get_kaldi_sequence())\n\n print 'generated model', model_dir\n\n k = standard_kaldi.Kaldi(os.path.join(model_dir, 'graphdir', 'HCLG.fst'))\n\n trans = standard_kaldi.transcribe(k, audio_f)\n\n ret = diff_align.align(trans[\"words\"], ms)\n\n return ret\n\nif __name__=='__main__':\n AUDIO_FILE = sys.argv[1]\n TEXT_FILE = sys.argv[2]\n OUTPUT_FILE = sys.argv[3]\n\n ret = lm_transcribe(AUDIO_FILE, TEXT_FILE)\n json.dump(ret, open(OUTPUT_FILE, 'w'), indent=2)\n \n","new_contents":"import metasentence\nimport language_model\nimport standard_kaldi\n\nimport diff_align\n\nimport json\nimport os\nimport sys\n\n\nvocab = metasentence.load_vocabulary('PROTO_LANGDIR\/graphdir\/words.txt')\n\ndef lm_transcribe(audio_f, text_f):\n\n ms = metasentence.MetaSentence(open(text_f).read(), vocab)\n model_dir = language_model.getLanguageModel(ms.get_kaldi_sequence())\n\n print 'generated model', model_dir\n\n k = standard_kaldi.Kaldi(os.path.join(model_dir, 'graphdir', 'HCLG.fst'))\n\n trans = standard_kaldi.transcribe(k, audio_f)\n\n ret = diff_align.align(trans[\"words\"], ms)\n\n return ret\n\nif __name__=='__main__':\n import argparse\n\n parser = argparse.ArgumentParser(\n description='Align a transcript to audio by generating a new language model.')\n parser.add_argument('audio_file', help='input audio file in any format supported by FFMPEG')\n parser.add_argument('text_file', help='input transcript as plain text')\n parser.add_argument('output_file', type=argparse.FileType('w'),\n help='output json file for aligned transcript')\n parser.add_argument('--proto_langdir', default=\"PROTO_LANGDIR\",\n help='path to the prototype language directory')\n\n args = parser.parse_args()\n\n ret = lm_transcribe(args.audio_file, args.text_file)\n json.dump(ret, args.output_file, indent=2)\n \n","subject":"Use argparse for main python entrypoint args.","message":"Use argparse for main python entrypoint args.\n\nWill make it easier to add proto_langdir as a flag argument in a future commit.\n","lang":"Python","license":"mit","repos":"lowerquality\/gentle,lowerquality\/gentle,lowerquality\/gentle,lowerquality\/gentle"} {"commit":"de15315b95f70e56d424d54637e3ac0d615ea0f0","old_file":"proto\/ho.py","new_file":"proto\/ho.py","old_contents":"from board import Board, BoardCanvas\n\n\nb = Board(19, 19)\nc = BoardCanvas(b)\n","new_contents":"#!\/usr\/bin\/env python\n\nimport platform\nimport subprocess\nimport sys\nfrom copy import deepcopy\n\nfrom board import Board, BoardCanvas\n\n\ndef clear():\n subprocess.check_call('cls' if platform.system() == 'Windows' else 'clear', shell=True)\n\n\nclass _Getch:\n \"\"\"\n Gets a single character from standard input. Does not echo to the\n screen.\n \"\"\"\n def __init__(self):\n try:\n self.impl = _GetchWindows()\n except ImportError:\n self.impl = _GetchUnix()\n\n def __call__(self):\n return self.impl()\n\n\nclass _GetchUnix:\n def __call__(self):\n import tty\n import termios\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n tty.setraw(sys.stdin.fileno())\n ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\n\nclass _GetchWindows:\n def __init__(self):\n import msvcrt # NOQA\n\n def __call__(self):\n import msvcrt\n return msvcrt.getch()\n\n\ngetch = _Getch()\n\n\nWIDTH = 19\nHEIGHT = 19\n\n\ndef trunc_width(v):\n return max(1, min(WIDTH, v))\n\n\ndef trunc_height(v):\n return max(1, min(HEIGHT, v))\n\n\ndef move_up(x, y):\n return trunc_width(x), trunc_height(y - 1)\n\n\ndef move_down(x, y):\n return trunc_width(x), trunc_height(y + 1)\n\n\ndef move_left(x, y):\n return trunc_width(x - 1), trunc_height(y)\n\n\ndef move_right(x, y):\n return trunc_width(x + 1), trunc_height(y)\n\n\nKEYS = {\n 'w': move_up,\n 'r': move_down,\n 'a': move_left,\n 's': move_right,\n}\n\n\ndef main():\n board = Board(WIDTH, HEIGHT)\n canvas = BoardCanvas(board)\n\n cur_x, cur_y = (1, 1)\n\n while True:\n clear()\n\n # Print board\n select_board = deepcopy(canvas)\n select_board.set(cur_x, cur_y, 'X')\n print select_board\n print 'Make your move... '\n\n # Get char\n c = getch()\n\n # Escape terminates\n if c == '\\x1b':\n break\n\n # Move cursor\n try:\n cur_x, cur_y = KEYS[c](cur_x, cur_y)\n except KeyError:\n pass\n\nif __name__ == '__main__':\n main()\n","subject":"Add game loop to prototype","message":"Add game loop to prototype\n","lang":"Python","license":"mit","repos":"davesque\/go.py"} {"commit":"038b56134017b6b3e4ea44d1b7197bc5168868d3","old_file":"safeopt\/__init__.py","new_file":"safeopt\/__init__.py","old_contents":"\"\"\"\nThe `safeopt` package provides...\n\nMain classes\n============\n.. autosummary::\n SafeOpt\n SafeOptSwarm\n\nUtilities\n=========\n.. autosummary::\n sample_gp_function\n linearly_spaced_combinations\n plot_2d_gp\n plot_3d_gp\n plot_contour_gp\n\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom .utilities import *\nfrom .gp_opt import *\n\n\n__all__ = [s for s in dir() if not s.startswith('_')]\n","new_contents":"\"\"\"\nThe `safeopt` package provides...\n\nMain classes\n============\n\nThese classes provide the main functionality for Safe Bayesian optimization.\n\n.. autosummary::\n SafeOpt\n SafeOptSwarm\n\nUtilities\n=========\n\nThe following are utilities to make testing and working with the library more pleasant.\n\n.. autosummary::\n sample_gp_function\n linearly_spaced_combinations\n plot_2d_gp\n plot_3d_gp\n plot_contour_gp\n\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom .utilities import *\nfrom .gp_opt import *\n\n\n__all__ = [s for s in dir() if not s.startswith('_')]\n","subject":"Add short comment to docs","message":"Add short comment to docs\n","lang":"Python","license":"mit","repos":"befelix\/SafeOpt,befelix\/SafeOpt"} {"commit":"d295575284e712a755d3891806a7e40b65377a69","old_file":"music_essentials\/chord.py","new_file":"music_essentials\/chord.py","old_contents":"class Chord(object):\n # TODO: doctring\n def __init__(self, root_note):\n # TODO: doctring\n # TODO: validation\n self.notes = [root_note]\n \n def root(self):\n # TODO: doctring\n # TODO: tests\n return self.notes[0]\n\n def add_note(self, new_note):\n # TODO: docstring\n # TODO: tests\n if new_note < self.root():\n self.notes.insert(0, new_note)\n return\n\n for i in range(len(self.notes) - 1):\n if (new_note >= self.notes[i]) and (new_note < self.notes[i + 1]):\n self.notes.insert(i + 1, new_note)\n return\n\n self.notes.append(new_note)","new_contents":"class Chord(object):\n # TODO: doctring\n def __init__(self, root_note):\n # TODO: doctring\n # TODO: validation\n self.notes = [root_note]\n \n def root(self):\n # TODO: doctring\n # TODO: tests\n return self.notes[0]\n\n def add_note(self, new_note):\n # TODO: docstring\n # TODO: tests\n if new_note < self.root():\n self.notes.insert(0, new_note)\n return\n\n for i in range(len(self.notes) - 1):\n if (new_note >= self.notes[i]) and (new_note < self.notes[i + 1]):\n self.notes.insert(i + 1, new_note)\n return\n\n self.notes.append(new_note)\n \n def __str__(self):\n # TODO: docstring\n out = ''\n for n in self.notes:\n out += n.__str__() + '+'\n out = out [:-1]\n \n return out","subject":"Add __str__ method for Chord class.","message":"Add __str__ method for Chord class.\n\nSigned-off-by: Charlotte Pierce <351429ca27f6e4bff2dbb77adb5046c88cd12fae@malformed-bits.com>\n","lang":"Python","license":"mit","repos":"charlottepierce\/music_essentials"} {"commit":"0d50f6663bbc7f366c9db6a9aeef5feb0f4cb5f2","old_file":"src\/ExampleNets\/readAllFields.py","new_file":"src\/ExampleNets\/readAllFields.py","old_contents":"import glob\nimport os\nimport SCIRunPythonAPI; from SCIRunPythonAPI import *\n\ndef allFields(path):\n\tnames = []\n\tfor dirname, dirnames, filenames in os.walk(path):\n\t\tfor filename in filenames:\n\t\t\tif filename.endswith(\"fld\"):\n\t\t\t\tnames.append(os.path.join(dirname, filename))\n\treturn names\n\t\ndir = r\"E:\\scirun\\trunk_ref\\SCIRunData\"\n\nfor file in allFields(dir):\n\tread = addModule(\"ReadField\")\n\tread.Filename = file\n\tshow = addModule(\"ReportFieldInfo\")\n\tread.output[0] >> show.input.Input\n#executeAll()\n","new_contents":"import glob\nimport os\nimport time\nimport SCIRunPythonAPI; from SCIRunPythonAPI import *\n\ndef allFields(path):\n\tnames = []\n\tfor dirname, dirnames, filenames in os.walk(path):\n\t\tfor filename in filenames:\n\t\t\tif filename.endswith(\"fld\"):\n\t\t\t\tnames.append(os.path.join(dirname, filename))\n\treturn names\n\t\ndef printList(list, name):\n\tthefile = open(name, 'w')\n\tfor f,v in list:\n\t\tthefile.write(\"%s\\n\\t%s\\n\" % (f,v))\n\t\n\ndir = r\"E:\\scirun\\trunk_ref\\SCIRunData\"\n\nvalues = []\nfiles = []\n\nfor file in allFields(dir):\n\tread = addModule(\"ReadField\")\n\tread.Filename = file\n\tfiles.append(file)\n\tshow = addModule(\"ReportFieldInfo\")\n\tprnt = addModule(\"PrintDatatype\")\n\tread.output[0] >> show.input.Input\n\tshow.output[0] >> prnt.input[0]\n\texecuteAll()\n\ttime.sleep(1)\n\tvalues.append(prnt.ReceivedValue)\n\t[removeModule(m.id) for m in modules()]\n\nprintList(zip(files, values), r'E:\\fieldTypes.txt')","subject":"Update script to print all field types to a file","message":"Update script to print all field types to a file\n","lang":"Python","license":"mit","repos":"moritzdannhauer\/SCIRunGUIPrototype,jessdtate\/SCIRun,jessdtate\/SCIRun,jessdtate\/SCIRun,jcollfont\/SCIRun,jcollfont\/SCIRun,ajanson\/SCIRun,jessdtate\/SCIRun,ajanson\/SCIRun,moritzdannhauer\/SCIRunGUIPrototype,collint8\/SCIRun,moritzdannhauer\/SCIRunGUIPrototype,moritzdannhauer\/SCIRunGUIPrototype,ajanson\/SCIRun,jessdtate\/SCIRun,collint8\/SCIRun,jcollfont\/SCIRun,ajanson\/SCIRun,collint8\/SCIRun,jcollfont\/SCIRun,jcollfont\/SCIRun,collint8\/SCIRun,ajanson\/SCIRun,jessdtate\/SCIRun,jessdtate\/SCIRun,jcollfont\/SCIRun,collint8\/SCIRun,collint8\/SCIRun,collint8\/SCIRun,ajanson\/SCIRun,jessdtate\/SCIRun,collint8\/SCIRun,moritzdannhauer\/SCIRunGUIPrototype,moritzdannhauer\/SCIRunGUIPrototype,ajanson\/SCIRun,moritzdannhauer\/SCIRunGUIPrototype,jcollfont\/SCIRun"} {"commit":"b1bd07038b0c6a6d801e686372996b3478c71af9","old_file":"iss\/management\/commands\/upsert_iss_organizations.py","new_file":"iss\/management\/commands\/upsert_iss_organizations.py","old_contents":"#!\/usr\/bin\/env python\n\"\"\"Upserts Organization records with data from Salesforce Accounts.\n\"\"\"\nimport logging\nimport os\n\nfrom django.core.management.base import BaseCommand\n\nimport iss.salesforce\nimport iss.utils\n\n\nlogger = logging.getLogger(os.path.basename(__file__))\n\n\nclass Command(BaseCommand):\n\n def add_arguments(self, parser):\n parser.add_argument(\n '-m', '--modified-within',\n type=int,\n metavar='n-days',\n default=7,\n help='upsert organizations for accounts modified within n-days')\n\n def handle(self, *args, **options):\n upsert_organizations_for_recently_modified_accounts(\n options['modified_within'])\n\n\ndef upsert_organizations_for_recently_modified_accounts(since=7):\n \"\"\"Upsert organizations for SF Accounts modified in last `since` days.\"\"\"\n logger.info('upserting orgs for accounts modified in last {since} days'.\n format(since=since))\n recently_modified_accounts = (\n iss.salesforce.Account.get_recently_modified_accounts(since=since))\n iss.utils.upsert_organizations_for_accounts(recently_modified_accounts)\n","new_contents":"#!\/usr\/bin\/env python\n\"\"\"Upserts Organization records with data from Salesforce Accounts.\n\"\"\"\nimport logging\nimport os\n\nfrom django.core.management.base import BaseCommand\n\nimport iss.models\nimport iss.salesforce\nimport iss.utils\n\n\nlogger = logging.getLogger(os.path.basename(__file__))\n\n\nclass Command(BaseCommand):\n\n def add_arguments(self, parser):\n parser.add_argument(\n '-m', '--modified-within',\n type=int,\n metavar='n-days',\n default=7,\n help='upsert organizations for accounts modified within n-days')\n parser.add_argument(\n '-i', '--include-aashe-in-website',\n action='store_true',\n help='force AASHE exclude_from_website to be False')\n\n def handle(self, *args, **options):\n upsert_organizations_for_recently_modified_accounts(\n since=options['modified_within'],\n include_aashe_in_website=options['include_aashe_in_website'])\n\n\ndef upsert_organizations_for_recently_modified_accounts(\n since=7, include_aashe_in_website=False):\n \"\"\"Upsert organizations for SF Accounts modified in last `since` days.\n\n When `include_aashe_in_website` is true, set the\n `exclude_from_website` flag on the Organization representing AASHE\n to False (0, actually). (Added for the Hub project.)\n \"\"\"\n logger.info('upserting orgs for accounts modified in last {since} days'.\n format(since=since))\n recently_modified_accounts = (\n iss.salesforce.Account.get_recently_modified_accounts(since=since))\n iss.utils.upsert_organizations_for_accounts(recently_modified_accounts)\n\n if include_aashe_in_website:\n aashe = iss.models.Organization.objects.get(org_name=\"AASHE\")\n if aashe.exclude_from_website:\n aashe.exclude_from_website = 0\n aashe.save()\n","subject":"Add --include-aashe-in-website flag to org upsert","message":"Add --include-aashe-in-website flag to org upsert\n","lang":"Python","license":"mit","repos":"AASHE\/iss"} {"commit":"ed45688c062aed44836fe902bb61bf858ed4b4bf","old_file":"sale_require_ref\/__openerp__.py","new_file":"sale_require_ref\/__openerp__.py","old_contents":"# -*- coding: utf-8 -*-\n{\n 'name': 'Sale Order Require Contract on Confirmation',\n 'version': '1.0',\n 'category': 'Projects & Services',\n 'sequence': 14,\n 'summary': '',\n 'description': \"\"\"\nSale Order Require Contract on Confirmation\n===========================================\n \"\"\",\n 'author': 'ADHOC SA',\n 'website': 'www.ingadhoc.com',\n 'images': [\n ],\n 'depends': [\n 'sale',\n ],\n 'data': [\n ],\n 'demo': [\n ],\n 'test': [\n ],\n 'installable': True,\n 'auto_install': False,\n 'application': False,\n}\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","new_contents":"# -*- coding: utf-8 -*-\n{\n 'name': 'Sale Order Require Contract on Confirmation',\n 'version': '1.0',\n 'category': 'Projects & Services',\n 'sequence': 14,\n 'summary': '',\n 'description': \"\"\"\nSale Order Require Contract on Confirmation\n===========================================\n \"\"\",\n 'author': 'ADHOC SA',\n 'website': 'www.ingadhoc.com',\n 'images': [\n ],\n 'depends': [\n 'sale',\n ],\n 'data': [\n ],\n 'demo': [\n ],\n 'test': [\n ],\n 'installable': False,\n 'auto_install': False,\n 'application': False,\n}\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","subject":"FIX mae sale require fe uninstallable","message":"FIX mae sale require fe uninstallable\n","lang":"Python","license":"agpl-3.0","repos":"ingadhoc\/account-analytic,ingadhoc\/sale,ingadhoc\/account-invoicing,bmya\/odoo-addons,ingadhoc\/stock,ingadhoc\/product,dvitme\/odoo-addons,maljac\/odoo-addons,adhoc-dev\/account-financial-tools,ingadhoc\/sale,HBEE\/odoo-addons,ClearCorp\/account-financial-tools,sysadminmatmoz\/ingadhoc,jorsea\/odoo-addons,jorsea\/odoo-addons,sysadminmatmoz\/ingadhoc,jorsea\/odoo-addons,dvitme\/odoo-addons,ClearCorp\/account-financial-tools,maljac\/odoo-addons,HBEE\/odoo-addons,ingadhoc\/product,ingadhoc\/account-payment,bmya\/odoo-addons,sysadminmatmoz\/ingadhoc,ingadhoc\/sale,adhoc-dev\/account-financial-tools,ingadhoc\/partner,adhoc-dev\/odoo-addons,dvitme\/odoo-addons,ingadhoc\/sale,HBEE\/odoo-addons,syci\/ingadhoc-odoo-addons,bmya\/odoo-addons,syci\/ingadhoc-odoo-addons,ingadhoc\/odoo-addons,maljac\/odoo-addons,adhoc-dev\/odoo-addons,ingadhoc\/odoo-addons,adhoc-dev\/odoo-addons,syci\/ingadhoc-odoo-addons,ingadhoc\/odoo-addons,ingadhoc\/account-financial-tools"} {"commit":"07f531c7e3bbc0149fad4cfda75d8803cbc48e1d","old_file":"smserver\/chatplugin.py","new_file":"smserver\/chatplugin.py","old_contents":"#!\/usr\/bin\/env python3\n# -*- coding: utf8 -*-\n\n\"\"\"\n This module add the class needed for creating custom chat command\n\n :Example:\n\n Here's a simple ChatPlugin which will send a HelloWorld on use\n\n ``\n ChatHelloWorld(ChatPlugin):\n helper = \"Display Hello World\"\n cimmand\n\n def __call__(self, serv, message):\n serv.send_message(\"Hello world\", to=\"me\")\n ``\n\"\"\"\n\n\nclass ChatPlugin(object):\n \"\"\"\n Inherit from this class to add a command in the chat.\n\n helper: Text that will be show when calling the help command\n permission: Permission needed for this command (see ability)\n room: Specify here if the command need to be execute in a room\n command: The command to use to call this function\n \"\"\"\n\n helper = \"\"\n permission = None\n room = False\n command = None\n\n def can(self, serv):\n \"\"\"\n Method call each time somenone try to run this command\n\n :param serv: The StepmaniaController instance\n :type serv: StepmaniaController\n :return: True if authorize False if not\n :rtype: bool\n \"\"\"\n\n if self.room and not serv.room:\n return False\n\n if self.permission and serv.cannot(self.permission, serv.conn.room):\n return False\n\n return True\n\n def __call__(self, serv, message):\n \"\"\"\n Action to perform when using the command\n\n :param serv: The StepmaniaController instance\n :param message: The text after the command. (Eg. \/command text)\n :type serv: StepmaniaController\n :type message: str\n :return: Nothing\n \"\"\"\n\n","new_contents":"#!\/usr\/bin\/env python3\n# -*- coding: utf8 -*-\n\n\"\"\"\n This module add the class needed for creating custom chat command\n\n :Example:\n\n Here's a simple ChatPlugin which will send a HelloWorld on use\n\n ``\n ChatHelloWorld(ChatPlugin):\n helper = \"Display Hello World\"\n command = \"hello\"\n\n def __call__(self, serv, message):\n serv.send_message(\"Hello world\", to=\"me\")\n ``\n\"\"\"\n\n\nclass ChatPlugin(object):\n \"\"\"\n Inherit from this class to add a command in the chat.\n\n helper: Text that will be show when calling the help command\n permission: Permission needed for this command (see ability)\n room: Specify here if the command need to be execute in a room\n command: The command to use to call this function\n \"\"\"\n\n helper = \"\"\n permission = None\n room = False\n command = None\n\n def can(self, serv):\n \"\"\"\n Method call each time somenone try to run this command\n\n :param serv: The StepmaniaController instance\n :type serv: StepmaniaController\n :return: True if authorize False if not\n :rtype: bool\n \"\"\"\n\n if self.room and not serv.room:\n return False\n\n if self.permission and serv.cannot(self.permission, serv.conn.room):\n return False\n\n return True\n\n def __call__(self, serv, message):\n \"\"\"\n Action to perform when using the command\n\n :param serv: The StepmaniaController instance\n :param message: The text after the command. (Eg. \/command text)\n :type serv: StepmaniaController\n :type message: str\n :return: Nothing\n \"\"\"\n\n","subject":"Correct chat plugin example in docsctring","message":"Correct chat plugin example in docsctring\n","lang":"Python","license":"mit","repos":"ningirsu\/stepmania-server,Nickito12\/stepmania-server,ningirsu\/stepmania-server,Nickito12\/stepmania-server"} {"commit":"83292a4b6f6bec00b20c623fa6f44e15aa82cd2a","old_file":"runtests.py","new_file":"runtests.py","old_contents":"#!\/usr\/bin\/env python\nimport sys\nfrom os.path import dirname, abspath\n\nimport django\nfrom django.conf import settings\n\n\nif len(sys.argv) > 1 and 'postgres' in sys.argv:\n sys.argv.remove('postgres')\n db_engine = 'django.db.backends.postgresql_psycopg2'\n db_name = 'test_main'\nelse:\n db_engine = 'django.db.backends.sqlite3'\n db_name = ''\n\nif not settings.configured:\n settings.configure(\n DATABASES=dict(default=dict(ENGINE=db_engine, NAME=db_name)),\n INSTALLED_APPS = [\n 'django.contrib.contenttypes',\n 'genericm2m',\n 'genericm2m.genericm2m_tests',\n ],\n )\n\nfrom django.test.utils import get_runner\n\n\ndef runtests(*test_args):\n if not test_args:\n if sys.version_info[0] > 2:\n test_args = ['genericm2m.genericm2m_tests']\n else:\n test_args = [\"genericm2m_tests\"]\n parent = dirname(abspath(__file__))\n sys.path.insert(0, parent)\n TestRunner = get_runner(settings)\n test_runner = TestRunner(verbosity=1, interactive=True)\n failures = test_runner.run_tests(test_args)\n sys.exit(failures)\n\nif __name__ == '__main__':\n runtests(*sys.argv[1:])\n","new_contents":"#!\/usr\/bin\/env python\nimport sys\nfrom os.path import dirname, abspath\n\nimport django\nfrom django.conf import settings\n\n\nif len(sys.argv) > 1 and 'postgres' in sys.argv:\n sys.argv.remove('postgres')\n db_engine = 'django.db.backends.postgresql_psycopg2'\n db_name = 'test_main'\nelse:\n db_engine = 'django.db.backends.sqlite3'\n db_name = ''\n\nif not settings.configured:\n settings.configure(\n DATABASES=dict(default=dict(ENGINE=db_engine, NAME=db_name)),\n INSTALLED_APPS = [\n 'django.contrib.contenttypes',\n 'genericm2m',\n 'genericm2m.genericm2m_tests',\n ],\n MIDDLEWARE_CLASSES = (),\n )\n\nfrom django.test.utils import get_runner\n\ndjango.setup()\n\ndef runtests(*test_args):\n if not test_args:\n if sys.version_info[0] > 2:\n test_args = ['genericm2m.genericm2m_tests']\n else:\n test_args = [\"genericm2m_tests\"]\n parent = dirname(abspath(__file__))\n sys.path.insert(0, parent)\n TestRunner = get_runner(settings)\n test_runner = TestRunner(verbosity=1, interactive=True)\n failures = test_runner.run_tests(test_args)\n sys.exit(failures)\n\nif __name__ == '__main__':\n runtests(*sys.argv[1:])\n","subject":"Fix \"AppRegistryNotReady: Models aren't loaded yet\"","message":"Fix \"AppRegistryNotReady: Models aren't loaded yet\"\n","lang":"Python","license":"mit","repos":"coleifer\/django-generic-m2m,coleifer\/django-generic-m2m,coleifer\/django-generic-m2m"} {"commit":"e77042c914b9725da0fef7e56ede12635c1a876b","old_file":"s3s3\/api.py","new_file":"s3s3\/api.py","old_contents":"\"\"\"\nThe API for s3s3.\n\"\"\"\nimport tempfile\n\nfrom boto.s3.connection import S3Connection\n\n\ndef create_connection(connection_args):\n connection_args = connection_args.copy()\n connection_args.pop('bucket_name')\n return S3Connection(**connection_args)\n\n\ndef upload(source_key, dest_keys):\n \"\"\"\n `source_key` The source boto s3 key.\n `dest_keys` The destination boto s3 keys.\n \"\"\"\n # Use the same name if no destination key is passed.\n if not dest_key:\n dest_key = source_key\n with tempfile.NamedTemporaryFile() as data:\n source_key.get_contents_to_file(data)\n for dest_key in dest_keys:\n dest_key.set_contents_from_filename(data.name)\n","new_contents":"\"\"\"\nThe API for s3s3.\n\"\"\"\nimport tempfile\n\nfrom boto.s3.connection import S3Connection\n\n\ndef create_connection(connection_args):\n connection_args = connection_args.copy()\n connection_args.pop('bucket_name')\n return S3Connection(**connection_args)\n\n\ndef upload(source_key, dest_keys):\n \"\"\"\n `source_key` The source boto s3 key.\n `dest_keys` A list of the destination boto s3 keys.\n \"\"\"\n # Use the same name if no destination key is passed.\n if not dest_keys or not source_key:\n raise Exception(\n 'The source_key and dest_keys parameters are required.')\n with tempfile.NamedTemporaryFile() as data:\n source_key.get_contents_to_file(data)\n for dest_key in dest_keys:\n dest_key.set_contents_from_filename(data.name)\n","subject":"Fix typo. dest_key => dest_keys.","message":"Fix typo. dest_key => dest_keys.\n\n\tmodified: s3s3\/api.py\n","lang":"Python","license":"mit","repos":"lsst-sqre\/s3s3,lsst-sqre\/s3-glacier"} {"commit":"ada7e2d2b98664fd6c481c4279677a4292e5bfef","old_file":"openedx\/features\/idea\/api_views.py","new_file":"openedx\/features\/idea\/api_views.py","old_contents":"from django.http import JsonResponse\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import status\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.views import APIView\n\nfrom openedx.features.idea.models import Idea\n\n\nclass FavoriteAPIView(APIView):\n \"\"\"\n FavoriteAPIView is used to toggle favorite idea for the user\n \"\"\"\n authentication_classes = (SessionAuthentication, BasicAuthentication)\n permission_classes = (IsAuthenticated,)\n\n def post(self, request, idea_id):\n response = {'message': 'Idea is added to favorites', 'is_idea_favorite': True}\n toggle_status = status.HTTP_201_CREATED\n user = request.user\n idea = get_object_or_404(Idea, pk=idea_id)\n toggle_favorite_status = idea.toggle_favorite(user)\n\n if not toggle_favorite_status:\n response['is_idea_favorite'] = False\n response['message'] = 'Idea is removed from favorites'\n toggle_status = status.HTTP_200_OK\n\n response['favorite_count'] = idea.favorites.count()\n return JsonResponse(response, status=toggle_status)\n","new_contents":"from django.http import JsonResponse\nfrom django.shortcuts import get_object_or_404\nfrom edx_rest_framework_extensions.auth.session.authentication import SessionAuthenticationAllowInactiveUser\nfrom rest_framework import status\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.views import APIView\n\nfrom openedx.features.idea.models import Idea\n\n\nclass FavoriteAPIView(APIView):\n \"\"\"\n FavoriteAPIView is used to toggle favorite idea for the user\n \"\"\"\n authentication_classes = (SessionAuthenticationAllowInactiveUser,)\n permission_classes = (IsAuthenticated,)\n\n def post(self, request, idea_id):\n response = {'message': 'Idea is added to favorites', 'is_idea_favorite': True}\n toggle_status = status.HTTP_201_CREATED\n user = request.user\n idea = get_object_or_404(Idea, pk=idea_id)\n toggle_favorite_status = idea.toggle_favorite(user)\n\n if not toggle_favorite_status:\n response['is_idea_favorite'] = False\n response['message'] = 'Idea is removed from favorites'\n toggle_status = status.HTTP_200_OK\n\n response['favorite_count'] = idea.favorites.count()\n return JsonResponse(response, status=toggle_status)\n","subject":"Change authentication classes to cater inactive users","message":"[LP-1965] Change authentication classes to cater inactive users\n","lang":"Python","license":"agpl-3.0","repos":"philanthropy-u\/edx-platform,philanthropy-u\/edx-platform,philanthropy-u\/edx-platform,philanthropy-u\/edx-platform"} {"commit":"d6782066e3ed3f00e3c8dcffe2ffd0b9bad18d17","old_file":"slave\/skia_slave_scripts\/render_pdfs.py","new_file":"slave\/skia_slave_scripts\/render_pdfs.py","old_contents":"#!\/usr\/bin\/env python\n# Copyright (c) 2013 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\n\"\"\" Run the Skia render_pdfs executable. \"\"\"\n\n\nfrom build_step import BuildStep, BuildStepWarning\nimport sys\n\n\nclass RenderPdfs(BuildStep):\n def _Run(self):\n # Skip this step for now, since the new SKPs are causing it to crash.\n raise BuildStepWarning('Skipping this step since it is crashing.')\n #self.RunFlavoredCmd('render_pdfs', [self._device_dirs.SKPDir()])\n\nif '__main__' == __name__:\n sys.exit(BuildStep.RunBuildStep(RenderPdfs))\n","new_contents":"#!\/usr\/bin\/env python\n# Copyright (c) 2013 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\n\"\"\" Run the Skia render_pdfs executable. \"\"\"\n\n\nfrom build_step import BuildStep\nimport sys\n\n\nclass RenderPdfs(BuildStep):\n def _Run(self):\n self.RunFlavoredCmd('render_pdfs', [self._device_dirs.SKPDir()])\n\nif '__main__' == __name__:\n sys.exit(BuildStep.RunBuildStep(RenderPdfs))\n","subject":"Revert \"Skip RenderPdfs until the crash is fixed\"","message":"Revert \"Skip RenderPdfs until the crash is fixed\"\n\nThis reverts commit fd03af0fbcb5f1b3656bcc78d934c560816d6810.\n\nhttps:\/\/codereview.chromium.org\/15002002\/ fixes the crash.\n\nR=borenet@google.com\n\nReview URL: https:\/\/codereview.chromium.org\/14577010\n\ngit-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9019 2bbb7eff-a529-9590-31e7-b0007b416f81\n","lang":"Python","license":"bsd-3-clause","repos":"Tiger66639\/skia-buildbot,google\/skia-buildbot,google\/skia-buildbot,google\/skia-buildbot,Tiger66639\/skia-buildbot,Tiger66639\/skia-buildbot,Tiger66639\/skia-buildbot,Tiger66639\/skia-buildbot,google\/skia-buildbot,google\/skia-buildbot,Tiger66639\/skia-buildbot,google\/skia-buildbot,google\/skia-buildbot,Tiger66639\/skia-buildbot,google\/skia-buildbot"} {"commit":"bf91e50b02ff8ef89e660e3c853cc2f30646f32d","old_file":"bash_runner\/tasks.py","new_file":"bash_runner\/tasks.py","old_contents":"\"\"\"\nCloudify plugin for running a simple bash script.\n\nOperations:\n start: Run a script\n\"\"\"\n\nfrom celery import task\nfrom cosmo.events import send_event as send_riemann_event\nfrom cloudify.utils import get_local_ip\n\n\nget_ip = get_local_ip\nsend_event = send_riemann_event\n\n\n@task\ndef start(__cloudify_id, port=8080, **kwargs):\n with open('\/home\/ubuntu\/hello', 'w') as f:\n print >> f, 'HELLO BASH! %s' % port\n send_event(__cloudify_id, get_ip(), \"hello_bash status\", \"state\", \"running\")\n","new_contents":"\"\"\"\nCloudify plugin for running a simple bash script.\n\nOperations:\n start: Run a script\n\"\"\"\n\nfrom celery import task\nfrom cosmo.events import send_event as send_riemann_event\nfrom cloudify.utils import get_local_ip\n\n\nget_ip = get_local_ip\nsend_event = send_riemann_event\n\n\n@task\ndef start(__cloudify_id, port=8080, **kwargs):\n with open('\/home\/ubuntu\/hello', 'w') as f:\n print >> f, 'HELLO BASH! %s' % port\n send_event(__cloudify_id, get_ip(), \"bash_runner status\", \"state\", \"running\")\n","subject":"Change the status string in riemann","message":"Change the status string in riemann\n","lang":"Python","license":"apache-2.0","repos":"rantav\/cosmo-plugin-bash-runner"} {"commit":"c568cf4b1be5e38b92f7d3a9131e67ff9eff764e","old_file":"lib\/ctf_gameserver\/lib\/helper.py","new_file":"lib\/ctf_gameserver\/lib\/helper.py","old_contents":"#!\/usr\/bin\/python3\n# -*- coding: utf-8 -*-\n\ndef convert_arg_line_to_args(arg_line):\n \"\"\"argparse helper for splitting input from config\n\n Allows comment lines in configfiles and allows both argument and\n value on the same line\n \"\"\"\n if arg_line.strip().startswith('#'):\n return []\n else:\n return arg_line.split()\n","new_contents":"#!\/usr\/bin\/python3\n# -*- coding: utf-8 -*-\n\nimport shlex\n\ndef convert_arg_line_to_args(arg_line):\n \"\"\"argparse helper for splitting input from config\n\n Allows comment lines in configfiles and allows both argument and\n value on the same line\n \"\"\"\n return shlex.split(arg_line, comments=True)\n","subject":"Improve config argument splitting to allow quoted spaces","message":"Improve config argument splitting to allow quoted spaces\n","lang":"Python","license":"isc","repos":"fausecteam\/ctf-gameserver,fausecteam\/ctf-gameserver,fausecteam\/ctf-gameserver,fausecteam\/ctf-gameserver,fausecteam\/ctf-gameserver"} {"commit":"a234b8dfc45d9e08a452ccc4f275283eb1eb5485","old_file":"dataactbroker\/scripts\/loadFSRS.py","new_file":"dataactbroker\/scripts\/loadFSRS.py","old_contents":"import logging\nimport sys\n\nfrom dataactcore.models.baseInterface import databaseSession\nfrom dataactbroker.fsrs import (\n configValid, fetchAndReplaceBatch, GRANT, PROCUREMENT)\n\n\nlogger = logging.getLogger(__name__)\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n with databaseSession() as sess:\n if not configValid():\n logger.error(\"No config for broker\/fsrs\/[service]\/wsdl\")\n sys.exit(1)\n else:\n procs = fetchAndReplaceBatch(sess, PROCUREMENT)\n grants = fetchAndReplaceBatch(sess, GRANT)\n awards = procs + grants\n numSubAwards = sum(len(a.subawards) for a in awards)\n logger.info(\"Inserted\/Updated %s awards, %s subawards\",\n len(awards), numSubAwards)\n","new_contents":"import logging\nimport sys\n\nfrom dataactcore.interfaces.db import databaseSession\nfrom dataactbroker.fsrs import (\n configValid, fetchAndReplaceBatch, GRANT, PROCUREMENT)\n\n\nlogger = logging.getLogger(__name__)\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n with databaseSession() as sess:\n if not configValid():\n logger.error(\"No config for broker\/fsrs\/[service]\/wsdl\")\n sys.exit(1)\n else:\n procs = fetchAndReplaceBatch(sess, PROCUREMENT)\n grants = fetchAndReplaceBatch(sess, GRANT)\n awards = procs + grants\n numSubAwards = sum(len(a.subawards) for a in awards)\n logger.info(\"Inserted\/Updated %s awards, %s subawards\",\n len(awards), numSubAwards)\n","subject":"Switch to using dbSession in db.py instead of baseInterface.py","message":"Switch to using dbSession in db.py instead of baseInterface.py\n\nThis is another file that should have been included in PR #272,\nwhere we transitioned all existing non-Flask db access to a\ndb connection using the new contextmanager. Originally missed\nthis one because it *is* using a contextmanager, but it's using\none in the deprecated baseInterface.py instead of the newer db.py.\n","lang":"Python","license":"cc0-1.0","repos":"fedspendingtransparency\/data-act-broker-backend,chambers-brian\/SIG_Digital-Strategy_SI_ODP_Backend,fedspendingtransparency\/data-act-broker-backend,chambers-brian\/SIG_Digital-Strategy_SI_ODP_Backend"} {"commit":"0022726e9f2d122ff84eb19ed2807649ab96f931","old_file":"deployment\/cfn\/utils\/constants.py","new_file":"deployment\/cfn\/utils\/constants.py","old_contents":"EC2_INSTANCE_TYPES = [\n 't2.micro',\n 't2.small',\n 't2.medium',\n 't2.large'\n]\n\nRDS_INSTANCE_TYPES = [\n 'db.t2.micro',\n 'db.t2.small',\n 'db.t2.medium',\n 'db.t2.large'\n]\n\nALLOW_ALL_CIDR = '0.0.0.0\/0'\nVPC_CIDR = '10.0.0.0\/16'\n\nHTTP = 80\nHTTPS = 443\nPOSTGRESQL = 5432\nSSH = 22\n\nAMAZON_ACCOUNT_ID = 'amazon'\nAMAZON_S3_VPC_ENDPOINT = 'com.amazonaws.us-east-1.s3'\n\nCANONICAL_ACCOUNT_ID = '099720109477'\n","new_contents":"EC2_INSTANCE_TYPES = [\n 't2.micro',\n 't2.small',\n 't2.medium',\n 't2.large',\n 'm3.medium'\n]\n\nRDS_INSTANCE_TYPES = [\n 'db.t2.micro',\n 'db.t2.small',\n 'db.t2.medium',\n 'db.t2.large'\n]\n\nALLOW_ALL_CIDR = '0.0.0.0\/0'\nVPC_CIDR = '10.0.0.0\/16'\n\nHTTP = 80\nHTTPS = 443\nPOSTGRESQL = 5432\nSSH = 22\n\nAMAZON_ACCOUNT_ID = 'amazon'\nAMAZON_S3_VPC_ENDPOINT = 'com.amazonaws.us-east-1.s3'\n\nCANONICAL_ACCOUNT_ID = '099720109477'\n","subject":"Add m3.medium to EC2 instance types","message":"Add m3.medium to EC2 instance types\n\nThis is the lowest `m3` family instance type with ephemeral storage.","lang":"Python","license":"apache-2.0","repos":"azavea\/raster-foundry,aaronxsu\/raster-foundry,kdeloach\/raster-foundry,kdeloach\/raster-foundry,azavea\/raster-foundry,azavea\/raster-foundry,aaronxsu\/raster-foundry,azavea\/raster-foundry,kdeloach\/raster-foundry,raster-foundry\/raster-foundry,azavea\/raster-foundry,raster-foundry\/raster-foundry,kdeloach\/raster-foundry,kdeloach\/raster-foundry,aaronxsu\/raster-foundry,raster-foundry\/raster-foundry,aaronxsu\/raster-foundry"} {"commit":"4d5d4665f2b46e12618b7762246d84884447e99e","old_file":"redash\/cli\/organization.py","new_file":"redash\/cli\/organization.py","old_contents":"from flask_script import Manager\nfrom redash import models\n\nmanager = Manager(help=\"Organization management commands.\")\n\n\n@manager.option('domains', help=\"comma separated list of domains to allow\")\ndef set_google_apps_domains(domains):\n organization = models.Organization.select().first()\n\n organization.settings[models.Organization.SETTING_GOOGLE_APPS_DOMAINS] = domains.split(',')\n organization.save()\n\n print \"Updated list of allowed domains to: {}\".format(organization.google_apps_domains)\n\n\n@manager.command\ndef show_google_apps_domains():\n organization = models.Organization.select().first()\n print \"Current list of Google Apps domains: {}\".format(organization.google_apps_domains)\n","new_contents":"from flask_script import Manager\nfrom redash import models\n\nmanager = Manager(help=\"Organization management commands.\")\n\n\n@manager.option('domains', help=\"comma separated list of domains to allow\")\ndef set_google_apps_domains(domains):\n organization = models.Organization.select().first()\n\n organization.settings[models.Organization.SETTING_GOOGLE_APPS_DOMAINS] = domains.split(',')\n organization.save()\n\n print \"Updated list of allowed domains to: {}\".format(organization.google_apps_domains)\n\n\n@manager.command\ndef show_google_apps_domains():\n organization = models.Organization.select().first()\n print \"Current list of Google Apps domains: {}\".format(organization.google_apps_domains)\n\n\n@manager.command\ndef list():\n \"\"\"List all organizations\"\"\"\n orgs = models.Organization.select()\n for i, org in enumerate(orgs):\n if i > 0:\n print \"-\" * 20\n\n print \"Id: {}\\nName: {}\\nSlug: {}\".format(org.id, org.name, org.slug)\n","subject":"Add 'manage.py org list' command","message":"Add 'manage.py org list' command\n\n'org list' simply prints out the organizations.\n","lang":"Python","license":"bsd-2-clause","repos":"pubnative\/redash,pubnative\/redash,pubnative\/redash,pubnative\/redash,pubnative\/redash"} {"commit":"c23cd25247974abc85c66451737f4de8d8b19d1b","old_file":"lib\/rapidsms\/backends\/backend.py","new_file":"lib\/rapidsms\/backends\/backend.py","old_contents":"#!\/usr\/bin\/env python\n# vim: ai ts=4 sts=4 et sw=4\n\n\nclass Backend(object):\n \n def log(self, level, message):\n self.router.log(level, message)\n\n def start(self):\n raise NotImplementedError\n \n def stop(self):\n raise NotImplementedError\n \n def send(self):\n raise NotImplementedError\n \n def receive(self):\n raise NotImplementedError\n","new_contents":"#!\/usr\/bin\/env python\n# vim: ai ts=4 sts=4 et sw=4\n\nclass Backend(object):\n def __init__ (self, router):\n self.router = router\n \n def log(self, level, message):\n self.router.log(level, message)\n\n def start(self):\n raise NotImplementedError\n \n def stop(self):\n raise NotImplementedError\n \n def send(self):\n raise NotImplementedError\n \n def receive(self):\n raise NotImplementedError\n","subject":"Add a constructor method for Backend","message":"Add a constructor method for Backend\n","lang":"Python","license":"bsd-3-clause","repos":"dimagi\/rapidsms,ehealthafrica-ci\/rapidsms,eHealthAfrica\/rapidsms,ken-muturi\/rapidsms,lsgunth\/rapidsms,catalpainternational\/rapidsms,unicefuganda\/edtrac,catalpainternational\/rapidsms,eHealthAfrica\/rapidsms,ken-muturi\/rapidsms,ken-muturi\/rapidsms,lsgunth\/rapidsms,unicefuganda\/edtrac,lsgunth\/rapidsms,ehealthafrica-ci\/rapidsms,unicefuganda\/edtrac,peterayeni\/rapidsms,caktus\/rapidsms,lsgunth\/rapidsms,caktus\/rapidsms,peterayeni\/rapidsms,peterayeni\/rapidsms,dimagi\/rapidsms,eHealthAfrica\/rapidsms,catalpainternational\/rapidsms,rapidsms\/rapidsms-core-dev,peterayeni\/rapidsms,rapidsms\/rapidsms-core-dev,catalpainternational\/rapidsms,ehealthafrica-ci\/rapidsms,dimagi\/rapidsms-core-dev,caktus\/rapidsms,dimagi\/rapidsms-core-dev"} {"commit":"7a37e3afa29410636c75408bc649e70c519e07f1","old_file":"test\/user_profile_test.py","new_file":"test\/user_profile_test.py","old_contents":"import json\n\nfrom pymessenger.user_profile import UserProfileApi\nfrom test_env import *\n\nupa = UserProfileApi(PAGE_ACCESS_TOKEN, app_secret=APP_SECRET)\n\ndef test_fields_blank():\n user_profile = upa.get(TEST_USER_ID)\n assert user_profile is not None\n\ndef test_fields():\n fields = ['first_name', 'last_name']\n user_profile = upa.get(TEST_USER_ID, fields=fields)\n assert user_profile is not None\n assert len(user_profile.keys()) == len(fields)\n","new_contents":"import json\nimport sys, os\nsys.path.append(os.path.realpath(os.path.dirname(__file__)+\"\/..\"))\n\nfrom pymessenger.user_profile import UserProfileApi\n\nTOKEN = os.environ.get('TOKEN')\nAPP_SECRET = os.environ.get('APP_SECRET')\nTEST_USER_ID = os.environ.get('RECIPIENT_ID')\n\nupa = UserProfileApi(TOKEN, app_secret=APP_SECRET)\n\ndef test_fields_blank():\n user_profile = upa.get(TEST_USER_ID)\n assert user_profile is not None\n\ndef test_fields():\n fields = ['first_name', 'last_name']\n user_profile = upa.get(TEST_USER_ID, fields=fields)\n assert user_profile is not None\n assert len(user_profile.keys()) == len(fields)\n","subject":"Fix user profile test to include same environment variables","message":"Fix user profile test to include same environment variables\n","lang":"Python","license":"mit","repos":"karlinnolabs\/pymessenger,Cretezy\/pymessenger2,davidchua\/pymessenger"} {"commit":"2fec4b3ffa1619f81088383c9f565b51f6171fd6","old_file":"seaborn\/miscplot.py","new_file":"seaborn\/miscplot.py","old_contents":"from __future__ import division\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n\n__all__ = [\"palplot\", \"dogplot\"]\n\n\ndef palplot(pal, size=1):\n \"\"\"Plot the values in a color palette as a horizontal array.\n\n Parameters\n ----------\n pal : sequence of matplotlib colors\n colors, i.e. as returned by seaborn.color_palette()\n size :\n scaling factor for size of plot\n\n \"\"\"\n n = len(pal)\n f, ax = plt.subplots(1, 1, figsize=(n * size, size))\n ax.imshow(np.arange(n).reshape(1, n),\n cmap=mpl.colors.ListedColormap(list(pal)),\n interpolation=\"nearest\", aspect=\"auto\")\n ax.set_xticks(np.arange(n) - .5)\n ax.set_yticks([-.5, .5])\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n\n\ndef dogplot():\n \"\"\"Who's a good boy?\"\"\"\n try:\n from urllib.request import urlopen\n except ImportError:\n from urllib2 import urlopen\n from io import BytesIO\n\n url = \"https:\/\/github.com\/mwaskom\/seaborn-data\/raw\/master\/png\/img1.png\"\n data = BytesIO(urlopen(url).read())\n img = plt.imread(data)\n f, ax = plt.subplots(figsize=(5, 5), dpi=100)\n f.subplots_adjust(0, 0, 1, 1)\n ax.imshow(img)\n ax.set_axis_off()\n","new_contents":"from __future__ import division\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n\n__all__ = [\"palplot\", \"dogplot\"]\n\n\ndef palplot(pal, size=1):\n \"\"\"Plot the values in a color palette as a horizontal array.\n\n Parameters\n ----------\n pal : sequence of matplotlib colors\n colors, i.e. as returned by seaborn.color_palette()\n size :\n scaling factor for size of plot\n\n \"\"\"\n n = len(pal)\n f, ax = plt.subplots(1, 1, figsize=(n * size, size))\n ax.imshow(np.arange(n).reshape(1, n),\n cmap=mpl.colors.ListedColormap(list(pal)),\n interpolation=\"nearest\", aspect=\"auto\")\n ax.set_xticks(np.arange(n) - .5)\n ax.set_yticks([-.5, .5])\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n\n\ndef dogplot():\n \"\"\"Who's a good boy?\"\"\"\n try:\n from urllib.request import urlopen\n except ImportError:\n from urllib2 import urlopen\n from io import BytesIO\n\n url = \"https:\/\/github.com\/mwaskom\/seaborn-data\/raw\/master\/png\/img{}.png\"\n pic = np.random.randint(2, 7)\n data = BytesIO(urlopen(url.format(pic)).read())\n img = plt.imread(data)\n f, ax = plt.subplots(figsize=(5, 5), dpi=100)\n f.subplots_adjust(0, 0, 1, 1)\n ax.imshow(img)\n ax.set_axis_off()\n","subject":"Update to reflect new example data","message":"Update to reflect new example data\n","lang":"Python","license":"bsd-3-clause","repos":"arokem\/seaborn,mwaskom\/seaborn,anntzer\/seaborn,arokem\/seaborn,mwaskom\/seaborn,anntzer\/seaborn"} {"commit":"694408d7f96c83318bbfc0d88be2a99a116deb90","old_file":"select2\/__init__.py","new_file":"select2\/__init__.py","old_contents":"VERSION = (0, 7)\n__version__ = '.'.join(map(str, VERSION))\nDATE = \"2014-06-17\"","new_contents":"VERSION = (0, 8)\n__version__ = '.'.join(map(str, VERSION))\nDATE = \"2014-06-17\"","subject":"Fix format syntax with python 2.6 - upgrade version","message":"Fix format syntax with python 2.6 - upgrade version\n","lang":"Python","license":"mit","repos":"20tab\/twentytab-select2,20tab\/twentytab-select2,20tab\/twentytab-select2"} {"commit":"a4c5e9a970a297d59000468dde8423fa9db00c0f","old_file":"packs\/fixtures\/actions\/scripts\/streamwriter-script.py","new_file":"packs\/fixtures\/actions\/scripts\/streamwriter-script.py","old_contents":"#!\/usr\/bin\/env python\n\nimport argparse\nimport sys\nimport ast\n\nfrom lib.exceptions import CustomException\n\n\nclass StreamWriter(object):\n\n def run(self, stream):\n if stream.upper() == 'STDOUT':\n sys.stdout.write('STREAM IS STDOUT.')\n return stream\n\n if stream.upper() == 'STDERR':\n sys.stderr.write('STREAM IS STDERR.')\n return stream\n\n raise CustomException('Invalid stream specified.')\n\n\ndef main(args):\n stream = args.stream\n writer = StreamWriter()\n stream = writer.run(stream)\n str_arg = args.str_arg\n int_arg = args.int_arg\n obj_arg = args.obj_arg\n if str_arg:\n sys.stdout.write(' STR: %s' % str_arg)\n if int_arg:\n sys.stdout.write(' INT: %d' % int_arg)\n if obj_arg:\n sys.stdout.write(' OBJ: %s' % obj_arg)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--stream', help='Stream.', required=True)\n parser.add_argument('--str_arg', help='Some string arg.')\n parser.add_argument('--int_arg', help='Some int arg.', type=float)\n parser.add_argument('--obj_arg', help='Some dict arg.', type=ast.literal_eval)\n args = parser.parse_args()\n main(args)\n","new_contents":"#!\/usr\/bin\/env python\n\nimport argparse\nimport sys\nimport ast\nimport re\n\nfrom lib.exceptions import CustomException\n\n\nclass StreamWriter(object):\n\n def run(self, stream):\n if stream.upper() == 'STDOUT':\n sys.stdout.write('STREAM IS STDOUT.')\n return stream\n\n if stream.upper() == 'STDERR':\n sys.stderr.write('STREAM IS STDERR.')\n return stream\n\n raise CustomException('Invalid stream specified.')\n\n\ndef main(args):\n stream = args.stream\n writer = StreamWriter()\n stream = writer.run(stream)\n\n str_arg = args.str_arg\n int_arg = args.int_arg\n obj_arg = args.obj_arg\n\n if str_arg:\n sys.stdout.write(' STR: %s' % str_arg)\n if int_arg:\n sys.stdout.write(' INT: %d' % int_arg)\n\n if obj_arg:\n # Remove any u'' so it works consistently under Python 2 and 3.x\n obj_arg_str = str(obj_arg)\n value = re.sub(\"u'(.*?)'\", r\"'\\1'\", obj_arg_str)\n sys.stdout.write(' OBJ: %s' % value)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--stream', help='Stream.', required=True)\n parser.add_argument('--str_arg', help='Some string arg.')\n parser.add_argument('--int_arg', help='Some int arg.', type=float)\n parser.add_argument('--obj_arg', help='Some dict arg.', type=ast.literal_eval)\n args = parser.parse_args()\n main(args)\n","subject":"Fix streamwriter action so it doesn't include \"u\" type prefix in the object result.","message":"Fix streamwriter action so it doesn't include \"u\" type prefix in the\nobject result.\n\nThis way it works consistently and correctly under Python 2 and Python\n3.\n","lang":"Python","license":"apache-2.0","repos":"StackStorm\/st2tests,StackStorm\/st2tests,StackStorm\/st2tests"} {"commit":"9fba6f871068b0d40b71b9de4f69ac59bc33f567","old_file":"tests\/test_CheckButton.py","new_file":"tests\/test_CheckButton.py","old_contents":"#!\/usr\/bin\/env python\nimport unittest\n\nfrom kiwi.ui.widgets.checkbutton import ProxyCheckButton\n\n\nclass CheckButtonTest(unittest.TestCase):\n def testForBool(self):\n myChkBtn = ProxyCheckButton()\n # PyGObject bug, we cannot set bool in the constructor with\n # introspection\n #self.assertEqual(myChkBtn.props.data_type, 'bool')\n\n # this test doens't work... maybe be a pygtk bug\n #self.assertRaises(TypeError, myChkBtn.set_property, 'data-type', str)\n\nif __name__ == '__main__':\n unittest.main()\n","new_contents":"#!\/usr\/bin\/env python\nimport unittest\n\nimport gtk\n\nfrom kiwi.ui.widgets.checkbutton import ProxyCheckButton\n\n\nclass CheckButtonTest(unittest.TestCase):\n def testForBool(self):\n myChkBtn = ProxyCheckButton()\n assert isinstance(myChkBtn, gtk.CheckButton)\n # PyGObject bug, we cannot set bool in the constructor with\n # introspection\n #self.assertEqual(myChkBtn.props.data_type, 'bool')\n\n # this test doens't work... maybe be a pygtk bug\n #self.assertRaises(TypeError, myChkBtn.set_property, 'data-type', str)\n\nif __name__ == '__main__':\n unittest.main()\n","subject":"Add a silly assert to avoid a pyflakes warning","message":"Add a silly assert to avoid a pyflakes warning","lang":"Python","license":"lgpl-2.1","repos":"stoq\/kiwi"} {"commit":"080cda37b93010232481c8fd6090a3909a086fe4","old_file":"tests\/test_mdx_embedly.py","new_file":"tests\/test_mdx_embedly.py","old_contents":"import markdown\nfrom mdx_embedly import EmbedlyExtension\n\n\ndef test_embedly():\n s = \"[https:\/\/github.com\/yymm:embed]\"\n expected = \"\"\"\n

    \nembed.ly<\/a>\n