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 |
|---|---|---|---|---|---|---|---|---|---|
865b9d8307f35203d7242e9c431ec2f6cb65c42e | whyis/manager.py | whyis/manager.py | # -*- coding:utf-8 -*-
import flask_script as script
from whyis import commands
from whyis.app_factory import app_factory
from whyis.config_utils import import_config_module
class Manager(script.Manager):
def __init__(self):
script.Manager.__init__(self, app_factory)
config = import_config_mo... | # -*- coding:utf-8 -*-
import flask_script as script
from whyis import commands
from whyis.app_factory import app_factory
from whyis.config_utils import import_config_module
class Manager(script.Manager):
def __init__(self):
script.Manager.__init__(self, app_factory)
config = import_config_mo... | Revert "Made commands consistent on use of underscores. Re-enabled 'interpret' command that had been misplaced." | Revert "Made commands consistent on use of underscores. Re-enabled 'interpret' command that had been misplaced."
This reverts commit 7827598d1060442570685e94633093c550ce7ff2.
| Python | apache-2.0 | tetherless-world/graphene,tetherless-world/graphene,tetherless-world/satoru,tetherless-world/satoru,tetherless-world/satoru,tetherless-world/graphene,tetherless-world/satoru,tetherless-world/graphene |
3f635db216c292c0eec720d28ecfbec3e23f1ca5 | ynr/s3_storage.py | ynr/s3_storage.py | from storages.backends.s3boto3 import S3Boto3Storage
from django.contrib.staticfiles.storage import ManifestFilesMixin
from pipeline.storage import PipelineMixin
from django.conf import settings
class StaticStorage(PipelineMixin, ManifestFilesMixin, S3Boto3Storage):
"""
Store static files on S3 at STATICFILE... | import os
from storages.backends.s3boto3 import S3Boto3Storage, SpooledTemporaryFile
from django.contrib.staticfiles.storage import ManifestFilesMixin
from pipeline.storage import PipelineMixin
from django.conf import settings
class PatchedS3Boto3Storage(S3Boto3Storage):
def _save_content(self, obj, content, pa... | Patch S3Boto3Storage to prevent closed file error when collectin static | Patch S3Boto3Storage to prevent closed file error when collectin static
This is copied from the aggregator API and prevents a bug where the
storage closes the files too early, raising a boto exception.
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
7b939076fba1bb11d0ded504bcf10da457b3d092 | scripts/add_identifiers_to_existing_preprints.py | scripts/add_identifiers_to_existing_preprints.py | import logging
import time
from website.app import init_app
from website.identifiers.utils import get_top_level_domain, request_identifiers_from_ezid
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def add_identifiers_to_preprints():
from osf.models import PreprintService
prepr... | import logging
import time
from website.app import init_app
from website.identifiers.utils import request_identifiers_from_ezid
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def add_identifiers_to_preprints():
from osf.models import PreprintService
preprints_without_identifie... | Remove check for domain in DOI | Remove check for domain in DOI
| Python | apache-2.0 | mattclark/osf.io,crcresearch/osf.io,aaxelb/osf.io,saradbowman/osf.io,adlius/osf.io,mattclark/osf.io,laurenrevere/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,sloria/osf.io,mfraezz/osf.io,chrisseto/osf.io,pattisdr/osf.io,sloria/osf.io,adlius/osf.io,felliott/osf.i... |
ade3a316166d3c4c362becd7880e60bd9387b259 | courriers/management/commands/mailjet_sync_unsubscribed.py | courriers/management/commands/mailjet_sync_unsubscribed.py | from django.core.management.base import BaseCommand
from django.db import DEFAULT_DB_ALIAS
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--connection',
action='store',
dest='connection',
... | from django.core.management.base import BaseCommand
from django.db import DEFAULT_DB_ALIAS
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--connection',
action='store',
dest='connection',
... | Select only unsubscribed contacts from mailjet on sync script | Select only unsubscribed contacts from mailjet on sync script
| Python | mit | ulule/django-courriers,ulule/django-courriers |
be40174929193085ccd38683e64944fb4aabb26b | serial_reader.py | serial_reader.py | #!/usr/bin/env python
from argparse import ArgumentParser
import sys
import serial
def run(device, baud):
with serial.Serial(device, baud, timeout=0.1) as ser:
while True:
line = ser.readline()
if line:
sys.stdout.write(line)
if __name__ == '__main__':
parser =... | #!/usr/bin/env python
from argparse import ArgumentParser
import sys
import serial
from datetime import datetime
def run(device, baud, prefix=None):
with serial.Serial(device, baud, timeout=0.1) as ser:
while True:
line = ser.readline()
if not line:
continue
... | Add option to timestamp each line from serial | Add option to timestamp each line from serial
| Python | unlicense | recursify/serial-debug-tool |
f035ea7fb453d09b37f5187c4f61e855b048cbd5 | aslo/web/__init__.py | aslo/web/__init__.py | from flask import Blueprint, g
web = Blueprint('web', __name__, template_folder='templates',
static_folder='static',
static_url_path='/web/static',
url_prefix='/<lang_code>')
@web.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lang_code', ... | from flask import Blueprint, g, session
web = Blueprint('web', __name__, template_folder='templates',
static_folder='static',
static_url_path='/web/static',
url_prefix='/<lang_code>')
@web.url_defaults
def add_language_code(endpoint, values):
values.setdefault('lan... | Use sessions to Tie it a with language. Also helps us to retrieve session code later " " | Use sessions to Tie it a with language. Also helps us to retrieve session code later "
"
| Python | mit | jatindhankhar/aslo-v3,jatindhankhar/aslo-v3,jatindhankhar/aslo-v3,jatindhankhar/aslo-v3 |
5d332259e16758bc43201073db91409390be9134 | UM/Operations/GroupedOperation.py | UM/Operations/GroupedOperation.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
## An operation that groups several other operations together.
#
# The intent of this operation is to hide an underlying chain of operations
# from the user if they correspond to only one in... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
## An operation that groups several other operations together.
#
# The intent of this operation is to hide an underlying chain of operations
# from the user if they correspond to only one in... | Remove removeOperation from grouped operation | Remove removeOperation from grouped operation
This function is never used and actually should never be used. The operation may not be modified after it is used, so removing an operation from the list makes no sense.
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
ef75ec5d27fcbcee1b451b5e22828a1129cfd209 | opps/boxes/models.py | opps/boxes/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
try:
OPPS_APPS = tuple([(u"{0}.{1}".format(
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
try:
OPPS_APPS = tuple([(u"{0}.{1}".format(
... | Add default (7) on limit field queryset model boxes | Add default (7) on limit field queryset model boxes
| Python | mit | YACOWS/opps,jeanmask/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,opps/opps,jeanmask/opps,jeanmask/opps,opps/opps |
38d7092f07884cb2530f95a5dc24ba177bfbe699 | ncclient/operations/third_party/nexus/rpc.py | ncclient/operations/third_party/nexus/rpc.py | from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
def request(self, cmd):
parent_node = etree.Element(qualify('exec-command', NXOS_1_0))
child_node = etree.SubElement(parent_node, qualify('cmd', NXOS_1_0))
child_node.text = c... | from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class ExecCommand(RPC):
def request(self, cmds):
node = etree.Element(qualify('exec-command', NXOS_1_0))
for cmd in cmds:
etree.SubElement(node, qualify('cmd', NXOS_1_0)).text = cmd
ret... | Allow specifying multiple cmd elements | Allow specifying multiple cmd elements
| Python | apache-2.0 | nwautomator/ncclient,joysboy/ncclient,aitorhh/ncclient,ncclient/ncclient,vnitinv/ncclient,cmoberg/ncclient,earies/ncclient,einarnn/ncclient,leopoul/ncclient,kroustou/ncclient,lightlu/ncclient,nnakamot/ncclient,OpenClovis/ncclient,GIC-de/ncclient |
0a152c792e2ebf20056780b5a20765175d73108b | ipv6map/geodata/admin.py | ipv6map/geodata/admin.py | from django.contrib import admin
from . import models
class BaseReadOnlyAdmin(admin.ModelAdmin):
list_display_links = None
def has_change_permission(self, request, obj=None):
return False if obj else True
@admin.register(models.Version)
class VersionAdmin(BaseReadOnlyAdmin):
list_display = ['p... | from django.contrib import admin
from . import models
@admin.register(models.Version)
class VersionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {
'fields': ['publish_date', 'location_count'],
}),
("Status", {
'fields': ['is_active'],
}),
]
list_dis... | Allow toggling active/inactive in VersionAdmin | Allow toggling active/inactive in VersionAdmin
| Python | unlicense | rlmuraya/ipv6map,rlmuraya/ipv6map,rlmuraya/ipv6map,rlmuraya/ipv6map |
7bea8f5cb6f958225ce61a9f7ce439e9a80036ea | tests/unit/utils/cache_test.py | tests/unit/utils/cache_test.py | # -*- coding: utf-8 -*-
'''
tests.unit.utils.cache_test
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test the salt cache objects
'''
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
from salt.utils import cache
im... | # -*- coding: utf-8 -*-
'''
tests.unit.utils.cache_test
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test the salt cache objects
'''
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
from salt.utils import cache
im... | Change python asserts to unittest asserts | Change python asserts to unittest asserts
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
091a08a8fe30c3cc00c6b85552e47a1b15b807b8 | preferences/views.py | preferences/views.py | from django.shortcuts import render
# Create your views here.
from registration.views import RegistrationView
from registration.forms import RegistrationFormUniqueEmail
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail | from django.shortcuts import render
from django.views.generic.edit import FormView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.forms import PreferencesForm
class EmailRegistrationView(RegistrationView):
form_class ... | Add userprefs and email reg view | Add userprefs and email reg view
| Python | mit | jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot |
5b877d2c42a44fb4ebd1c72f89a595ac5c095e07 | wsgi/bufsm/mainapp/urls.py | wsgi/bufsm/mainapp/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^linha/(?P<idLinha>[0-9]+)$', views.getLinha),
url(r'^linha/(?P<idLinha>[0-9]+)/(?P<token>.+)/(?P<lat>.+)/(?P<lng>.+)$', views.writeLinha),
url(r'^test$', views.testLinha),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^linha/(?P<idLinha>[0-9]+)$', views.testLinha),
url(r'^linha/(?P<idLinha>[0-9]+)/(?P<token>.+)/(?P<lat>.+)/(?P<lng>.+)$', views.writeLinha),
]
| Test in the original URL | Test in the original URL
| Python | mit | bufsm/bufsm,bufsm/bufsm,bufsm/bufsm,bufsm/bufsm,bufsm/bufsm |
fc7ad7d55622aa9edb77b9f7822260110a772805 | db.py | db.py | from flask.ext.script import Manager, Server
from flask_migrate import Migrate, MigrateCommand
from app import create_app, db
from credstash import getAllSecrets
import os
secrets = getAllSecrets(region="eu-west-1")
for key, val in secrets.items():
os.environ[key] = val
application = create_app()
manager = Manag... | from flask.ext.script import Manager, Server
from flask_migrate import Migrate, MigrateCommand
from app import create_app, db
from credstash import getAllSecrets
import os
default_env_file = '/home/ubuntu/environment'
environment = 'live'
if os.path.isfile(default_env_file):
with open(default_env_file, 'r') as en... | Bring DB script into line with other prod scripts | Bring DB script into line with other prod scripts
| Python | mit | alphagov/notifications-api,alphagov/notifications-api |
f0dc039976831ece319cb3c4992af54ac3c4c62d | virtool/pathoscope/subtract.py | virtool/pathoscope/subtract.py | from virtool.pathoscope import sam
def run(isolate_sam, host_sam):
# Get a mapping score for every read mapped to the host genome
host_scores = sam.all_scores(host_sam)
# This list will contain the read_ids for all reads that had better mapping qualities against the host
# genome
skipped = list()... | from virtool.pathoscope import sam
def run(isolate_sam, host_sam, snap=False):
# Get a mapping score for every read mapped to the host genome
host_scores = sam.all_scores(host_sam, snap=snap)
# This list will contain the read_ids for all reads that had better mapping qualities against the host
# geno... | Add parameters for dealing with SNAP output to Pathoscope sam module | Add parameters for dealing with SNAP output to Pathoscope sam module
| Python | mit | igboyes/virtool,virtool/virtool,virtool/virtool,igboyes/virtool |
2f67880e777c9efa5192f5c34ce5fc7d71fc0f08 | partner_communication_switzerland/wizards/end_contract_wizard.py | partner_communication_switzerland/wizards/end_contract_wizard.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2017 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) 2017 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... | FIX end contract depart letter generation | FIX end contract depart letter generation
| Python | agpl-3.0 | eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland |
cb2f768f01cc3d40fe95574d0702470d480888c2 | DTError.py | DTError.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This software is under a BSD license. See LICENSE.txt for details.
__all__ = ["DTErrorMessage", "DTSaveError"]
import sys
_errors = []
def DTErrorMessage(fcn, msg):
"""Accumulate a message and echo to standard error.
Arguments:
fcn -- typically a fu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This software is under a BSD license. See LICENSE.txt for details.
__all__ = ["DTErrorMessage", "DTSaveError"]
import sys
import os
_errors = []
def DTErrorMessage(fcn, msg):
"""Accumulate a message and echo to standard error.
Arguments:
fcn -- typi... | Allow passing None for function, and use the executable name in that case. Save error list anonymously | Allow passing None for function, and use the executable
name in that case.
Save error list anonymously
| Python | bsd-3-clause | amaxwell/datatank_py |
9e2728e7589deebce39ed6bca385f36c6c90f718 | tca/chat/models.py | tca/chat/models.py | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Member(models.Model):
lrz_id = models.CharField(max_length=7, unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_na... | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Member(models.Model):
lrz_id = models.CharField(max_length=7, unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_na... | Add a timestamp field to the Message model | Add a timestamp field to the Message model
The timestamp is automatically assigned at the moment of creation
of the message. It is represented as a Month-based ISO8601
date-time format when sending the Message resource representation
in JSON.
Closes #1
| Python | bsd-3-clause | mlalic/TumCampusAppBackend,mlalic/TumCampusAppBackend |
5caa758b5638e0244da6818aa27092ad41801cc1 | kazoo/tests/test_interrupt.py | kazoo/tests/test_interrupt.py | import os
from nose import SkipTest
from sys import platform
from kazoo.testing import KazooTestCase
class KazooInterruptTests(KazooTestCase):
def test_interrupted_systemcall(self):
'''
Make sure interrupted system calls don't break the world, since we can't
control what all signals our c... | import os
from nose import SkipTest
from sys import platform
from kazoo.testing import KazooTestCase
class KazooInterruptTests(KazooTestCase):
def test_interrupted_systemcall(self):
'''
Make sure interrupted system calls don't break the world, since we can't
control what all signals our c... | Add a sanity check per @bbangert | Add a sanity check per @bbangert
| Python | apache-2.0 | AlexanderplUs/kazoo,bsanders/kazoo,tempbottle/kazoo,rockerbox/kazoo,python-zk/kazoo,AlexanderplUs/kazoo,pombredanne/kazoo,Asana/kazoo,kormat/kazoo,harlowja/kazoo,rockerbox/kazoo,rgs1/kazoo,jacksontj/kazoo,max0d41/kazoo,bsanders/kazoo,rgs1/kazoo,tempbottle/kazoo,pombredanne/kazoo,harlowja/kazoo,max0d41/kazoo,kormat/kazo... |
62c59e1efdd0a5c04bb3854dfb3f98ed5c237c21 | skyfield/tests/test_almanac.py | skyfield/tests/test_almanac.py | from skyfield import api, almanac
# http://aa.usno.navy.mil/cgi-bin/aa_moonill2.pl?form=1&year=2018&task=00&tz=-05
def test_fraction_illuminated():
ts = api.load.timescale()
t0 = ts.utc(2018, 9, range(9, 19), 5)
e = api.load('de421.bsp')
p = almanac.fraction_illuminated(e, 'moon', t0).round(2)
asse... | from skyfield import api, almanac
# http://aa.usno.navy.mil/cgi-bin/aa_moonill2.pl?form=1&year=2018&task=00&tz=-05
def test_fraction_illuminated():
ts = api.load.timescale()
t0 = ts.utc(2018, 9, range(9, 19), 5)
e = api.load('de421.bsp')
f = almanac.fraction_illuminated(e, 'moon', t0[-1]).round(2)
... | Add test for single-value fraction_illuminated() | Add test for single-value fraction_illuminated()
| Python | mit | skyfielders/python-skyfield,skyfielders/python-skyfield |
2cf9060db40e746eb49665b3eac83c72fd81d461 | apigpio/utils.py | apigpio/utils.py | import functools
def Debounce(threshold=100):
"""
Simple debouncing decorator for apigpio callbacks.
Example:
`@Debouncer()
def my_cb(gpio, level, tick)
print('gpio cb: {} {} {}'.format(gpio, level, tick))
`
The threshold can be given to the decorator as an argument (in millis... | import functools
def Debounce(threshold=100):
"""
Simple debouncing decorator for apigpio callbacks.
Example:
`@Debouncer()
def my_cb(gpio, level, tick)
print('gpio cb: {} {} {}'.format(gpio, level, tick))
`
The threshold can be given to the decorator as an argument (in millis... | Fix callback erroneously filtered out | Fix callback erroneously filtered out
The tick from pigpio wraps aroud after xFFFFFFFF,
approximately 1h13. When it wraps the delay was not computed
correctly, causing all following calls to be filtered out.
| Python | mit | PierreRust/apigpio |
8a09e49cbcb9a874619b0e06601c2d69d5dad738 | keystoneclient/__init__.py | keystoneclient/__init__.py | # Copyright 2012 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | # Copyright 2012 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | Fix --version to output version | Fix --version to output version
Change-Id: I7d8dc83ac7c2ad7519633d136c1c32ce8537dce8
Fixes: bug 1182675
| Python | apache-2.0 | alexpilotti/python-keystoneclient,alexpilotti/python-keystoneclient,jamielennox/python-keystoneclient,ntt-sic/python-keystoneclient,klmitch/python-keystoneclient,metacloud/python-keystoneclient,sdpp/python-keystoneclient,ging/python-keystoneclient,sdpp/python-keystoneclient,ging/python-keystoneclient,darren-wang/ksc,Me... |
0d2cb6f2091c01c9e57fd9b3c9d723b3e3d7080c | nova/objects/__init__.py | nova/objects/__init__.py | # Copyright 2013 IBM Corp.
#
# 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 agree... | # Copyright 2013 IBM Corp.
#
# 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 agree... | Add security_group_rule to objects registry | Add security_group_rule to objects registry
This adds the security_group_rule module to the objects registry,
which allows a service to make sure that all of its objects are
registered before any could be received over RPC.
We don't really have a test for any of these because of the nature
of how they're imported. Re... | Python | apache-2.0 | Metaswitch/calico-nova,barnsnake351/nova,MountainWei/nova,cloudbase/nova-virtualbox,hanlind/nova,maelnor/nova,jianghuaw/nova,zhimin711/nova,blueboxgroup/nova,TwinkleChawla/nova,dawnpower/nova,bgxavier/nova,thomasem/nova,j-carpentier/nova,tianweizhang/nova,openstack/nova,bigswitch/nova,openstack/nova,yosshy/nova,berrang... |
35f9c78274876c6eb1e487071c7957c9b8460f68 | pecan/compat/__init__.py | pecan/compat/__init__.py | import inspect
import six
if six.PY3:
import urllib.parse as urlparse
from urllib.parse import quote, unquote_plus
from urllib.request import urlopen, URLError
from html import escape
izip = zip
else:
import urlparse # noqa
from urllib import quote, unquote_plus # noqa
from urllib2 i... | import inspect
import six
if six.PY3:
import urllib.parse as urlparse
from urllib.parse import quote, unquote_plus
from urllib.request import urlopen, URLError
from html import escape
izip = zip
else:
import urlparse # noqa
from urllib import quote, unquote_plus # noqa
from urllib2 i... | Simplify our argspec compatability shim. | Simplify our argspec compatability shim.
| Python | bsd-3-clause | pecan/pecan,ryanpetrello/pecan,pecan/pecan,ryanpetrello/pecan |
6432d92533953c2873b315945254e5260a109106 | cs251tk/student/markdownify/check_submit_date.py | cs251tk/student/markdownify/check_submit_date.py | import os
from dateutil.parser import parse
from ...common import run, chdir
def check_dates(spec_id, username, spec, basedir):
""" Port of the CheckDates program from C++
Finds the first submission date for an assignment
by comparing first commits for all files in the spec
and re... | import os
from dateutil.parser import parse
from ...common import run, chdir
def check_dates(spec_id, username, spec, basedir):
""" Port of the CheckDates program from C++
Finds the first submission date for an assignment
by comparing first commits for all files in the spec
and re... | Modify way to find earliest date | Modify way to find earliest date
| Python | mit | StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit |
f58940027a0e152ba68917a4b85dd1dfed1095a9 | appname/server.py | appname/server.py | from flask import render_template
from appname import app, db
from models import Foo
from flask.ext.assets import Environment, Bundle
# Static assets
assets = Environment(app)
css_main = Bundle(
'stylesheets/main.scss',
filters='scss',
output='build/main.css',
depends="**/*.scss"
)
assets.register('cs... | from flask import render_template
from appname import app, db
from models import Foo
from flask.ext.assets import Environment, Bundle
# Static assets
assets = Environment(app)
css_main = Bundle(
'stylesheets/main.scss',
filters='scss',
output='build/main.css',
depends="**/*.scss"
)
assets.register('cs... | Add data: and unsafe-local for base64 fonts and inline js | Add data: and unsafe-local for base64 fonts and inline js
| Python | mit | LandRegistry-Attic/flask-examples,LandRegistry-Attic/flask-examples,LandRegistry-Attic/flask-examples,LandRegistry-Attic/flask-examples |
32f06a7d3fc14600792a07bf00fab60af4ac395a | src/dashboard/src/contrib/utils.py | src/dashboard/src/contrib/utils.py | def get_directory_name(job):
"""
Expected format:
%sharedPath%watchedDirectories/workFlowDecisions/createDip/ImagesSIP-69826e50-87a2-4370-b7bd-406fc8aad94f/
"""
import re
directory = job.directory
uuid = job.sipuuid
try:
return re.search(r'^.*/(?P<directory>.*)-[\w]{8}(-[\w... | from django.shortcuts import render_to_response
from django.template.context import RequestContext
def render(request, template, context={}):
return render_to_response(template, context, context_instance=RequestContext(request))
def get_directory_name(job):
"""
Expected format:
%sharedPath%watched... | Add wrapper for render_to_resposne to include tmpl context processors easily | Add wrapper for render_to_resposne to include tmpl context processors easily
Autoconverted from SVN (revision:2231)
| Python | agpl-3.0 | artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history |
d15c830111987388bec89c2549a16b809d656a83 | jarn/mkrelease/scp.py | jarn/mkrelease/scp.py | from process import Process
from exit import err_exit
class SCP(object):
"""Secure copy abstraction."""
def __init__(self, process=None):
self.process = process or Process()
def has_host(self, location):
colon = location.find(':')
slash = location.find('/')
return colon >... | from tempfile import NamedTemporaryFile
from process import Process
from exit import err_exit
class SCP(object):
"""Secure copy and FTP abstraction."""
def __init__(self, process=None):
self.process = process or Process()
def run_scp(self, distfile, location):
if not self.process.quiet:... | Add run_sftp and remove URL manipulation methods from SCP. | Add run_sftp and remove URL manipulation methods from SCP.
| Python | bsd-2-clause | Jarn/jarn.mkrelease |
c2d7f4c6ae9042d1cc7f11fa82d7133e9b506ad7 | src/main/scripts/data_exports/export_json.py | src/main/scripts/data_exports/export_json.py | from lib.harvester import Harvester
from lib.cli_helper import is_writable_directory
import argparse
import logging
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.basicConfig(format="%(asctime... | from lib.harvester import Harvester
from lib.cli_helper import is_writable_directory
import argparse
import logging
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.basicConfig(format="%(asctime... | Fix UTF-8 encoding for json exports | Fix UTF-8 encoding for json exports
| Python | apache-2.0 | dainst/gazetteer,dainst/gazetteer,dainst/gazetteer,dainst/gazetteer,dainst/gazetteer,dainst/gazetteer |
2f3139b2dfa2662daa7e57b221836ff2923c5fc9 | actstream/admin.py | actstream/admin.py | from django.contrib import admin
from actstream import models
# Use django-generic-admin widgets if available
try:
from genericadmin.admin import GenericAdminModelAdmin as ModelAdmin
except ImportError:
ModelAdmin = admin.ModelAdmin
class ActionAdmin(ModelAdmin):
date_hierarchy = 'timestamp'
list_dis... | from django.contrib import admin
from actstream import models
# Use django-generic-admin widgets if available
try:
from genericadmin.admin import GenericAdminModelAdmin as ModelAdmin
except ImportError:
ModelAdmin = admin.ModelAdmin
class ActionAdmin(ModelAdmin):
date_hierarchy = 'timestamp'
list_dis... | Add 'public' field to ActionAdmin list display | Add 'public' field to ActionAdmin list display | Python | mit | druss16/danslist,Shanto/django-activity-stream,jimlyndon/django-activity-stream,intelivix/django-activity-stream,pombredanne/django-activity-stream,github-account-because-they-want-it/django-activity-stream,thelabnyc/django-activity-stream,github-account-because-they-want-it/django-activity-stream,pknowles/django-activ... |
7741968b9d48afc7ac135742774ae911e2611c83 | tests/test_util.py | tests/test_util.py | from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
class TestGrouper(objec... | from grazer.util import time_convert, grouper
class TestTimeConvert(object):
def test_seconds(self):
assert time_convert("10s") == 10
def test_minutes(self):
assert time_convert("2m") == 120
def test_hours(self):
assert time_convert("3h") == 3 * 60 * 60
class TestGrouper(objec... | Cover case when seq is oneven | Cover case when seq is oneven
| Python | mit | CodersOfTheNight/verata |
aa6df5b1ca4801cdaa85f7546c292be4f34e0107 | test/pyrostest/test_system.py | test/pyrostest/test_system.py | import pytest
import pyrostest
class TestSpinUp(pyrostest.RosTest):
def noop(self):
pass
@pyrostest.launch_node('pyrostest', 'add_one.py')
def launches_node(self):
pass
class FailureCases(pyrostest.RosTest):
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('this_isnt_a_proj... | import pytest
import pyrostest
class TestSpinUp(pyrostest.RosTest):
def test_noop(self):
pass
@pyrostest.launch_node('pyrostest', 'add_one.py')
def test_launches_node(self):
pass
class TestFailureCases(pyrostest.RosTest):
@pytest.mark.xfail(strict=True)
@pyrostest.launch_node('th... | Rename tests so that they run. | Rename tests so that they run.
| Python | mit | gtagency/pyrostest,gtagency/pyrostest |
ac7477803739d303df8374f916748173da32cb07 | test_elasticsearch/test_server/__init__.py | test_elasticsearch/test_server/__init__.py | from elasticsearch.helpers.test import get_test_client, ElasticsearchTestCase as BaseTestCase
client = None
def get_client():
global client
if client is not None:
return client
# try and locate manual override in the local environment
try:
from test_elasticsearch.local import get_clie... | from elasticsearch.helpers.test import get_test_client, ElasticsearchTestCase as BaseTestCase
client = None
def get_client(**kwargs):
global client
if client is not None and not kwargs:
return client
# try and locate manual override in the local environment
try:
from test_elasticsearc... | Allow test client to be created with kwargs | Allow test client to be created with kwargs
| Python | apache-2.0 | brunobell/elasticsearch-py,elastic/elasticsearch-py,brunobell/elasticsearch-py,elastic/elasticsearch-py |
6d5edb8a5eacfb2dc83a2eef5732562024995942 | api/serializers.py | api/serializers.py | from django.utils.translation import ugettext as _
from rest_framework.serializers import ModelSerializer, ValidationError
from reg.models import Team
class TeamSerializer(ModelSerializer):
def validate(self, data):
if 'is_school' in data and data['is_school']:
error_dict = {}
i... | from django.utils.translation import ugettext as _
from rest_framework.serializers import ModelSerializer, ValidationError
from reg.models import Team
class TeamSerializer(ModelSerializer):
def validate(self, data):
error_dict = {}
if 'is_school' in data and data['is_school']:
if 's... | Fix bug with registering non-school teams | Fix bug with registering non-school teams
| Python | bsd-3-clause | stefantsov/blackbox3,stefantsov/blackbox3,stefantsov/blackbox3 |
b3d0f710de7982877fb2c30c46c75de86262caf4 | grako/rendering.py | grako/rendering.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... | Allow render to take a template different from the default one. | Allow render to take a template different from the default one.
| Python | bsd-2-clause | swayf/grako,swayf/grako |
1690959502e2951920e52a0832e6571144bab6a8 | _lib/wordpress_faq_processor.py | _lib/wordpress_faq_processor.py | import sys
import json
import os.path
import requests
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
url = os.path.expandvars(url)
resp = requests.get(url, params={'page': current_page, 'count': '-1'})
results = json.loads(resp.conte... | import sys
import json
import os.path
import requests
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
url = os.path.expandvars(url)
resp = requests.get(url, params={'page': current_page, 'count': '-1'})
results = json.loads(resp.conte... | Change faq processor to bulk index | Change faq processor to bulk index
| Python | cc0-1.0 | kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh |
c4e497f24818169e8c59c07246582223c8214e45 | bitfield/forms.py | bitfield/forms.py | from django.forms import CheckboxSelectMultiple, IntegerField, ValidationError
from django.utils.encoding import force_unicode
from .types import BitHandler
class BitFieldCheckboxSelectMultiple(CheckboxSelectMultiple):
def render(self, name, value, attrs=None, choices=()):
if isinstance(value, BitHandler... | from django.forms import CheckboxSelectMultiple, IntegerField, ValidationError
from django.utils.encoding import force_unicode
from .types import BitHandler
class BitFieldCheckboxSelectMultiple(CheckboxSelectMultiple):
def render(self, name, value, attrs=None, choices=()):
if isinstance(value, BitHandler... | Allow values of BitFormField's to be integers (for legacy compatibility in some apps) | Allow values of BitFormField's to be integers (for legacy compatibility in some apps)
| Python | apache-2.0 | moggers87/django-bitfield,joshowen/django-bitfield,Elec/django-bitfield,budlight/django-bitfield,disqus/django-bitfield |
19da6c14a5063d3d0361b9b887fd0e4ed8d7a83d | nflpool/data/seasoninfo.py | nflpool/data/seasoninfo.py | from nflpool.data.modelbase import SqlAlchemyBase
import sqlalchemy
class SeasonInfo(SqlAlchemyBase):
__tablename__ = 'SeasonInfo'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True)
current_season = sqlalchemy.Column(sqlalchemy.Integer)
season_start_date = sqlalchemy.Colu... | from nflpool.data.modelbase import SqlAlchemyBase
import sqlalchemy
class SeasonInfo(SqlAlchemyBase):
__tablename__ = 'SeasonInfo'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True)
current_season = sqlalchemy.Column(sqlalchemy.Integer)
season_start_date = sqlalchemy.Colu... | Update SeasonInfo database table info | Update SeasonInfo database table info
Add columns for the first game star time, home and away teams for the
first NFL game played of the season
| Python | mit | prcutler/nflpool,prcutler/nflpool |
0428522c8df724ce49a32686676b2c5345abfda9 | sdklib/util/timetizer.py | sdklib/util/timetizer.py | import time
import datetime
def get_current_utc(time_format="%Y-%m-%d %H:%M:%S"):
"""
@return a string representation of the current time in UTC.
"""
return time.strftime(time_format, time.gmtime())
def today_strf():
t = datetime.date.today()
return t.strftime("%d/%m/%Y")
def tomorrow_strf... | import time
import datetime
def get_current_utc(time_format="%Y-%m-%d %H:%M:%S"):
"""
@return a string representation of the current time in UTC.
"""
return time.strftime(time_format, time.gmtime())
def today_strf(format="%d/%m/%Y"):
t = datetime.date.today()
return t.strftime(format)
def ... | Add format parameter to strf functions | Add format parameter to strf functions
| Python | bsd-2-clause | ivanprjcts/sdklib,ivanprjcts/sdklib |
c04872d00a26e9bf0f48eeacb360b37ce0fba01e | semantic_release/pypi.py | semantic_release/pypi.py | """PyPI
"""
from invoke import run
from twine.commands import upload as twine_upload
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dis... | """PyPI
"""
from invoke import run
from twine import settings
from twine.commands import upload as twine_upload
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi ... | Use new interface for twine | fix: Use new interface for twine
| Python | mit | relekang/python-semantic-release,relekang/python-semantic-release |
fd0dad58403f34338b85edd83641e65a68779705 | casslist/views.py | casslist/views.py | from django.views import generic
from django.db.models import Sum
from cassupload import models
class CassListView(generic.ListView):
template_name = 'casslist/index.html'
context_object_name = 'cass_sound_list'
total_plays = models.Sound.objects.all().aggregate(Sum('play_count'))['play_count__sum']
... | from django.db import OperationalError
from django.views import generic
from django.db.models import Sum
from cassupload import models
class CassListView(generic.ListView):
template_name = 'casslist/index.html'
context_object_name = 'cass_sound_list'
try:
total_plays = models.Sound.objects.all()... | Fix error when making first migrations in a new project | [casslist] Fix error when making first migrations in a new project
| Python | mit | joshuaprince/Cassoundra,joshuaprince/Cassoundra,joshuaprince/Cassoundra |
2f4b57b2b7c5b391af615a204ad85dd04cc780d3 | chatroom/views.py | chatroom/views.py | from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
def index(request):
return render(request, 'index.html')
def append(request):
# open("data", "a").write(str(request.args.get("msg")) + "\n\r")
open("/tmp/data", "ab").write(request.GET['ms... | from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from login.views import isLogin
from login import auth
def index(request):
return render(request, 'index.html')
def append(request):
# open("data", "a").write(str(request.args.get("m... | Load profiles on the order page | Load profiles on the order page
| Python | mit | sonicyang/chiphub,sonicyang/chiphub,sonicyang/chiphub |
070b02c17e423e446562828af3ef69d06667472b | server/users/schema/queries.py | server/users/schema/queries.py | from django.contrib.auth import get_user_model
from graphene import AbstractType, Field, String
from users.jwt_util import get_token_user_id
from .definitions import Viewer
class UserQueries(AbstractType):
viewer = Field(Viewer)
@staticmethod
def resolve_viewer(self, args, context, info):
try:
... | from django.contrib.auth import get_user_model
from graphene import AbstractType, Field, String
from users.jwt_util import get_token_user_id
from .definitions import Viewer
class UserQueries(AbstractType):
viewer = Field(Viewer)
@staticmethod
def resolve_viewer(self, args, context, info):
users ... | Add better exception to viewer resolver | Add better exception to viewer resolver
| Python | mit | ncrmro/reango,ncrmro/reango,ncrmro/ango,ncrmro/reango,ncrmro/ango,ncrmro/ango |
e696fa2d398eb331cd5e25b2085b9d5c1e892aa1 | server/lib/python/cartodb_services/test/test_mapboxtrueisoline.py | server/lib/python/cartodb_services/test/test_mapboxtrueisoline.py | import unittest
from mock import Mock
from cartodb_services.mapbox.true_isolines import MapboxTrueIsolines, DEFAULT_PROFILE
from cartodb_services.tools import Coordinate
from credentials import mapbox_api_key
VALID_ORIGIN = Coordinate(-73.989, 40.733)
class MapboxTrueIsolinesTestCase(unittest.TestCase):
def se... | import unittest
from mock import Mock
from cartodb_services.mapbox.true_isolines import MapboxTrueIsolines, DEFAULT_PROFILE
from cartodb_services.tools import Coordinate
from credentials import mapbox_api_key
VALID_ORIGIN = Coordinate(-73.989, 40.733)
class MapboxTrueIsolinesTestCase(unittest.TestCase):
def se... | Add test to validate time ranges | Add test to validate time ranges
| Python | bsd-3-clause | CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/dataservices-api |
5f9d8b30313200d9baa55ea468ad5b94481ba871 | bianca/orm/repository.py | bianca/orm/repository.py | """
file: repository.py
author: Ben Grawi <bjg1568@rit.edu>
date: October 2013
description: Holds the repository abstraction class and ORM
"""
import uuid
from db import *
from datetime import datetime
class Repository(Base):
"""
Commit():
description: The SQLAlchemy ORM for the repository table
"""
... | """
file: repository.py
author: Ben Grawi <bjg1568@rit.edu>
date: October 2013
description: Holds the repository abstraction class and ORM
"""
import uuid
from db import *
from datetime import datetime
class Repository(Base):
"""
Commit():
description: The SQLAlchemy ORM for the repository table
"""
... | Make repo serializable via as_dict | Make repo serializable via as_dict
| Python | mit | bumper-app/bumper-bianca,bumper-app/bumper-bianca |
465977c2228620877b196e46ca883c743aeed856 | cf_predict/test/conftest.py | cf_predict/test/conftest.py | """Unit tests configuration file."""
import pickle
import numpy as np
import pytest
from sklearn import linear_model, tree, svm
from cf_predict import create_app
def pytest_configure(config):
"""Disable verbose output when running tests."""
terminal = config.pluginmanager.getplugin('terminal')
base = te... | """Unit tests configuration file."""
import pickle
import numpy as np
import pytest
from sklearn import linear_model, tree, svm
from mockredis import MockRedis
from cf_predict import create_app
def pytest_configure(config):
"""Disable verbose output when running tests."""
terminal = config.pluginmanager.get... | Use MockRedis instead of dict to mock redis in unit tests | Use MockRedis instead of dict to mock redis in unit tests
| Python | mit | ronert/cf-predict,ronert/cf-predict |
1c7af58f9fabb5edfc559660d742825d3fbdefb0 | chaoswg/forms.py | chaoswg/forms.py | from flask_wtf import FlaskForm
from wtforms.fields import StringField, PasswordField, IntegerField, FloatField, SubmitField
from wtforms.validators import InputRequired, NumberRange, Optional
class LoginForm(FlaskForm):
name = StringField(u'Username', validators=[InputRequired()])
password = PasswordField(u'... | from flask_wtf import FlaskForm
from wtforms.fields import StringField, PasswordField, IntegerField, FloatField, SubmitField
from wtforms.validators import InputRequired, NumberRange, Optional
class LoginForm(FlaskForm):
name = StringField(u'Username', validators=[InputRequired()])
password = PasswordField(u'... | Add some defaults for form input | Add some defaults for form input
| Python | agpl-3.0 | Obihoernchen/ChaosWG-Manager,Obihoernchen/ChaosWG-Manager,Obihoernchen/ChaosWG-Manager |
33e1e41e867e996baccddb9a892ec05bbd4f93f9 | polls/views.py | polls/views.py | from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from polls.models import Choice, Poll
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=pol... | from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from polls.models import Choice, Poll
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=pol... | Fix vote view to work with sharded Choice | Fix vote view to work with sharded Choice
| Python | apache-2.0 | disqus/sharding-example,komuW/sharding-example,komuW/sharding-example |
2b3df42f77c7277369631c1b31266a41526bf90c | src/rotest/management/migrations/0002_auto_20150224_1427.py | src/rotest/management/migrations/0002_auto_20150224_1427.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth import models as auth_models
def create_users(apps, schema_editor):
qa_group, _ = auth_models.Group.objects.get_or_create(name="QA")
localhost, _ = auth_models.User.objects.get_or_create(... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth import models as auth_models
ADMIN_USERNAME = "rotest"
ADMIN_PASSWORD = "rotest"
def create_users(apps, schema_editor):
qa_group, _ = auth_models.Group.objects.get_or_create(name="QA")
l... | Revert the superuser creation in a migration | Revert the superuser creation in a migration
| Python | mit | gregoil/rotest |
c7ec4e6be21718ed7b9b94aed2815150d8e4b95f | cheroot/test/test_compat.py | cheroot/test/test_compat.py | """Test Python 2/3 compatibility module."""
from __future__ import unicode_literals
import unittest
import pytest
import six
from cheroot import _compat as compat
class StringTester(unittest.TestCase):
"""Tests for string conversion."""
@pytest.mark.skipif(six.PY3, reason='Only useful on Python 2')
de... | """Test Python 2/3 compatibility module."""
from __future__ import unicode_literals
import unittest
import pytest
import six
from cheroot import _compat as compat
class StringTester(unittest.TestCase):
"""Tests for string conversion."""
@pytest.mark.skipif(six.PY3, reason='Only useful on Python 2')
de... | Revert ntob check to imperative style | Revert ntob check to imperative style
As context manager isn't available under Python 2.6
| Python | bsd-3-clause | cherrypy/cheroot |
fab9c33ed2e4e8c7c43ecf548dbc49c7b8cfd752 | observatory/manage.py | observatory/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import os.path
import sys
if __name__ == "__main__":
#Include parent directory in the path by default
path = os.path.abspath('../')
if path not in sys.path:
sys.path.append(path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "observatory.settings")
from... | Add parent directory in path by default | Add parent directory in path by default
| Python | isc | rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory |
67fcadfa8fd3e6c4161ca4756cc65f0db1386c06 | usercustomize.py | usercustomize.py | """ Customize Python Interpreter.
Link your user customizing file to this file.
For more info see: https://docs.python.org/3/library/site.html
"Default value is ~/.local/lib/pythonX.Y/site-packages for UNIX and
non-framework Mac OS X builds, ~/Library/Python/X.Y/lib/python/site-packages
for Mac framework builds, and... | """ Customize Python Interpreter.
Link your user customizing file to this file.
For more info see: https://docs.python.org/3/library/site.html
"Default value is ~/.local/lib/pythonX.Y/site-packages for UNIX and
non-framework Mac OS X builds, ~/Library/Python/X.Y/lib/python/site-packages
for Mac framework builds, and... | Add OS X GTK to Python path. | Add OS X GTK to Python path.
| Python | mit | fossilet/dotfiles,fossilet/dotfiles,fossilet/dotfiles |
e22794f07c6d1027e16617ac6874289794080967 | account_payment_include_draft_move/wizard/payment_order_create.py | account_payment_include_draft_move/wizard/payment_order_create.py | # -*- coding: utf-8 -*-
#
##############################################################################
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gener... | # -*- coding: utf-8 -*-
#
##############################################################################
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gener... | Replace partial domain by (1,'=',1) | [IMP] Replace partial domain by (1,'=',1)
| Python | agpl-3.0 | sergio-incaser/bank-payment,sergio-incaser/bank-payment,sergiocorato/bank-payment,damdam-s/bank-payment,rlizana/bank-payment,CompassionCH/bank-payment,incaser/bank-payment,sergiocorato/bank-payment,Antiun/bank-payment,sergio-teruel/bank-payment,rlizana/bank-payment,ndtran/bank-payment,David-Amaro/bank-payment,sergio-te... |
1fd2299b2a0c993bd463ab88c0a7544ade2c945b | test_kasp/disk/test_disk.py | test_kasp/disk/test_disk.py | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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 applica... | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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 applica... | Remove init mrthod from disk test | Remove init mrthod from disk test
Removed init method from test class for disk test
| Python | apache-2.0 | vrovachev/kaspersky-framework |
4ce6792829174e7df4614e5caeddf5b280d59822 | comics/comics/darklegacy.py | comics/comics/darklegacy.py | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Dark Legacy"
language = "en"
url = "http://www.darklegacycomics.com/"
start_date = "2006-01-01"
rights = "Arad Kedar"
class Crawler(CrawlerBase... | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Dark Legacy"
language = "en"
url = "http://www.darklegacycomics.com/"
start_date = "2006-01-01"
rights = "Arad Kedar"
class Crawler(CrawlerBase... | Change history capability for "Dark Legacy" | Change history capability for "Dark Legacy"
| Python | agpl-3.0 | datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics |
d927ada17522edfb91489e8558bbc88ff741a3c5 | bokeh/models/widgets/markups.py | bokeh/models/widgets/markups.py | """ Various kinds of markup (static content) widgets.
"""
from __future__ import absolute_import
from ...properties import abstract
from ...properties import Int, String
from ..widget import Widget
class Paragraph(Widget):
""" A block (paragraph) of text.
"""
text = String(help="""
The contents of ... | """ Various kinds of markup (static content) widgets.
"""
from __future__ import absolute_import
from ...properties import abstract
from ...properties import Int, String
from ..widget import Widget
@abstract
class Markup(Widget):
""" Base class for HTML markup widget models. """
class Paragraph(Markup):
"""... | Introduce Markup abstract base class | Introduce Markup abstract base class
| Python | bsd-3-clause | aiguofer/bokeh,jakirkham/bokeh,ChinaQuants/bokeh,percyfal/bokeh,bokeh/bokeh,philippjfr/bokeh,philippjfr/bokeh,stonebig/bokeh,percyfal/bokeh,muku42/bokeh,DuCorey/bokeh,muku42/bokeh,ericmjl/bokeh,azjps/bokeh,muku42/bokeh,percyfal/bokeh,philippjfr/bokeh,msarahan/bokeh,deeplook/bokeh,Karel-van-de-Plassche/bokeh,htygithub/b... |
2cb73ac018287ab77b380c31166ec4fc6fd99f5e | performanceplatform/collector/gcloud/__init__.py | performanceplatform/collector/gcloud/__init__.py | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
ge... | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
ge... | Make the G-Cloud collector empty the data set | Make the G-Cloud collector empty the data set
https://www.pivotaltracker.com/story/show/72073020
[Delivers #72073020]
| Python | mit | alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector |
bd0ccca9e629b6a9c48147984b8d68cf80fe470c | test/single_system/bmc_test.py | test/single_system/bmc_test.py | import sys, unittest
from singlesystemtest import SingleSystemTest
class TestBmcInfo(SingleSystemTest):
def test_bmc_info(self):
"""BMC info provides expected results"""
info = self.bmc.info()
check_items = self.get_checks()['BMCInfo']
for item,expected in check_items.iteritems():... | import sys, unittest
from singlesystemtest import SingleSystemTest
class TestBmcInfo(SingleSystemTest):
def test_bmc_info(self):
"""BMC info provides expected results"""
info = self.bmc.info()
check_items = self.get_checks()['BMCInfo']
for item,expected in check_items.iteritems():... | Add a test for bmc info working eleven times in a row | Add a test for bmc info working eleven times in a row
This is specifically to check for SW-732, where results stop after 10
bmc info requests.
| Python | bsd-3-clause | Cynerva/pyipmi,emaadmanzoor/pyipmi |
7346103a36d69d1f27bc064843afa8c18d201d2b | go/apps/bulk_message/definition.py | go/apps/bulk_message/definition.py | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Write and send bulk message'
needs_confirmation = True
needs_group = True
needs_running = True
de... | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Write and send bulk message'
action_display_verb = 'Send message'
needs_confirmation = True
needs_grou... | Change send bulk message display verb to 'Send message'. | Change send bulk message display verb to 'Send message'.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go |
fc18f86964e170c48632c614c86a0d26c9fbdd41 | tests/test_load_module_from_file_location.py | tests/test_load_module_from_file_location.py | from pathlib import Path
from types import ModuleType
import pytest
from sanic.exceptions import LoadFileException
from sanic.utils import load_module_from_file_location
@pytest.fixture
def loaded_module_from_file_location():
return load_module_from_file_location(
str(Path(__file__).parent / "static/app... | from pathlib import Path
from types import ModuleType
import pytest
from sanic.exceptions import LoadFileException
from sanic.utils import load_module_from_file_location
@pytest.fixture
def loaded_module_from_file_location():
return load_module_from_file_location(
str(Path(__file__).parent / "static" / ... | Resolve broken test in appveyor | Resolve broken test in appveyor
| Python | mit | channelcat/sanic,channelcat/sanic,ashleysommer/sanic,channelcat/sanic,ashleysommer/sanic,ashleysommer/sanic,channelcat/sanic |
bdcaaf4ab999c51a6633b7e72971d7594de0b66b | bin/clean_unused_headers.py | bin/clean_unused_headers.py | #!/usr/bin/env python
from __future__ import print_function
import sys
import os
import re
from subprocess import check_output
IMAGE_PATTERN = re.compile(
'linux-image-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
HEADER_PATTERN = re.compile(
'linux-headers-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic'... | #!/usr/bin/env python
from __future__ import print_function
import sys
import os
import re
from subprocess import check_output
IMAGE_PATTERN = re.compile(
'linux-image-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
HEADER_PATTERN = re.compile(
'linux-headers-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic'... | Add python script to find unused linux-headers packages | Add python script to find unused linux-headers packages
| Python | apache-2.0 | elleryq/oh-my-home,elleryq/oh-my-home,elleryq/oh-my-home |
5392626ef746cf52043494e7d1360fd373bdfe93 | cort/core/util.py | cort/core/util.py | """ Utility functions. """
__author__ = 'smartschat'
def clean_via_pos(tokens, pos):
""" Clean a list of tokens according to their part-of-speech tags.
In particular, retain only tokens which do not have the part-of-speech tag
DT (determiner) or POS (possessive 's').
Args:
tokens (list(str)... | """ Utility functions. """
__author__ = 'smartschat'
def clean_via_pos(tokens, pos):
""" Clean a list of tokens according to their part-of-speech tags.
In particular, retain only tokens which do not have the part-of-speech tag
DT (determiner) or POS (possessive 's').
Args:
tokens (list(str)... | Read java path from environment variable if set | Read java path from environment variable if set | Python | mit | smartschat/cort,smartschat/cort,smartschat/cort,smartschat/cort,smartschat/cort |
67daf4140c17ce28b0ab45ddd2366968082de739 | two_factor/auth_backends.py | two_factor/auth_backends.py | from django.contrib.auth.backends import ModelBackend
from django.utils.timezone import now
from oath import accept_totp
class TokenBackend(ModelBackend):
def authenticate(self, user, token):
accepted, drift = accept_totp(key=user.token.seed, response=token)
return user if accepted else None
cla... | from django.contrib.auth.backends import ModelBackend
from django.utils.timezone import now
from oath import accept_totp
class TokenBackend(ModelBackend):
def authenticate(self, user, token):
accepted, drift = accept_totp(key=user.token.seed, response=token)
return user if accepted else None
cla... | Update last_used_at after successful computer verification | Update last_used_at after successful computer verification
| Python | mit | mathspace/django-two-factor-auth,percipient/django-two-factor-auth,percipient/django-two-factor-auth,moreati/django-two-factor-auth,Bouke/django-two-factor-auth,moreati/django-two-factor-auth,mathspace/django-two-factor-auth,koleror/django-two-factor-auth,koleror/django-two-factor-auth,Bouke/django-two-factor-auth,fusi... |
e80cc896396b217a3e3a4f01294b50061faf68cd | cyder/cydhcp/range/forms.py | cyder/cydhcp/range/forms.py | from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.cydhcp.range.models import Range, RangeAV
from cyder.cydns.forms import ViewChoiceForm
class RangeForm(ViewChoiceForm, UsabilityFormMixin):
class Meta:
model = Range
... | from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.cydhcp.range.models import Range, RangeAV
from cyder.cydns.forms import ViewChoiceForm
class RangeForm(ViewChoiceForm, UsabilityFormMixin):
class Meta:
model = Range
... | Put name first in range form | Put name first in range form
| Python | bsd-3-clause | zeeman/cyder,zeeman/cyder,akeym/cyder,akeym/cyder,akeym/cyder,OSU-Net/cyder,OSU-Net/cyder,murrown/cyder,zeeman/cyder,OSU-Net/cyder,OSU-Net/cyder,murrown/cyder,akeym/cyder,zeeman/cyder,drkitty/cyder,murrown/cyder,murrown/cyder,drkitty/cyder,drkitty/cyder,drkitty/cyder |
f9aa61893ea0b7e98dc4e5b25cbf63c2fffde672 | libs/googleapis.py | libs/googleapis.py | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
... | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
... | Add url logging in google shortener | Add url logging in google shortener
| Python | mit | sevazhidkov/leonard |
93282e663a03c2a62fcf9731db3d152b3d2c32c7 | test_publisher.py | test_publisher.py | import publisher
def from_html_file():
source_file = "~/Projects/markdown-publisher/source_test.md"
print publisher.get_html_from_file(source_file)
def from_html():
test_source = "# Test heading\n\n- test item 1\n- test item 2"
print publisher.get_html(test_source)
def from_html_to_pdf():
test_ht... | import publisher
test_pdf_filename = "test/test.pdf"
test_css_filename = "test/test.css"
test_md_filename = "test/test.md"
test_html_filename = "test/test.html"
test_md = "# Test heading\n\n- test item 1\n- test item 2"
def from_html_file():
print publisher.md_to_html(publisher.from_file(test_md_filename))
def ... | Add MD+CSS processing test to test module. | Add MD+CSS processing test to test module.
| Python | mit | cpgillem/markdown_publisher,cpgillem/markdown_publisher |
1b6c49c6d74dcd31c8a0e51f82932866bc99adc2 | setup_rouge.py | setup_rouge.py | #!/usr/bin/env python
"""
Utility to copy ROUGE script.
It has to be run before `setup.py`
"""
import os
import shutil
from files2rouge import settings
from six.moves import input
def copy_rouge():
home = os.environ['HOME']
src_rouge_root = "./files2rouge/RELEASE-1.5.5/"
default_root = os.path... | #!/usr/bin/env python
"""
Utility to copy ROUGE script.
It has to be run before `setup.py`
"""
import os
import shutil
from files2rouge import settings
from six.moves import input
def copy_rouge():
if 'HOME' not in os.environ:
home = os.environ['HOMEPATH']
else:
home = os.environ['HO... | Fix bug: KeyError: 'HOME' in Windows. | Fix bug: KeyError: 'HOME' in Windows.
| Python | mit | pltrdy/files2rouge,pltrdy/files2rouge |
77b0ac8e4230663e0c0394366185ad32fb8ff6ba | configurator/__init__.py | configurator/__init__.py | """Adaptive configuration dialogs.
Attributes:
__version__: The current version string.
"""
import os
import subprocess
def _get_version(version=None): # overwritten by setup.py
if version is None:
pkg_dir = os.path.dirname(__file__)
src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir... | """Adaptive configuration dialogs.
Attributes:
__version__: The current version string.
"""
import os
import subprocess
def _get_version(version=None): # overwritten by setup.py
if version is None:
pkg_dir = os.path.dirname(__file__)
src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir... | Fix _get_version for tagged releases | Fix _get_version for tagged releases
| Python | apache-2.0 | yasserglez/configurator,yasserglez/configurator |
5a03cd340e5dc8a796c7d430128f0e22be17333e | qiime/sdk/__init__.py | qiime/sdk/__init__.py | # ----------------------------------------------------------------------------
# Copyright (c) 2016--, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# -----------------------------------------------... | # ----------------------------------------------------------------------------
# Copyright (c) 2016--, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# -----------------------------------------------... | Add helper URLs to qiime.sdk | ENH: Add helper URLs to qiime.sdk
Adds citation url, help page, and conda channel URLs to qiime.sdk
| Python | bsd-3-clause | biocore/qiime2,thermokarst/qiime2,ebolyen/qiime2,jakereps/qiime2,qiime2/qiime2,qiime2/qiime2,nervous-laughter/qiime2,biocore/qiime2,thermokarst/qiime2,jairideout/qiime2,jakereps/qiime2 |
4b43a2f50740bbeab95f64137eb8993ed8ac4617 | other/password_generator.py | other/password_generator.py | import string
from random import *
letters = string.ascii_letters
digits = string.digits
symbols = string.punctuation
chars = letters + digits + symbols
min_length = 8
max_length = 16
password = ''.join(choice(chars) for x in range(randint(min_length, max_length)))
print('Password: %s' % password)
print('[ If you are... | import string
import random
letters = [letter for letter in string.ascii_letters]
digits = [digit for digit in string.digits]
symbols = [symbol for symbol in string.punctuation]
chars = letters + digits + symbols
random.shuffle(chars)
min_length = 8
max_length = 16
password = ''.join(random.choice(chars) for x in ran... | Add another randomness into the password generator | Add another randomness into the password generator
Uses import random for namespace cleanliness
Uses list instead of string for 'chars' variable in order to shuffle, increases randomness
Instead of string formatting, uses string concatenation because (currently) it is simpler | Python | mit | TheAlgorithms/Python |
9e02f92fc19b7f833b25d0273143e98261a3b484 | democracy/admin/__init__.py | democracy/admin/__init__.py | from django.contrib import admin
from nested_admin.nested import NestedAdmin, NestedStackedInline
from democracy import models
# Inlines
class HearingImageInline(NestedStackedInline):
model = models.HearingImage
extra = 0
class SectionImageInline(NestedStackedInline):
model = models.SectionImage
... | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from nested_admin.nested import NestedAdmin, NestedStackedInline
from democracy import models
# Inlines
class HearingImageInline(NestedStackedInline):
model = models.HearingImage
extra = 0
exclude = ("public", "tit... | Hide unnecessary fields in the admins | Hide unnecessary fields in the admins
* Hide some unnecessary fields from Hearings
* Hide Public and Commenting flags from Sections
(Section commenting option follows that of hearings.)
* Hide Public and Title fields from images
* Hide Public field from labels
Refs #118
| Python | mit | vikoivun/kerrokantasi,stephawe/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,stephawe/kerrokantasi,vikoivun/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,vikoivun/kerrokantasi |
6b4e34a5091ec00dffb1add55fa8dc279cbc2c89 | scattertext/frequencyreaders/DefaultBackgroundFrequencies.py | scattertext/frequencyreaders/DefaultBackgroundFrequencies.py | import pkgutil
from io import StringIO
import pandas as pd
from scipy.stats import rankdata
class BackgroundFrequencies(object):
@staticmethod
def get_background_frequency_df(frequency_path=None):
raise Exception
@classmethod
def get_background_rank_df(cls, frequency_path=None):
df = cls.get_background_freq... | import pkgutil
from io import StringIO
import pandas as pd
from scipy.stats import rankdata
class BackgroundFrequencies(object):
@staticmethod
def get_background_frequency_df(frequency_path=None):
raise Exception
@classmethod
def get_background_rank_df(cls, frequency_path=None):
df =... | Fix FutureWarning: read_table is deprecated, use read_csv instead, passing sep='\t' | Fix FutureWarning: read_table is deprecated, use read_csv instead, passing sep='\t'
| Python | apache-2.0 | JasonKessler/scattertext,JasonKessler/scattertext,JasonKessler/scattertext,JasonKessler/scattertext |
40fc5c555e471f28959cbe3ad7d929636384595a | casexml/apps/stock/utils.py | casexml/apps/stock/utils.py | UNDERSTOCK_THRESHOLD = 0.5 # months
OVERSTOCK_THRESHOLD = 2. # months
def months_of_stock_remaining(stock, daily_consumption):
try:
return stock / (daily_consumption * 30)
except (TypeError, ZeroDivisionError):
return None
def stock_category(stock, daily_consumption):
if stock is None:... | from decimal import Decimal
UNDERSTOCK_THRESHOLD = 0.5 # months
OVERSTOCK_THRESHOLD = 2. # months
def months_of_stock_remaining(stock, daily_consumption):
if daily_consumption:
return stock / Decimal((daily_consumption * 30))
else:
return None
def stock_category(stock, daily_consumption):... | Fix error handling on aggregate status report | Fix error handling on aggregate status report
Previously the catch block was a little too aggressive. It was swallowing a
real error (since aggregate reports pass a float, not a decimal). Now we
prevent the original possible errors by converting no matter what the type is
and checking for zero/null values first.
| Python | bsd-3-clause | dimagi/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,SEL-Col... |
ceb32eb2cefadc04fdf7cf5c474a96d307a1618f | core/observables/file.py | core/observables/file.py | from __future__ import unicode_literals
from mongoengine import *
from core.observables import Observable
from core.observables import Hash
class File(Observable):
value = StringField(verbose_name="SHA256 hash")
mime_type = StringField(verbose_name="MIME type")
hashes = DictField(verbose_name="Hashes"... | from __future__ import unicode_literals
from flask import url_for
from flask_mongoengine.wtf import model_form
from mongoengine import *
from core.observables import Observable
from core.database import StringListField
class File(Observable):
value = StringField(verbose_name="Value")
mime_type = StringFie... | Clean up File edit view | Clean up File edit view
| Python | apache-2.0 | yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti |
6172eafbaf65b859462985056bb33490b98b0749 | peloid/app/shell/service.py | peloid/app/shell/service.py | from twisted.cred import portal
from twisted.conch import manhole_ssh
from twisted.conch.checkers import SSHPublicKeyDatabase
from carapace.util import ssh as util
from peloid.app.shell import gameshell, setupshell
def getGameShellFactory(**namespace):
game = None
sshRealm = gameshell.TerminalRealm(namespac... | from twisted.cred import portal
from twisted.conch import manhole_ssh
from twisted.conch.checkers import SSHPublicKeyDatabase
from carapace.util import ssh as util
from peloid.app import mud
from peloid.app.shell import gameshell, setupshell
def getGameShellFactory(**namespace):
game = mud.Game()
sshRealm =... | Use the new Game class. | Use the new Game class.
| Python | mit | oubiwann/peloid |
7b77297f9099019f4424c7115deb933dd51eaf80 | setup.py | setup.py | #!/usr/local/bin/python3
from distutils.core import setup, Extension
setup(
name = 'Encoder',
version = '1.0',
description = 'Encode stuff',
ext_modules = [
Extension(
name = '_encoder',
sources = [
'src/encoder.c',
'src/module.c',
... | #!/usr/local/bin/python3
from distutils.core import setup, Extension
setup(
name = 'Encoder',
version = '1.0',
description = 'Encode stuff',
ext_modules = [
Extension(
name = '_encoder',
sources = [
'src/encoder.c',
'src/module.c',
... | Include buffer.h as a dependency for rebuilds | Include buffer.h as a dependency for rebuilds
| Python | apache-2.0 | blake-sheridan/py-serializer,blake-sheridan/py-serializer |
346ddf5e26351fe1fadbed1bf06482565080a728 | stack.py | stack.py | #!/usr/bin/env python
'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''
class Item(object):
def __init__(self, value, next_item=None):
self.value = value
self.... | #!/usr/bin/env python
'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''
class Item(object):
def __init__(self, value, next_item=None):
self.value = value
self.... | Add pop method on Stack class | Add pop method on Stack class
| Python | mit | jwarren116/data-structures-deux |
0d475a69ca53eee62aeb39f35b3d3a8f875d5e71 | tests/menu_test_5.py | tests/menu_test_5.py | """Tests the menu features."""
##==============================================================#
## SECTION: Imports #
##==============================================================#
from testlib import *
from qprompt import enum_menu
##=================================... | """Tests the menu features."""
##==============================================================#
## SECTION: Imports #
##==============================================================#
from testlib import *
from qprompt import enum_menu
##=================================... | Change to get test to pass. | Change to get test to pass.
| Python | mit | jeffrimko/Qprompt |
ab41fe934ce241a4dbe5f73f648858f6f9351d5c | tests/settings.py | tests/settings.py | import dj_database_url
DATABASES = {
'default': dj_database_url.config(
default='postgres://localhost/test_utils',
),
}
INSTALLED_APPS = (
'incuna_test_utils',
'tests',
'feincms.module.page',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'... | import dj_database_url
DATABASES = {
'default': dj_database_url.config(
default='postgres://localhost/test_utils',
),
}
INSTALLED_APPS = (
'incuna_test_utils',
'tests',
'feincms.module.page',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'... | Fix TEMPLATES warning on Django 1.9 | Fix TEMPLATES warning on Django 1.9
| Python | bsd-2-clause | incuna/incuna-test-utils,incuna/incuna-test-utils |
f3cd06721efaf3045d09f2d3c2c067e01b27953a | tests/som_test.py | tests/som_test.py | import unittest
from parameterized import parameterized
from som.vm.universe import Universe
class SomTest(unittest.TestCase):
@parameterized.expand([
("ClassStructure",),
("Array" ,),
("Block" ,),
("ClassLoading" ,),
("Closure" ,),
("Coercio... | import unittest
from parameterized import parameterized
from som.vm.universe import Universe
class SomTest(unittest.TestCase):
@parameterized.expand([
("Array" ,),
("Block" ,),
("ClassLoading" ,),
("ClassStructure",),
("Closure" ,),
("Coercio... | Sort tests, to verify they are complete | Sort tests, to verify they are complete
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
| Python | mit | SOM-st/PySOM,SOM-st/RPySOM,SOM-st/RTruffleSOM,SOM-st/RPySOM,smarr/PySOM,smarr/PySOM,smarr/RTruffleSOM,SOM-st/RTruffleSOM,smarr/RTruffleSOM,SOM-st/PySOM |
4f3f738d7fc4b1728c74d6ffc7bf3064ce969520 | tests/test_cli.py | tests/test_cli.py | import subprocess
def test_cli_usage():
cmd = ["salib"]
out = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
out = out.decode()
assert len(out) > 0 and "usage" in out.lower(), \
"Incorrect message returned from utility"
def test_cli_setup():
cmd = ["salib", "sample", ... | import subprocess
import importlib
from SALib.util import avail_approaches
def test_cli_usage():
cmd = ["salib"]
out = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
out = out.decode()
assert len(out) > 0 and "usage" in out.lower(), \
"Incorrect message returned from utilit... | Test to ensure all samplers and analyzers have required functions | Test to ensure all samplers and analyzers have required functions
All methods should have `cli_parse` and `cli_action` functions available | Python | mit | willu47/SALib,willu47/SALib,jdherman/SALib,jdherman/SALib,SALib/SALib |
ace38e69c66a5957a155091fbd3c746952f982fc | tests.py | tests.py | from scraper.tivix import get_list_of_tivix_members
from scraper.tivix import get_random_tivix_member_bio
def test_get_all_tivix_members():
members = get_list_of_tivix_members()
assert members
assert '/team-members/jack-muratore/' in members
assert '/team-members/kyle-connors/' in members
assert '... | from scraper.tivix import get_list_of_tivix_members
from scraper.tivix import get_random_tivix_member_bio
def test_get_all_tivix_members():
members = get_list_of_tivix_members()
assert members
assert '/team-members/jack-muratore/' in members
assert '/team-members/kyle-connors/' in members
assert '... | Rename test to be more fitting | Rename test to be more fitting
| Python | mit | banjocat/alexa-tivix-members |
797e9f3e4fad744e9211c07067992c245a344fb5 | tests/test_whatcd.py | tests/test_whatcd.py | from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase, use_vcr
class TestInputWhatCD(FlexGetBase):
__yaml__ = """
tasks:
no_fields:
whatcd:
no_user:
whatcd:
password: test
no_pass:
... | from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase, use_vcr
class TestWhatCDOnline(FlexGetBase):
__yaml__ = """
tasks:
badlogin:
whatcd:
username: invalid
password: invalid
"""
@use_vcr
def test_... | Remove schema validation unit tests frow whatcd | Remove schema validation unit tests frow whatcd
| Python | mit | JorisDeRieck/Flexget,Danfocus/Flexget,qk4l/Flexget,Flexget/Flexget,JorisDeRieck/Flexget,qk4l/Flexget,ianstalk/Flexget,dsemi/Flexget,oxc/Flexget,crawln45/Flexget,qvazzler/Flexget,Flexget/Flexget,sean797/Flexget,oxc/Flexget,Flexget/Flexget,dsemi/Flexget,drwyrm/Flexget,OmgOhnoes/Flexget,drwyrm/Flexget,jacobmetrick/Flexget... |
e3a3f55b0db2a5ed323e23dc0d949378a9871a15 | nex/parsing/general_text_parser.py | nex/parsing/general_text_parser.py | from ..tokens import BuiltToken
from .common_parsing import pg as common_pg
gen_txt_pg = common_pg.copy_to_extend()
@gen_txt_pg.production('general_text : filler LEFT_BRACE BALANCED_TEXT_AND_RIGHT_BRACE')
def general_text(p):
return BuiltToken(type_='general_text', value=p[2].value,
posit... | from ..rply import ParserGenerator
from ..tokens import BuiltToken
term_types = ['SPACE', 'RELAX', 'LEFT_BRACE', 'BALANCED_TEXT_AND_RIGHT_BRACE']
gen_txt_pg = ParserGenerator(term_types, cache_id="general_text")
@gen_txt_pg.production('general_text : filler LEFT_BRACE BALANCED_TEXT_AND_RIGHT_BRACE')
def general_tex... | Duplicate small parts to make general text parser independent and simple | Duplicate small parts to make general text parser independent and simple
| Python | mit | eddiejessup/nex |
c6b8ff0f5c8b67dd6d48ccfe8c82b98d33b979a6 | openfisca_web_api/scripts/serve.py | openfisca_web_api/scripts/serve.py | # -*- coding: utf-8 -*-
import os
import sys
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
hostname = 'localhost'
port = 2000
def main():
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-fr... | # -*- coding: utf-8 -*-
import os
import sys
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
hostname = 'localhost'
port = 2000
def main():
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-fr... | Manage case where api installed with --editable | Manage case where api installed with --editable
| Python | agpl-3.0 | openfisca/openfisca-web-api,openfisca/openfisca-web-api |
537cf5da8b0328d7e6d745a4ab5456b77702e124 | delivery/services/external_program_service.py | delivery/services/external_program_service.py |
import subprocess
import logging
from delivery.models.execution import ExecutionResult, Execution
log = logging.getLogger(__name__)
class ExternalProgramService(object):
"""
A service for running external programs
"""
@staticmethod
def run(cmd):
"""
Run a process and do not wai... |
from tornado.process import Subprocess
from tornado import gen
from subprocess import PIPE
from delivery.models.execution import ExecutionResult, Execution
class ExternalProgramService(object):
"""
A service for running external programs
"""
@staticmethod
def run(cmd):
"""
Run... | Make ExternalProgramService use async process from tornado | Make ExternalProgramService use async process from tornado
| Python | mit | arteria-project/arteria-delivery |
5827c09e3a003f53baa5abe2d2d0fc5d695d4334 | arxiv_vanity/papers/management/commands/delete_all_expired_renders.py | arxiv_vanity/papers/management/commands/delete_all_expired_renders.py | from django.core.management.base import BaseCommand, CommandError
from ...models import Render
class Command(BaseCommand):
help = 'Deletes output of all expired renders'
def handle(self, *args, **options):
for render in Render.objects.expired().iterator():
try:
render.dele... | from django.core.management.base import BaseCommand, CommandError
from ...models import Render
class Command(BaseCommand):
help = 'Deletes output of all expired renders'
def handle(self, *args, **options):
for render in Render.objects.expired().iterator():
try:
render.dele... | Add flush to delete all renders print | Add flush to delete all renders print
| Python | apache-2.0 | arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity |
16ad5a3f17fdb96f2660019fabbd7bb787ae4ffb | pywsd/baseline.py | pywsd/baseline.py | #!/usr/bin/env python -*- coding: utf-8 -*-
#
# Python Word Sense Disambiguation (pyWSD): Baseline WSD
#
# Copyright (C) 2014-2020 alvations
# URL:
# For license information, see LICENSE.md
import random
custom_random = random.Random(0)
def random_sense(ambiguous_word, pos=None):
""" Returns a random sense. """
... | #!/usr/bin/env python -*- coding: utf-8 -*-
#
# Python Word Sense Disambiguation (pyWSD): Baseline WSD
#
# Copyright (C) 2014-2020 alvations
# URL:
# For license information, see LICENSE.md
import random
custom_random = random.Random(0)
def random_sense(ambiguous_word, pos=None):
""" Returns a random sense. """
... | Add pos for max_lemma_count also | Add pos for max_lemma_count also
| Python | mit | alvations/pywsd,alvations/pywsd |
dfbe71a6d6a1e8591b1a6d7d5baeda20f2e40c47 | indra/explanation/model_checker/__init__.py | indra/explanation/model_checker/__init__.py | from .model_checker import ModelChecker, PathResult, PathMetric, get_path_iter
from .pysb import PysbModelChecker
from .signed_graph import SignedGraphModelChecker
from .unsigned_graph import UnsignedGraphModelChecker
from .pybel import PybelModelChecker
| from .model_checker import ModelChecker, PathResult, PathMetric, get_path_iter
from .pysb import PysbModelChecker
from .signed_graph import SignedGraphModelChecker
from .unsigned_graph import UnsignedGraphModelChecker
from .pybel import PybelModelChecker
from .model_checker import signed_edges_to_signed_nodes, prune_si... | Make function top level importable | Make function top level importable
| Python | bsd-2-clause | bgyori/indra,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra,sorgerlab/belpy,sorgerlab/indra,sorgerlab/indra,bgyori/indra,johnbachman/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/belpy |
d0e5c03fe37d89747e870c57312701df0e2949c0 | ulp/urlextract.py | ulp/urlextract.py | # coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.getenv('HOM... | # coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.getenv('HOM... | Move ansi_escape to generic function | Move ansi_escape to generic function
| Python | mit | victal/ulp,victal/ulp |
b4f4e870877e4eae8e7dbf2dd9c961e5eec6980d | devtools/ci/push-docs-to-s3.py | devtools/ci/push-docs-to-s3.py | import os
import pip
import tempfile
import subprocess
import openpathsampling.version
BUCKET_NAME = 'openpathsampling.org'
if not openpathsampling.version.release:
PREFIX = 'latest'
else:
PREFIX = openpathsampling.version.short_version
if not any(d.project_name == 's3cmd' for d in pip.get_installed_distribu... | import os
import pip
import tempfile
import subprocess
import openpathsampling.version
BUCKET_NAME = 'openpathsampling.org'
if not openpathsampling.version.release:
PREFIX = 'latest'
else:
PREFIX = openpathsampling.version.short_version
if not any(d.project_name == 's3cmd' for d in pip.get_installed_distribu... | Add MIME-handling options to s3cmd | Add MIME-handling options to s3cmd
| Python | mit | openpathsampling/openpathsampling,choderalab/openpathsampling,choderalab/openpathsampling,dwhswenson/openpathsampling,openpathsampling/openpathsampling,choderalab/openpathsampling,dwhswenson/openpathsampling,dwhswenson/openpathsampling,openpathsampling/openpathsampling,dwhswenson/openpathsampling,openpathsampling/openp... |
40491b243beca358e81184857a155fb4d2d52157 | drogher/shippers/base.py | drogher/shippers/base.py | import re
class Shipper(object):
barcode = None
barcode_pattern = None
shipper = None
def __init__(self, barcode):
self.barcode = barcode
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property... | import re
class Shipper(object):
barcode = None
barcode_pattern = None
shipper = None
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('shippers.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
i... | Add a more useful representation of Shipper objects | Add a more useful representation of Shipper objects
| Python | bsd-3-clause | jbittel/drogher |
5a44392b810800c4440b04aa92a4614e45c12e86 | mla_game/apps/transcript/management/commands/fake_game_one_gameplay.py | mla_game/apps/transcript/management/commands/fake_game_one_gameplay.py | import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random... | import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random... | Fix fake game one script | Fix fake game one script
| Python | mit | WGBH/FixIt,WGBH/FixIt,WGBH/FixIt |
a595e75968fa26a49b3d08661b9a0e3bb192929e | kokki/cookbooks/cloudera/recipes/default.py | kokki/cookbooks/cloudera/recipes/default.py |
from kokki import *
apt_list_path = '/etc/apt/sources.list.d/cloudera.list'
apt = (
"deb http://archive.cloudera.com/debian {distro}-cdh3 contrib\n"
"deb-src http://archive.cloudera.com/debian {distro}-cdh3 contrib\n"
).format(distro=env.system.lsb['codename'])
Execute("apt-get update", action="nothing")
Ex... |
from kokki import *
env.include_recipe("java.jre")
apt_list_path = '/etc/apt/sources.list.d/cloudera.list'
apt = (
"deb http://archive.cloudera.com/debian {distro}-cdh3 contrib\n"
"deb-src http://archive.cloudera.com/debian {distro}-cdh3 contrib\n"
).format(distro=env.system.lsb['codename'])
Execute("apt-ge... | Install sun java when using cloudera | Install sun java when using cloudera
| Python | bsd-3-clause | samuel/kokki |
700912cc3db69cfd99e33b715dcba7b6717aa225 | apps/bluebottle_utils/models.py | apps/bluebottle_utils/models.py | from django.db import models
from django_countries import CountryField
class Address(models.Model):
"""
A postal address.
"""
address_line1 = models.CharField(max_length=100, blank=True)
address_line2 = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=100, blank... | from django.db import models
from django_countries import CountryField
class Address(models.Model):
"""
A postal address.
"""
line1 = models.CharField(max_length=100, blank=True)
line2 = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=100, blank=True)
state ... | Remove the address_ prefix from line1 and line2 in the Address model. | Remove the address_ prefix from line1 and line2 in the Address model.
The address_ prefix is redundant now that we have an Address model.
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site |
efaa172668b8961734fa8a10650dc3191b4a7348 | website/project/metadata/authorizers/__init__.py | website/project/metadata/authorizers/__init__.py | import json
import os
import logging
logger = logging.getLogger(__name__)
HERE = os.path.dirname(os.path.realpath(__file__))
groups = json.load(open('{0}/defaults.json'.format(HERE)))
try:
fp = open('{0}/local.json'.format(HERE))
except IOError:
logger.info('No local.json found to populate lists of DraftRegi... | import json
import os
import logging
logger = logging.getLogger(__name__)
HERE = os.path.dirname(os.path.realpath(__file__))
groups = json.load(open('{0}/defaults.json'.format(HERE)))
fp = None
try:
fp = open('{0}/local.json'.format(HERE))
except IOError:
logger.info('No local.json found to populate lists of... | Allow local.json to be missing | Allow local.json to be missing
| Python | apache-2.0 | kch8qx/osf.io,acshi/osf.io,binoculars/osf.io,abought/osf.io,mluo613/osf.io,cslzchen/osf.io,chrisseto/osf.io,ticklemepierce/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,kwierman/osf.io,brandonPurvis/osf.io,icereval/osf.io,TomBaxter/osf.io,doublebits/osf.io,mluke93/osf.io,wearpants/osf.io,alexschiller/osf.io,billyhunt/osf.... |
07823ae7f7368f4bc4a4e4436129319f7215150b | faker/utils/distribution.py | faker/utils/distribution.py | # coding=utf-8
import bisect
from faker.generator import random
def random_sample():
return random.uniform(0.0, 1.0)
def cumsum(it):
total = 0
for x in it:
total += x
yield total
def choice_distribution(a, p):
assert len(a) == len(p)
cdf = list(cumsum(p))
normal = cdf[-1]
... | # coding=utf-8
import bisect
from sys import version_info
from faker.generator import random
def random_sample():
return random.uniform(0.0, 1.0)
def cumsum(it):
total = 0
for x in it:
total += x
yield total
def choice_distribution(a, p):
assert len(a) == len(p)
if version_inf... | Use random.choices when available for better performance | Use random.choices when available for better performance
| Python | mit | joke2k/faker,joke2k/faker,danhuss/faker |
4e0db2766a719a347cbdf5b3e2fadd5a807d4a83 | tests/ipy_test_runner.py | tests/ipy_test_runner.py | from __future__ import print_function
import os
import pytest
HERE = os.path.dirname(__file__)
if __name__ == '__main__':
# Fake Rhino modules
pytest.load_fake_module('Rhino')
pytest.load_fake_module('Rhino.Geometry', fake_types=['RTree', 'Sphere', 'Point3d'])
pytest.run(HERE, ['tests/compas/files/... | from __future__ import print_function
import os
import pytest
HERE = os.path.dirname(__file__)
if __name__ == '__main__':
# Fake Rhino modules
pytest.load_fake_module('Rhino')
pytest.load_fake_module('Rhino.Geometry', fake_types=['RTree', 'Sphere', 'Point3d'])
pytest.run(HERE)
| Remove deleted test from ignore list | Remove deleted test from ignore list
| Python | mit | compas-dev/compas |
6290b81234f92073262a3fa784ae4e94f16192a8 | tests/test_autoconfig.py | tests/test_autoconfig.py | # coding: utf-8
import os
import pytest
from mock import patch
from decouple import AutoConfig
def test_autoconfig_env():
config = AutoConfig()
path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project')
with patch.object(config, '_caller_path', return_value=path):
assert 'ENV' ... | # coding: utf-8
import os
import pytest
from mock import patch
from decouple import AutoConfig
def test_autoconfig_env():
config = AutoConfig()
path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project')
with patch.object(config, '_caller_path', return_value=path):
assert 'ENV' ... | Test we have access to envvar when we have no file | Test we have access to envvar when we have no file
| Python | mit | henriquebastos/python-decouple,flaviohenriqu/python-decouple,mrkschan/python-decouple,henriquebastos/django-decouple,liukaijv/python-decouple |
d976bc3b992811911e5b28cf29df1df936ca7cc5 | localtv/subsite/__init__.py | localtv/subsite/__init__.py | from django.conf import settings
from django.contrib.sites.models import Site
from localtv import models
def context_processor(request):
sitelocation = models.SiteLocation.objects.get(
site=Site.objects.get_current())
display_submit_button = sitelocation.display_submit_button
if display_subm... | import urlparse
from django.conf import settings
from django.contrib.sites.models import Site
from localtv import models
class FixAJAXMiddleware:
"""
Firefox doesn't handle redirects in XMLHttpRequests correctly (it doesn't
set X-Requested-With) so we fake it with a GET argument.
"""
def process_... | Add a middleware class to fix Firefox's bad AJAX redirect handling | Add a middleware class to fix Firefox's bad AJAX redirect handling
| Python | agpl-3.0 | pculture/mirocommunity,natea/Miro-Community,pculture/mirocommunity,natea/Miro-Community,pculture/mirocommunity,pculture/mirocommunity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.