commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
09cfd33df218725aa88d2f64d87868056c2778ba | indra/tests/test_biogrid.py | indra/tests/test_biogrid.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.databases import biogrid_client
from indra.util import unicode_strs
from nose.plugins.attrib import attr
@attr('webservice', 'nonpublic')
def test_biogrid_request():
results = biogrid_client._send_req... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.databases import biogrid_client
from indra.util import unicode_strs
from nose.plugins.attrib import attr
from indra.sources.biogrid import process_file
from indra.statements import Complex
@attr('webservi... | Add test for downloading and parsing biogrid tsv file | Add test for downloading and parsing biogrid tsv file
| Python | bsd-2-clause | johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra,pvtodorov/indra,johnbachman/belpy,bgyori/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra | ---
+++
@@ -3,9 +3,33 @@
from indra.databases import biogrid_client
from indra.util import unicode_strs
from nose.plugins.attrib import attr
+from indra.sources.biogrid import process_file
+from indra.statements import Complex
@attr('webservice', 'nonpublic')
def test_biogrid_request():
results = biogrid_... |
91d50ff929a25345860d9dd91a92473db1fea932 | cla_backend/libs/eligibility_calculator/constants/disposable_income.py | cla_backend/libs/eligibility_calculator/constants/disposable_income.py | LIMIT = 73300
PARTNER_ALLOWANCE = 18191
CHILD_ALLOWANCE = 29149
CHILDLESS_HOUSING_CAP = 54500
EMPLOYMENT_COSTS_ALLOWANCE = 4500
| LIMIT = 73300
PARTNER_ALLOWANCE = 18141
CHILD_ALLOWANCE = 29070
CHILDLESS_HOUSING_CAP = 54500
EMPLOYMENT_COSTS_ALLOWANCE = 4500
| Change dependant allowance amounts to match policy change | Change dependant allowance amounts to match policy change
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | ---
+++
@@ -1,6 +1,6 @@
LIMIT = 73300
-PARTNER_ALLOWANCE = 18191
-CHILD_ALLOWANCE = 29149
+PARTNER_ALLOWANCE = 18141
+CHILD_ALLOWANCE = 29070
CHILDLESS_HOUSING_CAP = 54500
EMPLOYMENT_COSTS_ALLOWANCE = 4500 |
5da62bbe9df92df58dea742120f4e78555509bd0 | lib/log_processor.py | lib/log_processor.py | import re
import snmpy
class log_processor(snmpy.plugin):
def create(self):
for k, v in sorted(self.conf['objects'].items()):
extra = {
'count': re.compile(v['count']),
'reset': re.compile(v['reset']) if 'reset' in v else None,
'start': int(v['... | import glob
import re
import snmpy
class log_processor(snmpy.plugin):
def create(self):
for k, v in sorted(self.conf['objects'].items()):
extra = {
'count': re.compile(v['count']),
'reset': re.compile(v['reset']) if 'reset' in v else None,
'star... | Support file globbing for log processor since names could be dynamic (based on hostname, etc.). | Support file globbing for log processor since names could be dynamic (based on hostname, etc.).
| Python | mit | mk23/snmpy,mk23/snmpy | ---
+++
@@ -1,3 +1,4 @@
+import glob
import re
import snmpy
@@ -18,7 +19,7 @@
@snmpy.plugin.task
def tail(self):
- for line in snmpy.plugin.tail(self.conf['file_name'], True):
+ for line in snmpy.plugin.tail(glob.glob(self.conf['file_name'])[0], True):
if line is True:
... |
0d70cc8fb27240390e252881615f740103535c93 | testsuite/python3.py | testsuite/python3.py | #!/usr/bin/env python3
from typing import ClassVar, List
# Annotated function (Issue #29)
def foo(x: int) -> int:
return x + 1
# Annotated variables #575
CONST: int = 42
class Class:
cls_var: ClassVar[str]
def m(self):
xs: List[int] = []
| #!/usr/bin/env python3
from typing import ClassVar, List
# Annotated function (Issue #29)
def foo(x: int) -> int:
return x + 1
# Annotated variables #575
CONST: int = 42
class Class:
cls_var: ClassVar[str]
for_var: ClassVar[str]
while_var: ClassVar[str]
def_var: ClassVar[str]
if_var: Class... | Add test when variable with annotation start with a keyword | Add test when variable with annotation start with a keyword | Python | mit | PyCQA/pep8 | ---
+++
@@ -13,6 +13,16 @@
class Class:
cls_var: ClassVar[str]
-
+ for_var: ClassVar[str]
+ while_var: ClassVar[str]
+ def_var: ClassVar[str]
+ if_var: ClassVar[str]
+ elif_var: ClassVar[str]
+ else_var: ClassVar[str]
+ try_var: ClassVar[str]
+ except_var: ClassVar[str]
+ finally_va... |
7202c5027158356b8276c118d48609d5b2e1b369 | api/setup.py | api/setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import humbug
import glob
import os.path
from distutils.core import setup
setup(name='humbug',
version=humbug.__version__,
description='Bindings for the Humbug message API',
author='Humbug, Inc.',
author_email='humbug@humbughq.com',
classifi... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import humbug
import glob
import os
from distutils.core import setup
setup(name='humbug',
version=humbug.__version__,
description='Bindings for the Humbug message API',
author='Humbug, Inc.',
author_email='humbug@humbughq.com',
classifiers=[... | Install the demos directory in /usr/local/share/ as well. | Install the demos directory in /usr/local/share/ as well.
(imported from commit 7516e5318f9e30544f53703ead4bca60f2dd7828)
| Python | apache-2.0 | blaze225/zulip,RobotCaleb/zulip,natanovia/zulip,ryanbackman/zulip,andersk/zulip,blaze225/zulip,peguin40/zulip,hackerkid/zulip,deer-hope/zulip,paxapy/zulip,hafeez3000/zulip,susansls/zulip,mohsenSy/zulip,PhilSk/zulip,tdr130/zulip,aakash-cr7/zulip,Diptanshu8/zulip,arpitpanwar/zulip,amallia/zulip,hengqujushi/zulip,christi3... | ---
+++
@@ -4,7 +4,7 @@
import humbug
import glob
-import os.path
+import os
from distutils.core import setup
setup(name='humbug',
@@ -24,7 +24,9 @@
data_files=[('share/humbug/examples', ["examples/humbugrc", "examples/send-message"])] + \
[(os.path.join('share/humbug/', relpath),
... |
72064e373e6b13f5847199aeb8116ab1708523b2 | astroquery/cadc/tests/setup_package.py | astroquery/cadc/tests/setup_package.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import
import os
# setup paths to the test data
# can specify a single file or a list of files
def get_package_data():
paths = [os.path.join('data', '*.vot'),
os.path.join('data', '*.xml'),
o... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import
import os
# setup paths to the test data
# can specify a single file or a list of files
def get_package_data():
paths = [os.path.join('data', '*.vot'),
os.path.join('data', '*.xml'),
o... | Add fits file to package build | Add fits file to package build
| Python | bsd-3-clause | imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery,imbasimba/astroquery | ---
+++
@@ -10,6 +10,7 @@
paths = [os.path.join('data', '*.vot'),
os.path.join('data', '*.xml'),
os.path.join('data', '*.pem'),
+ os.path.join('data', '*.fits'),
] # etc, add other extensions
# you can also enlist files individually by names
# fina... |
1e71dbaa3d82ca757e1e38f114f2153a2d54500e | app/views.py | app/views.py | from flask import Flask, render_template, session, redirect, url_for, flash
from app import app, forms, models
@app.route('/', methods=['GET', 'POST'])
def index():
login_form = forms.LoginForm()
if login_form.validate_on_submit():
user = models.User.query.filter_by(username = login_form.username.data)... | from flask import Flask, render_template, session, redirect, url_for, flash
from app import app, forms, models, db
import datetime
@app.route('/', methods=['GET', 'POST'])
def index():
login_form = forms.LoginForm()
if login_form.validate_on_submit():
user = models.User.query.filter_by(username = login... | Add patient data from the create form to the database. | Add patient data from the create form to the database.
| Python | mit | jawrainey/atc,jawrainey/atc | ---
+++
@@ -1,5 +1,6 @@
from flask import Flask, render_template, session, redirect, url_for, flash
-from app import app, forms, models
+from app import app, forms, models, db
+import datetime
@app.route('/', methods=['GET', 'POST'])
def index():
@@ -24,12 +25,25 @@
@app.route('/create/', methods=['GET', 'POS... |
5ab0e32f3a3b49747b6035cee6dcc1002b5075e1 | path/program_drive_provider.py | path/program_drive_provider.py | import os
from functools import lru_cache
from .. import logger
# use absolute path because of re-occuraing imports '.' could not work
from .program_path_provider import get_cached_program_path
@lru_cache(maxsize=None)
def get_cached_program_drive():
"""Get the value of the #PROGRAMDRIVE# variable"""
rainme... | """
This module provides methods for determine the program drive.
Rainmeter has an built-in variable called #PROGRAMDRIVE#.
With this you can directly route to the drive in which Rainmeter is contained.
If by some chance people use @Include on #PROGRAMDRIVE# it is still able to resolve
the path and open the include fo... | Add docstring to program drive provider | Add docstring to program drive provider
| Python | mit | thatsIch/sublime-rainmeter | ---
+++
@@ -1,3 +1,12 @@
+"""
+This module provides methods for determine the program drive.
+
+Rainmeter has an built-in variable called #PROGRAMDRIVE#.
+With this you can directly route to the drive in which Rainmeter is contained.
+If by some chance people use @Include on #PROGRAMDRIVE# it is still able to resolve... |
d2a024dda2d9032680131b1e8fba38e6bcf0f671 | billjobs/tests/tests_user_admin_api.py | billjobs/tests/tests_user_admin_api.py | from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
from billjobs.views import UserAdmin
class UserAdminAPI(TestCase):
""" Test User Admin API REST endpoint """
... | from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
from billjobs.views import UserAdmin, UserAdminDetail
class UserAdminAPI(TestCase):
""" Test User Admin API REST ... | Add test admin to retrieve a user detail | Add test admin to retrieve a user detail
| Python | mit | ioO/billjobs | ---
+++
@@ -3,7 +3,7 @@
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
-from billjobs.views import UserAdmin
+from billjobs.views import UserAdmin, UserAdminDetail
class UserAdminAPI(TestCase):
""" Test User Admin API REST endpoi... |
6ff6bdad9f7544be103e798838c12509411a2098 | tests/__init__.py | tests/__init__.py | import logging
from unittest import TestCase
import datetime
from redash import settings
settings.DATABASE_CONFIG = {
'name': 'circle_test',
'threadlocals': True
}
settings.REDIS_URL = "redis://localhost:6379/5"
from redash import models, redis_connection
logging.getLogger('peewee').setLevel(logging.INFO)
... | import os
os.environ['REDASH_REDIS_URL'] = "redis://localhost:6379/5"
import logging
from unittest import TestCase
import datetime
from redash import settings
settings.DATABASE_CONFIG = {
'name': 'circle_test',
'threadlocals': True
}
from redash import models, redis_connection
logging.getLogger('peewee').se... | Use the correct redis connection in tests | Use the correct redis connection in tests
| Python | bsd-2-clause | guaguadev/redash,vishesh92/redash,easytaxibr/redash,guaguadev/redash,pubnative/redash,M32Media/redash,vishesh92/redash,rockwotj/redash,amino-data/redash,pubnative/redash,chriszs/redash,alexanderlz/redash,stefanseifert/redash,vishesh92/redash,hudl/redash,ninneko/redash,easytaxibr/redash,akariv/redash,denisov-vlad/redash... | ---
+++
@@ -1,13 +1,15 @@
+import os
+os.environ['REDASH_REDIS_URL'] = "redis://localhost:6379/5"
+
import logging
from unittest import TestCase
import datetime
from redash import settings
+
settings.DATABASE_CONFIG = {
'name': 'circle_test',
'threadlocals': True
}
-
-settings.REDIS_URL = "redis://loc... |
75d6920503b166efd778a6becf0939fe1d2cbe1f | openprescribing/pipeline/management/commands/fetch_prescribing_data.py | openprescribing/pipeline/management/commands/fetch_prescribing_data.py | import os
import requests
from bs4 import BeautifulSoup
from django.conf import settings
from django.core.management import BaseCommand
from openprescribing.utils import mkdir_p
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("year", type=int)
parser.add_argumen... | import os
import requests
from django.conf import settings
from django.core.management import BaseCommand
from openprescribing.utils import mkdir_p
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("year", type=int)
parser.add_argument("month", type=int)
def ... | Use BSA's API to get URL of latest prescribing data | Use BSA's API to get URL of latest prescribing data
| Python | mit | ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing | ---
+++
@@ -1,7 +1,6 @@
import os
import requests
-from bs4 import BeautifulSoup
from django.conf import settings
from django.core.management import BaseCommand
@@ -15,22 +14,27 @@
parser.add_argument("month", type=int)
def handle(self, year, month, **kwargs):
- year_and_month = "{year}... |
3bb560dc03809238f586f78385deb41bba512ba9 | scripts/asgard-deploy.py | scripts/asgard-deploy.py | #!/usr/bin/env python
import sys
import logging
import click
import tubular.asgard as asgard
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
@click.command()
@click.option('--ami_id', envvar='AMI_ID', help='The ami-id to deploy', required=True)
def deploy(ami_id):
try:
asgard.deploy(ami_id)
... | #!/usr/bin/env python
import sys
import logging
import click
from os import path
# Add top-level module path to sys.path before importing tubular code.
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from tubular import asgard
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
@cl... | Add top-level module path before tubular import. | Add top-level module path before tubular import.
| Python | agpl-3.0 | eltoncarr/tubular,eltoncarr/tubular | ---
+++
@@ -2,7 +2,13 @@
import sys
import logging
import click
-import tubular.asgard as asgard
+from os import path
+
+# Add top-level module path to sys.path before importing tubular code.
+sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
+
+from tubular import asgard
+
logging.basic... |
b60b03c5f9ff8b203c309714c06922c2680a244e | tests/test_now.py | tests/test_now.py | # -*- coding: utf-8 -*-
import pytest
from jinja2 import Environment
@pytest.fixture(scope='session')
def environment():
return Environment(extensions=['jinja2_time.TimeExtension'])
def test_foobar(environment):
assert environment
| # -*- coding: utf-8 -*-
from freezegun import freeze_time
from jinja2 import Environment, exceptions
import pytest
@pytest.fixture(scope='session')
def environment():
return Environment(extensions=['jinja2_time.TimeExtension'])
def test_tz_is_required(environment):
with pytest.raises(exceptions.TemplateSyn... | Implement a test for the extensions default datetime format | Implement a test for the extensions default datetime format
| Python | mit | hackebrot/jinja2-time | ---
+++
@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
+from freezegun import freeze_time
+from jinja2 import Environment, exceptions
import pytest
-
-from jinja2 import Environment
@pytest.fixture(scope='session')
@@ -10,5 +10,13 @@
return Environment(extensions=['jinja2_time.TimeExtension'])
-def test_fo... |
8237072384204e51bc281de3dcdfd83e9c85df2d | us_ignite/sections/templatetags/sections_tags.py | us_ignite/sections/templatetags/sections_tags.py | from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
... | from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
... | Make the request context available in the template. | Make the request context available in the template.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -14,10 +14,10 @@
def render(self, context):
template_name = self.template_name.resolve(context)
- template_context = {
+ context.update({
'object_list': Sponsor.objects.all()
- }
- return render_to_string(template_name, template_context)
+ })
... |
63d74ee66e9fe05c07d0032690889b3991e32e1b | logtacts/settings/heroku.py | logtacts/settings/heroku.py | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.config()
SECRET_KEY = get_env_variable("SECRET_KEY")
ALLOWED_HOSTS = [
'localhost',
'127.0.0.1',
'.herokuapp.com',
'.pebble.ink',
]
STATIC_URL = '//logtacts.s3.amazonaws.com/assets... | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.parse(get_env_variable('LOGTACTS_DB_URL'))
SECRET_KEY = get_env_variable("SECRET_KEY")
ALLOWED_HOSTS = [
'localhost',
'127.0.0.1',
'.herokuapp.com',
'.pebble.ink',
]
STATIC_URL = '... | Adjust settings to use specific db url | Adjust settings to use specific db url
| Python | mit | phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts | ---
+++
@@ -4,7 +4,7 @@
DEBUG = False
TEMPLATE_DEBUG = DEBUG
-DATABASES['default'] = dj_database_url.config()
+DATABASES['default'] = dj_database_url.parse(get_env_variable('LOGTACTS_DB_URL'))
SECRET_KEY = get_env_variable("SECRET_KEY")
|
d78ff232acee51f95af3e815e72d3db32cb90533 | apps/privatemsg/management/commands/cleanupprivatemsg.py | apps/privatemsg/management/commands/cleanupprivatemsg.py | """
Management command to cleanup deleted private message database entries.
"""
from django.core.management.base import NoArgsCommand
from apps.privatemsg.models import PrivateMessage
class Command(NoArgsCommand):
"""
A management command which deletes deleted private messages from the database.
Calls `... | """
Management command to cleanup deleted private message from database.
"""
from django.core.management.base import NoArgsCommand
from ...models import PrivateMessage
class Command(NoArgsCommand):
"""
A management command which deletes deleted private messages from the database.
Calls ``PrivateMessage.... | Use relative import and update docstring | Use relative import and update docstring
| Python | agpl-3.0 | TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker | ---
+++
@@ -1,10 +1,10 @@
"""
-Management command to cleanup deleted private message database entries.
+Management command to cleanup deleted private message from database.
"""
from django.core.management.base import NoArgsCommand
-from apps.privatemsg.models import PrivateMessage
+from ...models import Privat... |
0ad4e80daff3441d3d0dc56f6891d6fefb9cedb9 | tinyblog/feeds.py | tinyblog/feeds.py | from datetime import date
from django.conf import settings
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from tinyblog.models import Post
class LatestEntriesFeed(Feed):
def title(self):
return settings.TINYBLOG_TITLE
def description(self):
retu... | from datetime import date
from django.conf import settings
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from tinyblog.models import Post
class LatestEntriesFeed(Feed):
def title(self):
return settings.TINYBLOG_TITLE
def description(self):
retu... | Fix for copyright not showing up in RSS feed | Fix for copyright not showing up in RSS feed
Code coverage showed I was missing a line, because I'd used
the wrong function name. Once I fixed that, I discovered a
bug in the way I was getting the date for the copyright.
| Python | bsd-3-clause | dominicrodger/tinyblog,dominicrodger/tinyblog | ---
+++
@@ -18,9 +18,9 @@
def author_link(self):
return settings.TINYBLOG_AUTHORLINK
- def copyright(self):
+ def feed_copyright(self):
return (u'Copyright (c) %d %s.'
- % (date.now().year, settings.TINYBLOG_AUTHORNAME))
+ % (date.today().year, settings.TIN... |
07b0b608a948e1058aeb40fdfbf5a0425933562d | mcavatar/__init__.py | mcavatar/__init__.py | from redis import Redis
from flask import Flask, g
app = Flask(__name__)
app.config.from_pyfile('config.py')
_redis = Redis(
host=app.config['REDIS_HOST'],
port=app.config['REDIS_PORT'],
db=app.config['REDIS_DB']
)
from mcavatar.views.public import public
from mcavatar.views.img import img
app.register_... | from redis import Redis
from flask import Flask, g
app = Flask(__name__)
app.config.from_pyfile('config.py')
_redis = Redis(
host=app.config['REDIS_HOST'],
port=app.config['REDIS_PORT'],
db=app.config['REDIS_DB']
)
from mcavatar.views.public import public
from mcavatar.views.img import img
app.register_... | Increment total_requests key in redis after each request | Increment total_requests key in redis after each request
| Python | mit | joealcorn/MCAvatar | ---
+++
@@ -20,3 +20,8 @@
@app.before_request
def set_db():
g.redis = _redis
+
+
+@app.teardown_request
+def incr_requests(ex):
+ g.redis.incr('total_requests') |
e1a9f02051038270cdf3377c38c650a27bd65507 | apps/organizations/middleware.py | apps/organizations/middleware.py | from django.http import Http404
from django.shortcuts import get_object_or_404
from .models import Organization
class OrganizationMiddleware(object):
def process_request(self, request):
subdomain = request.subdomain
user = request.user
if subdomain is None:
request.organizat... | from django.http import Http404
from django.shortcuts import get_object_or_404
from .models import Organization
class OrganizationMiddleware(object):
def process_request(self, request):
subdomain = request.subdomain
user = request.user
request.organization = None
if subdomain is... | Set requestion organization to none | Set requestion organization to none
| Python | mit | xobb1t/ddash2013,xobb1t/ddash2013 | ---
+++
@@ -9,6 +9,7 @@
def process_request(self, request):
subdomain = request.subdomain
user = request.user
+ request.organization = None
if subdomain is None:
request.organization = None |
5a710d1013020dcbd66128b1c5235d652c4ef2da | udata/core/badges/forms.py | udata/core/badges/forms.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from udata.forms import ModelForm, fields, validators
from udata.i18n import lazy_gettext as _
from udata.models import Badge
__all__ = ('badge_form', )
def badge_form(model):
'''A form factory for a given model badges'''
class BadgeForm(ModelF... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from udata.forms import ModelForm, fields, validators
from udata.i18n import lazy_gettext as _
from udata.models import Badge
__all__ = ('badge_form', )
def badge_form(model):
'''A form factory for a given model badges'''
class BadgeForm(ModelF... | Switch from the deprecated validators.required() to validators.DataRequired() | Switch from the deprecated validators.required() to validators.DataRequired()
| Python | agpl-3.0 | opendatateam/udata,opendatateam/udata,etalab/udata,etalab/udata,etalab/udata,opendatateam/udata | ---
+++
@@ -14,7 +14,7 @@
model_class = Badge
kind = fields.RadioField(
- _('Kind'), [validators.required()],
+ _('Kind'), [validators.DataRequired()],
choices=model.__badges__.items(),
description=_('Kind of badge (certified, etc)'))
|
ee9df63aeaabb4111cea3698a4f0e30b4502e519 | test/disable_captcha.py | test/disable_captcha.py | import owebunit
import urlparse
from wolis_test_case import WolisTestCase
class AcpLoginTestCase(WolisTestCase):
def test_disable_captcha(self):
self.login('morpheus', 'morpheus')
self.acp_login('morpheus', 'morpheus')
start_url = '/adm/index.php'
self.get_with_sid(start_ur... | import owebunit
import urlparse
from wolis_test_case import WolisTestCase
class AcpLoginTestCase(WolisTestCase):
def test_disable_captcha(self):
self.login('morpheus', 'morpheus')
self.acp_login('morpheus', 'morpheus')
self.change_acp_knob(
link_text='Spambot countermea... | Generalize to allow editing other configuration | Generalize to allow editing other configuration
| Python | bsd-2-clause | p/wolis-phpbb,p/wolis-phpbb | ---
+++
@@ -7,25 +7,33 @@
self.login('morpheus', 'morpheus')
self.acp_login('morpheus', 'morpheus')
+ self.change_acp_knob(
+ link_text='Spambot countermeasures',
+ check_page_text='Enable spambot countermeasures',
+ name='enable_confirm',
+ ... |
d2d6e614bf618428ebd51019b82b6576f2e9c677 | bluebottle/activities/effects.py | bluebottle/activities/effects.py | from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from bluebottle.fsm.effects import Effect
from bluebottle.activities.models import Organizer, OrganizerContribution
class CreateOrganizer(Effect):
"Create an organizer for the activity"
def post_save(self, **kwarg... | from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from bluebottle.fsm.effects import Effect
from bluebottle.activities.models import Organizer, OrganizerContribution
class CreateOrganizer(Effect):
"Create an organizer for the activity"
display = False
def po... | Make sure we can add activities to initiatives in admin | Make sure we can add activities to initiatives in admin
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -8,6 +8,8 @@
class CreateOrganizer(Effect):
"Create an organizer for the activity"
+
+ display = False
def post_save(self, **kwargs):
Organizer.objects.get_or_create(
@@ -21,6 +23,8 @@
class CreateOrganizerContribution(Effect):
"Create an contribution for the organizer of... |
fa88a6e6da009e1279589c76cff1e73abaebae48 | common/djangoapps/track/utils.py | common/djangoapps/track/utils.py | """Utility functions and classes for track backends"""
import json
from datetime import datetime, date
from pytz import UTC
class DateTimeJSONEncoder(json.JSONEncoder):
"""JSON encoder aware of datetime.datetime and datetime.date objects"""
def default(self, obj): # pylint: disable=method-hidden
"... | """Utility functions and classes for track backends"""
import json
from datetime import datetime, date
from pytz import UTC
class DateTimeJSONEncoder(json.JSONEncoder):
"""JSON encoder aware of datetime.datetime and datetime.date objects"""
def default(self, obj): # pylint: disable=method-hidden
"... | Fix the misspell in docstring | style: Fix the misspell in docstring
Datatime -> Datetime
| Python | agpl-3.0 | romain-li/edx-platform,romain-li/edx-platform,romain-li/edx-platform,romain-li/edx-platform,romain-li/edx-platform | ---
+++
@@ -13,7 +13,7 @@
"""
Serialize datetime and date objects of iso format.
- datatime objects are converted to UTC.
+ datetime objects are converted to UTC.
"""
if isinstance(obj, datetime): |
d130a926c847f37f039dfff7c14140d933b7a6af | django/website/contacts/tests/test_group_permissions.py | django/website/contacts/tests/test_group_permissions.py | import pytest
from django.contrib.auth.models import Permission, Group, ContentType
from contacts.group_permissions import GroupPermissions
@pytest.mark.django_db
def test_add_perms():
g1, _ = Group.objects.get_or_create(name="Test Group 1")
g2, _ = Group.objects.get_or_create(name="Test Group 2")
any_m... | import pytest
from django.contrib.auth.models import Permission, Group, ContentType
from django.core.exceptions import ObjectDoesNotExist
from contacts.group_permissions import GroupPermissions
@pytest.mark.django_db
def test_add_perms():
g1, _ = Group.objects.get_or_create(name="Test Group 1")
g2, _ = Grou... | Test can't give group non-exsitent permission | Test can't give group non-exsitent permission
| Python | agpl-3.0 | aptivate/alfie,daniell/kashana,aptivate/alfie,aptivate/kashana,aptivate/alfie,aptivate/alfie,daniell/kashana,daniell/kashana,aptivate/kashana,daniell/kashana,aptivate/kashana,aptivate/kashana | ---
+++
@@ -1,6 +1,7 @@
import pytest
from django.contrib.auth.models import Permission, Group, ContentType
+from django.core.exceptions import ObjectDoesNotExist
from contacts.group_permissions import GroupPermissions
@@ -24,3 +25,19 @@
gp.add_permissions(any_model, *codenames)
assert list(g1.... |
dd444029abd63da594a36f52efbbc72851ac344f | bnw_handlers/command_register.py | bnw_handlers/command_register.py | # -*- coding: utf-8 -*-
#from twisted.words.xish import domish
from base import *
import random
import time
import bnw_core.bnw_objects as objs
def _(s,user):
return s
from uuid import uuid4
import re
@check_arg(name=USER_RE)
@defer.inlineCallbacks
def cmd_register(request,name=""):
""" Регистрация """... | # -*- coding: utf-8 -*-
#from twisted.words.xish import domish
from base import *
import random
import time
import bnw_core.bnw_objects as objs
def _(s,user):
return s
from uuid import uuid4
import re
@check_arg(name=USER_RE)
@defer.inlineCallbacks
def cmd_register(request,name=""):
""" Регистрация """... | Set servicejid setting on register | Set servicejid setting on register
| Python | bsd-2-clause | un-def/bnw,stiletto/bnw,stiletto/bnw,stiletto/bnw,ojab/bnw,ojab/bnw,ojab/bnw,un-def/bnw,un-def/bnw,un-def/bnw,stiletto/bnw,ojab/bnw | ---
+++
@@ -36,6 +36,7 @@
'regdate': int(time.time()),
'jid': request.bare_jid,
'interface': 'redeye',
+ 'settings.servicejid': request.to.split('/',1)[0],
})
if not (yield objs.User.find_one({'name':name})):
... |
80ad2451dabadeeeee6bb632ce6681fac3682b95 | boris/settings/local_template.py | boris/settings/local_template.py | from logging import LOGGING
DEBUG = True
# Don't log to sentry on local.
LOGGING['root']['handlers'] = ['console']
LOGGING['loggers']['django.request'] = {
'level': 'ERROR',
'handlers': ['console'],
'propagate': False,
}
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.te... | DEBUG = True
# Don't log to sentry on local.
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'root': {
'level': 'WARNING',
'handlers': ['console'],
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d ... | Fix up logging on local. | Fix up logging on local.
| Python | mit | fragaria/BorIS,fragaria/BorIS,fragaria/BorIS | ---
+++
@@ -1,13 +1,25 @@
-from logging import LOGGING
-
DEBUG = True
# Don't log to sentry on local.
-LOGGING['root']['handlers'] = ['console']
-LOGGING['loggers']['django.request'] = {
- 'level': 'ERROR',
- 'handlers': ['console'],
- 'propagate': False,
+LOGGING = {
+ 'version': 1,
+ 'disable_exi... |
eda0dc8bdc89e815ff21be91ade9d53f0c13721a | mockito/tests/numpy_test.py | mockito/tests/numpy_test.py | import mockito
from mockito import when, patch
import numpy as np
from . import module
def xcompare(a, b):
if isinstance(a, mockito.matchers.Matcher):
return a.matches(b)
return np.array_equal(a, b)
class TestEnsureNumpyWorks:
def testEnsureNumpyArrayAllowedWhenStubbing(self):
array = ... | import mockito
from mockito import when, patch
import pytest
import numpy as np
from . import module
pytestmark = pytest.mark.usefixtures("unstub")
def xcompare(a, b):
if isinstance(a, mockito.matchers.Matcher):
return a.matches(b)
return np.array_equal(a, b)
class TestEnsureNumpyWorks:
def ... | Make numpy test clearer and ensure unstub | Make numpy test clearer and ensure unstub
| Python | mit | kaste/mockito-python | ---
+++
@@ -1,8 +1,12 @@
import mockito
from mockito import when, patch
+import pytest
import numpy as np
from . import module
+
+
+pytestmark = pytest.mark.usefixtures("unstub")
def xcompare(a, b):
@@ -15,8 +19,9 @@
class TestEnsureNumpyWorks:
def testEnsureNumpyArrayAllowedWhenStubbing(self):
... |
6df1f99592588f68c3aeac4c5808bde3f108be84 | owl2csv.py | owl2csv.py | import sys
import click
import json
import csv
from rdflib import Graph, Namespace, URIRef
def observe_dataset(dataset, query, prefixes):
g = Graph()
if prefixes:
prefixes = json.load(prefixes)
for name, url in prefixes.items():
g.bind(name, Namespace(url.strip('<>')))
g.parse(... | import sys
import click
import json
import csv
from rdflib import Graph, Namespace, URIRef
def observe_dataset(datasets, query, prefixes):
g = Graph()
if prefixes:
prefixes = json.load(prefixes)
for name, url in prefixes.items():
g.bind(name, Namespace(url.strip('<>')))
for dat... | Add support for multiple datasets | Add support for multiple datasets
| Python | mit | Guhogu/owl2csv | ---
+++
@@ -5,13 +5,15 @@
from rdflib import Graph, Namespace, URIRef
-def observe_dataset(dataset, query, prefixes):
+def observe_dataset(datasets, query, prefixes):
g = Graph()
if prefixes:
prefixes = json.load(prefixes)
for name, url in prefixes.items():
g.bind(name, N... |
17cad98d95eeb1c5ae2748fbad0621d0ca460e8b | PrettyJson.py | PrettyJson.py | import sublime
import sublime_plugin
import simplejson as json
from simplejson import OrderedDict
import decimal
s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyjsonCommand(sublime_plugin.TextCommand):
""" Pretty Print JSON
"""
def run(self, edit):
for region in self.view.se... | import sublime
import sublime_plugin
import PrettyJSON.simplejson as json
from PrettyJSON.simplejson import OrderedDict
import decimal
s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyjsonCommand(sublime_plugin.TextCommand):
""" Pretty Print JSON
"""
def run(self, edit):
for ... | Prepend simplejson import with 'module' name | Prepend simplejson import with 'module' name
| Python | mit | dzhibas/SublimePrettyJson | ---
+++
@@ -1,7 +1,7 @@
import sublime
import sublime_plugin
-import simplejson as json
-from simplejson import OrderedDict
+import PrettyJSON.simplejson as json
+from PrettyJSON.simplejson import OrderedDict
import decimal
s = sublime.load_settings("Pretty JSON.sublime-settings") |
43bae84b1359d56ad150b49b38c2f8d400b05af2 | opps/core/cache/managers.py | opps/core/cache/managers.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.core.cache import cache
from django.conf import settings
class CacheManager(models.Manager):
def __cache_key(self, id):
return u'{}:{}:{}'.format(settings.CACHE_PREFIX,
self.model._meta... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.core.cache import cache
from django.conf import settings
def _cache_key(model, id):
return u'{}:{}:{}'.format(settings.CACHE_PREFIX,
model._meta.db_table,
id)
class ... | Fix cache key set, on core cache | Fix cache key set, on core cache
| Python | mit | jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,opps/opps,opps/opps,opps/opps | ---
+++
@@ -5,15 +5,16 @@
from django.conf import settings
+def _cache_key(model, id):
+ return u'{}:{}:{}'.format(settings.CACHE_PREFIX,
+ model._meta.db_table,
+ id)
+
+
class CacheManager(models.Manager):
- def __cache_key(self, id):
- re... |
e3369232014adf29f78975ff102f8e3aec51b81a | corgi/pandas_utils.py | corgi/pandas_utils.py | import math
import numpy as np
def remove_single_value_columns(df):
drop_ix = df.apply(pd.Series.value_counts,
normalize=True,
axis=0).max() == 1
drop_cols = df.columns[drop_ix]
df = df.drop(drop_cols, axis=1)
return df
def sample(df, sample_percent=2e-... | import math
import numpy as np
def remove_single_value_columns(df):
drop_ix = df.apply(pd.Series.value_counts,
normalize=True,
axis=0).max() == 1
drop_cols = df.columns[drop_ix]
df = df.drop(drop_cols, axis=1)
return df
| Remove pandas sample utils, these are built into pandas | Remove pandas sample utils, these are built into pandas
| Python | mit | log0ymxm/corgi | ---
+++
@@ -10,14 +10,3 @@
drop_cols = df.columns[drop_ix]
df = df.drop(drop_cols, axis=1)
return df
-
-
-def sample(df, sample_percent=2e-2):
- sample_n = math.floor(len(df) * sample_percent)
- rows = np.random.choice(df.shape[0], sample_n)
- return df.ix[rows]
-
-
-def sample_columns(df, sam... |
7f91d84cb7e57332ea843aac35ef9fae0a3023f0 | cumulusci/__init__.py | cumulusci/__init__.py | __import__('pkg_resources').declare_namespace('cumulusci')
__version__ = '2.0.0-beta56'
| import os
__import__('pkg_resources').declare_namespace('cumulusci')
__version__ = '2.0.0-beta56'
__location__ = os.path.dirname(os.path.realpath(__file__))
| Add a never changing __location__ attribute to cumulusci to get the root of the cumulusci codebase | Add a never changing __location__ attribute to cumulusci to get the root
of the cumulusci codebase
| Python | bsd-3-clause | SalesforceFoundation/CumulusCI,e02d96ec16/CumulusCI,SalesforceFoundation/CumulusCI,e02d96ec16/CumulusCI | ---
+++
@@ -1,2 +1,4 @@
+import os
__import__('pkg_resources').declare_namespace('cumulusci')
__version__ = '2.0.0-beta56'
+__location__ = os.path.dirname(os.path.realpath(__file__)) |
ca4b4732b4eacb6e1ac0e70bbc384982007d92de | custos/notify/http.py | custos/notify/http.py | import logging
import requests
from .base import Notifier
log = logging.getLogger(__name__)
class HTTPNotifier(Notifier):
''' A Notifier that sends http post request to a given url '''
def __init__(self, auth=None, json=True, **kwargs):
'''
Create a new HTTPNotifier
:param auth: If ... | import logging
import requests
from .base import Notifier
log = logging.getLogger(__name__)
class HTTPNotifier(Notifier):
''' A Notifier that sends http post request to a given url '''
def __init__(self, auth=None, json=True, **kwargs):
'''
Create a new HTTPNotifier
:param auth: If ... | Fix exception handling in HTTPNotifier | Fix exception handling in HTTPNotifier
| Python | mit | fact-project/pycustos | ---
+++
@@ -42,5 +42,8 @@
ret.raise_for_status()
except ConnectionError:
+ # traceback of requests connection errors are really long for
+ # such a simple thing
+ log.error('No connection to {}'.format(recipient))
except:
log.exception('Co... |
a0d9d3f213fb28914040e9647509c897ad8cc41a | skimage/_shared/utils.py | skimage/_shared/utils.py | import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
'''Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use i... | import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
"""Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use i... | Use double instead of single quotes for doc string | Use double instead of single quotes for doc string
| Python | bsd-3-clause | GaZ3ll3/scikit-image,chintak/scikit-image,ajaybhat/scikit-image,warmspringwinds/scikit-image,bennlich/scikit-image,michaelaye/scikit-image,almarklein/scikit-image,michaelpacer/scikit-image,youprofit/scikit-image,almarklein/scikit-image,chintak/scikit-image,WarrenWeckesser/scikits-image,dpshelio/scikit-image,rjeli/sciki... | ---
+++
@@ -6,7 +6,7 @@
class deprecated(object):
- '''Decorator to mark deprecated functions with warning.
+ """Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
@@ -17,7 +17,7 @@
behavior : {'warn', 'raise'}
Beha... |
2142db8de793382bdfc56de9133b320b5d6f2690 | tests/test_vector2_isclose.py | tests/test_vector2_isclose.py | from ppb_vector import Vector2
from utils import vectors
from hypothesis import assume, given, note, example
from hypothesis.strategies import floats
@given(x=vectors(), abs_tol=floats(min_value=0), rel_tol=floats(min_value=0))
def test_isclose_to_self(x, abs_tol, rel_tol):
assert x.isclose(x, abs_tol=abs_tol, re... | from ppb_vector import Vector2
from pytest import raises # type: ignore
from utils import vectors
from hypothesis import assume, given, note, example
from hypothesis.strategies import floats
@given(x=vectors(), abs_tol=floats(min_value=0), rel_tol=floats(min_value=0))
def test_isclose_to_self(x, abs_tol, rel_tol):
... | Test Vector2.isclose with invalid values | Test Vector2.isclose with invalid values
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | ---
+++
@@ -1,4 +1,5 @@
from ppb_vector import Vector2
+from pytest import raises # type: ignore
from utils import vectors
from hypothesis import assume, given, note, example
from hypothesis.strategies import floats
@@ -7,3 +8,13 @@
@given(x=vectors(), abs_tol=floats(min_value=0), rel_tol=floats(min_value=0))
d... |
e39c247f7ba97bdc2e2394f696437a298bd734d5 | api/models.py | api/models.py | from django.db import models
from rest_framework import serializers
class Question(models.Model):
version = models.CharField(primary_key=True, max_length=8)
text = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Choice(mode... | from django.db import models
from rest_framework import serializers
class Question(models.Model):
version = models.CharField(primary_key=True, max_length=8)
text = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Choice(mode... | Rename version field in Choice to question_id | Rename version field in Choice to question_id
| Python | mit | holycattle/pysqueak-api,holycattle/pysqueak-api | ---
+++
@@ -9,7 +9,7 @@
class Choice(models.Model):
text = models.TextField()
- version = models.ForeignKey(Question, on_delete=models.CASCADE)
+ question_id = models.ForeignKey(Question, on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTim... |
acbd2db59024f6b6847193329ca5b83ace9f1202 | refactor/tests/dnstamper.py | refactor/tests/dnstamper.py | from dns import resolver
import gevent
import os
def lookup(hostname, ns):
res = resolver.Resolver(configure=False)
res.nameservers = [ns]
answer = res.query(hostname)
ret = []
for data in answer:
ret.append(data.address)
return ret
def compare_lookups(address):
exp = l... | from dns import resolver
import gevent
import os
def lookup(hostname, ns):
res = resolver.Resolver(configure=False)
res.nameservers = [ns]
answer = res.query(hostname)
ret = []
for data in answer:
ret.append(data.address)
return ret
def compare_lookups(args):
# this is ... | Clean up the DNS test | Clean up the DNS test
| Python | bsd-2-clause | 0xPoly/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,hackerberry/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmur... | ---
+++
@@ -13,9 +13,13 @@
ret.append(data.address)
return ret
-def compare_lookups(address):
- exp = lookup(address, '8.8.8.8')
- control = lookup(address, '208.67.222.222')
+def compare_lookups(args):
+ # this is just a dirty hack
+ address = args[0]
+ ooni = args[1]
+ ns = args[2]... |
4f59ac92fe9aaff621898ee61e76a434c1511e17 | django_wysiwyg/__init__.py | django_wysiwyg/__init__.py | __author__ = 'Daniel Greenfeld, Chris Adams'
VERSION = (0, 5, 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
return version
__version__ = get_version()
def clean_html():
raise ImportError("clean_html requires html5l... | __author__ = 'Daniel Greenfeld, Chris Adams'
VERSION = (0, 5, 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
return version
__version__ = get_version()
def clean_html():
raise ImportError("clean_html requires html5l... | Use relative imports, Python 2.6 style | Use relative imports, Python 2.6 style
| Python | mit | saydulk/django-wysiwyg,pydanny/django-wysiwyg,saydulk/django-wysiwyg,pydanny/django-wysiwyg | ---
+++
@@ -19,11 +19,11 @@
try:
import html5lib
- from utils import clean_html5lib as clean_html
- from utils import sanitize_html5lib as sanitize_html
+ from .utils import clean_html5lib as clean_html
+ from .utils import sanitize_html5lib as sanitize_html
except ImportError:
try:
... |
e5c1cccaa08b519a19b6900db1376f2b75113668 | admin/urls.py | admin/urls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .views import AdminHandler, CubeHandler, ConnectionHandler
INCLUDE_URLS = [
(r"/admin", AdminHandler),
(r"/admin/connection", ConnectionHandler),
(r"/admin/cube/?(?P<slug>[\w-]+)?", CubeHandler),
]
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .views import AdminHandler, CubeHandler, ConnectionHandler
from .views import ElementHandler
INCLUDE_URLS = [
(r"/admin", AdminHandler),
(r"/admin/connection", ConnectionHandler),
(r"/admin/cube/?(?P<slug>[\w-]+)?", CubeHandler),
(r"/admin/element/?(?... | Add Element admin view in admin url | Add Element admin view in admin url
| Python | mit | jgabriellima/mining,AndrzejR/mining,mining/mining,mlgruby/mining,seagoat/mining,mlgruby/mining,jgabriellima/mining,mlgruby/mining,avelino/mining,chrisdamba/mining,seagoat/mining,AndrzejR/mining,chrisdamba/mining,avelino/mining,mining/mining | ---
+++
@@ -1,9 +1,12 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .views import AdminHandler, CubeHandler, ConnectionHandler
+from .views import ElementHandler
+
INCLUDE_URLS = [
(r"/admin", AdminHandler),
(r"/admin/connection", ConnectionHandler),
(r"/admin/cube/?(?P<slug>[\w-]+)?", Cu... |
afb97310cba3c32d28f3b21b0895c53183914326 | interface.py | interface.py | import npyscreen
class App(npyscreen.NPSApp):
def main(self):
form = npyscreen.FormBaseNew(name='EKOiE')
form.add_widget(npyscreen.TitleSelectOne, name='Track number', values=[1, 2, 3, 4, 5])
form.edit()
if __name__ == '__main__':
app = App()
app.run()
| from contextlib import contextmanager
import os
import sys
import npyscreen
@contextmanager
def use_xterm():
"""Helper setting proper TERM value
Required for colors to work under 16-color tmux.
"""
old_value = os.environ.get('TERM')
os.environ['TERM'] = 'xterm'
yield
if old_value is not ... | Quit popup, NPSAppManaged and TERM | Quit popup, NPSAppManaged and TERM
Main class (App) now extends NPSAppManaged, and forms are added in
kosher way. Quit popup is also implemented and available upon
pressing `q` key (`Q` key too!).
Additionally, application sets TERM env variable to proper value
(`xterm`) in order for colors to properly show up under ... | Python | mit | modrzew/ekoie | ---
+++
@@ -1,13 +1,77 @@
+from contextlib import contextmanager
+import os
+import sys
+
import npyscreen
-class App(npyscreen.NPSApp):
- def main(self):
- form = npyscreen.FormBaseNew(name='EKOiE')
- form.add_widget(npyscreen.TitleSelectOne, name='Track number', values=[1, 2, 3, 4, 5])
- ... |
71b2f82d99ffeda9d9435d279c7512fcbaaf108f | trackpy/tests/test_misc.py | trackpy/tests/test_misc.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import os
import unittest
import warnings
import trackpy
import trackpy.diag
path, _ = os.path.split(os.path.abspath(__file__))
class DiagTests(unittest.TestCase):
def test_performance_report(s... | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import os
import unittest
import warnings
import pims
import trackpy
import trackpy.diag
path, _ = os.path.split(os.path.abspath(__file__))
class DiagTests(unittest.TestCase):
def test_performa... | Fix pims warning test under Py3 | TST: Fix pims warning test under Py3
| Python | bsd-3-clause | daniorerio/trackpy,daniorerio/trackpy | ---
+++
@@ -5,6 +5,7 @@
import unittest
import warnings
+import pims
import trackpy
import trackpy.diag
@@ -20,7 +21,13 @@
class APITests(unittest.TestCase):
def test_pims_deprecation(self):
- with warnings.catch_warnings(True) as w:
- warnings.simplefilter('always')
- _ =... |
6a40aab945e28c509e24ede6a48b7ac1f3b89ce2 | product_isp/__manifest__.py | product_isp/__manifest__.py | # Copyright (C) 2019 - TODAY, Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Product ISP',
'version': '12.0.1.0.0',
'license': 'AGPL-3',
'summary': 'Assign ISPs to Products',
'author': 'Open Source Integrators, Odoo Community Association (OCA)',
... | # Copyright (C) 2019 - TODAY, Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Product ISP',
'version': '12.0.1.0.0',
'license': 'AGPL-3',
'summary': 'Assign ISPs to Products',
'author': 'Open Source Integrators, Odoo Community Association (OCA)',
... | Remove unneeded dependency on Inventory | [IMP] Remove unneeded dependency on Inventory
| Python | agpl-3.0 | OCA/vertical-isp,OCA/vertical-isp | ---
+++
@@ -9,7 +9,7 @@
'author': 'Open Source Integrators, Odoo Community Association (OCA)',
"website": 'https://github.com/OCA/vertical-isp',
'depends': [
- 'stock',
+ 'product',
'base_phone_rate'
],
'data': [ |
f49276f78b1b303df5fed063e226ee78165baff5 | spam_lists/exceptions.py | spam_lists/exceptions.py | # -*- coding: utf-8 -*-
'''
This module contains all classes of exceptions raised
by the library
'''
from __future__ import unicode_literals
class SpamListsError(Exception):
'''There was an error during testing a url or host'''
class SpamListsValueError(SpamListsError, ValueError):
'''An inapropriate value ... | # -*- coding: utf-8 -*-
'''
This module contains all classes of exceptions raised
by the library
'''
from __future__ import unicode_literals
class SpamListsError(Exception):
'''There was an error during testing a url or host'''
class SpamListsValueError(SpamListsError, ValueError):
'''An inapropriate value ... | Change bases of exception classes extending SpamListsError and ValueError | Change bases of exception classes extending SpamListsError and ValueError
This commit removes SpamListsError and ValueError as direct base classes
of other exception classes (except SpamListsValueError), and replaces
them with SpamListsValueError.
| Python | mit | piotr-rusin/spam-lists | ---
+++
@@ -18,11 +18,11 @@
'''The classification code from the service was not recognized'''
-class UnathorizedAPIKeyError(SpamListsError, ValueError):
+class UnathorizedAPIKeyError(SpamListsValueError):
'''The API key used to query the service was not authorized'''
-class InvalidHostError(SpamList... |
ba5efae80cf9e1e26399f1e6d9b9c41106a1c2ec | conanfile.py | conanfile.py | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.1"
class ToolingCMakeUtilConan(ConanFile):
name = "tooling-find-pkg-util"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/c... | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class ToolingCMakeUtilConan(ConanFile):
name = "tooling-find-pkg-util"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/c... | Bump version: 0.0.1 -> 0.0.2 | Bump version: 0.0.1 -> 0.0.2
[ci skip]
| Python | mit | polysquare/tooling-find-package-cmake-util,polysquare/tooling-find-package-cmake-util,polysquare/tooling-find-pkg-util,polysquare/tooling-find-pkg-util | ---
+++
@@ -2,7 +2,7 @@
from conans.tools import download, unzip
import os
-VERSION = "0.0.1"
+VERSION = "0.0.2"
class ToolingCMakeUtilConan(ConanFile): |
b0c2262bb50fb51bcc2f5eadb86b353cc9eb38a3 | bin/Bullet.py | bin/Bullet.py | from tkinter import Label
import threading
class Bullet(Label):
def __init__(self, x, y, space):
self.space = space
self.bullet_timer = 0.01
self.bullet_indicator = "'"
self.damage = -100
Label.__init__(self, text=self.bullet_indicator)
self.pack()
self._x =... | from tkinter import Label
import threading
class Bullet(Label):
def __init__(self, x, y, space):
self.space = space
self.bullet_timer = 0.01
self.bullet_indicator = "'"
self.damage = -100
Label.__init__(self, text=self.bullet_indicator)
self.pack()
self._x =... | Add bullet hit function to destroy self. | Add bullet hit function to destroy self.
| Python | mit | emreeroglu/DummyShip | ---
+++
@@ -36,10 +36,12 @@
def set_y(self, value):
self._y += value
for callback in self._observers:
- callback(x=self._x, y=self._y, thing=self)
+ callback(thing=self)
y = property(get_y, set_y)
def bind_to(self, callback):
self._observers.append(c... |
59cd1879efd790d664989d9f506ebdb72f8b6ed3 | portainer/util/fs.py | portainer/util/fs.py |
import os.path
import errno
def touch(path, times=None):
"""Mimics the behavior of the `touch` UNIX command line tool, to create
empty files.
"""
with open(path):
os.utime(path, times)
def mkdir_p(path):
"""Mimics the behavior of the `mkdir -p` UNIX command line took, creating
dire... |
import os.path
import errno
def touch(path, times=None):
"""Mimics the behavior of the `touch` UNIX command line tool, to create
empty files.
"""
with open(path, "a"):
os.utime(path, times)
def mkdir_p(path):
"""Mimics the behavior of the `mkdir -p` UNIX command line took, creating
... | Handle touching files that don't yet exist | Handle touching files that don't yet exist
| Python | mit | duedil-ltd/portainer,duedil-ltd/portainer | ---
+++
@@ -8,7 +8,7 @@
empty files.
"""
- with open(path):
+ with open(path, "a"):
os.utime(path, times)
|
6de094b3b08751a8585c5a492bf009807ff3e1e1 | stringinfo.py | stringinfo.py | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
stringinfo STRING...
Options:
STRING One or more strings for which you want information
"""
from docopt import docopt
import plugins
__author__ = 'peter'
def main():
args = docopt(__doc__)
# Find plugins
ps = plugins.get_plugins()
... | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
stringinfo STRING...
Options:
STRING One or more strings for which you want information
"""
import colorama
from docopt import docopt
import plugins
__author__ = 'peter'
def main():
args = docopt(__doc__)
# Find plugins
ps = plugins.get... | Use colorama to print colors and print a plugin's short_description after running | Use colorama to print colors and print a plugin's short_description after running
| Python | mit | Sakartu/stringinfo | ---
+++
@@ -7,6 +7,7 @@
Options:
STRING One or more strings for which you want information
"""
+import colorama
from docopt import docopt
import plugins
@@ -20,10 +21,14 @@
# Find plugins
ps = plugins.get_plugins()
+ # Initialize colorama
+ colorama.init()
+
# For each plugin, c... |
6fa6ef07dd18794b75d63ffa2a5be83e2ec9b674 | bit/count_ones.py | bit/count_ones.py | """
Write a function that takes an unsigned integer and
returns the number of ’1' bits it has
(also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary
representation 00000000000000000000000000001011,
so the function should return 3.
"""
def count_ones(n):
"""
:type n: int
:rtyp... | """
Write a function that takes an unsigned integer and
returns the number of ’1' bits it has
(also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary
representation 00000000000000000000000000001011,
so the function should return 3.
"""
def count_ones(n):
"""
:type n: int
:rtyp... | Check if the input is negative | Check if the input is negative
As the comments mention, the code would work only for unsigned integers.
If a negative integer is provided as input, then the code runs into an
infinite loop. To avoid this, we are checking if the input is negative.
If yes, then return control before loop is entered.
| Python | mit | amaozhao/algorithms,keon/algorithms | ---
+++
@@ -14,6 +14,8 @@
:type n: int
:rtype: int
"""
+ if n < 0:
+ return
counter = 0
while n:
counter += n & 1 |
cdc63148c00a38ebbfd74879da8d646427627d1f | rasterio/rio/main.py | rasterio/rio/main.py | #!/usr/bin/env python
# main: loader of all the command entry points.
from pkg_resources import iter_entry_points
for entry_point in iter_entry_points('rasterio.rio_commands'):
entry_point.load()
| #!/usr/bin/env python
# main: loader of all the command entry points.
from pkg_resources import iter_entry_points
from rasterio.rio.cli import cli
for entry_point in iter_entry_points('rasterio.rio_commands'):
entry_point.load()
| Add back import of cli. | Add back import of cli.
| Python | bsd-3-clause | youngpm/rasterio,brendan-ward/rasterio,brendan-ward/rasterio,njwilson23/rasterio,kapadia/rasterio,brendan-ward/rasterio,perrygeo/rasterio,johanvdw/rasterio,perrygeo/rasterio,johanvdw/rasterio,johanvdw/rasterio,kapadia/rasterio,njwilson23/rasterio,youngpm/rasterio,youngpm/rasterio,perrygeo/rasterio,njwilson23/rasterio,c... | ---
+++
@@ -3,6 +3,8 @@
from pkg_resources import iter_entry_points
+from rasterio.rio.cli import cli
+
for entry_point in iter_entry_points('rasterio.rio_commands'):
entry_point.load() |
28a457926921ef5e7f57c086d6e6b77a0221348c | carnifex/utils.py | carnifex/utils.py | """
@author: Geir Sporsheim
@license: see LICENCE for details
"""
def attr_string(filterKeys=(), filterValues=(), **kwargs):
return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() if k not in filterKeys and v not in filterValues])
| """
@author: Geir Sporsheim
@license: see LICENCE for details
"""
def attr_string(filterKeys=(), filterValues=(), **kwargs):
"""Build a string consisting of 'key=value' substrings for each keyword
argument in :kwargs:
@param filterKeys: list of key names to ignore
@param filterValues: list of values t... | Add documentation and touch up formatting of attr_string util method | Add documentation and touch up formatting of attr_string util method
| Python | mit | sporsh/carnifex | ---
+++
@@ -4,4 +4,12 @@
"""
def attr_string(filterKeys=(), filterValues=(), **kwargs):
- return ', '.join([str(k)+'='+repr(v) for k, v in kwargs.iteritems() if k not in filterKeys and v not in filterValues])
+ """Build a string consisting of 'key=value' substrings for each keyword
+ argument in :kwargs:... |
b330afbcdc907343ab609a5b000f08e69671116e | sobotka/lib/ssh_config_util.py | sobotka/lib/ssh_config_util.py | from storm.parsers.ssh_config_parser import ConfigParser as StormParser
from os.path import expanduser
def add_host(name, user, hostname, key_file):
sconfig = StormParser(expanduser("~/.ssh/config"))
sconfig.load()
sconfig.add_host(name, {
'user': user,
'hostname': hostname,
'Identi... | from storm.parsers.ssh_config_parser import ConfigParser as StormParser
from os.path import expanduser
def add_host(name, user, hostname, key_file):
sconfig = StormParser(expanduser("~/.ssh/config"))
sconfig.load()
sconfig.add_host(name, {
'user': user,
'hostname': hostname,
'Identi... | Disable strict host checking for ssh | Disable strict host checking for ssh
| Python | mit | looneym/sobotka,looneym/sobotka | ---
+++
@@ -7,7 +7,8 @@
sconfig.add_host(name, {
'user': user,
'hostname': hostname,
- 'IdentityFile': key_file
+ 'IdentityFile': key_file,
+ "StrictHostKeyChecking": "no"
})
sconfig.write_to_ssh_config()
|
f529198d385e63ea657c33c166eb05d43bdcf14a | sensor/core/models/event.py | sensor/core/models/event.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.db import models
VALUE_MAX_LEN = 128
class GenericEvent(models.Model):
"""Represents a measuremen... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.db import models
VALUE_MAX_LEN = 128
class GenericEvent(models.Model):
"""Represents a measuremen... | Add datetime field to Event model in sensor.core | Add datetime field to Event model in sensor.core
| Python | mpl-2.0 | HeisenbergPeople/weather-station-site,HeisenbergPeople/weather-station-site,HeisenbergPeople/weather-station-site | ---
+++
@@ -22,6 +22,7 @@
"""Base class for sensor-specific event types"""
generic_event = models.OneToOneField('core.GenericEvent')
+ datetime = models.DateTimeField()
def value_to_string(self):
"""Event.value_to_string() -> unicode |
db20368ba2531af3d027a25f0b9e71389a8ea7fd | rszio/templatetags/rszio.py | rszio/templatetags/rszio.py | from django import template
from django.urls import reverse
register = template.Library()
@register.simple_tag
def image(img, **kwargs):
# Convert the kwargs to an appropriate string
options = []
for key, value in kwargs.items():
options.append('{key},{value}'.format(key=key, value=value))
... | from django import template
from django.conf import settings
from django.urls import reverse
register = template.Library()
@register.simple_tag
def image(img, **kwargs):
if not img:
if settings.DEBUG:
raise ValueError('No image path defined')
return ''
# Convert the kwargs to an... | Raise ValueError when no path and DEBUG | Raise ValueError when no path and DEBUG
Fails silently when DEBUG is False
| Python | mit | g3rd/django-rszio | ---
+++
@@ -1,4 +1,5 @@
from django import template
+from django.conf import settings
from django.urls import reverse
@@ -7,6 +8,11 @@
@register.simple_tag
def image(img, **kwargs):
+ if not img:
+ if settings.DEBUG:
+ raise ValueError('No image path defined')
+ return ''
+
... |
d0ea4b585ef9523eac528c5a4fba4b0af653cad3 | tests/loginput/test_loginput_index.py | tests/loginput/test_loginput_index.py | from loginput_test_suite import LoginputTestSuite
class TestTestRoute(LoginputTestSuite):
routes = ['/test', '/test/']
status_code = 200
body = ''
# Routes left need to have unit tests written for:
# @route('/veris')
# @route('/veris/')
# @post('/blockip', methods=['POST'])
# @post('/blockip/', methods=... | from loginput_test_suite import LoginputTestSuite
class TestTestRoute(LoginputTestSuite):
routes = ['/test', '/test/']
status_code = 200
body = ''
# Routes left need to have unit tests written for:
# @route('/_bulk',method='POST')
# @route('/_bulk/',method='POST')
# @route('/_status')
# @route('/_status... | Update comments for loginput tests | Update comments for loginput tests
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com>
| Python | mpl-2.0 | jeffbryner/MozDef,mpurzynski/MozDef,Phrozyn/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,gdestuynder/MozDef,ameihm0912/MozDef,gdestuynder/MozDef,mozilla/MozDef,ameihm0912/MozDef,gdestuynder/MozDef,mozilla/MozDef,ameihm0912/MozDef,mpurzynski/MozDef,mozilla/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,jeffbryner/... | ---
+++
@@ -8,20 +8,14 @@
body = ''
# Routes left need to have unit tests written for:
-# @route('/veris')
-# @route('/veris/')
-# @post('/blockip', methods=['POST'])
-# @post('/blockip/', methods=['POST'])
-# @post('/ipwhois', methods=['POST'])
-# @post('/ipwhois/', methods=['POST'])
-# @post('/ipintel', met... |
4a37433c43ffda2443f80cc93c99f9cd76aa6475 | examples/miniapps/movie_lister/movies/__init__.py | examples/miniapps/movie_lister/movies/__init__.py | """Movies package.
Top-level package of movies library. This package contains IoC container of
movies module component providers - ``MoviesModule``. It is recommended to use
movies library functionality by fetching required instances from
``MoviesModule`` providers.
``MoviesModule.finder`` is a factory that provides ... | """Movies package.
Top-level package of movies library. This package contains IoC container of
movies module component providers - ``MoviesModule``. It is recommended to use
movies library functionality by fetching required instances from
``MoviesModule`` providers.
``MoviesModule.finder`` is a factory that provides ... | Add minor fixes to movie lister miniapp | Add minor fixes to movie lister miniapp
| Python | bsd-3-clause | rmk135/objects,ets-labs/python-dependency-injector,ets-labs/dependency_injector,rmk135/dependency_injector | ---
+++
@@ -23,10 +23,10 @@
class MoviesModule(containers.DeclarativeContainer):
"""IoC container of movies module component providers."""
- models_factory = providers.Factory(movies.models.Movie)
+ movie = providers.Factory(movies.models.Movie)
finder = providers.AbstractFactory(movies.finders.M... |
68b7786c83eb16d3e752b4c5ed22c44e0a1aeddb | examples/status_watcher.py | examples/status_watcher.py | import logging
from twisted.internet import reactor
from flist.core import FList_Account
def log_status(data):
logging.debug("{character} is {status}: {statusmsg}".format(**data))
def on_disconnect():
reactor.callLater(60, connect)
def connect():
account = FList_Account('account', 'password')
char =... | import logging
from twisted.internet import reactor
import flist
def log_status(data):
logging.debug("{character} is {status}: {statusmsg}".format(**data))
def on_disconnect():
reactor.callLater(60, connect)
def connect():
account = flist.Account('account', 'password')
char = account.characters['char... | Update example to refactored code | Update example to refactored code
| Python | bsd-2-clause | StormyDragon/python-flist | ---
+++
@@ -1,7 +1,6 @@
import logging
from twisted.internet import reactor
-
-from flist.core import FList_Account
+import flist
def log_status(data):
logging.debug("{character} is {status}: {statusmsg}".format(**data))
@@ -10,10 +9,10 @@
reactor.callLater(60, connect)
def connect():
- account =... |
3aa8734ac9790a8869e01d5d56498dfaf697fe28 | cea/interfaces/dashboard/api/dashboard.py | cea/interfaces/dashboard/api/dashboard.py | from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c... | from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c... | Include plot title to plots | Include plot title to plots
| Python | mit | architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst | ---
+++
@@ -21,7 +21,11 @@
plot_cache = cea.plots.cache.PlotCache(config)
dashboards = cea.plots.read_dashboards(config, plot_cache)
- return [{'name': d.name, 'description': d.description, 'layout': d.layout if d.layout in LAYOUTS else 'row',
- 'plots': [{'title': plot.tit... |
8440ffcfd87814e04188fe4077717e132f285cb2 | ckanext/requestdata/tests/test_helpers.py | ckanext/requestdata/tests/test_helpers.py | # encoding: utf-8
import nose
from datetime import datetime, timedelta
from ckanext.requestdata import helpers as h
import ckan.plugins as p
from ckan.tests import helpers, factories
from ckan import logic
ok_ = nose.tools.ok_
eq_ = nose.tools.eq_
raises = nose.tools.raises
class ActionBase(object):
@classmetho... | # encoding: utf-8
import nose
from datetime import datetime, timedelta
from ckanext.requestdata import helpers as h
import ckan.plugins as p
from ckan.tests import helpers, factories
from ckan import logic
ok_ = nose.tools.ok_
eq_ = nose.tools.eq_
raises = nose.tools.raises
class ActionBase(object):
@classmetho... | Add tests for valid email converter | Add tests for valid email converter
| Python | agpl-3.0 | ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata | ---
+++
@@ -37,3 +37,12 @@
def test_time_ago_from_datetime_valid_string_result(self):
d = datetime.today() - timedelta(days=2)
assert isinstance(h.time_ago_from_datetime(d), str)
+
+ def test_convert_id_to_emails_valid(self):
+ user = factories.User()
+ users = [{'name': user['... |
d4ffa7a0dd5462ad7d2b7eaf720bc8056ca1b859 | medical_medication_us/models/medical_medicament.py | medical_medication_us/models/medical_medicament.py | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import fields, models
class MedicalMedicament(models.Model):
_inherit = 'medical.medicament'
ndc = fields.Char(
string='NDC',
help='National Drug Code for medication... | # -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import fields, models
class MedicalMedicament(models.Model):
_inherit = 'medical.medicament'
ndc = fields.Char(
string='NDC',
help='National Drug Code for medication... | Add gpi and gcn to medicament in medical_medication_us | Add gpi and gcn to medicament in medical_medication_us
| Python | agpl-3.0 | laslabs/vertical-medical,laslabs/vertical-medical | ---
+++
@@ -11,6 +11,14 @@
string='NDC',
help='National Drug Code for medication'
)
+ gpi = fields.Integer(
+ string='GPI',
+ help='Generic Product Identifier',
+ )
+ gcn = fields.Integer(
+ string='GCN',
+ help='Generic Code Number',
+ )
control_cod... |
edecc16f83eadbf836477c46fb056cb6eba5df28 | feder/contrib/sites/migrations/0001_initial.py | feder/contrib/sites/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.contrib.sites.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Site',
fields=[
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.contrib.sites.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Site',
fields=[
... | Fix type in contrib.sites.migrations for Django 2.x compatibility | Fix type in contrib.sites.migrations for Django 2.x compatibility
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder | ---
+++
@@ -26,7 +26,7 @@
'ordering': ('domain',),
},
managers=[
- (b'objects', django.contrib.sites.models.SiteManager()),
+ ('objects', django.contrib.sites.models.SiteManager()),
],
),
] |
b7dfb33e6cf4dd18a2ab626372bedc6b7c269780 | src/adhocracy/adhocracy/catalog/__init__.py | src/adhocracy/adhocracy/catalog/__init__.py | """ Catalog utilities."""
from substanced import catalog
from substanced.interfaces import IIndexingActionProcessor
from zope.interface import Interface
@catalog.catalog_factory('adhocracy')
class AdhocracyCatalogFactory:
tag = catalog.Keyword()
def includeme(config):
"""Register catalog utilities."""
c... | """ Catalog utilities."""
from substanced import catalog
from substanced.interfaces import IIndexingActionProcessor
from zope.interface import Interface
@catalog.catalog_factory('adhocracy')
class AdhocracyCatalogFactory:
tag = catalog.Keyword()
def includeme(config):
"""Register catalog utilities."""
c... | Fix regression: 'import pytest' error when starting adhocracy | Fix regression: 'import pytest' error when starting adhocracy
| Python | agpl-3.0 | liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adh... | ---
+++
@@ -20,4 +20,4 @@
(Interface,),
IIndexingActionProcessor)
config.scan('substanced.catalog')
- config.scan('.')
+ config.add_catalog_factory('adhocracy', AdhocracyCatalogFactory) |
82fec866f384813118411d0485e31b12deaed9f0 | pmst/examples/isotropic_point_source/isotropic_point_source.py | pmst/examples/isotropic_point_source/isotropic_point_source.py | from pmst.source import DirectedPointSource
from pmst.microscope import Microscope
from pmst.detector import Detector
from pmst.geometry import Point
import numpy as np
s = DirectedPointSource(Point(0, 0, 0), n_rays=1e5, direction=Point(0, 0, 1), psi=np.pi/2)
center = Point(0, 0, 2)
x_edge = Point(5, 0, 2)
y_edge = P... | from pmst.source import DirectedPointSource
from pmst.microscope import Microscope
from pmst.detector import Detector
from pmst.geometry import Point
import numpy as np
import time; start = time.time(); print('Running...')
s = DirectedPointSource(Point(0, 0, 0), n_rays=1e5, direction=Point(0, 0, 1), psi=np.pi/2)
cent... | Add timing message to example | Add timing message to example
| Python | mit | talonchandler/pmst | ---
+++
@@ -3,6 +3,7 @@
from pmst.detector import Detector
from pmst.geometry import Point
import numpy as np
+import time; start = time.time(); print('Running...')
s = DirectedPointSource(Point(0, 0, 0), n_rays=1e5, direction=Point(0, 0, 1), psi=np.pi/2)
@@ -20,3 +21,4 @@
src = myfile.readlines()
m.plo... |
ebfcef6ecf0acc202af081e7aa487e50fd7785af | soulmate_finder/__init__.py | soulmate_finder/__init__.py | # allow `soulmate_finder` to be imported
# FIXME: This is bad
# FIXME: WHY IS THIS CAUSING A RUNTIMEWARNING???
# from .__main__ import *
| from .core import *
| Allow package to be imported | Allow package to be imported
| Python | mit | erkghlerngm44/r-anime-soulmate-finder | ---
+++
@@ -1,5 +1 @@
-# allow `soulmate_finder` to be imported
-
-# FIXME: This is bad
-# FIXME: WHY IS THIS CAUSING A RUNTIMEWARNING???
-# from .__main__ import *
+from .core import * |
42e78f7ff795202843085daa65d241cf3fe29d08 | xoinvader/tests/test_level.py | xoinvader/tests/test_level.py | """Test xoinvader.level module."""
from xoinvader.level import Level
# pylint: disable=invalid-name,protected-access,missing-docstring
def test_wave():
e = Level()
# pylint: disable=too-few-public-methods
class MockObject(object):
def __init__(self):
self.value = 0
def add(s... | """Test xoinvader.level module."""
from xoinvader.level import Level
# pylint: disable=invalid-name,protected-access,missing-docstring
def test_level():
e = Level()
# pylint: disable=too-few-public-methods
class MockObject(object):
def __init__(self):
self.value = 0
def add(... | Fix test name, cover speed getter | Fix test name, cover speed getter
Signed-off-by: pkulev <661f9993ccc93424ad20871d2ea98bc2860e5968@gmail.com>
| Python | mit | pkulev/xoinvader,pankshok/xoinvader | ---
+++
@@ -4,7 +4,7 @@
# pylint: disable=invalid-name,protected-access,missing-docstring
-def test_wave():
+def test_level():
e = Level()
# pylint: disable=too-few-public-methods
@@ -22,6 +22,7 @@
e.add_event(20, b.add)
e.speed = 10
+ assert e.speed == 10
e.update()
assert a... |
0c5888aeab12c82d84ead79e4005133e0e91ef21 | dj/manage.py | dj/manage.py | #!/usr/bin/env python
###################################################################
#
# Copyright (c) 2011 Canonical Ltd.
# Copyright (c) 2013 Miing.org <samuel.miing@gmail.com>
#
# This software is licensed under the GNU Affero General Public
# License version 3 (AGPLv3), as published by the Free Software
# F... | #!/usr/bin/env python
###################################################################
#
# Copyright (c) 2011 Canonical Ltd.
# Copyright (c) 2013 Miing.org <samuel.miing@gmail.com>
#
# This software is licensed under the GNU Affero General Public
# License version 3 (AGPLv3), as published by the Free Software
# F... | Fix 'not import from sys' | Fix 'not import from sys'
| Python | agpl-3.0 | miing/mci_migo,miing/mci_migo,miing/mci_migo | ---
+++
@@ -17,6 +17,9 @@
###################################################################
+import os
+import sys
+
import paths
paths.setup_paths()
|
819b0375a2d0386fe349863b11ddba7da77ec1be | node/rand.py | node/rand.py | #!/usr/bin/env python
import datetime
import random
import ephem
from nodes import Node
class Random(Node):
char = "H"
args = 1
results = 1
def random_choice(self, inp:Node.indexable):
"""Choose one in a list randomly"""
return [random.choice(inp)]
def randint(self... | #!/usr/bin/env python
import datetime
import random
import ephem
from nodes import Node
class Random(Node):
char = "H"
args = 1
results = 1
def random_choice(self, inp:Node.indexable):
"""Choose one in a list randomly"""
return [random.choice(inp)]
def randint(self... | Fix get next new moon | Fix get next new moon
| Python | mit | muddyfish/PYKE,muddyfish/PYKE | ---
+++
@@ -22,7 +22,7 @@
return random.randint(0,inp)
def get_next_new_moon(self, time: Node.clock):
- """Gets the date of the next full moon"""
+ """Gets the date of the next new moon"""
new_time = datetime.datetime(*time.time_obj[:7])
- return ephem.next_full_moon(ne... |
d8b3fcb34761af01e87026e3bc5b929bd6b68fc2 | frappe/patches/v11_0/copy_fetch_data_from_options.py | frappe/patches/v11_0/copy_fetch_data_from_options.py | import frappe
def execute():
frappe.reload_doc("core", "doctype", "docfield", force=True)
frappe.reload_doc("custom", "doctype", "custom_field", force=True)
frappe.reload_doc("custom", "doctype", "customize_form_field", force=True)
frappe.reload_doc("custom", "doctype", "property_setter", force=True)
frappe.db.s... | import frappe
def execute():
frappe.reload_doc("core", "doctype", "docfield", force=True)
frappe.reload_doc("custom", "doctype", "custom_field", force=True)
frappe.reload_doc("custom", "doctype", "customize_form_field", force=True)
frappe.reload_doc("custom", "doctype", "property_setter", force=True)
frappe.db.s... | Rename property setter for fetch_from | [fix] Rename property setter for fetch_from
| Python | mit | mhbu50/frappe,frappe/frappe,vjFaLk/frappe,RicardoJohann/frappe,ESS-LLP/frappe,mhbu50/frappe,saurabh6790/frappe,mhbu50/frappe,vjFaLk/frappe,yashodhank/frappe,almeidapaulopt/frappe,RicardoJohann/frappe,yashodhank/frappe,adityahase/frappe,vjFaLk/frappe,ESS-LLP/frappe,yashodhank/frappe,saurabh6790/frappe,RicardoJohann/frap... | ---
+++
@@ -24,7 +24,7 @@
frappe.db.sql('''
update `tabProperty Setter`
- set property="fetch_from"
+ set property="fetch_from", name=concat(doc_type, '-', field_name, '-', property)
where property="options" and value like '%.%'
and property_type in ('Data', 'Read Only', 'Text', 'Small Text', 'Text Edi... |
ee61414cb53dd883d9f5ab60b0148bf0ed9bf3d7 | us_ignite/people/tests/integration_tests.py | us_ignite/people/tests/integration_tests.py | from nose.tools import eq_
from django.contrib.auth.models import User
from django.test import TestCase
from django_nose.tools import assert_redirects
from us_ignite.common.tests import utils
from us_ignite.profiles.tests import fixtures
def _teardown_profiles():
for model in [User]:
model.objects.all()... | from nose.tools import eq_
from django.contrib.auth.models import User
from django.test import TestCase
from django_nose.tools import assert_redirects
from us_ignite.common.tests import utils
from us_ignite.profiles.tests import fixtures
def _teardown_profiles():
for model in [User]:
model.objects.all()... | Update tests to refelct the removal of the users list view. | Update tests to refelct the removal of the users list view.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -13,25 +13,7 @@
model.objects.all().delete()
-class TestPeopleListUnauthenticated(TestCase):
-
- def test_people_list_requires_auth(self):
- url = '/people/'
- response = self.client.get(url)
- assert_redirects(response, utils.get_login_url(url))
-
- def test_people_... |
499b7e95b10c453083d2e0438bfef8a57b330d9a | gui/status/TrayIconView.py | gui/status/TrayIconView.py | import trayjenkins
from PySide import QtGui
from pyjenkins.Event import Event
from trayjenkins.status.interfaces import IView
class TrayIconView(IView):
def __init__(self, parentWidget, delayInSecons):
"""
@type parentWidget: QtGui.QWidget
"""
self._statusRefreshEvent= Event()
... | import trayjenkins
from PySide import QtGui
from pyjenkins.Event import Event
from trayjenkins.status.interfaces import IView
class TrayIconView(IView):
def __init__(self, parentWidget, delayInSecons):
"""
@type parentWidget: QtGui.QWidget
"""
self._statusRefreshEvent= Event()
... | Set icon before calling show() to avoid warning. | Set icon before calling show() to avoid warning.
| Python | mit | coolhandmook/trayjenkins,coolhandmook/trayjenkins | ---
+++
@@ -13,7 +13,6 @@
self._delayInSeconds= delayInSecons
self._trayIcon= QtGui.QSystemTrayIcon(parentWidget)
- self._trayIcon.show()
self._icons= {}
self._icons[trayjenkins.status.FAILING]= QtGui.QIcon('images/status/failing.png')
@@ -21,6 +20,8 @@
self._ic... |
27a1d78611cef1ab23044db22bd4bf7c61582efe | src/data/Track/UploadHandlers/YoutubeUploadHandler.py | src/data/Track/UploadHandlers/YoutubeUploadHandler.py | import os
from data.Track.UploadHandler import UploadHandler
from src.data.Track.Tracks import YoutubeTrack
class YoutubeUploadHandler(UploadHandler):
def __init__(self, workingDir):
super().__init__(workingDir)
self.attributes.update({
"URL": ["string", "required", "url"]
... | import os
from src.data.Track import UploadHandler
from src.data.Track.Tracks import YoutubeTrack
class YoutubeUploadHandler(UploadHandler):
def __init__(self, workingDir):
super().__init__(workingDir)
self.attributes.update({
"URL": ["string", "required", "url"]
})
def... | Fix wrong import from UploadHandler | Fix wrong import from UploadHandler
| Python | agpl-3.0 | Pynitus-Universe/Pynitus-Backend,Pynitus-Universe/Pynitus-Backend,Pynitus-Universe/Pynitus,Pynitus-Universe/Pynitus | ---
+++
@@ -1,7 +1,6 @@
import os
-from data.Track.UploadHandler import UploadHandler
-
+from src.data.Track import UploadHandler
from src.data.Track.Tracks import YoutubeTrack
|
cf94fb86cab2fc892b762b66b760a80ed268e8b3 | social/accounts/__init__.py | social/accounts/__init__.py | """Import and register all account types."""
from abc import ABC, abstractmethod
class Account(ABC):
@abstractmethod
def __init__(self, *breadcrumbs):
"""
Return an Account object corresponding to the breadcrumbs.
This should only be called if "match" returned truthy about matching ... | """Import and register all account types."""
from abc import ABC, abstractmethod
__all__ = ['github']
class Account(ABC):
@abstractmethod
def __init__(self, *breadcrumbs):
"""
Return an Account object corresponding to the breadcrumbs.
This should only be called if "match" returned ... | Add github to the accounts package. | Add github to the accounts package.
| Python | bsd-3-clause | brenns10/social,brenns10/social | ---
+++
@@ -1,6 +1,8 @@
"""Import and register all account types."""
from abc import ABC, abstractmethod
+
+__all__ = ['github']
class Account(ABC): |
504bd5d8bb7ec63747318d16f90d24930e640fc6 | ipython_notebook_config.py | ipython_notebook_config.py | # See http://ipython.org/ipython-doc/1/interactive/public_server.html for more information.
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 6789
c.NotebookApp.open_browser = False
c.NotebookApp.profile = u'default'
import yaml
with open('/import/conf.yaml','... | # See http://ipython.org/ipython-doc/1/interactive/public_server.html for more information.
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 6789
c.NotebookApp.open_browser = False
c.NotebookApp.profile = u'default'
import os
import yaml
config_file_path = ... | Implement fallback mode to make the image unsable without Galaxy | Implement fallback mode to make the image unsable without Galaxy
| Python | mit | bgruening/docker-jupyter-notebook,bgruening/docker-jupyter-notebook,bgruening/docker-ipython-notebook,bgruening/docker-ipython-notebook,bgruening/docker-jupyter-notebook,bgruening/docker-ipython-notebook | ---
+++
@@ -5,8 +5,18 @@
c.NotebookApp.port = 6789
c.NotebookApp.open_browser = False
c.NotebookApp.profile = u'default'
+
+import os
import yaml
-with open('/import/conf.yaml','r') as handle:
- conf = yaml.load(handle)
-c.NotebookApp.base_url = '/ipython/%d/' % conf['docker_port']
-c.NotebookApp.webapp_settin... |
2e8d7952f4508e1cbf8d5d9b321a15bcd3bcf2ed | pylearn2/packaged_dependencies/theano_linear/util.py | pylearn2/packaged_dependencies/theano_linear/util.py |
_ndarray_status_fmt='%(msg)s shape=%(shape)s min=%(min)f max=%(max)f'
def ndarray_status(x, fmt=_ndarray_status_fmt, msg="", **kwargs):
kwargs.update(dict(
msg=msg,
min=x.min(),
max=x.max(),
mean=x.mean(),
var = x.var(),
shape=x.shape))
... |
from imaging import tile_slices_to_image
_ndarray_status_fmt='%(msg)s shape=%(shape)s min=%(min)f max=%(max)f'
def ndarray_status(x, fmt=_ndarray_status_fmt, msg="", **kwargs):
kwargs.update(dict(
msg=msg,
min=x.min(),
max=x.max(),
mean=x.mean(),
var =... | Remove pylearn1 dependency from packaged_dependencies/theano_linear | Remove pylearn1 dependency from packaged_dependencies/theano_linear
| Python | bsd-3-clause | caidongyun/pylearn2,hantek/pylearn2,msingh172/pylearn2,junbochen/pylearn2,sandeepkbhat/pylearn2,pkainz/pylearn2,lunyang/pylearn2,skearnes/pylearn2,cosmoharrigan/pylearn2,lunyang/pylearn2,aalmah/pylearn2,goodfeli/pylearn2,woozzu/pylearn2,mkraemer67/pylearn2,matrogers/pylearn2,goodfeli/pylearn2,skearnes/pylearn2,theoryno... | ---
+++
@@ -1,3 +1,5 @@
+
+from imaging import tile_slices_to_image
_ndarray_status_fmt='%(msg)s shape=%(shape)s min=%(min)f max=%(max)f'
@@ -12,12 +14,3 @@
shape=x.shape))
return fmt%kwargs
-
-# XXX: copy-paste out of pylearn
-try:
- from pylearn.io.image_tiling import tile_slices_to_imag... |
b52037176cd1b8a4d99ff195d72680928ba3790f | cms/djangoapps/export_course_metadata/management/commands/export_course_metadata_for_all_courses.py | cms/djangoapps/export_course_metadata/management/commands/export_course_metadata_for_all_courses.py | """
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import modulestore
from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task
... | """
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import modulestore
from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task
... | Change how we get course ids to avoid memory issues | Change how we get course ids to avoid memory issues
| Python | agpl-3.0 | angelapper/edx-platform,arbrandes/edx-platform,angelapper/edx-platform,eduNEXT/edx-platform,edx/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,eduNEXT/edunext-platform,eduNEXT/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,angelapper/edx-platform,angel... | ---
+++
@@ -27,7 +27,6 @@
"""
Export course metadata for all courses
"""
- module_store = modulestore()
- courses = module_store.get_courses()
+ courses = modulestore().get_course_summaries()
for course in courses:
export_course_metadata_task.delay(str(course.id)) |
cf19c9ad305328f9ab21490e8bdaec4da72adec8 | webmanager/management/commands/keys_default/admin_pass.py | webmanager/management/commands/keys_default/admin_pass.py | default_admin_user = "richard"
default_admin_password = "richard555"
| default_admin_user = "richard"
default_admin_password = "richard666"
| Change default super user password. | Change default super user password.
| Python | bsd-3-clause | weijia/webmanager,weijia/webmanager,weijia/webmanager | ---
+++
@@ -1,2 +1,2 @@
default_admin_user = "richard"
-default_admin_password = "richard555"
+default_admin_password = "richard666" |
a8eff550934730b1b9289796366cc4fe23c669db | stanford/bin/send-email.py | stanford/bin/send-email.py | #!/usr/bin/env python
from email.mime.text import MIMEText
import smtplib
import sys
def send(recipient, sender, subject, body):
message = MIMEText(body, _charset='UTF-8')
message['Subject'] = subject
message['From'] = sender
message['To'] = recipient
smtp = smtplib.SMTP('localhost')
result = s... | #!/usr/bin/env python
from email.mime.text import MIMEText
from subprocess import call
import sys
def send(recipient, sender, sender_name, subject, body):
with open('configuration/stanford/bin/email_params.txt', 'rt') as fin:
with open('email.txt', 'wt') as fout:
for line in fin:
... | Use AWS SMTP server in cut release script. | Use AWS SMTP server in cut release script.
| Python | agpl-3.0 | Stanford-Online/configuration,Stanford-Online/configuration,Stanford-Online/configuration,Stanford-Online/configuration,Stanford-Online/configuration | ---
+++
@@ -1,22 +1,27 @@
#!/usr/bin/env python
from email.mime.text import MIMEText
-import smtplib
+from subprocess import call
import sys
-def send(recipient, sender, subject, body):
- message = MIMEText(body, _charset='UTF-8')
- message['Subject'] = subject
- message['From'] = sender
- message['T... |
f8a160b91cf91a02f36bfd88316c199b914298b2 | src/nodeconductor_assembly_waldur/experts/filters.py | src/nodeconductor_assembly_waldur/experts/filters.py | import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
... | import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
... | Allow to filter expert requests by state | Allow to filter expert requests by state [WAL-1041]
| Python | mit | opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind | ---
+++
@@ -21,7 +21,7 @@
class Meta(object):
model = models.ExpertRequest
- fields = []
+ fields = ['state']
class ExpertBidFilter(django_filters.FilterSet): |
34fa7690fe2255d44b129c7d2397113d713342b6 | test/requests/test-website.py | test/requests/test-website.py | # Run with something like
#
# env GN2_PROFILE=/home/wrk/opt/gn-latest ./bin/genenetwork2 ./etc/default_settings.py -c ../test/requests/test-website.py http://localhost:5003
#
# Mostly to pick up the Guix GN2_PROFILE and python modules
import requests as req
import sys
print "Mechanical Rob firing up..."
if len(sys... | # Run with something like
#
# env GN2_PROFILE=/home/wrk/opt/gn-latest ./bin/genenetwork2 ./etc/default_settings.py -c ../test/requests/test-website.py http://localhost:5003
#
# Mostly to pick up the Guix GN2_PROFILE and python modules
from __future__ import print_function
from link_checker import check_links
import a... | Use argparse to handle arguments | Use argparse to handle arguments
* Use argparse to handle commandline arguments.
* Create initial layout of how the code might end up - lots of the code
is currently commented out.
| Python | agpl-3.0 | genenetwork/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,DannyArends/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2,DannyArends/genenetwork2,pjotrp/genenetwork2,DannyArends/genenetwork2,zsloan/genenetwork2,DannyArends/genenetwork2,DannyArends/genenetwork2,... | ---
+++
@@ -3,18 +3,60 @@
# env GN2_PROFILE=/home/wrk/opt/gn-latest ./bin/genenetwork2 ./etc/default_settings.py -c ../test/requests/test-website.py http://localhost:5003
#
# Mostly to pick up the Guix GN2_PROFILE and python modules
+from __future__ import print_function
+from link_checker import check_links
+im... |
64042be2b6febf64d601adaa6f85a542ae9b876d | sunpy/instr/iris/iris.py | sunpy/instr/iris/iris.py | """
Some very beta tools for IRIS
"""
import sunpy.io
import sunpy.time
import sunpy.map
__all__ = ['SJI_to_cube']
def SJI_to_cube(filename, start=0, stop=None):
"""
Read a SJI file and return a MapCube
..warning::
This function is a very early beta and is not stable. Further work is
... | """
Some very beta tools for IRIS
"""
import sunpy.io
import sunpy.time
import sunpy.map
__all__ = ['SJI_to_cube']
def SJI_to_cube(filename, start=0, stop=None, hdu=0):
"""
Read a SJI file and return a MapCube
..warning::
This function is a very early beta and is not stable. Further work is ... | Change hdu[0] to hdu for optional indexing | Change hdu[0] to hdu for optional indexing
| Python | bsd-2-clause | Alex-Ian-Hamilton/sunpy,dpshelio/sunpy,dpshelio/sunpy,Alex-Ian-Hamilton/sunpy,dpshelio/sunpy,Alex-Ian-Hamilton/sunpy | ---
+++
@@ -8,7 +8,7 @@
__all__ = ['SJI_to_cube']
-def SJI_to_cube(filename, start=0, stop=None):
+def SJI_to_cube(filename, start=0, stop=None, hdu=0):
"""
Read a SJI file and return a MapCube
@@ -27,6 +27,9 @@
stop:
Temporal index to stop MapCube at
+ hdu:
+ Choose... |
2d5c5a1bf693f428b53f8d4a6e788f7be864aa9e | image_site_app/forms.py | image_site_app/forms.py | from django import forms
class SignupForm(forms.Form):
field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']
first_name = forms.CharField(max_length=30, label='First name (optional)', required=False)
last_name = forms.CharField(max_length=30, label='Last name (optional)'... | from django import forms
class SignupForm(forms.Form):
field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']
first_name = forms.CharField(max_length=30,
label='First name (optional)',
required=False,
... | Add placeholder to first_name and last_name fields in signup form | Add placeholder to first_name and last_name fields in signup form
| Python | mit | frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq | ---
+++
@@ -4,8 +4,19 @@
class SignupForm(forms.Form):
field_order = ['username', 'first_name', 'last_name', 'email', 'password', 'password2']
- first_name = forms.CharField(max_length=30, label='First name (optional)', required=False)
- last_name = forms.CharField(max_length=30, label='Last name (optio... |
64bc8ff452d03c7bb026be0b2edd9a047a88b386 | foyer/forcefields/forcefields.py | foyer/forcefields/forcefields.py | import os
import glob
from pkg_resources import resource_filename
from foyer import Forcefield
def get_ff_path():
return [resource_filename('foyer', 'forcefields')]
def get_forcefield_paths(forcefield_name=None):
for dir_path in get_ff_path():
file_pattern = os.path.join(dir_path, 'xml/*.xml')
... | import os
import glob
from pkg_resources import resource_filename
from foyer import Forcefield
def get_ff_path():
return [resource_filename('foyer', 'forcefields')]
def get_forcefield_paths(forcefield_name=None):
for dir_path in get_ff_path():
file_pattern = os.path.join(dir_path, 'xml/*.xml')
... | Make discrete functions for each force field | Make discrete functions for each force field
| Python | mit | mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer,iModels/foyer | ---
+++
@@ -27,5 +27,14 @@
' in path {}'.format(name, get_ff_path()))
return Forcefield(ff_path)
-load_OPLSAA = get_forcefield(name='oplsaa')
-load_TRAPPE_UA = get_forcefield(name='trappe-ua')
+
+def load_OPLSAA():
+ return get_forcefield(name='oplsaa')
+
+
+def load_TRAPPE_UA():
+ retur... |
3fbca600b1b90ad3499d941e178aae89d1c7df70 | regulations/generator/layers/external_citation.py | regulations/generator/layers/external_citation.py | from django.template import loader
import utils
from regulations.generator.layers.base import SearchReplaceLayer
class ExternalCitationLayer(SearchReplaceLayer):
shorthand = 'external'
data_source = 'external-citations'
def __init__(self, layer):
self.layer = layer
self.template = loader... | from django.template import loader
from regulations.generator.layers import utils
from regulations.generator.layers.base import SearchReplaceLayer
class ExternalCitationLayer(SearchReplaceLayer):
shorthand = 'external'
data_source = 'external-citations'
def __init__(self, layer):
self.layer = la... | Make external citations Python3 compatible | Make external citations Python3 compatible
| Python | cc0-1.0 | 18F/regulations-site,18F/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,18F/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,18F/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site | ---
+++
@@ -1,6 +1,6 @@
from django.template import loader
-import utils
+from regulations.generator.layers import utils
from regulations.generator.layers.base import SearchReplaceLayer
|
d7f25a05622f115babacc74e05e20f8c147867c3 | accelerator_abstract/models/base_application_answer.py | accelerator_abstract/models/base_application_answer.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from accelerator_abstract.models.accelerator_model import AcceleratorModel
@python_2_unicode_compatible
class Base... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from accelerator_abstract.models.accelerator_model import AcceleratorModel
@python_2_unicode_compatible
class Base... | Change field type for answer_text | [AC-8296] Change field type for answer_text
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator | ---
+++
@@ -18,7 +18,7 @@
application_question = models.ForeignKey(swapper.get_model_name(
AcceleratorModel.Meta.app_label, 'ApplicationQuestion'),
on_delete=models.CASCADE)
- answer_text = models.CharField(max_length=2000, blank=True)
+ answer_text = models.TextField(blank=True)
c... |
6963b2d42cfee97b57c512a2776df02604da8e5f | polling_stations/apps/data_importers/management/commands/import_reading.py | polling_stations/apps/data_importers/management/commands/import_reading.py | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "RDG"
addresses_name = (
"2022-05-05/2022-03-01T15:11:53.624789/Democracy_Club__05May2022.tsv"
)
stations_name = (
"2022-05-05/2022-03-01T15... | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "RDG"
addresses_name = (
"2022-05-05/2022-03-01T15:11:53.624789/Democracy_Club__05May2022.tsv"
)
stations_name = (
"2022-05-05/2022-03-01T15... | Fix an incorrect postcode for Reading | Fix an incorrect postcode for Reading
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations | ---
+++
@@ -14,9 +14,11 @@
def address_record_to_dict(self, record):
+ if record.property_urn.strip().lstrip("0") == "310088234":
+ record = record._replace(addressline6="RG1 1SN")
+
if record.addressline6 in [
"RG30 4RX",
- "RG1 3NF",
"RG4 8ES"... |
d994294d2c5297635fa36bf7911fbaef6e8e0345 | admin/base/urls.py | admin/base/urls.py | from django.conf.urls import include, url, patterns
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(base_pattern,
include(patterns('',
url(r'^$', views.home, name='h... | from django.conf.urls import include, url, patterns
from django.contrib import admin
from django.views.generic import RedirectView
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(base_pattern,
include(patterns('',
... | Add redirect to /admin/ on Admin app w/ empty URL | Add redirect to /admin/ on Admin app w/ empty URL
| Python | apache-2.0 | crcresearch/osf.io,jnayak1/osf.io,felliott/osf.io,zachjanicki/osf.io,icereval/osf.io,kwierman/osf.io,zamattiac/osf.io,wearpants/osf.io,cwisecarver/osf.io,leb2dg/osf.io,RomanZWang/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,asanfilippo7/osf.io,brandonPur... | ---
+++
@@ -1,5 +1,7 @@
from django.conf.urls import include, url, patterns
from django.contrib import admin
+from django.views.generic import RedirectView
+
from settings import ADMIN_BASE
from . import views
@@ -21,5 +23,6 @@
name='password_reset_complete'),
... |
34061c55be17a19846833148e2cf6e015918efae | frameworks/C/onion/setup.py | frameworks/C/onion/setup.py | import subprocess
import sys
import os
import setup_util
def start(args, logfile, errfile):
setup_util.replace_text("onion/hello.c", "mysql_real_connect\(data.db\[i\], \".*\",", "mysql_real_connect(data.db[i], \"" + args.database_host + "\",")
subprocess.call("rm *.o", cwd="onion", shell=True, stderr=errfile, ... | import subprocess
import sys
import os
import setup_util
def start(args, logfile, errfile):
setup_util.replace_text("onion/hello.c", "mysql_real_connect\(data.db\[i\], \".*\",", "mysql_real_connect(data.db[i], \"" + args.database_host + "\",")
subprocess.call("rm -f *.o", cwd="onion", shell=True, stderr=errfil... | Remove minor errors in onion | Remove minor errors in onion
| Python | bsd-3-clause | alubbe/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,sxend/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jamming/FrameworkBenchmarks,torhve/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,ratpack/FrameworkBenchmar... | ---
+++
@@ -6,8 +6,8 @@
def start(args, logfile, errfile):
setup_util.replace_text("onion/hello.c", "mysql_real_connect\(data.db\[i\], \".*\",", "mysql_real_connect(data.db[i], \"" + args.database_host + "\",")
- subprocess.call("rm *.o", cwd="onion", shell=True, stderr=errfile, stdout=logfile)
- subprocess... |
c90f279d9555f1f21e6bc80348c7ebe7156e94a4 | wiblog/formatting.py | wiblog/formatting.py | from django.utils.safestring import mark_safe
import markdown
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
return mark_safe(markdown.markdown(value, output_format="html5"))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
i... | from django.utils.safestring import mark_safe
import markdown
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
return mark_safe(markdown.markdown(value, output_format="html5"))
# Get a summary of a post
def summarize(fullBody):
firstNewline = fullBody.find("\n")
i... | Fix UTF-8 Bug In summarize Function | Fix UTF-8 Bug In summarize Function
| Python | agpl-3.0 | lo-windigo/fragdev,lo-windigo/fragdev | ---
+++
@@ -12,6 +12,6 @@
firstNewline = fullBody.find("\n")
if firstNewline > 0:
- return str(fullBody)[:firstNewline]
+ return unicode(fullBody)[:firstNewline]
return fullBody |
9a84ffde3909c74a47049c65e3b2bb5038a2cfaa | sillymap/burrows_wheeler.py | sillymap/burrows_wheeler.py |
def burrows_wheeler(text):
"""Returns the burrows wheeler transform of <text>.
The text is assumed to not contain the character $"""
text += "$"
all_permutations = []
for i in range(len(text)):
all_permutations.append(text[i:] + text[:i])
all_permutations.sort()
return "".join([w... |
def burrows_wheeler(text):
"""Calculates the burrows wheeler transform of <text>.
returns the burrows wheeler string and the suffix array indices
The text is assumed to not contain the character $"""
text += "$"
all_permutations = []
for i in range(len(text)):
all_permutations.append(... | Return suffix array indices from burrows wheeler | Return suffix array indices from burrows wheeler
| Python | mit | alneberg/sillymap | ---
+++
@@ -1,13 +1,21 @@
def burrows_wheeler(text):
- """Returns the burrows wheeler transform of <text>.
+ """Calculates the burrows wheeler transform of <text>.
+ returns the burrows wheeler string and the suffix array indices
The text is assumed to not contain the character $"""
text += ... |
bcdcd9451de924e2fa870e20414086729369b7bd | version.py | version.py | major = 0
minor=0
patch=27
branch="master"
timestamp=1376610643.76 | major = 0
minor=0
patch=28
branch="master"
timestamp=1376705489.59 | Tag commit for v0.0.28-master generated by gitmake.py | Tag commit for v0.0.28-master generated by gitmake.py
| Python | mit | ryansturmer/gitmake | ---
+++
@@ -1,5 +1,5 @@
major = 0
minor=0
-patch=27
+patch=28
branch="master"
-timestamp=1376610643.76
+timestamp=1376705489.59 |
a8d1812532211312287e58093ca966a7ea2050f4 | core/ModificationEntities.py | core/ModificationEntities.py | # coding: utf8
from core.ParsingEntities import Entity
class ModificationEntity(Entity):
def __add__(self, other):
if isinstance(self, ModificationEntity) and isinstance(other, ModificationEntity):
modification_operator = ModificationOperator()
return modification_operator
... | # coding: utf8
from core.ParsingEntities import Entity
class ModificationEntity(Entity):
def __add__(self, other):
if isinstance(self, ModificationEntity) and isinstance(other, ModificationEntity):
modification_operator = ModificationOperator()
return modification_operator
... | Implement ModificationOperator and ModificationCondition classes | Implement ModificationOperator and ModificationCondition classes
| Python | mit | JCH222/matriochkas | ---
+++
@@ -12,9 +12,20 @@
raise TypeError("Operands have to be ModificationEntity's subclasses")
-class ModificationCondition(ModificationEntity):
- pass
+class ModificationOperator(ModificationEntity):
+ def __init__(self, operand_a, operand_b):
+ self.operandA = operand_a
+ sel... |
fbc4bd9a9b803a831862ca81d315aa9eb79847d5 | geokey_wegovnow/__init__.py | geokey_wegovnow/__init__.py | """Main initialization for the WeGovNow extension."""
VERSION = (3, 1, 2)
__version__ = '.'.join(map(str, VERSION))
try:
from geokey.extensions.base import register
register(
'geokey_wegovnow',
'WeGovNow',
display_admin=False,
superuser=False,
version=__version__
... | """Main initialization for the WeGovNow extension."""
VERSION = (3, 2, 0)
__version__ = '.'.join(map(str, VERSION))
try:
from geokey.extensions.base import register
register(
'geokey_wegovnow',
'WeGovNow',
display_admin=False,
superuser=False,
version=__version__
... | Increment version number ahead of release. | Increment version number ahead of release. | Python | mit | ExCiteS/geokey-wegovnow,ExCiteS/geokey-wegovnow | ---
+++
@@ -1,6 +1,6 @@
"""Main initialization for the WeGovNow extension."""
-VERSION = (3, 1, 2)
+VERSION = (3, 2, 0)
__version__ = '.'.join(map(str, VERSION))
|
54f99c5c62c170b538a7a6ea4bf786c897151e5a | pylcp/url.py | pylcp/url.py | def url_path_join(url, path_part):
"""Join a path part to the end of a URL adding/removing slashes as necessary."""
result = url + '/' if url[-1] != '/' else url
index = 1 if path_part[0] == '/' else 0
return result + path_part[index:]
| def url_path_join(url, path_part):
"""Join a path part to the end of a URL adding/removing slashes as necessary."""
result = url + '/' if not url.endswith('/') else url
index = 1 if path_part.startswith('/') else 0
return result + path_part[index:]
| Use startswith/endswith instead of indices for readability. | Use startswith/endswith instead of indices for readability.
| Python | bsd-3-clause | bradsokol/PyLCP,Points/PyLCP,bradsokol/PyLCP,Points/PyLCP | ---
+++
@@ -1,5 +1,5 @@
def url_path_join(url, path_part):
"""Join a path part to the end of a URL adding/removing slashes as necessary."""
- result = url + '/' if url[-1] != '/' else url
- index = 1 if path_part[0] == '/' else 0
+ result = url + '/' if not url.endswith('/') else url
+ index = 1 if ... |
6e17e781f6cb8e29a7284beffe10463c843b86b3 | tests/test_vector2_equality.py | tests/test_vector2_equality.py | from hypothesis import assume, given
from ppb_vector import Vector2
from utils import vectors
@given(x=vectors())
def test_equal_self(x: Vector2):
assert x == x
@given(x=vectors())
def test_non_zero_equal(x: Vector2):
assume(x != (0, 0))
assert x != 1.1 * x
@given(x=vectors(), y=vectors())
def test_not_equal_... | from hypothesis import assume, given
from ppb_vector import Vector2
from utils import vectors
@given(x=vectors())
def test_equal_self(x: Vector2):
assert x == x
@given(x=vectors())
def test_non_zero_equal(x: Vector2):
assume(x != (0, 0))
assert x != 1.1 * x
assert x != -x
@given(x=vectors(), y=vectors())
de... | Add another (generated) negative example | tests/equality: Add another (generated) negative example
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | ---
+++
@@ -11,6 +11,7 @@
def test_non_zero_equal(x: Vector2):
assume(x != (0, 0))
assert x != 1.1 * x
+ assert x != -x
@given(x=vectors(), y=vectors())
def test_not_equal_equivalent(x: Vector2, y: Vector2): |
132a10f38c6c5d29c38a388af7d50e7ceb71e8fa | zipline_extension/calendars/exchange_calendar_forex.py | zipline_extension/calendars/exchange_calendar_forex.py | import pytz
from datetime import time
from zipline.utils.calendars import TradingCalendar
class ForexCalendar(TradingCalendar):
@property
def name(self):
return "forex"
@property
def tz(self):
return pytz.UTC
@property
def open_time(self):
return time(0, 0)
@prope... | import pytz
import pandas as pd
from datetime import time
from zipline.utils.calendars import TradingCalendar
class ForexCalendar(TradingCalendar):
NYT_5PM = time(9)
@property
def name(self):
return "forex"
@property
def tz(self):
return pytz.UTC
@property
def open_time... | Add weekend close and open times | Add weekend close and open times
| Python | mit | bernoullio/toolbox | ---
+++
@@ -1,8 +1,13 @@
import pytz
+import pandas as pd
from datetime import time
from zipline.utils.calendars import TradingCalendar
+
class ForexCalendar(TradingCalendar):
+
+ NYT_5PM = time(9)
+
@property
def name(self):
return "forex"
@@ -18,3 +23,23 @@
@property
def close_... |
01657e6991197c999180c2fec367fc75e59fba15 | var/spack/repos/builtin/packages/suite-sparse/package.py | var/spack/repos/builtin/packages/suite-sparse/package.py | from spack import *
class SuiteSparse(Package):
"""
SuiteSparse is a suite of sparse matrix algorithms
"""
homepage = 'http://faculty.cse.tamu.edu/davis/suitesparse.html'
url = 'http://faculty.cse.tamu.edu/davis/SuiteSparse/SuiteSparse-4.5.1.tar.gz'
version('4.5.1', 'f0ea9aad8d2d1ffec66a5b6bf... | from spack import *
class SuiteSparse(Package):
"""
SuiteSparse is a suite of sparse matrix algorithms
"""
homepage = 'http://faculty.cse.tamu.edu/davis/suitesparse.html'
url = 'http://faculty.cse.tamu.edu/davis/SuiteSparse/SuiteSparse-4.5.1.tar.gz'
version('4.5.1', 'f0ea9aad8d2d1ffec66a5b6bf... | Make suite-sparse use spack compilers. | Make suite-sparse use spack compilers.
| Python | lgpl-2.1 | lgarren/spack,TheTimmy/spack,mfherbst/spack,lgarren/spack,iulian787/spack,LLNL/spack,skosukhin/spack,mfherbst/spack,lgarren/spack,krafczyk/spack,mfherbst/spack,krafczyk/spack,lgarren/spack,TheTimmy/spack,TheTimmy/spack,tmerrick1/spack,LLNL/spack,krafczyk/spack,matthiasdiener/spack,skosukhin/spack,TheTimmy/spack,iulian7... | ---
+++
@@ -23,4 +23,14 @@
# FIXME : this actually uses the current workaround
# FIXME : (blas / lapack always provide libblas and liblapack as aliases)
- make('install', 'INSTALL=%s' % prefix, 'BLAS=-lblas', 'LAPACK=-llapack')
+ make('install', 'INSTALL=%s' % prefix,
+
+ ... |
c33f011d3ea9e1783149a9fb34d941a899f7cedc | blog/forms.py | blog/forms.py | from .models import BlogPost, Comment
from django.forms import ModelForm
class BlogPostForm(ModelForm):
class Meta:
model = BlogPost
exclude = ('user',)
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ('post',)
| from .models import BlogPost, Comment
from django.forms import ModelForm
class BlogPostForm(ModelForm):
class Meta:
model = BlogPost
exclude = ('user',)
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ('post', 'user', 'date',)
| Exclude fields from CommentForm that will be automatically inserted | Exclude fields from CommentForm that will be automatically inserted
| Python | mit | andreagrandi/bloggato,andreagrandi/bloggato | ---
+++
@@ -9,4 +9,4 @@
class CommentForm(ModelForm):
class Meta:
model = Comment
- exclude = ('post',)
+ exclude = ('post', 'user', 'date',) |
e03426b8fd696b8794e21ef52c76a0a5140e1463 | Maths/fibonacciSeries.py | Maths/fibonacciSeries.py | # Fibonacci Sequence Using Recursion
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
limit = int(input("How many terms to include in fibonacci series: "))
if limit <= 0:
print("Please enter a positive integer: ")
else:
print(f"The first {limit} ter... | # Fibonacci Sequence Using Recursion
def recur_fibo(n):
return n if n <= 1 else (recur_fibo(n-1) + recur_fibo(n-2))
def isPositiveInteger(limit):
return limit >= 0
def main():
limit = int(input("How many terms to include in fibonacci series: "))
if isPositiveInteger:
print(f"The first {li... | Improve and Refactor the fibonnaciSeries.py (Recursion) | Improve and Refactor the fibonnaciSeries.py (Recursion)
| Python | mit | TheAlgorithms/Python | ---
+++
@@ -1,16 +1,18 @@
# Fibonacci Sequence Using Recursion
def recur_fibo(n):
- if n <= 1:
- return n
- else:
- return(recur_fibo(n-1) + recur_fibo(n-2))
+ return n if n <= 1 else (recur_fibo(n-1) + recur_fibo(n-2))
-limit = int(input("How many terms to include in fibonacci series: ")... |
00222bb47818ea2fdf60847e6ad42ba96c39f16b | whacked4/whacked4/dehacked/filters.py | whacked4/whacked4/dehacked/filters.py | #!/usr/bin/env python
#coding=utf8
"""
This module contains functions used by a Dehacked table entry to filter certain values when reading or writing
them.
"""
import math
import re
def filter_thing_flags_read(value, table):
"""
Filters a thing's flags value.
Extended patches can use mnemonics for ... | #!/usr/bin/env python
#coding=utf8
"""
This module contains functions used by a Dehacked table entry to filter certain values when reading or writing
them.
"""
import math
import re
def filter_thing_flags_read(value, table):
"""
Filters a thing's flags value.
Extended patches can use mnemonics for ... | Fix flag delimiter support from 30ec188. | Fix flag delimiter support from 30ec188.
| Python | bsd-2-clause | GitExl/WhackEd4,GitExl/WhackEd4 | ---
+++
@@ -17,14 +17,14 @@
Extended patches can use mnemonics for flag names, separated by plus signs.
@raise LookupError: if the value contains an unknown mnemonic.
- """
-
- items = re.split(r"[,+| \t\f\r]+", value)
-
- if len(items) <= 1 and value.isalpha() == True:
+ """
... |
45e2651325ebf3d4554816d5c7bef04030d147b2 | tests/test_middleware.py | tests/test_middleware.py | from os import environ
from unittest import TestCase
environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
from incuna_auth.middleware import LoginRequiredMiddleware
class AuthenticatedUser(object):
def is_authenticated(self):
return True
class AnonymousUser(object):
def is_authenticated(self):
... | from os import environ
from unittest import TestCase
environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
from incuna_auth.middleware import LoginRequiredMiddleware
class AuthenticatedUser(object):
def is_authenticated(self):
return True
class AnonymousUser(object):
def is_authenticated(self):
... | Add test for non-GET requests | Add test for non-GET requests
* Check that we get a 403 result.
| Python | bsd-2-clause | incuna/incuna-auth,incuna/incuna-auth,ghickman/incuna-auth,ghickman/incuna-auth | ---
+++
@@ -43,3 +43,9 @@
self.request.user = AuthenticatedUser()
response = self.middleware.process_request(self.request)
self.assertEqual(response, None)
+
+ def test_403_result_if_non_get_request(self):
+ self.request = Request('protected-url/', 'POST')
+ self.request.us... |
85c509913cc9a6b22036c33eccb07277b39260e3 | pygraphc/anomaly/AnomalyScore.py | pygraphc/anomaly/AnomalyScore.py | import csv
from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction
from pygraphc.clustering.ClusterUtility import ClusterUtility
class AnomalyScore(object):
"""A class to calculate anomaly score in a cluster.
"""
def __init__(self, graph, clusters, filename):
"""The constructor of ... | import csv
from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction
from pygraphc.clustering.ClusterUtility import ClusterUtility
class AnomalyScore(object):
"""A class to calculate anomaly score in a cluster.
"""
def __init__(self, graph, clusters, filename):
"""The constructor of c... | Add description of Parameters section in docstring | Add description of Parameters section in docstring
| Python | mit | studiawan/pygraphc | ---
+++
@@ -1,5 +1,4 @@
import csv
-
from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction
from pygraphc.clustering.ClusterUtility import ClusterUtility
@@ -13,8 +12,11 @@
Parameters
----------
graph : graph
+ A graph to be analyzed for its anomaly.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.