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 |
|---|---|---|---|---|---|---|---|---|---|
433167fb55378a73f4c0a808728f572de9d03e62 | swimlane/core/fields/valueslist.py | swimlane/core/fields/valueslist.py | import six
from .base import MultiSelectField
class ValuesListField(MultiSelectField):
field_type = 'Core.Models.Fields.ValuesListField, Core'
supported_types = six.string_types
def __init__(self, *args, **kwargs):
"""Map names to IDs for use in field rehydration"""
super(ValuesListFiel... | import six
from swimlane.exceptions import ValidationError
from .base import MultiSelectField
class ValuesListField(MultiSelectField):
field_type = 'Core.Models.Fields.ValuesListField, Core'
supported_types = six.string_types
def __init__(self, *args, **kwargs):
"""Map names to IDs for use in f... | Convert ValueError -> ValidationError in ValuesListField | Convert ValueError -> ValidationError in ValuesListField
| Python | mit | Swimlane/sw-python-client |
8d70645168ea4962359d67b00926f29544f4c506 | organizations/managers.py | organizations/managers.py | from django.db import models
class OrgManager(models.Manager):
def get_for_user(self, user):
return self.get_query_set().filter(users=user)
class ActiveOrgManager(OrgManager):
"""
A more useful extension of the default manager which returns querysets
including only active organizations
... | from django.db import models
class OrgManager(models.Manager):
def get_for_user(self, user):
if hasattr(self, 'get_queryset'):
return self.get_queryset().filter(users=user)
else:
# Deprecated method for older versions of Django
return self.get_query_set().filte... | Use get_queryset method by default | Use get_queryset method by default
Adds handler for get_query_set where the former method is not available
in the base manager class.
Closes gh-48
| Python | bsd-2-clause | GauthamGoli/django-organizations,DESHRAJ/django-organizations,bennylope/django-organizations,st8st8/django-organizations,GauthamGoli/django-organizations,DESHRAJ/django-organizations,bennylope/django-organizations,st8st8/django-organizations |
fbc757281aa6f0bdbba57fb21c89553a7274f58d | billjobs/tests/tests_model.py | billjobs/tests/tests_model.py | from django.test import TestCase, Client
from django.contrib.auth.models import User
from billjobs.models import Bill, Service
from billjobs.settings import BILLJOBS_BILL_ISSUER
class BillingTestCase(TestCase):
''' Test billing creation and modification '''
fixtures = ['dev_data.json']
def setUp(self):
... | from django.test import TestCase, Client
from django.contrib.auth.models import User
from billjobs.models import Bill, Service
from billjobs.settings import BILLJOBS_BILL_ISSUER
class BillingTestCase(TestCase):
''' Test billing creation and modification '''
fixtures = ['dev_data.json']
def setUp(self):
... | Save bill fixtures to test recorded values | Save bill fixtures to test recorded values
| Python | mit | ioO/billjobs |
7630ca3a1ced1a29f428efd2e60ce02a7a6c5869 | bin/update/deploy_dev_base.py | bin/update/deploy_dev_base.py | import logging
from commander.deploy import task
from deploy_base import * # noqa
log = logging.getLogger(__name__)
base_update_assets = update_assets
base_database = database
@task
def database(ctx):
# only ever run this one on demo and dev.
management_cmd(ctx, 'bedrock_truncate_database --yes-i-am-sure... | import logging
from commander.deploy import task
from deploy_base import * # noqa
log = logging.getLogger(__name__)
base_update_assets = update_assets
base_database = database
@task
def database(ctx):
# only ever run this one on demo and dev.
base_database()
management_cmd(ctx, 'rnasync')
managem... | Stop truncating the DB for dev/demo pushes. | Stop truncating the DB for dev/demo pushes.
| Python | mpl-2.0 | alexgibson/bedrock,jpetto/bedrock,MichaelKohler/bedrock,CSCI-462-01-2017/bedrock,CSCI-462-01-2017/bedrock,hoosteeno/bedrock,l-hedgehog/bedrock,Sancus/bedrock,alexgibson/bedrock,gerv/bedrock,gauthierm/bedrock,analytics-pros/mozilla-bedrock,mermi/bedrock,jpetto/bedrock,pascalchevrel/bedrock,l-hedgehog/bedrock,hoosteeno/b... |
6dc47f932b5c7f84918ec730b3ccd03d74070453 | app/py/cuda_sort/app_specific.py | app/py/cuda_sort/app_specific.py | import os
from cudatext import *
def get_ini_fn():
return os.path.join(app_path(APP_DIR_SETTINGS), 'cuda_sort.ini')
def ed_set_text_all(lines):
ed.set_text_all('\n'.join(lines)+'\n')
def ed_get_text_all():
n = ed.get_line_count()
if ed.get_text_line(n-1)=='': n-=1
return [ed.get_text_line(i) for ... | import os
from cudatext import *
def get_ini_fn():
return os.path.join(app_path(APP_DIR_SETTINGS), 'cuda_sort.ini')
def ed_set_text_all(lines):
ed.set_text_all('\n'.join(lines)+'\n')
def ed_get_text_all():
n = ed.get_line_count()
if ed.get_text_line(n-1)=='': n-=1
return [ed.get_text_line(i) for ... | Sort plg: fix caret pos after 'delete empty lines' | Sort plg: fix caret pos after 'delete empty lines'
| Python | mpl-2.0 | Alexey-T/CudaText,vhanla/CudaText,vhanla/CudaText,Alexey-T/CudaText,vhanla/CudaText,Alexey-T/CudaText,vhanla/CudaText,Alexey-T/CudaText,vhanla/CudaText,vhanla/CudaText,vhanla/CudaText,vhanla/CudaText,Alexey-T/CudaText,vhanla/CudaText,vhanla/CudaText,Alexey-T/CudaText,Alexey-T/CudaText,Alexey-T/CudaText |
ab68bce48b500d1ba9f7f5fa749f179ad78b5fdf | test/on_yubikey/cli_piv/test_misc.py | test/on_yubikey/cli_piv/test_misc.py | import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv',... | import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv',... | Test that piv read-object preserves ANSI escape codes | Test that piv read-object preserves ANSI escape codes
Objects written might (accidentally?) contain such codes, so they
should be preserved when read back out. For example, there's a 281 in
10^12 chance that any six random bytes happen to make the escape code for
red text colour.
| Python | bsd-2-clause | Yubico/yubikey-manager,Yubico/yubikey-manager |
bad8133c6714a25ad764419302f4db0da3f39952 | spec_cleaner/rpminstall.py | spec_cleaner/rpminstall.py | # vim: set ts=4 sw=4 et: coding=UTF-8
import string
from rpmsection import Section
class RpmInstall(Section):
'''
Remove commands that wipe out the build root.
Replace %makeinstall (suse-ism).
'''
def add(self, line):
install_command = 'make DESTDIR=%{buildroot} install %{?_smp_... | # vim: set ts=4 sw=4 et: coding=UTF-8
from rpmsection import Section
class RpmInstall(Section):
'''
Remove commands that wipe out the build root.
Replace %makeinstall (suse-ism).
'''
def add(self, line):
install_command = 'make DESTDIR=%{buildroot} install %{?_smp_mflags}'
... | Fix test failures on py3. | Fix test failures on py3.
| Python | bsd-3-clause | plusky/spec-cleaner,plusky/spec-cleaner,pombredanne/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,pombredanne/spec-cleaner,plusky/spec-cleaner |
619fa5a8345a32eb2913b85f01b9d2bc8453b688 | sms_939/controllers/sms_notification_controller.py | sms_939/controllers/sms_notification_controller.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | Put SMS answer job in very high priority | Put SMS answer job in very high priority
| Python | agpl-3.0 | CompassionCH/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland |
bd26414b71497bbf39e40bd3b676cc345880b5dd | byceps/services/image/service.py | byceps/services/image/service.py | """
byceps.services.image.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import BinaryIO, FrozenSet, Iterable, Set
from ...util.image import read_dimensions
from ...util.image.models import Dimensions, ImageType
from .... | """
byceps.services.image.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import BinaryIO, FrozenSet, Iterable, Set
from ...util.image import read_dimensions
from ...util.image.models import Dimensions, ImageType
from .... | Remove constant and function that list all existing image types | Remove constant and function that list all existing image types
This allows having additional image types for (temporarily) internal
purposes without accidentally exposing them.
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps |
ef69cad1175fa92543fce085cd46a9ec990fa55b | nbresuse/__init__.py | nbresuse/__init__.py | from notebook.utils import url_path_join
from tornado import ioloop
from nbresuse.api import ApiHandler
from nbresuse.config import ResourceUseDisplay
from nbresuse.metrics import PSUtilMetricsLoader
from nbresuse.prometheus import PrometheusHandler
def _jupyter_server_extension_paths():
"""
Set up the serve... | from notebook.utils import url_path_join
from tornado import ioloop
from nbresuse.api import ApiHandler
from nbresuse.config import ResourceUseDisplay
from nbresuse.metrics import PSUtilMetricsLoader
from nbresuse.prometheus import PrometheusHandler
def _jupyter_server_extension_paths():
"""
Set up the serve... | Add back the /metrics endpoint | Add back the /metrics endpoint
| Python | bsd-2-clause | yuvipanda/nbresuse,yuvipanda/nbresuse |
8b1c229aa3891ca80c88f3514d9c7014cf7909fc | src/epiweb/apps/survey/views.py | src/epiweb/apps/survey/views.py | # -*- coding: utf-8 -*-
from django import forms
from django.template import Context, loader
from django.http import HttpResponse
from epiweb.apps.survey import utils
from epiweb.apps.survey.data import example
def create_field(item):
if item['type'] == 'yes-no':
field = forms.ChoiceField(widget=forms.Ra... | # -*- coding: utf-8 -*-
from django import forms
from django.template import Context, loader
from django.http import HttpResponse
from epiweb.apps.survey import utils
from epiweb.apps.survey.data import example
def index(request):
if request.method == 'POST':
form = utils.generate_form(example.data.sect... | Remove form generator from the view. | Remove form generator from the view.
| Python | agpl-3.0 | ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website |
cba49af7fce05eb22fda3012f23c8fa8736fd022 | polling_stations/apps/pollingstations/migrations/0009_customfinder.py | polling_stations/apps/pollingstations/migrations/0009_customfinder.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('pollingstations', '0006_residentialaddress_slug'),
]
operations = [
migrations.CreateModel(
name='CustomFinder',... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('pollingstations', '0008_auto_20160415_1854'),
]
operations = [
migrations.CreateModel(
name='CustomFinder',
... | Edit migration so it depends on 0008_auto_20160415_1854 | Edit migration so it depends on 0008_auto_20160415_1854
Ensure the migrations will apply correctly without conflcit once merged
Merging this branch is now blocked on PR #239
| Python | bsd-3-clause | chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations |
361c0293085a688cc60e06b675eca66c9c52d72e | pi_approach/Distance_Pi/recv.py | pi_approach/Distance_Pi/recv.py | # Lidar Project Distance Subsystem
import serial
import socket
import time
arduino_dist = serial.Serial('/dev/ttyUSB0',9600)
def get_distance():
distance = arduino_dist.readline()
return distance
class Client(object):
"""A class that uses sockets to connect to a server"""
HOST = "userinterface.local"
PORT = 12... | # Lidar Project Distance Subsystem
import serial
import socket
import time
import sys
sys.path.insert(0, "/home/pi/lidar/pi_approach/Libraries")
import serverxclient
arduino_dist = serial.Serial('/dev/ttyUSB0',9600)
def get_distance():
distance = arduino_dist.readline()
return distance
client = Client()
client.so... | Remove local use of client, instead rely on imported library | Remove local use of client, instead rely on imported library
| Python | mit | the-raspberry-pi-guy/lidar |
0cc12b24ec4aac88380a36bb519bfc78ad81b277 | run_job.py | run_job.py | #!/usr/bin/env python
#
# Syntax: ./run_job <session-id>
#
# It should be run with the current working directory set properly
#
import sys, json
from sci.session import Session
from sci.bootstrap import Bootstrap
data = json.loads(sys.stdin.read())
session_id = sys.argv[1]
session = Session.load(session_id)
run_info... | #!/usr/bin/env python
#
# Syntax: ./run_job <session-id>
#
# It should be run with the current working directory set properly
#
import sys, json
from sci.session import Session
from sci.bootstrap import Bootstrap
data = json.loads(sys.stdin.read())
session_id = sys.argv[1]
session = Session.load(session_id)
run_info... | Support when run_info is not specified | Support when run_info is not specified
That is the case when starting a build (not running a step)
| Python | apache-2.0 | boivie/sci,boivie/sci |
2b60161118c2407c9bff736710b4f1a4b62a7468 | scipy/constants/tests/test_codata.py | scipy/constants/tests/test_codata.py |
import warnings
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = find('qwertyuiop', disp=False)
... |
import warnings
import codata
import constants
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = fin... | Add very basic tests for codata and constants. | ENH: Add very basic tests for codata and constants.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@6563 d6536bca-fef9-0310-8506-e4c0a848fbcf
| Python | bsd-3-clause | lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor |
8842bbf45ffe2a76832075e053dce90a95964bcd | Bookie/bookie/tests/__init__.py | Bookie/bookie/tests/__init__.py | import ConfigParser
import os
import unittest
from pyramid.config import Configurator
from pyramid import testing
global_config = {}
ini = ConfigParser.ConfigParser()
ini.read('test.ini')
settings = dict(ini.items('app:bookie'))
def setup_db(settings):
""" We need to create the test sqlite database to run our t... | import ConfigParser
import os
import unittest
from pyramid.config import Configurator
from pyramid import testing
global_config = {}
ini = ConfigParser.ConfigParser()
# we need to pull the right ini for the test we want to run
# by default pullup test.ini, but we might want to test mysql, pgsql, etc
test_ini = os.en... | Add ability to set test ini via env variable | Add ability to set test ini via env variable
| Python | agpl-3.0 | charany1/Bookie,teodesson/Bookie,skmezanul/Bookie,teodesson/Bookie,skmezanul/Bookie,adamlincoln/Bookie,adamlincoln/Bookie,adamlincoln/Bookie,GreenLunar/Bookie,bookieio/Bookie,pombredanne/Bookie,wangjun/Bookie,adamlincoln/Bookie,pombredanne/Bookie,pombredanne/Bookie,skmezanul/Bookie,bookieio/Bookie,charany1/Bookie,Green... |
0ae8cb79ef13ac652edca3a29825436c8c2d6cd8 | SessionManager.py | SessionManager.py | import sublime
import sublime_plugin
from .modules import messages
from .modules import settings
class SaveSession(sublime_plugin.ApplicationCommand):
def run(self):
settings.load()
sublime.active_window().show_input_panel(
messages.dialog("session_name"),
se... | import sublime
import sublime_plugin
from .modules import messages
from .modules import serialize
from .modules import settings
from .modules.session import Session
class SaveSession(sublime_plugin.ApplicationCommand):
def run(self):
settings.load()
sublime.active_window().show_inpu... | Save the session on SaveSession | Save the session on SaveSession
| Python | mit | Zeeker/sublime-SessionManager |
d650cbe26ce0fcc4c5146466d2827b930c153b0f | PlatformPhysicsOperation.py | PlatformPhysicsOperation.py | from UM.Operations.Operation import Operation
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
from UM.Operations.TranslateOperation import TranslateOperation
## A specialised operation designed specifically to modify the previous operation.
class PlatformPhysicsOperation(Operation):
def __in... | from UM.Operations.Operation import Operation
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
from UM.Operations.TranslateOperation import TranslateOperation
from UM.Operations.GroupedOperation import GroupedOperation
## A specialised operation designed specifically to modify the previous operat... | Use GroupedOperation for merging PlatformPhyisicsOperation | Use GroupedOperation for merging PlatformPhyisicsOperation
| Python | agpl-3.0 | senttech/Cura,quillford/Cura,fxtentacle/Cura,hmflash/Cura,totalretribution/Cura,ynotstartups/Wanhao,bq/Ultimaker-Cura,lo0ol/Ultimaker-Cura,lo0ol/Ultimaker-Cura,DeskboxBrazil/Cura,derekhe/Cura,fxtentacle/Cura,fieldOfView/Cura,quillford/Cura,fieldOfView/Cura,derekhe/Cura,senttech/Cura,totalretribution/Cura,DeskboxBrazil/... |
d77fcfc212b81c2935a2de9b712af5b6f8c43ee1 | server/mlabns/tests/test_distance.py | server/mlabns/tests/test_distance.py | import unittest2
from mlabns.util import distance
class DistanceTestCase(unittest2.TestCase):
def testValidSmallDistance(self):
dist = distance.distance(0, 0, 10, 10)
self.assertEqual(1568.5205567985761, dist)
def testValidLargeDistance(self):
dist = distance.distance(20, 20, 100, 100)
self.asse... | import unittest2
from mlabns.util import distance
class DistanceTestCase(unittest2.TestCase):
def testValidSmallDistance(self):
dist = distance.distance(0, 0, 10, 10)
self.assertEqual(1568.5205567985761, dist)
def testValidLargeDistance(self):
dist = distance.distance(20, 20, 100, 10... | Update indentation as per style guide | Update indentation as per style guide
| Python | apache-2.0 | fernandalavalle/mlab-ns,m-lab/mlab-ns,fernandalavalle/mlab-ns,m-lab/mlab-ns,m-lab/mlab-ns,fernandalavalle/mlab-ns,m-lab/mlab-ns,fernandalavalle/mlab-ns |
fa8cfbc631dfab0067b8c15bf6374579af071e7a | tests/test_main.py | tests/test_main.py | import sys
import unittest
import tempfile
import pathlib
import os
import os.path
from unittest.mock import patch
import monitor
class TestMonitor(unittest.TestCase):
def test_MonitorConfigInterval(self):
with self.assertRaises(SystemExit):
testargs = ["monitor.py", "-f", "tests/mocks/ini/m... | import sys
import unittest
import tempfile
import pathlib
import os
import os.path
import time
from unittest.mock import patch
import monitor
class TestMonitor(unittest.TestCase):
def test_MonitorConfigInterval(self):
with self.assertRaises(SystemExit):
testargs = ["monitor.py", "-f", "tests... | Add sleep during tests to prevent race | Add sleep during tests to prevent race
| Python | bsd-3-clause | jamesoff/simplemonitor,jamesoff/simplemonitor,jamesoff/simplemonitor,jamesoff/simplemonitor,jamesoff/simplemonitor |
95474b52fd81b8363809fe915bd38d00335424a9 | thinglang/execution/builtins.py | thinglang/execution/builtins.py | class ThingObjectBase(object):
def __getitem__(self, item):
return getattr(self, item)
def __contains__(self, item):
return hasattr(self, item)
class ThingObjectOutput(ThingObjectBase):
def __init__(self):
self.data = []
def write(self, *args):
self.data.append(' '.... | class ThingObjectBase(object):
def __getitem__(self, item):
return getattr(self, item)
def __contains__(self, item):
return hasattr(self, item)
class ThingObjectOutput(ThingObjectBase):
def __init__(self):
self.data = []
def write(self, *args):
self.data.append(' '.... | Update Input object to support direct output during get_line operations | Update Input object to support direct output during get_line operations
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang |
bdf35f5d45bd701bc720cd7bed6db5d7b311e713 | pyxform/tests_v1/test_background_audio.py | pyxform/tests_v1/test_background_audio.py | # -*- coding: utf-8 -*-
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class AuditTest(PyxformTestCase):
def test_background_audio(self):
self.assertPyxformXform(
name="data",
md="""
| survey | | |
| |... | # -*- coding: utf-8 -*-
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
import unittest
class BackgroundAudioTest(PyxformTestCase):
def test_background_audio(self):
self.assertPyxformXform(
name="data",
md="""
| survey | | ... | Add ignored test for recordaction validation | Add ignored test for recordaction validation
| Python | bsd-2-clause | XLSForm/pyxform,XLSForm/pyxform |
9ef4d62362ab38623499d7f00bab1b05c9e016c0 | user_deletion/notifications.py | user_deletion/notifications.py | from django.conf import settings
from django.core.mail import send_mass_mail
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from pigeon.notification import Notification
def send_emails(notification):
messages = []
context = {'site': notification.sit... | from django.conf import settings
from django.core.mail import send_mass_mail
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from pigeon.notification import Notification
def build_emails(notification):
context = {'site': notification.site}
for user i... | Use a generator instead of append | Use a generator instead of append
| Python | bsd-2-clause | incuna/django-user-deletion |
7d8d5516a279cf1349af703f9051bb1acf084eaa | tests/test_browser_test_case.py | tests/test_browser_test_case.py | from unittest import TestCase
from keteparaha.browser import BrowserTestCase
class BrowserTestCaseTest(TestCase):
class SubClassed(BrowserTestCase):
def do_nothing(self):
pass
def test_start_browser_when_given_unsupported_driver(self):
bc = self.SubClassed("do_nothing")
... | from unittest import TestCase
from keteparaha.browser import BrowserTestCase
class SubClassed(BrowserTestCase):
def do_nothing(self):
pass
class BrowserTestCaseTest(TestCase):
def test_browser_returns_last_browser_started(self):
btc = SubClassed('do_nothing')
btc.browsers.appe... | Modify tests for the BrowserTestCase class so they don't hang | Modify tests for the BrowserTestCase class so they don't hang
| Python | mit | aychedee/keteparaha,tomdottom/keteparaha |
9510a0da5a6fee780e16db8f128f7c24bdb579d4 | tests/test_post_import_hooks.py | tests/test_post_import_hooks.py | from __future__ import print_function
import unittest
import wrapt
class TestPostImportHooks(unittest.TestCase):
def test_simple(self):
invoked = []
@wrapt.when_imported('socket')
def hook_socket(module):
self.assertEqual(module.__name__, 'socket')
invoked.append... | from __future__ import print_function
import unittest
import wrapt
class TestPostImportHooks(unittest.TestCase):
def test_simple(self):
invoked = []
@wrapt.when_imported('this')
def hook_this(module):
self.assertEqual(module.__name__, 'this')
invoked.append(1)
... | Adjust test to use different module as socket imported by coverage tools. | Adjust test to use different module as socket imported by coverage tools.
| Python | bsd-2-clause | linglaiyao1314/wrapt,pombredanne/python-lazy-object-proxy,linglaiyao1314/wrapt,pombredanne/wrapt,akash1808/wrapt,pombredanne/wrapt,github4ry/wrapt,wujuguang/wrapt,pombredanne/python-lazy-object-proxy,akash1808/wrapt,ionelmc/python-lazy-object-proxy,ionelmc/python-lazy-object-proxy,github4ry/wrapt,GrahamDumpleton/wrapt,... |
101a7c8e0e26089d6d1deb4e7728e4eb59274b74 | app/main/forms.py | app/main/forms.py | from flask.ext.wtf import Form
from wtforms import validators
from dmutils.forms import StripWhitespaceStringField
from .. import data_api_client
class AdminEmailAddressValidator(object):
def __init__(self, message=None):
self.message = message
def __call__(self, form, field):
if not data_... | from flask.ext.wtf import Form
from wtforms import RadioField, validators
from dmutils.forms import StripWhitespaceStringField
from .. import data_api_client
class AdminEmailAddressValidator(object):
def __init__(self, message=None):
self.message = message
def __call__(self, form, field):
... | Add InviteAdminForm with email_address and role fields | Add InviteAdminForm with email_address and role fields
| Python | mit | alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend |
31bbec5d55437d36b78ca1c36dee19e74203695b | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(
name = 'ffn',
version = '0.1.0',
author = 'Michal Januszewski',
author_email = 'mjanusz@google.com',
packages = ['ffn', 'ffn.inference', 'ffn.training', 'ffn.utils'],
scripts = ['build_coordinates.py', 'compute_partitions.py', 'run_inference.py',... | #!/usr/bin/env python
from distutils.core import setup
setup(
name = 'ffn',
version = '0.1.0',
author = 'Michal Januszewski',
author_email = 'mjanusz@google.com',
packages = ['ffn', 'ffn.inference', 'ffn.training', 'ffn.training.models', 'ffn.utils'],
scripts = ['build_coordinates.py', 'compute_partitions.p... | Add ffn.training.models and switch to Pillow. | Add ffn.training.models and switch to Pillow.
It is still easier to use this repo via git clone rather than pip
install, e.g. from Colab. But this seemed worth updating anyway.
| Python | apache-2.0 | google/ffn |
1ee1a337cb3094ae5a5cc79b6d4c62c2f7f64dc3 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(
name='dbtools',
version=open("VERSION.txt").read().strip(),
description='Lightweight SQLite interface',
author='Jessica B. Hamrick',
author_email='jhamrick@berkeley.edu',
url='https://github.com/jhamrick/dbtools',
packages=['dbt... | #!/usr/bin/env python
from distutils.core import setup
setup(
name='dbtools',
version=open("VERSION.txt").read().strip(),
description='Lightweight SQLite interface',
author='Jessica B. Hamrick',
author_email='jhamrick@berkeley.edu',
url='https://github.com/jhamrick/dbtools',
packages=['dbt... | Add trove classifier for Python 3 | Add trove classifier for Python 3
| Python | mit | jhamrick/dbtools,jhamrick/dbtools |
f981802947fd2c15be04489f6805395971807c9d | PVGeo/__main__.py | PVGeo/__main__.py | __all__ = [
'test',
]
def test():
"""
@desc: This is a convienance method to run all of the tests in `PVGeo`.
@notes:
This can be executed from either the command line of within a standard Python environment:
```bash
$ python -m PVGeo test
```
```py
>>> import PVGeo
>>> P... | __all__ = [
'test',
]
def test(close=False):
"""
@desc: This is a convienance method to run all of the tests in `PVGeo`.
@notes:
This can be executed from either the command line of within a standard Python environment:
```bash
$ python -m PVGeo test
```
```py
>>> import PVGe... | Add catch for Travis CI testing. | Add catch for Travis CI testing.
| Python | bsd-3-clause | banesullivan/ParaViewGeophysics,banesullivan/ParaViewGeophysics,banesullivan/ParaViewGeophysics |
0406ddcb3e22f8f3eb3b1fdba702e41ebe8b5bf0 | connector/tests/__init__.py | connector/tests/__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | Remove deprecated fast_suite and check list for unit tests | Remove deprecated fast_suite and check list for unit tests
| Python | agpl-3.0 | OCA/connector,OCA/connector |
9dafef749aaf2fca9e865cf28b043ea22bafe3a5 | backend/django/apps/accounts/tests.py | backend/django/apps/accounts/tests.py | from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import factory
import json
from .models import BaseAccount
from .serializers import WholeAccountSerializer
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = B... | from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import factory
import json
from .models import BaseAccount
from .serializers import WholeAccountSerializer
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = B... | Create a test for Account creation | Create a test for Account creation
| Python | mit | slavpetroff/sweetshop,slavpetroff/sweetshop |
994b9fbc9372b0c54f840a239f8b4a1cc89315ee | src/waldur_mastermind/invoices/filters.py | src/waldur_mastermind/invoices/filters.py | import django_filters
from waldur_core.core import filters as core_filters
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
state = dja... | import django_filters
from waldur_core.core import filters as core_filters
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
state = dja... | Allow to filter invoices by date | Allow to filter invoices by date [WAL-2340]
| Python | mit | opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur |
f25814cd2a91cb183e6cdae4a4597534dc8de17e | codesearch/paths.py | codesearch/paths.py | # Copyright 2017 The Chromium Authors.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd.
import os
def GetPackageRelativePath(filename):
"""GetPackageRelativePath returns the path to |filename| rela... | # Copyright 2017 The Chromium Authors.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd.
import os
class NoSourceRootError(Exception):
"""Exception raise when the CodeSearch library can't determine... | Raise a more specific exception when the source root cannot be found. | Raise a more specific exception when the source root cannot be found.
| Python | bsd-3-clause | chromium/codesearch-py,chromium/codesearch-py |
7e153f0cb35a3572a724c29f3be26bf6254d632b | client/views.py | client/views.py | from django.shortcuts import render
from django.http import HttpResponse, Http404
from .models import Message
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def chatroom(request):
messages = Message.objects.order_by('date')
context = {'messages': messages}
... | from django.shortcuts import render, render_to_response, HttpResponseRedirect
from django.http import HttpResponse, Http404
from .models import Message, MessageForm
from django.contrib.auth.decorators import login_required
import datetime
# Create your views here.
@login_required
def chatroom(request):
# if this i... | Update chatroom view to process new messages | Update chatroom view to process new messages
| Python | apache-2.0 | jason-feng/chatroom,jason-feng/chatroom,jason-feng/chatroom,jason-feng/chatroom |
59a717588c9f0e76d532516a0c38624042527291 | testing/plot_test_data.py | testing/plot_test_data.py |
import zephyr.util
from zephyr.collector import MeasurementCollector
from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler
from zephyr.message import MessagePayloadParser
from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial
from zephyr.protocol import Protocol... |
import zephyr.util
from zephyr.collector import MeasurementCollector
from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler
from zephyr.message import MessagePayloadParser
from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial
from zephyr.protocol import Protocol... | Fix test data plotting to use the changed interfaces | Fix test data plotting to use the changed interfaces | Python | bsd-2-clause | jpaalasm/zephyr-bt |
19280ac68748cb5cd2cb439edeb667f581840604 | tests/test_http_client.py | tests/test_http_client.py | import unittest
import httpretty
from fbmsgbot.http_client import HttpClient
from fbmsgbot.resources.urls import FACEBOOK_MESSAGES_POST_URL
class TestHttpClient(unittest.TestCase):
"""
Test the HttpClient
"""
@httpretty.activate
def test_submit_GET_request(self):
httpretty.register_uri... | import unittest
import httpretty
from fbmsgbot.http_client import HttpClient
from fbmsgbot.resources.urls import FACEBOOK_MESSAGES_POST_URL
class TestHttpClient(unittest.TestCase):
"""
Test the HttpClient
"""
@httpretty.activate
def test_submit_GET_request(self):
httpretty.register_uri... | Update tests to remove completion blocks | Update tests to remove completion blocks
| Python | mit | ben-cunningham/pybot,ben-cunningham/python-messenger-bot |
01382a617d075b468ea8a08087f298da5c55a46c | kolibri/core/bookmarks/models.py | kolibri/core/bookmarks/models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from morango.models import UUIDField
from kolibri.core.auth.models import AbstractFacilityDataModel
from kolibri.core.auth.models import Facility
from kolibri.core.auth.models import Facility... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from morango.models import UUIDField
from kolibri.core.auth.models import AbstractFacilityDataModel
from kolibri.core.auth.models import FacilityUser
from kolibri.core.auth.permissions.genera... | Remove unnecessary cruft from Bookmark.infer_dataset | Remove unnecessary cruft from Bookmark.infer_dataset
| Python | mit | learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri |
40aa16d48c58a17ab08ac526e1a8806214167a1b | carnifex/test/integration/test_local_process.py | carnifex/test/integration/test_local_process.py | from twisted.trial.unittest import TestCase
from carnifex.localprocess import LocalProcessInductor
from twisted.internet import reactor
class InductorTest(TestCase):
def test_real_run(self):
executable = 'echo'
echo_text = "hello world!"
expected_stdout = echo_text + '\n'
inductor... | from twisted.trial.unittest import TestCase
from carnifex.localprocess import LocalProcessInductor
from twisted.internet import reactor
class InductorTest(TestCase):
def test_real_run(self):
executable = 'echo'
echo_text = "hello world!"
expected_stdout = echo_text + '\n'
inductor... | Add more tests to the local process integration test | Add more tests to the local process integration test
| Python | mit | sporsh/carnifex |
446da2ceffb49fe694026c3e8d3c7f24cdcc4215 | tests.py | tests.py | """Test suite for Mann."""
# -*- coding: utf-8 -*-
import unittest
from colour_runner import runner as crunner
# from mypleasure.mann import Mann
class ConsoleTestCase(unittest.TestCase):
"""Test console logger."""
def runTest(self): # noqa
pass
def suite():
"""Compose and return test suite."""... | """Test suite for Mann."""
# -*- coding: utf-8 -*-
import sys
import unittest
from io import StringIO
from colour_runner import runner as crunner
from mypleasure.mann import Mann
class ConsoleTestCase(unittest.TestCase):
"""Test console logger."""
def runTest(self): # noqa
try:
out = Stri... | Create test for console output. | Create test for console output.
| Python | mit | mypleasureteam/mann |
b19951bcf2035c9e755ad731e4f5081cf5f0d46f | troposphere/codeguruprofiler.py | troposphere/codeguruprofiler.py | # Copyright (c) 2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject
class ProfilingGroup(AWSObject):
resource_type = "AWS::CodeGuruProfiler::ProfilingGroup"
props = {
'ProfilingGroupName': (basestring, True),
}
| # Copyright (c) 2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject
class ProfilingGroup(AWSObject):
resource_type = "AWS::CodeGuruProfiler::ProfilingGroup"
props = {
'AgentPermissions': (dict, False),
'ProfilingGroupName': (b... | Update AWS::CodeGuruProfiler::ProfilingGroup per 2020-06-03 changes | Update AWS::CodeGuruProfiler::ProfilingGroup per 2020-06-03 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere |
22a0968d92ef81e021aeae5ab4fd724cc64a3f8c | saleor/site/utils.py | saleor/site/utils.py | from django.conf import settings
from .models import SiteSetting
def get_site_settings(request):
if not hasattr(request, 'site_settings'):
site_settings_id = getattr(settings, 'SITE_SETTINGS_ID', None)
request.site_settings = get_site_settings_uncached(site_settings_id)
return request.site_se... | from django.conf import settings
from .models import SiteSetting
def get_site_settings(request):
if not hasattr(request, 'site_settings'):
site_settings_id = getattr(settings, 'SITE_SETTINGS_ID', None)
request.site_settings = get_site_settings_uncached(site_settings_id)
return request.site_se... | Define function for getting setting value by key | Define function for getting setting value by key
| Python | bsd-3-clause | KenMutemi/saleor,maferelo/saleor,mociepka/saleor,HyperManTT/ECommerceSaleor,maferelo/saleor,jreigel/saleor,KenMutemi/saleor,itbabu/saleor,UITools/saleor,maferelo/saleor,itbabu/saleor,tfroehlich82/saleor,UITools/saleor,jreigel/saleor,car3oon/saleor,tfroehlich82/saleor,tfroehlich82/saleor,jreigel/saleor,mociepka/saleor,U... |
7caa677b300340b62f999ed3733e95fb431da9d4 | views.py | views.py | from django.shortcuts import render, HttpResponse
from django.shortcuts import HttpResponseRedirect
from django.template import Context, Template
from models import UploadFileForm
from models import extGenOptimizer1
OPTIONS = """
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek',
},
defau... | from django.shortcuts import render, HttpResponse
from django.shortcuts import HttpResponseRedirect
from django.template import Context, Template
from django.middleware.csrf import rotate_token
from models import UploadFileForm
from models import extGenOptimizer1
OPTIONS = """
header: {
left: 'prev,next today',
cent... | Add rotation of CSRF token to prevent form resubmission | Add rotation of CSRF token to prevent form resubmission
| Python | mit | cameronlai/EXT_GEN,cameronlai/EXT_GEN |
8a821cb62a35547417fcd56d02486e5cc2d8494f | xzarr.py | xzarr.py | from .base import DataSourceMixin
class ZarrSource(DataSourceMixin):
"""Open a xarray dataset.
Parameters
----------
urlpath: str
Path to source. This can be a local directory or a remote data
service (i.e., with a protocol specifier like ``'s3://``).
storage_options: dict
... | from .base import DataSourceMixin
class ZarrSource(DataSourceMixin):
"""Open a xarray dataset.
Parameters
----------
urlpath: str
Path to source. This can be a local directory or a remote data
service (i.e., with a protocol specifier like ``'s3://``).
storage_options: dict
... | Make work with any filesystem | Make work with any filesystem
| Python | bsd-3-clause | ericdill/databroker,ericdill/databroker |
f04e32cf6731e8900fa85b1814d9a68da1bcaa9d | vimeo/auth/authorization_code.py | vimeo/auth/authorization_code.py | #! /usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
import urllib
from .base import AuthenticationMixinBase
from . import GrantFailed
try:
basestring
except NameError:
basestring = str
class AuthorizationCodeMixin(AuthenticationMixinBase):
"""Implement helpers for the Authori... | #! /usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
from .base import AuthenticationMixinBase
from . import GrantFailed
# We need to get urlencode from urllib.parse in Python 3, but fall back to
# urllib in Python 2
try:
from urllib.parse import urlencode
except ImportError:
from ... | Make urlencode load properly in python 3. | Make urlencode load properly in python 3.
| Python | apache-2.0 | blorenz/vimeo.py,vimeo/vimeo.py,gabrielgisoldo/vimeo.py,greedo/vimeo.py |
483e04671095eedabc8972982dd2109a5329c603 | tests/test_templatetags.py | tests/test_templatetags.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_templatetags
-------------------
Tests for `columns.templatetags` module.
"""
import unittest
from columns.templatetags.columns import rows, columns
class TestColumns(unittest.TestCase):
def test_columns(self):
data = range(7)
result = ro... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_templatetags
-------------------
Tests for `columns.templatetags` module.
"""
import unittest
from columns.templatetags.columns import columns
class TestColumns(unittest.TestCase):
def test_columns(self):
data = range(7)
result = columns(... | Fix tests to match updated defs. | Fix tests to match updated defs.
| Python | bsd-3-clause | audreyr/django-columns,audreyr/django-columns,audreyr/django-columns |
272d4bab431cd2b4e2010f3a7cd5b1c236bdacb4 | Export.py | Export.py | import sqlite3
def main():
conn = sqlite3.connect("database")
cursor = conn.cursor()
# I claim this gives the current score. Another formulation is
# select trackid, score, max(scoreid) from scores group by trackid;
# cursor.execute("""select trackid, score from scores
# group b... | import sqlite3
def main():
conn = sqlite3.connect("database")
cursor = conn.cursor()
# I claim this gives the current score. Another formulation is
# select trackid, score, max(scoreid) from scores group by trackid;
# cursor.execute("""select trackid, score from scores
# group b... | Use new column for score. | Use new column for score.
| Python | bsd-3-clause | erbridge/NQr,erbridge/NQr,erbridge/NQr |
005d74dcb1f1f3e576af71e7cb3fb1e1d6d4df08 | scripts/lib/paths.py | scripts/lib/paths.py | details_source = './source/details/'
xml_source = './source/raw_xml/'
term_dest = './courses/terms/'
course_dest = './source/courses/'
info_path = './courses/info.json'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid ... | details_source = './source/details/'
xml_source = './source/raw_xml/'
term_dest = './courses/terms/'
course_dest = './source/courses/'
info_path = './courses/info.json'
mappings_path = './related-data/generated/'
handmade_path = './related-data/handmade/'
def find_details_subdir(clbid):
str_clbid ... | Remove the allocation of a variable in make_course_path | Remove the allocation of a variable in make_course_path
| Python | mit | StoDevX/course-data-tools,StoDevX/course-data-tools |
e30b9cfd55b91424de62e5ac9fcdb0464a78f37e | testtube/tests/__init__.py | testtube/tests/__init__.py | import sys
if sys.version_info[:2] < (2, 7):
import unittest2 as unittest
else:
import unittest
| import sys
if sys.version_info[:2] < (2, 7):
import unittest2 as unittest # NOQA
else:
import unittest # NOQA
if sys.version_info < (3,):
from mock import Mock, patch # NOQA
else:
from unittest.mock import Mock, patch # NOQA
# Frosted doesn't yet support noqa flags, so this hides the imported/un... | Make import mock.Mock or unittest.mock.Mock easier | Make import mock.Mock or unittest.mock.Mock easier
| Python | mit | thomasw/testtube,beck/testtube,blaix/testtube |
e9edc74a28442c2f519d4a3c40253f7844c9ca2f | thecut/authorship/forms.py | thecut/authorship/forms.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
class AuthorshipFormMixin(object):
"""Set the ``created_by`` and ``updated_by`` fields on a model.
This form requires that a property, ``self.user`` be set to an instance of
:py:class`~django.contrib.auth.models.User` before... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
class AuthorshipFormMixin(object):
"""Set the ``created_by`` and ``updated_by`` fields on a model.
Requires that a ``User`` instance be passed in to the constructor. Views
that inherit from ``AuthorshipViewMixin`` automatica... | Set the `self.user` property on the `AuthorshipFormMixin`. | Set the `self.user` property on the `AuthorshipFormMixin`.
| Python | apache-2.0 | thecut/thecut-authorship |
3df3f72b54068deaca51ce2b4c52c185bf8f4526 | virtool/uploads/models.py | virtool/uploads/models.py | import enum
from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum
from virtool.postgres import Base
class UploadType(enum.Enum):
hmm = "hmm"
reference = "reference"
reads = "reads"
subtraction = "subtraction"
null = None
class Upload(Base):
__tablename__ = "uploads"
... | import enum
from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum
from virtool.postgres import Base
class UploadType(str, enum.Enum):
hmm = "hmm"
reference = "reference"
reads = "reads"
subtraction = "subtraction"
null = None
class Upload(Base):
__tablename__ = "uploads"
... | Declare subclass of `UploadType` to be `str` | Declare subclass of `UploadType` to be `str`
* Fixes issues with JSON serializing
* Revert `__repr__` string format changes as the newlines created large gaps of whitespace | Python | mit | virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool |
cdf674fc65491c72723d068e72f9ba9f85c5b482 | django_summernote/__init__.py | django_summernote/__init__.py | version_info = (0, 8, 11, 6)
__version__ = version = '.'.join(map(str, version_info))
__project__ = PROJECT = 'django-summernote'
__author__ = AUTHOR = "django-summernote contributors"
default_app_config = 'django_summernote.apps.DjangoSummernoteConfig'
| version_info = (0, 8, 11, 6)
__version__ = version = '.'.join(map(str, version_info))
__project__ = PROJECT = 'django-summernote'
__author__ = AUTHOR = "django-summernote contributors"
from django import VERSION as django_version
if django_version < (3, 2):
default_app_config = 'django_summernote.apps.DjangoSumme... | Fix default_app_config problem with Django >= 3.20 | Fix default_app_config problem with Django >= 3.20
| Python | mit | summernote/django-summernote,summernote/django-summernote,summernote/django-summernote |
298a60fa2ad56cb6bfbf4a9821b547e5b197384c | django_replicated/decorators.py | django_replicated/decorators.py | # -*- coding:utf-8 -*-
'''
Decorators for using specific routing state for particular requests.
Used in cases when automatic switching based on request method doesn't
work.
Usage:
from django_replicated.decorators import use_master, use_slave
@use_master
def my_view(request, ...):
# master databa... | # -*- coding:utf-8 -*-
'''
Decorators for using specific routing state for particular requests.
Used in cases when automatic switching based on request method doesn't
work.
Usage:
from django_replicated.decorators import use_master, use_slave
@use_master
def my_view(request, ...):
# master databa... | Use 'wraps' from 'functools', to keep wrapped function's docstring, name and attributes. | Use 'wraps' from 'functools', to keep wrapped function's docstring, name and attributes.
| Python | bsd-3-clause | lavr/django_replicated,dmirain/django_replicated,Zunonia/django_replicated |
af2afbbbd3014f85c69bbfb4dc65f6850e7840b4 | djlint/analyzers/db_backends.py | djlint/analyzers/db_backends.py | import ast
from .base import BaseAnalyzer, Result
class DB_BackendsVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
deprecated_items = {
'django.db.backends.postgresql':
'django.db.backends.postgresql_psycopg2',
}
def visit_Str(self, node):
if node... | import ast
from .base import BaseAnalyzer, Result
class DB_BackendsVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
removed_items = {
'django.db.backends.postgresql':
'django.db.backends.postgresql_psycopg2',
}
def visit_Str(self, node):
if node.s ... | Update database backends analyzer to target 1.5 | Update database backends analyzer to target 1.5
| Python | isc | alfredhq/djlint |
f8a209e7b0cca0fb6cd7bd49fa4f024c472b4e13 | zappa/ext/django_zappa.py | zappa/ext/django_zappa.py | import sys
# add the Lambda root path into the sys.path
sys.path.append('/var/task')
from django.core.handlers.wsgi import WSGIHandler
from django.core.wsgi import get_wsgi_application
import os
def get_django_wsgi(settings_module):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
import dja... | import os
import sys
# add the Lambda root path into the sys.path
sys.path.append('/var/task')
def get_django_wsgi(settings_module):
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
import django
if django.VERSION[0] <= 1 and django.... | Call django.setup() from zappa only for django < 1.7.0 | Call django.setup() from zappa only for django < 1.7.0
* because since django 1.7 it leads to double initialization, which is problematic on some installations
| Python | mit | scoates/Zappa,Miserlou/Zappa,anush0247/Zappa,mathom/Zappa,michi88/Zappa,parroyo/Zappa,anush0247/Zappa,longzhi/Zappa,Miserlou/Zappa,longzhi/Zappa,scoates/Zappa,pjz/Zappa,pjz/Zappa,parroyo/Zappa,mathom/Zappa,michi88/Zappa |
5e671fe98093cf506ce1cb134c335cabd934ad84 | aioredis/locks.py | aioredis/locks.py | from asyncio.locks import Lock as _Lock
from asyncio import coroutine
from asyncio import futures
from .util import create_future
# Fixes an issue with all Python versions that leaves pending waiters
# without being awakened when the first waiter is canceled.
# Code adapted from the PR https://github.com/python/cpyth... | from asyncio.locks import Lock as _Lock
from asyncio import coroutine
from asyncio import futures
from .util import create_future
# Fixes an issue with all Python versions that leaves pending waiters
# without being awakened when the first waiter is canceled.
# Code adapted from the PR https://github.com/python/cpyth... | Fix critical bug with patched Lock | Fix critical bug with patched Lock
| Python | mit | aio-libs/aioredis,aio-libs/aioredis,ymap/aioredis |
2fb1e51d7131f089b6cedbdf227eddb79e3641bf | zerver/webhooks/dropbox/view.py | zerver/webhooks/dropbox/view.py | from django.http import HttpRequest, HttpResponse
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import UserProfile
@api_key_only_webhook_view('Dropbox')... | from django.http import HttpRequest, HttpResponse
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import UserProfile
@api_key_only_webhook_view('Dropbox',... | Fix incorrect placement of notify_bot_owner_on_invalid_json. | dropbox: Fix incorrect placement of notify_bot_owner_on_invalid_json.
This was an error I introduced in editing
b79213d2602291a4c7ccbafe0f775f77db60665b.
| Python | apache-2.0 | punchagan/zulip,brainwane/zulip,andersk/zulip,dhcrzf/zulip,rht/zulip,rishig/zulip,dhcrzf/zulip,andersk/zulip,showell/zulip,punchagan/zulip,rishig/zulip,showell/zulip,kou/zulip,kou/zulip,hackerkid/zulip,brainwane/zulip,synicalsyntax/zulip,hackerkid/zulip,rishig/zulip,jackrzhang/zulip,kou/zulip,andersk/zulip,rht/zulip,ti... |
7b05ce75c0dd16944b26f2c53f1508aa3f771d27 | migrations/versions/0177_add_virus_scan_statuses.py | migrations/versions/0177_add_virus_scan_statuses.py | """
Revision ID: 0177_add_virus_scan_statuses
Revises: 0176_alter_billing_columns
Create Date: 2018-02-21 14:05:04.448977
"""
from alembic import op
revision = '0176_alter_billing_columns'
down_revision = '0175_drop_job_statistics_table'
def upgrade():
op.execute("INSERT INTO notification_status_types (name) ... | """
Revision ID: 0177_add_virus_scan_statuses
Revises: 0176_alter_billing_columns
Create Date: 2018-02-21 14:05:04.448977
"""
from alembic import op
revision = '0177_add_virus_scan_statuses'
down_revision = '0176_alter_billing_columns'
def upgrade():
op.execute("INSERT INTO notification_status_types (name) VA... | Fix revision numbers in migration 0177 | Fix revision numbers in migration 0177
| Python | mit | alphagov/notifications-api,alphagov/notifications-api |
a7acf05dd308b88fe9de5e04018438e7861e5c93 | src/sentry/web/forms/invite_organization_member.py | src/sentry/web/forms/invite_organization_member.py | from __future__ import absolute_import
from django import forms
from django.db import transaction, IntegrityError
from sentry.models import (
AuditLogEntry, AuditLogEntryEvent, OrganizationMember
)
class InviteOrganizationMemberForm(forms.ModelForm):
class Meta:
fields = ('email', 'role')
mo... | from __future__ import absolute_import
from django import forms
from django.db import transaction, IntegrityError
from sentry.models import (
AuditLogEntry, AuditLogEntryEvent, OrganizationMember
)
class InviteOrganizationMemberForm(forms.ModelForm):
# override this to ensure the field is required
email... | Enforce requirement of email field on member invite | Enforce requirement of email field on member invite
| Python | bsd-3-clause | mitsuhiko/sentry,ifduyue/sentry,fotinakis/sentry,mvaled/sentry,zenefits/sentry,jean/sentry,BuildingLink/sentry,fotinakis/sentry,BuildingLink/sentry,jean/sentry,JamesMura/sentry,BuildingLink/sentry,JamesMura/sentry,JackDanger/sentry,gencer/sentry,mvaled/sentry,daevaorn/sentry,BuildingLink/sentry,zenefits/sentry,daevaorn... |
c40cb3410944053c18abf8fb2b23a59f4b336015 | conversion_calls.py | conversion_calls.py | from settings import CONVERSIONS
def get_conversions(index):
"""
Get the list of conversions to be performed.
Defaults to doing all XSL conversions for all the files.
"""
if 0 <= index and index < len(CONVERSIONS):
return [CONVERSIONS[index],]
# Default to all conversions.
return CONVERSIONS
def get_msx... | from settings import CONVERSIONS
def get_conversions(index):
"""
Get the list of conversions to be performed.
Defaults to doing all XSL conversions for all the files.
Parameters
----------
index : int
Index of conversion to be used.
Incorrect index will use default (all conversions).
Returns
-------... | Expand docstring for get conversions. | Expand docstring for get conversions.
Add parameter and return value descriptions.
| Python | mit | AustralianAntarcticDataCentre/metadata_xml_convert,AustralianAntarcticDataCentre/metadata_xml_convert |
0f446d166818ec6b218b59751a1dce80842ce677 | app/auth/views.py | app/auth/views.py | # Copyright (C) 2016 University of Zurich. All rights reserved.
#
# This file is part of MSRegistry Backend.
#
# MSRegistry Backend is free software: you can redistribute it and/or
# modify it under the terms of the version 3 of the GNU Affero General
# Public License as published by the Free Software Foundation, or a... | # Copyright (C) 2016 University of Zurich. All rights reserved.
#
# This file is part of MSRegistry Backend.
#
# MSRegistry Backend is free software: you can redistribute it and/or
# modify it under the terms of the version 3 of the GNU Affero General
# Public License as published by the Free Software Foundation, or a... | Remove code field from API /auth/test response | Remove code field from API /auth/test response
| Python | agpl-3.0 | uzh/msregistry |
df9691aecf19d31eab1f52f7d735ed746877ffac | dache/__init__.py | dache/__init__.py | from six.moves.urllib.parse import urlparse
from dache.backends.base import CacheKeyWarning # noqa
from dache.backends.filebased import FileBasedCache
from dache.backends.locmem import LocMemCache
from dache.backends.redis import RedisCache
from dache.utils.module_loading import import_string
__version__ = '0.0.1'
... | import six
from six.moves.urllib.parse import urlparse
from dache.backends.base import CacheKeyWarning # noqa
from dache.backends.filebased import FileBasedCache
from dache.backends.locmem import LocMemCache
from dache.backends.redis import RedisCache
from dache.utils.module_loading import import_string
__version_... | Fix Python 3 string type checking | Fix Python 3 string type checking
| Python | bsd-3-clause | eliangcs/dache |
0bcdde64aeee1ddc7ae40d6aca8729a4070c604a | fabfile.py | fabfile.py | #!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, webpy_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable, disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
e... | #!/usr/bin/env python
import os
from fabric.api import *
from fab_shared import (test, webpy_deploy as deploy,
setup, development, production, localhost, staging, restart_webserver,
rollback, lint, enable, disable, maintenancemode, rechef)
env.unit = "trinity"
env.path = "/var/tornado/%(unit)s" % env
e... | Add reset method for erasing graph database. | Add reset method for erasing graph database.
| Python | mit | peplin/trinity |
1b36dd94759c41c4af433ce53e131e318d09c14a | tests/storage/dav/test_carddav.py | tests/storage/dav/test_carddav.py |
# -*- coding: utf-8 -*-
'''
vdirsyncer.tests.storage.test_carddav
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2014 Markus Unterwaditzer
:license: MIT, see LICENSE for more details.
'''
from vdirsyncer.storage.dav.carddav import CarddavStorage
from . import DavStorageTests
class TestCardda... |
# -*- coding: utf-8 -*-
'''
vdirsyncer.tests.storage.test_carddav
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2014 Markus Unterwaditzer
:license: MIT, see LICENSE for more details.
'''
from vdirsyncer.storage.dav.carddav import CarddavStorage
from . import DavStorageTests
VCARD_TEMPLATE =... | Move vcard template to real multi-line string | Move vcard template to real multi-line string
| Python | mit | tribut/vdirsyncer,untitaker/vdirsyncer,credativUK/vdirsyncer,mathstuf/vdirsyncer,hobarrera/vdirsyncer,hobarrera/vdirsyncer,untitaker/vdirsyncer,untitaker/vdirsyncer,credativUK/vdirsyncer,tribut/vdirsyncer,mathstuf/vdirsyncer |
8ca4babf48425efafb3c6229f5db0cec9715ab97 | example/tests/test_views.py | example/tests/test_views.py | from django.core.urlresolvers import reverse
from django.test import TestCase
import json
from myshop.models.polymorphic.product import Product
from myshop.models.manufacturer import Manufacturer
class ProductSelectViewTest(TestCase):
def setUp(self):
manufacturer = Manufacturer.objects.create(name="te... | from django.core.urlresolvers import reverse
from django.test import TestCase
import json
from myshop.models.polymorphic.product import Product
from myshop.models.manufacturer import Manufacturer
class ProductSelectViewTest(TestCase):
def setUp(self):
manufacturer = Manufacturer.objects.create(name="te... | Fix test for Python 3 | Fix test for Python 3
| Python | bsd-3-clause | khchine5/django-shop,nimbis/django-shop,nimbis/django-shop,jrief/django-shop,divio/django-shop,khchine5/django-shop,khchine5/django-shop,jrief/django-shop,divio/django-shop,divio/django-shop,khchine5/django-shop,awesto/django-shop,nimbis/django-shop,jrief/django-shop,nimbis/django-shop,awesto/django-shop,awesto/django-... |
e72ab305e2a90433c07300f37f7ae6fa2901b9cc | app/auth/views.py | app/auth/views.py | # -*- coding: utf-8 -*-
from flask import render_template, redirect, request, url_for, flash
from flask.ext.login import login_user, logout_user, login_required, \
current_user
from . import auth
from .forms import LoginForm, RegistrationForm
from .. import db
from ..models import User
@auth.route('/login', met... | # -*- coding: utf-8 -*-
from flask import render_template, redirect, request, url_for, flash
from flask.ext.login import login_user, logout_user, login_required, \
current_user
from . import auth
from .forms import LoginForm, RegistrationForm
from ..models import User
@auth.route('/login', methods=['GET', 'POST... | Use newly added save on new users. | Use newly added save on new users.
| Python | mit | guillaumededrie/flask-todolist,poulp/flask-todolist,guillaumededrie/flask-todolist,rtzll/flask-todolist,0xfoo/flask-todolist,polyfunc/flask-todolist,poulp/flask-todolist,rtzll/flask-todolist,polyfunc/flask-todolist,guillaumededrie/flask-todolist,0xfoo/flask-todolist,poulp/flask-todolist,0xfoo/flask-todolist,polyfunc/fl... |
9bf1f19eefc48dbced4b6ea1cc5258518d14bceb | app/utils/http.py | app/utils/http.py | import aiofiles
import aiohttp
import aiohttp.client_exceptions
from aiopath import AsyncPath
from sanic.log import logger
EXCEPTIONS = (
aiohttp.client_exceptions.ClientConnectionError,
aiohttp.client_exceptions.InvalidURL,
aiohttp.client_exceptions.TooManyRedirects,
AssertionError,
UnicodeError,
... | import asyncio
import aiofiles
import aiohttp
import aiohttp.client_exceptions
from aiopath import AsyncPath
from sanic.log import logger
EXCEPTIONS = (
aiohttp.client_exceptions.ClientConnectionError,
aiohttp.client_exceptions.InvalidURL,
aiohttp.client_exceptions.TooManyRedirects,
AssertionError,
... | Add timeout to downloading custom background images | Add timeout to downloading custom background images
| Python | mit | jacebrowning/memegen,jacebrowning/memegen |
07367ced88bd68666e4460d2734c6c18069573a3 | django_field_cryptography/fields.py | django_field_cryptography/fields.py | from django.conf import settings
from django.db import models
from django.utils.encoding import force_bytes, force_str
from django.utils.six import with_metaclass
from cryptography.fernet import Fernet, InvalidToken
fernet = Fernet(settings.FERNET_KEY)
class EncryptedTextField(with_metaclass(models.SubfieldBase, m... | from django.conf import settings
from django.db import models
from django.utils.encoding import force_bytes, force_str
from django.utils.six import with_metaclass
from cryptography.fernet import Fernet, InvalidToken
fernet = Fernet(settings.FERNET_KEY)
class EncryptedTextField(with_metaclass(models.SubfieldBase, m... | Add doctring for `to_python` [ci-skip]. | Add doctring for `to_python` [ci-skip].
`to_python` is called when assigning and retrieving a value from the
database.
| Python | bsd-2-clause | incuna/django-field-cryptography,tombooth/django-field-cryptography |
0f7af860d8df01d1c614b20d687ff6d0393d6938 | docker/transport/basehttpadapter.py | docker/transport/basehttpadapter.py | import requests.adapters
class BaseHTTPAdapter(requests.adapters.HTTPAdapter):
def close(self):
self.pools.clear()
| import requests.adapters
class BaseHTTPAdapter(requests.adapters.HTTPAdapter):
def close(self):
super(BaseHTTPAdapter, self).close()
if hasattr(self, 'pools'):
self.pools.clear()
| Fix BaseHTTPAdapter for the SSL case | Fix BaseHTTPAdapter for the SSL case
Signed-off-by: Ulysses Souza <a0ff1337c6a0e43e9559f5f67fc3acb852912071@docker.com>
| Python | apache-2.0 | docker/docker-py,funkyfuture/docker-py,docker/docker-py,funkyfuture/docker-py,vdemeester/docker-py,vdemeester/docker-py |
2cb10055b34972644d705bb07f80a0d40ac85002 | vk_channelify/models/channel.py | vk_channelify/models/channel.py | from sqlalchemy import Column, String, Integer
from . import Base
class Channel(Base):
__tablename__ = 'channels'
channel_id = Column(String, primary_key=True, nullable=False)
vk_group_id = Column(String, nullable=False)
last_vk_post_id = Column(Integer, nullable=False, server_default='0')
owner... | from sqlalchemy import Column, String, Integer
from . import Base
class Channel(Base):
__tablename__ = 'channels'
channel_id = Column(String, primary_key=True, nullable=False)
vk_group_id = Column(String, nullable=False)
last_vk_post_id = Column(Integer, nullable=False, server_default='0', default=0... | Fix error 'unorderable types: int() > NoneType()' | Fix error 'unorderable types: int() > NoneType()'
| Python | mit | reo7sp/vk-channelify,reo7sp/vk-channelify |
eabc792a4ed87900ae1cb6a9404c3f85874cd053 | avwx_api/views.py | avwx_api/views.py | """
Michael duPont - michael@mdupont.com
avwx_api.views - Routes and views for the flask application
"""
# pylint: disable=W0702
# library
from flask import jsonify
# module
from avwx_api import app
##-------------------------------------------------------##
# Static Web Pages
@app.route('/')
@app.route('/home')
def... | """
Michael duPont - michael@mdupont.com
avwx_api.views - Routes and views for the flask application
"""
# pylint: disable=W0702
# library
from flask import jsonify
# module
from avwx_api import app
##-------------------------------------------------------##
# Static Web Pages
@app.route('/')
@app.route('/home')
def... | Return 400 status for incomplete API queries | Return 400 status for incomplete API queries
| Python | mit | flyinactor91/AVWX-API,flyinactor91/AVWX-API,flyinactor91/AVWX-API |
16b3c9680f44722cf2544bdab581f9505666aef0 | ds_utils/pandas.py | ds_utils/pandas.py | import numpy as np
def dataframe_size(df):
"""Return a dict with the size of DataFrame components in MB.
:param df: pandas.DataFrame
:return dictionary with index, columns, values and total size
"""
byte_to_megabyte_factor = 1024 ** 2
size = dict(zip(['index', 'columns', 'values'],
... | import numpy as np
import pandas as pd
def dataframe_size(df):
"""Return a dict with the size of DataFrame components in MB.
:param df: pandas.DataFrame
:return dictionary with index, columns, values and total size
"""
byte_to_megabyte_factor = 1024 ** 2
size = dict(zip(['index', 'columns', 'v... | Add function for printing full DataFrame | Add function for printing full DataFrame | Python | mit | hgrif/ds-utils |
b21327ab07451dd83eec0a17ee84a6e9d19f16c9 | folivora/utils/notifications.py | folivora/utils/notifications.py | # -*- coding: utf-8 -*-
"""
folivora.utils.notification
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Framework for user/project notifications.
"""
from django.conf import settings
from django.template import loader
from django.core.mail import send_mail
def route_notifications(*log_entries):
for entry in log_entries:... | # -*- coding: utf-8 -*-
"""
folivora.utils.notification
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Framework for user/project notifications.
"""
from django.conf import settings
from django.template import loader
from django.core.mail import send_mail
def route_notifications(*log_entries):
for entry in log_entries:... | Use project member email if given | Use project member email if given
| Python | isc | rocketDuck/folivora,rocketDuck/folivora,rocketDuck/folivora |
ee00138478726ffb60b0a9d3541bb010b95903d8 | cea/interfaces/dashboard/api/__init__.py | cea/interfaces/dashboard/api/__init__.py | from flask import Blueprint
from flask_restplus import Api
from .tools import api as tools
from .project import api as project
from .inputs import api as inputs
from .dashboard import api as dashboard
from .glossary import api as glossary
blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(blueprint)
... | from flask import Blueprint
from flask_restplus import Api
from .tools import api as tools
from .project import api as project
from .inputs import api as inputs
from .dashboard import api as dashboard
from .glossary import api as glossary
blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(blueprint)
... | Add general error handler for unhandled exceptions in api | Add general error handler for unhandled exceptions in api
| Python | mit | architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst |
e8d5732e94d14a3a72999bd270af1fd3f3a2e09f | fileutil_posix.py | fileutil_posix.py | import sys, os, subprocess
def run(args, workdir=None):
p = subprocess.Popen(args, close_fds=True, cwd=workdir)
return p.wait()
if sys.platform == "darwin":
shell_open_command = "open"
else:
shell_open_command = "xdg-open"
def shell_open(path, workdir=None):
return run([shell_open_command, path],... | import sys, os, subprocess
def run(args, workdir=None):
p = subprocess.Popen(args, close_fds=True, cwd=workdir)
return p.wait()
if sys.platform == "darwin":
shell_open_command = "open"
else:
shell_open_command = "xdg-open"
def shell_open(path, workdir=None):
return run([shell_open_command, path],... | Use XDG_CONFIG_HOME for configuration directory. | Use XDG_CONFIG_HOME for configuration directory.
| Python | mit | shaurz/devo |
e84ca44178e984a356c0d77b6ce76040b74dd520 | bin/upload_version.py | bin/upload_version.py | #!python
import os
import sys
import json
import requests
if __name__ == '__main__':
# create release
version = sys.argv[1]
filename = sys.argv[2]
github_token = os.environ['GITHUB_TOKEN']
auth = (github_token, 'x-oauth-basic')
commit_sha = os.environ['CIRCLE_SHA1']
params = json.dumps({
'tag_name':... | #!python
import os
import sys
import json
import requests
if __name__ == '__main__':
version = sys.argv[1]
filename = sys.argv[2].split('/')[-1]
github_token = os.environ['GITHUB_TOKEN']
auth = (github_token, 'x-oauth-basic')
commit_sha = os.environ['CIRCLE_SHA1']
params = json.dumps({
'tag_name': 'v{... | Use only filename; without path | Use only filename; without path
| Python | bsd-2-clause | chriszs/redash,alexanderlz/redash,rockwotj/redash,akariv/redash,useabode/redash,pubnative/redash,amino-data/redash,ninneko/redash,pubnative/redash,denisov-vlad/redash,easytaxibr/redash,moritz9/redash,denisov-vlad/redash,pubnative/redash,jmvasquez/redashtest,easytaxibr/redash,easytaxibr/redash,crowdworks/redash,stefanse... |
f28716fba7f3b351b37fdfbb6e6cd1225592da57 | example/app/templatetags/sqlformat.py | example/app/templatetags/sqlformat.py | from __future__ import unicode_literals
import sqlparse
from django import template
register = template.Library()
@register.filter
def sqlformat(sql):
return sqlparse.format(str(sql), reindent=True)
| from __future__ import unicode_literals
import sqlparse
from django import template
register = template.Library()
@register.filter
def sqlformat(sql):
'''
Format SQL queries.
'''
return sqlparse.format(str(sql), reindent=True, wrap_after=120)
| Use less vertical space in query formatting | Use less vertical space in query formatting
| Python | bsd-3-clause | zostera/django-modeltrans,zostera/django-modeltrans |
4ed0272e82c3bdef548643f4b9bce8f6bc510a42 | classes.py | classes.py | from collections import namedtuple
class User:
def __init__(self, id_, first_name, last_name='', username=''):
self.id = id_
self.first_name = first_name
self.last_name = last_name
self.username = username
@classmethod
def from_database(cls, user):
return cls(*user... | from collections import namedtuple
class User:
def __init__(self, id_, first_name, last_name='', username='',
language_code=''):
self.id = id_
self.first_name = first_name
self.last_name = last_name
self.username = username
@classmethod
def from_database(cls, u... | Update User class to match Telegram API | Update User class to match Telegram API
| Python | mit | Doktor/soup-dumpling |
49fb141da9bf544b73001c1e49ef19e85e88cefb | example.py | example.py | from ui import *
import traceback
################################################################################
# example usage
status = Text('Tests something | ok: 0 | error: 0 | fail: 0', style='RB')
try:
aoeu
except Exception as e:
err = traceback.format_exc()[:-1]
exception = TextNoWrap(err)
def test(i... | from ui import *
import traceback
################################################################################
# example usage
status = TextNoWrap('Tests something | ok: 0 | error: 0 | fail: 0', style='RB')
try:
aoeu
except Exception as e:
err = traceback.format_exc()[:-1]
exception = TextNoWrap(err)
def ... | Add extra booger-like properties before transferring | Add extra booger-like properties before transferring
| Python | mit | thenoviceoof/booger,thenoviceoof/booger |
6506ece45d123bcf615a636245bc12498b5348de | hsdecomp/ptrutil.py | hsdecomp/ptrutil.py | import struct
from hsdecomp.types import *
def read_half_word(settings, file_offset):
return struct.unpack(settings.rt.halfword.struct, settings.binary[file_offset:file_offset+settings.rt.halfword.size])[0]
def read_word(settings, file_offset):
return struct.unpack(settings.rt.word.struct, settings.binary[fi... | import struct
from hsdecomp.types import *
def read_half_word(settings, file_offset):
return struct.unpack(settings.rt.halfword.struct, settings.binary[file_offset:file_offset+settings.rt.halfword.size])[0]
def read_word(settings, file_offset):
return struct.unpack(settings.rt.word.struct, settings.binary[fi... | Kill obsolete case in pointer_offset | Kill obsolete case in pointer_offset
| Python | mit | gereeter/hsdecomp |
d901af0d908053d11db556c7755dbce32e9d1311 | importlib_resources/tests/test_contents.py | importlib_resources/tests/test_contents.py | import unittest
import importlib_resources as resources
from . import data01
from . import util
class ContentsTests:
@property
def contents(self):
return sorted(
[el for el in list(resources.contents(self.data)) if el != '__pycache__']
)
class ContentsDiskTests(ContentsTests, un... | import unittest
import importlib_resources as resources
from . import data01
from . import util
class ContentsTests:
expected = {
'__init__.py',
'binary.file',
'subdirectory',
'utf-16.file',
'utf-8.file',
}
def test_contents(self):
assert self.expected <= ... | Consolidate some behavior and re-use 'set' comparison for less strict unordered comparisons. | Consolidate some behavior and re-use 'set' comparison for less strict unordered comparisons.
| Python | apache-2.0 | python/importlib_resources |
7c12e3d3fc4e09658b0ad7dc7a1fbb80e6ec80b8 | generate_table.py | generate_table.py | import json
import xml.etree.ElementTree as etree
table = etree.Element("table", attrib={
"class": "tablesorter",
"cellspacing": "1",
"cellpadding": "0",
})
thead = etree.SubElement(table, "thead")
tbody = etree.SubElement(table, "tbody")
tr = etree.SubElement(thead, "tr")
for heading in ["Product", ... | import json
import xml.etree.ElementTree as etree
table = etree.Element("table", attrib={
"id": "apple",
"class": "tablesorter",
"cellspacing": "1",
"cellpadding": "0",
})
thead = etree.SubElement(table, "thead")
tbody = etree.SubElement(table, "tbody")
tr = etree.SubElement(thead, "tr")
for head... | Make sure to add the apple id | Make sure to add the apple id
| Python | mit | kyleconroy/apple-stock |
26bbb0b8cca1d44548c96726d4b4e8296a482d12 | ircstat/defaults.py | ircstat/defaults.py | # Copyright 2013 John Reese
# Licensed under the MIT license
filename_regex = r'(?:[a-z]+_)#(?P<channel>[a-z]+)_(?P<date>\d{8}).log'
channel_regex_group = 1
date_regex_group = 2
date_format = r'%Y%m%d'
| # Copyright 2013 John Reese
# Licensed under the MIT license
# the regex to parse data from irc log filenames.
# must contain two named matching groups:
# channel: the name of the channel
# date: the date of the conversation
filename_regex = r'#?(?P<channel>[a-z]+)_(?P<date>\d{8}).log'
# the format of the date co... | Clean up and document default config values | Clean up and document default config values
| Python | mit | jreese/ircstat,jreese/ircstat |
9116828db256ecb1a1e303e31049e526ab9ae8eb | mailqueue/urls.py | mailqueue/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('mailqueue.views',
url(r'^clear$', 'clear_sent_messages', name='clear_sent_messages'),
url(r'^$', 'run_mail_job', name='run_mail_job'),
)
| from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^clear$', views.clear_sent_messages, name='clear_sent_messages'),
url(r'^$', views.run_mail_job, name='run_mail_job'),
]
| Remove warning "deprecated" in url.py | Remove warning "deprecated" in url.py
version django=1.9.6
RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.
| Python | mit | dstegelman/django-mail-queue,Goury/django-mail-queue,Goury/django-mail-queue,dstegelman/django-mail-queue |
05fc49863d202b2e12f8ac822c40bab4618aeff1 | moocng/peerreview/managers.py | moocng/peerreview/managers.py | # Copyright 2013 Rooter Analysis S.L.
#
# 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 applicable law or agreed to in w... | # Copyright 2013 Rooter Analysis S.L.
#
# 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 applicable law or agreed to in w... | Fix the order of assignments | Fix the order of assignments
| Python | apache-2.0 | OpenMOOC/moocng,GeographicaGS/moocng,GeographicaGS/moocng,GeographicaGS/moocng,OpenMOOC/moocng,GeographicaGS/moocng |
68c768634503d359fac23869e20931f0b39897dc | fulfil_client/contrib/mocking.py | fulfil_client/contrib/mocking.py | # -*- coding: utf-8 -*-
try:
from unittest import mock
except ImportError:
import mock
class MockFulfil(object):
"""
A Mock object that helps mock away the Fulfil API
for testing.
"""
responses = []
models = {}
def __init__(self, target, responses=None):
self.target = targ... | # -*- coding: utf-8 -*-
try:
from unittest import mock
except ImportError:
import mock
class MockFulfil(object):
"""
A Mock object that helps mock away the Fulfil API
for testing.
"""
responses = []
models = {}
context = {}
subdomain = 'mock-test'
def __init__(self, target... | Add subdomain and context to mock | Add subdomain and context to mock
| Python | isc | sharoonthomas/fulfil-python-api,fulfilio/fulfil-python-api |
3a0b5bd923eff1fb143aa73fc54f735e7b330068 | examples/plot_sphere_function.py | examples/plot_sphere_function.py | #!/usr/bin/env python3
# coding: utf-8
"""
================================================
Optimization Benchmark: Plot the Sphere Function
================================================
This example show how to plot the *Sphere function*.
"""
######################################################################... | #!/usr/bin/env python3
# coding: utf-8
"""
================================================
Optimization Benchmark: Plot the Sphere Function
================================================
This example show how to plot the *Sphere function*.
"""
######################################################################... | Switch off the output file generation. | Switch off the output file generation.
| Python | mit | jeremiedecock/pyai,jeremiedecock/pyai |
04fcda42222fff1daad780db53190bcfb721d034 | polling_stations/apps/data_collection/management/commands/import_mid_sussex.py | polling_stations/apps/data_collection/management/commands/import_mid_sussex.py | """
Imports Mid Sussex
"""
import sys
from django.contrib.gis.geos import Point, GEOSGeometry
from data_collection.management.commands import BaseKamlImporter
class Command(BaseKamlImporter):
"""
Imports the Polling Station data from Mid Sussex
"""
council_id = 'E07000228'
districts_name = 'm... | """
Imports Mid Sussex
"""
import sys
from lxml import etree
from django.contrib.gis.geos import Point, GEOSGeometry
from data_collection.management.commands import BaseKamlImporter
class Command(BaseKamlImporter):
"""
Imports the Polling Station data from Mid Sussex
"""
council_id = 'E07000228'
... | Fix Mid Sussex Import script | Fix Mid Sussex Import script
Set polling_district_id
Use mserid as internal_council_id to avoid importing duplicate points
| Python | bsd-3-clause | chris48s/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,andylolz/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations |
d36e624acb349b3fd78bb3fb91ba0bcc696719c2 | imagekit/utils.py | imagekit/utils.py | import tempfile
import types
from django.utils.functional import wraps
from imagekit.lib import Image
def img_to_fobj(img, format, **kwargs):
tmp = tempfile.TemporaryFile()
# Preserve transparency if the image is in Pallette (P) mode.
if img.mode == 'P':
kwargs['transparency'] = len(img.split()... | import tempfile
import types
from django.utils.functional import wraps
from imagekit.lib import Image
def img_to_fobj(img, format, **kwargs):
tmp = tempfile.TemporaryFile()
# Preserve transparency if the image is in Pallette (P) mode.
transparency_formats = ('PNG', 'GIF', )
if img.mode == 'P' and f... | Fix conversion of PNG "palette" or "P" mode images to JPEG. "P" mode images need to be converted to 'RGB' if target image format is not PNG or GIF. | Fix conversion of PNG "palette" or "P" mode images to JPEG.
"P" mode images need to be converted to 'RGB' if target image format is not PNG or GIF. | Python | bsd-3-clause | pcompassion/django-imagekit,tawanda/django-imagekit,tawanda/django-imagekit,FundedByMe/django-imagekit,pcompassion/django-imagekit,pcompassion/django-imagekit,FundedByMe/django-imagekit |
04ca2afaa43cc4de88020235a7e1bf4d4377c5bc | pearbot.py | pearbot.py | #!/usr/bin/env python3
# vim:fileencoding=utf-8:ts=8:et:sw=4:sts=4:tw=79
"""
pearbot.py
The PearBot IRC bot entry point.
It sets up logging and starts up the IRC client.
Copyright (c) 2014 Twisted Pear <pear at twistedpear dot at>
See the file LICENSE for copying permission.
"""
import asyncio
import command
import... | #!/usr/bin/env python3
# vim:fileencoding=utf-8:ts=8:et:sw=4:sts=4:tw=79
"""
pearbot.py
The PearBot IRC bot entry point.
It sets up logging and starts up the IRC client.
Copyright (c) 2014 Twisted Pear <pear at twistedpear dot at>
See the file LICENSE for copying permission.
"""
import asyncio
import command
import... | Change log format (added PID) | Change log format (added PID)
| Python | mit | pyrige/pump19 |
b96ac3debb472dcf3aaac84f43309a4d01a27159 | exam/tests/test_dynamic_import.py | exam/tests/test_dynamic_import.py | # -*- coding: utf-8 -*-
from django.test import TestCase
from should_dsl import should
from exam.dynamic_import import create_specific_exam
from core.tests import FormatTest
from sys import stderr
class TestDynamicImport(FormatTest, TestCase):
def setUp(self):
self.my_type = '[Exam - Dynamic Import]'
... | # -*- coding: utf-8 -*-
from django.test import TestCase
from should_dsl import should
from exam.dynamic_import import create_specific_exam
from core.tests import FormatTest
from sys import stderr
class TestDynamicImport(FormatTest, TestCase):
def setUp(self):
self.my_type = '[Exam - Dynamic Import]'
... | Update variables names in exam tests | Update variables names in exam tests
| Python | mit | msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub |
353fe0141267a8e50992f564bd991eba096a3fca | zforce.py | zforce.py | import zipfile
def bf_extract(zfile, password):
zip = zipfile.ZipFile(zfile)
try:
zip.setpassword(password)
zip.extractall()
except:
pass
finally:
zip.close()
if __name__ == "__main__":
bf_extract("spmv.zip", "ok") | import zipfile
import optparse
class InvalidZip(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def bf_extract(zfile, password):
res = True
if (zipfile.is_zipfile(zfile)):
zip = zipfile.ZipFile(zfile)
try:
... | Decompress a zip given a list file | Decompress a zip given a list file
| Python | apache-2.0 | alexst07/ZipBruteforce |
1f958dc4439fbe435b1d0381d15860708f1f9745 | constance/__init__.py | constance/__init__.py | from .base import Config
__version__ = '1.0a1'
try:
from django.apps import AppConfig # noqa
except ImportError:
config = Config()
else:
default_app_config = 'constance.apps.ConstanceConfig'
| from .base import Config
from django.utils.functional import SimpleLazyObject
__version__ = '1.0a1'
try:
from django.apps import AppConfig # noqa
except ImportError:
config = SimpleLazyObject(Config)
else:
default_app_config = 'constance.apps.ConstanceConfig'
| Make the config object lazy for old Djangos. | Make the config object lazy for old Djangos.
This should prevent import time side effects from instantiating the config object directly there.
| Python | bsd-3-clause | gmflanagan/waterboy,vinnyrose/django-constance,jerzyk/django-constance,metalpriest/django-constance,thorgate/django-constance,jmerdich/django-constance,jazzband/django-constance,jonzlin95/django-constance,winzard/django-constance,metalpriest/django-constance,jazzband/django-constance,django-leonardo/django-constance,po... |
55983918f76066662496a82d321ac482c1668492 | profile_bs_xf03id/startup/50-scans.py | profile_bs_xf03id/startup/50-scans.py | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... | Add xspress3 to step-scan detector list | Add xspress3 to step-scan detector list
| Python | bsd-2-clause | NSLS-II-HXN/ipython_ophyd,NSLS-II-HXN/ipython_ophyd |
1cb79216f992ea0f31abb28031a74f6e703582cb | YouKnowShit/DownloadPic.py | YouKnowShit/DownloadPic.py | import requests
import bs4
import os
import urllib.request
import shutil
import re
base_url = 'http://www.j8vlib.com/cn/vl_searchbyid.php?keyword='
srcDir = 'F:\\utorrent\\WEST'
filterWord = "video_jacket_img"
filenames = os.listdir(srcDir)
for filename in filenames:
preFileName = filename.split(".")[0]
if (p... | import requests
import bs4
import os
import urllib.request
import shutil
import re
base_url = 'http://www.jav11b.com/cn/vl_searchbyid.php?keyword='
srcDir = 'H:\\temp'
filterWord = "video_jacket_img"
filenames = os.listdir(srcDir)
for filename in filenames:
preFileName = filename.split(".")[0]
if (preFileName... | Update the pic download base url. | Update the pic download base url.
| Python | mit | jiangtianyu2009/PiSoftCake |
1ea2ca47070ab58a8df9e308d2bcb4bd4debe088 | tests/test_script.py | tests/test_script.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from scripttest import TestFileEnvironment
def main()... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A script to test CKAN Utils functionality """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from sys import exit, stderr
from os import path as p
from scripttest import TestFil... | Fix and update script test | Fix and update script test | Python | mit | luiscape/ckanutils,reubano/ckanutils,reubano/ckanny,reubano/ckanutils,reubano/ckanny,luiscape/ckanutils |
2a893314a6f20092379298cfb53910c15154243c | tests/test_trivia.py | tests/test_trivia.py |
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_large_num... |
import unittest
from units.trivia import check_answer
class TestCheckAnswer(unittest.TestCase):
def test_correct_answer(self):
self.assertTrue(check_answer("correct", "correct"))
def test_incorrect_answer(self):
self.assertFalse(check_answer("correct", "incorrect"))
def test_correct_e... | Test correct encoding for trivia answer | [Tests] Test correct encoding for trivia answer
Rename test_wrong_encoding to test_incorrect_encoding
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot |
b4f8e0ca25b27047cc3bf556a15cb603688ba905 | respite/serializers/jsonserializer.py | respite/serializers/jsonserializer.py | try:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data)
| try:
import json
except ImportError:
from django.utils import simplejson as json
from base import Serializer
class JSONSerializer(Serializer):
def serialize(self):
data = self.preprocess()
return json.dumps(data, ensure_ascii=False)
| Fix a bug that caused JSON to be serialized as a byte stream with unicode code points | Fix a bug that caused JSON to be serialized as a byte stream with unicode code points
| Python | mit | jgorset/django-respite,jgorset/django-respite,jgorset/django-respite |
2c64a9e0bd1a19cc766035d80b72ec8c4baec99f | project/submission/forms.py | project/submission/forms.py | from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **... | from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import FileSubmission, VideoSubmission
class VideoSubmissionForm(forms.ModelForm):
class Meta:
model = VideoSubmission
fields = ['video_url']
def __init__(self, *args, **... | Decrease accepted file size to 128MB | Decrease accepted file size to 128MB
| Python | mit | compsci-hfh/app,compsci-hfh/app |
81d9558c5d75671349228b8cde84d7049289d3df | troposphere/settings/__init__.py | troposphere/settings/__init__.py | from troposphere.settings.default import *
from troposphere.settings.local import *
| from troposphere.settings.default import *
try:
from troposphere.settings.local import *
except ImportError:
raise Exception("No local settings module found. Refer to README.md")
| Add exception for people who dont read the docs | Add exception for people who dont read the docs
| Python | apache-2.0 | CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend |
011a285ce247286879e4c063e7c5917f1125732f | numba/postpasses.py | numba/postpasses.py | # -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec... | # -*- coding: utf-8 -*-
"""
Postpasses over the LLVM IR.
The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc
"""
from __future__ import print_function, division, absolute_import
from numba.support.math_support import math_support
default_postpasses = {}
def register_default(name):
def dec... | Resolve math functions from LLVM math library | Resolve math functions from LLVM math library
| Python | bsd-2-clause | pombredanne/numba,stonebig/numba,pitrou/numba,gmarkall/numba,cpcloud/numba,ssarangi/numba,stonebig/numba,sklam/numba,ssarangi/numba,pombredanne/numba,stefanseefeld/numba,IntelLabs/numba,numba/numba,cpcloud/numba,stefanseefeld/numba,stonebig/numba,seibert/numba,pombredanne/numba,gdementen/numba,seibert/numba,cpcloud/num... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.