commit
stringlengths
40
40
old_file
stringlengths
5
117
new_file
stringlengths
5
117
old_contents
stringlengths
0
1.93k
new_contents
stringlengths
19
3.3k
subject
stringlengths
17
320
message
stringlengths
18
3.28k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
42.4k
completion
stringlengths
152
6.66k
prompt
stringlengths
21
3.65k
cb97f453284658da56d12ab696ef6b7d7991c727
dipy/io/tests/test_csareader.py
dipy/io/tests/test_csareader.py
""" Testing Siemens CSA header reader """ import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing imp...
""" Testing Siemens CSA header reader """ import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing imp...
TEST - add test for value
TEST - add test for value
Python
bsd-3-clause
jyeatman/dipy,beni55/dipy,samuelstjean/dipy,FrancoisRheaultUS/dipy,demianw/dipy,demianw/dipy,nilgoyyou/dipy,jyeatman/dipy,Messaoud-Boudjada/dipy,maurozucchelli/dipy,Messaoud-Boudjada/dipy,StongeEtienne/dipy,villalonreina/dipy,JohnGriffiths/dipy,rfdougherty/dipy,villalonreina/dipy,sinkpoint/dipy,JohnGriffiths/dipy,Franc...
<REPLACE_OLD> print csa_info <REPLACE_NEW> yield assert_equal(tags['NumberOfImagesInMosaic']['value'], '48') <REPLACE_END> <|endoftext|> """ Testing Siemens CSA header reader """ import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools im...
TEST - add test for value """ Testing Siemens CSA header reader """ import os from os.path import join as pjoin import numpy as np import dipy.io.csareader as csa from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_e...
c541e85f8b1dccaabd047027e89791d807550ee5
fade/config.py
fade/config.py
#!/usr/bin/env python """ See LICENSE.txt file for copyright and license details. """ import os basedir = os.path.abspath(os.path.dirname(__file__)) WTF_CSRF_ENABLED = True SECRET_KEY = '3124534675689780' # TODO: switch this to postgresql SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db') ...
#!/usr/bin/env python """ See LICENSE.txt file for copyright and license details. """ import os basedir = os.path.abspath(os.path.dirname(__file__)) WTF_CSRF_ENABLED = True SECRET_KEY = '3124534675689780' dbuser = 'rockwolf' dbpass = '' dbhost = 'testdb' dbname = 'finance' SQLALCHEMY_DATABASE_URI = 'postgresql:...
Switch database connection string to pg
Switch database connection string to pg
Python
bsd-3-clause
rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python
<REPLACE_OLD> '3124534675689780' # TODO: switch this to postgresql SQLALCHEMY_DATABASE_URI <REPLACE_NEW> '3124534675689780' dbuser <REPLACE_END> <REPLACE_OLD> 'sqlite:///' <REPLACE_NEW> 'rockwolf' dbpass = '' dbhost = 'testdb' dbname = 'finance' SQLALCHEMY_DATABASE_URI = 'postgresql://' <REPLACE_END> ...
Switch database connection string to pg #!/usr/bin/env python """ See LICENSE.txt file for copyright and license details. """ import os basedir = os.path.abspath(os.path.dirname(__file__)) WTF_CSRF_ENABLED = True SECRET_KEY = '3124534675689780' # TODO: switch this to postgresql SQLALCHEMY_DATABASE_URI = 'sqlite...
3875b14e6c94c4a6a7ad47a3eb55cae62096d0e4
agateremote/table_remote.py
agateremote/table_remote.py
#!/usr/bin/env python """ This module contains the Remote extension to :class:`Table <agate.table.Table>`. """ import agate import requests import six def from_url(cls, url, callback=agate.Table.from_csv, binary=False, **kwargs): """ Download a remote file and pass it to a :class:`.Table` parser. :param...
#!/usr/bin/env python """ This module contains the Remote extension to :class:`Table <agate.table.Table>`. """ import agate import requests import six def from_url(cls, url, callback=agate.Table.from_csv, requests_encoding=None, binary=False, **kwargs): """ Download a remote file and pass it to a :class:`.Ta...
Add 'requests_encoding' parameter Allows user to override Requests' 'educated guess' about encoding of a response. Useful when loading a remote CSV that has a BOM that has been served with a 'text/csv' content-type, which Requests guesses needs a 'ISO-8859-1' encoding.
Add 'requests_encoding' parameter Allows user to override Requests' 'educated guess' about encoding of a response. Useful when loading a remote CSV that has a BOM that has been served with a 'text/csv' content-type, which Requests guesses needs a 'ISO-8859-1' encoding.
Python
mit
wireservice/agate-remote
<INSERT> requests_encoding=None, <INSERT_END> <INSERT> :param requests_encoding: An encoding to pass to requests for use when decoding the response content. (e.g. force use of 'utf-8-sig' when CSV has a BOM). <INSERT_END> <INSERT> requests_encoding: r.encoding = requests_encoding if <IN...
Add 'requests_encoding' parameter Allows user to override Requests' 'educated guess' about encoding of a response. Useful when loading a remote CSV that has a BOM that has been served with a 'text/csv' content-type, which Requests guesses needs a 'ISO-8859-1' encoding. #!/usr/bin/env python """ This module contains t...
6a830973fa8f29278015d55819dcbd87f0472ac9
post_office/test_urls.py
post_office/test_urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls), name='admin'), )
from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls), name='admin'), ]
Fix Django 1.10 url patterns warning
Fix Django 1.10 url patterns warning
Python
mit
ui/django-post_office,JostCrow/django-post_office,RafRaf/django-post_office,ui/django-post_office,yprez/django-post_office,jrief/django-post_office
<DELETE> patterns, <DELETE_END> <REPLACE_OLD> patterns('', <REPLACE_NEW> [ <REPLACE_END> <REPLACE_OLD> name='admin'), ) <REPLACE_NEW> name='admin'), ] <REPLACE_END> <|endoftext|> from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', incl...
Fix Django 1.10 url patterns warning from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls), name='admin'), )
d86fe37bb29cc8c09c4659de579d4c370a59c40b
scripts/container_log_collector.py
scripts/container_log_collector.py
# stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(e...
# stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(e...
Set docker log encoding to utf-8
Set docker log encoding to utf-8
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
<REPLACE_OLD> path.write_text(container_logs) stored_files <REPLACE_NEW> path.write_text(container_logs, encoding="utf-8") stored_files <REPLACE_END> <|endoftext|> # stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir...
Set docker log encoding to utf-8 # stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = lo...
33e610576462d017bf25a65f1e879e6340f2ca06
python2/raygun4py/middleware/django.py
python2/raygun4py/middleware/django.py
from __future__ import absolute_import from django.conf import settings from raygun4py import raygunprovider class Provider(object): def __init__(self): config = getattr(settings, 'RAYGUN4PY_CONFIG', {}) apiKey = getattr(settings, 'RAYGUN4PY_API_KEY', config.get('api_key', None)) self.se...
from __future__ import absolute_import from django.conf import settings from raygun4py import raygunprovider class Provider(object): def __init__(self): config = getattr(settings, 'RAYGUN4PY_CONFIG', {}) apiKey = getattr(settings, 'RAYGUN4PY_API_KEY', config.get('api_key', None)) self.se...
Fix RawPostDataException on request.body access.
Fix RawPostDataException on request.body access. Django's HttpRequest class doesn't like the `request.body` to be accessed more than one time. Upon the second attempt to read from `request.body`, Django throws a `RawPostDataException`. Since the previous code in this spot was conditional upon a `hasattr(request, 'bo...
Python
mit
MindscapeHQ/raygun4py
<REPLACE_OLD> v <REPLACE_NEW> v <REPLACE_END> <|endoftext|> from __future__ import absolute_import from django.conf import settings from raygun4py import raygunprovider class Provider(object): def __init__(self): config = getattr(settings, 'RAYGUN4PY_CONFIG', {}) apiKey = getattr(settings, 'RAYGU...
Fix RawPostDataException on request.body access. Django's HttpRequest class doesn't like the `request.body` to be accessed more than one time. Upon the second attempt to read from `request.body`, Django throws a `RawPostDataException`. Since the previous code in this spot was conditional upon a `hasattr(request, 'bo...
a8115391de5a4490929cacc606282852b59f54c9
IPython/html/widgets/widget_image.py
IPython/html/widgets/widget_image.py
"""ButtonWidget class. Represents a button in the frontend using a widget. Allows user to listen for click events on the button and trigger backend code when the clicks are fired. """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. #...
"""ButtonWidget class. Represents a button in the frontend using a widget. Allows user to listen for click events on the button and trigger backend code when the clicks are fired. """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. #...
Use CUnicode for width and height in ImageWidget
Use CUnicode for width and height in ImageWidget
Python
bsd-3-clause
ipython/ipython,ipython/ipython
<INSERT> CUnicode, <INSERT_END> <REPLACE_OLD> Unicode(sync=True) # TODO: C unicode <REPLACE_NEW> CUnicode(sync=True) <REPLACE_END> <REPLACE_OLD> Unicode(sync=True) <REPLACE_NEW> CUnicode(sync=True) <REPLACE_END> <|endoftext|> """ButtonWidget class. Represents a button in the frontend using a widget. Allows user...
Use CUnicode for width and height in ImageWidget """ButtonWidget class. Represents a button in the frontend using a widget. Allows user to listen for click events on the button and trigger backend code when the clicks are fired. """ #----------------------------------------------------------------------------- # C...
70377c4397680c32b9ee6958bd250dce697fcb62
setup.py
setup.py
from setuptools import setup, find_packages install_requires = [ 'dill==0.2.5', 'easydict==1.6', 'h5py==2.6.0', 'jsonpickle==0.9.3', 'Keras==1.2.0', 'nflgame==1.2.20', 'numpy==1.11.2', 'pandas==0.19.1', 'scikit-learn==0.18.1', 'scipy==0.18.1', 'tensorflow==0.12.0rc1', '...
from setuptools import setup, find_packages install_requires = [ 'dill==0.2.5', 'easydict==1.6', 'h5py==2.6.0', 'jsonpickle==0.9.3', 'Keras==1.2.0', 'nflgame==1.2.20', 'numpy==1.11.2', 'pandas==0.19.1', 'scikit-learn==0.18.1', 'scipy==0.18.1', 'tensorflow==0.12.0rc1', '...
Add back models and data
Add back models and data
Python
mit
kahnjw/wincast
<REPLACE_OLD> ('', <REPLACE_NEW> ('models', <REPLACE_END> <REPLACE_OLD> ('', <REPLACE_NEW> ('data', <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages install_requires = [ 'dill==0.2.5', 'easydict==1.6', 'h5py==2.6.0', 'jsonpickle==0.9.3', 'Keras==1.2.0', 'nflgame==1.2.20'...
Add back models and data from setuptools import setup, find_packages install_requires = [ 'dill==0.2.5', 'easydict==1.6', 'h5py==2.6.0', 'jsonpickle==0.9.3', 'Keras==1.2.0', 'nflgame==1.2.20', 'numpy==1.11.2', 'pandas==0.19.1', 'scikit-learn==0.18.1', 'scipy==0.18.1', 'ten...
2f593f1581eaa4ec30c1a73a71bc8e0a52284441
setup.py
setup.py
from setuptools import setup setup( name='armstrong.base', version='0.1.2', description='Base functionality that needs to be shared widely', author='Texas Tribune', author_email='tech@texastribune.org', url='http://github.com/texastribune/armstrong.base/', packages=[ 'armstrong.base...
from setuptools import setup setup( name='armstrong.base', version='0.1.3', description='Base functionality that needs to be shared widely', author='Texas Tribune', author_email='tech@texastribune.org', url='http://github.com/texastribune/armstrong.base/', packages=[ 'armstrong.base...
Install missing templatetags test package
Install missing templatetags test package
Python
bsd-3-clause
texastribune/armstrong.base
<REPLACE_OLD> version='0.1.2', <REPLACE_NEW> version='0.1.3', <REPLACE_END> <INSERT> 'armstrong.base.tests.templatetags', <INSERT_END> <|endoftext|> from setuptools import setup setup( name='armstrong.base', version='0.1.3', description='Base functionality that needs to be shared widely', aut...
Install missing templatetags test package from setuptools import setup setup( name='armstrong.base', version='0.1.2', description='Base functionality that needs to be shared widely', author='Texas Tribune', author_email='tech@texastribune.org', url='http://github.com/texastribune/armstrong.bas...
26e2feb6f2dfe74ade46cf871167101599c0acba
app/timetables/models.py
app/timetables/models.py
from __future__ import unicode_literals from django.db import models from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) ...
from __future__ import unicode_literals from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the w...
Update clean method to ensure that meal end_time is not same as or less than meal start_time
Update clean method to ensure that meal end_time is not same as or less than meal start_time
Python
mit
teamtaverna/core
<REPLACE_OLD> models from <REPLACE_NEW> models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from <REPLACE_END> <INSERT> clean(self): if self.start_time >= self.end_time: raise ValidationError(_('start_time must be less than end_time.'))...
Update clean method to ensure that meal end_time is not same as or less than meal start_time from __future__ import unicode_literals from django.db import models from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" ...
4fa76c04a3455ebce6251b59aea54f5a769f3deb
invite/utils.py
invite/utils.py
from datetime import date, timedelta def get_cutoff_date(days): """Calculate the cutoff date or return None if no time period was set.""" if days is None or type(days) != int: return None else: if days >= 0: return date.today() - timedelta(days=days) else: r...
from datetime import date, timedelta def get_cutoff_date(days): """Calculate the cutoff date or return None if no time period was set.""" if days is None or type(days) != int: return None else: if days > 0: return date.today() - timedelta(days=days) elif days == 0: ...
Make it so a cutoff of 0 leads to no invites/registrations being shown.
Make it so a cutoff of 0 leads to no invites/registrations being shown.
Python
bsd-3-clause
unt-libraries/django-invite,unt-libraries/django-invite
<REPLACE_OLD> >= <REPLACE_NEW> > <REPLACE_END> <INSERT> elif days == 0: return date.today() + timedelta(days=2) <INSERT_END> <|endoftext|> from datetime import date, timedelta def get_cutoff_date(days): """Calculate the cutoff date or return None if no time period was set.""" if days is No...
Make it so a cutoff of 0 leads to no invites/registrations being shown. from datetime import date, timedelta def get_cutoff_date(days): """Calculate the cutoff date or return None if no time period was set.""" if days is None or type(days) != int: return None else: if days >= 0: ...
65d7ff9fc275bd6186484236d7a0d03c65cc62d7
peerinst/admin.py
peerinst/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Mai...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Mai...
Use nifty filter widget for selecting questions for an assignment.
Use nifty filter widget for selecting questions for an assignment.
Python
agpl-3.0
open-craft/dalite-ng,open-craft/dalite-ng,open-craft/dalite-ng
<REPLACE_OLD> pass <REPLACE_NEW> filter_horizontal = ['questions'] <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class Question...
Use nifty filter widget for selecting questions for an assignment. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): ...
e5e6d4ac9e86aa7e44694cf4746c4c9ec91df107
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup setup(name = 'skeleton', version = '0.0', description = 'A python skeleton project', long_description = ''' This project represents a basic python skeleton project that can be used as the basis for other projects. Feel free to fork this project...
#!/usr/bin/env python from distutils.core import setup setup(name = 'skeleton', version = '0.0', description = 'A python skeleton project', long_description = ''' This project represents a basic python skeleton project that can be used as the basis for other projects. Feel free to fork this project...
Move generic lib to botton of config.
Move generic lib to botton of config.
Python
bsd-2-clause
arlaneenalra/python-skeleton
<DELETE> package_dir = { '': 'lib'}, <DELETE_END> <REPLACE_OLD> [], ) <REPLACE_NEW> [], package_dir = { '': 'lib'}, ) <REPLACE_END> <|endoftext|> #!/usr/bin/env python from distutils.core import setup setup(name = 'skeleton', version = '0.0', description = 'A python skeleton project', ...
Move generic lib to botton of config. #!/usr/bin/env python from distutils.core import setup setup(name = 'skeleton', version = '0.0', description = 'A python skeleton project', long_description = ''' This project represents a basic python skeleton project that can be used as the basis for other pr...
149a8091333766068cac445db770ea73055d8647
simuvex/procedures/stubs/UserHook.py
simuvex/procedures/stubs/UserHook.py
import simuvex class UserHook(simuvex.SimProcedure): NO_RET = True # pylint: disable=arguments-differ def run(self, user_func=None, user_kwargs=None, default_return_addr=None): result = user_func(self.state, **user_kwargs) if result is None: self.add_successor(self.state, defau...
import simuvex class UserHook(simuvex.SimProcedure): NO_RET = True # pylint: disable=arguments-differ def run(self, user_func=None, user_kwargs=None, default_return_addr=None, length=None): result = user_func(self.state, **user_kwargs) if result is None: self.add_successor(self...
Make the userhook take the length arg b/c why not
Make the userhook take the length arg b/c why not
Python
bsd-2-clause
axt/angr,schieb/angr,tyb0807/angr,chubbymaggie/angr,chubbymaggie/simuvex,chubbymaggie/angr,chubbymaggie/simuvex,f-prettyland/angr,axt/angr,angr/angr,f-prettyland/angr,tyb0807/angr,schieb/angr,axt/angr,chubbymaggie/angr,f-prettyland/angr,iamahuman/angr,tyb0807/angr,iamahuman/angr,angr/angr,iamahuman/angr,angr/angr,schie...
<REPLACE_OLD> default_return_addr=None): <REPLACE_NEW> default_return_addr=None, length=None): <REPLACE_END> <|endoftext|> import simuvex class UserHook(simuvex.SimProcedure): NO_RET = True # pylint: disable=arguments-differ def run(self, user_func=None, user_kwargs=None, default_return_addr=None, lengt...
Make the userhook take the length arg b/c why not import simuvex class UserHook(simuvex.SimProcedure): NO_RET = True # pylint: disable=arguments-differ def run(self, user_func=None, user_kwargs=None, default_return_addr=None): result = user_func(self.state, **user_kwargs) if result is Non...
efe24b5b9d25bc499de0aff57f7d28f0f3c73991
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() requirements = [ 'furl==0.5.6', 'six==1.10.0' ] test_requirements = [ # TODO: put package test requirements here ] setup( name='surveymonkey', versi...
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() requirements = [ 'furl==0.5.6', 'six==1.10.0', 'pytest==3.0.3' ] test_requirements = [ # TODO: put package test requirements here ] setup( name='sur...
Add pytest to surveymonkey dependencies
Add pytest to surveymonkey dependencies
Python
mit
Administrate/surveymonkey
<REPLACE_OLD> 'six==1.10.0' ] test_requirements <REPLACE_NEW> 'six==1.10.0', 'pytest==3.0.3' ] test_requirements <REPLACE_END> <|endoftext|> #!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() requirements = [ 'f...
Add pytest to surveymonkey dependencies #!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() requirements = [ 'furl==0.5.6', 'six==1.10.0' ] test_requirements = [ # TODO: put package test requirements here ] ...
fc9dd735c96ae21b4a64286e4c9ebcedc0e1fbca
subsetKerning.py
subsetKerning.py
import sys from plistlib import writePlist from defcon import Font __doc__ = ''' Subset kerning in UFO given a list of glyphs provided. Will export new plist files that can be swapped into the UFO. Usage: python subsetKerning.py subsetList font.ufo ''' class SubsetKerning(object): """docstring for SubsetKernin...
Add script to subset kerning plist.
Add script to subset kerning plist.
Python
mit
adobe-type-tools/kern-dump
<REPLACE_OLD> <REPLACE_NEW> import sys from plistlib import writePlist from defcon import Font __doc__ = ''' Subset kerning in UFO given a list of glyphs provided. Will export new plist files that can be swapped into the UFO. Usage: python subsetKerning.py subsetList font.ufo ''' class SubsetKerning(object): ...
Add script to subset kerning plist.
c8376eddddd7bb61d4ae608e2fe0a0f333b0be84
backend/zotero.py
backend/zotero.py
# -*- encoding: utf-8 -*- from django.conf import settings from papers.errors import MetadataSourceException from papers.utils import sanitize_html import requests ##### Zotero interface ##### def fetch_zotero_by_DOI(doi): """ Fetch Zotero metadata for a given DOI. Works only with the doi_cache proxy. ...
# -*- encoding: utf-8 -*- from django.conf import settings from papers.errors import MetadataSourceException from papers.utils import sanitize_html import requests ##### Zotero interface ##### def fetch_zotero_by_DOI(doi): """ Fetch Zotero metadata for a given DOI. Works only with the doi_cache proxy. ...
Use HTTPS instead of HTTP since cache does redirect anyways
Use HTTPS instead of HTTP since cache does redirect anyways
Python
agpl-3.0
wetneb/dissemin,dissemin/dissemin,dissemin/dissemin,wetneb/dissemin,dissemin/dissemin,wetneb/dissemin,wetneb/dissemin,dissemin/dissemin,dissemin/dissemin
<REPLACE_OLD> requests.get('http://'+settings.DOI_PROXY_DOMAIN+'/zotero/'+doi) <REPLACE_NEW> requests.get('https://'+settings.DOI_PROXY_DOMAIN+'/zotero/'+doi) <REPLACE_END> <|endoftext|> # -*- encoding: utf-8 -*- from django.conf import settings from papers.errors import MetadataSourceException from papers.utils imp...
Use HTTPS instead of HTTP since cache does redirect anyways # -*- encoding: utf-8 -*- from django.conf import settings from papers.errors import MetadataSourceException from papers.utils import sanitize_html import requests ##### Zotero interface ##### def fetch_zotero_by_DOI(doi): """ Fetch Zotero metadat...
205b832c287bdd587eff7ba266a4429f6aebb277
data/models.py
data/models.py
import numpy import ast from django.db import models class DataPoint(models.Model): name = models.CharField(max_length=600) exact_name = models.CharField(max_length=1000, null=True, blank=True) decay_feature = models.CharField(max_length=1000, null=True, blank=True) created = models.DateTimeField(aut...
import numpy import ast from django.db import models class DataPoint(models.Model): name = models.CharField(max_length=600) exact_name = models.CharField(max_length=1000, null=True, blank=True) decay_feature = models.CharField(max_length=1000, null=True, blank=True) created = models.DateTimeField(aut...
Fix __unicode__ for DataPoint model
Fix __unicode__ for DataPoint model
Python
mit
crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp
<REPLACE_OLD> self.exact_name <REPLACE_NEW> unicode(self.name) <REPLACE_END> <|endoftext|> import numpy import ast from django.db import models class DataPoint(models.Model): name = models.CharField(max_length=600) exact_name = models.CharField(max_length=1000, null=True, blank=True) decay_feature = ...
Fix __unicode__ for DataPoint model import numpy import ast from django.db import models class DataPoint(models.Model): name = models.CharField(max_length=600) exact_name = models.CharField(max_length=1000, null=True, blank=True) decay_feature = models.CharField(max_length=1000, null=True, blank=True) ...
902e4ce0848cc2c3afa7192a85d413ed2919c798
csunplugged/tests/plugging_it_in/models/test_testcase.py
csunplugged/tests/plugging_it_in/models/test_testcase.py
from plugging_it_in.models import TestCase from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = Top...
from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data = TopicsTestDataGenerator() def create_testc...
Fix models unit test for plugging it in
Fix models unit test for plugging it in
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
<DELETE> plugging_it_in.models import TestCase from <DELETE_END> <DELETE> self.test_data.create_programming_challenge_test_case(1, challenge) <DELETE_END> <REPLACE_OLD> TestCase.objects.get(id=1) <REPLACE_NEW> self.test_data.create_programming_challenge_test_case(1, challenge) <REPLACE_END> <|endoftext|> f...
Fix models unit test for plugging it in from plugging_it_in.models import TestCase from tests.BaseTestWithDB import BaseTestWithDB from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator class TestCaseModelTest(BaseTestWithDB): def __init__(self, *args, **kwargs): super().__init__(*arg...
67c90087bad42d54b44044c3d1afae02538c456f
tests/logging.py
tests/logging.py
import os def save_logs(groomer, test_description): divider = ('=' * 10 + '{}' + '=' * 10 + '\n') test_log_path = 'tests/test_logs/{}.log'.format(test_description) with open(test_log_path, 'w+') as test_log: test_log.write(divider.format('TEST LOG')) with open(groomer.logger.log_path, 'r')...
import os from datetime import datetime def save_logs(groomer, test_description): divider = ('=' * 10 + '{}' + '=' * 10 + '\n') test_log_path = 'tests/test_logs/{}.log'.format(test_description) with open(test_log_path, 'w+') as test_log: test_log.write(divider.format('TEST LOG')) test_log....
Add time information to test logs
Add time information to test logs
Python
bsd-3-clause
CIRCL/PyCIRCLean,Rafiot/PyCIRCLean,Rafiot/PyCIRCLean,CIRCL/PyCIRCLean
<REPLACE_OLD> os def <REPLACE_NEW> os from datetime import datetime def <REPLACE_END> <INSERT> test_log.write(str(datetime.now().time()) + '\n') test_log.write(test_description + '\n') test_log.write('-' * 20 + '\n') <INSERT_END> <|endoftext|> import os from datetime import datetime def sa...
Add time information to test logs import os def save_logs(groomer, test_description): divider = ('=' * 10 + '{}' + '=' * 10 + '\n') test_log_path = 'tests/test_logs/{}.log'.format(test_description) with open(test_log_path, 'w+') as test_log: test_log.write(divider.format('TEST LOG')) with...
006380832d1f45c6c1c4ffad9356e7ed2399d681
setup.py
setup.py
#!/usr/bin/env python import io from setuptools import setup, Extension with io.open('README.rst', encoding='utf8') as readme: long_description = readme.read() setup( name="pyspamsum", version="1.0.5", description="A Python wrapper for Andrew Tridgell's spamsum algorithm", long_description=long...
#!/usr/bin/env python import io from setuptools import setup, Extension with io.open('README.rst', encoding='utf8') as readme: long_description = readme.read() setup( name="pyspamsum", version="1.0.5", description="A Python wrapper for Andrew Tridgell's spamsum algorithm", long_description=long...
Add a content type description to keep twine happy.
Add a content type description to keep twine happy.
Python
bsd-3-clause
freakboy3742/pyspamsum,freakboy3742/pyspamsum
<INSERT> long_description_content_type='text/x-rst', <INSERT_END> <|endoftext|> #!/usr/bin/env python import io from setuptools import setup, Extension with io.open('README.rst', encoding='utf8') as readme: long_description = readme.read() setup( name="pyspamsum", version="1.0.5", description="...
Add a content type description to keep twine happy. #!/usr/bin/env python import io from setuptools import setup, Extension with io.open('README.rst', encoding='utf8') as readme: long_description = readme.read() setup( name="pyspamsum", version="1.0.5", description="A Python wrapper for Andrew Tri...
0476e30119c02d715c8674d1e362207bd9a464c9
tests/startsymbol_tests/__init__.py
tests/startsymbol_tests/__init__.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """
Add directory for start symbol tests
Add directory for start symbol tests
Python
mit
PatrikValkovic/grammpy
<REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ <REPLACE_END> <|endoftext|> #!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """
Add directory for start symbol tests
6c1d1c0662a0ae05dcfbb55484164a302bf5e0d3
tests/test_cl_json.py
tests/test_cl_json.py
from kqml import cl_json, KQMLList def test_parse(): json_dict = {'a': 1, 'b': 2, 'c': ['foo', {'bar': None, 'done': False}], 'this is json': True} res = cl_json.parse_json(json_dict) assert isinstance(res, KQMLList) assert len(res) == 2*len(json_dict.keys())
Add a test of the parser.
Add a test of the parser.
Python
bsd-2-clause
bgyori/pykqml
<INSERT> from kqml import cl_json, KQMLList def test_parse(): <INSERT_END> <INSERT> json_dict = {'a': 1, 'b': 2, 'c': ['foo', {'bar': None, 'done': False}], 'this is json': True} res = cl_json.parse_json(json_dict) assert isinstance(res, KQMLList) assert len(res) == 2*...
Add a test of the parser.
b2dfa7ea44a0b9e061ffbb346fe9196ba96c2a44
nanshe_workflow/_reg_joblib.py
nanshe_workflow/_reg_joblib.py
import dask import dask.distributed import distributed try: import dask.distributed.joblib except ImportError: pass try: import distributed.joblib except ImportError: pass import sklearn import sklearn.externals import sklearn.externals.joblib
Add backwards compatible Distributed Joblib hook
Add backwards compatible Distributed Joblib hook Depending on the versions of Distributed, Joblib, and scikit-learn, there are different strategies for registering the Joblib backend. Try going with the standard Distributed technique first, which may fail for Distributed 1.24.0+. In other cases, import `joblib` and `s...
Python
apache-2.0
nanshe-org/nanshe_workflow,DudLab/nanshe_workflow
<INSERT> import dask import dask.distributed import distributed try: <INSERT_END> <INSERT> import dask.distributed.joblib except ImportError: pass try: import distributed.joblib except ImportError: pass import sklearn import sklearn.externals import sklearn.externals.joblib <INSERT_END> <|endoftext|...
Add backwards compatible Distributed Joblib hook Depending on the versions of Distributed, Joblib, and scikit-learn, there are different strategies for registering the Joblib backend. Try going with the standard Distributed technique first, which may fail for Distributed 1.24.0+. In other cases, import `joblib` and `s...
965dc806c5577fea89f1fcf78e3cdfcbff84b65f
moto/iam/exceptions.py
moto/iam/exceptions.py
from __future__ import unicode_literals from moto.core.exceptions import RESTError class IAMNotFoundException(RESTError): code = 404 def __init__(self, message): super(IAMNotFoundException, self).__init__( "Not Found", message) class IAMConflictException(RESTError): code = 409 ...
from __future__ import unicode_literals from moto.core.exceptions import RESTError class IAMNotFoundException(RESTError): code = 404 def __init__(self, message): super(IAMNotFoundException, self).__init__( "NoSuchEntity", message) class IAMConflictException(RESTError): code = 409 ...
Fix the error code for IAMNotFoundException to NoSuchEntity used by AWS.
Fix the error code for IAMNotFoundException to NoSuchEntity used by AWS.
Python
apache-2.0
spulec/moto,spulec/moto,botify-labs/moto,kefo/moto,kefo/moto,william-richard/moto,dbfr3qs/moto,Affirm/moto,ZuluPro/moto,kefo/moto,botify-labs/moto,botify-labs/moto,whummer/moto,Affirm/moto,botify-labs/moto,ZuluPro/moto,Brett55/moto,Brett55/moto,Affirm/moto,rocky4570/moto,william-richard/moto,rocky4570/moto,whummer/moto...
<REPLACE_OLD> "Not Found", <REPLACE_NEW> "NoSuchEntity", <REPLACE_END> <|endoftext|> from __future__ import unicode_literals from moto.core.exceptions import RESTError class IAMNotFoundException(RESTError): code = 404 def __init__(self, message): super(IAMNotFoundException, self).__init__( ...
Fix the error code for IAMNotFoundException to NoSuchEntity used by AWS. from __future__ import unicode_literals from moto.core.exceptions import RESTError class IAMNotFoundException(RESTError): code = 404 def __init__(self, message): super(IAMNotFoundException, self).__init__( "Not Foun...
61cef22952451df6345355ad596b38cb92697256
flocker/test/test_flocker.py
flocker/test/test_flocker.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Tests for top-level ``flocker`` package. """ from sys import executable from subprocess import check_output, STDOUT from twisted.trial.unittest import SynchronousTestCase class WarningsTests(SynchronousTestCase): """ Tests for warning suppres...
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Tests for top-level ``flocker`` package. """ from sys import executable from subprocess import check_output, STDOUT from twisted.trial.unittest import SynchronousTestCase from twisted.python.filepath import FilePath import flocker class WarningsTest...
Make sure flocker package can be imported even if it's not installed.
Make sure flocker package can be imported even if it's not installed.
Python
apache-2.0
beni55/flocker,hackday-profilers/flocker,achanda/flocker,adamtheturtle/flocker,mbrukman/flocker,Azulinho/flocker,w4ngyi/flocker,agonzalezro/flocker,agonzalezro/flocker,1d4Nf6/flocker,moypray/flocker,AndyHuu/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,w4ngyi/flocker,Azulinho/flocker,LaynePe...
<REPLACE_OLD> SynchronousTestCase class <REPLACE_NEW> SynchronousTestCase from twisted.python.filepath import FilePath import flocker class <REPLACE_END> <INSERT> root = FilePath(flocker.__file__) <INSERT_END> <REPLACE_OLD> stderr=STDOUT) <REPLACE_NEW> stderr=STDOUT, # Make sure we can import ...
Make sure flocker package can be imported even if it's not installed. # Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Tests for top-level ``flocker`` package. """ from sys import executable from subprocess import check_output, STDOUT from twisted.trial.unittest import SynchronousTestCase class Wa...
d5315907c25a42b6275b43b49f6e24ae72308c5b
utils/image_to_calc.py
utils/image_to_calc.py
#!/usr/bin/env python import sys, os import serial from PIL import Image if not len(sys.argv) == 2: print sys.argv[0], "/path/to/image" sys.exit(1) filepath = sys.argv[1] im = Image.open(filepath) rgb_im = im.convert('RGB') width, height = im.size if not width == 96 or not height == 64: print "Image wr...
Send images to calculator over serial.
Send images to calculator over serial.
Python
mit
jmptable/deshellator,jmptable/deshellator,jmptable/deshellator,jmptable/deshellator,jmptable/deshellator
<REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python import sys, os import serial from PIL import Image if not len(sys.argv) == 2: print sys.argv[0], "/path/to/image" sys.exit(1) filepath = sys.argv[1] im = Image.open(filepath) rgb_im = im.convert('RGB') width, height = im.size if not width == 96 or not heig...
Send images to calculator over serial.
033c16034074d4fd6eab054a9c97888d23668316
tests/test_empty_polygons.py
tests/test_empty_polygons.py
from shapely.geometry import MultiPolygon, Polygon def test_empty_polygon(): """No constructor arg makes an empty polygon geometry.""" assert Polygon().is_empty def test_empty_multipolygon(): """No constructor arg makes an empty multipolygon geometry.""" assert MultiPolygon().is_empty def test_mul...
from shapely.geometry import MultiPolygon, Point, Polygon def test_empty_polygon(): """No constructor arg makes an empty polygon geometry.""" assert Polygon().is_empty def test_empty_multipolygon(): """No constructor arg makes an empty multipolygon geometry.""" assert MultiPolygon().is_empty def t...
Add test of an empty and non empty polygon
Add test of an empty and non empty polygon
Python
bsd-3-clause
jdmcbr/Shapely,jdmcbr/Shapely
<INSERT> Point, <INSERT_END> <REPLACE_OLD> MultiPolygon([Polygon()]).is_empty <REPLACE_NEW> MultiPolygon([Polygon()]).is_empty def test_multipolygon_empty_among_polygon(): """An empty polygon passed to MultiPolygon() is ignored.""" assert len(MultiPolygon([Point(0,0).buffer(1.0), Polygon()])) == 1 <REPLACE_...
Add test of an empty and non empty polygon from shapely.geometry import MultiPolygon, Polygon def test_empty_polygon(): """No constructor arg makes an empty polygon geometry.""" assert Polygon().is_empty def test_empty_multipolygon(): """No constructor arg makes an empty multipolygon geometry.""" a...
a59eea30cb34bb301c610089d467e927a4d0f312
setup.py
setup.py
import husk from setuptools import setup, find_packages kwargs = { 'packages': find_packages(), 'include_package_data': True, 'test_suite': 'tests', 'name': 'husk', 'version': husk.__version__, 'author': 'Byron Ruth, Patrick Henning', 'author_email': 'b@devel.io', 'description': husk.__...
import husk from setuptools import setup, find_packages kwargs = { 'packages': find_packages(), 'include_package_data': True, 'test_suite': 'tests', 'name': 'husk', 'version': husk.__version__, 'author': 'Byron Ruth, Patrick Henning', 'author_email': 'b@devel.io', 'description': husk.__...
Update URL to point to new repository/website
Update URL to point to new repository/website
Python
bsd-2-clause
husk/husk
<REPLACE_OLD> 'https://bruth.github.com/husk/', <REPLACE_NEW> 'http://husk.github.com/husk/', <REPLACE_END> <|endoftext|> import husk from setuptools import setup, find_packages kwargs = { 'packages': find_packages(), 'include_package_data': True, 'test_suite': 'tests', 'name': 'husk', 'version':...
Update URL to point to new repository/website import husk from setuptools import setup, find_packages kwargs = { 'packages': find_packages(), 'include_package_data': True, 'test_suite': 'tests', 'name': 'husk', 'version': husk.__version__, 'author': 'Byron Ruth, Patrick Henning', 'author_em...
5dce9c5438b4fcb63c2b7a4a4f481cba331836ed
wger/exercises/management/commands/exercises-health-check.py
wger/exercises/management/commands/exercises-health-check.py
# -*- coding: utf-8 *-* # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any ...
Add script to check the current exercise translations
Add script to check the current exercise translations
Python
agpl-3.0
wger-project/wger,wger-project/wger,wger-project/wger,wger-project/wger
<REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 *-* # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the Licens...
Add script to check the current exercise translations
a859890c9f17b2303061b2d68e5c58ad27e07b35
grizli/pipeline/__init__.py
grizli/pipeline/__init__.py
""" Automated processing of associated exposures """
""" Automated processing of associated exposures """ def fetch_from_AWS_bucket(root='j022644-044142', id=1161, product='.beams.fits', bucket_name='aws-grivam', verbose=True, dryrun=False, output_path='./', get_fit_args=False, skip_existing=True): """ Fetch products from the Grizli AWS bucket. Boto3 ...
Add script to fetch data from AWS
Add script to fetch data from AWS
Python
mit
gbrammer/grizli
<REPLACE_OLD> exposures """ <REPLACE_NEW> exposures """ def fetch_from_AWS_bucket(root='j022644-044142', id=1161, product='.beams.fits', bucket_name='aws-grivam', verbose=True, dryrun=False, output_path='./', get_fit_args=False, skip_existing=True): """ Fetch products from the Grizli AWS bucket. ...
Add script to fetch data from AWS """ Automated processing of associated exposures """
1e62898d02ae5187ce078a2bb699eefd6bc184ef
s2v2.py
s2v2.py
from s2v1 import * def number_of_records(data_sample): return len(data_sample) number_of_ties = number_of_records(data_from_csv) - 1 # minus header row print(number_of_ties, "ties in our data sample") def number_of_records2(data_sample): return data_sample.size number_of_ties_my_csv = number_of_records2(my_csv) ...
from s2v1 import * def number_of_records(data_sample): return len(data_sample) number_of_ties = number_of_records(data_from_csv) - 1 # minus header row # print(number_of_ties, "ties in our data sample") def number_of_records2(data_sample): return data_sample.size number_of_ties_my_csv = number_of_records2(my_csv...
Comment out print statements for total number of ties
Comment out print statements for total number of ties
Python
mit
alexmilesyounger/ds_basics
<REPLACE_OLD> row print(number_of_ties, <REPLACE_NEW> row # print(number_of_ties, <REPLACE_END> <REPLACE_OLD> number_of_records2(my_csv) print(number_of_ties_my_csv, <REPLACE_NEW> number_of_records2(my_csv) # print(number_of_ties_my_csv, <REPLACE_END> <|endoftext|> from s2v1 import * def number_of_records(data_sampl...
Comment out print statements for total number of ties from s2v1 import * def number_of_records(data_sample): return len(data_sample) number_of_ties = number_of_records(data_from_csv) - 1 # minus header row print(number_of_ties, "ties in our data sample") def number_of_records2(data_sample): return data_sample.si...
f4dfcf91c11fd06b5b71135f888b6979548a5147
conveyor/__main__.py
conveyor/__main__.py
from __future__ import absolute_import from .core import Conveyor def main(): Conveyor().run() if __name__ == "__main__": main()
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from .core import Conveyor def main(): Conveyor().run() if __name__ == "__main__": main()
Bring the standard __future__ imports over
Bring the standard __future__ imports over
Python
bsd-2-clause
crateio/carrier
<REPLACE_OLD> absolute_import from <REPLACE_NEW> absolute_import from __future__ import division from __future__ import unicode_literals from <REPLACE_END> <REPLACE_OLD> Conveyor().run() if <REPLACE_NEW> Conveyor().run() if <REPLACE_END> <|endoftext|> from __future__ import absolute_import from __future__ import d...
Bring the standard __future__ imports over from __future__ import absolute_import from .core import Conveyor def main(): Conveyor().run() if __name__ == "__main__": main()
c3762443859ada75687e5a62d576fe8140a42a7c
tests/test_csv2iati.py
tests/test_csv2iati.py
import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the def...
import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } }
Remove redundant csv2iati test now site has been decommissioned
Remove redundant csv2iati test now site has been decommissioned
Python
mit
IATI/IATI-Website-Tests
<REPLACE_OLD> } def test_contains_links(self, loaded_request): """ Test that each page contains links to the defined URLs. """ result = utility.get_links_from_page(loaded_request) assert "http://iatistandard.org" in result @pytest.mark.parametrize("target_request", ["C...
Remove redundant csv2iati test now site has been decommissioned import pytest from web_test_base import * class TestCSV2IATI(WebTestBase): requests_to_load = { 'CSV2IATI Homepage': { 'url': 'http://csv2iati.iatistandard.org/' } } def test_contains_links(self, loaded_request): ...
c617083fa413a0d45ff26c96751210901dfad7cf
cab/urls/search.py
cab/urls/search.py
from django.conf.urls import url from haystack.views import SearchView, search_view_factory from ..forms import AdvancedSearchForm search_view = search_view_factory(view_class=SearchView, template='search/advanced_search.html', form_class=AdvancedSea...
from django.conf.urls import url from haystack.views import SearchView, basic_search, search_view_factory from ..forms import AdvancedSearchForm from ..views.snippets import autocomplete search_view = search_view_factory(view_class=SearchView, template='search/advanced_search.html', ...
Remove string views in urlpatterns
Remove string views in urlpatterns
Python
bsd-3-clause
django/djangosnippets.org,django/djangosnippets.org,django/djangosnippets.org,django-de/djangosnippets.org,django-de/djangosnippets.org,django/djangosnippets.org,django-de/djangosnippets.org,django-de/djangosnippets.org,django/djangosnippets.org
<INSERT> basic_search, <INSERT_END> <REPLACE_OLD> AdvancedSearchForm search_view <REPLACE_NEW> AdvancedSearchForm from ..views.snippets import autocomplete search_view <REPLACE_END> <REPLACE_OLD> url(r'^$', 'haystack.views.basic_search', <REPLACE_NEW> url(r'^$', basic_search, <REPLACE_END> <REPLACE_OL...
Remove string views in urlpatterns from django.conf.urls import url from haystack.views import SearchView, search_view_factory from ..forms import AdvancedSearchForm search_view = search_view_factory(view_class=SearchView, template='search/advanced_search.html', ...
0378572237df9c3a4bfa7a5a7009fdd664e527e5
wagtail/wagtailadmin/templatetags/gravatar.py
wagtail/wagtailadmin/templatetags/gravatar.py
# place inside a 'templatetags' directory inside the top level of a Django app (not project, must be inside an app) # at the top of your page template include this: # {% load gravatar %} # and to use the url do this: # <img src="{% gravatar_url 'someone@somewhere.com' %}"> # or # <img src="{% gravatar_url sometemplatev...
# place inside a 'templatetags' directory inside the top level of a Django app (not project, must be inside an app) # at the top of your page template include this: # {% load gravatar %} # and to use the url do this: # <img src="{% gravatar_url 'someone@somewhere.com' %}"> # or # <img src="{% gravatar_url sometemplatev...
Make mystery man the default Gravatar image
Make mystery man the default Gravatar image
Python
bsd-3-clause
gasman/wagtail,rsalmaso/wagtail,nealtodd/wagtail,timorieber/wagtail,jnns/wagtail,wagtail/wagtail,gasman/wagtail,thenewguy/wagtail,mikedingjan/wagtail,wagtail/wagtail,gasman/wagtail,torchbox/wagtail,iansprice/wagtail,zerolab/wagtail,takeflight/wagtail,kaedroho/wagtail,Toshakins/wagtail,jnns/wagtail,nimasmi/wagtail,kaedr...
<REPLACE_OLD> "blank" <REPLACE_NEW> "mm" <REPLACE_END> <|endoftext|> # place inside a 'templatetags' directory inside the top level of a Django app (not project, must be inside an app) # at the top of your page template include this: # {% load gravatar %} # and to use the url do this: # <img src="{% gravatar_url 'som...
Make mystery man the default Gravatar image # place inside a 'templatetags' directory inside the top level of a Django app (not project, must be inside an app) # at the top of your page template include this: # {% load gravatar %} # and to use the url do this: # <img src="{% gravatar_url 'someone@somewhere.com' %}"> ...
2b4b4ac3ec238a039717feff727316217c13d294
test/test_cronquot.py
test/test_cronquot.py
import unittest from cronquot.cronquot import has_directory class CronquotTest(unittest.TestCase): def test_has_directory(self): self.assertTrue(has_directory('/tmp')) if __name__ == '__main__': unittest.test()
import unittest import os from cronquot.cronquot import has_directory class CronquotTest(unittest.TestCase): def test_has_directory(self): sample_dir = os.path.join( os.path.dirname(__file__), 'crontab') self.assertTrue(has_directory(sample_dir)) if __name__ == '__main__': un...
Fix to test crontab dir
Fix to test crontab dir
Python
mit
pyohei/cronquot,pyohei/cronquot
<REPLACE_OLD> unittest from <REPLACE_NEW> unittest import os from <REPLACE_END> <REPLACE_OLD> self.assertTrue(has_directory('/tmp')) if <REPLACE_NEW> sample_dir = os.path.join( os.path.dirname(__file__), 'crontab') self.assertTrue(has_directory(sample_dir)) if <REPLACE_END> <|endoftext|> impor...
Fix to test crontab dir import unittest from cronquot.cronquot import has_directory class CronquotTest(unittest.TestCase): def test_has_directory(self): self.assertTrue(has_directory('/tmp')) if __name__ == '__main__': unittest.test()
65bae0d38b96fde3e3dd54cdc915e99b661b974a
web_tools.py
web_tools.py
import urllib, subprocess, random, re from bs4 import BeautifulSoup # http://www.crummy.com/software/BeautifulSoup/bs4/doc/# import socket, struct, binascii class Web(): def getHeader(self, url): """Get Header Info""" http_r = urllib.urlopen(url) if http_r.code == 200: return http_r.headers e...
Add Web tools: getHeader, getParticularClass, getLinks, errorHandling, bannerGrapper
Add Web tools: getHeader, getParticularClass, getLinks, errorHandling, bannerGrapper
Python
mit
rudolfvavra/network,rudolfvavra/network,rudolfvavra/network,rudolfvavra/network,rudolfvavra/network,rudolfvavra/network,rudolfvavra/network,rudolfvavra/network,rudolfvavra/network,rudolfvavra/network,rudolfvavra/network
<REPLACE_OLD> <REPLACE_NEW> import urllib, subprocess, random, re from bs4 import BeautifulSoup # http://www.crummy.com/software/BeautifulSoup/bs4/doc/# import socket, struct, binascii class Web(): def getHeader(self, url): """Get Header Info""" http_r = urllib.urlopen(url) if http_r.code == 200: ...
Add Web tools: getHeader, getParticularClass, getLinks, errorHandling, bannerGrapper
7d3ffe4582a5b4032f9a59a3ea8edfded57a7a1f
src/nodeconductor_openstack/openstack/migrations/0031_tenant_backup_storage.py
src/nodeconductor_openstack/openstack/migrations/0031_tenant_backup_storage.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.contenttypes.models import ContentType from django.db import migrations from nodeconductor.quotas import models as quotas_models from .. import models def cleanup_tenant_quotas(apps, schema_editor): for obj in models.Tenant.obj...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from .. import models def cleanup_tenant_quotas(apps, schema_editor): quota_names = models.Tenant.get_quotas_names() for obj in models.Tenant.objects.all(): obj.quotas.exclude(name__in=quota_names).delet...
Clean up quota cleanup migration
Clean up quota cleanup migration [WAL-433]
Python
mit
opennode/nodeconductor-openstack
<DELETE> django.contrib.contenttypes.models import ContentType from <DELETE_END> <DELETE> nodeconductor.quotas import models as quotas_models from <DELETE_END> <INSERT> quota_names = models.Tenant.get_quotas_names() <INSERT_END> <REPLACE_OLD> quotas_names = models.Tenant.QUOTAS_NAMES + [f.name for f in models.Tena...
Clean up quota cleanup migration [WAL-433] # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.contenttypes.models import ContentType from django.db import migrations from nodeconductor.quotas import models as quotas_models from .. import models def cleanup_tenant_quotas(apps, sche...
1afebd46c8cf786673adface7724e9488df17a7e
appengine-experimental/src/models.py
appengine-experimental/src/models.py
from datetime import datetime, timedelta from google.appengine.ext import db class CHPIncident(db.Model): CenterID = db.StringProperty(required=True) DispatchID = db.StringProperty(required=True) LogID = db.StringProperty(required=True) LogTime = db.DateTimeProperty() LogType = db.StringProperty() LogTypeID = ...
from datetime import datetime, timedelta from google.appengine.ext import db class CHPIncident(db.Model): CenterID = db.StringProperty(required=True) DispatchID = db.StringProperty(required=True) LogID = db.StringProperty(required=True) LogTime = db.DateTimeProperty() LogType = db.StringProperty() LogTypeID = ...
Tweak the "inactive" timeout a bit to take latency into account.
Tweak the "inactive" timeout a bit to take latency into account.
Python
isc
lectroidmarc/SacTraffic,lectroidmarc/SacTraffic
<REPLACE_OLD> timedelta(minutes=5): # <REPLACE_NEW> timedelta(minutes=6): # <REPLACE_END> <REPLACE_OLD> 5 min <REPLACE_NEW> the last update <REPLACE_END> <REPLACE_OLD> inactive return <REPLACE_NEW> inactive # # Note this is the cronned update interval + 1. return <REPLACE_END> <|endoftext|> from datet...
Tweak the "inactive" timeout a bit to take latency into account. from datetime import datetime, timedelta from google.appengine.ext import db class CHPIncident(db.Model): CenterID = db.StringProperty(required=True) DispatchID = db.StringProperty(required=True) LogID = db.StringProperty(required=True) LogTime = ...
7cb7fa17720864669ac1e0c3fe361e3925415169
client/python/plot_request_times.py
client/python/plot_request_times.py
import requests r = requests.get('http://localhost:8081/monitor_results/1') print(r.json()) for monitoring_data in r.json(): print 'URL: ' + monitoring_data['urlToMonitor']['url']
Add stub for python client
Add stub for python client
Python
mit
gernd/simple-site-mon
<INSERT> import requests r = requests.get('http://localhost:8081/monitor_results/1') print(r.json()) for monitoring_data in r.json(): <INSERT_END> <INSERT> print 'URL: ' + monitoring_data['urlToMonitor']['url'] <INSERT_END> <|endoftext|> import requests r = requests.get('http://localhost:8081/monitor_results/1')...
Add stub for python client
e3835baeb03da43456442fdd2678891cf2b6f957
DeployUtil/authentication.py
DeployUtil/authentication.py
import urllib.request import ssl import http.cookiejar #TODO: give an indicator of success #TODO: handle errors a bit better. def do_pair(ip, pin, **_args): # IF YOU DON'T DO THIS OVER HTTPS YOU WILL GET 308s to goto HTTPS scheme = 'https://' port = '' api = '/api/authorize/pair?pin={pin}&persistent=0' verb = 'P...
import urllib.request import ssl import http.cookiejar #TODO: give an indicator of success #TODO: handle errors a bit better. def do_pair(ip, pin, **_args): # IF YOU DON'T DO THIS OVER HTTPS YOU WILL GET 308s to goto HTTPS scheme = 'https://' port = '' api = '/api/authorize/pair?pin={pin}&persistent=0' verb = 'P...
Fix a bug in cleanup
Fix a bug in cleanup
Python
mit
loarabia/DeployUtil
<REPLACE_OLD> urllib.request.build_opener(WDPRedirectHandler(), https_handler, <REPLACE_NEW> urllib.request.build_opener(https_handler, <REPLACE_END> <|endoftext|> import urllib.request import ssl import http.cookiejar #TODO: give an indicator of success #TODO: handle errors a bit better. def do_pair(ip, pin, **_args...
Fix a bug in cleanup import urllib.request import ssl import http.cookiejar #TODO: give an indicator of success #TODO: handle errors a bit better. def do_pair(ip, pin, **_args): # IF YOU DON'T DO THIS OVER HTTPS YOU WILL GET 308s to goto HTTPS scheme = 'https://' port = '' api = '/api/authorize/pair?pin={pin}&pe...
c8c616dffcce4a8083e3415607b07da6ae1adc7a
2019/aoc2019/day13.py
2019/aoc2019/day13.py
from typing import TextIO from aoc2019.intcode import Computer, read_program def part1(data: TextIO) -> int: computer = Computer(read_program(data)) computer.run() screen = {} while computer.output: x = computer.output.popleft() y = computer.output.popleft() val = computer....
Implement 2019 day 13 part 1
Implement 2019 day 13 part 1
Python
mit
bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adv...
<INSERT> from typing import TextIO from aoc2019.intcode import Computer, read_program def part1(data: TextIO) -> int: <INSERT_END> <INSERT> computer = Computer(read_program(data)) computer.run() screen = {} while computer.output: x = computer.output.popleft() y = computer.output.pop...
Implement 2019 day 13 part 1
3c94fc8a784420740caa8831363b6ebb8b1d6095
django_archive/archivers/__init__.py
django_archive/archivers/__init__.py
from .tarball import TarballArchiver from .zipfile import ZipArchiver TARBALL = TarballArchiver.UNCOMPRESSED TARBALL_GZ = TarballArchiver.GZ TARBALL_BZ2 = TarballArchiver.BZ2 TARBALL_XZ = TarballArchiver.XZ ZIP = 'zip' def get_archiver(fmt): """ Return the class corresponding with the provided archival form...
from .tarball import TarballArchiver from .zipfile import ZipArchiver TARBALL = TarballArchiver.UNCOMPRESSED TARBALL_GZ = TarballArchiver.GZ TARBALL_BZ2 = TarballArchiver.BZ2 TARBALL_XZ = TarballArchiver.XZ ZIP = 'zip' FORMATS = ( (TARBALL, "Tarball (.tar)"), (TARBALL_GZ, "gzip-compressed Tarball (.tar.gz)")...
Add tuple containing all supported archive formats and their human-readable description.
Add tuple containing all supported archive formats and their human-readable description.
Python
mit
nathan-osman/django-archive,nathan-osman/django-archive
<REPLACE_OLD> 'zip' def <REPLACE_NEW> 'zip' FORMATS = ( (TARBALL, "Tarball (.tar)"), (TARBALL_GZ, "gzip-compressed Tarball (.tar.gz)"), (TARBALL_BZ2, "bzip2-compressed Tarball (.tar.bz2)"), (TARBALL_XZ, "xz-compressed Tarball (.tar.xz)"), (ZIP, "ZIP archive (.zip)"), ) def <REPLACE_END> <|endof...
Add tuple containing all supported archive formats and their human-readable description. from .tarball import TarballArchiver from .zipfile import ZipArchiver TARBALL = TarballArchiver.UNCOMPRESSED TARBALL_GZ = TarballArchiver.GZ TARBALL_BZ2 = TarballArchiver.BZ2 TARBALL_XZ = TarballArchiver.XZ ZIP = 'zip' def get...
1bb5bb76489acd65d61415b9ce82bbb35dc53de3
src/ggrc/migrations/versions/20150520103539_b0c3361797a_migrate_control_sections_to_.py
src/ggrc/migrations/versions/20150520103539_b0c3361797a_migrate_control_sections_to_.py
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com """Migrate control_sections to relationships Revision ID: b0c3361797a Revises: ...
Add control_sections to relationships migration
Add control_sections to relationships migration
Python
apache-2.0
andrei-karalionak/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,kr41/ggrc-core,NejcZupec/ggrc-core,josthkko/ggrc-core,jmakov/ggrc-core,AleksNeStu/ggrc-core,prasannav7/ggrc-core,hyperNURb/ggrc-core,AleksNeStu/ggrc-core,prasannav7/ggrc-core,jmakov/ggrc-core,josthkko/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-co...
<REPLACE_OLD> <REPLACE_NEW> # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com """Migrate control_sections to relationships Revis...
Add control_sections to relationships migration
6d1b20bd047a47c46e3aa33a920e71f890f2b1fa
run.py
run.py
__author__ = 'matt' import datetime import blockbuster blockbuster.app.debug = blockbuster.config.debug_mode blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.config.app_version + " " ...
__author__ = 'matt' import datetime import blockbuster blockbuster.app.debug = blockbuster.config.debug_mode blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.__version__ + " " ...
Update reference to application version
Update reference to application version
Python
mit
mattstibbs/blockbuster-server,mattstibbs/blockbuster-server
<REPLACE_OLD> blockbuster.config.app_version <REPLACE_NEW> blockbuster.__version__ <REPLACE_END> <|endoftext|> __author__ = 'matt' import datetime import blockbuster blockbuster.app.debug = blockbuster.config.debug_mode blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") b...
Update reference to application version __author__ = 'matt' import datetime import blockbuster blockbuster.app.debug = blockbuster.config.debug_mode blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + ...
0d897c469d168d0362e71c26d039163fd0d3bdd2
zerver/management/commands/client-activity.py
zerver/management/commands/client-activity.py
from __future__ import absolute_import from django.core.management.base import BaseCommand from django.db.models import Count from zerver.models import UserActivity, UserProfile, Realm, \ get_realm, get_user_profile_by_email import datetime class Command(BaseCommand): help = """Report rough client activity ...
Add a utility to report some rough recent client activity metrics.
Add a utility to report some rough recent client activity metrics. (imported from commit 27b4a70871939b2728fcbe0ce5824326ff4decc2)
Python
apache-2.0
pradiptad/zulip,esander91/zulip,JPJPJPOPOP/zulip,hustlzp/zulip,MayB/zulip,AZtheAsian/zulip,ApsOps/zulip,MayB/zulip,amallia/zulip,bowlofstew/zulip,ufosky-server/zulip,showell/zulip,vabs22/zulip,qq1012803704/zulip,mohsenSy/zulip,he15his/zulip,atomic-labs/zulip,andersk/zulip,johnnygaddarr/zulip,tiansiyuan/zulip,AZtheAsian...
<REPLACE_OLD> <REPLACE_NEW> from __future__ import absolute_import from django.core.management.base import BaseCommand from django.db.models import Count from zerver.models import UserActivity, UserProfile, Realm, \ get_realm, get_user_profile_by_email import datetime class Command(BaseCommand): help = """...
Add a utility to report some rough recent client activity metrics. (imported from commit 27b4a70871939b2728fcbe0ce5824326ff4decc2)
ee99527185268ac386aad0c54056ac640c197e42
dbmigrator/commands/init.py
dbmigrator/commands/init.py
# -*- coding: utf-8 -*- # ### # Copyright (c) 2015, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### from .. import utils __all__ = ('cli_loader',) @utils.with_cursor def cli_command(cursor, migrations_d...
# -*- coding: utf-8 -*- # ### # Copyright (c) 2015, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### from .. import utils __all__ = ('cli_loader',) @utils.with_cursor def cli_command(cursor, migrations_d...
Stop changing schema_migrations data if the table already exists
Stop changing schema_migrations data if the table already exists
Python
agpl-3.0
karenc/db-migrator
<INSERT> SELECT 1 FROM information_schema.tables WHERE table_name = 'schema_migrations'""") table_exists = cursor.fetchone() if table_exists: print('Schema migrations already initialized.') return cursor.execute("""\ <INSERT_END> <DELETE> IF NOT EXISTS <DELETE_END> <DELETE> ...
Stop changing schema_migrations data if the table already exists # -*- coding: utf-8 -*- # ### # Copyright (c) 2015, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### from .. import utils __all__ = ('cli_l...
68faeb845e50b4038157fc9fc5155bdeb6f3742b
common/apps.py
common/apps.py
from django.apps import AppConfig from django.conf import settings from common.helpers.db import db_is_initialized class CommonConfig(AppConfig): name = 'common' def ready(self): self.display_missing_environment_variables() from common.helpers.tags import import_tags_from_csv if db_is...
import sys from django.apps import AppConfig from django.conf import settings from common.helpers.db import db_is_initialized class CommonConfig(AppConfig): name = 'common' def ready(self): self.display_missing_environment_variables() from common.helpers.tags import import_tags_from_csv ...
Clean content types table and don't load tags when running loaddata
Clean content types table and don't load tags when running loaddata
Python
mit
DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange
<REPLACE_OLD> from <REPLACE_NEW> import sys from <REPLACE_END> <INSERT> 'loaddata' in sys.argv: self.loaddata_clean() elif <INSERT_END> <REPLACE_OLD> ','.join(missing_required_variables)) <REPLACE_NEW> ','.join(missing_required_variables)) def loaddata_clean(self): from django.contrib....
Clean content types table and don't load tags when running loaddata from django.apps import AppConfig from django.conf import settings from common.helpers.db import db_is_initialized class CommonConfig(AppConfig): name = 'common' def ready(self): self.display_missing_environment_variables() ...
d7c3bf6f7176f595198c078003a1fc8e8f50ea0f
molo/core/migrations/0071_remove_old_image_hashes.py
molo/core/migrations/0071_remove_old_image_hashes.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def delete_imageinfo(apps, schema_editor): ImageInfo = apps.get_model('core.ImageInfo') ImageInfo.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('core', '00...
Remove old type of image hashes
Remove old type of image hashes
Python
bsd-2-clause
praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo
<INSERT> # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def delete_imageinfo(apps, schema_editor): <INSERT_END> <INSERT> ImageInfo = apps.get_model('core.ImageInfo') ImageInfo.objects.all().delete() class Migration(migrations.Migration): depende...
Remove old type of image hashes
9448374db62049b6f0209a0b6c3b01f3336e2b2b
talks/core/renderers.py
talks/core/renderers.py
from datetime import datetime from rest_framework import renderers from icalendar import Calendar, Event class ICalRenderer(renderers.BaseRenderer): media_type = 'text/calendar' format = 'ics' def render(self, data, media_type=None, renderer_context=None): cal = Calendar() cal.add('prodi...
from datetime import datetime from rest_framework import renderers from icalendar import Calendar, Event class ICalRenderer(renderers.BaseRenderer): media_type = 'text/calendar' format = 'ics' def render(self, data, media_type=None, renderer_context=None): cal = Calendar() cal.add('prodi...
Refactor method string to date
Refactor method string to date
Python
apache-2.0
ox-it/talks.ox,ox-it/talks.ox,ox-it/talks.ox
<DELETE> # 2015-01-29T18:00:00Z <DELETE_END> <REPLACE_OLD> datetime.strptime(e['start'], "%Y-%m-%dT%H:%M:%SZ")) <REPLACE_NEW> dt_string_to_object(e['start'])) <REPLACE_END> <REPLACE_OLD> event <REPLACE_NEW> event def dt_string_to_object(string): """Transforms a string date into a datetime object ...
Refactor method string to date from datetime import datetime from rest_framework import renderers from icalendar import Calendar, Event class ICalRenderer(renderers.BaseRenderer): media_type = 'text/calendar' format = 'ics' def render(self, data, media_type=None, renderer_context=None): cal = C...
0d31f071b5a5ba76f484ffa49e32f34381b44281
examples/continuous_recordings.py
examples/continuous_recordings.py
#!/usr/bin/env python3 # One common issue is that Saleae records traces into memory, which means that # it can't handle very long captures. This example shows how to use scripting to # do long recordings over time. There will be brief gaps every time Saleae saves # the old recording and starts a new one. import os im...
Add example for repeated / continuous recordings
Add example for repeated / continuous recordings
Python
apache-2.0
ppannuto/python-saleae
<REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python3 # One common issue is that Saleae records traces into memory, which means that # it can't handle very long captures. This example shows how to use scripting to # do long recordings over time. There will be brief gaps every time Saleae saves # the old recording and st...
Add example for repeated / continuous recordings
79e22a810638fbf2098f87525fa5a68d3c3b8c49
hitcount/management/commands/hitcount_cleanup.py
hitcount/management/commands/hitcount_cleanup.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from django.utils import timezone try: from django.core.management.base import BaseCommand except ImportError: from django.core.management.base import NoArgsCommand as BaseCommand ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from django.utils import timezone try: from django.core.management.base import BaseCommand except ImportError: from django.core.management.base import NoArgsCommand as BaseCommand ...
Use count() on queryset instead of len()
Use count() on queryset instead of len() Ensure a fast query even for millions of rows.
Python
mit
thornomad/django-hitcount,thornomad/django-hitcount,thornomad/django-hitcount
<REPLACE_OLD> len(qs) <REPLACE_NEW> qs.count() <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from django.utils import timezone try: from django.core.management.base import BaseCommand except ImportErro...
Use count() on queryset instead of len() Ensure a fast query even for millions of rows. # -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from django.utils import timezone try: from django.core.management.base import BaseCommand exce...
777eeaf61c256f04031d87995b4bccd7a93f1182
lg_mirror/test/test_mirror_scene.py
lg_mirror/test/test_mirror_scene.py
#!/usr/bin/env python import rospy from interactivespaces_msgs.msg import GenericMessage DIRECTOR_MESSAGE = """ { "description": "bogus", "duration": 0, "name": "test whatever", "resource_uri": "bogus", "slug": "test message", "windows": [ { "activity": "mirror", "activity_config": { ...
#!/usr/bin/env python import rospy from interactivespaces_msgs.msg import GenericMessage DIRECTOR_MESSAGE = """ { "description": "bogus", "duration": 0, "name": "test whatever", "resource_uri": "bogus", "slug": "test message", "windows": [ { "activity": "mirror", "activity_config": { ...
Update mirror test scene for single activity
Update mirror test scene for single activity
Python
apache-2.0
EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes
<DELETE> }, { "activity": "mirror", "activity_config": { "viewport": "center" }, "assets": [ ], "width": 450, "height": 800, "presentation_viewport": "right_one", "x_coord": 0, "y_coord": 0 <DELETE_END> <|endoftext|> #!/usr/bin/env python impor...
Update mirror test scene for single activity #!/usr/bin/env python import rospy from interactivespaces_msgs.msg import GenericMessage DIRECTOR_MESSAGE = """ { "description": "bogus", "duration": 0, "name": "test whatever", "resource_uri": "bogus", "slug": "test message", "windows": [ { "activity"...
5c341fc463840bc2e237e1529a43aa5915a70c77
luhn/luhn.py
luhn/luhn.py
# File: luhn.py # Purpose: Write a program that can take a number and determine whether # or not it is valid per the Luhn formula. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 09:55 PM def Luhn(card_number): def digits_of(n): return [in...
# File: luhn.py # Purpose: Write a program that can take a number and determine whether # or not it is valid per the Luhn formula. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 09:55 PM def Luhn(card_number): def digits_of(n): return [in...
Return the remainder of checksum
Return the remainder of checksum
Python
mit
amalshehu/exercism-python
<REPLACE_OLD> sum(odd_digits) def <REPLACE_NEW> sum(odd_digits) for d in even_digits: checksum += sum(digits_of(d*2)) return checksum % 10 def <REPLACE_END> <|endoftext|> # File: luhn.py # Purpose: Write a program that can take a number and determine whether # or not it is valid ...
Return the remainder of checksum # File: luhn.py # Purpose: Write a program that can take a number and determine whether # or not it is valid per the Luhn formula. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 09:55 PM def Luhn(card_number): de...
173565f7f2b9ffa548b355a0cbc8f972f1445a50
tests/test_guess.py
tests/test_guess.py
from rdopkg import guess from collections import namedtuple import pytest VersionTestCase = namedtuple('VersionTestCase', ('expected', 'input_data')) data_table_good = [ VersionTestCase(('1.2.3', None), '1.2.3'), VersionTestCase(('1.2.3', 'vX.Y.Z'), 'v1.2.3'), VersionTestCase(('1.2.3', 'VX.Y.Z'), 'V1.2.3...
Add test coverage for rdopkg.guess version2tag and tag2version
Add test coverage for rdopkg.guess version2tag and tag2version adding coverage unittest, there are some not well handled input cases but better to capture existing behavior and update tests and code to handle things better Change-Id: I16dfb60886a1ac5ddfab86100e08ac23f8cf6c65
Python
apache-2.0
redhat-openstack/rdopkg,redhat-openstack/rdopkg,openstack-packages/rdopkg,openstack-packages/rdopkg
<REPLACE_OLD> <REPLACE_NEW> from rdopkg import guess from collections import namedtuple import pytest VersionTestCase = namedtuple('VersionTestCase', ('expected', 'input_data')) data_table_good = [ VersionTestCase(('1.2.3', None), '1.2.3'), VersionTestCase(('1.2.3', 'vX.Y.Z'), 'v1.2.3'), VersionTestCase...
Add test coverage for rdopkg.guess version2tag and tag2version adding coverage unittest, there are some not well handled input cases but better to capture existing behavior and update tests and code to handle things better Change-Id: I16dfb60886a1ac5ddfab86100e08ac23f8cf6c65
f39a640a8d5bf7d4a5d80f94235d1fa7461bd4dc
s3stash/stash_single_image.py
s3stash/stash_single_image.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os import argparse import logging import json from s3stash.nxstashref_image import NuxeoStashImage def main(argv=None): parser = argparse.ArgumentParser(description='Produce jp2 version of Nuxeo image file and stash in S3.') parser.add_argument('path',...
Add code for stashing a single nuxeo image on s3.
Add code for stashing a single nuxeo image on s3.
Python
bsd-3-clause
barbarahui/nuxeo-calisphere,barbarahui/nuxeo-calisphere
<REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os import argparse import logging import json from s3stash.nxstashref_image import NuxeoStashImage def main(argv=None): parser = argparse.ArgumentParser(description='Produce jp2 version of Nuxeo image file and stash in S3.') ...
Add code for stashing a single nuxeo image on s3.
4b3e2289dbf20c0e2a7e0f83c7bd5963f2aa311f
longshot.py
longshot.py
HOME_URL = 'https://github.com/ftobia/longshot/blob/master/longshot.py' def upgrade(): backup_self() download_and_overwrite() restart() def backup_self(): import shutil new_name = __file__ + '.bak' shutil.copy(__file__, new_name) def download_and_overwrite(): import urllib2 respo...
HOME_URL = 'https://raw.githubusercontent.com/ftobia/longshot/develop/longshot.py' def upgrade(): backup_self() download_and_overwrite() restart() def backup_self(): import shutil new_name = __file__ + '.bak' shutil.copy(__file__, new_name) def download_and_overwrite(): import urllib...
Use the right download URL.
Use the right download URL.
Python
bsd-3-clause
ftobia/longshot
<REPLACE_OLD> 'https://github.com/ftobia/longshot/blob/master/longshot.py' def <REPLACE_NEW> 'https://raw.githubusercontent.com/ftobia/longshot/develop/longshot.py' def <REPLACE_END> <|endoftext|> HOME_URL = 'https://raw.githubusercontent.com/ftobia/longshot/develop/longshot.py' def upgrade(): backup_self()...
Use the right download URL. HOME_URL = 'https://github.com/ftobia/longshot/blob/master/longshot.py' def upgrade(): backup_self() download_and_overwrite() restart() def backup_self(): import shutil new_name = __file__ + '.bak' shutil.copy(__file__, new_name) def download_and_overwrite():...
f012d59f163a8b8a693dc894d211f077ae015d11
Instanssi/kompomaatti/tests.py
Instanssi/kompomaatti/tests.py
from django.test import TestCase from Instanssi.kompomaatti.models import Entry VALID_YOUTUBE_URLS = [ # must handle various protocols in the video URL "http://www.youtube.com/v/asdf123456", "https://www.youtube.com/v/asdf123456/", "//www.youtube.com/v/asdf123456", "www.youtube.com/v/asdf123456", ...
from django.test import TestCase from Instanssi.kompomaatti.models import Entry VALID_YOUTUBE_URLS = [ # must handle various protocols and hostnames in the video URL "http://www.youtube.com/v/asdf123456", "https://www.youtube.com/v/asdf123456/", "//www.youtube.com/v/asdf123456", "www.youtube.com/v...
Add more test data; improve feedback on failing case
kompomaatti: Add more test data; improve feedback on failing case
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
<INSERT> and hostnames <INSERT_END> <INSERT> "youtube.com/v/asdf123456/", <INSERT_END> <REPLACE_OLD> "http://youtu.be/asdf123456/" ] class <REPLACE_NEW> "https://youtu.be/asdf123456/" ] class <REPLACE_END> <DELETE> that various <DELETE_END> <REPLACE_OLD> URLs are parsed properly.""" <REPLACE_NEW> video id extr...
kompomaatti: Add more test data; improve feedback on failing case from django.test import TestCase from Instanssi.kompomaatti.models import Entry VALID_YOUTUBE_URLS = [ # must handle various protocols in the video URL "http://www.youtube.com/v/asdf123456", "https://www.youtube.com/v/asdf123456/", "//...
f80bf4cf1723db814e62753ee4bd5a7c302e09ee
src/project/lda_corpus.py
src/project/lda_corpus.py
import sys import logging from os.path import isdir, isfile from gensim import models from corpus import Corpus logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) class LDACorpus(Corpus): def __init__(self, dict_loc, vec_loc, no_topics=100, update=1, chunksize=10000, pass...
Add basic framework for LDA
Add basic framework for LDA
Python
mit
PinPinIre/Final-Year-Project,PinPinIre/Final-Year-Project,PinPinIre/Final-Year-Project
<REPLACE_OLD> <REPLACE_NEW> import sys import logging from os.path import isdir, isfile from gensim import models from corpus import Corpus logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) class LDACorpus(Corpus): def __init__(self, dict_loc, vec_loc, no_topics=100, up...
Add basic framework for LDA
1d0faecd1f8897e4b9e68cb62cc49125250ff59f
k8s_snapshots/rule.py
k8s_snapshots/rule.py
from typing import Dict, Any import attr @attr.s(slots=True) class Rule: """ A rule describes how and when to make backups. """ volume_name = attr.ib() namespace = attr.ib() deltas = attr.ib() gce_disk = attr.ib() gce_disk_zone = attr.ib() claim_name = attr.ib() @property ...
from typing import Dict, Any import attr @attr.s(slots=True) class Rule: """ A rule describes how and when to make backups. """ name = attr.ib() namespace = attr.ib() deltas = attr.ib() gce_disk = attr.ib() gce_disk_zone = attr.ib() claim_name = attr.ib() @property def...
Fix accidentally commited attribute name change
Fix accidentally commited attribute name change
Python
bsd-2-clause
miracle2k/k8s-snapshots,EQTPartners/k8s-snapshots
<REPLACE_OLD> volume_name <REPLACE_NEW> name <REPLACE_END> <|endoftext|> from typing import Dict, Any import attr @attr.s(slots=True) class Rule: """ A rule describes how and when to make backups. """ name = attr.ib() namespace = attr.ib() deltas = attr.ib() gce_disk = attr.ib() gce...
Fix accidentally commited attribute name change from typing import Dict, Any import attr @attr.s(slots=True) class Rule: """ A rule describes how and when to make backups. """ volume_name = attr.ib() namespace = attr.ib() deltas = attr.ib() gce_disk = attr.ib() gce_disk_zone = attr...
cda81a4585d2b2be868e784566f3c804feb1e9bf
analyze.py
analyze.py
import sys import re def main(argv): # Message to perform sentiment analysis on message = argv[0] if len(argv) > 0 else "" if message == "": print("Usage: python analyze.py [message]") sys.exit(1) # Load the positive and negative words words = {} with open("words/positive.txt"...
import sys import re def main(argv): # Load the positive and negative words words = {} with open("words/positive.txt") as file: for line in file: words[line.rstrip()] = 1 with open("words/negative.txt") as file: for line in file: words[line.rstrip()] = -1 #...
Read from standard input and perform on each line
Read from standard input and perform on each line The analyze script can now be run with, for example - echo "Message" | python analyze.py - cat | python analyze.py (enter messages and end with Ctrl-D) - python analyze.py < filename - MapReduce (at some point)
Python
mit
timvandermeij/sentiment-analysis,timvandermeij/sentiment-analysis
<DELETE> # Message to perform sentiment analysis on message = argv[0] if len(argv) > 0 else "" if message == "": print("Usage: python analyze.py [message]") sys.exit(1) <DELETE_END> <INSERT> for message in sys.stdin: <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> ...
Read from standard input and perform on each line The analyze script can now be run with, for example - echo "Message" | python analyze.py - cat | python analyze.py (enter messages and end with Ctrl-D) - python analyze.py < filename - MapReduce (at some point) import sys import re def main(argv): # Message to pe...
e3a44a03c0aa8166bb6ce6740a82004cfab7a8ab
test/test_examples.py
test/test_examples.py
import os import subprocess import tempfile import nbformat class TestExamples: def _notebook_run(self, path): """ Execute a notebook via nbconvert and collect output. Returns (parsed nb object, execution errors) """ dirname, __ = os.path.split(path) os.chdir(dirna...
Add tests for jupyter notebooks
Add tests for jupyter notebooks
Python
mit
oemof/feedinlib
<REPLACE_OLD> <REPLACE_NEW> import os import subprocess import tempfile import nbformat class TestExamples: def _notebook_run(self, path): """ Execute a notebook via nbconvert and collect output. Returns (parsed nb object, execution errors) """ dirname, __ = os.path.split...
Add tests for jupyter notebooks
641434ef0d1056fecdedbe7dacfe2d915b89408b
undecorated.py
undecorated.py
# -*- coding: utf-8 -*- # Copyright 2016 Ionuț Arțăriși <ionut@artarisi.eu> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required...
# -*- coding: utf-8 -*- # Copyright 2016 Ionuț Arțăriși <ionut@artarisi.eu> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required...
Remove module docstring as we have it on the func
Remove module docstring as we have it on the func
Python
apache-2.0
mapleoin/undecorated
<REPLACE_OLD> License. """Return a function with any decorators removed """ __version__ <REPLACE_NEW> License. __version__ <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- # Copyright 2016 Ionuț Arțăriși <ionut@artarisi.eu> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
Remove module docstring as we have it on the func # -*- coding: utf-8 -*- # Copyright 2016 Ionuț Arțăriși <ionut@artarisi.eu> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www...
efdcc11678aed558fc464ea9e1b1f9351d6e1f8d
Python-practice/fy_print_seq_len_in_fasta.py
Python-practice/fy_print_seq_len_in_fasta.py
#!/usr/bin/env python ''' Script: fy_print_seq_len_in_fasta.py Function: Print sequence length to STDOUT in fasta file Note: Python3 is not default installed for most computer, and the extra-installed module like Biopython could not be directly used by python3. So, it's not the righ time to use Pyth...
#!/usr/bin/env python ''' Script: fy_print_seq_len_in_fasta.py Function: Print sequence length to STDOUT in fasta file Note: Python3 is not default installed for most computer, and the extra-installed module like Biopython could not be directly used by python3. So, it's not the righ time to use Pyth...
Use single quotes instead of double quotes
Use single quotes instead of double quotes
Python
bsd-2-clause
lileiting/gfat
<REPLACE_OLD> seqlen[-1] print("Number <REPLACE_NEW> seqlen[-1] print('Number <REPLACE_END> <REPLACE_OLD> " <REPLACE_NEW> ' <REPLACE_END> <REPLACE_OLD> str(num_of_seq)) print("Total <REPLACE_NEW> str(num_of_seq)) print('Total <REPLACE_END> <REPLACE_OLD> " <REPLACE_NEW> ' <REPLACE_END> <REPLACE_OLD> str(total_len)) pr...
Use single quotes instead of double quotes #!/usr/bin/env python ''' Script: fy_print_seq_len_in_fasta.py Function: Print sequence length to STDOUT in fasta file Note: Python3 is not default installed for most computer, and the extra-installed module like Biopython could not be directly used by python3. ...
a01d306a887eabc912a9e57af0ad862e6c45f652
saleor/cart/__init__.py
saleor/cart/__init__.py
from __future__ import unicode_literals from django.utils.translation import pgettext from satchless import cart from satchless.item import ItemList, ClassifyingPartitioner from ..product.models import DigitalShip class ShippedGroup(ItemList): ''' Group for shippable products. ''' pass class Digit...
from __future__ import unicode_literals from django.utils.translation import pgettext from satchless import cart from satchless.item import ItemList, ClassifyingPartitioner from ..product.models import DigitalShip class ShippedGroup(ItemList): ''' Group for shippable products. ''' pass class Digit...
Use clear cart method from satchless
Use clear cart method from satchless https://github.com/mirumee/satchless/commit/3acaa8f6a27d9ab259a2d66fc3f7416a18fab1ad This reverts commit 2ad16c44adb20e9ba023e873149d67068504c34c.
Python
bsd-3-clause
dashmug/saleor,taedori81/saleor,avorio/saleor,avorio/saleor,tfroehlich82/saleor,arth-co/saleor,laosunhust/saleor,dashmug/saleor,rchav/vinerack,arth-co/saleor,Drekscott/Motlaesaleor,taedori81/saleor,rchav/vinerack,josesanch/saleor,arth-co/saleor,KenMutemi/saleor,paweltin/saleor,KenMutemi/saleor,jreigel/saleor,Drekscott/...
<REPLACE_OLD> self.count()} def clear(self): self._state = [] <REPLACE_NEW> self.count()} <REPLACE_END> <|endoftext|> from __future__ import unicode_literals from django.utils.translation import pgettext from satchless import cart from satchless.item import ItemList, ClassifyingPartitioner from ..produ...
Use clear cart method from satchless https://github.com/mirumee/satchless/commit/3acaa8f6a27d9ab259a2d66fc3f7416a18fab1ad This reverts commit 2ad16c44adb20e9ba023e873149d67068504c34c. from __future__ import unicode_literals from django.utils.translation import pgettext from satchless import cart from satchless.item...
0942d2ccf68b88db2616f9839c1ca1ebfacb8ad9
migration/versions/013_dataset_serp.py
migration/versions/013_dataset_serp.py
from sqlalchemy import * from migrate import * meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine dataset = Table('dataset', meta, autoload=True) serp_title = Column('serp_title', Unicode()) serp_title.create(dataset) serp_teaser = Column('serp_teaser', Unicode()) serp...
Migrate in domain model changes
Migrate in domain model changes
Python
agpl-3.0
johnjohndoe/spendb,CivicVision/datahub,USStateDept/FPA_Core,USStateDept/FPA_Core,spendb/spendb,openspending/spendb,pudo/spendb,johnjohndoe/spendb,nathanhilbert/FPA_Core,spendb/spendb,nathanhilbert/FPA_Core,CivicVision/datahub,spendb/spendb,nathanhilbert/FPA_Core,CivicVision/datahub,openspending/spendb,openspending/spen...
<INSERT> from sqlalchemy import * from migrate import * meta = MetaData() def upgrade(migrate_engine): <INSERT_END> <INSERT> meta.bind = migrate_engine dataset = Table('dataset', meta, autoload=True) serp_title = Column('serp_title', Unicode()) serp_title.create(dataset) serp_teaser = Column('ser...
Migrate in domain model changes
c22c6c3a0927f224cb9a396173292ec2a332a74e
setup.py
setup.py
from setuptools import setup setup( name='polygraph', version='0.1.0', description='Python library for defining GraphQL schemas', url='https://github.com/yen223/polygraph/', author='Wei Yen, Lee', author_email='hello@weiyen.net', license='MIT', install_requires=[ 'marshmallow>=...
from setuptools import setup setup( name='polygraph', version='0.1.0', description='Python library for defining GraphQL schemas', url='https://github.com/yen223/polygraph/', author='Wei Yen, Lee', author_email='hello@weiyen.net', license='MIT', install_requires=[ 'marshmallow>=...
Add isort as a development requirement
Add isort as a development requirement
Python
mit
polygraph-python/polygraph
<INSERT> 'isort', <INSERT_END> <|endoftext|> from setuptools import setup setup( name='polygraph', version='0.1.0', description='Python library for defining GraphQL schemas', url='https://github.com/yen223/polygraph/', author='Wei Yen, Lee', author_email='hello@weiyen.net', lic...
Add isort as a development requirement from setuptools import setup setup( name='polygraph', version='0.1.0', description='Python library for defining GraphQL schemas', url='https://github.com/yen223/polygraph/', author='Wei Yen, Lee', author_email='hello@weiyen.net', license='MIT', i...
9ec35300975a141162749cba015cedbe900f97eb
idiotscript/Collector.py
idiotscript/Collector.py
class Collector(object): def __init__(self): self._groups = [] self._current_group = None def add_input(self, new_input): if self._current_group is None: self._current_group = [] self._current_group.append(new_input) def finalise_group(self): self._group...
class Collector(object): def __init__(self): self._groups = [] self._current_group = None def add_input(self, new_input): if self._current_group is None: self._current_group = [] self._groups.append(self._current_group) self._current_group.append(new_inpu...
Fix bug with collector losing last group of input
Fix bug with collector losing last group of input This means the script runner doesn't have to manually finalise the last input, which was always a bit silly. In fact, the whole metaphor is rather silly. I should change it to be "start new group" instead.
Python
unlicense
djmattyg007/IdiotScript
<INSERT> self._groups.append(self._current_group) <INSERT_END> <DELETE> self._groups.append(self._current_group) <DELETE_END> <|endoftext|> class Collector(object): def __init__(self): self._groups = [] self._current_group = None def add_input(self, new_input): if se...
Fix bug with collector losing last group of input This means the script runner doesn't have to manually finalise the last input, which was always a bit silly. In fact, the whole metaphor is rather silly. I should change it to be "start new group" instead. class Collector(object): def __init__(self): self....
bf82a1437d89f82d417b72cca6274dc35ac7d147
example/urls.py
example/urls.py
from django.conf import settings from django.conf.urls import static from django.contrib import admin from django.urls import path admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings from django.conf.urls import static from django.contrib import admin from django.urls import path admin.autodiscover() urlpatterns = [ path("admin/", admin.site.urls), ] urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Fix correction to comply with black
Fix correction to comply with black
Python
bsd-3-clause
jonasundderwolf/django-localizedfields,jonasundderwolf/django-localizedfields
<REPLACE_OLD> path('admin/', <REPLACE_NEW> path("admin/", <REPLACE_END> <|endoftext|> from django.conf import settings from django.conf.urls import static from django.contrib import admin from django.urls import path admin.autodiscover() urlpatterns = [ path("admin/", admin.site.urls), ] urlpatterns += static.sta...
Fix correction to comply with black from django.conf import settings from django.conf.urls import static from django.contrib import admin from django.urls import path admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.ME...
c2961fbe1746ba61707fb9fc9a0a9873a4abbf33
folium/elements.py
folium/elements.py
from branca.element import Figure, Element, JavascriptLink, CssLink class JSCSSMixin(Element): """Render links to external Javascript and CSS resources.""" default_js = [] default_css = [] def render(self, **kwargs): figure = self.get_root() assert isinstance(figure, Figure), ('You c...
Add mixin to render JS and CSS links
Add mixin to render JS and CSS links
Python
mit
python-visualization/folium,ocefpaf/folium,python-visualization/folium,ocefpaf/folium
<INSERT> from branca.element import Figure, Element, JavascriptLink, CssLink class JSCSSMixin(Element): <INSERT_END> <INSERT> """Render links to external Javascript and CSS resources.""" default_js = [] default_css = [] def render(self, **kwargs): figure = self.get_root() assert isins...
Add mixin to render JS and CSS links
d2883e9c38d0b093c78b2145343b922fd2406cbb
samples/debugger_membp_singlestep.py
samples/debugger_membp_singlestep.py
import sys import os.path import pprint sys.path.append(os.path.abspath(__file__ + "\..\..")) import windows import windows.test import windows.debug import windows.native_exec.simple_x86 as x86 from windows.generated_def.winstructs import * class MyDebugger(windows.debug.Debugger): def __init__(self, *args, *...
Add a sample on memoryBP + singlestep (cc Heurs :D)
Add a sample on memoryBP + singlestep (cc Heurs :D)
Python
bsd-3-clause
hakril/PythonForWindows
<REPLACE_OLD> <REPLACE_NEW> import sys import os.path import pprint sys.path.append(os.path.abspath(__file__ + "\..\..")) import windows import windows.test import windows.debug import windows.native_exec.simple_x86 as x86 from windows.generated_def.winstructs import * class MyDebugger(windows.debug.Debugger): ...
Add a sample on memoryBP + singlestep (cc Heurs :D)
bbb3119c0087ec52185cd275b5dc132868129658
oc/models.py
oc/models.py
class Person: def __init__(self, name, birth_date): self.name = name self.birth_date = birth_date class BirthDate: def __init__(self, year, date): self.year = year self.date = date class Date: def __init__(self, day, month): self.day = day self.month = mon...
class Calendar: def __init__(self, year=2015): self.year = year # TODO get current year self.dates = [] for month in range(1, 13): self.insert_dates(month) def insert_dates(self, month): days = 28 if month in [1, 4, 6, 9, 11]: days = 30 i...
Create Calender with list of all dates
Create Calender with list of all dates
Python
mit
be-ndee/object-calisthenics
<INSERT> Calendar: def __init__(self, year=2015): self.year = year # TODO get current year self.dates = [] for month in range(1, 13): self.insert_dates(month) def insert_dates(self, month): days = 28 if month in [1, 4, 6, 9, 11]: days = 30 ...
Create Calender with list of all dates class Person: def __init__(self, name, birth_date): self.name = name self.birth_date = birth_date class BirthDate: def __init__(self, year, date): self.year = year self.date = date class Date: def __init__(self, day, month): ...
a0dda9abaebd154c8e4fd68206c0f10d796ae75d
tests/property/app_test.py
tests/property/app_test.py
# -*- coding: utf-8 -*- """ Property Test: orchard.app """ import hypothesis import hypothesis.strategies as st import unittest import orchard class AppPropertyTest(unittest.TestCase): def setUp(self): self.app_context = orchard.app.app_context() self.app_context.push() self.client...
# -*- coding: utf-8 -*- """ Property Test: orchard.app """ import hypothesis import hypothesis.strategies as st import unittest import orchard class AppPropertyTest(unittest.TestCase): def setUp(self): self.app_context = orchard.app.app_context() self.app_context.push() self.client...
Remove blank line at end of file.
Remove blank line at end of file.
Python
mit
BMeu/Orchard,BMeu/Orchard
<REPLACE_OLD> data) <REPLACE_NEW> data) <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- """ Property Test: orchard.app """ import hypothesis import hypothesis.strategies as st import unittest import orchard class AppPropertyTest(unittest.TestCase): def setUp(self): self.app_context = orchar...
Remove blank line at end of file. # -*- coding: utf-8 -*- """ Property Test: orchard.app """ import hypothesis import hypothesis.strategies as st import unittest import orchard class AppPropertyTest(unittest.TestCase): def setUp(self): self.app_context = orchard.app.app_context() self.app...
16bd36fe6fdcbd267413eabe1997337165775f28
taOonja/game/admin.py
taOonja/game/admin.py
from django.contrib import admin # Register your models here.
from django.contrib import admin from game.models import * class LocationAdmin(admin.ModelAdmin): model = Location admin.site.register(Location, LocationAdmin) class DetailAdmin(admin.ModelAdmin): model = Detail admin.site.register(Detail, DetailAdmin)
Add models to Admin Panel
Add models to Admin Panel
Python
mit
Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja
<REPLACE_OLD> admin # Register your models here. <REPLACE_NEW> admin from game.models import * class LocationAdmin(admin.ModelAdmin): model = Location admin.site.register(Location, LocationAdmin) class DetailAdmin(admin.ModelAdmin): model = Detail admin.site.register(Detail, DetailAdmin) <REPLACE_END> <...
Add models to Admin Panel from django.contrib import admin # Register your models here.
f5c46ea946f487d6ff445020bac55bd7b137088b
test/widgets/test_wttr.py
test/widgets/test_wttr.py
# Copyright (c) 2021 elParaguayo # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distrib...
Add test for wttr widget
Add test for wttr widget
Python
mit
qtile/qtile,qtile/qtile,ramnes/qtile,ramnes/qtile
<REPLACE_OLD> <REPLACE_NEW> # Copyright (c) 2021 elParaguayo # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
Add test for wttr widget
c557058a7a7206167108535129bc0b160e4fe62b
nipype/testing/tests/test_utils.py
nipype/testing/tests/test_utils.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Test testing utilities """ from nipype.testing.utils import TempFATFS from nose.tools import assert_true def test_tempfatfs(): with TempFATFS() as tmpdir: yield assert_true, tmpdir is not ...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Test testing utilities """ import os import warnings from nipype.testing.utils import TempFATFS from nose.tools import assert_true def test_tempfatfs(): try: fatfs = TempFATFS() except...
Add warning for TempFATFS test
TEST: Add warning for TempFATFS test
Python
bsd-3-clause
mick-d/nipype,carolFrohlich/nipype,FCP-INDI/nipype,sgiavasis/nipype,mick-d/nipype,FCP-INDI/nipype,FCP-INDI/nipype,carolFrohlich/nipype,carolFrohlich/nipype,FCP-INDI/nipype,mick-d/nipype,sgiavasis/nipype,mick-d/nipype,carolFrohlich/nipype,sgiavasis/nipype,sgiavasis/nipype
<REPLACE_OLD> utilities """ from <REPLACE_NEW> utilities """ import os import warnings from <REPLACE_END> <INSERT> try: fatfs = TempFATFS() except IOError: warnings.warn("Cannot mount FAT filesystems <INSERT_END> <REPLACE_OLD> TempFATFS() <REPLACE_NEW> FUSE") else: with fatfs <REPLACE_...
TEST: Add warning for TempFATFS test # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Test testing utilities """ from nipype.testing.utils import TempFATFS from nose.tools import assert_true def test_tempfatfs(): with TempFATFS() as tmpdir: ...
3315ce5ce730f0607c16864e12b6bbb7b2a1c69e
setup.py
setup.py
from distutils.core import setup import sslserver setup(name="django-sslserver", version=sslserver.__version__, author="Ted Dziuba", author_email="tjdziuba@gmail.com", description="An SSL-enabled development server for Django", url="https://github.com/teddziuba/django-sslserver", pa...
from distutils.core import setup import sslserver setup(name="django-sslserver", version=sslserver.__version__, author="Ted Dziuba", author_email="tjdziuba@gmail.com", description="An SSL-enabled development server for Django", url="https://github.com/teddziuba/django-sslserver", pa...
Fix Django dependency: update Django version from 1.4 to 1.8
Fix Django dependency: update Django version from 1.4 to 1.8
Python
mit
teddziuba/django-sslserver
<REPLACE_OLD> 1.4"], <REPLACE_NEW> 1.8"], <REPLACE_END> <|endoftext|> from distutils.core import setup import sslserver setup(name="django-sslserver", version=sslserver.__version__, author="Ted Dziuba", author_email="tjdziuba@gmail.com", description="An SSL-enabled development server for Djan...
Fix Django dependency: update Django version from 1.4 to 1.8 from distutils.core import setup import sslserver setup(name="django-sslserver", version=sslserver.__version__, author="Ted Dziuba", author_email="tjdziuba@gmail.com", description="An SSL-enabled development server for Django", ...
e73bb8cecf516f4379dd7d90282ef2412d348ac8
autotranslate/utils.py
autotranslate/utils.py
import six from autotranslate.compat import importlib from django.conf import settings def perform_import(val, setting_name): """ If the given setting is a string import notation, then perform the necessary import or imports. Credits: https://github.com/tomchristie/django-rest-framework/blob/master/r...
import six from autotranslate.compat import importlib from django.conf import settings def perform_import(val, setting_name): """ If the given setting is a string import notation, then perform the necessary import or imports. Credits: https://github.com/tomchristie/django-rest-framework/blob/master/r...
Make sure we don't expose translator as global
Make sure we don't expose translator as global
Python
mit
ankitpopli1891/django-autotranslate
<REPLACE_OLD> e)) TranslatorService <REPLACE_NEW> e)) def get_translator(): """ Returns the default translator. """ TranslatorService <REPLACE_END> <REPLACE_OLD> 'autotranslate.services.GoSlateTranslatorService') translator <REPLACE_NEW> 'autotranslate.services.GoSlateTranslatorService') tran...
Make sure we don't expose translator as global import six from autotranslate.compat import importlib from django.conf import settings def perform_import(val, setting_name): """ If the given setting is a string import notation, then perform the necessary import or imports. Credits: https://github.com/...
b1dae11860d61e3b574c7bd6b332053819675ddb
tests/test_block_cache.py
tests/test_block_cache.py
import angr import logging l = logging.getLogger("angr.tests") import os test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) def test_block_cache(): p = angr.Project(os.path.join(test_location, "x86_64", "fauxware"), translation_cache=True) b = p.factory.blo...
import angr import logging l = logging.getLogger("angr.tests") import os test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) def test_block_cache(): p = angr.Project(os.path.join(test_location, "x86_64", "fauxware"), translation_cache=True) b = p.factory.blo...
Fix the test case for block cache.
Fix the test case for block cache.
Python
bsd-2-clause
f-prettyland/angr,f-prettyland/angr,axt/angr,chubbymaggie/angr,schieb/angr,schieb/angr,angr/angr,tyb0807/angr,tyb0807/angr,f-prettyland/angr,iamahuman/angr,iamahuman/angr,tyb0807/angr,angr/angr,schieb/angr,iamahuman/angr,chubbymaggie/angr,chubbymaggie/angr,axt/angr,axt/angr,angr/angr
<REPLACE_OLD> p.factory.block(p.entry) <REPLACE_NEW> p.factory.block(p.entry).vex <REPLACE_END> <REPLACE_OLD> b <REPLACE_NEW> b.vex <REPLACE_END> <REPLACE_OLD> p.factory.block(p.entry) <REPLACE_NEW> p.factory.block(p.entry).vex <REPLACE_END> <REPLACE_OLD> b if <REPLACE_NEW> b.vex if <REPLACE_END> <|endoftext|> im...
Fix the test case for block cache. import angr import logging l = logging.getLogger("angr.tests") import os test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) def test_block_cache(): p = angr.Project(os.path.join(test_location, "x86_64", "fauxware"), translati...
3c25f2802f70a16869e93fb301428c31452c00f0
plyer/platforms/macosx/uniqueid.py
plyer/platforms/macosx/uniqueid.py
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) ...
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) ...
Fix TypeError if `LANG` is not set in on osx
Fix TypeError if `LANG` is not set in on osx In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corre...
Python
mit
kivy/plyer,kived/plyer,KeyWeeUsr/plyer,johnbolia/plyer,johnbolia/plyer,kivy/plyer,KeyWeeUsr/plyer,kived/plyer,KeyWeeUsr/plyer,kivy/plyer
<INSERT> if old_lang is None: environ.pop('LANG') else: <INSERT_END> <REPLACE_OLD> old_lang <REPLACE_NEW> old_lang <REPLACE_END> <|endoftext|> from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OS...
Fix TypeError if `LANG` is not set in on osx In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corre...
493aef6b9965bd4fd83fac8a4cdd790b2d8010e2
chainercv/links/connection/seblock.py
chainercv/links/connection/seblock.py
import chainer import chainer.functions as F import chainer.links as L class SEBlock(chainer.Chain): """A squeeze-and-excitation block. This block is part of squeeze-and-excitation networks. Channel-wise multiplication weights are inferred from and applied to input feature map. Please refer to `the ...
import chainer import chainer.functions as F import chainer.links as L class SEBlock(chainer.Chain): """A squeeze-and-excitation block. This block is part of squeeze-and-excitation networks. Channel-wise multiplication weights are inferred from and applied to input feature map. Please refer to `the ...
Simplify SEBlock by broadcast of binary op
Simplify SEBlock by broadcast of binary op instead of explicit broadcast_to. The main motivation of this change is to simplify the exported ONNX, but this would also improve performance.
Python
mit
chainer/chainercv,pfnet/chainercv,chainer/chainercv
<REPLACE_OLD> F.sigmoid(self.up(x)) <REPLACE_NEW> F.sigmoid(self.up(x)) <REPLACE_END> <REPLACE_OLD> F.broadcast_to(x, (H, W, B, C)) x = x.transpose((2, 3, 0, 1)) <REPLACE_NEW> F.reshape(x, x.shape[:2] + (1, 1)) # Spatial axes of `x` will be broadcasted. <REPLACE_END> <|endoftext|> import chainer i...
Simplify SEBlock by broadcast of binary op instead of explicit broadcast_to. The main motivation of this change is to simplify the exported ONNX, but this would also improve performance. import chainer import chainer.functions as F import chainer.links as L class SEBlock(chainer.Chain): """A squeeze-and-excita...
b6b65f0ca7253af5325eafc6b19e7cfecda231b3
hw3/hw3_2b.py
hw3/hw3_2b.py
import sympy x1, x2 = sympy.symbols('x1 x2') f = 8*x1 + 12*x2 + x1**2 -2*x2**2 df_dx1 = sympy.diff(f,x1) df_dx2 = sympy.diff(f,x2) H = sympy.hessian(f, (x1, x2)) xs = sympy.solve([df_dx1, df_dx2], [x1, x2]) H_xs = H.subs([(x1,xs[x1]), (x2,xs[x2])]) lambda_xs = H_xs.eigenvals() count = 0 for i in lambda_xs.keys(): ...
Add solution for exercise 2b of hw3
Add solution for exercise 2b of hw3
Python
bsd-2-clause
escorciav/amcs211,escorciav/amcs211
<INSERT> import sympy x1, x2 = sympy.symbols('x1 x2') f = 8*x1 + 12*x2 + x1**2 -2*x2**2 df_dx1 = sympy.diff(f,x1) df_dx2 = sympy.diff(f,x2) H = sympy.hessian(f, (x1, x2)) xs = sympy.solve([df_dx1, df_dx2], [x1, x2]) H_xs = H.subs([(x1,xs[x1]), (x2,xs[x2])]) lambda_xs = H_xs.eigenvals() count = 0 for i in lambda_xs...
Add solution for exercise 2b of hw3
1c5dbc45213262051ff2472cc0454273d88b82d0
setup.py
setup.py
#!/usr/bin/env python import setuptools import os setuptools.setup( name='endpoints-proto-datastore', version='0.9.0', description='Endpoints Proto Datastore API', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), url='https://github.com/GoogleCloudPlatform/endpoi...
#!/usr/bin/env python import setuptools import os setuptools.setup( name='endpoints-proto-datastore', version='0.9.0', description='Google Cloud Endpoints Proto Datastore Library', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), url='https://github.com/GoogleClo...
Change desc to clearly advertise that this is a library to work with Google Cloud Endpoints
Change desc to clearly advertise that this is a library to work with Google Cloud Endpoints
Python
apache-2.0
jbergant/endpoints-proto-datastore,mnieper/endpoints-proto-datastore,maxandron/endpoints-proto-datastore,dhermes/endpoints-proto-datastore,GoogleCloudPlatform/endpoints-proto-datastore
<REPLACE_OLD> description='Endpoints <REPLACE_NEW> description='Google Cloud Endpoints <REPLACE_END> <REPLACE_OLD> API', <REPLACE_NEW> Library', <REPLACE_END> <|endoftext|> #!/usr/bin/env python import setuptools import os setuptools.setup( name='endpoints-proto-datastore', version='0.9.0', description=...
Change desc to clearly advertise that this is a library to work with Google Cloud Endpoints #!/usr/bin/env python import setuptools import os setuptools.setup( name='endpoints-proto-datastore', version='0.9.0', description='Endpoints Proto Datastore API', long_description=open(os.path.join(os.path.di...
a4135626721efada6a68dab6cb86ce2dfb687462
factory/tools/cat_StarterLog.py
factory/tools/cat_StarterLog.py
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py <logname>" def main(): try:...
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py <logname>" def main(): try:...
Support both old and new format
Support both old and new format
Python
bsd-3-clause
bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,holzman/glideinwms-old
<REPLACE_OLD> gWftLogParser.get_CondorLog(sys.argv[1],"StarterLog.vm2") <REPLACE_NEW> gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") <REPLACE_END> <|endoftext|> #!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logna...
Support both old and new format #!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py...
945d64464857581052e18d79e62a6fde8bdecb9b
fabfile.py
fabfile.py
import sys from fabric.api import local, task @task def start_db(): if sys.platform.startswith('darwin'): # Mac OSX local('postgres -D /usr/local/var/postgres -s')
import sys from pathlib import Path from fabric.api import local, task, lcd, env from fabric.contrib.console import confirm from fabric.utils import abort src_p = Path(env.real_fabfile).parent / 'src' @task def start_db(): if sys.platform.startswith('darwin'): # Mac OSX local('postgres -D /usr/lo...
Add fab command to backup and destroy database
Add fab command to backup and destroy database
Python
mit
ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai
<INSERT> pathlib import Path from <INSERT_END> <REPLACE_OLD> task @task def <REPLACE_NEW> task, lcd, env from fabric.contrib.console import confirm from fabric.utils import abort src_p = Path(env.real_fabfile).parent / 'src' @task def <REPLACE_END> <REPLACE_OLD> -s') <REPLACE_NEW> -s') @task def backup(): cm...
Add fab command to backup and destroy database import sys from fabric.api import local, task @task def start_db(): if sys.platform.startswith('darwin'): # Mac OSX local('postgres -D /usr/local/var/postgres -s')
f74ce9c077054119c04ab65fc0afa4c137204770
comics/comics/basicinstructions.py
comics/comics/basicinstructions.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Basic Instructions" language = "en" url = "http://www.basicinstructions.net/" start_date = "2006-07-01" rights = "Scott Meyer" class Crawler(Cr...
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Basic Instructions" language = "en" url = "http://www.basicinstructions.net/" start_date = "2006-07-01" rights = "Scott Meyer" class Crawler(Cr...
Update "Basic Instructions" after feed change
Update "Basic Instructions" after feed change
Python
agpl-3.0
datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics
<REPLACE_OLD> entry.summary.src('img[src*="/storage/"][src*=".gif"]') <REPLACE_NEW> entry.summary.src("img") <REPLACE_END> <|endoftext|> from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Basic Instructions" ...
Update "Basic Instructions" after feed change from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Basic Instructions" language = "en" url = "http://www.basicinstructions.net/" start_date = "2006-07-01...
2c8dafec701d80ddd9a3d1855a14a8eef0c44790
tests/modules/contrib/test_network_traffic.py
tests/modules/contrib/test_network_traffic.py
import pytest pytest.importorskip("psutil") pytest.importorskip("netifaces") def test_load_module(): __import__("modules.contrib.network_traffic")
import pytest from unittest import TestCase, mock import core.config import core.widget import modules.contrib.network_traffic from types import SimpleNamespace pytest.importorskip("psutil") pytest.importorskip("netifaces") def io_counters_mock(recv, sent): return { 'lo': SimpleNamespace( by...
Add Network Traffic module tests
Add Network Traffic module tests
Python
mit
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
<REPLACE_OLD> pytest pytest.importorskip("psutil") pytest.importorskip("netifaces") def test_load_module(): <REPLACE_NEW> pytest from unittest import TestCase, mock import core.config import core.widget import modules.contrib.network_traffic from types import SimpleNamespace pytest.importorskip("psutil") pytest....
Add Network Traffic module tests import pytest pytest.importorskip("psutil") pytest.importorskip("netifaces") def test_load_module(): __import__("modules.contrib.network_traffic")
01a27d35b6d14d6e5c59646442c22e0d1f98c0cf
examples/ultracoldNeutralPlasma.py
examples/ultracoldNeutralPlasma.py
import ucilib.Sim as Sim import ucilib.BorisUpdater as BorisUpdater import numpy as np # Some helpful constants. fund_charge = 1.602176565e-19 # Mass of Be^+ ions. ion_mass = 8.9465 * 1.673e-27 # Create a simulation with n particles. n = 10000 s = Sim.Sim() s.ptcls.set_nptcls(n) # 1/e radius of cloud. s.ptcls.r...
Add an example simulation setup for an ultracold neutral plasma.
Add an example simulation setup for an ultracold neutral plasma.
Python
mit
Tech-XCorp/ultracold-ions,Tech-XCorp/ultracold-ions,hosseinsadeghi/ultracold-ions,hosseinsadeghi/ultracold-ions
<REPLACE_OLD> <REPLACE_NEW> import ucilib.Sim as Sim import ucilib.BorisUpdater as BorisUpdater import numpy as np # Some helpful constants. fund_charge = 1.602176565e-19 # Mass of Be^+ ions. ion_mass = 8.9465 * 1.673e-27 # Create a simulation with n particles. n = 10000 s = Sim.Sim() s.ptcls.set_nptcls(n) # 1...
Add an example simulation setup for an ultracold neutral plasma.
3081fcd1e37520f504804a3efae62c33d3371a21
temba/msgs/migrations/0034_move_recording_domains.py
temba/msgs/migrations/0034_move_recording_domains.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('msgs', '0033_exportmessagestask_uuid'), ] def move_recording_domains(apps, schema_editor): M...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('msgs', '0033_exportmessagestask_uuid'), ] def move_recording_domains(apps, schema_editor): M...
Tweak to migration so it is a bit faster for future migraters
Tweak to migration so it is a bit faster for future migraters
Python
agpl-3.0
tsotetsi/textily-web,tsotetsi/textily-web,pulilab/rapidpro,praekelt/rapidpro,ewheeler/rapidpro,reyrodrigues/EU-SMS,reyrodrigues/EU-SMS,ewheeler/rapidpro,reyrodrigues/EU-SMS,tsotetsi/textily-web,tsotetsi/textily-web,pulilab/rapidpro,praekelt/rapidpro,tsotetsi/textily-web,praekelt/rapidpro,pulilab/rapidpro,ewheeler/rapid...
<REPLACE_OLD> Msg.objects.filter(msg_type='V').exclude(recording_url=None): <REPLACE_NEW> Msg.objects.filter(direction='I', msg_type='V').exclude(recording_url=None): <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf ...
Tweak to migration so it is a bit faster for future migraters # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('msgs', '0033_exportmessagestask_uuid'), ] ...
35c023f78c2d2c735cba9f6acf504d62d5ac5c83
setup.py
setup.py
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='pybbm-private-messages', version='0...
import os from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='pybbm-private-messages',...
Include custom templatetags in package build.
Include custom templatetags in package build.
Python
mit
skolsuper/pybbm_private_messages,skolsuper/pybbm_private_messages,skolsuper/pybbm_private_messages
<REPLACE_OLD> setup with <REPLACE_NEW> setup, find_packages with <REPLACE_END> <REPLACE_OLD> version='0.2.1', packages=['private_messages', 'private_messages.migrations'], <REPLACE_NEW> version='0.2.2', packages=find_packages(), <REPLACE_END> <|endoftext|> import os from setuptools import setup, find_packag...
Include custom templatetags in package build. import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( ...
8c1f303d4cc04c95170dea268ab836a23d626064
thezombies/management/commands/crawl_agency_datasets.py
thezombies/management/commands/crawl_agency_datasets.py
from django.core.management.base import BaseCommand from thezombies.tasks.main import crawl_agency_datasets class Command(BaseCommand): """Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background""" args = '<agency_id ...>' def hand...
from django.core.management.base import BaseCommand from thezombies.models import Agency from thezombies.tasks.main import crawl_agency_datasets class Command(BaseCommand): """Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background""" a...
Add message for when command is not supplied any arguments.
Add message for when command is not supplied any arguments.
Python
bsd-3-clause
sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies
<INSERT> thezombies.models import Agency from <INSERT_END> <INSERT> else: self.stdout.write(u'Please provide an agency id:\n') agency_list = u'\n'.join(['{0:2d}: {1}'.format(a.id, a.name) for a in Agency.objects.all()]) self.stdout.write(agency_list) self.stdout.wr...
Add message for when command is not supplied any arguments. from django.core.management.base import BaseCommand from thezombies.tasks.main import crawl_agency_datasets class Command(BaseCommand): """Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in...
1716d38b995638c6060faa0925861bd8ab4c0e2b
statsmodels/stats/tests/test_outliers_influence.py
statsmodels/stats/tests/test_outliers_influence.py
from numpy.testing import assert_almost_equal from statsmodels.datasets import statecrime from statsmodels.regression.linear_model import OLS from statsmodels.stats.outliers_influence import reset_ramsey from statsmodels.tools import add_constant data = statecrime.load_pandas().data def test_reset_stata(): mod ...
from numpy.testing import assert_almost_equal from statsmodels.datasets import statecrime, get_rdataset from statsmodels.regression.linear_model import OLS from statsmodels.stats.outliers_influence import reset_ramsey from statsmodels.stats.outliers_influence import variance_inflation_factor from statsmodels.tools imp...
Add pandas dataframe capability in variance_inflation_factor
ENH: Add pandas dataframe capability in variance_inflation_factor
Python
bsd-3-clause
josef-pkt/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,bashtage...
<REPLACE_OLD> statecrime from <REPLACE_NEW> statecrime, get_rdataset from <REPLACE_END> <INSERT> statsmodels.stats.outliers_influence import variance_inflation_factor from <INSERT_END> <REPLACE_OLD> add_constant data <REPLACE_NEW> add_constant import numpy as np data <REPLACE_END> <INSERT> decimal=4) exog_idx =...
ENH: Add pandas dataframe capability in variance_inflation_factor from numpy.testing import assert_almost_equal from statsmodels.datasets import statecrime from statsmodels.regression.linear_model import OLS from statsmodels.stats.outliers_influence import reset_ramsey from statsmodels.tools import add_constant data...
af28c1449cf525460de16304c231616873b2ca3d
tests/test_memory_leak.py
tests/test_memory_leak.py
import resource import pytest from .models import TestModel as DirtyMixinModel pytestmark = pytest.mark.django_db def test_rss_usage(): DirtyMixinModel() rss_1 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss for _ in range(1000): DirtyMixinModel() rss_2 = resource.getrusage(resource.RU...
Add test for detecting memory leaks
Add test for detecting memory leaks
Python
bsd-3-clause
romgar/django-dirtyfields,smn/django-dirtyfields
<INSERT> import resource import pytest from .models import TestModel as DirtyMixinModel pytestmark = pytest.mark.django_db def test_rss_usage(): <INSERT_END> <INSERT> DirtyMixinModel() rss_1 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss for _ in range(1000): DirtyMixinModel() rss_2 = ...
Add test for detecting memory leaks
d5e5ddbd1e1108f327a8d4c27cc18925cf7a3e1a
src/sentry/api/endpoints/project_stats.py
src/sentry/api/endpoints/project_stats.py
from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): def get(self, request, pro...
from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint, DocSection from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): doc_section = ...
Add project stats to docs
Add project stats to docs
Python
bsd-3-clause
looker/sentry,kevinlondon/sentry,pauloschilling/sentry,1tush/sentry,daevaorn/sentry,wong2/sentry,fuziontech/sentry,gencer/sentry,imankulov/sentry,felixbuenemann/sentry,ifduyue/sentry,gg7/sentry,1tush/sentry,camilonova/sentry,hongliang5623/sentry,boneyao/sentry,camilonova/sentry,songyi199111/sentry,llonchj/sentry,mvaled...
<REPLACE_OLD> BaseStatsEndpoint from <REPLACE_NEW> BaseStatsEndpoint, DocSection from <REPLACE_END> <INSERT> doc_section = DocSection.PROJECTS <INSERT_END> <INSERT> """ Retrieve event counts for a project **Draft:** This endpoint may change in the future without notice. Return a set of po...
Add project stats to docs from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): ...
ec42a3cfcb491b265c87160ed9dae0005552acb4
tests/test_result.py
tests/test_result.py
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject @pytest.mark.django_db def test_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh fr...
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject, RelatableObject @pytest.mark.django_db def test_simple_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let t...
Work on testing, bulk indexing, etc
Work on testing, bulk indexing, etc
Python
mit
theonion/djes
<REPLACE_OLD> SimpleObject @pytest.mark.django_db def test_get(es_client): <REPLACE_NEW> SimpleObject, RelatableObject @pytest.mark.django_db def test_simple_get(es_client): <REPLACE_END> <REPLACE_OLD> None <REPLACE_NEW> None with pytest.raises(RelatableObject.DoesNotExist): RelatableObject.search...
Work on testing, bulk indexing, etc from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject @pytest.mark.django_db def test_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.slee...
ce3249dea725d40d5e0916b344cdde53ab6d53dc
src/satosa/micro_services/processors/scope_extractor_processor.py
src/satosa/micro_services/processors/scope_extractor_processor.py
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and ...
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and ...
Make the ScopeExtractorProcessor usable for the Primary Identifier
Make the ScopeExtractorProcessor usable for the Primary Identifier This patch adds support to use the ScopeExtractorProcessor on the Primary Identifiert which is, in contrast to the other values, a string. Closes #348
Python
apache-2.0
SUNET/SATOSA,SUNET/SATOSA,its-dirg/SATOSA
<INSERT> isinstance(values, list): values = [values] if not <INSERT_END> <|endoftext|> from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' ...
Make the ScopeExtractorProcessor usable for the Primary Identifier This patch adds support to use the ScopeExtractorProcessor on the Primary Identifiert which is, in contrast to the other values, a string. Closes #348 from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_pro...
9debed5d1d83bdf2098a7a3841ae4ff272e7ea8e
lib/__init__.py
lib/__init__.py
from client import WebHDFSClient __version__ = '1.0'
from errors import WebHDFSError from client import WebHDFSClient from attrib import WebHDFSObject __version__ = '1.0'
Make other API classes available from base module.
Make other API classes available from base module.
Python
mit
mk23/webhdfs,mk23/webhdfs
<INSERT> errors import WebHDFSError from <INSERT_END> <REPLACE_OLD> WebHDFSClient __version__ <REPLACE_NEW> WebHDFSClient from attrib import WebHDFSObject __version__ <REPLACE_END> <|endoftext|> from errors import WebHDFSError from client import WebHDFSClient from attrib import WebHDFSObject __version__ = '1.0'
Make other API classes available from base module. from client import WebHDFSClient __version__ = '1.0'
9f356ed8f9b975eb82d44454a1e4482f2063b1b1
server_dev.py
server_dev.py
import projects from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @app.route('/blog') def blog(): return "Flasktopress isn't quite ready yet, but we're stoked that ...
import projects from flask import Flask, render_template, abort app = Flask(__name__) @app.route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @app.route('/blog') def blog(): return "Flasktopress isn't quite ready yet, but we're stoke...
Test if a project exists, load or 404 accordingly
Test if a project exists, load or 404 accordingly
Python
mit
teslaworksumn/teslaworks.net,teslaworksumn/teslaworks.net
<REPLACE_OLD> render_template app <REPLACE_NEW> render_template, abort app <REPLACE_END> <INSERT> project_list = projects.get_projects() if project in project_list: project_data = project_list[project] <INSERT_END> <REPLACE_OLD> "Bet you can't wait <REPLACE_NEW> "Contact %s <REPLACE_END> <REPLACE_OL...
Test if a project exists, load or 404 accordingly import projects from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): project_list = projects.get_projects() return render_template('index.html', projects=project_list) @app.route('/blog') def blog(): return "Flaskto...
13b96626a35bc7a430352cf21d6c9a5d206bd910
simplesqlite/loader/formatter.py
simplesqlite/loader/formatter.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import abc import six from .acceptor import LoaderAcceptor from .error import InvalidDataError @six.add_metaclass(abc.ABCMeta) class TableFormatterInterface(object): """ Abstract class ...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import abc import six from .acceptor import LoaderAcceptor from .error import InvalidDataError @six.add_metaclass(abc.ABCMeta) class TableFormatterInterface(object): """ Abstract class ...
Delete a private method from interface
Delete a private method from interface
Python
mit
thombashi/SimpleSQLite,thombashi/SimpleSQLite
<DELETE> # pragma: no cover pass @abc.abstractmethod def _validate_source_data(self): <DELETE_END> <|endoftext|> # encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import abc import six from .acceptor import LoaderAcceptor from ...
Delete a private method from interface # encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import abc import six from .acceptor import LoaderAcceptor from .error import InvalidDataError @six.add_metaclass(abc.ABCMeta) class TableFormatterInterf...