commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
32508dea4ef00fb54919c0260b7ba2902835faf5
prepareupload.py
prepareupload.py
import sys import olrcdb import os # Globals COUNT = 0 class FileParser(object): '''Object used to parse through a directory for all it's files. Collects the paths of all the files and stores a record of these in a new table in the database. The Schema of the database is: NewTable(path, uploade...
import sys import olrcdb import os # Globals COUNT = 0 class FileParser(object): '''Object used to parse through a directory for all it's files. Collects the paths of all the files and stores a record of these in a new table in the database. The Schema of the database is: NewTable(path, uploade...
Print messages for prepare upload.
Print messages for prepare upload.
Python
bsd-3-clause
OLRC/SwiftBulkUploader,cudevmaxwell/SwiftBulkUploader
66b20aa7fbd322a051ab7ae26ecd8c46f7605763
ptoolbox/tags.py
ptoolbox/tags.py
# -*- coding: utf-8 -*- from datetime import datetime TAG_WIDTH = 'EXIF ExifImageWidth' TAG_HEIGHT = 'EXIF ExifImageLength' TAG_DATETIME = 'Image DateTime' TAG_ORIENTATION = 'Image Orientation' # XXX: this is a terrible way to retrieve the orientations. Exifread regretfully does not # get back raw EXIF orientations,...
# -*- coding: utf-8 -*- from datetime import datetime TAG_WIDTH = 'EXIF ExifImageWidth' TAG_HEIGHT = 'EXIF ExifImageLength' TAG_DATETIME = 'Image DateTime' def parse_time(tags): tag = tags.get(TAG_DATETIME, None) if not tag: raise KeyError(TAG_DATETIME) return datetime.strptime(str(tag), "%Y:%m:%...
Remove orientation tag parsing, not needed.
Remove orientation tag parsing, not needed.
Python
mit
vperron/picasa-toolbox
ad3a495e38e22f3759a724a23ce0492cd42e0bc4
qual/calendar.py
qual/calendar.py
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar...
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar...
Use from_date to construct from year, month, day.
Use from_date to construct from year, month, day.
Python
apache-2.0
jwg4/calexicon,jwg4/qual
4303a5cb38f2252dfe09a0ca21320d4bd67bd966
byceps/blueprints/user/current/forms.py
byceps/blueprints/user/current/forms.py
""" byceps.blueprints.user.current.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from wtforms import DateField, StringField from wtforms.validators import InputRequired, Length, Optional from ....util.l10n import LocalizedFo...
""" byceps.blueprints.user.current.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from wtforms import DateField, StringField from wtforms.fields.html5 import TelField from wtforms.validators import InputRequired, Length, Optio...
Use `<input type="tel">` for phone number field
Use `<input type="tel">` for phone number field
Python
bsd-3-clause
m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
71c9235a7e48882fc8c1393e9527fea4531c536c
filter_plugins/fap.py
filter_plugins/fap.py
#!/usr/bin/python import ipaddress def site_code(ipv4): # Verify IP address _ = ipaddress.ip_address(ipv4) segments = ipv4.split(".") return int(segments[1]) class FilterModule(object): def filters(self): return {"site_code": site_code}
#!/usr/bin/python import ipaddress def site_code(ipv4): # Verify IP address _ = ipaddress.ip_address(ipv4) segments = ipv4.split(".") return int(segments[1]) # rest:https://restic.storage.tjoda.fap.no/rpi1.ldn.fap.no # rclone:Jotta:storage.tjoda.fap.no # /Volumes/storage/restic/kramacbook def res...
Add really hacky way to reformat restic repos
Add really hacky way to reformat restic repos
Python
mit
kradalby/plays,kradalby/plays
417415283d87654b066c11d807516d3cd5b5bf3d
tests/test_probabilistic_interleave_speed.py
tests/test_probabilistic_interleave_speed.py
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(100, 200)) for i in range(1000): method = il....
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(50, 150)) r3 = list(range(100, 200)) r4 = list(ra...
Add tests for measuring the speed of probabilistic interleaving
Add tests for measuring the speed of probabilistic interleaving
Python
mit
mpkato/interleaving
b8839af335757f58fa71916ff3394f5a6806165d
user_management/api/tests/test_exceptions.py
user_management/api/tests/test_exceptions.py
from django.test import TestCase from rest_framework.status import HTTP_400_BAD_REQUEST from ..exceptions import InvalidExpiredToken class InvalidExpiredTokenTest(TestCase): """Assert `InvalidExpiredToken` behaves as expected.""" def test_raise(self): """Assert `InvalidExpiredToken` can be raised."""...
from django.test import TestCase from rest_framework.status import HTTP_400_BAD_REQUEST from ..exceptions import InvalidExpiredToken class InvalidExpiredTokenTest(TestCase): """Assert `InvalidExpiredToken` behaves as expected.""" def test_raise(self): """Assert `InvalidExpiredToken` can be raised."""...
Use more explicit name for error
Use more explicit name for error
Python
bsd-2-clause
incuna/django-user-management,incuna/django-user-management
287dc6f7a7f0321fec8e35d1dc08f07a3b12f63b
test/342-winter-sports-pistes.py
test/342-winter-sports-pistes.py
# http://www.openstreetmap.org/way/313466665 assert_has_feature( 15, 5467, 12531, 'roads', { 'kind': 'piste', 'piste_type': 'downhill', 'piste_difficulty': 'easy', 'id': 313466665 }) # http://www.openstreetmap.org/way/313466720 assert_has_feature( 15, 5467, 12531, 'roads', { 'kind': '...
# http://www.openstreetmap.org/way/313466665 assert_has_feature( 15, 5467, 12531, 'roads', { 'kind': 'piste', 'piste_type': 'downhill', 'piste_difficulty': 'easy', 'id': 313466665 }) # http://www.openstreetmap.org/way/313466720 assert_has_feature( 15, 5467, 12531, 'roads', { 'kind': '...
Add piste test to catch dev issue
Add piste test to catch dev issue
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
40653d829efcc0461d0da9472111aa89b41e08f1
hasjob/views/login.py
hasjob/views/login.py
# -*- coding: utf-8 -*- from flask import Response, redirect, flash from flask.ext.lastuser.sqlalchemy import UserManager from coaster.views import get_next_url from hasjob import app, lastuser from hasjob.models import db, User lastuser.init_usermanager(UserManager(db, User)) @app.route('/login') @lastuser.login...
# -*- coding: utf-8 -*- from flask import Response, redirect, flash from flask.ext.lastuser.sqlalchemy import UserManager from coaster.views import get_next_url from hasjob import app, lastuser from hasjob.models import db, User lastuser.init_usermanager(UserManager(db, User)) @app.route('/login') @lastuser.login...
Support for Lastuser push notifications.
Support for Lastuser push notifications.
Python
agpl-3.0
qitianchan/hasjob,qitianchan/hasjob,hasgeek/hasjob,hasgeek/hasjob,nhannv/hasjob,hasgeek/hasjob,sindhus/hasjob,sindhus/hasjob,nhannv/hasjob,sindhus/hasjob,qitianchan/hasjob,sindhus/hasjob,qitianchan/hasjob,ashwin01/hasjob,ashwin01/hasjob,hasgeek/hasjob,ashwin01/hasjob,ashwin01/hasjob,nhannv/hasjob,nhannv/hasjob,qitianch...
dce404d65f1f2b8f297cfa066210b885621d38d0
graphene/commands/exit_command.py
graphene/commands/exit_command.py
from graphene.commands.command import Command class ExitCommand(Command): def __init__(self): pass
from graphene.commands.command import Command class ExitCommand(Command): def __init__(self): pass def execute(self, storage_manager, timer=None): # This should never be used anyway. pass
Fix EXIT command to have execute method for abstract class
Fix EXIT command to have execute method for abstract class
Python
apache-2.0
PHB-CS123/graphene,PHB-CS123/graphene,PHB-CS123/graphene
c7578896036bc07bb1edc2d79f699968c25ca89e
bika/lims/upgrade/to1117.py
bika/lims/upgrade/to1117.py
from Acquisition import aq_inner from Acquisition import aq_parent from Products.CMFCore.utils import getToolByName def upgrade(tool): """ Enable portlets for key=/ (re-import portlets.xml): issue #695 """ portal = aq_parent(aq_inner(tool)) setup = portal.portal_setup setup.runImportStepFromProfi...
from Acquisition import aq_inner from Acquisition import aq_parent from Products.CMFCore.utils import getToolByName def upgrade(tool): """ Enable portlets for key=/ (re-import portlets.xml): issue #695 """ portal = aq_parent(aq_inner(tool)) setup = portal.portal_setup setup.runImportStepFromProfi...
Upgrade 1117 - add run_dependencies=False
Upgrade 1117 - add run_dependencies=False Somehow re-importing the 'portlets' step, causes a beforeDelete handler to fail a HoldingReference check.
Python
agpl-3.0
labsanmartin/Bika-LIMS,veroc/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS,anneline/Bika-LIMS,rockfruit/bika.lims,rockfruit/bika.lims,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS,DeBortoliWines/Bika-LIMS,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS
7cde5e713ace2b0a1d9cdef01ac912f3a53814cd
run_scripts/build_phylogenies.py
run_scripts/build_phylogenies.py
#!/usr/bin/env python # Automatically generate phylogenies from a settings file # specifying input fasta and genomes import sys import dendrogenous as dg import dendrogenous.settings import dendrogenous.utils import dendrogenous.core import multiprocessing def main(settings_file): settings = dg.settings.S...
#!/usr/bin/env python # Automatically generate phylogenies from a settings file # specifying input fasta and genomes import sys import dendrogenous as dg import dendrogenous.settings import dendrogenous.utils import dendrogenous.core import joblib import pickle #multiprocessing def main(settings_file): settings =...
Change run script to use worker pool
Change run script to use worker pool
Python
bsd-3-clause
fmaguire/dendrogenous
a11c839988b71e9f769cb5ba856474205b7aeefb
jsonschema/tests/fuzz_validate.py
jsonschema/tests/fuzz_validate.py
""" Fuzzing setup for OSS-Fuzz. See https://github.com/google/oss-fuzz/tree/master/projects/jsonschema for the other half of the setup here. """ import sys from hypothesis import given, strategies import jsonschema PRIM = strategies.one_of( strategies.booleans(), strategies.integers(), strategies.floats...
""" Fuzzing setup for OSS-Fuzz. See https://github.com/google/oss-fuzz/tree/master/projects/jsonschema for the other half of the setup here. """ import sys from hypothesis import given, strategies import jsonschema PRIM = strategies.one_of( strategies.booleans(), strategies.integers(), strategies.floats...
Fix fuzzer to include instrumentation
Fix fuzzer to include instrumentation
Python
mit
python-jsonschema/jsonschema
224d9f4e243f6645e88b32ad7342a55128f19eeb
html5lib/__init__.py
html5lib/__init__.py
""" HTML parsing library based on the WHATWG "HTML5" specification. The parser is designed to be compatible with existing HTML found in the wild and implements well-defined error recovery that is largely compatible with modern desktop web browsers. Example usage: import html5lib f = open("my_document.html") tree = ht...
""" HTML parsing library based on the WHATWG "HTML5" specification. The parser is designed to be compatible with existing HTML found in the wild and implements well-defined error recovery that is largely compatible with modern desktop web browsers. Example usage:: import html5lib f = open("my_document.html") ...
Fix formatting of docstring example
Fix formatting of docstring example It runs together in the built HTML.
Python
mit
html5lib/html5lib-python,html5lib/html5lib-python,html5lib/html5lib-python
f748facb9edd35ca6c61be336cad3109cafbbc89
tests/test_authentication.py
tests/test_authentication.py
import unittest from flask import json from api import create_app, db class AuthenticationTestCase(unittest.TestCase): def setUp(self): self.app = create_app(config_name='TestingEnv') self.client = self.app.test_client() # Binds the app to current context with self.app.app_context...
import unittest from flask import json from api import db from api.BucketListAPI import app from instance.config import application_config class AuthenticationTestCase(unittest.TestCase): def setUp(self): app.config.from_object(application_config['TestingEnv']) self.client = app.test_client() ...
Add test for index route
Add test for index route
Python
mit
patlub/BucketListAPI,patlub/BucketListAPI
644896c856b1e6ad20a3790234439b8ac8403917
examples/dft/12-camb3lyp.py
examples/dft/12-camb3lyp.py
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # ''' The default XC functional library (libxc) supports the energy and nuclear gradients for range separated functionals. Nuclear Hessian and TDDFT gradients need xcfun library. See also example 32-xcfun_as_default.py for how to set xcfun library a...
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # '''Density functional calculations can be run with either the default backend library, libxc, or an alternative library, xcfun. See also example 32-xcfun_as_default.py for how to set xcfun as the default XC functional library. ''' from pyscf impor...
Update the camb3lyp example to libxc 5 series
Update the camb3lyp example to libxc 5 series
Python
apache-2.0
sunqm/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf
bf007267246bd317dc3ccad9f5cf8a9f452b3e0b
firecares/utils/__init__.py
firecares/utils/__init__.py
from django.core.files.storage import get_storage_class from storages.backends.s3boto import S3BotoStorage from PIL import Image def convert_png_to_jpg(img): """ Converts a png to a jpg. :param img: Absolute path to the image. :returns: the filename """ im = Image.open(img) bg = Image.new(...
from django.core.files.storage import get_storage_class from storages.backends.s3boto import S3BotoStorage from PIL import Image class CachedS3BotoStorage(S3BotoStorage): """ S3 storage backend that saves the files locally, too. """ def __init__(self, *args, **kwargs): super(CachedS3BotoStorag...
Remove the unused convert_png_to_jpg method.
Remove the unused convert_png_to_jpg method.
Python
mit
FireCARES/firecares,FireCARES/firecares,meilinger/firecares,meilinger/firecares,FireCARES/firecares,meilinger/firecares,HunterConnelly/firecares,HunterConnelly/firecares,FireCARES/firecares,HunterConnelly/firecares,FireCARES/firecares,meilinger/firecares,HunterConnelly/firecares
49f5802a02a550cc8cee3be417426a83c31de5c9
Source/Git/Experiments/git_log.py
Source/Git/Experiments/git_log.py
#!/usr/bin/python3 import sys import git r = git.Repo( sys.argv[1] ) def printTree( tree, indent=0 ): prefix = ' '*indent print( prefix, '-' * 16 ) print( prefix, 'Tree path %s' % (tree.path,) ) for blob in tree: print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) ) for chi...
#!/usr/bin/python3 import sys import git r = git.Repo( sys.argv[1] ) def printTree( tree, indent=0 ): prefix = ' '*indent print( prefix, '-' * 16 ) print( prefix, 'Tree path %s' % (tree.path,) ) for blob in tree: print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) ) for chi...
Exit the loop early when experimenting.
Exit the loop early when experimenting.
Python
apache-2.0
barry-scott/scm-workbench,barry-scott/scm-workbench,barry-scott/scm-workbench
4e6ec9cc5b052341094723433f58a21020fa82f0
tools/scheduler/scheduler/core.py
tools/scheduler/scheduler/core.py
# scheduler.core: Data structures for managing K3 jobs. class Job: def __init__(self, roles): self.roles = roles self.tasks = None self.status = None class Role: def __init__(self, peers = 0, variables {}, inputs {}, hostmask = r"*"): self.peers = peers self.variables = variables, self.inp...
# scheduler.core: Data structures for managing K3 jobs. class Job: def __init__(self, roles, binary_url): self.roles = roles self.binary_url = binary_url self.tasks = None self.status = None class Role: def __init__(self, peers = 0, variables {}, inputs {}, hostmask = r"*"): self.peers = peers...
Add binary_url member to Job.
Add binary_url member to Job.
Python
apache-2.0
DaMSL/K3,DaMSL/K3,yliu120/K3
40d204c996e41a030dac240c99c66a25f8f8586e
scripts/generate-bcrypt-hashed-password.py
scripts/generate-bcrypt-hashed-password.py
#!/usr/bin/env python """ A script to return a bcrypt hash of a password. It's intended use is for creating known passwords to replace user passwords in cleaned up databases. Cost-factor is the log2 number of rounds of hashing to use for the salt. It's worth researching how many rounds you need for your use context, ...
#!/usr/bin/env python """ A script to return a bcrypt hash of a password. It's intended use is for creating known passwords to replace user passwords in cleaned up databases. Cost-factor is the log2 number of rounds of hashing to use for the salt. It's worth researching how many rounds you need for your use context, ...
Fix "string argument without an encoding" python3 error in bcrypt script
Fix "string argument without an encoding" python3 error in bcrypt script generate-bcrypt-hashed-password raises an error on python3 since `bytes` is called without an encoding argument. Replacing it with `.encode` should fix the problem.
Python
mit
alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws
4037036de79f6503921bbd426bb5352f2f86f12b
plyer/platforms/android/camera.py
plyer/platforms/android/camera.py
from os import unlink from jnius import autoclass, cast from plyer.facades import Camera from plyer.platforms.android import activity Intent = autoclass('android.content.Intent') PythonActivity = autoclass('org.renpy.android.PythonActivity') MediaStore = autoclass('android.provider.MediaStore') Uri = autoclass('androi...
import android import android.activity from os import unlink from jnius import autoclass, cast from plyer.facades import Camera from plyer.platforms.android import activity Intent = autoclass('android.content.Intent') PythonActivity = autoclass('org.renpy.android.PythonActivity') MediaStore = autoclass('android.provi...
Revert "Activity was imported twice"
Revert "Activity was imported twice" This reverts commit a0600929774c1e90c7dc43043ff87b5ea84213b4.
Python
mit
johnbolia/plyer,johnbolia/plyer,kived/plyer,kivy/plyer,cleett/plyer,kived/plyer,kivy/plyer,kivy/plyer,KeyWeeUsr/plyer,KeyWeeUsr/plyer,cleett/plyer,kostyll/plyer,KeyWeeUsr/plyer,kostyll/plyer
7a5b86bcb8c0a2e8c699c7602cef50bed2acef1b
src/keybar/tests/factories/user.py
src/keybar/tests/factories/user.py
import factory from django.contrib.auth.hashers import make_password from keybar.models.user import User class UserFactory(factory.DjangoModelFactory): email = factory.Sequence(lambda i: '{0}@none.none'.format(i)) is_active = True class Meta: model = User @classmethod def _prepare(cls, ...
import factory from django.contrib.auth.hashers import make_password from keybar.models.user import User class UserFactory(factory.DjangoModelFactory): email = factory.Sequence(lambda i: '{0}@none.none'.format(i)) is_active = True class Meta: model = User @classmethod def _prepare(cls, ...
Use pdbkdf_sha256 hasher for testing too.
Use pdbkdf_sha256 hasher for testing too.
Python
bsd-3-clause
keybar/keybar
5c29b4322d1a24c4f389076f2a9b8acbeabd89e2
python/lumidatumclient/classes.py
python/lumidatumclient/classes.py
import os import requests class LumidatumClient(object): def __init__(self, authentication_token, model_id=None, host_address='https://www.lumidatum.com'): self.authentication_token = authentication_token self.model_id = model_id self.host_address = host_address def getRecommendatio...
import os import requests class LumidatumClient(object): def __init__(self, authentication_token, model_id=None, host_address='https://www.lumidatum.com'): self.authentication_token = authentication_token self.model_id = str(model_id) self.host_address = host_address def getRecommen...
Fix for os.path.join with model_id, was breaking on non-string model_id values.
Fix for os.path.join with model_id, was breaking on non-string model_id values.
Python
mit
Lumidatum/lumidatumclients,Lumidatum/lumidatumclients,daws/lumidatumclients,Lumidatum/lumidatumclients
7b2dac39cdcbc8d5f05d4979df06bf1ab1ae065f
goetia/pythonizors/pythonize_parsing.py
goetia/pythonizors/pythonize_parsing.py
from goetia.pythonizors.utils import is_template_inst def pythonize_goetia_parsing(klass, name): is_fastx, _ = is_template_inst(name, 'FastxParser') if is_fastx: def __iter__(self): while not self.is_complete(): record = self.next() if record: ...
from goetia.pythonizors.utils import is_template_inst def pythonize_goetia_parsing(klass, name): is_fastx, _ = is_template_inst(name, 'FastxParser') if is_fastx: def __iter__(self): while not self.is_complete(): record = self.next() if record: ...
Fix std::optional access in SplitPairedReader pythonization
Fix std::optional access in SplitPairedReader pythonization
Python
mit
camillescott/boink,camillescott/boink,camillescott/boink,camillescott/boink
ccb7446b02b394af308f4fba0500d402240f117e
home/migrations/0002_create_homepage.py
home/migrations/0002_create_homepage.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def create_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') Home...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def create_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') Home...
Remove any existing localhost sites and use the page id rather than the object to set the default homepage.
Remove any existing localhost sites and use the page id rather than the object to set the default homepage.
Python
mit
OpenCanada/lindinitiative,OpenCanada/lindinitiative
1179163881fe1dedab81a02a940c711479a334ab
Instanssi/admin_auth/forms.py
Instanssi/admin_auth/forms.py
# -*- coding: utf-8 -*- from django import forms from uni_form.helper import FormHelper from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder class LoginForm(forms.Form): username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät ke...
# -*- coding: utf-8 -*- from django import forms from uni_form.helper import FormHelper from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder class LoginForm(forms.Form): username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät ke...
Use passwordinput in password field.
admin_auth: Use passwordinput in password field.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
ab7856950c058d00aac99874669839e09bc116c6
models.py
models.py
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.File...
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.File...
Order feedback items by their timestamp.
Order feedback items by their timestamp.
Python
bsd-3-clause
littleweaver/django-talkback,littleweaver/django-talkback,littleweaver/django-talkback
cdaffa187b41f3a84cb5a6b44f2e781a9b249f2b
tests/test_users.py
tests/test_users.py
from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self...
from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self...
Update test to reflect new method name.
Update test to reflect new method name.
Python
mit
nhshd-slot/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT
a3cce9e4840cc687f6dcdd0b88577d2f13f3258e
onlineweb4/settings/raven.py
onlineweb4/settings/raven.py
import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:pass@sentry.io/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), }
import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:pass@sentry.io/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), ...
Make it possible to specify which app to represent in sentry
Make it possible to specify which app to represent in sentry
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
e2cc9c822abb675a196468ee89b063e0162c16d5
changes/api/author_build_index.py
changes/api/author_build_index.py
from __future__ import absolute_import, division, unicode_literals from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.api.auth import get_current_user from changes.models import Author, Build class AuthorBuildIndexAPIView(APIView): def _get_author(self, author_id): i...
from __future__ import absolute_import, division, unicode_literals from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.api.auth import get_current_user from changes.models import Author, Build class AuthorBuildIndexAPIView(APIView): def _get_author(self, author_id): i...
Move 'me' check outside of author lookup
Move 'me' check outside of author lookup
Python
apache-2.0
wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,dropbox/changes
b8a7dd2dfc9322498dc7500f840bedd20d807ae1
samples/numpy_blir.py
samples/numpy_blir.py
import numpy as np from blaze.blir import compile, execute source = """ def main(x: array[int], n : int) -> void { var int i; var int j; for i in range(n) { for j in range(n) { x[i,j] = i+j; } x[i-1,j-1] = 10; } } """ N = 14 ast, env = compile(source) arr = np.eye(...
import numpy as np from blaze.blir import compile, execute source = """ def main(x: array[int], n : int) -> void { var int i; var int j; for i in range(n) { for j in range(n) { x[i,j] = i+j; } } } """ N = 15 ast, env = compile(source) arr = np.eye(N, dtype='int32') args = ...
Fix dumb out of bounds error.
Fix dumb out of bounds error.
Python
bsd-2-clause
seibert/blaze-core,seibert/blaze-core,seibert/blaze-core,seibert/blaze-core,seibert/blaze-core
379c6254da0d6a06f8c01cd7cd2632a1d59624ac
comics/sets/context_processors.py
comics/sets/context_processors.py
from comics.sets.models import UserSet def user_set(request): try: user_set = UserSet.objects.get(user=request.user) return { 'user_set': user_set, 'user_set_comics': user_set.comics.all(), } except UserSet.DoesNotExist: return {}
def user_set(request): if hasattr(request, 'user_set'): return { 'user_set': request.user_set, 'user_set_comics': request.user_set.comics.all(), } else: return {}
Use request.user_set in context preprocessor
Use request.user_set in context preprocessor
Python
agpl-3.0
datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics
3aa2f858f93ed3945bf1960d5c5d1d90df34422c
MoodJournal/entries/serializers.py
MoodJournal/entries/serializers.py
from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator, UniqueForDateValidator from .models import UserDefinedCategory from .models import EntryInstance class UserDefinedCategorySerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentity...
from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from .models import UserDefinedCategory from .models import EntryInstance class UserDefinedCategorySerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='categor...
Revert "unique for date validator"
Revert "unique for date validator" This reverts commit 7d2eee38eebf62787b77cdd41e7677cfdad6d47b.
Python
mit
swpease/MoodJournal,swpease/MoodJournal,swpease/MoodJournal
e394c1889eccb5806a480033dca467da51d515e5
scripts/test_setup.py
scripts/test_setup.py
#! /usr/bin/python import platform import subprocess import sys def _execute(*args, **kwargs): result = subprocess.call(*args, **kwargs) if result != 0: sys.exit(result) if __name__ == '__main__': python_version = platform.python_version() deps = [ "execnet", "Jinja2", ...
#! /usr/bin/python import platform import subprocess import sys def _execute(*args, **kwargs): result = subprocess.call(*args, **kwargs) if result != 0: sys.exit(result) if __name__ == '__main__': python_version = platform.python_version() deps = [ "execnet", "nose", "...
Test dependencies: On Python 2.5, require Jinja 2.6
Test dependencies: On Python 2.5, require Jinja 2.6
Python
bsd-3-clause
omergertel/logbook,pombredanne/logbook,Rafiot/logbook,alonho/logbook,Rafiot/logbook,alonho/logbook,omergertel/logbook,Rafiot/logbook,FintanH/logbook,DasIch/logbook,DasIch/logbook,RazerM/logbook,mitsuhiko/logbook,omergertel/logbook,DasIch/logbook,dommert/logbook,alonho/logbook
da54fa6d681ab7f2e3146b55d562e5a4d68623cc
luigi/tasks/export/ftp/__init__.py
luigi/tasks/export/ftp/__init__.py
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by...
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by...
Make GO term export part of FTP export
Make GO term export part of FTP export
Python
apache-2.0
RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline
eb496468d61ff3245adbdec4108a04bc40a357fc
Grid.py
Grid.py
from boomslang.LineStyle import LineStyle class Grid(object): def __init__(self, color="#dddddd", style="-", visible=True): self.color = color self._lineStyle = LineStyle() self._lineStyle.style = style self.visible = visible @property def style(self): return self._...
from boomslang.LineStyle import LineStyle class Grid(object): def __init__(self, color="#dddddd", style="-", visible=True): self.color = color self._lineStyle = LineStyle() self._lineStyle.style = style self.visible = visible self.which = 'major' @property def style...
Allow gridlines on both major and minor axes.
Allow gridlines on both major and minor axes.
Python
bsd-3-clause
alexras/boomslang
8ae82e08fc42d89402550f5f545dbaa258196c8c
ibmcnx/test/test.py
ibmcnx/test/test.py
#import ibmcnx.test.loadFunction import sys from java.lang import String from java.util import HashSet from java.util import HashMap import java import lotusConnectionsCommonAdmin globdict = globals() def loadFilesService(): global globdict execfile( "filesAdmin.py", globdict ) loadFilesService() FilesPolic...
#import ibmcnx.test.loadFunction import sys from java.lang import String from java.util import HashSet from java.util import HashMap import java import lotusConnectionsCommonAdmin globdict = globals() def loadFilesService(): global globdict execfile( "filesAdmin.py", globdict ) loadFilesService() test = Fil...
Customize scripts to work with menu
Customize scripts to work with menu
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
fc42c3cf72abeb053560c21e1870e8507aa2d666
examples/framework/faren/faren.py
examples/framework/faren/faren.py
#!/usr/bin/env python import gtk from kiwi.controllers import BaseController from kiwi.ui.views import BaseView from kiwi.ui.gadgets import quit_if_last class FarenControl(BaseController): def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() def after_temperature__changed(self, entry, ...
#!/usr/bin/env python import gtk from kiwi.controllers import BaseController from kiwi.ui.views import BaseView from kiwi.ui.gadgets import quit_if_last class FarenControl(BaseController): def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() def after_temperature__insert_text(self, ent...
Use insert_text instead of changed
Use insert_text instead of changed
Python
lgpl-2.1
stoq/kiwi
a859890c9f17b2303061b2d68e5c58ad27e07b35
grizli/pipeline/__init__.py
grizli/pipeline/__init__.py
""" Automated processing of associated exposures """
""" Automated processing of associated exposures """ def fetch_from_AWS_bucket(root='j022644-044142', id=1161, product='.beams.fits', bucket_name='aws-grivam', verbose=True, dryrun=False, output_path='./', get_fit_args=False, skip_existing=True): """ Fetch products from the Grizli AWS bucket. Boto3 ...
Add script to fetch data from AWS
Add script to fetch data from AWS
Python
mit
gbrammer/grizli
f46059285851d47a9bee2174e32e9e084efe1182
jirafs/constants.py
jirafs/constants.py
from jirafs import __version__ as version # Metadata filenames TICKET_DETAILS = 'fields.jira' TICKET_COMMENTS = 'comments.read_only.jira' TICKET_NEW_COMMENT = 'new_comment.jira' TICKET_LINKS = 'links.jira' TICKET_FILE_FIELD_TEMPLATE = u'{field_name}.jira' # Generic settings LOCAL_ONLY_FILE = '.jirafs_local' REMOTE_IG...
from jirafs import __version__ as version # Metadata filenames TICKET_DETAILS = 'fields.jira' TICKET_COMMENTS = 'comments.read_only.jira' TICKET_NEW_COMMENT = 'new_comment.jira' TICKET_LINKS = 'links.jira' TICKET_FILE_FIELD_TEMPLATE = u'{field_name}.jira' # Generic settings LOCAL_ONLY_FILE = '.jirafs_local' REMOTE_IG...
Remove my personal domain from the public jirafs git config.
Remove my personal domain from the public jirafs git config.
Python
mit
coddingtonbear/jirafs,coddingtonbear/jirafs
1690c1981614e20183d33de4d117af0aa62ae9c5
kboard/board/urls.py
kboard/board/urls.py
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_p...
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new...
Modify board_slug in url regex to pass numeric letter
Modify board_slug in url regex to pass numeric letter
Python
mit
kboard/kboard,guswnsxodlf/k-board,kboard/kboard,cjh5414/kboard,hyesun03/k-board,cjh5414/kboard,hyesun03/k-board,guswnsxodlf/k-board,kboard/kboard,hyesun03/k-board,darjeeling/k-board,cjh5414/kboard,guswnsxodlf/k-board
ff34a0b9ffc3fed7be9d30d65f9e8f0c24a3cf83
abusehelper/contrib/spamhaus/xbl.py
abusehelper/contrib/spamhaus/xbl.py
""" Spamhaus XBL list handler. Maintainer: Sauli Pahlman <sauli@codenomicon.com> """ import idiokit from abusehelper.core import cymruwhois, bot, events class SpamhausXblBot(bot.PollingBot): xbl_filepath = bot.Param("Filename of Spamhaus XBL file") @idiokit.stream def poll(self): skip_chars = [...
""" Spamhaus XBL list handler. Maintainer: Sauli Pahlman <sauli@codenomicon.com> """ import idiokit from abusehelper.core import cymruwhois, bot, events class SpamhausXblBot(bot.PollingBot): xbl_filepath = bot.Param("Filename of Spamhaus XBL file") @idiokit.stream def poll(self): skip_chars = [...
Make the bot to save memory by sending events as soon as it reads through the corresponding lines of the input file.
Make the bot to save memory by sending events as soon as it reads through the corresponding lines of the input file.
Python
mit
abusesa/abusehelper
0d73cc1b38703653c3302d8f9ff4efbeaaa2b406
credentials/apps/records/models.py
credentials/apps/records/models.py
""" Models for the records app. """ import uuid from django.db import models from django_extensions.db.models import TimeStampedModel from credentials.apps.catalog.models import CourseRun, Program from credentials.apps.core.models import User class UserGrade(TimeStampedModel): """ A grade for a specific use...
""" Models for the records app. """ import uuid from django.db import models from django_extensions.db.models import TimeStampedModel from credentials.apps.catalog.models import CourseRun, Program from credentials.apps.core.models import User from credentials.apps.credentials.models import ProgramCertificate class ...
Revert early removal of certificate field
Revert early removal of certificate field
Python
agpl-3.0
edx/credentials,edx/credentials,edx/credentials,edx/credentials
efd44be24e84a35db353ac79dae7cc7392a18b0c
matador/commands/deploy_ticket.py
matador/commands/deploy_ticket.py
#!/usr/bin/env python from .command import Command from matador import utils import subprocess import os class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, r...
#!/usr/bin/env python from .command import Command from matador import utils import subprocess import os class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, r...
Add ticket and branch arguments
Add ticket and branch arguments
Python
mit
Empiria/matador
6795e02c14fa99da2c0812fe6694bbd503f89ad1
tests/mock_vws/test_invalid_given_id.py
tests/mock_vws/test_invalid_given_id.py
""" Tests for passing invalid endpoints which require a target ID to be given. """ import pytest import requests from requests import codes from mock_vws._constants import ResultCodes from tests.mock_vws.utils import ( TargetAPIEndpoint, VuforiaDatabaseKeys, assert_vws_failure, delete_target, ) @pyt...
""" Tests for passing invalid endpoints which require a target ID to be given. """ import pytest import requests from requests import codes from mock_vws._constants import ResultCodes from tests.mock_vws.utils import ( TargetAPIEndpoint, VuforiaDatabaseKeys, assert_vws_failure, delete_target, ) @pyt...
Use any_endpoint on invalid id test
Use any_endpoint on invalid id test
Python
mit
adamtheturtle/vws-python,adamtheturtle/vws-python
4eda3f3535d28e2486745f33504c417ba6837c3a
stdnum/nz/__init__.py
stdnum/nz/__init__.py
# __init__.py - collection of New Zealand numbers # coding: utf-8 # # Copyright (C) 2019 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the Licen...
# __init__.py - collection of New Zealand numbers # coding: utf-8 # # Copyright (C) 2019 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the Licen...
Add missing vat alias for New Zealand
Add missing vat alias for New Zealand Closes https://github.com/arthurdejong/python-stdnum/pull/202
Python
lgpl-2.1
arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum
ea3a72443f2fa841ea0bc73ec461968c447f39c1
egg_timer/apps/utils/management/commands/check_requirements.py
egg_timer/apps/utils/management/commands/check_requirements.py
import subprocess from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Ensure that all installed packages are in requirements.txt' def _get_file_contents(self, name): req_file = open('requirements/%s.txt' % name) reqs = req_file.read() req_file.clos...
import subprocess from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Ensure that all installed packages are in requirements.txt' def handle(self, *args, **options): proc = subprocess.Popen(['pip', 'freeze'], stdout=subprocess.PIPE) freeze_results = proc.c...
Revert "Added a prod option to the rquirements checker"
Revert "Added a prod option to the rquirements checker" This reverts commit 5b9ae76d157d068ef456d5caa5c4352a139f528b.
Python
mit
jessamynsmith/eggtimer-server,jessamynsmith/eggtimer-server,jessamynsmith/eggtimer-server,jessamynsmith/eggtimer-server
8014285e5dc8fb13377b729f9fd19b4187fbaf29
fireplace/carddata/spells/other.py
fireplace/carddata/spells/other.py
from ..card import * # The Coin class GAME_005(Card): def action(self): self.controller.tempMana += 1
from ..card import * # The Coin class GAME_005(Card): def action(self): self.controller.tempMana += 1 # RFG # Adrenaline Rush class NEW1_006(Card): action = drawCard combo = drawCards(2)
Implement Adrenaline Rush why not
Implement Adrenaline Rush why not
Python
agpl-3.0
Ragowit/fireplace,butozerca/fireplace,Meerkov/fireplace,smallnamespace/fireplace,amw2104/fireplace,liujimj/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,oftc-ftw/fireplace,butozerca/fireplace,NightKev/fireplace,jleclanche/fireplace,liujimj/fireplace,Meerkov/fireplace,beheh/fireplace,smallnamespace/fireplace,amw2104/fi...
9410ceb83d85d70a484bbf08ecc274216fa0589f
mythril/support/source_support.py
mythril/support/source_support.py
from mythril.solidity.soliditycontract import SolidityContract from mythril.ethereum.evmcontract import EVMContract class Source: def __init__( self, source_type=None, source_format=None, source_list=None, meta=None ): self.source_type = source_type self.source_format = source_format ...
from mythril.solidity.soliditycontract import SolidityContract from mythril.ethereum.evmcontract import EVMContract class Source: """Class to handle to source data""" def __init__( self, source_type=None, source_format=None, source_list=None, meta=None ): """ :param source_type: w...
Add documentation for Source class
Add documentation for Source class
Python
mit
b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril
db46374695aed370aa8d8a51c34043d6a48a702d
waldo/tests/unit/test_contrib_config.py
waldo/tests/unit/test_contrib_config.py
# pylint: disable=R0904,W0212 # Copyright (c) 2011-2013 Rackspace Hosting # All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/lice...
# pylint: disable=C0103,C0111,R0903,R0904,W0212,W0232 # Copyright (c) 2011-2013 Rackspace Hosting # All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # ht...
Add common ignore list per README
Add common ignore list per README
Python
apache-2.0
checkmate/simpl,ryandub/simpl,ziadsawalha/simpl,samstav/simpl,larsbutler/simpl
ad98e3c25434dc251fe6d7ace3acfe418a4d8955
simplekv/db/mongo.py
simplekv/db/mongo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from .. import KeyValueStore from .._compat import BytesIO from .._compat import pickle from bson.binary import Binary class MongoStore(KeyValueStore): """Uses a MongoDB collection as the backend, using pickle as a serializer. :param db: A (already authenticate...
#!/usr/bin/env python # -*- coding: utf-8 -*- from .. import KeyValueStore from .._compat import BytesIO from .._compat import pickle from bson.binary import Binary class MongoStore(KeyValueStore): """Uses a MongoDB collection as the backend, using pickle as a serializer. :param db: A (already authenticate...
Fix Python3s lack of .next().
Fix Python3s lack of .next().
Python
mit
mbr/simplekv,karteek/simplekv,mbr/simplekv,fmarczin/simplekv,karteek/simplekv,fmarczin/simplekv
f87a923678f5d7e9f6390ffcb42eae6b2a0f9cc2
services/views.py
services/views.py
import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request....
import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request....
Use separate API key for feedback about app.
Use separate API key for feedback about app.
Python
agpl-3.0
City-of-Helsinki/smbackend,City-of-Helsinki/smbackend
b92c1caa8e19376c17f503de1464d4466e547cdf
api/base/content_negotiation.py
api/base/content_negotiation.py
from rest_framework.negotiation import BaseContentNegotiation class CustomClientContentNegotiation(BaseContentNegotiation): def select_parser(self, request, parsers): """ Select the first parser in the `.parser_classes` list. """ return parsers[0] def select_renderer(self, req...
from rest_framework.negotiation import BaseContentNegotiation class CustomClientContentNegotiation(BaseContentNegotiation): def select_parser(self, request, parsers): """ Select the first parser in the `.parser_classes` list. """ return parsers[0] def select_renderer(self, req...
Select third renderer if 'text/html' in accept
Select third renderer if 'text/html' in accept
Python
apache-2.0
brianjgeiger/osf.io,arpitar/osf.io,TomHeatwole/osf.io,Nesiehr/osf.io,zachjanicki/osf.io,RomanZWang/osf.io,DanielSBrown/osf.io,doublebits/osf.io,crcresearch/osf.io,amyshi188/osf.io,acshi/osf.io,monikagrabowska/osf.io,petermalcolm/osf.io,GageGaskins/osf.io,kwierman/osf.io,TomHeatwole/osf.io,cslzchen/osf.io,brandonPurvis/...
69de2261c30a8bab1ac4d0749cf32baec49e0cc4
webapp/byceps/blueprints/board/views.py
webapp/byceps/blueprints/board/views.py
# -*- coding: utf-8 -*- """ byceps.blueprints.board.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2014 Jochen Kupperschmidt """ from ...util.framework import create_blueprint from ...util.templating import templated from ..authorization.registry import permission_registry from .authorization import BoardPos...
# -*- coding: utf-8 -*- """ byceps.blueprints.board.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2014 Jochen Kupperschmidt """ from ...util.framework import create_blueprint from ...util.templating import templated from ..authorization.registry import permission_registry from .authorization import BoardPos...
Throw 404 if category/topic with given id is not found.
Throw 404 if category/topic with given id is not found.
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps
b890c9046d36687a65d46be724cfaa8726417b5d
selectable/tests/runtests.py
selectable/tests/runtests.py
#!/usr/bin/env python import os import sys from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', } }, INSTALLED_APPS=( ...
#!/usr/bin/env python import os import sys from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', } }, INSTALLED_APPS=( ...
Add SITE_ID to test settings setup for Django 1.3.
Add SITE_ID to test settings setup for Django 1.3.
Python
bsd-2-clause
mlavin/django-selectable,affan2/django-selectable,makinacorpus/django-selectable,makinacorpus/django-selectable,affan2/django-selectable,mlavin/django-selectable,mlavin/django-selectable,affan2/django-selectable
2d3b899011c79324195a36aaf3bd53dae6abe961
seleniumrequests/__init__.py
seleniumrequests/__init__.py
from selenium.webdriver import Firefox, Chrome, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote from seleniumrequests.request import RequestsSessionMixin class Firefox(RequestsSessionMixin, Firefox): pass class Chrome(RequestsSessionMixin, Chrome): pass class Ie(RequestsSessionMixin, Ie):...
from selenium.webdriver import _Firefox, _Chrome, _Ie, _Edge, _Opera, _Safari, _BlackBerry, _PhantomJS, _Android, \ _Remote from seleniumrequests.request import RequestsSessionMixin class Firefox(RequestsSessionMixin, _Firefox): pass class Chrome(RequestsSessionMixin, _Chrome): pass class Ie(Requests...
Fix PyCharm warnings like this: "Cannot find reference `request` in `PhantomJS | WebDriver`"
Fix PyCharm warnings like this: "Cannot find reference `request` in `PhantomJS | WebDriver`"
Python
mit
cryzed/Selenium-Requests
1e0327c852b851f867d21a182ba7604b42d15331
examples/charts/file/stacked_bar.py
examples/charts/file/stacked_bar.py
from bokeh.charts import Bar, output_file, show from bokeh.charts.operations import blend from bokeh.charts.attributes import cat, color from bokeh.charts.utils import df_from_json from bokeh.sampledata.olympics2014 import data from bokeh.models.tools import HoverTool # utilize utility to make it easy to get json/dic...
from bokeh.charts import Bar, output_file, show from bokeh.charts.operations import blend from bokeh.charts.attributes import cat, color from bokeh.charts.utils import df_from_json from bokeh.sampledata.olympics2014 import data # utilize utility to make it easy to get json/dict data converted to a dataframe df = df_fr...
Update stacked bar example to use the hover kwarg.
Update stacked bar example to use the hover kwarg.
Python
bsd-3-clause
Karel-van-de-Plassche/bokeh,rs2/bokeh,jakirkham/bokeh,msarahan/bokeh,DuCorey/bokeh,schoolie/bokeh,schoolie/bokeh,quasiben/bokeh,timsnyder/bokeh,KasperPRasmussen/bokeh,ericmjl/bokeh,stonebig/bokeh,bokeh/bokeh,ericmjl/bokeh,bokeh/bokeh,aavanian/bokeh,dennisobrien/bokeh,clairetang6/bokeh,DuCorey/bokeh,ericmjl/bokeh,azjps/...
05419e49c438c3f867c1ab4bd37021755ec09332
skimage/exposure/__init__.py
skimage/exposure/__init__.py
from .exposure import histogram, equalize, equalize_hist, \ rescale_intensity, cumulative_distribution, \ adjust_gamma, adjust_sigmoid, adjust_log from ._adapthist import equalize_adapthist __all__ = ['histogram', 'equalize', 'equalize_hist', ...
from .exposure import histogram, equalize, equalize_hist, \ rescale_intensity, cumulative_distribution, \ adjust_gamma, adjust_sigmoid, adjust_log from ._adapthist import equalize_adapthist from .unwrap import unwrap __all__ = ['histogram', 'equalize', ...
Make unwrap visible in the exposure package.
Make unwrap visible in the exposure package.
Python
bsd-3-clause
SamHames/scikit-image,ClinicalGraphics/scikit-image,chintak/scikit-image,bennlich/scikit-image,robintw/scikit-image,rjeli/scikit-image,youprofit/scikit-image,ClinicalGraphics/scikit-image,rjeli/scikit-image,chriscrosscutler/scikit-image,SamHames/scikit-image,blink1073/scikit-image,youprofit/scikit-image,GaZ3ll3/scikit-...
27e137ef5f3b6c4f6c8679edc6412b2c237b8fb4
plasmapy/physics/tests/test_parameters_cython.py
plasmapy/physics/tests/test_parameters_cython.py
"""Tests for functions that calculate plasma parameters using cython.""" import numpy as np import pytest from astropy import units as u from warnings import simplefilter from ...utils.exceptions import RelativityWarning, RelativityError from ...utils.exceptions import PhysicsError from ...constants import c, m_p, m_...
"""Tests for functions that calculate plasma parameters using cython.""" import numpy as np import pytest from astropy import units as u from warnings import simplefilter from plasmapy.utils.exceptions import RelativityWarning, RelativityError from plasmapy.utils.exceptions import PhysicsError from plasmapy.constants...
Update tests for cython parameters
Update tests for cython parameters
Python
bsd-3-clause
StanczakDominik/PlasmaPy
81bb47c28af70936be76f319ba780f2ad89ba2a0
Train_SDAE/tools/evaluate_model.py
Train_SDAE/tools/evaluate_model.py
import numpy as np # import pandas as pd # import sys from scipy.special import expit from sklearn import ensemble def get_activations(exp_data, w, b): exp_data = np.transpose(exp_data) prod = exp_data.dot(w) prod_with_bias = prod + b return( expit(prod_with_bias) ) # Order of *args: first all the wei...
import numpy as np from scipy.special import expit from sklearn import ensemble def get_activations(exp_data, w, b): exp_data = np.transpose(exp_data) prod = exp_data.dot(w) prod_with_bias = prod + b return( expit(prod_with_bias) ) # Order of *args: first all the weights and then all the biases def ru...
Support for variable number of layers
Support for variable number of layers
Python
apache-2.0
glrs/StackedDAE,glrs/StackedDAE
4986f02edbe45d73f8509b01270490cd8c8f90dd
docs/source/examples/chapel.sfile-inline.py
docs/source/examples/chapel.sfile-inline.py
from pych.extern import Chapel @Chapel(sfile="/home/safl/pychapel/module/ext/src/mymodule.chpl") def hello_mymodule(): return None @Chapel() def hello_inline(): """ writeln("Hello from inline."); """ return None if __name__ == "__main__": hello_mymodule() hello_inline()
from pych.extern import Chapel import os currentloc = os.getcwd(); # Note: depends on test living in a specific location relative to # mymodule.chpl. Not ideal, but also not a huge issue. @Chapel(sfile=currentloc + "/../../../module/ext/src/mymodule.chpl") def hello_mymodule(): return None @Chapel() def hello_i...
Use repository hierarchy instead of absolute path for sfile
Use repository hierarchy instead of absolute path for sfile The test chapel.sfile-inline.py was depending on an absolute path to find the location of a chapel file that was outside the normal sfile storage location. The absolute location was both machine and user-specific. I replaced the path with a relative path tha...
Python
apache-2.0
chapel-lang/pychapel,chapel-lang/pychapel,russel/pychapel,safl/pychapel,chapel-lang/pychapel,safl/pychapel,safl/pychapel,russel/pychapel,russel/pychapel,safl/pychapel
90974a088813dcc3a0c4a7cae5758f67c4b52a15
qual/tests/test_calendar.py
qual/tests/test_calendar.py
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def test_valid_date(self): d = self.calendar.date(1200, 2, 29) self.assertIsNotNone(d)
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNon...
Check a leap year date from before the start of the calendar.
Check a leap year date from before the start of the calendar. This is not really a strong test of the proleptic calendar. All days back to year 1 which are valid in the Julian calendar are valid in the Gregorian calendar.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
dc70fb35a104e260b40425fce23cba84b9770994
addons/event/models/res_partner.py
addons/event/models/res_partner.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResPartner(models.Model): _inherit = 'res.partner' event_count = fields.Integer("Events", compute='_compute_event_count', help="Number of events the partner has partic...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResPartner(models.Model): _inherit = 'res.partner' event_count = fields.Integer("Events", compute='_compute_event_count', help="Number of events the partner has partic...
Set default value for event_count
[FIX] event: Set default value for event_count Fixes https://github.com/odoo/odoo/pull/39583 This commit adds a default value for event_count Assigning default value for non-stored compute fields is required in 13.0 closes odoo/odoo#39974 X-original-commit: 9ca72b98f54d7686c0e6019870b40f14dbdd2881 Signed-off-by: Vi...
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
4f776ca2260419c06c2594568c73ce279426d039
GenotypeNetwork/test_genotype_network.py
GenotypeNetwork/test_genotype_network.py
import GenotypeNetwork as gn import os import networkx as nx GN = gn.GenotypeNetwork() GN.read_sequences('test/Demo_052715.fasta') GN.generate_genotype_network() GN.write_genotype_network('test/Demo_052715.pkl') GN.read_genotype_network('test/Demo_052715.pkl') def test_read_sequences_works_correctly(): """ C...
import GenotypeNetwork as gn import os import networkx as nx # Change cwd for tests to the current path. here = os.path.dirname(os.path.realpath(__file__)) os.chdir(here) GN = gn.GenotypeNetwork() GN.read_sequences('test/Demo_052715.fasta') GN.generate_genotype_network() GN.write_genotype_network('test/Demo_052715.pk...
Make tests run from correct directory.
Make tests run from correct directory.
Python
mit
ericmjl/genotype-network
453af98b1a05c62acd55afca431236d8f54fdae3
test_bert_trainer.py
test_bert_trainer.py
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(out...
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(out...
Test for deterministic results when testing BERT model
Test for deterministic results when testing BERT model
Python
apache-2.0
googleinterns/smart-news-query-embeddings,googleinterns/smart-news-query-embeddings
1d3e956dcf667601feb871eab2a462fa09d0d101
tests/test_length.py
tests/test_length.py
from math import sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_le...
from math import fabs, sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import floats, isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)],...
Test the axioms of normed vector spaces
tests/length: Test the axioms of normed vector spaces
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
052f06b0ef4f3c2befaf0cbbfd605e42553b48da
h2o-hadoop-common/tests/python/pyunit_trace.py
h2o-hadoop-common/tests/python/pyunit_trace.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- import sys import os sys.path.insert(1, os.path.join("..","..","..")) import h2o from h2o.exceptions import H2OServerError from tests import pyunit_utils def trace_request(): err = None try: h2o.api("TRACE /") except H2OServerError as e: err ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- import sys, os sys.path.insert(1, os.path.join("..", "..", "..", "h2o-py")) import h2o from h2o.exceptions import H2OServerError from tests import pyunit_utils def trace_request(): err = None try: h2o.api("TRACE /") except H2OServerError as e: ...
Fix TRACE test also in rel-yau
Fix TRACE test also in rel-yau
Python
apache-2.0
h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3
209a8e029e14766027376bb6d8f0b2e0a4a07f1b
simulator-perfect.py
simulator-perfect.py
#!/usr/bin/env python3 import timer import sys import utils # A set of files already in the storage seen = set() # The total number of uploads total_uploads = 0 # The number of files in the storage files_in = 0 tmr = timer.Timer() for (hsh, _) in utils.read_upload_stream(): if hsh not in seen: files_in ...
#!/usr/bin/env python3 import timer import sys import utils def simulate(): # A set of files already in the storage seen = set() # The size of the all uploads combined (deduplicated or not) total_in = 0 # The size of the data sent to the service data_in = 0 tmr = timer.Timer() for (...
Modify the perfect simulator to calculate dedup percentages based on file sizes (1 - data_in / data_total)
Modify the perfect simulator to calculate dedup percentages based on file sizes (1 - data_in / data_total)
Python
apache-2.0
sjakthol/dedup-simulator,sjakthol/dedup-simulator
dbe57e9b76194b13d90834163ebe8bf924464dd0
src/mcedit2/util/lazyprop.py
src/mcedit2/util/lazyprop.py
""" ${NAME} """ from __future__ import absolute_import, division, print_function, unicode_literals import logging log = logging.getLogger(__name__) def lazyprop(fn): """ Lazily computed property wrapper. >>> class Foo(object): ... @lazyprop ... def func(self): ... print("B...
""" ${NAME} """ from __future__ import absolute_import, division, print_function, unicode_literals import logging import weakref log = logging.getLogger(__name__) def lazyprop(fn): """ Lazily computed property wrapper. >>> class Foo(object): ... @lazyprop ... def func(self): ... ...
Add a property descriptor for weakref'd members
Add a property descriptor for weakref'd members
Python
bsd-3-clause
vorburger/mcedit2,Rubisk/mcedit2,Rubisk/mcedit2,vorburger/mcedit2
c89e30d1a33df2d9d8c5ceb03df98d29b3b08724
spacy/tests/en/test_exceptions.py
spacy/tests/en/test_exceptions.py
# coding: utf-8 """Test that tokenizer exceptions are handled correctly.""" from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["e.g.", "p.m.", "Jan.", "Dec.", "Inc."]) def test_tokenizer_handles_abbr(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) ==...
# coding: utf-8 """Test that tokenizer exceptions are handled correctly.""" from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["e.g.", "p.m.", "Jan.", "Dec.", "Inc."]) def test_tokenizer_handles_abbr(en_tokenizer, text): tokens = en_tokenizer(text) assert len(tokens) ==...
Add test for English time exceptions ("1a.m." etc.)
Add test for English time exceptions ("1a.m." etc.)
Python
mit
honnibal/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,recognai/spaCy,raphael0202/spaCy,aikramer2/spaCy,explosion/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,honnibal/spaCy,explosion/spaCy,raphael0202/spaCy,spacy-io/spaCy,honnibal/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,r...
99b1610fad7224d2efe03547c5114d2f046f50ca
bin/cgroup-limits.py
bin/cgroup-limits.py
#!/usr/bin/python env_vars = {} def read_file(path): try: with open(path, 'r') as f: return f.read().strip() except IOError: return None def get_memory_limit(): limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes') if limit: env_vars['MEMORY_LIMIT_IN_B...
#!/usr/bin/python from __future__ import print_function import sys env_vars = {} def read_file(path): try: with open(path, 'r') as f: return f.read().strip() except IOError: return None def get_memory_limit(): limit = read_file('/sys/fs/cgroup/memory/memory.limit_in_bytes')...
Print warnings to standard error
Print warnings to standard error
Python
apache-2.0
soltysh/sti-base,mfojtik/sti-base,hhorak/sti-base,bparees/sti-base,openshift/sti-base,sclorg/s2i-base-container,openshift/sti-base,mfojtik/sti-base,bparees/sti-base
e93dadc8215f3946e4e7b64ca8ab3481fcf3c197
froide/foirequestfollower/apps.py
froide/foirequestfollower/apps.py
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class FoiRequestFollowerConfig(AppConfig): name = 'froide.foirequestfollower' verbose_name = _('FOI Request Follower') def ready(self): from froide.account import account_canceled import froide.foire...
import json from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class FoiRequestFollowerConfig(AppConfig): name = 'froide.foirequestfollower' verbose_name = _('FOI Request Follower') def ready(self): from froide.account import account_canceled import...
Add user data export for foirequest follower
Add user data export for foirequest follower
Python
mit
fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide
29ffe1df88927aa568d3e86b07e372e5ba589310
indra/sources/eidos/server.py
indra/sources/eidos/server.py
"""This is a Python-based web server that can be run to read with Eidos. To run the server, do python -m indra.sources.eidos.server and then submit POST requests to the `localhost:5000/process_text` endpoint with JSON content as `{'text': 'text to read'}`. The response will be the Eidos JSON-LD output. """ impor...
"""This is a Python-based web server that can be run to read with Eidos. To run the server, do python -m indra.sources.eidos.server and then submit POST requests to the `localhost:5000/process_text` endpoint with JSON content as `{'text': 'text to read'}`. The response will be the Eidos JSON-LD output. """ impor...
Allow one or multiple texts to reground
Allow one or multiple texts to reground
Python
bsd-2-clause
sorgerlab/belpy,johnbachman/indra,bgyori/indra,johnbachman/belpy,bgyori/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,bgyori/indra,sorgerlab/belpy,sorgerlab/indra
46b60e3bb2b84685e27035a270e8ae81551f3f72
silver/management/commands/generate_docs.py
silver/management/commands/generate_docs.py
from optparse import make_option from datetime import datetime as dt from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings from dateutil.relativedelta import * from silver.documents_generator import DocumentsGenerator from silver.models import Subscr...
from optparse import make_option from datetime import datetime as dt from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings from dateutil.relativedelta import * from silver.documents_generator import DocumentsGenerator from silver.models import Subscr...
Add language code in the command
Add language code in the command
Python
apache-2.0
PressLabs/silver,PressLabs/silver,PressLabs/silver
13be198c8aec08f5738eecbb7da2bfdcafd57a48
pygraphc/clustering/MaxCliquesPercolationSA.py
pygraphc/clustering/MaxCliquesPercolationSA.py
from MaxCliquesPercolation import MaxCliquesPercolationWeighted class MaxCliquesPercolationSA(MaxCliquesPercolationWeighted): def __init__(self, graph, edges_weight, nodes_id, k, threshold): super(MaxCliquesPercolationSA, self).__init__(graph, edges_weight, nodes_id, k, threshold) def get_maxcliques_...
from MaxCliquesPercolation import MaxCliquesPercolationWeighted from pygraphc.optimization.SimulatedAnnealing import SimulatedAnnealing from numpy import linspace class MaxCliquesPercolationSA(MaxCliquesPercolationWeighted): def __init__(self, graph, edges_weight, nodes_id, k, threshold, tmin, tmax, alpha, energy...
Add constructor and get method with SA
Add constructor and get method with SA
Python
mit
studiawan/pygraphc
33309df85823bde19fcdd2b21b73db9f1da131ab
requests_oauthlib/compliance_fixes/facebook.py
requests_oauthlib/compliance_fixes/facebook.py
from json import dumps from oauthlib.common import urldecode from urlparse import parse_qsl def facebook_compliance_fix(session): def _compliance_fix(r): # if Facebook claims to be sending us json, let's trust them. if 'application/json' in r.headers['content-type']: return r ...
from json import dumps try: from urlparse import parse_qsl except ImportError: from urllib.parse import parse_qsl def facebook_compliance_fix(session): def _compliance_fix(r): # if Facebook claims to be sending us json, let's trust them. if 'application/json' in r.headers['content-type']:...
Remove unused import. Facebook compliance support python3
Remove unused import. Facebook compliance support python3
Python
isc
abhi931375/requests-oauthlib,gras100/asks-oauthlib,requests/requests-oauthlib,singingwolfboy/requests-oauthlib,jayvdb/requests-oauthlib,lucidbard/requests-oauthlib,dongguangming/requests-oauthlib,jsfan/requests-oauthlib,jayvdb/requests-oauthlib,sigmavirus24/requests-oauthlib,elafarge/requests-oauthlib
60a9ace22f219f7b125b3a618090c4dd36cded4c
api/base/exceptions.py
api/base/exceptions.py
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ from rest_framework.views import exception_handler response = exception_handler(exc, context) ...
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ from rest_framework.views import exception_handler response = exception_handler(exc, context) ...
Add additional error detail to cover other circumstances that intend to throw 401
Add additional error detail to cover other circumstances that intend to throw 401
Python
apache-2.0
abought/osf.io,mfraezz/osf.io,rdhyee/osf.io,GageGaskins/osf.io,TomHeatwole/osf.io,Ghalko/osf.io,pattisdr/osf.io,HalcyonChimera/osf.io,billyhunt/osf.io,brianjgeiger/osf.io,cosenal/osf.io,danielneis/osf.io,caseyrygt/osf.io,haoyuchen1992/osf.io,cslzchen/osf.io,acshi/osf.io,emetsger/osf.io,Nesiehr/osf.io,samanehsan/osf.io,...
18d06379a2dd89ef3d8db0d045f563b8f38f57db
badgekit_webhooks/urls.py
badgekit_webhooks/urls.py
from __future__ import unicode_literals from django.conf.urls import patterns, url from . import views from django.contrib.admin.views.decorators import staff_member_required urlpatterns = patterns( "", url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"), url(r"^issued/$", "b...
from __future__ import unicode_literals from django.conf.urls import patterns, url from . import views from django.contrib.admin.views.decorators import staff_member_required urlpatterns = patterns( "", url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"), url(r"^issued/$", "b...
Mark instance list as staff-only, and give it a view name
Mark instance list as staff-only, and give it a view name
Python
mit
tgs/django-badgekit-webhooks
fb15b0735a8d2710baa33ac4e74d1dc88de209bc
suplemon/lexer.py
suplemon/lexer.py
# -*- encoding: utf-8 import pygments import pygments.lexers class Lexer: def __init__(self, app): self.app = app def lex(self, code, lex): """Return tokenified code. Return a list of tuples (scope, word) where word is the word to be printed and scope the scope name represen...
# -*- encoding: utf-8 import pygments import pygments.lexers class Lexer: def __init__(self, app): self.app = app def lex(self, code, lex): """Return tokenified code. Return a list of tuples (scope, word) where word is the word to be printed and scope the scope name represen...
Make sure that Lexer.lex() returns str instead of bytes
Make sure that Lexer.lex() returns str instead of bytes
Python
mit
twolfson/suplemon,richrd/suplemon,richrd/suplemon,severin31/suplemon,twolfson/suplemon,trylle/suplemon
d8247d43c8026a8de39b09856a3f7beb235dc4f6
antxetamedia/multimedia/handlers.py
antxetamedia/multimedia/handlers.py
from boto.s3.connection import S3Connection from boto.exception import S3ResponseError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket.endswith('-'): bucket = bucket[:-1] t...
from boto.s3.connection import S3Connection from boto.s3.bucket import Bucket from boto.exception import S3ResponseError, S3CreateError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket...
Handle the case where the bucket already exists
Handle the case where the bucket already exists
Python
agpl-3.0
GISAElkartea/antxetamedia,GISAElkartea/antxetamedia,GISAElkartea/antxetamedia
e61bd9a56b31dde461ad0cb82e3140bd0dbfa958
ckanext/tayside/logic/action/update.py
ckanext/tayside/logic/action/update.py
from ckan.logic.action import update as update_core import ckan.lib.uploader as uploader def config_option_update(context, data_dict): upload = uploader.get_uploader('admin') upload.update_data_dict(data_dict, 'hero_image_url', 'hero_image_upload', 'clear_hero_image_upload') up...
from ckan.logic.action import update as update_core import ckan.lib.uploader as uploader def config_option_update(context, data_dict): upload = uploader.get_uploader('admin') upload.update_data_dict(data_dict, 'hero_image_url', 'hero_image_upload', 'clear_hero_image_upload') ...
Fix bug for saving images in config
Fix bug for saving images in config
Python
agpl-3.0
ViderumGlobal/ckanext-tayside,ViderumGlobal/ckanext-tayside,ViderumGlobal/ckanext-tayside,ViderumGlobal/ckanext-tayside
b0fd983269fca4c514a8a21d0bb17d47d46780c3
system_maintenance/tests/functional/base.py
system_maintenance/tests/functional/base.py
from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from system_maintenance.tests.utilities import populate_test_db class FunctionalTest(StaticLiveServerTestCase): def setUp(self): populate_test_db() ...
from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from system_maintenance.tests.utilities import populate_test_db class FunctionalTest(StaticLiveServerTestCase): def setUp(self): populate_test_db() ...
Make functional testing compatible with selenium 3.141.0
Make functional testing compatible with selenium 3.141.0
Python
bsd-3-clause
mfcovington/django-system-maintenance,mfcovington/django-system-maintenance,mfcovington/django-system-maintenance
7408862af1a6dc618e9dd78ece2120533466ab75
test/settings/gyptest-settings.py
test/settings/gyptest-settings.py
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Smoke-tests 'settings' blocks. """ import TestGyp test = TestGyp.TestGyp() test.run_gyp('settings.gyp') test.build('test.gyp', test.AL...
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Smoke-tests 'settings' blocks. """ import TestGyp # 'settings' is only supported for make and scons (and will be removed there as # we...
Make new settings test not run for xcode generator.
Make new settings test not run for xcode generator. TBR=evan Review URL: http://codereview.chromium.org/7472006
Python
bsd-3-clause
csulmone/gyp,csulmone/gyp,csulmone/gyp,csulmone/gyp
ff2def37816fbf1a8cf726914368036c0081e869
tests/integration/shared.py
tests/integration/shared.py
class ServiceTests(object): def test_bash(self): return self.check( input='bc -q\n1+1\nquit()', type='org.tyrion.service.bash', output='2', error='', code='0', ) def test_python(self): return self.check( input='pr...
class ServiceTests(object): def test_bash(self): return self.check( input='bc -q\n1+1\nquit()', type='org.tyrion.service.bash', output='2', error='', code='0', ) def test_python(self): return self.check( input='pr...
Tweak integration timeout test to match gtest
Tweak integration timeout test to match gtest
Python
mit
silas/tyrion,silas/tyrion,silas/tyrion,silas/tyrion,silas/tyrion
9aaf3bd6c376f608911b232d5f811e0b7964022f
tests/django_mysql_tests/tests.py
tests/django_mysql_tests/tests.py
# -*- coding:utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create()
# -*- coding:utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create() def test_t...
Add second test, trying to trigger travis
Add second test, trying to trigger travis
Python
mit
nickmeharry/django-mysql,nickmeharry/django-mysql,arnau126/django-mysql,adamchainz/django-mysql,arnau126/django-mysql,graingert/django-mysql,graingert/django-mysql
b0dd95950058d174e50589ceeb18c6a0e2a16ec8
docs/source/_static/export_all_data.py
docs/source/_static/export_all_data.py
#!/usr/bin/env python """export_all_data.py - script for exporting all available data""" import os from collectionbatchtool import * def export_all_data(output_dir=None): """ Export table data to CSV files. Parameters ---------- output_dir : str Path to the output directory. """ ...
#!/usr/bin/env python """export_all_data.py - script for exporting all available data""" import os from collectionbatchtool import * def export_all_data(output_dir=None, quiet=True): """ Export table data to CSV files. Parameters ---------- output_dir : str Path to the output directory....
Add parameter "quiet" to export function
Add parameter "quiet" to export function
Python
mit
jmenglund/CollectionBatchTool
3d027b8d4d39fcdbc839bd0e186ea225e1c7b976
tests/__init__.py
tests/__init__.py
from .test_great_expectations import * from .test_util import * from .test_dataset import * from .test_pandas_dataset import * from tests.pandas.test_pandas_dataset_distributional_expectations import * from .test_expectation_decorators import * from .test_cli import *
# from .test_great_expectations import * # from .test_util import * # from .test_dataset import * # from .test_pandas_dataset import * # from tests.pandas.test_pandas_dataset_distributional_expectations import * # from .test_expectation_decorators import * # from .test_cli import *
Remove explicit import in tests module.
Remove explicit import in tests module.
Python
apache-2.0
great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations
fa1b111e63ebd069c027a3b969f679b2de54949f
tests/conftest.py
tests/conftest.py
import pytest from sanic import Sanic from sanic_openapi import swagger_blueprint @pytest.fixture() def app(): app = Sanic('test') app.blueprint(swagger_blueprint) return app
import pytest from sanic import Sanic import sanic_openapi @pytest.fixture() def app(): app = Sanic("test") app.blueprint(sanic_openapi.swagger_blueprint) yield app # Clean up sanic_openapi.swagger.definitions = {} sanic_openapi.swagger._spec = {}
Add clean up in app fixture
Test: Add clean up in app fixture
Python
mit
channelcat/sanic-openapi,channelcat/sanic-openapi
04e5083006ee1faffbbdc73bd71b4601ff1db3ae
tests/workers/test_merge.py
tests/workers/test_merge.py
import pytest from mock import patch, MagicMock from gitfs.worker.merge import MergeWorker class TestMergeWorker(object): def test_run(self): mocked_queue = MagicMock() mocked_idle = MagicMock(side_effect=ValueError) mocked_queue.get.side_effect = ValueError() worker = MergeWork...
import pytest from mock import patch, MagicMock from gitfs.worker.merge import MergeWorker class TestMergeWorker(object): def test_run(self): mocked_queue = MagicMock() mocked_idle = MagicMock(side_effect=ValueError) mocked_queue.get.side_effect = ValueError() worker = MergeWork...
Test merge worker with commits and merges
test: Test merge worker with commits and merges
Python
apache-2.0
rowhit/gitfs,bussiere/gitfs,PressLabs/gitfs,PressLabs/gitfs,ksmaheshkumar/gitfs
3a2936bf55019dfd9203031ebe73966846b6f041
tests/test_dpp.py
tests/test_dpp.py
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from agents.dpp import DPP import replay_buffer from test_dqn_like import _TestDQNLike from chainer ...
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from agents.dpp import DPP from agents.dpp import DPPL from agents.dpp import DPPGreedy import repl...
Add tests for DPPL and DPPGreedy.
Add tests for DPPL and DPPGreedy.
Python
mit
toslunar/chainerrl,toslunar/chainerrl
7c1b539436b1f27896bc0e193b52838e2323519b
tutorials/urls.py
tutorials/urls.py
from django.conf.urls import include, url from tutorials import views urlpatterns = [ url(r'^$', views.ListTutorials.as_view()), url(r'add/', views.NewTutorial.as_view(), name='add_tutorial'), url(r'(?P<tutorial_id>[\w\-]+)/edit/', views.EditTutorials.as_view(), name='edit_tutorial'), # This must be ...
from django.conf.urls import include, url from tutorials import views urlpatterns = [ url(r'^$', views.ListTutorials.as_view(), name='list_tutorials'), url(r'add/', views.CreateNewTutorial.as_view(), name='add_tutorial'), url(r'(?P<tutorial_id>[\w\-]+)/edit/', views.EditTutorials.as_view(), name='edit_tut...
Add url name to ListView, New url for delete view, Refactor ViewClass name for NewTutorials to CreateNewTutorials
Add url name to ListView, New url for delete view, Refactor ViewClass name for NewTutorials to CreateNewTutorials
Python
agpl-3.0
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
835b8adfb610cdac0233840497f3a1cf9860f946
cerebro/tests/core/test_usecases.py
cerebro/tests/core/test_usecases.py
import unittest import cerebro.core.entities as en import cerebro.core.usecases as uc class TestUseCases(unittest.TestCase): def setUp(self): self.neurons_path = ["./cerebro/neurons"] self.neuron_test = ("system check") self.neuron_test_response = "All working properly." self.com...
import unittest import cerebro.core.entities as en import cerebro.core.usecases as uc class TestUseCases(unittest.TestCase): def setUp(self): self.neurons_path = ["./cerebro/neurons"] self.neuron_test = ("system check") self.neuron_test_response = "All working properly." self.com...
Test cases changed and minor optimization
Test cases changed and minor optimization
Python
mit
Le-Bot/cerebro
a0775510c81494777ab1adf7c822c4ca9a0227b2
tensorbayes/distributions.py
tensorbayes/distributions.py
""" Assumes softplus activations for gaussian """ import tensorflow as tf import numpy as np def log_bernoulli_with_logits(x, logits): return -tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(logits, x), 1) def log_normal(x, mu, var): return -0.5 * tf.reduce_sum(tf.log(2 * np.pi) + tf.log(var) + tf.squar...
""" Assumes softplus activations for gaussian """ import tensorflow as tf import numpy as np def log_bernoulli_with_logits(x, logits, eps=0.0): if eps > 0.0: max_val = np.log(1.0 - eps) - np.log(eps) logits = tf.clip_by_value(logits, -max_val, max_val, name='clipped_logit') return -tf.reduce_su...
Add eps factor for numerical stability
Add eps factor for numerical stability
Python
mit
RuiShu/tensorbayes
f603d382ab8b93677713d6c9c26f9b6a2616ba13
src/utils/indices.py
src/utils/indices.py
import json import os from elasticsearch import Elasticsearch from elasticsearch_dsl import Index from model import APIDoc _dirname = os.path.dirname(__file__) with open(os.path.join(_dirname, 'mapping.json'), 'r') as file: SMARTAPI_MAPPING = json.load(file) def setup(): """ Setup Elasticsearch Index. ...
import json import os from elasticsearch import Elasticsearch from elasticsearch_dsl import Index from model import APIDoc _dirname = os.path.dirname(__file__) with open(os.path.join(_dirname, 'mapping.json'), 'r') as file: SMARTAPI_MAPPING = json.load(file) def exists(): return Index(APIDoc.Index.name).exi...
Add a few methods used in admin.py
Add a few methods used in admin.py
Python
mit
Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI
e28c9da712574618eb28b6ff82631462fee67c16
changes/utils/times.py
changes/utils/times.py
def duration(value): ONE_SECOND = 1000 ONE_MINUTE = ONE_SECOND * 60 if not value: return '0 s' if value < 3 * ONE_SECOND: return '%d ms' % (value,) elif value < 5 * ONE_MINUTE: return '%d s' % (value / ONE_SECOND,) else: return '%d m' % (value / ONE_MINUTE,)
def duration(value): ONE_SECOND = 1000 ONE_MINUTE = ONE_SECOND * 60 if not value: return '0 s' abs_value = abs(value) if abs_value < 3 * ONE_SECOND: return '%d ms' % (value,) elif abs_value < 5 * ONE_MINUTE: return '%d s' % (value / ONE_SECOND,) else: retur...
Fix for negative values in duration
Fix for negative values in duration
Python
apache-2.0
bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes
876d414f85297d45dca4f2c9158f9257dfd6cf5f
wagtailgeowidget/edit_handlers.py
wagtailgeowidget/edit_handlers.py
import warnings import wagtail if wagtail.VERSION < (2, 0): warnings.warn("GeoPanel only works in Wagtail 2+", Warning) # NOQA warnings.warn("Please import GeoPanel from wagtailgeowidget.legacy_edit_handlers instead", Warning) # NOQA warnings.warn("All support for Wagtail 1.13 and below will be droppen ...
from wagtail.admin.edit_handlers import FieldPanel from wagtailgeowidget.widgets import ( GeoField, ) from wagtailgeowidget.app_settings import ( GEO_WIDGET_ZOOM ) class GeoPanel(FieldPanel): def __init__(self, *args, **kwargs): self.classname = kwargs.pop('classname', "") self.address_f...
Remove no-longer needed wagtail 2.0 warning
Remove no-longer needed wagtail 2.0 warning
Python
mit
Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget
d466785a4faaf1c01519935317ededf336f9dd14
contentstore/management/commands/tests/test_sync_schedules.py
contentstore/management/commands/tests/test_sync_schedules.py
from six import BytesIO from django.core.management import call_command from django.test import TestCase from mock import patch from contentstore.models import Schedule from seed_stage_based_messaging import test_utils as utils class SyncSchedulesTests(TestCase): @patch('contentstore.management.commands.sync_sch...
from six import StringIO from django.core.management import call_command from django.test import TestCase from mock import patch from contentstore.models import Schedule from seed_stage_based_messaging import test_utils as utils class SyncSchedulesTests(TestCase): @patch('contentstore.management.commands.sync_sc...
Use StringIO instead of BytesIO
Use StringIO instead of BytesIO
Python
bsd-3-clause
praekelt/seed-staged-based-messaging,praekelt/seed-stage-based-messaging,praekelt/seed-stage-based-messaging
fcd523105e9f158f423018d45b05527435a41fb0
geotrek/altimetry/tests/test_models.py
geotrek/altimetry/tests/test_models.py
import os from django.test import TestCase from django.conf import settings from geotrek.trekking.factories import TrekFactory from geotrek.trekking.models import Trek class AltimetryMixinTest(TestCase): def test_get_elevation_chart_none(self): trek = TrekFactory.create(no_path=True) trek.get_el...
import os from django.test import TestCase from django.conf import settings from django.utils.translation import get_language from geotrek.trekking.factories import TrekFactory from geotrek.trekking.models import Trek class AltimetryMixinTest(TestCase): def test_get_elevation_chart_none(self): trek = Tr...
Change test model elevation chart
Change test model elevation chart
Python
bsd-2-clause
GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,makinacorpus/Geotrek
68452ffc8490d976b043f660a0e3e1f19c4ed98e
great_expectations/actions/__init__.py
great_expectations/actions/__init__.py
from .actions import ( BasicValidationAction, NamespacedValidationAction, NoOpAction, SummarizeAndStoreAction, ) from .validation_operators import ( DefaultActionAwareValidationOperator )
from .actions import ( BasicValidationAction, NamespacedValidationAction, NoOpAction, SummarizeAndStoreAction, SlackNotificationAction ) from .validation_operators import ( DefaultActionAwareValidationOperator )
Add Slack action to init
Add Slack action to init
Python
apache-2.0
great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations
dabd787a647e345bdd9f3fd2fee1474b04347512
website/addons/base/utils.py
website/addons/base/utils.py
from os.path import basename from website import settings def serialize_addon_config(config): lookup = config.template_lookup return { 'addon_short_name': config.short_name, 'addon_full_name': config.full_name, 'node_settings_template': lookup.get_template(basename(config.node_setting...
from os.path import basename from website import settings def serialize_addon_config(config): lookup = config.template_lookup return { 'addon_short_name': config.short_name, 'addon_full_name': config.full_name, 'node_settings_template': lookup.get_template(basename(config.node_setting...
Use default settings if no user settings
Use default settings if no user settings
Python
apache-2.0
aaxelb/osf.io,DanielSBrown/osf.io,bdyetton/prettychart,HalcyonChimera/osf.io,rdhyee/osf.io,caseyrygt/osf.io,dplorimer/osf,icereval/osf.io,alexschiller/osf.io,pattisdr/osf.io,zachjanicki/osf.io,petermalcolm/osf.io,jmcarp/osf.io,KAsante95/osf.io,acshi/osf.io,cwisecarver/osf.io,adlius/osf.io,cldershem/osf.io,kch8qx/osf.io...