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 |
|---|---|---|---|---|---|---|---|---|---|
1e7e103799661acfd2cd492febbcc0ef537215e1 | bazaar/warehouse/views.py | bazaar/warehouse/views.py | from __future__ import unicode_literals
from django.core.urlresolvers import reverse_lazy
from django.views.generic import FormView
from braces.views import LoginRequiredMixin
from ..mixins import BazaarPrefixMixin
from . import api
from .forms import MovementForm
class MovementMixin(LoginRequiredMixin, BazaarPref... | from __future__ import unicode_literals
from django.core.urlresolvers import reverse_lazy
from django.views.generic import FormView
from braces.views import LoginRequiredMixin
from ..mixins import BazaarPrefixMixin
from . import api
from .forms import MovementForm
class MovementMixin(LoginRequiredMixin, BazaarPref... | Fix of dummymovement form to use product.move instead of api.move | Fix of dummymovement form to use product.move instead of api.move
| Python | bsd-2-clause | meghabhoj/NEWBAZAAR,evonove/django-bazaar,evonove/django-bazaar,meghabhoj/NEWBAZAAR,meghabhoj/NEWBAZAAR,evonove/django-bazaar |
9cffd831aaf1aff1dd3f655c4336c57831fef700 | nomadblog/urls.py | nomadblog/urls.py | from django.conf.urls.defaults import patterns, url
from nomadblog.views import PostList
urlpatterns = patterns('nomadblog.views',
# List blog posts
url('^$', PostList.as_view(), name='list_posts'),
# Show single post, category + slug based URL
url(
regex=r'^(?P<category_slug>[-\w]+)/(?P<post_... | from django.conf.urls import patterns, include, url
from nomadblog.views import PostList
urlpatterns = patterns(
'nomadblog.views',
url('^$', PostList.as_view(), name='list_posts'),
url(regex=r'^(?P<category_slug>[-\w]+)/(?P<post_slug>[-\w]+)/$', view='show_post', name='show_post'),
url(regex=r'^categ... | Fix ImportError: No module named defaults (dj 1.6) | Fix ImportError: No module named defaults (dj 1.6)
| Python | bsd-3-clause | Nomadblue/django-nomad-blog,Nomadblue/django-nomad-blog |
301593cbbd25e8cfce3998450f4954ce0610f23e | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='python-ev3',
version='0.1',
description='Python library of Lego EV3',
author='Gong Yi',
author_email='topikachu@163.com',
url='https://github.com/topikachu/python-ev3',
packages=['ev3', 'ev3.rawdevice'],
) | #!/usr/bin/env python
from distutils.core import setup
setup(name='python-ev3',
version='0.1',
description='Python library of Lego EV3',
author='Gong Yi',
author_email='topikachu@163.com',
url='https://github.com/topikachu/python-ev3',
packages=['ev3', 'ev3.rawdevice', 'ev3.motor',... | Update list of packages to install. | Update list of packages to install.
| Python | apache-2.0 | MaxNoe/python-ev3,topikachu/python-ev3,evz/python-ev3,MaxNoe/python-ev3,topikachu/python-ev3,evz/python-ev3 |
3fc109a396ccbdf1f9b26a0cf89e2a92d3f87fb0 | setup.py | setup.py | #!/usr/bin/env python
"""
setup.py file for afnumpy
"""
from distutils.core import setup
from afnumpy import __version__
setup (name = 'afnumpy',
version = __version__,
author = "Filipe Maia",
author_email = "filipe.c.maia@gmail.com",
url = 'https://github.com/FilipeMaia/afnumpy',
... | #!/usr/bin/env python
"""
setup.py file for afnumpy
"""
from distutils.core import setup
from afnumpy import __version__
setup (name = 'afnumpy',
version = __version__,
author = "Filipe Maia",
author_email = "filipe.c.maia@gmail.com",
url = 'https://github.com/FilipeMaia/afnumpy',
... | Correct again the pip URL | Correct again the pip URL
| Python | bsd-2-clause | FilipeMaia/afnumpy,daurer/afnumpy |
719037cf20ae17e5fba71136cad1db7e8a47f703 | spacy/lang/fi/examples.py | spacy/lang/fi/examples.py | # coding: utf8
from __future__ import unicode_literals
"""
Example sentences to test spaCy and its language models.
>>> from spacy.lang.tr.examples import sentences
>>> docs = nlp.pipe(sentences)
"""
sentences = [
"Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla."
"Itseajavat autot siirtäv... | # coding: utf8
from __future__ import unicode_literals
"""
Example sentences to test spaCy and its language models.
>>> from spacy.lang.fi.examples import sentences
>>> docs = nlp.pipe(sentences)
"""
sentences = [
"Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla.",
"Itseajavat auto... | Update formatting and add missing commas | Update formatting and add missing commas | Python | mit | recognai/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spa... |
754d1a18da471e10937dad90478cd8368b20f4c5 | tests/test_sqlite.py | tests/test_sqlite.py | # This is an example test settings file for use with the Django test suite.
#
# The 'sqlite3' backend requires only the ENGINE setting (an in-
# memory database will be used). All other backends will require a
# NAME and potentially authentication information. See the
# following section in the docs for more informatio... | # This is an example test settings file for use with the Django test suite.
#
# The 'sqlite3' backend requires only the ENGINE setting (an in-
# memory database will be used). All other backends will require a
# NAME and potentially authentication information. See the
# following section in the docs for more informatio... | Use the old django test runner | Use the old django test runner
We aren't ready to switch to the new unittest discovery in django.
| Python | apache-2.0 | j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy |
569840b37f9e43bec0de3f6ddadc89d6a2f9e17b | traceview/formatters.py | traceview/formatters.py | # -*- coding: utf-8 -*-
"""
traceview.formatters
This module contains functions used to format TraceView API results.
"""
from collections import namedtuple
def identity(results):
return results
def tuplify(results, class_name='Result'):
if 'fields' in results and 'items' in results:
return _tup... | # -*- coding: utf-8 -*-
"""
traceview.formatters
This module contains functions used to format TraceView API results.
"""
from collections import namedtuple
def identity(results):
return results
def tuplify(results, class_name='Result'):
if 'fields' in results and 'items' in results:
return _tup... | Replace map with a list comprehension. | Replace map with a list comprehension.
| Python | mit | danriti/python-traceview |
5a307c9ed6ad00c6df40f505caa9a8dfb432892d | utils.py | utils.py | import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if not have_appserver:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
app... | import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if not have_appserver:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
app... | Tweak the way that on_production_server is determined | Tweak the way that on_production_server is determined
| Python | bsd-3-clause | potatolondon/djangoappengine-1-4,potatolondon/djangoappengine-1-4 |
6da3b2a09914546bbc29caa9f807e05f0ee66b0d | cybox/objects/port_object.py | cybox/objects/port_object.py | # Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import cybox.utils as utils
import cybox.bindings.port_object as port_binding
from cybox.common import ObjectProperties, String, PositiveInteger
class Port(ObjectProperties):
_namespace = 'http://cybox.mitre.o... | # Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import cybox
import cybox.bindings.port_object as port_binding
from cybox.common import ObjectProperties, String, PositiveInteger
class Port(ObjectProperties):
_binding = port_binding
_binding_class = port... | Convert Port object to simpler representation | Convert Port object to simpler representation
| Python | bsd-3-clause | CybOXProject/python-cybox |
b479fbcbd6aa620d060ea626bd0f0097ec04cf79 | plugins/libs/request.py | plugins/libs/request.py | import urllib
import json
import logging
def quote(text):
try:
return urllib.quote(text.encode('utf-8'))
except UnicodeDecodeError:
return urllib.quote(unicode(text, 'utf-8').encode('utf-8'))
def quote_plus(text):
try:
return urllib.quote_plus(text.encode('utf-8'))
except Uni... | import urllib
import json
import logging
def quote(text):
try:
return urllib.quote(text.encode('utf-8'))
except UnicodeDecodeError:
return urllib.quote(unicode(text, 'utf-8').encode('utf-8'))
def quote_plus(text):
try:
return urllib.quote_plus(text.encode('utf-8'))
except Uni... | Fix crash when invalid json is returned | Fix crash when invalid json is returned
| Python | apache-2.0 | numixproject/numibot,IamRafy/numibot |
e0119a582ceb6a55123e8d16ccf33a0d52f7a0a9 | server/app/handlers.py | server/app/handlers.py | import os
import aiohttp
import json
from aiohttp import web
from .consts import KUDAGO_API_BASE_URL, CLIENT_DIR
async def serve_api(request):
url = '{}/{}/?{}'.format(
KUDAGO_API_BASE_URL,
request.match_info['path'],
request.query_string,
)
response = await aiohttp.get(url)
b... | import os
import aiohttp
import json
from aiohttp import web
from .consts import KUDAGO_API_BASE_URL, CLIENT_DIR
async def serve_api(request):
url = '{}/{}/?{}'.format(
KUDAGO_API_BASE_URL,
request.match_info['path'],
request.query_string,
)
response = await aiohttp.get(url)
b... | Return unicode from the server | Return unicode from the server
Fixes #18
| Python | mit | despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics |
cc2a600a7a68e438aa1dceb43f40c7ccd61b5df9 | apps/innovate/views.py | apps/innovate/views.py | import jingo
from innovate.utils import get_blog_feed_entries
from projects.models import Project
def splash(request):
"""Display splash page. With featured projects and news feed."""
projects = Project.objects.filter(featured=True, inactive=False)[:4]
return jingo.render(request, 'innovate/splash.html',... | import jingo
from innovate.utils import get_blog_feed_entries
from projects.models import Project
def splash(request):
"""Display splash page. With featured projects and news feed."""
# refresh cache if requested
force = request.META.get('HTTP_CACHE_CONTROL') == 'no-cache'
entries = get_blog_feed_ent... | Add shift-refresh to update HP cache on demand. | Add shift-refresh to update HP cache on demand.
| Python | bsd-3-clause | mozilla/betafarm,mozilla/betafarm,mozilla/betafarm,mozilla/betafarm |
f4691dd72c46fdc1a42f454ceec82128be33e907 | twstock/cli/__init__.py | twstock/cli/__init__.py | # -*- coding: utf-8 -*-
import argparse
from twstock.codes import __update_codes
from twstock.cli import best_four_point
from twstock.cli import stock
from twstock.cli import realtime
def run():
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bfp', nargs='+')
parser.add_argument('-s', '-... | # -*- coding: utf-8 -*-
65;5403;1c
import argparse
from twstock.codes import __update_codes
from twstock.cli import best_four_point
from twstock.cli import stock
from twstock.cli import realtime
def run():
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bfp', nargs='+')
parser.add_argumen... | Add help message to cli tool | Add help message to cli tool
| Python | mit | mlouielu/twstock,TCCinTaiwan/twstock |
252ffda53d494403133fdb1986c92422264406d8 | tests_app/tests/unit/serializers/models.py | tests_app/tests/unit/serializers/models.py | # -*- coding: utf-8 -*-
import os
from django.db import models
from django.conf import settings
class UserModel(models.Model):
name = models.CharField(max_length=20)
upload_to = os.path.join(settings.FILE_STORAGE_DIR, 'test_serializers')
class CommentModel(models.Model):
user = models.ForeignKey(
... | # -*- coding: utf-8 -*-
import os
from django.db import models
from django.conf import settings
class UserModel(models.Model):
name = models.CharField(max_length=20)
upload_to = os.path.join(settings.FILE_STORAGE_DIR, 'test_serializers')
class CommentModel(models.Model):
user = models.ForeignKey(
... | Fix CommentModel m2m null warning | Fix CommentModel m2m null warning
| Python | mit | chibisov/drf-extensions |
b2c32ac006ac62957f56c2cad90615a8f349cb8e | scanpointgenerator/point.py | scanpointgenerator/point.py | class Point(object):
"""Contains information about for each scan point
Attributes:
positions (dict): Dict of str position_name -> float position for each
scannable dimension. E.g. {"x": 0.1, "y": 2.2}
lower (dict): Dict of str position_name -> float lower_bound for each
... | from collections import OrderedDict
class Point(object):
"""Contains information about for each scan point
Attributes:
positions (dict): Dict of str position_name -> float position for each
scannable dimension. E.g. {"x": 0.1, "y": 2.2}
lower (dict): Dict of str position_name -> f... | Refactor Point to use OrderedDict for positions, upper and lower | Refactor Point to use OrderedDict for positions, upper and lower
| Python | apache-2.0 | dls-controls/scanpointgenerator |
a560868cd6658a4a5134ce8d53a03a5f86d92d6d | dimensionful/common_units.py | dimensionful/common_units.py | """
Define some common units, so users can import the objects directly.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
from sympy.core import Integer
from dimensionful.dimensions import *
from dimensionful.units import Unit, unit_symbols_dict
# cgs base units
g = Unit("g")
cm = Unit("c... | """
Define some common units, so users can import the objects directly.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
from dimensionful.dimensions import *
from dimensionful.units import Unit
# cgs base units
g = Unit("g")
cm = Unit("cm")
s = Unit("s")
K = Unit("K")
# other cgs
dyne... | Remove imports we don't need anymore. | Remove imports we don't need anymore. | Python | bsd-2-clause | caseywstark/dimensionful |
e9c45c30203a3b100ab897dd2337985790b07dff | autoload/tsurf/core.py | autoload/tsurf/core.py | # -*- coding: utf-8 -*-
"""
tsurf.core
~~~~~~~~~~
This module defines the TagSurfer class. This class serve two purpose:
1) Defines the methods that are used by tsurf-owned vim commands.
2) Creates all tsurf components and acts as a brigde among them.
"""
import vim
from tsurf import ui
from tsurf import finde... | # -*- coding: utf-8 -*-
"""
tsurf.core
~~~~~~~~~~
This module defines the TagSurfer class. This class serve two purpose:
1) Defines the methods that are used by tsurf-owned vim commands.
2) Creates all tsurf components and acts as a brigde among them.
"""
import os
import vim
from tsurf import ui
from tsurf im... | Improve usability of the command "TsurfSetRoot" | Improve usability of the command "TsurfSetRoot"
| Python | mit | bossmido/tag-surfer,bossmido/tag-surfer,bossmido/tag-surfer |
a2ad75b8dac515d1bbc49c32257c62a7da59e2e1 | semantic_release/helpers.py | semantic_release/helpers.py | import configparser
import semver
from invoke import run
def get_current_version():
return run('python setup.py --version', hide=True).stdout.strip()
def evaluate_version_bump(force=None):
if force:
return force
return 'patch'
def get_new_version(current_version, level_bump):
return getatt... | import configparser
import os
import re
import semver
from invoke import run
def get_current_version():
return run('python setup.py --version', hide=True).stdout.strip()
def evaluate_version_bump(force=None):
if force:
return force
return 'patch'
def get_new_version(current_version, level_bump... | Implement setting of new version | :sparkles: Implement setting of new version
| Python | mit | riddlesio/python-semantic-release,relekang/python-semantic-release,relekang/python-semantic-release,wlonk/python-semantic-release,jvrsantacruz/python-semantic-release |
25ff50839e50a46b4e973acf0a6ae28472a71473 | wait-for-statuses.py | wait-for-statuses.py | import urllib.request
import json
import subprocess
import time
import os
# We're limited to this number by GH Actions API
# https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run
max_jobs=100
status_url = "https://api.github.com/repos/" \
+ os.environ['GITHUB_REP... | import urllib.request
import json
import subprocess
import time
import os
import sys
# We're limited to this number by GH Actions API
# https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run
max_jobs=100
status_url = "https://api.github.com/repos/" \
+ os.environ[... | Return an error when number of jobs exceeds max_jobs | Return an error when number of jobs exceeds max_jobs
ghactions API call we're using limits number of jobs
returned in one call. If jobs exceed this number they are
grouped into "pages". Page handling code shall be added
when we exceed this number.
| Python | apache-2.0 | litex-hub/litex-conda-ci,litex-hub/litex-conda-ci |
18e1e0a1c1b4492e623d5b86d7a23fff00d5fa72 | pysingcells/__main__.py | pysingcells/__main__.py | #!/usr/bin/env python3
# std import
import os
import sys
import configparser
from subprocess import call
# project import
from . import logger
from .mapper import hisat2
def main(config_path):
""" Main function of pro'gramme read configuration and run enable step """
config = configparser.ConfigParser()
... | #!/usr/bin/env python3
# std import
import os
import sys
import configparser
from subprocess import call
# project import
from . import logger
from .mapper import hisat2
def main(config_path):
""" Main function of pro'gramme read configuration and run enable step """
config = configparser.ConfigParser()
... | Add test of hisat2 object | Add test of hisat2 object
| Python | mit | Fougere87/pysingcells |
b67ee17b401df9dec4f76f1a24cef2a7ce25406b | 1-moderate/locks/main.py | 1-moderate/locks/main.py | import sys
def do_lock_pass(locked):
for i in xrange(0, len(locked), 2):
locked[i] = True
def do_flip_pass(locked):
for i in xrange(0, len(locked), 3):
locked[i] = not locked[i]
def count_unlocked(locked):
result = 0
for l in locked:
if not l: result += 1
return result
de... | import sys
def do_lock_pass(locked):
for i in xrange(1, len(locked), 2):
locked[i] = True
def do_flip_pass(locked):
for i in xrange(2, len(locked), 3):
locked[i] = not locked[i]
def count_unlocked(locked):
result = 0
for l in locked:
if not l: result += 1
return result
de... | Fix solution to the locks problem. | Fix solution to the locks problem.
| Python | unlicense | mpillar/codeeval,mpillar/codeeval,mpillar/codeeval,mpillar/codeeval |
b5852d1b579325b5ef5d8d7aebca53f1fb9bae04 | pyads/utils.py | pyads/utils.py | # -*- coding: utf-8 -*-
"""Utility functions.
:author: Stefan Lehmann <stlm@posteo.de>
:license: MIT, see license file or https://opensource.org/licenses/MIT
:created on: 2018-06-11 18:15:53
:last modified by: Stefan Lehmann
:last modified time: 2018-07-12 14:11:12
"""
import sys
from ctypes import c_ubyte
def pla... | # -*- coding: utf-8 -*-
"""Utility functions.
:author: Stefan Lehmann <stlm@posteo.de>
:license: MIT, see license file or https://opensource.org/licenses/MIT
:created on: 2018-06-11 18:15:53
:last modified by: Stefan Lehmann
:last modified time: 2018-07-12 14:11:12
"""
import sys
from ctypes import c_ubyte
def pla... | Add 'cli' as being a platform recognized as a Windows platform. | Add 'cli' as being a platform recognized as a Windows platform.
This will be the case when using e.g. IronPython (.NET).
| Python | mit | MrLeeh/pyads |
952289a08784bc0ee86dee6239025397395f7033 | tests/conftest.py | tests/conftest.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Contains pytest fixtures which are globally available throughout the suite.
"""
import pytest
@pytest.fixture
def foobar():
pass
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
conftest
--------
Contains pytest fixtures which are globally available throughout the suite.
"""
import pytest
@pytest.fixture
def foobar():
pass
| Change doc str to sphinx format | Change doc str to sphinx format
| Python | bsd-3-clause | sp1rs/cookiecutter,vincentbernat/cookiecutter,cguardia/cookiecutter,willingc/cookiecutter,drgarcia1986/cookiecutter,kkujawinski/cookiecutter,drgarcia1986/cookiecutter,michaeljoseph/cookiecutter,ionelmc/cookiecutter,audreyr/cookiecutter,takeflight/cookiecutter,dajose/cookiecutter,letolab/cookiecutter,jhermann/cookiecutt... |
725f5b12c43380e239d6a511a9435577dda37b49 | astropy/utils/compat/_subprocess_py2/__init__.py | astropy/utils/compat/_subprocess_py2/__init__.py | from __future__ import absolute_import
from subprocess import *
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte
string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the... | from __future__ import absolute_import
from subprocess import *
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte
string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the... | Fix subprocess on Python 2.6 | Fix subprocess on Python 2.6
| Python | bsd-3-clause | bsipocz/astropy,kelle/astropy,lpsinger/astropy,MSeifert04/astropy,AustereCuriosity/astropy,AustereCuriosity/astropy,joergdietrich/astropy,mhvk/astropy,DougBurke/astropy,astropy/astropy,joergdietrich/astropy,StuartLittlefair/astropy,tbabej/astropy,kelle/astropy,stargaser/astropy,funbaker/astropy,AustereCuriosity/astropy... |
098044c80fff2ff639da088f87f7fc6952813fc1 | txircd/channel.py | txircd/channel.py | from txircd.utils import CaseInsensitiveDictionary, now()
class IRCChannel(object):
def __init__(self, ircd, name):
self.ircd = ircd
self.name = name
self.created = now()
self.topic = ""
self.topicSetter = ""
self.topicTime = now()
self.mode = {}
self.users = CaseInsensitiveDictionary()
self.metadat... | from txircd.utils import CaseInsensitiveDictionary, now()
class IRCChannel(object):
def __init__(self, ircd, name):
self.ircd = ircd
self.name = name
self.created = now()
self.topic = ""
self.topicSetter = ""
self.topicTime = now()
self.mode = {}
self.users = CaseInsensitiveDictionary()
self.metadat... | Change how mode strings are constructed | Change how mode strings are constructed
| Python | bsd-3-clause | DesertBus/txircd,Heufneutje/txircd,ElementalAlchemist/txircd |
749aa35a85b6482cfba9dec7d37473a787d73c32 | integration-test/1106-merge-ocean-earth.py | integration-test/1106-merge-ocean-earth.py | # There should be a single (merged) ocean feature in this tile
assert_less_than_n_features(9, 167, 186, 'water', {'kind': 'ocean'}, 2)
# There should be a single (merged) earth feature in this tile
assert_less_than_n_features(9, 170, 186, 'earth', {'kind': 'earth'}, 2)
| # There should be a single, merged feature in each of these tiles
# Natural Earth
assert_less_than_n_features(5, 11, 11, 'water', {'kind': 'ocean'}, 2)
assert_less_than_n_features(5, 8, 11, 'earth', {'kind': 'earth'}, 2)
# OpenStreetMap
assert_less_than_n_features(9, 167, 186, 'water', {'kind': 'ocean'}, 2)
assert_le... | Add lowzoom tests for polygon merging | Add lowzoom tests for polygon merging
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource |
7812934504c299464227c4f8cd28cacc2b904008 | test/run_tests.py | test/run_tests.py | import platform
from unittest import main
from test_net_use_table import *
from test_sanitize import *
from test_utils import *
from test_unc_directory import *
if platform.system() == 'Windows':
print 'Including Windows-specific tests'
from test_connecting import *
else:
print 'WARNING: Excluding Wi... | import platform
from unittest import main
from test_net_use_table import *
from test_sanitize import *
from test_utils import *
from test_unc_directory import *
if platform.system() == 'Windows':
print 'Including Windows-specific tests'
from test_connecting import *
else:
print 'WARNING: Exc... | Use spaces instead of tabs | Use spaces instead of tabs
| Python | mit | nithinphilips/py_win_unc,CovenantEyes/py_win_unc |
6cd640eb09d674afaff1c96e69322705a843dde9 | src/commands/user/user.py | src/commands/user/user.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User command...
"""
import grp
class User(object):
"""Something, something, something darkside...."""
def __init__(self, settingsInstance, commandInstance, cmdName, *args):
super(User, self).__init__()
self.settingsInstance = settingsInstanc... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User command...
"""
import grp
class User(object):
"""Something, something, something darkside...."""
def __init__(self, settingsInstance, commandInstance, cmdName, *args):
super(User, self).__init__()
self.settingsInstance = settingsInstanc... | Test if you can return the channel. | Test if you can return the channel.
| Python | bsd-3-clause | Tehnix/PyIRCb |
030265cc2dca23e256bdce59b2bd0cb77e88ca74 | InvenTree/stock/forms.py | InvenTree/stock/forms.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from InvenTree.forms import HelperForm
from .models import StockLocation, StockItem
class EditStockLocationForm(HelperForm):
class Meta:
model = StockLocation
fields = [
'name',
'par... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from InvenTree.forms import HelperForm
from .models import StockLocation, StockItem
class EditStockLocationForm(HelperForm):
class Meta:
model = StockLocation
fields = [
'name',
'par... | Allow editing of 'notes' field when creating new StockItem | Allow editing of 'notes' field when creating new StockItem
| Python | mit | SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree |
ec3a70e038efc565ce88294caf0e78d5efaa9a85 | djangocms_picture/cms_plugins.py | djangocms_picture/cms_plugins.py | from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/pi... | from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/pi... | Modify the picture plugin slightly | Modify the picture plugin slightly
| Python | mit | okfn/foundation,okfn/website,okfn/website,okfn/foundation,MjAbuz/foundation,MjAbuz/foundation,okfn/website,okfn/foundation,MjAbuz/foundation,okfn/foundation,okfn/website,MjAbuz/foundation |
2fda06e11c9b536a5771d5b7f4fb31e5c20223a0 | run_jstests.py | run_jstests.py | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs DomDistillers jstests.
This uses ChromeDriver (https://sites.google.com/a/chromium.org/chromedriver/) to run the jstests.
This... | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs DomDistillers jstests.
This uses ChromeDriver (https://sites.google.com/a/chromium.org/chromedriver/) to run the jstests.
This... | Fix printing of logged non-ascii characters | Fix printing of logged non-ascii characters
webdriver seems to not handle non-ascii characters in the result of an
executed script correctly (python throws an exception when printing the
string). This makes them be printed correctly.
R=mdjones@chromium.org
Review URL: https://codereview.chromium.org/848503003
| Python | apache-2.0 | dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller |
4fa40ddbe6eacb33a97eb18719aa7ae61d8c9218 | s3_url_sign.py | s3_url_sign.py | import boto.s3.connection
import optparse
def main():
parser = optparse.OptionParser(
usage='%prog BUCKET [KEY]',
)
parser.add_option(
'--method',
default='GET',
help='HTTP method to use [default: %default]',
)
parser.add_option(
'--expiry',
t... | import boto.s3.connection
import optparse
def main():
parser = optparse.OptionParser(
usage='%prog BUCKET [KEY]',
)
parser.add_option(
'--method',
default='GET',
help='HTTP method to use [default: %default]',
)
parser.add_option(
'--expiry',
t... | Allow overriding host/port of S3 service to connect to. | Allow overriding host/port of S3 service to connect to.
Hardcode non-vhost calling convention, at least for now.
(The host name overriding typically doesn't work with vhosts;
"BUCKET.localhost" is not very helpful.)
To use a local S3-compatible service, put something like
this in ~/.boto:
[Boto]
s3_host = localhos... | Python | mit | tv42/s3-url-sign,tv42/s3-url-sign |
25c0558b0c75306c8d9c547668df9cef25bae786 | symbolset.py | symbolset.py | class SymbolSet():
def __init__(self):
self._address_labels = dict()
self._label_addresses = dict()
self._generic_id = 0
def load(self, config_path):
pass
def add_label(self, address, label):
if address in self._address_labels:
raise TargetRel... | class SymbolSet():
def __init__(self):
self._address_labels = dict()
self._label_addresses = dict()
self._generic_id = 0
def add_label(self, address, label):
if address in self._address_labels:
raise TargetRelabelException("{:#04X} has already been given the ... | Remove redundant load() method from SymbolSet. | Remove redundant load() method from SymbolSet.
| Python | mit | achan1989/diSMB |
322ecf060500e43a05c604be62edefcec48efd5a | bh_sshcmd.py | bh_sshcmd.py | #!/usr/bin/env python
#Black Hat Python; SSH w/ Paramiko (p 26)
import threading, paramiko, subprocess
def banner():
print "############ n1cFury- NetCat tool #################"
print "############ courtesy of Black Hat Python ###########"
print ""
def usage():
print "./bh_sshcmd.py <hostname> <u... | #!/usr/bin/env python
#Black Hat Python; SSH w/ Paramiko (p 26)
import threading, paramiko, subprocess
host = sys.argv[1]
user = sys.argv[2]
passwd = sys.argv[3]
command = sys.argv[4]
def banner():
print ""
print "############ n1cFury- SSH Client #################"
print ""
def usage():
print "./bh_ss... | DEBUG AND MAKE SURE FUNCTIONS WORK | TODO: DEBUG AND MAKE SURE FUNCTIONS WORK
| Python | mit | n1cfury/BlackHatPython |
8671a368cff459d5a00c5b43d330d084e2f6ed3d | numpy/_array_api/_types.py | numpy/_array_api/_types.py | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', '... | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', '... | Use the array API types for the array API type annotations | Use the array API types for the array API type annotations
| Python | bsd-3-clause | numpy/numpy,mattip/numpy,charris/numpy,simongibbons/numpy,seberg/numpy,charris/numpy,anntzer/numpy,simongibbons/numpy,jakirkham/numpy,numpy/numpy,jakirkham/numpy,endolith/numpy,simongibbons/numpy,jakirkham/numpy,pdebuyl/numpy,rgommers/numpy,seberg/numpy,anntzer/numpy,endolith/numpy,mattip/numpy,numpy/numpy,seberg/numpy... |
11543deda3222965ee95adc4ea6db5cdec21ac94 | admin_tests/factories.py | admin_tests/factories.py | import factory
from admin.common_auth.models import MyUser
class UserFactory(factory.Factory):
class Meta:
model = MyUser
id = 123
email = 'cello@email.org'
first_name = 'Yo-yo'
last_name = 'Ma'
osf_id = 'abc12'
@classmethod
def is_in_group(cls, value):
return True
| import factory
from admin.common_auth.models import AdminProfile
from osf_tests.factories import UserFactory as OSFUserFactory
class UserFactory(factory.Factory):
class Meta:
model = AdminProfile
user = OSFUserFactory
desk_token = 'el-p'
test_token_secret = 'mike'
@classmethod
def ... | Fix up admin user factory to reflect model changes | Fix up admin user factory to reflect model changes
| Python | apache-2.0 | alexschiller/osf.io,HalcyonChimera/osf.io,felliott/osf.io,baylee-d/osf.io,mattclark/osf.io,erinspace/osf.io,alexschiller/osf.io,alexschiller/osf.io,leb2dg/osf.io,chrisseto/osf.io,chennan47/osf.io,cslzchen/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,acshi/osf.io,caseyrollins/osf.io,aaxelb/osf.io,icereval/osf.io,h... |
1f3730ac4d531ca0d582a8b8bded871acb409847 | backend/api-server/warehaus_api/events/models.py | backend/api-server/warehaus_api/events/models.py | from .. import db
class Event(db.Model):
timestamp = db.Field()
obj_id = db.Field() # The object for which this event was created about
user_id = db.Field() # The user who performed the action
# A list of IDs which are interested in this event. For example, when creating
# a server we obvious... | from .. import db
class Event(db.Model):
timestamp = db.Field()
obj_id = db.Field() # The object for which this event was created about
user_id = db.Field() # The user who performed the action
# A list of IDs which are interested in this event. For example, when creating
# a server we obvious... | Fix api-server events not saving the user ID | Fix api-server events not saving the user ID
| Python | agpl-3.0 | labsome/labsome,warehaus/warehaus,warehaus/warehaus,labsome/labsome,warehaus/warehaus,labsome/labsome |
4602b19c1bd827c40ddc190c177b71b8922a39f6 | IndexedRedis/fields/raw.py | IndexedRedis/fields/raw.py | # Copyright (c) 2014, 2015, 2016 Timothy Savannah under LGPL version 2.1. See LICENSE for more information.
#
# fields.compressed - Some types and objects related to compressed fields. Use in place of IRField ( in FIELDS array to activate functionality )
#
# vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab :
fro... | # Copyright (c) 2014, 2015, 2016 Timothy Savannah under LGPL version 2.1. See LICENSE for more information.
#
# fields.raw - Raw field, no encoding or decoding will occur.
#
# vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab :
from . import IRField
class IRRawField(IRField):
'''
IRRawField - Return the raw d... | Fix wrong comment in module | Fix wrong comment in module
| Python | lgpl-2.1 | kata198/indexedredis,kata198/indexedredis |
0a04143c94540d864a288e5c79ade4ba9bf31e37 | src/test/stresstest.py | src/test/stresstest.py | #!/usr/bin/env python
# Copyright 2007 Albert Strasheim <fullung@gmail.com>
#
# 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 requ... | #!/usr/bin/env python
# Copyright 2007 Albert Strasheim <fullung@gmail.com>
#
# 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 requ... | Test everything with stress test. | Test everything with stress test.
| Python | apache-2.0 | aberzan/pyactivemq,WilliamFF/pyactivemq,alberts/pyactivemq,cl2dlope/pyactivemq,aberzan/pyactivemq,winking324/pyactivemq,hetian9288/pyactivemq,winking324/pyactivemq,chenrui333/pyactivemq,cleardo/pyactivemq,haofree/pyactivemq,alberts/pyactivemq,hetian9288/pyactivemq,haofree/pyactivemq,cl2dlope/pyactivemq,WilliamFF/pyacti... |
774a57478d93663968c0ed0e9407785f618b6eae | stackdio/core/middleware.py | stackdio/core/middleware.py | class JSONIndentAcceptHeaderMiddleware(object):
def process_request(self, request):
request.META['HTTP_ACCEPT'] = 'application/json; indent=4'
return None
| class JSONIndentAcceptHeaderMiddleware(object):
def process_request(self, request):
if request.META.get('HTTP_ACCEPT') == 'application/json':
request.META['HTTP_ACCEPT'] = 'application/json; indent=4'
return None
| Apply indenting to only requests that specify application/json accept headers | PI-248: Apply indenting to only requests that specify application/json accept
headers
| Python | apache-2.0 | clarkperkins/stackdio,stackdio/stackdio,stackdio/stackdio,clarkperkins/stackdio,clarkperkins/stackdio,stackdio/stackdio,stackdio/stackdio,clarkperkins/stackdio |
4460231b1abf053e8e2bb8581007ccb0e61cae50 | main.py | main.py | #!/usr/bin/env python3
# Standard imports
import argparse
import sys
import os.path
# Non-standard imports
import jinja2
import yaml
def main(args):
parser = argparse.ArgumentParser(description="Builds a CV using a YAML database.")
parser.add_argument("source", help="The YAML database to source from.")
p... | #!/usr/bin/env python3
# Standard imports
import argparse
import sys
import os.path
# Non-standard imports
import jinja2
import yaml
def filter_db(db, tags):
return db
def main(args):
parser = argparse.ArgumentParser(description="Builds a CV using a YAML database.")
parser.add_argument("source", help="T... | Tag filtering infrastructure up (currently stubbed). | Tag filtering infrastructure up (currently stubbed).
| Python | apache-2.0 | proaralyst/cvgen |
7c805eecc90ead4e412e091c2500e881f47dd383 | test/tests/__init__.py | test/tests/__init__.py | #
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2... | #
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2... | Remove tests from __all__ which are no longere here. | Remove tests from __all__ which are no longere here.
git-svn-id: fc68d25ef6d4ed42045cee93f23b6b1994a11c36@1122 5646265b-94b7-0310-9681-9501d24b2df7
| Python | mit | kirkeby/sheared |
52077ba667efcf596c9186dbbd8d7cedc95d624d | tests/document_test.py | tests/document_test.py | from document import Document
import unittest
class TestDocument(unittest.TestCase):
def _get_document(self):
spec = {
"author": "John Humphreys",
"content": {
"title": "How to make cookies",
"text": "First start by pre-heating the oven..."
... | from document import Document
import unittest
class TestDocument(unittest.TestCase):
def _get_document(self):
spec = {
"author": "John Humphreys",
"content": {
"title": "How to make cookies",
"text": "First start by pre-heating the oven..."
... | Test blank keys are not allowed. | Test blank keys are not allowed.
| Python | mit | gamechanger/schemer,gamechanger/mongothon |
f1496f7f5babdf1f9fa8f527f42442aeccab46d7 | tests/test_location.py | tests/test_location.py | from SUASSystem import *
import math
import numpy
import unittest
from dronekit import LocationGlobalRelative
class locationTestCase(unittest.TestCase):
def setUp(self):
self.position = Location(5, 12, 20)
def test_get_lat(self):
self.assertEquals(5, self.position.get_lat())
| from SUASSystem import *
import math
import numpy
import unittest
from dronekit import LocationGlobalRelative
class locationTestCase(unittest.TestCase):
def setUp(self):
self.position = Location(5, 12, 20)
def test_get_lat(self):
self.assertEquals(5, self.position.get_lat())
def test_get... | Add finished working location unit tests | Add finished working location unit tests
| Python | mit | FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition |
236c37e39d1c3821b60e183845594195091acd3e | corehq/ex-submodules/pillow_retry/tasks.py | corehq/ex-submodules/pillow_retry/tasks.py | from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db.models import Count
from corehq.util.datadog.gauges import datadog_gauge
from pillow_retry.models import PillowError
@periodic_task(
run_every=crontab(minute="*/15"),
queue=settings.CELE... | from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db.models import Count
from corehq.util.datadog.gauges import datadog_gauge
from pillow_retry.models import PillowError
@periodic_task(
run_every=crontab(minute="*/15"),
queue=settings.CELE... | Revert "Send error-type info to pillow error DD metrics" | Revert "Send error-type info to pillow error DD metrics"
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
4b698854d3dc9a30b507716d839065011b1ac545 | addons/clinic_sale/__openerp__.py | addons/clinic_sale/__openerp__.py | # -*- coding: utf-8 -*-
{'active': False,
'author': 'Ingenieria ADHOC',
'category': 'Clinic',
'demo_xml': [],
'depends': ['clinic', 'sale_dummy_confirmation'],
'description': """
Clinic Sales
=============
""",
'init_xml': [],
'installable': True,
'license': 'AGPL-3',
'name': 'Clinic... | # -*- coding: utf-8 -*-
{'active': False,
'author': 'Ingenieria ADHOC',
'category': 'Clinic',
'demo_xml': [],
'depends': [
'clinic',
'sale_dummy_confirmation',
'l10n_ar_aeroo_sale',
],
'description': """
Clinic Sales
=============
""",
'init_xml': [],
'install... | ADD aeroo report to clinic sale | ADD aeroo report to clinic sale
| Python | agpl-3.0 | ingadhoc/odoo-clinic,ingadhoc/odoo-clinic,ingadhoc/odoo-clinic |
79a453f503e0f4283700071d415e32e82d35162b | eadred/management/commands/generatedata.py | eadred/management/commands/generatedata.py | import imp
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.importlib import import_module
from optparse import make_option
class Command(BaseCommand):
help = 'Generates sample data.'
option_list = BaseCommand.option_list + (
make_option('--with'... | import imp
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.importlib import import_module
from optparse import make_option
class Command(BaseCommand):
help = 'Generates sample data.'
option_list = BaseCommand.option_list + (
make_option('--with'... | Fix issue where options['param'] can be None. | Fix issue where options['param'] can be None.
| Python | bsd-3-clause | willkg/django-eadred |
5da7189f195d0daf9595c61f05156c85031ba0c5 | tests/testapp/tests/test_scheduling.py | tests/testapp/tests/test_scheduling.py | from django.test import TestCase
from testapp.tests import factories
class SchedulingTestCase(TestCase):
def test_scheduling(self):
for i in range(20):
factories.AssignmentFactory.create()
factories.WaitListFactory.create()
admin = factories.UserFactory.create(is_staff=Tr... | from django.test import TestCase
from zivinetz.models import Assignment
from testapp.tests import factories
class SchedulingTestCase(TestCase):
def test_scheduling(self):
for i in range(20):
factories.AssignmentFactory.create()
factories.WaitListFactory.create()
admin = ... | Test that scheduling does not crash | Test that scheduling does not crash
| Python | mit | matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz |
8e316a4b1305e8fb49e89b867b30bd27b428e689 | test/example/manage.py | test/example/manage.py | #!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to ... | #!/usr/bin/env python
from django.core.management import execute_manager
import sys
sys.path.insert(0, '../../')
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears yo... | Make the test suite use the development version of djqmethod. | Make the test suite use the development version of djqmethod.
| Python | unlicense | zacharyvoase/django-qmethod,fdemmer/django-qmethod |
0da1f02c0f6bb554a8a093bd4c597ebbe45e479b | tests/unit/test_objector.py | tests/unit/test_objector.py | from . import UnitTest
class TestObjector(UnitTest):
def test_objectify_returns_None_for_None(self):
assert self.reddit._objector.objectify(None) is None
| import pytest
from praw.exceptions import APIException, ClientException
from . import UnitTest
class TestObjector(UnitTest):
def test_objectify_returns_None_for_None(self):
assert self.reddit._objector.objectify(None) is None
def test_parse_error(self):
objector = self.reddit._objector
... | Add tests for `Objector.parse_error()` and `.check_error()` | Add tests for `Objector.parse_error()` and `.check_error()`
| Python | bsd-2-clause | praw-dev/praw,gschizas/praw,leviroth/praw,leviroth/praw,gschizas/praw,praw-dev/praw |
e66894584a3762af2db8ebdbc4269e6aee1bc24e | thesite/thesite/urls.py | thesite/thesite/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'', # First arg to patterns is a namespace parameter.
# A handful of views in a base app.
url(r'^$', 'base_app.views.site_index'),
url(r'^logout/$', 'base_app.views.logout'),
url(r'^creat... | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'', # First arg to patterns is a namespace parameter.
# A handful of views in a base app.
url(r'^$', 'base_app.views.site_index'),
url(r'^logout/$', 'base_app.views.logout'),
url(r'^creat... | Include views from the Django Optimizer | Include views from the Django Optimizer
| Python | apache-2.0 | petwitter/petwitter,petwitter/petwitter,petwitter/petwitter |
249367a835166ca9740cf70f36d6f61c43e0581a | tests/test_encoding.py | tests/test_encoding.py | import os, sys; sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import codecs
import pytest
from lasio import read
egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn)
| import os, sys; sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import codecs
import pytest
from lasio import read
egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn)
def test_utf8_default():
fn = egfn("sample_extended_chars_utf8.las")
l = read(fn)
def test_utf8wbom_de... | Add some possibly ineffective tests... | Add some possibly ineffective tests...
| Python | mit | Kramer477/lasio,kwinkunks/lasio,kinverarity1/lasio,kinverarity1/las-reader |
0ec5b3887e42191f1b1dda3c8b0f199655674394 | main.py | main.py | #! /usr/bin/python
from __future__ import print_function
import db, os, sys, re
import argparse
import json
from collections import namedtuple
tf2_key = namedtuple('tf2_key', "server_account server_token steam_account host")
# Initial setup of DB
# We keep the connection & cursor seperate so we can do commits when we... | #! /usr/bin/python
from __future__ import print_function
import db, os, sys, re
import argparse
import json
from collections import namedtuple
tf2_key = namedtuple('tf2_key', "server_account server_token steam_account host")
# Initial setup of DB
# We keep the connection & cursor seperate so we can do commits when we... | Print everything on individual lines | Print everything on individual lines
| Python | mit | cloudgameservers/tf2-keyserver |
4ffb58466820cfb2569cf4d4837c8e48caed2c17 | seven23/api/permissions.py | seven23/api/permissions.py |
from itertools import chain
from rest_framework import permissions
from django.utils import timezone
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` a... |
from itertools import chain
from rest_framework import permissions
from datetime import datetime
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attri... | Fix issue with imezone on IsPaid Permission | Fix issue with imezone on IsPaid Permission
| Python | mit | sebastienbarbier/723e,sebastienbarbier/723e_server,sebastienbarbier/723e_server,sebastienbarbier/723e |
b2bc9a893a8b7fea59759e74be6235b890a1ff96 | keybaseproofbot/models.py | keybaseproofbot/models.py | from sqlalchemy import Column, Integer, String
from keybaseproofbot.database import Base
class Proof(Base):
__tablename__ = 'proofs'
user_id = Column(Integer, primary_key=True)
keybase_username = Column(String)
telegram_username = Column(String)
chat_id = Column(Integer)
message_id = Column(I... | from sqlalchemy import Column, BigInteger, String
from keybaseproofbot.database import Base
class Proof(Base):
__tablename__ = 'proofs'
user_id = Column(BigInteger, primary_key=True)
keybase_username = Column(String)
telegram_username = Column(String)
chat_id = Column(BigInteger)
message_id =... | Make ids BigInteger for postgres | Make ids BigInteger for postgres | Python | mit | pingiun/keybaseproofbot |
4c4022e3a215b9b591220cd19fedbc501b63a1b2 | virtualenv/builders/base.py | virtualenv/builders/base.py | import sys
class BaseBuilder(object):
def __init__(self, python, system_site_packages=False, clear=False):
# We default to sys.executable if we're not given a Python.
if python is None:
python = sys.executable
self.python = python
self.system_site_packages = system_si... | import sys
class BaseBuilder(object):
def __init__(self, python, system_site_packages=False, clear=False):
# We default to sys.executable if we're not given a Python.
if python is None:
python = sys.executable
self.python = python
self.system_site_packages = system_si... | Add a hook we'll eventually use to install the activate scripts | Add a hook we'll eventually use to install the activate scripts
| Python | mit | ionelmc/virtualenv,ionelmc/virtualenv,ionelmc/virtualenv |
c0fd2b981f2657e0a78de028335ea172735c5f6b | zaqar/common/cli.py | zaqar/common/cli.py | # Copyright (c) 2013 Rackspace Hosting, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2013 Rackspace Hosting, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | Fix regression: No handlers could be found for logger when start | Fix regression: No handlers could be found for logger when start
This change fixed a function regression on bug/1201562.
Closes-Bug: #1201562
Change-Id: I3994c97633f5d09cccf6defdf0eac3957d63304e
Signed-off-by: Zhi Yan Liu <98cb9f7b35c45309ab1e4c4eac6ba314b641cf7a@cn.ibm.com>
| Python | apache-2.0 | openstack/zaqar,openstack/zaqar,openstack/zaqar,openstack/zaqar |
97f507ab5869c306ed468c683ca6e6e9b3266f5e | tests/tests/models/authorization_token.py | tests/tests/models/authorization_token.py | from django.test import TestCase
from django.contrib.auth.models import User
from doac.models import AuthorizationToken, Client, RefreshToken, Scope
class TestAuthorizationTokenModel(TestCase):
def setUp(self):
self.oclient = Client(name="Test Client", access_host="http://localhost/")
self.oclien... | from django.test import TestCase
from django.contrib.auth.models import User
from doac.models import AuthorizationToken, Client, RefreshToken, Scope
class TestAuthorizationTokenModel(TestCase):
def setUp(self):
self.oclient = Client(name="Test Client", access_host="http://localhost/")
self.oclien... | Split up the tests for AuthorizationToken | Split up the tests for AuthorizationToken
| Python | mit | Rediker-Software/doac |
52f585aa3aaaa4f645b61575d6ca307555247bcc | appengine/models/product_group.py | appengine/models/product_group.py | from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsModel
from endpoints_proto_datastore.ndb import EndpointsAliasProperty
from protorpc import messages
class ProductGroup(EndpointsModel):
_message_fields_schema = ('id', 'tag', 'description', 'url', 'image')
_api_key = No... | from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsModel
from endpoints_proto_datastore.ndb import EndpointsAliasProperty
from protorpc import messages
class ProductGroup(EndpointsModel):
_message_fields_schema = (
'id', 'tag', 'description', 'url', 'image', 'so_tags'... | Add so tags to ProductGroup entity | Add so tags to ProductGroup entity
| Python | apache-2.0 | GoogleDeveloperExperts/experts-app-backend |
0a035a93666eb98b460d083e5dd822d7adb0614f | us_ignite/blog/admin.py | us_ignite/blog/admin.py | from django import forms
from django.contrib import admin
from django.contrib.auth.models import User
from us_ignite.common import sanitizer
from us_ignite.blog.models import BlogLink, Post, PostAttachment
from tinymce.widgets import TinyMCE
class PostAdminForm(forms.ModelForm):
author = forms.ModelChoiceField(... | from django import forms
from django.contrib import admin
from django.contrib.auth.models import User
from us_ignite.common import sanitizer
from us_ignite.blog.models import BlogLink, Post, PostAttachment
from tinymce.widgets import TinyMCE
class PostAdminForm(forms.ModelForm):
author = forms.ModelChoiceField(... | Make the blog author in the form a non required field. | Make the blog author in the form a non required field.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite |
58e636838b0988814905fc163f369dd837aedfde | mopidy/backends/gstreamer.py | mopidy/backends/gstreamer.py | import logging
from mopidy.backends import BaseBackend, BasePlaybackController
logger = logging.getLogger(u'backends.gstreamer')
class GStreamerBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(GStreamerBackend, self).__init__(*args, **kwargs)
self.playback = GStreamerPlaybackCont... | import logging
import gst
from mopidy.backends import BaseBackend, BasePlaybackController
logger = logging.getLogger(u'backends.gstreamer')
class GStreamerBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(GStreamerBackend, self).__init__(*args, **kwargs)
self.playback = GStreamer... | Add playback states to GStreamer | Add playback states to GStreamer
| Python | apache-2.0 | abarisain/mopidy,rawdlite/mopidy,jodal/mopidy,SuperStarPL/mopidy,dbrgn/mopidy,hkariti/mopidy,swak/mopidy,jmarsik/mopidy,rawdlite/mopidy,swak/mopidy,adamcik/mopidy,glogiotatidis/mopidy,adamcik/mopidy,ali/mopidy,jmarsik/mopidy,mokieyue/mopidy,vrs01/mopidy,tkem/mopidy,woutervanwijk/mopidy,bencevans/mopidy,priestd09/mopidy... |
2ac9b826fa56a9b146c90767fe0b7a77b1d7ea5a | test/test_cmdline_main.py | test/test_cmdline_main.py | import textwrap
from pathlib import Path
from unittest.mock import Mock, patch
import pytest
from pyinstrument.__main__ import main
from pyinstrument.renderers.console import ConsoleRenderer
from .util import BUSY_WAIT_SCRIPT
def test_renderer_option(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
(tmp_path ... | import textwrap
from pathlib import Path
from unittest.mock import Mock, patch
import pytest
from pyinstrument.__main__ import main
from pyinstrument.renderers.console import ConsoleRenderer
from .util import BUSY_WAIT_SCRIPT
def test_renderer_option(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
(tmp_path ... | Add tests for -p option | Add tests for -p option
| Python | bsd-3-clause | joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument |
e2f9c0c0e8b96e44c5410c242d0609ef36b5ee4e | tests/test_ghostscript.py | tests/test_ghostscript.py | import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.com... | import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
universal_newlines=True,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)... | Make Popen.communicate return output as strings not bytes. | Make Popen.communicate return output as strings not bytes.
| Python | mit | YPlan/treepoem |
6eb4c09cfc43e2f939660525101a1a8fac9c4838 | threadedcomments/forms.py | threadedcomments/forms.py | from django import forms
from django.contrib.comments.forms import CommentForm
from django.conf import settings
from django.utils.hashcompat import sha_constructor
from threadedcomments.models import ThreadedComment
class ThreadedCommentForm(CommentForm):
parent = forms.IntegerField(required=False, widget=forms.H... | from django import forms
from django.contrib.comments.forms import CommentForm
from django.conf import settings
from django.utils.hashcompat import sha_constructor
from threadedcomments.models import ThreadedComment
class ThreadedCommentForm(CommentForm):
parent = forms.IntegerField(required=False, widget=forms.H... | Make title field appear before comment in the form | Make title field appear before comment in the form
Fixes #7
| Python | bsd-3-clause | yrcjaya/django-threadedcomments,coxmediagroup/django-threadedcomments,nikolas/django-threadedcomments,ccnmtl/django-threadedcomments,yrcjaya/django-threadedcomments,nikolas/django-threadedcomments,SmithsonianEnterprises/django-threadedcomments,PolicyStat/django-threadedcomments,ccnmtl/django-threadedcomments,Smithsonia... |
84a7b7fd8612121379700498c61e7c292eb8262a | malcolm/controllers/builtin/defaultcontroller.py | malcolm/controllers/builtin/defaultcontroller.py | from malcolm.core import Controller, DefaultStateMachine, Hook, \
method_only_in, method_takes
sm = DefaultStateMachine
@sm.insert
@method_takes()
class DefaultController(Controller):
Resetting = Hook()
Disabling = Hook()
@method_takes()
def disable(self):
try:
self.transit... | from malcolm.core import Controller, DefaultStateMachine, Hook, \
method_only_in, method_takes
sm = DefaultStateMachine
@sm.insert
@method_takes()
class DefaultController(Controller):
Resetting = Hook()
Disabling = Hook()
@method_takes()
def disable(self):
try:
self.transit... | Make part task creation explicit | Make part task creation explicit
| Python | apache-2.0 | dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm |
031fffb277fbf86e8aba3d7509823ee7b3acf873 | seleniumbase/config/proxy_list.py | seleniumbase/config/proxy_list.py | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:po... | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:po... | Update proxy with a currently-working example | Update proxy with a currently-working example
| Python | mit | mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase |
c02d6bef8a91d436e9c26363f810eb8053ca2a69 | fmn/filters/generic.py | fmn/filters/generic.py | # Generic filters for FMN
def user_filter(config, message, fasnick):
""" Filters the messages by the user that performed the action.
Use this filter to filter out messages that are associated with a
specified user.
"""
print config
return fasnick in fedmsg.meta.msg2usernames(message)
| # Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" Filters the messages by the user that performed the action.
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fa... | Fix the user_filter to handle arguments properly | Fix the user_filter to handle arguments properly
fasnick=None is required so that the argument is displayed in the UI
*args, **kw is actually how the arguments are passed to the filter for it to run
This **kw is the actual important bit here. | Python | lgpl-2.1 | jeremycline/fmn,jeremycline/fmn,jeremycline/fmn |
12fbf40ce5ffaab44c7a602925230e0c2d96b9b0 | cameo/strain_design/heuristic/observers.py | cameo/strain_design/heuristic/observers.py | # Copyright 2014 Novo Nordisk Foundation Center for Biosustainability, DTU.
#
# 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 requi... | # Copyright 2014 Novo Nordisk Foundation Center for Biosustainability, DTU.
#
# 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 requi... | Fix the bug fix. Now is really fixed. | Fix the bug fix. Now is really fixed.
| Python | apache-2.0 | biosustain/cameo,biosustain/cameo,KristianJensen/cameo |
ee30d1f8b268f6a5862de0527bc48dd45f59b9f6 | trackingtermites/utils.py | trackingtermites/utils.py | """Utilitary shared functions."""
boolean_parameters = ['show_labels', 'highlight_collisions',
'show_bounding_box', 'show_frame_info',
'show_d_lines', 'show_trails']
tuple_parameters = ['video_source_size', 'arena_size']
integer_parameters = ['n_termites', 'box_size', 'sca... | """Utilitary shared functions."""
boolean_parameters = ['show_labels', 'highlight_collisions',
'show_bounding_box', 'show_frame_info',
'show_d_lines', 'show_trails']
tuple_parameters = ['video_source_size', 'arena_size']
integer_parameters = ['n_termites', 'box_size', 'sca... | Add termite radius to integer parameters | Add termite radius to integer parameters
| Python | mit | dmrib/trackingtermites |
7bdcf639f19c2f1960bd46f7400b8010c5da1de8 | rasterio/rio/main.py | rasterio/rio/main.py | # main: loader of all the command entry points.
import sys
import traceback
from click.formatting import HelpFormatter
from pkg_resources import iter_entry_points
from rasterio.rio.cli import BrokenCommand, cli
# Find and load all entry points in the rasterio.rio_commands group.
# This includes the standard comman... | # main: loader of all the command entry points.
import sys
import traceback
from pkg_resources import iter_entry_points
from rasterio.rio.cli import BrokenCommand, cli
# Find and load all entry points in the rasterio.rio_commands group.
# This includes the standard commands included with Rasterio as well
# as comm... | Remove unneeded import of HelpFormatter. | Remove unneeded import of HelpFormatter.
| Python | bsd-3-clause | brendan-ward/rasterio,perrygeo/rasterio,clembou/rasterio,perrygeo/rasterio,njwilson23/rasterio,johanvdw/rasterio,njwilson23/rasterio,clembou/rasterio,brendan-ward/rasterio,clembou/rasterio,kapadia/rasterio,perrygeo/rasterio,brendan-ward/rasterio,kapadia/rasterio,njwilson23/rasterio,johanvdw/rasterio,kapadia/rasterio,yo... |
fa0513fe303a0111291d459d3bf275229b1eb052 | main.py | main.py | import datetime
import argparse
from auth import twitter_auth as auth
from twitterbot import TwitterBot
from apscheduler.schedulers.blocking import BlockingScheduler
parser = argparse.ArgumentParser(description='Respond to Twitter mentions.')
parser.add_argument('-l', '--listen', nargs='+', default='happy birthday',
... | import sys
import datetime
import argparse
from auth import twitter_auth as auth
from twitterbot import TwitterBot
from apscheduler.schedulers.blocking import BlockingScheduler
parser = argparse.ArgumentParser(description='Respond to Twitter mentions.')
parser.add_argument('-l', '--listen', nargs='+', default=['happy... | Change default type for listen argument | Change default type for listen argument
str->list
| Python | mit | kshvmdn/TwitterBirthdayResponder,kshvmdn/twitter-birthday-responder,kshvmdn/twitter-autoreply |
0774eea1027bc9bb88b5289854aa26109f258712 | great_expectations/exceptions.py | great_expectations/exceptions.py | class GreatExpectationsError(Exception):
pass
class ExpectationsConfigNotFoundError(GreatExpectationsError):
def __init__(self, data_asset_name):
self.data_asset_name = data_asset_name
self.message = "No expectations config found for data_asset_name %s" % data_asset_name
class BatchKwarg... | class GreatExpectationsError(Exception):
pass
class ExpectationsConfigNotFoundError(GreatExpectationsError):
def __init__(self, data_asset_name):
self.data_asset_name = data_asset_name
self.message = "No expectations config found for data_asset_name %s" % data_asset_name
class BatchKwarg... | Add batch_kwargs to custom error | Add batch_kwargs to custom error
| Python | apache-2.0 | great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations |
30470437a86a58e5d89167f24206227737a04cf8 | src/integration_tests/test_validation.py | src/integration_tests/test_validation.py | import pytest
from tests import base
from buildercore import cfngen, project
import logging
LOG = logging.getLogger(__name__)
logging.disable(logging.NOTSET) # re-enables logging during integration testing
# Depends on talking to AWS.
class TestValidationFixtures(base.BaseCase):
def test_validation(self):
... | import pytest
from tests import base
from buildercore import cfngen, project
import logging
LOG = logging.getLogger(__name__)
logging.disable(logging.NOTSET) # re-enables logging during integration testing
# Depends on talking to AWS.
class TestValidationFixtures(base.BaseCase):
def test_validation(self):
... | Correct pytest setup and teardown | Correct pytest setup and teardown
| Python | mit | elifesciences/builder,elifesciences/builder |
760ce74fca8fa9a640167eabb4af83e31e902500 | openedx/core/djangoapps/api_admin/utils.py | openedx/core/djangoapps/api_admin/utils.py | """ Course Discovery API Service. """
from django.conf import settings
from edx_rest_api_client.client import EdxRestApiClient
from openedx.core.djangoapps.theming import helpers
from openedx.core.lib.token_utils import get_id_token
from provider.oauth2.models import Client
CLIENT_NAME = 'course-discovery'
def cour... | """ Course Discovery API Service. """
import datetime
from django.conf import settings
from edx_rest_api_client.client import EdxRestApiClient
import jwt
from openedx.core.djangoapps.theming import helpers
from provider.oauth2.models import Client
from student.models import UserProfile, anonymous_id_for_user
CLIENT_... | Use correct JWT audience when connecting to course discovery. | Use correct JWT audience when connecting to course discovery.
| Python | agpl-3.0 | cecep-edu/edx-platform,ahmedaljazzar/edx-platform,fintech-circle/edx-platform,waheedahmed/edx-platform,proversity-org/edx-platform,pabloborrego93/edx-platform,mbareta/edx-platform-ft,ESOedX/edx-platform,longmen21/edx-platform,pepeportela/edx-platform,chrisndodge/edx-platform,procangroup/edx-platform,ampax/edx-platform,... |
8f2ca07286bd0950e17c410fc27297775934ba21 | vispy/visuals/graphs/layouts/circular.py | vispy/visuals/graphs/layouts/circular.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Circular Layout
===============
This module contains several graph layouts which rely heavily on circles.
"""
import numpy as np
from ..util import straight_line_vertice... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Circular Layout
===============
This module contains several graph layouts which rely heavily on circles.
"""
import numpy as np
from ..util import straight_line_vertice... | Use T attribute to get transpose | Use T attribute to get transpose
| Python | bsd-3-clause | drufat/vispy,michaelaye/vispy,drufat/vispy,ghisvail/vispy,Eric89GXL/vispy,Eric89GXL/vispy,ghisvail/vispy,michaelaye/vispy,Eric89GXL/vispy,michaelaye/vispy,drufat/vispy,ghisvail/vispy |
bf7dd8bb6ff3e4a8f6412122ca23829c35554082 | contrib/examples/sensors/echo_flask_app.py | contrib/examples/sensors/echo_flask_app.py | from flask import request, Flask
from st2reactor.sensor.base import Sensor
class EchoFlaskSensor(Sensor):
def __init__(self, sensor_service, config):
super(EchoFlaskSensor, self).__init__(
sensor_service=sensor_service,
config=config
)
self._host = '127.0.0.1'
... | from flask import request, Flask
from st2reactor.sensor.base import Sensor
class EchoFlaskSensor(Sensor):
def __init__(self, sensor_service, config):
super(EchoFlaskSensor, self).__init__(
sensor_service=sensor_service,
config=config
)
self._host = '127.0.0.1'
... | Update the port to be an integer. | Update the port to be an integer.
Fix the port to be an integer. Use the format function for string formatting. | Python | apache-2.0 | StackStorm/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,Plexxi/st2 |
55b878bae84fea91bf210e3b30a726877990732e | config.py | config.py | # -*- coding: utf-8 -*-
import os
#
# This is the configuration file of the application
#
# Please make sure you don't store here any secret information and use environment
# variables
#
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
SENDGRID_USERNAME = os.environ.get('SENDGRID_USERNAME')
SENDGRID_PASSWORD... | # -*- coding: utf-8 -*-
import os
#
# This is the configuration file of the application
#
# Please make sure you don't store here any secret information and use environment
# variables
#
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
SQLALCHEMY_TRACK_MODIFICATIONS = True
SENDGRID_USERNAME = os.environ.get(... | Set SQLALCHEMY_TRACK_MODIFICATIONS = True to avoid warnings | Set SQLALCHEMY_TRACK_MODIFICATIONS = True to avoid warnings
| Python | bsd-3-clause | boazin/anyway,yosinv/anyway,hasadna/anyway,yosinv/anyway,hasadna/anyway,boazin/anyway,hasadna/anyway,hasadna/anyway,boazin/anyway,yosinv/anyway |
f2a7fe543aa338e81bea692b8267154e64e7478d | polling_stations/apps/file_uploads/utils.py | polling_stations/apps/file_uploads/utils.py | import os
from django.db.models import Q
from councils.models import Council, UserCouncils
def get_domain(request):
return os.environ.get("APP_DOMAIN", request.META.get("HTTP_HOST"))
def assign_councils_to_user(user):
"""
Adds rows to the join table between User and Council
"""
email_domain = ... | import os
from django.db.models import Q
from councils.models import Council, UserCouncils
def get_domain(request):
return os.environ.get("APP_DOMAIN", request.META.get("HTTP_HOST"))
def assign_councils_to_user(user):
"""
Adds rows to the join table between User and Council
"""
email_domain = ... | Make sure UserCouncil is created in logger db | Make sure UserCouncil is created in logger db
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations |
e71c2c5e593be6d6aef04d9752a675bde3ea3150 | ramicova_debug.py | ramicova_debug.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pynux import utils
from os.path import expanduser
import collections
import pprint
pp = pprint.PrettyPrinter(indent=4)
CHILD_NXQL = "SELECT * FROM Document WHERE ecm:parentId = '{}' AND " \
"ecm:currentLifeCycleState != 'deleted' ORDER BY ecm:pos"
nx =... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pynux import utils
from os.path import expanduser
import collections
import pprint
pp = pprint.PrettyPrinter(indent=4)
CHILD_NXQL = "SELECT * FROM Document WHERE ecm:parentId = '{}' AND " \
"ecm:isTrashed = 0 ORDER BY ecm:pos"
nx = utils.Nuxeo(rcfile=o... | Update query for new trash handling | Update query for new trash handling
| Python | bsd-3-clause | ucldc/ucldc-merritt |
b8291dd5bee21ea2dfb77f0fc5b6756773eb5798 | 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_or_create_identifiers
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def add_identifiers_to_preprints():
from osf.models import PreprintService
preprints_without_identifiers =... | import logging
import time
from website.app import init_app
from website.identifiers.utils import get_or_create_identifiers, get_subdomain
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def add_identifiers_to_preprints():
from osf.models import PreprintService
preprints_withou... | Add more logging and asserts to script | Add more logging and asserts to script
| Python | apache-2.0 | erinspace/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,chennan47/osf.io,pattisdr/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,saradbowman/osf.io,saradbowman/osf.io,TomBaxter/osf.io,aaxelb/osf.io,felliott/osf.io,pattisdr/osf.io,leb2dg/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,CenterForOpenScience/osf.io... |
c43b69174e44e3de4888b31d70d3dd8939160988 | alexandria/views/user.py | alexandria/views/user.py | from pyramid.view import (
view_config,
view_defaults,
)
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import (
remember,
forget,
)
@view_defaults(accept='application/json', renderer='json', context='..traversal.User')
class User(object):
de... | from pyramid.view import (
view_config,
view_defaults,
)
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import (
remember,
forget,
)
@view_defaults(accept='application/json', renderer='json', context='..traversal.User')
class User(object):
de... | Add predicate to check CSRF token | Add predicate to check CSRF token
| Python | isc | bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,cdunklau/alexandria,bertjwregeer/alexandria |
dfac2339c1d667beef5df5e11b74e451e3e35a02 | tests/tests.py | tests/tests.py | import datetime
from importlib import import_module
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from session_cleanup.tasks import cleanup
class CleanupTest(TestCase):
@override_settings(SESSION_ENGINE="django... | import datetime
from importlib import import_module
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from session_cleanup.tasks import cleanup
class CleanupTest(TestCase):
@override_settings(SESSION_ENGINE="django... | Use PickleSerializer to serialize test sessions. | Use PickleSerializer to serialize test sessions.
Use PickleSerializer so that we can serialize datetimes in sessions
(this is necessary to set expired sessions in automated tests). See
https://docs.djangoproject.com/en/2.0/topics/http/sessions/#write-your-own-serializer.
| Python | bsd-2-clause | sandersnewmedia/django-session-cleanup |
25aa6fb5887f1f60c833299c379bbf03cc794e45 | src/inbox/util/__init__.py | src/inbox/util/__init__.py | # Don't add new code here! Find the relevant submodule, or use misc.py if
# there's really no other place.
| """ Non-server-specific utility modules. These shouldn't depend on any code
from the inbox.server module tree!
Don't add new code here! Find the relevant submodule, or use misc.py if
there's really no other place.
"""
| Clarify the role of inbox.util module. | Clarify the role of inbox.util module.
| Python | agpl-3.0 | jobscore/sync-engine,jobscore/sync-engine,closeio/nylas,rmasters/inbox,wakermahmud/sync-engine,Eagles2F/sync-engine,Eagles2F/sync-engine,EthanBlackburn/sync-engine,gale320/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,gale320/sync-engine,nylas/sync-engine,PriviPK/privipk-sync-engine,rmasters/inbox,closeio/ny... |
120225323011a53d4a0564d0fcfe834d9ac27062 | build.py | build.py | import argparse
import os
import string
def generate_rpm_spec(template, patch_file):
spec_template = string.Template(template)
base_name, _ = os.path.splitext(patch_file)
values = {
'name': 'kpatch-module-{}'.format(base_name),
'patch_file': patch_file,
'kmod_filename': 'kpatch-{... | import argparse
import os
import string
def generate_rpm_spec(template, patch_file):
spec_template = string.Template(template)
base_name, _ = os.path.splitext(patch_file)
values = {
'name': 'kpatch-module-{}'.format(base_name),
'patch_file': patch_file,
'kmod_filename': 'kpatch-{... | Split arg parsing into function | Split arg parsing into function
| Python | mit | centos-livepatching/kpatch-package-builder |
b2d2f4e4bde02570e51537d4db72cebcba63c1f5 | malcolm/modules/builtin/parts/labelpart.py | malcolm/modules/builtin/parts/labelpart.py | from annotypes import Anno
from malcolm.core import Part, PartRegistrar, StringMeta
from ..infos import LabelInfo
from ..util import set_tags
with Anno("Initial value of Block label"):
ALabelValue = str
class LabelPart(Part):
"""Part representing a the title of the Block a GUI should display"""
def __i... | from annotypes import Anno
from malcolm.core import Part, PartRegistrar, StringMeta
from ..infos import LabelInfo
from ..util import set_tags
with Anno("Initial value of Block label"):
ALabelValue = str
class LabelPart(Part):
"""Part representing a the title of the Block a GUI should display"""
def __i... | Fix LabelPart to always report the validated set value | Fix LabelPart to always report the validated set value
| Python | apache-2.0 | dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm |
8aec91209521d7f2701e63c681f4b765c1b2c6bb | src/program/lwaftr/tests/subcommands/run_test.py | src/program/lwaftr/tests/subcommands/run_test.py | """
Test the "snabb lwaftr run" subcommand. Needs NIC names.
"""
import unittest
from test_env import DATA_DIR, SNABB_CMD, BaseTestCase, nic_names
SNABB_PCI0, SNABB_PCI1 = nic_names()
@unittest.skipUnless(SNABB_PCI0 and SNABB_PCI1, 'NICs not configured')
class TestRun(BaseTestCase):
cmd_args = (
str(S... | """
Test the "snabb lwaftr run" subcommand. Needs NIC names.
"""
import unittest
from test_env import DATA_DIR, SNABB_CMD, BaseTestCase, nic_names, ENC
SNABB_PCI0, SNABB_PCI1 = nic_names()
@unittest.skipUnless(SNABB_PCI0 and SNABB_PCI1, 'NICs not configured')
class TestRun(BaseTestCase):
cmd_args = (
... | Add test for migration using --on-a-stick command | Add test for migration using --on-a-stick command
When --on-a-stick command is used with a single instance defined it
should migrate the instance to work in a stick (replace the device
with the one provided in the flag and remove the device in
`external-device`). It just checks that it works by not crashing and
says ... | Python | apache-2.0 | alexandergall/snabbswitch,Igalia/snabbswitch,snabbco/snabb,snabbco/snabb,snabbco/snabb,dpino/snabbswitch,dpino/snabb,eugeneia/snabb,Igalia/snabb,dpino/snabb,eugeneia/snabb,eugeneia/snabbswitch,eugeneia/snabb,SnabbCo/snabbswitch,eugeneia/snabb,Igalia/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,Igalia/snabb,dpino/s... |
2bdc9561461dbd830285ca1478f828b0b89ac727 | tests/extensions/functional/show_chrome.py | tests/extensions/functional/show_chrome.py | """
Show chrome with extension loaded.
Useful for DOM HTML tree elements inspection with
chrome extension loaded, like when running the tests.
"""
from tests.base import TestBaseTouchscreen
from tests.base import MAPS_URL
klass = TestBaseTouchscreen
klass.setup_class()
# if browser automatically redirects to nat... | """
Show chrome with extension loaded.
Useful for DOM HTML tree elements inspection with
chrome extension loaded, like when running the tests.
"""
from tests.base import TestBaseTouchscreen
from tests.base import MAPS_URL
klass = TestBaseTouchscreen
klass.setup_class()
# if browser automatically redirects to nat... | Add test to print information about chrome version | Add test to print information about chrome version
| Python | apache-2.0 | EndPointCorp/appctl,EndPointCorp/appctl |
22b87959099056e8189f40805bb8320c2cfbfb57 | go/api/go_api/tests/test_action_dispatcher.py | go/api/go_api/tests/test_action_dispatcher.py | """Tests for go.api.go_api.action_dispatcher."""
from twisted.trial.unittest import TestCase
from go.api.go_api.action_dispatcher import (
ActionDispatcher, ActionError, ConversationActionDispatcher,
RouterActionDispatcher)
class ActionDispatcherTestCase(TestCase):
def test_dispatcher_type_name(self):
... | """Tests for go.api.go_api.action_dispatcher."""
from mock import Mock
from twisted.trial.unittest import TestCase
from vumi.tests.utils import LogCatcher
from go.api.go_api.action_dispatcher import (
ActionDispatcher, ActionError, ConversationActionDispatcher,
RouterActionDispatcher)
class ActionDispatch... | Add tests for unknown_action and dispatching to action handlers that generate exceptions. | Add tests for unknown_action and dispatching to action handlers that generate exceptions.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go |
046fe99e4e2de0503c44555287eedaedc56ef280 | skimage/filters/tests/test_filter_import.py | skimage/filters/tests/test_filter_import.py | from warnings import catch_warnings, simplefilter
def test_filter_import():
with catch_warnings():
simplefilter('ignore')
from skimage import filter as F
assert('sobel' in dir(F))
assert any(['has been renamed' in w
for (w, _, _) in F.__warningregistry__]), F.__warningregi... | from warnings import catch_warnings, simplefilter
def test_filter_import():
with catch_warnings():
simplefilter('always')
from skimage import filter as F
assert('sobel' in dir(F))
assert any(['has been renamed' in w
for (w, _, _) in F.__warningregistry__])
| Make sure warning is raised upon import | Make sure warning is raised upon import
| Python | bsd-3-clause | bennlich/scikit-image,vighneshbirodkar/scikit-image,ofgulban/scikit-image,youprofit/scikit-image,pratapvardhan/scikit-image,robintw/scikit-image,ofgulban/scikit-image,GaZ3ll3/scikit-image,Midafi/scikit-image,Britefury/scikit-image,pratapvardhan/scikit-image,ofgulban/scikit-image,Hiyorimi/scikit-image,Britefury/scikit-i... |
d3f72f3ded76fb49eedb0c93c58211aab0231b97 | jetson/networkTable.py | jetson/networkTable.py | import time
from networktables import NetworkTables
rioIP = '10.58.06.2' # this shouldn't change
tableName = 'JetsonToRio' # should be same in rio's java NT program
def initTable():
NetworkTables.initialize(server=rioIP)
return NetworkTables.getTable(tableName)
def pushVals(table, jetsonVals):
table.putNumberArra... | import time
from networktables import NetworkTables
def initTable():
NetworkTables.initialize(server=rioIP)
return NetworkTables.getTable(tableName)
def pushVals(table, jetsonVals):
table.putNumberArray(jetsonVals)
class NetworkInterface(object):
"""docstring for NetworkInterface."""
rioIP = '10.58.06.2' # t... | Put network table interface in class format | Put network table interface in class format
| Python | mit | frc5806/Steamworks,frc5806/Steamworks,frc5806/Steamworks,frc5806/Steamworks |
e17d8f9b8bd09b1b96cad3e61961f3833d2e486c | dataverse/file.py | dataverse/file.py | from __future__ import absolute_import
from dataverse.utils import sanitize
class DataverseFile(object):
def __init__(self, dataset, name, file_id=None):
self.dataset = dataset
self.name = sanitize(name)
self.id = file_id
self.download_url = '{0}/access/datafile/{1}'.format(
... | from __future__ import absolute_import
from dataverse.utils import sanitize
class DataverseFile(object):
def __init__(self, dataset, name, file_id=None):
self.dataset = dataset
self.name = sanitize(name)
self.id = file_id
self.download_url = '{0}/access/datafile/{1}'.format(
... | Fix 'class DataverseFile' to handle old and new response format Tests were failing after swith to new server/version | Fix 'class DataverseFile' to handle old and new response format
Tests were failing after swith to new server/version
| Python | apache-2.0 | CenterForOpenScience/dataverse-client-python,IQSS/dataverse-client-python |
02ac5dcfa6bdaf9b8152ef2f49fd61afe9faf8ab | client/python/plot_request_times.py | client/python/plot_request_times.py | import requests
from plotly.offline import plot
import plotly.graph_objs as go
r = requests.get('http://localhost:8081/monitor_results/1')
print(r.json())
# build traces for plotting from monitoring data
request_times = list()
timestamps = list()
timestamp = 0
url = r.json()[0]['urlToMonitor']['url']
for monitoring_d... | import requests
from plotly.offline import plot
import plotly.graph_objs as go
def build_data_for_monitored_url(id):
'''Fetches and prepares data for plotting for the given URL id'''
r = requests.get('http://localhost:8081/monitor_results/' + str(id))
# build traces for plotting from monitoring data
re... | Implement fetching all monitored data | Implement fetching all monitored data
| Python | mit | gernd/simple-site-mon |
876d995967c5f8e580fc8e89fff859860b648057 | wagtail/wagtailimages/backends/pillow.py | wagtail/wagtailimages/backends/pillow.py | from __future__ import absolute_import
import PIL.Image
from wagtail.wagtailimages.backends.base import BaseImageBackend
class PillowBackend(BaseImageBackend):
def __init__(self, params):
super(PillowBackend, self).__init__(params)
def open_image(self, input_file):
image = PIL.Image.open(in... | from __future__ import absolute_import
import PIL.Image
from wagtail.wagtailimages.backends.base import BaseImageBackend
class PillowBackend(BaseImageBackend):
def __init__(self, params):
super(PillowBackend, self).__init__(params)
def open_image(self, input_file):
image = PIL.Image.open(in... | Convert P images with transparency into RGBA | Convert P images with transparency into RGBA
Fixes #800
| Python | bsd-3-clause | jorge-marques/wagtail,gasman/wagtail,mikedingjan/wagtail,takeflight/wagtail,nimasmi/wagtail,chimeno/wagtail,kurtrwall/wagtail,Pennebaker/wagtail,mephizzle/wagtail,zerolab/wagtail,gogobook/wagtail,inonit/wagtail,m-sanders/wagtail,mikedingjan/wagtail,nealtodd/wagtail,timorieber/wagtail,takeshineshiro/wagtail,nutztherooki... |
c9b0bfa8d7ced6b521fa4e0454e8640e11aa512b | hr_contract_reference/models/hr_contract.py | hr_contract_reference/models/hr_contract.py | # -*- coding:utf-8 -*-
##############################################################################
#
# Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Af... | # -*- coding:utf-8 -*-
##############################################################################
#
# Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Af... | Update code as commented, update readme. | Update code as commented, update readme.
| Python | agpl-3.0 | OCA/hr,OCA/hr,OCA/hr |
00cffc4197d393e6fc8d8031a4d1f8e78d5c532c | IPython/config/profile/pysh/ipython_config.py | IPython/config/profile/pysh/ipython_config.py | c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
c.InteractiveShell.prompt_in1 = r'\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
c.I... | c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]... | Update prompt config for pysh profile. | Update prompt config for pysh profile.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
24e9cd06f56f4b825a9e22b1974e573b34edb8b9 | ec2_security_group_list.py | ec2_security_group_list.py | #!/usr/bin/env python
import boto
print 'Security group information:\n'
ec2 = boto.connect_ec2()
sgs = ec2.get_all_security_groups()
for sg in sgs:
instances = sg.instances()
print 'id: %s, name: %s, count: %s' % (sg.id, sg.name, len(instances))
for inst in instances:
tag_name = 'UNKNOWN'
... | #!/usr/bin/env python
import boto3
print 'Security group information:\n'
ec2 = boto3.resource('ec2')
sgs = ec2.security_groups.all()
for sg in sgs:
tag_name = sg.group_name
if sg.tags is not None:
for tag in sg.tags:
if tag['Key'] == 'Name' and tag['Value'] != '':
tag_name... | Update script to use boto3 instead of boto2 | Update script to use boto3 instead of boto2
| Python | mit | thinhpham/aws-tools |
1324bec259bc8c0dd041d293a2ef60350c7a1f3c | db/alembic/versions/71213454a09a_7_remove_name_from_measurement.py | db/alembic/versions/71213454a09a_7_remove_name_from_measurement.py | """7_remove_name_from_measurement
Revision ID: 71213454a09a
Revises: f16c6875f138
Create Date: 2017-05-11 14:25:08.256463
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '71213454a09a'
down_revision = 'f16c6875f138'
branch_labels = None
depends_on = None
def ... | """7_remove_name_from_measurement
Revision ID: 71213454a09a
Revises: f16c6875f138
Create Date: 2017-05-11 14:25:08.256463
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '71213454a09a'
down_revision = 'f16c6875f138'
branch_labels = None
depends_on = None
def ... | Fix migration: measurement did not have column key. | Fix migration: measurement did not have column key.
| Python | mit | atlefren/pitilt-api,atlefren/pitilt-api,atlefren/pitilt-api,atlefren/pitilt-api |
b79108c849b5b729eaf35c9c217e04e974474753 | tree.py | tree.py | from PySide import QtGui, QtCore
class Tree(QtGui.QTreeView):
def __init__(self, parent=None):
super(Tree, self).__init__(parent)
def load_from_path(self, path):
""" Load directory containing file into the tree. """
# Link the tree to a model
model = QtGui.QFileSystemModel()
model.setRootPath(path)
... | from PySide import QtGui, QtCore
class Tree(QtGui.QTreeView):
def __init__(self, parent=None):
super(Tree, self).__init__(parent)
def load_from_path(self, path):
""" Load directory containing file into the tree. """
# Link the tree to a model
model = QtGui.QFileSystemModel()
model.setRootPath(path)
... | Print selection in selectionChanged handler. | Print selection in selectionChanged handler.
| Python | bsd-3-clause | techdragon/sphinx-gui,audreyr/sphinx-gui,audreyr/sphinx-gui,techdragon/sphinx-gui |
ac088c3278e509bfaf6fa7b86af1831c7fbb010d | argyle/postgres.py | argyle/postgres.py | from argyle.base import upload_template
from fabric.api import sudo, task
@task
def create_db_user(username, password=None, flags=None):
"""Create a databse user."""
flags = flags or u'-D -A -R'
sudo(u'createuser %s %s' % (flags, username), user=u'postgres')
if password:
change_db_user_passwo... | from argyle.base import upload_template
from fabric.api import sudo, task
@task
def create_db_user(username, password=None, flags=None):
"""Create a databse user."""
flags = flags or u'-D -A -R'
sudo(u'createuser %s %s' % (flags, username), user=u'postgres')
if password:
change_db_user_passwo... | Use sudo to change db user password. | Use sudo to change db user password.
| Python | bsd-2-clause | mlavin/argyle,mlavin/argyle,mlavin/argyle |
725b3a9db33c90187b913123deefeb180c7fee4c | client/app.py | client/app.py | #!/usr/bin/env python3
import argparse
from server import *
from commandRunner import *
class App:
def __init__(self, baseurl, clientid):
self.server = Server(baseurl, clientid)
def run(self):
runner = CommandRunner()
command = self.server.get()
while command is not None:
response = runner... | #!/usr/bin/env python3
import argparse
from server import *
from commandRunner import *
class App:
server = None
runner = None
def __init__(self, baseurl, clientid):
self.server = Server(baseurl, clientid)
self.runner = CommandRunner()
def run(self):
command = self.server.get()
while co... | Add DI to App object | Add DI to App object
| Python | mit | CaminsTECH/owncloud-test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.