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 |
|---|---|---|---|---|---|---|---|---|---|
1b338aa716311b4c91281993e35e9beda376735a | addons/osfstorage/settings/defaults.py | addons/osfstorage/settings/defaults.py | # encoding: utf-8
import importlib
import os
import logging
from website import settings
logger = logging.getLogger(__name__)
WATERBUTLER_CREDENTIALS = {
'storage': {}
}
WATERBUTLER_SETTINGS = {
'storage': {
'provider': 'filesystem',
'folder': os.path.join(settings.BASE_PATH, 'osfstoragecach... | # encoding: utf-8
import importlib
import os
import logging
from website import settings
logger = logging.getLogger(__name__)
WATERBUTLER_CREDENTIALS = {
'storage': {}
}
WATERBUTLER_SETTINGS = {
'storage': {
'provider': 'filesystem',
'folder': os.path.join(settings.BASE_PATH, 'osfstoragecach... | Make environmental override of osfstorage settings work | Make environmental override of osfstorage settings work
Signed-off-by: Chris Wisecarver <5fccdd17c1f7bcc7e393d2cb5e2fad37705ca69f@cos.io>
| Python | apache-2.0 | CenterForOpenScience/osf.io,binoculars/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,TomBaxter/osf.io,chrisseto/osf.io,monikagrabowska/osf.io,sloria/osf.io,crcresearch/osf.io,erinspace/osf.io,caseyrollins/osf.io,Nesiehr/osf.io,TomBaxter/osf.io,leb2dg/osf.io,pattisdr/osf.io,baylee-d/osf.io,adlius/osf.io,felliott/osf.io... |
5a45a312eebe9e432b066b99d914b49a2adb920c | openfaas/yaml2json/function/handler.py | openfaas/yaml2json/function/handler.py | # Author: Milos Buncic
# Date: 2017/10/14
# Description: Convert YAML to JSON and vice versa (OpenFaaS function)
import os
import sys
import json
import yaml
def handle(data, **parms):
def yaml2json(ydata):
"""
Convert YAML to JSON (output: JSON)
"""
try:
d = yaml.load(ydata, Loader=yaml.Base... | # Author: Milos Buncic
# Date: 2017/10/14
# Description: Convert YAML to JSON and vice versa (OpenFaaS function)
import os
import sys
import json
import yaml
def yaml2json(data):
"""
Convert YAML to JSON (output: JSON)
"""
try:
d = yaml.load(data, Loader=yaml.BaseLoader)
except Exception as e:
d = ... | Make handle function to behave similar as main function | Make handle function to behave similar as main function
| Python | mit | psyhomb/serverless |
bd9d08870ec3db09c41c825029c6a513ecc4d1c7 | packs/asserts/actions/object_equals.py | packs/asserts/actions/object_equals.py | import pprint
import sys
from st2actions.runners.pythonrunner import Action
__all__ = [
'AssertObjectEquals'
]
class AssertObjectEquals(Action):
def run(self, object, expected):
ret = cmp(object, expected)
if ret == 0:
sys.stdout.write('EQUAL.')
else:
pprint.... | import pprint
import sys
from st2actions.runners.pythonrunner import Action
__all__ = [
'AssertObjectEquals'
]
def cmp(x, y):
return (x > y) - (x < y)
class AssertObjectEquals(Action):
def run(self, object, expected):
ret = cmp(object, expected)
if ret == 0:
sys.stdout.wri... | Make action python 3 compatible | Make action python 3 compatible
| Python | apache-2.0 | StackStorm/st2tests,StackStorm/st2tests,StackStorm/st2tests |
22412b3f46451177286f8fc58509a69bb2d95731 | numpy/testing/setup.py | numpy/testing/setup.py | #!/usr/bin/env python3
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('testing', parent_package, top_path)
config.add_subpackage('_private')
config.add_subpackage('tests')
config.add_data_files('*.pyi')
return conf... | #!/usr/bin/env python3
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('testing', parent_package, top_path)
config.add_subpackage('_private')
config.add_subpackage('tests')
config.add_data_files('*.pyi')
config.add_... | Add support for *.pyi data-files to `np.testing._private` | BLD: Add support for *.pyi data-files to `np.testing._private`
| Python | bsd-3-clause | rgommers/numpy,numpy/numpy,endolith/numpy,pdebuyl/numpy,simongibbons/numpy,simongibbons/numpy,mhvk/numpy,seberg/numpy,mattip/numpy,jakirkham/numpy,jakirkham/numpy,mattip/numpy,mhvk/numpy,charris/numpy,seberg/numpy,anntzer/numpy,rgommers/numpy,jakirkham/numpy,mhvk/numpy,charris/numpy,anntzer/numpy,pdebuyl/numpy,rgommers... |
3c2663d4c8ca523d072b6e82bf872f412aba9321 | mrgeo-python/src/main/python/pymrgeo/rastermapop.py | mrgeo-python/src/main/python/pymrgeo/rastermapop.py | import copy
import json
from py4j.java_gateway import JavaClass, java_import
from pymrgeo.instance import is_instance_of as iio
class RasterMapOp(object):
mapop = None
gateway = None
context = None
job = None
def __init__(self, gateway=None, context=None, mapop=None, job=None):
self.gatew... | import copy
import json
from py4j.java_gateway import java_import
from pymrgeo.instance import is_instance_of as iio
class RasterMapOp(object):
mapop = None
gateway = None
context = None
job = None
def __init__(self, gateway=None, context=None, mapop=None, job=None):
self.gateway = gatewa... | Implement empty metadata a little differently | Implement empty metadata a little differently
| Python | apache-2.0 | ngageoint/mrgeo,ngageoint/mrgeo,ngageoint/mrgeo |
a78f56e5c4dedc4148ff3503a05705a8d343b638 | qmpy/web/views/analysis/calculation.py | qmpy/web/views/analysis/calculation.py | from django.shortcuts import render_to_response
from django.template import RequestContext
import os.path
from qmpy.models import Calculation
from ..tools import get_globals
from bokeh.embed import components
def calculation_view(request, calculation_id):
calculation = Calculation.objects.get(pk=calculation_id)
... | from django.shortcuts import render_to_response
from django.template import RequestContext
import os
from qmpy.models import Calculation
from ..tools import get_globals
from bokeh.embed import components
def calculation_view(request, calculation_id):
calculation = Calculation.objects.get(pk=calculation_id)
d... | Handle missing INCAR files gracefully | Handle missing INCAR files gracefully
| Python | mit | wolverton-research-group/qmpy,wolverton-research-group/qmpy,wolverton-research-group/qmpy,wolverton-research-group/qmpy,wolverton-research-group/qmpy |
eb453010915f6700edd1baa0febcc634deec81dc | src/viewsapp/views.py | src/viewsapp/views.py | from decorator_plus import (
require_form_methods, require_safe_methods)
from django.shortcuts import (
get_object_or_404, redirect, render)
from .forms import ExampleForm
from .models import ExampleModel
@require_safe_methods
def model_detail(request, *args, **kwargs):
request_slug = kwargs.get('slug')
... | from decorator_plus import require_http_methods
from django.shortcuts import (
get_object_or_404, redirect, render)
from .forms import ExampleForm
from .models import ExampleModel
@require_http_methods(['GET'])
def model_detail(request, *args, **kwargs):
request_slug = kwargs.get('slug')
example_obj = ge... | Switch to using require_http_methods decorator. | Switch to using require_http_methods decorator.
| Python | bsd-2-clause | jambonrose/djangocon2015-views,jambonrose/djangocon2015-views |
94e44e18832311bc063830c0a6bfe23e04e40a8d | srsly/_msgpack_api.py | srsly/_msgpack_api.py | # coding: utf8
from __future__ import unicode_literals
import gc
from . import msgpack
from .util import force_path
def msgpack_dumps(data):
return msgpack.dumps(data, use_bin_type=True)
def msgpack_loads(data):
# msgpack-python docs suggest disabling gc before unpacking large messages
gc.disable()
... | # coding: utf8
from __future__ import unicode_literals
import gc
from . import msgpack
from .util import force_path
def msgpack_dumps(data):
return msgpack.dumps(data, use_bin_type=True)
def msgpack_loads(data, use_list=True):
# msgpack-python docs suggest disabling gc before unpacking large messages
... | Allow passing use_list to msgpack_loads | Allow passing use_list to msgpack_loads
| Python | mit | explosion/srsly,explosion/srsly,explosion/srsly,explosion/srsly |
e78b3f53150a5f1c170b860f8719e982cf1c6f9e | integration/main.py | integration/main.py | import os
import sys
from spec import Spec, skip
from invoke import run
class Integration(Spec):
def setup(self):
from tessera.application import db
# Ensure we have a clean db target.
self.dbpath = db.engine.url.database
msg = "You seem to have a db in the default location ({0}) ... | import os
import sys
from spec import Spec, skip, eq_
from invoke import run
class Integration(Spec):
def setup(self):
from tessera.application import db
# Ensure we have a clean db target.
self.dbpath = db.engine.url.database
msg = "You seem to have a db in the default location (... | Fix state bleed, add fixture import test | Fix state bleed, add fixture import test
| Python | apache-2.0 | section-io/tessera,urbanairship/tessera,tessera-metrics/tessera,jmptrader/tessera,section-io/tessera,urbanairship/tessera,aalpern/tessera,section-io/tessera,jmptrader/tessera,filippog/tessera,aalpern/tessera,aalpern/tessera,Slach/tessera,Slach/tessera,urbanairship/tessera,urbanairship/tessera,Slach/tessera,jmptrader/te... |
0ad29aa9945448236500b221fc489c1627e6693b | api.py | api.py | from collections import namedtuple
import requests
QUERY_TEMPLATE = '?token={}&domain={}'
BASE_URL = 'https://pddimp.yandex.ru/api2/'
Connection = namedtuple('Connection', ['auth', 'domain'])
def list_emails(connection):
url = '{}admin/email/list'.format(BASE_URL) + QUERY_TEMPLATE.format(*connection)
ret ... | import json
import random
import string
from collections import namedtuple
import requests
QUERY_TEMPLATE = '?token={}&domain={}'
BASE_URL = 'https://pddimp.yandex.ru/api2/'
Connection = namedtuple('Connection', ['auth', 'domain'])
class YandexException(Exception):
pass
rndstr = lambda: ''.join(random.samp... | Add create email and delete email methods | Add create email and delete email methods
| Python | mit | chrisseto/dinosaurs.sexy,chrisseto/dinosaurs.sexy |
cbddfe308f4e0da728974777f10b245a966520b6 | summarize/__init__.py | summarize/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from itertools import combinations
from operator import itemgetter
from distance import jaccard
from networkx import Graph, pagerank
from nltk import tokenize
from .utils import get_stopwords, get_words
def summarize(text, sentence_count=5, language='... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from itertools import combinations
from operator import itemgetter
from distance import jaccard
from networkx import Graph, pagerank
from nltk import tokenize
from .utils import get_stopwords, get_words
def summarize(text, sentence_count=5, language='... | Fix sentence index shifting with empty sentences | Fix sentence index shifting with empty sentences
| Python | mit | despawnerer/summarize |
dc68813d5f555a01f1bdd2511d9d2de820369573 | conditional/blueprints/spring_evals.py | conditional/blueprints/spring_evals.py | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | Restructure major projects for spring evals 👷 | Restructure major projects for spring evals 👷
| Python | mit | RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional |
3ffea173c206d4c8a58953eceb34d80fb66d609b | utils/tasks.py | utils/tasks.py | from celery.task import task
from utils import send_templated_email
@task
def send_templated_email_async(to, subject, body_template, body_dict,
from_email=None, ct="html", fail_silently=False):
return send_templated_email(to,subject, body_template, body_dict,
fro... | from celery.task import task
from utils import send_templated_email
@task
def send_templated_email_async(to, subject, body_template, body_dict,
from_email=None, ct="html", fail_silently=False, check_user_preference=True):
return send_templated_email(to,subject, body_template, body_dict,
... | Allow check_user_preferences for email to be passed from async templated email send | Allow check_user_preferences for email to be passed from async templated email send
| Python | agpl-3.0 | ReachingOut/unisubs,norayr/unisubs,wevoice/wesub,eloquence/unisubs,ujdhesa/unisubs,ujdhesa/unisubs,ReachingOut/unisubs,pculture/unisubs,eloquence/unisubs,wevoice/wesub,ReachingOut/unisubs,ofer43211/unisubs,ofer43211/unisubs,ofer43211/unisubs,wevoice/wesub,ujdhesa/unisubs,pculture/unisubs,wevoice/wesub,ujdhesa/unisubs,n... |
45963022a39f8c0f3d57199017adc78b39005d6a | openspending/lib/unicode_dict_reader.py | openspending/lib/unicode_dict_reader.py | # work around python2's csv.py's difficulty with utf8
# partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support
class EmptyCSVError(Exception):
pass
def UnicodeDictReader(file_or_str, encoding='utf8', **kwargs):
import csv
def decode(s, enco... | # work around python2's csv.py's difficulty with utf8
# partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support
import csv
class EmptyCSVError(Exception):
pass
class UnicodeDictReader(object):
def __init__(self, file_or_str, encoding='utf8', **... | Convert UnicodeDictReader to an iterator class, so that EmptyCSVError will get thrown on instantiation, rather than on iteration. | Convert UnicodeDictReader to an iterator class, so that EmptyCSVError will get thrown on instantiation, rather than on iteration.
| Python | agpl-3.0 | pudo/spendb,nathanhilbert/FPA_Core,USStateDept/FPA_Core,openspending/spendb,CivicVision/datahub,nathanhilbert/FPA_Core,CivicVision/datahub,spendb/spendb,johnjohndoe/spendb,johnjohndoe/spendb,spendb/spendb,USStateDept/FPA_Core,nathanhilbert/FPA_Core,pudo/spendb,openspending/spendb,johnjohndoe/spendb,openspending/spendb,... |
db935a152efc8ab730491fc860db6d4c9cf65c5f | test/test_packages.py | test/test_packages.py | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("atom"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-ce"),
("fonts-font-awesome"),
("git"),
("gnupg"),
("gnupg2"),
("gnupg-agent"),
("handbrake"),... | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("atom"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-ce"),
("fonts-font-awesome"),
("git"),
("gnupg"),
("gnupg2"),
("gnupg-agent"),
("handbrake"),... | Change test function as existing method deprecated | Change test function as existing method deprecated
| Python | mit | wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build |
7d621db3618db90679461550fb0c952417616402 | bot.py | bot.py | import asyncio
import configparser
import discord
from discord.ext import commands
class Bot(commands.Bot):
def __init__(self, config_filepath, command_prefix):
super().__init__(command_prefix)
self._load_config_data(config_filepath)
def _load_config_data(self, filepath):
config = configparser.ConfigParser()
... | import asyncio
import configparser
import discord
from discord.ext import commands
class Bot(commands.Bot):
def __init__(self, config_filepath, command_prefix):
super().__init__(command_prefix)
self._load_config_data(config_filepath)
def _load_config_data(self, filepath):
config = configparser.ConfigParser()
... | Add Bot.run and an on_ready message | Add Bot.run and an on_ready message
| Python | mit | MagiChau/ZonBot |
ee2ed250fdf42d0e4616f0e783ff1ace0a201514 | scripts/spat_conlisk_univariate_fig2.py | scripts/spat_conlisk_univariate_fig2.py | """
Purpose: to recreate the univariate pdfs of Conlisk et al. (2007)
in figure 2. This provides a test that the univariate pdfs are
working correctly
"""
import numpy as np
import mete
import csv
n0 = 617
c = 256
sing_pdfs = np.zeros((4, 7))
psi = [0.01, 0.25, 0.5, 0.75]
for i in range(0, len(psi)):
sing_pdfs[... | """
Purpose: to recreate the univariate pdfs of Conlisk et al. (2007)
in figure 2. This provides a test that the univariate pdfs are
working correctly
"""
import numpy as np
import mete
import matplotlib.pyplot as plt
n0 = 617
c = 256
sing_pdfs = np.zeros((4, 8))
psi = [0.01, 0.25, 0.5, 0.75]
for i in range(0, len(... | Create a pdf of the univariate pdfs instead of writing to a .csv file. | Create a pdf of the univariate pdfs instead of writing to a .csv file.
| Python | mit | weecology/mete-spatial,weecology/mete-spatial,weecology/mete-spatial,weecology/mete-spatial |
54e715f26ed62e62e8794d8084110091c8db580b | oauth_provider/utils.py | oauth_provider/utils.py | import oauth.oauth as oauth
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME'
def initialize_server_request(request):
"""Shortcut for initialization."""
oauth_request = oauth.OAuthRequest.from_request(request.meth... | import oauth.oauth as oauth
from django.conf import settings
from django.http import HttpResponse
from stores import DataStore
OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME'
def initialize_server_request(request):
"""Shortcut for initialization."""
# Django converts Authorization header in HTTP_AUTHORIZATION... | Fix a bug introduced in the latest revision, testing auth header in initialize_server_request now, thanks Chris McMichael for the report and patch | Fix a bug introduced in the latest revision, testing auth header in initialize_server_request now, thanks Chris McMichael for the report and patch
| Python | bsd-3-clause | lukegb/django-oauth-plus,amrox/django-oauth-plus |
73fe535416dbf744752d745f0186d5406bd15d8c | test/client/local_recognizer_test.py | test/client/local_recognizer_test.py | import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
self.recognizer ... | import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
rl = RecognizerL... | Fix init of local recognizer | Fix init of local recognizer
| Python | apache-2.0 | linuxipho/mycroft-core,aatchison/mycroft-core,MycroftAI/mycroft-core,aatchison/mycroft-core,forslund/mycroft-core,linuxipho/mycroft-core,Dark5ide/mycroft-core,Dark5ide/mycroft-core,MycroftAI/mycroft-core,forslund/mycroft-core |
eb06e85c7dcb93febe22d20cd7e3e694939449ba | tests/test_xelatex.py | tests/test_xelatex.py | from latex.build import LatexMkBuilder
def test_xelatex():
min_latex = r"""
\documentclass{article}
\begin{document}
Hello, world!
\end{document}
"""
builder = LatexMkBuilder(variant='xelatex')
pdf = builder.build_pdf(min_latex)
assert pdf
| from latex.build import LatexMkBuilder
def test_xelatex():
# the example below should not compile on pdflatex, but on xelatex
min_latex = r"""
\documentclass[12pt]{article}
\usepackage{fontspec}
\setmainfont{Times New Roman}
\title{Sample font document}
\author{Hubert Farnsworth}
\date{this month, 2014}
... | Make XeLaTeX test harder (to actually test xelatex being used). | Make XeLaTeX test harder (to actually test xelatex being used).
| Python | bsd-3-clause | mbr/latex |
d95d71f996483bdde4f0b27d9d9c023aef706c65 | freebasics/tests/test_env_variables.py | freebasics/tests/test_env_variables.py | from django.test import TestCase, RequestFactory
from molo.core.tests.base import MoloTestCaseMixin
from freebasics.views import HomeView
from freebasics.templatetags import freebasics_tags
class EnvTestCase(TestCase, MoloTestCaseMixin):
def setUp(self):
self.mk_main()
def test_block_ordering(self):... | from django.test import TestCase, RequestFactory
from molo.core.tests.base import MoloTestCaseMixin
from freebasics.views import HomeView
from freebasics.templatetags import freebasics_tags
class EnvTestCase(TestCase, MoloTestCaseMixin):
def setUp(self):
self.mk_main()
def test_block_ordering(self):... | Add test for custom css | Add test for custom css
| Python | bsd-2-clause | praekelt/molo-freebasics,praekelt/molo-freebasics,praekelt/molo-freebasics,praekelt/molo-freebasics |
59c66d0e172b23ea7106a70866871d20bbcabe5b | timezones/__init__.py | timezones/__init__.py |
import pytz
TIMEZONE_CHOICES = zip(pytz.all_timezones, pytz.all_timezones)
|
import pytz
TIMEZONE_CHOICES = zip(pytz.common_timezones, pytz.common_timezones)
| Use common timezones and not all timezones pytz provides. | Use common timezones and not all timezones pytz provides.
git-svn-id: 13ea2b4cf383b32e0a7498d153ee882d068671f7@13 86ebb30f-654e-0410-bc0d-7bf82786d749
| Python | bsd-2-clause | mfogel/django-timezone-field,brosner/django-timezones |
8bd738972cebd27b068250bd52db8aacea6c7876 | src/condor_tests/ornithology/plugin.py | src/condor_tests/ornithology/plugin.py | import pytest
from .scripts import SCRIPTS
# This module is loaded as a "plugin" by pytest by a setting in conftest.py
# Any fixtures defined here will be globally available in tests,
# as if they were defined in conftest.py itself.
@pytest.fixture(scope="session")
def path_to_sleep():
return SCRIPTS["sleep"]
| import sys
import pytest
from .scripts import SCRIPTS
# This module is loaded as a "plugin" by pytest by a setting in conftest.py
# Any fixtures defined here will be globally available in tests,
# as if they were defined in conftest.py itself.
@pytest.fixture(scope="session")
def path_to_sleep():
return SCRIPTS[... | Add path_to_python fixture to make writing multiplatform job scripts easier. | Add path_to_python fixture to make writing multiplatform job scripts easier.
| Python | apache-2.0 | htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor |
775170d69862aaff63231b669639a872596ed2cd | test_interpreter.py | test_interpreter.py | import unittest
import brainfuck
test_cases = [("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.", "Hello World!\n")]
class InterpreterTestCase(unittest.TestCase):
def setUp(self):
self.interpreter = brainfuck.BrainfuckInterpreter()
def runTes... | import unittest
import brainfuck
hello_case = ("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.", "Hello World!\n")
class InterpreterTestCase(unittest.TestCase):
def setUp(self):
self.interpreter = brainfuck.BrainfuckInterpreter()
def test_hel... | Add unittest for missing parenthesis | Add unittest for missing parenthesis
| Python | bsd-3-clause | handrake/brainfuck |
131454ffaec010442c17f748365ab491668d947f | plumeria/plugins/bing_images.py | plumeria/plugins/bing_images.py | from aiohttp import BasicAuth
from plumeria import config, scoped_config
from plumeria.command import commands, CommandError
from plumeria.config.common import nsfw
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://api.datamarket.a... | import random
from aiohttp import BasicAuth
from plumeria import config, scoped_config
from plumeria.command import commands, CommandError
from plumeria.config.common import nsfw
from plumeria.message import Response
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
SEARCH_URL = "https://a... | Make the Bing images search pick a random top 20 image. | Make the Bing images search pick a random top 20 image.
| Python | mit | sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria |
f7caec9d0c0058b5d760992172b434b461f70d90 | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service... | import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service... | Remove test enforcing listening on port 1883 | Remove test enforcing listening on port 1883
| Python | mit | triplepoint/ansible-mosquitto |
3dc06581d07a204a3044e3a78deb84950a6ebf74 | mtp_transaction_uploader/api_client.py | mtp_transaction_uploader/api_client.py | from urllib.parse import urljoin
from oauthlib.oauth2 import LegacyApplicationClient
from requests_oauthlib import OAuth2Session
import slumber
from . import settings
REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/')
def get_authenticated_connection():
"""
Returns:
an authenticated sl... | from urllib.parse import urljoin
from oauthlib.oauth2 import LegacyApplicationClient
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
import slumber
from . import settings
REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/')
def get_authenticated_connection():
"""
... | Use HTTPBasicAuth when connecting to the API | Use HTTPBasicAuth when connecting to the API
| Python | mit | ministryofjustice/money-to-prisoners-transaction-uploader |
e6933a46086f83913de307fb8803ccbfd3c55114 | mysite/mysite/tests/test_middleware.py | mysite/mysite/tests/test_middleware.py | from django.contrib.auth.models import User
from django.test import TestCase
from DjangoLibrary.middleware import FactoryBoyMiddleware
from mock import Mock
import json
class TestFactoryBoyMiddleware(TestCase):
def setUp(self):
self.middleware = FactoryBoyMiddleware()
self.request = Mock()
... | from django.contrib.auth.models import User
from django.test import TestCase
from DjangoLibrary.middleware import FactoryBoyMiddleware
from mock import Mock
import json
class TestFactoryBoyMiddleware(TestCase):
def setUp(self):
self.middleware = FactoryBoyMiddleware()
self.request = Mock()
... | Fix integration tests for Python 3. | Fix integration tests for Python 3.
| Python | apache-2.0 | kitconcept/robotframework-djangolibrary |
e68c38428c055f7c001011c6cc325593d2a26a81 | pyFxTrader/strategy/__init__.py | pyFxTrader/strategy/__init__.py | # -*- coding: utf-8 -*-
class Strategy(object):
TIMEFRAMES = [] # e.g. ['M30', 'H2']
def __init__(self, instrument):
self.instrument = instrument
if not self.TIMEFRAMES:
raise ValueError('Please define TIMEFRAMES variable.')
def start(self):
"""Called on strategy star... | # -*- coding: utf-8 -*-
from collections import deque
from logbook import Logger
log = Logger('pyFxTrader')
class Strategy(object):
TIMEFRAMES = [] # e.g. ['M30', 'H2']
BUFFER_SIZE = 500
feeds = {}
def __init__(self, instrument):
self.instrument = instrument
if not self.TIMEFRAM... | Add default BUFFER_SIZE for feeds | Add default BUFFER_SIZE for feeds
| Python | mit | jmelett/pyfx,jmelett/pyFxTrader,jmelett/pyfx |
73d9049dea55ddfa32e4cb09f969b6ff083fee2c | tests/redisdl_test.py | tests/redisdl_test.py | import redisdl
import unittest
import json
import os.path
class RedisdlTest(unittest.TestCase):
def setUp(self):
import redis
self.r = redis.Redis()
for key in self.r.keys('*'):
self.r.delete(key)
def test_roundtrip(self):
path = os.path.join(os.path.dirname(__file_... | import redisdl
import unittest
import json
import os.path
class RedisdlTest(unittest.TestCase):
def setUp(self):
import redis
self.r = redis.Redis()
for key in self.r.keys('*'):
self.r.delete(key)
def test_roundtrip(self):
path = os.path.join(os.path.dirname(__file_... | Add tests for dumping string and unicode values | Add tests for dumping string and unicode values
| Python | bsd-2-clause | p/redis-dump-load,p/redis-dump-load,hyunchel/redis-dump-load,hyunchel/redis-dump-load |
23a0db627060afc3e1563d298c733edd8bb106a1 | src/ConfigLoader.py | src/ConfigLoader.py | import json
import sys
def load_config_file(out=sys.stdout):
default_filepath = "../resources/config/default-config.json"
user_filepath = "../resources/config/user-config.json"
try:
default_json = read_json(default_filepath)
user_json = read_json(user_filepath)
for property in use... | import json
import sys
def load_config_file(out=sys.stdout):
if sys.argv[0].endswith('nosetests'):
default_filepath = "./resources/config/default-config.json"
user_filepath = "./resources/config/user-config.json"
else:
default_filepath = "../resources/config/default-config.json"
... | Fix nosetests for config file loading | Fix nosetests for config file loading
| Python | bsd-3-clause | sky-uk/bslint |
4fb39abc5afef5b0ca87e5c3b40e3dc9c9c0b2ef | tests/functions_tests/test_accuracy.py | tests/functions_tests/test_accuracy.py | import unittest
import numpy
import six
import chainer
from chainer import cuda
from chainer import gradient_check
from chainer.testing import attr
if cuda.available:
cuda.init()
class TestAccuracy(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (10, 3)).astype(numpy.flo... | import unittest
import numpy
import six
import chainer
from chainer import cuda
from chainer import gradient_check
from chainer.testing import attr
if cuda.available:
cuda.init()
class TestAccuracy(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (10, 3)).astype(numpy.flo... | Add test fot shape of result of accuracy function | Add test fot shape of result of accuracy function
| Python | mit | elviswf/chainer,1986ks/chainer,cupy/cupy,ktnyt/chainer,hvy/chainer,tigerneil/chainer,rezoo/chainer,sou81821/chainer,tereka114/chainer,hvy/chainer,wavelets/chainer,jfsantos/chainer,chainer/chainer,ikasumi/chainer,okuta/chainer,aonotas/chainer,ysekky/chainer,kashif/chainer,ktnyt/chainer,niboshi/chainer,pfnet/chainer,ytoy... |
7d6e6325e0baf5f4994350a7dd52856db0cb6c8a | src/apps/processing/ala/management/commands/ala_import.py | src/apps/processing/ala/management/commands/ala_import.py | import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from datetime import date, timedelta
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Import data from ALA stations, optionally you can pass date.... | import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from dateutil import relativedelta
from datetime import date, timedelta
logger = logging.getLogger(__name__)
def parse_date_range(date_str):
if len(date_str) == 4:
... | Enable ALA import by month or year | Enable ALA import by month or year
| Python | bsd-3-clause | gis4dis/poster,gis4dis/poster,gis4dis/poster |
830a767aa42cfafc22342ff71c23419c86845fe8 | src/Classes/SubClass/SubClass.py | src/Classes/SubClass/SubClass.py | class defaultDict(dict):
def __init__(self, default=None):
dict.__init__(self)
self.default = default
def __getitem__(self, key):
try:
return dict.__getitem____(self, key)
except KeyError:
return self.default | class defaultDict(dict):
def __init__(self, default=None):
dict.__init__(self)
self.default = default
def __getitem__(self, key):
if(key in self):
return dict.__getitem__(self, key)
else:
return self.default
def get(self, key, *args):
if not args:
... | Add get and merge method. Add Main Function to use class. | [Add] Add get and merge method.
Add Main Function to use class.
| Python | mit | williamHuang5468/ExpertPython |
ad2b8bce02c7b7b7ab477fc7fccc1b38fb60e63a | turbustat/statistics/input_base.py | turbustat/statistics/input_base.py | # Licensed under an MIT open source license - see LICENSE
from astropy.io.fits import PrimaryHDU
from spectral_cube import SpectralCube
from spectral_cube.lower_dimensional_structures import LowerDimensionalObject
def input_data(data):
'''
Accept a variety of input data forms and return those expected by the... | # Licensed under an MIT open source license - see LICENSE
from astropy.io.fits import PrimaryHDU
from spectral_cube import SpectralCube
from spectral_cube.lower_dimensional_structures import LowerDimensionalObject
import numpy as np
def input_data(data, no_header=False):
'''
Accept a variety of input data fo... | Allow for the case when a header isn't needed | Allow for the case when a header isn't needed
| Python | mit | Astroua/TurbuStat,e-koch/TurbuStat |
2ef4362be90e2314b69a2ff17ccb5d25ef8905fd | rackspace/database/database_service.py | rackspace/database/database_service.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Set default version for cloud databases. | Set default version for cloud databases.
| Python | apache-2.0 | rackerlabs/rackspace-sdk-plugin,briancurtin/rackspace-sdk-plugin |
a307bddf490b6ad16739593d4ca51693b9a340fe | regulations/templatetags/in_context.py | regulations/templatetags/in_context.py | from django import template
register = template.Library()
class InContextNode(template.Node):
def __init__(self, nodelist, subcontext_names):
self.nodelist = nodelist
self.subcontext_names = subcontext_names
def render(self, context):
new_context = {}
for field in self.subcon... | from django import template
register = template.Library()
class InContextNode(template.Node):
def __init__(self, nodelist, subcontext_names):
self.nodelist = nodelist
self.subcontext_names = subcontext_names
def render(self, context):
new_context = {}
for field in self.subcon... | Fix custom template tag to work with django 1.8 | Fix custom template tag to work with django 1.8
| Python | cc0-1.0 | 18F/regulations-site,jeremiak/regulations-site,18F/regulations-site,18F/regulations-site,eregs/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,jeremiak/regulations-site,jeremiak/regulation... |
4a6f76857a626dd756675a4fe1dd3660cf63d8b7 | alg_fibonacci.py | alg_fibonacci.py | """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import print_function
import time
def fibonacci(n):
"""Get nth number of Fibonacci series by recursion."""
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
... | """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import print_function
def fibonacci(n):
"""Get nth number of Fibonacci series by recursion."""
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
... | Move module time to main() | Move module time to main()
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
ea5fd30a583016b4dc858848e28168ada74deca3 | blaze/py3help.py | blaze/py3help.py | import sys
import itertools
PY3 = sys.version_info[:2] >= (3,0)
if PY3:
def dict_iteritems(d):
return d.items().__iter__()
xrange = range
_inttypes = (int,)
_strtypes = (str,)
unicode = str
imap = map
basestring = str
import urllib
urlparse = urllib.parse
else:
import _... | import sys
import itertools
PY3 = sys.version_info[:2] >= (3,0)
if PY3:
def dict_iteritems(d):
return d.items().__iter__()
xrange = range
_inttypes = (int,)
_strtypes = (str,)
unicode = str
imap = map
basestring = str
import urllib.parse as urlparse
else:
import __builtin__... | Check in fix for py3k and urlparse. | Check in fix for py3k and urlparse.
| Python | bsd-3-clause | scls19fr/blaze,markflorisson/blaze-core,ChinaQuants/blaze,jdmcbr/blaze,nkhuyu/blaze,cpcloud/blaze,LiaoPan/blaze,FrancescAlted/blaze,cowlicks/blaze,FrancescAlted/blaze,mwiebe/blaze,markflorisson/blaze-core,mwiebe/blaze,ContinuumIO/blaze,FrancescAlted/blaze,aterrel/blaze,AbhiAgarwal/blaze,jdmcbr/blaze,aterrel/blaze,China... |
05b2848849553172873600ffd6344fc2b1f12d8e | example/__init__.py | example/__init__.py | from pupa.scrape import Jurisdiction
from .people import PersonScraper
class Example(Jurisdiction):
jurisdiction_id = 'ex'
def get_metadata(self):
return {
'name': 'Example',
'legislature_name': 'Example Legislature',
'legislature_url': 'http://example.com',
... | from pupa.scrape import Jurisdiction
from .people import PersonScraper
class Example(Jurisdiction):
jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example'
def get_metadata(self):
return {
'name': 'Example',
'legislature_name': 'Example Legislature',
... | Substitute a more realistic jurisdiction_id | Substitute a more realistic jurisdiction_id
| Python | bsd-3-clause | datamade/pupa,mileswwatkins/pupa,rshorey/pupa,opencivicdata/pupa,mileswwatkins/pupa,influence-usa/pupa,datamade/pupa,influence-usa/pupa,rshorey/pupa,opencivicdata/pupa |
3298fff0ded49c21897a7387a7f3093c351ae04f | scripts/run_psql.py | scripts/run_psql.py | #!/usr/bin/env python
# Copyright (C) 2011 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
from acoustid.script import run_script
import subprocess
def main(script, opts, args):
subprocess.call(['psql'] + script.config.database.create_psql_args())
run_script(main)
| #!/usr/bin/env python
# Copyright (C) 2011 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
from acoustid.script import run_script
import os
def main(script, opts, args):
os.execlp('psql', 'psql', *script.config.database.create_psql_args())
run_script(main)
| Use os.exelp to launch psql | Use os.exelp to launch psql
| Python | mit | lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server |
e10f2b85775412dd60f11deea6e7a7f8b84edfbe | buysafe/urls.py | buysafe/urls.py | from django.conf.urls import patterns
urlpatterns = patterns(
'buysafe.views',
(r'^entry/(?P<order_id>\d+)/$', 'entry'),
(r'^start/$', 'start'),
(r'^success/(?P<payment_type>[01])/$', 'success'),
(r'^fail/(?P<payment_type>[01])/$', 'fail'),
(r'^check/(?P<payment_type>[01])/$', 'check')
)
| from django.conf.urls import patterns, url
urlpatterns = patterns(
'buysafe.views',
url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'),
(r'^start/$', 'start'),
(r'^success/(?P<payment_type>[01])/$', 'success'),
(r'^fail/(?P<payment_type>[01])/$', 'fail'),
(r'^check/(?P<payment_typ... | Add name for entry view URL | Add name for entry view URL
| Python | bsd-3-clause | uranusjr/django-buysafe |
202a9b2ad72ffe4ab5981f9a4a886e0a36808eb6 | tests/sentry/utils/json/tests.py | tests/sentry/utils/json/tests.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import datetime
import uuid
from sentry.utils import json
from sentry.testutils import TestCase
class JSONTest(TestCase):
def test_uuid(self):
res = uuid.uuid4()
self.assertEquals(json.dumps(res), '"%s"' % res.hex)
def test_da... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import datetime
import uuid
from sentry.utils import json
from sentry.testutils import TestCase
class JSONTest(TestCase):
def test_uuid(self):
res = uuid.uuid4()
self.assertEquals(json.dumps(res), '"%s"' % res.hex)
def test_da... | Add test for handling Infinity in json | Add test for handling Infinity in json
| Python | bsd-3-clause | mitsuhiko/sentry,ifduyue/sentry,looker/sentry,mvaled/sentry,gencer/sentry,mvaled/sentry,looker/sentry,zenefits/sentry,korealerts1/sentry,zenefits/sentry,Kryz/sentry,kevinlondon/sentry,alexm92/sentry,JamesMura/sentry,mvaled/sentry,kevinlondon/sentry,looker/sentry,beeftornado/sentry,BuildingLink/sentry,ifduyue/sentry,fel... |
27fec389928c93ba0efe4ca1e4c5b34c3b73fa2c | snippet/__init__.py | snippet/__init__.py | """
"cms.plugins.snippet" (from djangocms) clone to extend it with some facilities
""" | """
"cms.plugins.snippet" (from djangocms) clone to extend it with some facilities
"""
__version__ = '2.3.6.1'
| Add a version base on djangocms version from where the code was cloned | Add a version base on djangocms version from where the code was cloned
| Python | bsd-3-clause | emencia/emencia-cms-snippet,emencia/emencia-cms-snippet,emencia/emencia-cms-snippet |
de22e547c57be633cb32d51e93a6efe9c9e90293 | src/helper_threading.py | src/helper_threading.py | import threading
try:
import prctl
def set_thread_name(name): prctl.set_name(name)
def _thread_name_hack(self):
set_thread_name(self.name)
threading.Thread.__bootstrap_original__(self)
threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap
threading.Thread._T... | import threading
try:
import prctl
def set_thread_name(name): prctl.set_name(name)
def _thread_name_hack(self):
set_thread_name(self.name)
threading.Thread.__bootstrap_original__(self)
threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap
threading.Thread._T... | Remove buggy log message if prctl is missing | Remove buggy log message if prctl is missing
- it's not that important that you need to be informed of it, and
importing logging may cause cyclic dependencies/other problems
| Python | mit | hb9kns/PyBitmessage,hb9kns/PyBitmessage,hb9kns/PyBitmessage,hb9kns/PyBitmessage |
a25920e3549933e4c6c158cc9490f3eaa883ec66 | Lib/test/test_heapq.py | Lib/test/test_heapq.py | """Unittests for heapq."""
from test.test_support import verify, vereq, verbose, TestFailed
from heapq import heappush, heappop
import random
def check_invariant(heap):
# Check the heap invariant.
for pos, item in enumerate(heap):
parentpos = ((pos+1) >> 1) - 1
if parentpos >= 0:
... | """Unittests for heapq."""
from test.test_support import verify, vereq, verbose, TestFailed
from heapq import heappush, heappop
import random
def check_invariant(heap):
# Check the heap invariant.
for pos, item in enumerate(heap):
if pos: # pos 0 has no parent
parentpos = (pos-1) >> 1
... | Use the same child->parent "formula" used by heapq.py. | check_invariant(): Use the same child->parent "formula" used by heapq.py.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
b12b4f47d3cd701506380c914e45b9958490392c | functional_tests.py | functional_tests.py | from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://localhost:8000')
assert 'Django' in browser.title
| from selenium import webdriver
import unittest
class NewVisitorTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
self.browser.quit()
def test_can_start_a_list_and_retrieve_it_later(self):
# Edith has heard about a cool new onlien to-... | Add FT specs and use unittest. | Add FT specs and use unittest.
| Python | mit | ejpreciado/superlists,ejpreciado/superlists,ejpreciado/superlists |
d98e33d28105c8180b591e3097af83e42599bfc5 | django_local_apps/management/commands/docker_exec.py | django_local_apps/management/commands/docker_exec.py | import logging
import docker
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
log = logging.getLogger()
class DockerExecutor(DjangoCmdBase):
def add_arguments(self, parser):
# Positional arguments
"""
:param: in the args it could be: /usr/local/bin/python /... | import logging
import docker
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
log = logging.getLogger()
class DockerExecutor(DjangoCmdBase):
def add_arguments(self, parser):
# Positional arguments
"""
:param: in the args it could be: /usr/local/bin/python /... | Remove the usage of nargs to avoid different behaviors between chronograph and command line. | Remove the usage of nargs to avoid different behaviors between chronograph and command line.
| Python | bsd-3-clause | weijia/django-local-apps,weijia/django-local-apps |
36e7af17c8d7c4bdb9cfd20387c470697e1bac96 | po/build-babel.py | po/build-babel.py | import subprocess
from pathlib import Path
po_path: Path = Path(__file__).resolve().parent
def run_babel(command: str, input: Path, output_file: Path, locale: str):
subprocess.run(
[
"pybabel",
command,
f"--input={str(input)}",
f"--output-file={str(output_f... | import subprocess
from pathlib import Path
po_path: Path = Path(__file__).resolve().parent
def run_babel(command: str, input: Path, output_file: Path, locale: str):
subprocess.run(
[
"pybabel",
command,
f"--input={input}",
f"--output-file={output_file}",
... | Simplify f-string to remove cast | Simplify f-string to remove cast
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor |
7cee7edabad08b01ceda0ed8f2798ebf47c87e95 | src/pycontw2016/urls.py | src/pycontw2016/urls.py | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from core.views import flat_page
from users.views import user_dashboard
urlpatterns = [
url(r'^$', TemplateView.as_v... | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from core.views import flat_page
from users.views import user_dashboard
urlpatterns = [
url(r'^$', TemplateView.as_v... | Fix catch-all URLs with prefix | Fix catch-all URLs with prefix
| Python | mit | uranusjr/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016 |
e2cbd73218e6f5cf5b86718f6adebd92e9fee2a3 | geotrek/trekking/tests/test_filters.py | geotrek/trekking/tests/test_filters.py | from geotrek.land.tests.test_filters import LandFiltersTest
from geotrek.trekking.filters import TrekFilterSet
from geotrek.trekking.factories import TrekFactory
class TrekFilterLandTest(LandFiltersTest):
filterclass = TrekFilterSet
def test_land_filters_are_well_setup(self):
filterset = TrekFilter... | # Make sure land filters are set up when testing
from geotrek.land.filters import * # NOQA
from geotrek.land.tests.test_filters import LandFiltersTest
from geotrek.trekking.filters import TrekFilterSet
from geotrek.trekking.factories import TrekFactory
class TrekFilterLandTest(LandFiltersTest):
filterclass = T... | Make sure land filters are set up when testing | Make sure land filters are set up when testing
| Python | bsd-2-clause | GeotrekCE/Geotrek-admin,johan--/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,johan--/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,mabhub/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,Anaethelion/Geotrek,makinacorpus/... |
c1b0cfe9fdfbacf71ffbba45b4a8f7efe3fe36a7 | docker/dev_wrong_port_warning.py | docker/dev_wrong_port_warning.py | #!/usr/bin/env python
"""
Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This
provides a helpful message to anyone still trying to use port 8000
"""
import BaseHTTPServer
import sys
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(503)
... | #!/usr/bin/env python
"""
Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This
provides a helpful message to anyone still trying to use port 8000
"""
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
se... | Update wront port script to Python3 | Update wront port script to Python3
| Python | bsd-2-clause | kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat |
fee10efeae410a0bc51842877ef8ffb5fe8b97af | src/file_dialogs.py | src/file_dialogs.py | #!/usr/bin/env python
# Copyright 2011 Google 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... | #!/usr/bin/env python
# Copyright 2011 Google 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... | Add gtk implementation of open_file | Add gtk implementation of open_file
| Python | apache-2.0 | natduca/trace_event_viewer,natduca/trace_event_viewer,natduca/trace_event_viewer |
6104b111b4ceaec894018b77cbea4a0de31400d4 | chainer/trainer/extensions/_snapshot.py | chainer/trainer/extensions/_snapshot.py | from chainer.serializers import npz
from chainer.trainer import extension
def snapshot(savefun=npz.save_npz,
filename='snapshot_iter_{.updater.iteration}'):
"""Return a trainer extension to take snapshots of the trainer.
This extension serializes the trainer object and saves it to the output
... | from chainer.serializers import npz
from chainer.trainer import extension
def snapshot(savefun=npz.save_npz,
filename='snapshot_iter_{.updater.iteration}'):
"""Return a trainer extension to take snapshots of the trainer.
This extension serializes the trainer object and saves it to the output
... | Add name to the snapshot extension | Add name to the snapshot extension
| Python | mit | hvy/chainer,jnishi/chainer,ktnyt/chainer,chainer/chainer,cupy/cupy,hvy/chainer,ktnyt/chainer,cupy/cupy,wkentaro/chainer,ysekky/chainer,kikusu/chainer,pfnet/chainer,jnishi/chainer,okuta/chainer,keisuke-umezawa/chainer,ktnyt/chainer,okuta/chainer,niboshi/chainer,niboshi/chainer,cupy/cupy,rezoo/chainer,chainer/chainer,hvy... |
ab6b61d8d0b91ebc2d0b1b8cbd526cfbb6a45a42 | chipy_org/libs/social_auth_pipelines.py | chipy_org/libs/social_auth_pipelines.py | from django.contrib.auth import get_user_model
from django.utils.translation import ugettext
from social_auth.exceptions import AuthAlreadyAssociated
from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email
def associate_by_email(*args, **kwargs):
"""Check if a user with ... | from django.contrib.auth import get_user_model
from django.utils.translation import ugettext
from social_auth.exceptions import AuthAlreadyAssociated
from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email
def associate_by_email(*args, **kwargs):
"""Check if a user with ... | Check for a user from previously in the pipeline before checking for duplicate user. | Check for a user from previously in the pipeline before checking for duplicate user.
| Python | mit | chicagopython/chipy.org,tanyaschlusser/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,brianray/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,bharathelangovan/chipy.org,brianray/chipy.org,agfor/chipy.org,bharathelangovan/chipy.or... |
62a04170e41d599d653e94afe0844576e175c314 | settings_example.py | settings_example.py | import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
CSV_FOLDER = os.getcwd()
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''... | import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by su... | Add comments on variable settings | Add comments on variable settings
| Python | mit | AustralianAntarcticDataCentre/save_emails_to_files,AustralianAntarcticDataCentre/save_emails_to_files |
d03b385b5d23c321ee1d4bd2020be1452e8c1cab | pika/__init__.py | pika/__init__.py | # ***** BEGIN LICENSE BLOCK *****
#
# For copyright and licensing please refer to COPYING.
#
# ***** END LICENSE BLOCK *****
__version__ = '0.9.13p1'
from pika.connection import ConnectionParameters
from pika.connection import URLParameters
from pika.credentials import PlainCredentials
from pika.spec import BasicPrope... | # ***** BEGIN LICENSE BLOCK *****
#
# For copyright and licensing please refer to COPYING.
#
# ***** END LICENSE BLOCK *****
__version__ = '0.9.13p2'
from pika.connection import ConnectionParameters
from pika.connection import URLParameters
from pika.credentials import PlainCredentials
from pika.spec import BasicPrope... | Remove Python 2.4 support monkey patch and bump rev | Remove Python 2.4 support monkey patch and bump rev
| Python | bsd-3-clause | reddec/pika,skftn/pika,Tarsbot/pika,shinji-s/pika,jstnlef/pika,zixiliuyue/pika,fkarb/pika-python3,renshawbay/pika-python3,vrtsystems/pika,Zephor5/pika,pika/pika,vitaly-krugl/pika,knowsis/pika,hugoxia/pika,benjamin9999/pika |
cea891a2de493ce211ccf13f4bf0c487f945985d | test_audio_files.py | test_audio_files.py | import fore.apikeys
import fore.mixer
import fore.database
import pyechonest.track
for file in fore.database.get_many_mp3(status='all'):
print("Name: {} Length: {}".format(file.filename, file.track_details['length']))
track.track_from_filename('audio/'+file.filename, force_upload=True)
| import fore.apikeys
import fore.mixer
import fore.database
import pyechonest.track
for file in fore.database.get_many_mp3(status='all'):
print("Name: {} Length: {}".format(file.filename, file.track_details['length']))
track = track.track_from_filename('audio/'+file.filename, force_upload=True)
print(track.id)
| Print out the new track id. | Print out the new track id.
| Python | artistic-2.0 | Rosuav/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension |
550b48c0d1b464a782d875e30da140c742cd4b3e | tests/test_bayes.py | tests/test_bayes.py | from unittest import TestCase
from itertools import repeat, imap, izip, cycle
from spicedham.bayes import Bayes
from spicedham import Spicedham
class TestBayes(TestCase):
def test_classify(self):
sh = Spicedham()
b = Bayes(sh.config, sh.backend)
b.backend.reset()
self._traini... | from unittest import TestCase
from itertools import repeat, imap, izip, cycle
from spicedham.bayes import Bayes
from spicedham import Spicedham
class TestBayes(TestCase):
def test_classify(self):
sh = Spicedham()
b = Bayes(sh.config, sh.backend)
b.backend.reset()
self._traini... | Replace assertGreaterEqual with assertTrue(a >= b) | Replace assertGreaterEqual with assertTrue(a >= b)
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham |
2fdf35f8a9bf7a6249bc92236952655314a47080 | swapify/__init__.py | swapify/__init__.py | # -*- encoding: utf-8 -*-
__version__ = VERSION = '0.0.0' | # -*- encoding: utf-8 -*-
__author__ = 'Sebastian Vetter'
__version__ = VERSION = '0.0.0'
__license__ = 'MIT'
| Add author and lincense variables | Add author and lincense variables
| Python | mit | elbaschid/swapify |
40897be402bd05ed5fb53e116f03d2d954720245 | astrobin_apps_platesolving/utils.py | astrobin_apps_platesolving/utils.py | # Python
import urllib2
# Django
from django.conf import settings
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
def getFromStorage(image, alias):
url = image.thumbnail(alias)
if "://" in url:
url = url.split('://')[1]
else:
url = settings.BASE_UR... | # Python
import urllib2
# Django
from django.conf import settings
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
def getFromStorage(image, alias):
def encoded(path):
return urllib2.quote(path.encode('utf-8'))
url = image.thumbnail(alias)
if "://" in url... | Fix plate-solving on local development mode | Fix plate-solving on local development mode
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin |
8fe8717b4e2afe6329d2dd25210371df3eab2b4f | test/test_stdlib.py | test/test_stdlib.py | # -*- coding: utf-8 -*-
"""
Tests for the standard library PEP 543 shim.
"""
import pep543.stdlib
from .backend_tests import SimpleNegotiation
class TestSimpleNegotiationStdlib(SimpleNegotiation):
BACKEND = pep543.stdlib.STDLIB_BACKEND
| # -*- coding: utf-8 -*-
"""
Tests for the standard library PEP 543 shim.
"""
import pep543
import pep543.stdlib
import pytest
from .backend_tests import SimpleNegotiation
CONTEXTS = (
pep543.stdlib.STDLIB_BACKEND.client_context,
pep543.stdlib.STDLIB_BACKEND.server_context
)
def assert_wrap_fails(context,... | Test that we reject bad TLS versions | Test that we reject bad TLS versions
| Python | mit | python-hyper/pep543 |
04608636f6e4fc004458560499338af4b871cddb | asyncio_irc/message.py | asyncio_irc/message.py | from .utils import to_bytes
class Message:
"""A message recieved from the IRC network."""
def __init__(self, raw_message):
self.raw = raw_message
self.prefix, self.command, self.params, self.suffix = self._elements()
def _elements(self):
"""
Split the raw message into it'... | from .utils import to_bytes
class Message(bytes):
"""A message recieved from the IRC network."""
def __init__(self, raw_message_bytes_ignored):
super().__init__()
self.prefix, self.command, self.params, self.suffix = self._elements()
def _elements(self):
"""
Split the raw... | Make Message a subclass of bytes | Make Message a subclass of bytes
| Python | bsd-2-clause | meshy/framewirc |
729a5c2e1276f9789733fc46fb7f48d0ac7e3178 | src/slackmoji.py | src/slackmoji.py | # pylint: disable = C0103, C0111
# Standard Library
import json
import mimetypes
from os import makedirs
from subprocess import check_output
# Third Party
import requests
def list_emojis(domain, token):
script = ['bin/list_emojis.sh {0} {1}'.format(domain, token)]
response = check_output(script, shell=True)
... | # pylint: disable = C0103, C0111
# Standard Library
import json
import mimetypes
from os import makedirs
# Third Party
import requests
def list_emojis(domain, token):
url = r'https://%s.slack.com/api/emoji.list' % domain
data = [('token', token)]
response = requests.post(url, data=data)
print "\nGot ... | Use requests to fetch emoji list | Use requests to fetch emoji list
| Python | mit | le1ia/slackmoji |
48b7880fec255c7a021361211e56980be2bd4c6b | project/creditor/management/commands/addrecurring.py | project/creditor/management/commands/addrecurring.py | # -*- coding: utf-8 -*-
from creditor.models import RecurringTransaction
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Gets all RecurringTransactions and runs conditional_add_transaction()'
def handle(self, *args, **options):
for t in RecurringT... | # -*- coding: utf-8 -*-
import datetime
import itertools
import dateutil.parser
from creditor.models import RecurringTransaction
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from asylum.utils import datetime_proxy, months
class Command(BaseCommand):
help = ... | Add "since" parameter to this command | Add "since" parameter to this command
Fixes #25
| Python | mit | HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum |
ccfe12391050d598ec32861ed146b66f4e907943 | noodles/entities.py | noodles/entities.py | """
Find all company names in a piece of text
extractor = EntityExtractor()
entities = extractor.entities_from_text(text)
> ['acme incorporated', 'fubar limited', ...]
TODO:
- work out a standard form to normalize company names to
- import company names into the massive regex
"""
import re
norm_reqs = (
('lt... | """
Find all company names in a piece of text
extractor = EntityExtractor()
entities = extractor.entities_from_text(text)
> ['acme incorporated', 'fubar limited', ...]
"""
COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv'
import re
import csv
norm_reqs = (
('ltd.', 'limited'),
(' bv ', 'b.v.'),
)
def norm... | Use big company list for regex entity extraction | Use big company list for regex entity extraction
| Python | mit | uf6/noodles,uf6/noodles |
93e2ff0dd32a72efa90222988d4289c70bb55b98 | c2corg_api/models/common/fields_book.py | c2corg_api/models/common/fields_book.py | DEFAULT_FIELDS = [
'locales.title',
'locales.summary',
'locales.description',
'locales.lang',
'author',
'editor',
'activities',
'url',
'isbn',
'book_types',
'publication_date',
'langs',
'nb_pages'
]
DEFAULT_REQUIRED = [
'locales',
'locales.title',
'book_t... | DEFAULT_FIELDS = [
'locales.title',
'locales.summary',
'locales.description',
'locales.lang',
'author',
'editor',
'activities',
'url',
'isbn',
'book_types',
'publication_date',
'langs',
'nb_pages'
]
DEFAULT_REQUIRED = [
'locales',
'locales.title',
'book_t... | Add summary to book listing | Add summary to book listing
| Python | agpl-3.0 | c2corg/v6_api,c2corg/v6_api,c2corg/v6_api |
38845ecae177635b98a2e074355227f0c9f9834d | cartoframes/viz/widgets/__init__.py | cartoframes/viz/widgets/__init__.py | """
Widget functions to generate widgets faster.
"""
from __future__ import absolute_import
from .animation_widget import animation_widget
from .category_widget import category_widget
from .default_widget import default_widget
from .formula_widget import formula_widget
from .histogram_widget import histogram_widget
f... | """
Widget functions to generate widgets faster.
"""
from __future__ import absolute_import
from .animation_widget import animation_widget
from .category_widget import category_widget
from .default_widget import default_widget
from .formula_widget import formula_widget
from .histogram_widget import histogram_widget
f... | Add Widget and WidgetList to namespace | Add Widget and WidgetList to namespace
| Python | bsd-3-clause | CartoDB/cartoframes,CartoDB/cartoframes |
3640a5b1976ea6c5b21617cda11324d73071fb9f | trimwhitespace.py | trimwhitespace.py | """Remove trailing whitespace from files in current path and sub directories."""
import os, glob
def scanpath(path):
for filepath in glob.glob(os.path.join(path, '*')):
if os.path.isdir(filepath):
scanpath(filepath)
else:
trimwhitespace(filepath)
def trimwhitespace(filepath):
handle = open(fi... | """Remove trailing whitespace from files in current path and sub directories."""
import os, glob
def scanpath(path):
for filepath in glob.glob(os.path.join(path, '*')):
if os.path.isdir(filepath):
scanpath(filepath)
else:
trimwhitespace(filepath)
def trimwhitespace(filepath):
handle = open(fi... | Fix for whitespace.py so that Windows will save Unix EOLs. | Fix for whitespace.py so that Windows will save Unix EOLs.
| Python | apache-2.0 | GoogleCloudPlatform/datastore-ndb-python,GoogleCloudPlatform/datastore-ndb-python |
d31d2a73127a79566651e644d105cbe2063a6e2a | webapp/publish.py | webapp/publish.py | from cloudly.pubsub import Pusher
from cloudly.tweets import Tweets
from cloudly.twitterstream import Streamer
from webapp import config
class Publisher(Pusher):
def publish(self, tweets, event):
"""Keep only relevant fields from the given tweets."""
stripped = []
for tweet in tweets:
... | from cloudly.pubsub import Pusher
from cloudly.tweets import Tweets, StreamManager, keep
from webapp import config
pubsub = Pusher.open(config.pubsub_channel)
def processor(tweets):
pubsub.publish(keep(['coordinates'], tweets), "tweets")
return len(tweets)
def start():
streamer = StreamManager('locate... | Fix for the new cloudly APi. | Fix for the new cloudly APi.
| Python | mit | hdemers/webapp-template,hdemers/webapp-template,hdemers/webapp-template |
c1f5b9e3bfa96762fdbe9f4ca54b3851b38294da | test/__init__.py | test/__init__.py | import glob, os.path, sys
# Add path to hiredis.so load path
path = glob.glob("build/lib*/hiredis/*.so")[0]
sys.path.insert(0, os.path.dirname(path))
from unittest import *
from . import reader
def tests():
suite = TestSuite()
suite.addTest(makeSuite(reader.ReaderTest))
return suite
| import glob, os.path, sys
version = sys.version.split(" ")[0]
majorminor = version[0:3]
# Add path to hiredis.so load path
path = glob.glob("build/lib*-%s/hiredis/*.so" % majorminor)[0]
sys.path.insert(0, os.path.dirname(path))
from unittest import *
from . import reader
def tests():
suite = TestSuite()
suite.a... | Add versioned path for dynamic library lookup | Add versioned path for dynamic library lookup
| Python | bsd-3-clause | badboy/hiredis-py-win,charsyam/hiredis-py,badboy/hiredis-py-win,redis/hiredis-py,charsyam/hiredis-py,badboy/hiredis-py-win,redis/hiredis-py |
3e30737c98a4a9e890d362ba4cbbb2315163bc29 | cfgov/v1/__init__.py | cfgov/v1/__init__.py | from __future__ import absolute_import # Python 2 only
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from wagtail.wagtailcore.templatetags import wagtailcore_tags
from wagtail.wagtailadmin.templatetags... | from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from wagtail.wagtailcore.templatetags import wagtailcore_tags
from wagtail.wagtailadmin.templatetags import wagtailuserbar
from jinja2 import Environment
fr... | Remove unused Python 2 support | Remove unused Python 2 support
| Python | cc0-1.0 | kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh |
f20c0b650da2354f3008c7a0933eb32a1409fbf0 | openacademy/model/openacademy_session.py | openacademy/model/openacademy_session.py | # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
in... | # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
in... | Add domain or and ilike | [REF] openacademy: Add domain or and ilike
| Python | apache-2.0 | KarenKawaii/openacademy-project |
410207e4c0a091e7b4eca9cedd08f381095f50a9 | pypeerassets/card_parsers.py | pypeerassets/card_parsers.py | '''parse cards according to deck issue mode'''
from .pautils import exponent_to_amount
def none_parser(cards):
'''parser for NONE [0] issue mode'''
return None
def custom_parser(cards, parser=None):
'''parser for CUSTOM [1] issue mode,
please provide your custom parser as argument'''
if not p... | '''parse cards according to deck issue mode'''
from .pautils import exponent_to_amount
def none_parser(cards):
'''parser for NONE [0] issue mode'''
return None
def custom_parser(cards, parser=None):
'''parser for CUSTOM [1] issue mode,
please provide your custom parser as argument'''
if not p... | Revert "change from string to int" | Revert "change from string to int"
This reverts commit a89f8f251ee95609ec4c1ea412b0aa7ec4603252.
| Python | bsd-3-clause | PeerAssets/pypeerassets |
b8f33283014854bfa2d92896e2061bf17de00836 | pygypsy/__init__.py | pygypsy/__init__.py | """pygypsy
Based on Hueng et all (2009)
Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system
(GYPSY) for natural and post-harvest stands in Alberta. Forestry Division,
Alberta Sustainable Resource Development, 25.
Important Acronyms:
aw = white aspen
sb = black spruce
sw = white spruce
pl... | """pygypsy
Based on Hueng et all (2009)
Huang, S., Meng, S. X., & Yang, Y. (2009). A growth and yield projection system
(GYPSY) for natural and post-harvest stands in Alberta. Forestry Division,
Alberta Sustainable Resource Development, 25.
Important Acronyms:
aw = white aspen
sb = black spruce
sw = white spruce
pl... | Revert "Try not importing basal_area_increment to init" | Revert "Try not importing basal_area_increment to init"
This reverts commit 30f9d5367085285a3100d7ec5d6a9e07734c5ccd.
| Python | mit | tesera/pygypsy,tesera/pygypsy |
72ce164a461987f7b9d35ac9a2b3a36386b7f8c9 | ui/Interactor.py | ui/Interactor.py | """
Interactor
This class can be used to simply managing callback resources.
Callbacks are often used by interactors with vtk and callbacks
are hard to keep track of.
Use multiple inheritance to inherit from this class to get access
to the convenience methods.
Observers for vtk events can be added through
AddObserver... | """
Interactor
This class can be used to simply managing callback resources.
Callbacks are often used by interactors with vtk and callbacks
are hard to keep track of.
Use multiple inheritance to inherit from this class to get access
to the convenience methods.
Observers for vtk events can be added through
AddObserver... | Add possibility of passing priority for adding an observer | Add possibility of passing priority for adding an observer
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop |
e85fcd553756eab32cedca214c9b8b86ff48f8b8 | app/forms/vacancy.py | app/forms/vacancy.py | from flask_wtf import Form
from flask_babel import lazy_gettext as _ # noqa
from wtforms import StringField, SubmitField, TextAreaField, \
DateField, SelectField
from wtforms.validators import InputRequired
class VacancyForm(Form):
title = StringField(_('Title'), validators=[InputRequired(
message=_(... | from flask_wtf import Form
from flask_babel import lazy_gettext as _ # noqa
from wtforms import StringField, SubmitField, TextAreaField, \
DateField, SelectField
from wtforms.validators import InputRequired
class VacancyForm(Form):
title = StringField(_('Title'), validators=[InputRequired(
message=_(... | Make workload optional when editing vacancies | Make workload optional when editing vacancies
| Python | mit | viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct |
2627c2c5ea6fdbff9d9979765deee8740a11c7c9 | backend/globaleaks/handlers/__init__.py | backend/globaleaks/handlers/__init__.py | # -*- encoding: utf-8 -*-
#
# In here you will find all the handlers that are tasked with handling the
# requests specified in the API.
#
# From these handlers we will be instantiating models objects that will take care
# of our business logic and the generation of the output to be sent to GLClient.
#
# In here we are ... | # -*- encoding: utf-8 -*-
#
# In here you will find all the handlers that are tasked with handling the
# requests specified in the API.
#
# From these handlers we will be instantiating models objects that will take care
# of our business logic and the generation of the output to be sent to GLClient.
#
# In here we are ... | Fix module packaging thanks to landscape.io hint | Fix module packaging thanks to landscape.io hint
| Python | agpl-3.0 | vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks |
6728bf1fecef3ac1aea9489e7c74333ad0a3b552 | datalogger/__main__.py | datalogger/__main__.py | import sys
from PyQt5.QtWidgets import QApplication
from datalogger.bin.workspace import Workspace
from datalogger.analysis_window_testing import AnalysisWindow
def full():
app = 0
app = QApplication(sys.argv)
# Create the window
w = AnalysisWindow()
w.CurrentWorkspace = Workspace()
# Load ... | import sys
from PyQt5.QtWidgets import QApplication
from datalogger.bin.workspace import Workspace
from datalogger.analysis_window_testing import AnalysisWindow
def full():
app = 0
app = QApplication(sys.argv)
# Create the window
w = AnalysisWindow()
w.CurrentWorkspace = Workspace()
#w.Curr... | Comment out audo-discovery of addons | Comment out audo-discovery of addons
| Python | bsd-3-clause | torebutlin/cued_datalogger |
a5faeb16a599b4260f32741846607dd05f10bc53 | myproject/myproject/project_settings.py | myproject/myproject/project_settings.py | # Project Settings - Settings that don't exist in settings.py that you want to
# add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER,
# CELERYD_PREFETCH_MULTIPLIER, etc.)
#USE_THOUSAND_SEPARATOR = True
#GRAPPELLI_ADMIN_TITLE = ''
#import djcelery
#djcelery.setup_loader()
#CELERYBEAT_SCHEDUL... | # Project Settings - Settings that don't exist in settings.py that you want to
# add (e.g. USE_THOUSAND_SEPARATOR, GRAPPELLI_ADMIN_TITLE, CELERYBEAT_SCHEDULER,
# CELERYD_PREFETCH_MULTIPLIER, etc.)
#USE_THOUSAND_SEPARATOR = True
#GRAPPELLI_ADMIN_TITLE = ''
#import djcelery
#djcelery.setup_loader()
#CELERYBEAT_SCHEDUL... | Add ability to specify which settings are used via `export PRODUCTION=0' | Add ability to specify which settings are used via `export PRODUCTION=0'
| Python | unlicense | django-settings/django-settings |
794596fd6f55806eecca1c54e155533590108eee | openspending/lib/unicode_dict_reader.py | openspending/lib/unicode_dict_reader.py | # work around python2's csv.py's difficulty with utf8
# partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support
import csv
class EmptyCSVError(Exception):
pass
class UnicodeDictReader(object):
def __init__(self, file_or_str, encoding='utf8', **... | # work around python2's csv.py's difficulty with utf8
# partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support
import csv
class EmptyCSVError(Exception):
pass
class UnicodeDictReader(object):
def __init__(self, fp, encoding='utf8', **kwargs):
... | Rename misleading parameter name: UnicodeDictReader should have the same interface as csv.DictReader | Rename misleading parameter name: UnicodeDictReader should have the same interface as csv.DictReader
| Python | agpl-3.0 | CivicVision/datahub,nathanhilbert/FPA_Core,USStateDept/FPA_Core,johnjohndoe/spendb,openspending/spendb,spendb/spendb,CivicVision/datahub,pudo/spendb,CivicVision/datahub,nathanhilbert/FPA_Core,pudo/spendb,openspending/spendb,johnjohndoe/spendb,spendb/spendb,nathanhilbert/FPA_Core,openspending/spendb,johnjohndoe/spendb,s... |
207d4c71fbc40dd30c0099769d6f12fcb63f826e | tests/test_utils.py | tests/test_utils.py | import subprocess
from pytest import mark
from pytest_benchmark.utils import clonefunc, get_commit_info
f1 = lambda a: a
def f2(a):
return a
@mark.parametrize('f', [f1, f2])
def test_clonefunc(f):
assert clonefunc(f)(1) == f(1)
assert clonefunc(f)(1) == f(1)
def test_clonefunc_not_function():
ass... | import subprocess
from pytest import mark
from pytest_benchmark.utils import clonefunc, get_commit_info
pytest_plugins = 'pytester',
f1 = lambda a: a
def f2(a):
return a
@mark.parametrize('f', [f1, f2])
def test_clonefunc(f):
assert clonefunc(f)(1) == f(1)
assert clonefunc(f)(1) == f(1)
def test_clo... | Add missing username conf for mercurial. | Add missing username conf for mercurial.
| Python | bsd-2-clause | thedrow/pytest-benchmark,SectorLabs/pytest-benchmark,ionelmc/pytest-benchmark,aldanor/pytest-benchmark |
967cf8774a5033f310ca69e7ad86fc79b2628882 | infrastructure/aws/trigger-provision.py | infrastructure/aws/trigger-provision.py | # trigger-provision.py <indexer-provision.sh | web-server-provision.sh>
import boto3
from datetime import datetime, timedelta
import sys
import os.path
provisioners = sys.argv[1:]
ec2 = boto3.resource('ec2')
client = boto3.client('ec2')
script = ''
for provisioner in provisioners:
script += open(provisioner).re... | # trigger-provision.py <indexer-provision.sh | web-server-provision.sh>
import boto3
from datetime import datetime, timedelta
import sys
import os.path
provisioners = sys.argv[1:]
ec2 = boto3.resource('ec2')
client = boto3.client('ec2')
script = ''
for provisioner in provisioners:
script += open(provisioner).re... | Tag provisioning instances to make them easier to identify | Tag provisioning instances to make them easier to identify
| Python | mpl-2.0 | bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox,bill-mccloskey/searchfox |
2f31af1ea22e0bfefe2042f8d2ba5ad6ce365116 | RG/drivers/s3/secrets.py | RG/drivers/s3/secrets.py | #!/usr/bin/python
SECRETS = {
"AWS_ACCESS_KEY_ID": "AKIAI2TRFQV2HZIHUD4A",
"AWS_SECRET_ACCESS_KEY": "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"
}
| #!/usr/bin/python
SECRETS = {
"AWS_ACCESS_KEY_ID": "XXX",
"AWS_SECRET_ACCESS_KEY": "XXX"
}
| Clear S3 API key from code | Clear S3 API key from code
| Python | apache-2.0 | jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate,iychoi/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,jcnelson/syndicate,iychoi/syndicate,jcnelson/syndicate,iychoi/syndicate |
fbe7b34c575e30114c54587952c9aa919bc28d81 | south/introspection_plugins/__init__.py | south/introspection_plugins/__init__.py | # This module contains built-in introspector plugins for various common
# Django apps.
# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_o... | # This module contains built-in introspector plugins for various common
# Django apps.
# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_o... | Add import of django-annoying patch | Add import of django-annoying patch
| Python | apache-2.0 | theatlantic/django-south,theatlantic/django-south |
9ff63d002293da44871307960d5b439b5e6ba48f | app/commands/help.py | app/commands/help.py | def proc(command, message):
return {
"data": {
"status": "ok",
"html": """
<p>
Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br>
📷 camera controls<br>
... | def proc(command, message):
return {
"data": {
"status": "ok",
"html": """
<p>
Hi! I can control your Raspberry Pi. Send me the commands <b>in bold</b> to make me do stuff.<br><br>
📷 camera controls<br>
... | Remove 'lights' command for a while | Remove 'lights' command for a while
| Python | mit | alwye/spark-pi,alwye/spark-pi |
0a6b43f2202cb63aad18c119d7d46916b4d54873 | examples/site-api.py | examples/site-api.py | #!/usr/bin/env python
# Sets up a basic site that can allow two browsers to connect to each
# other via WebRTC DataChannels, sending connection events via WebSockets.
from flask import Flask, send_from_directory
from flask_sockets import Sockets
import json
app = Flask(__name__)
sockets = Sockets(app)
channels = {}... | #!/usr/bin/env python
# Sets up a basic site that can allow two browsers to connect to each
# other via WebRTC DataChannels, sending connection events via WebSockets.
from flask import Flask, send_from_directory
from flask_sockets import Sockets
import json
app = Flask(__name__)
sockets = Sockets(app)
channels = {}... | Make it easier to load the initial page | Make it easier to load the initial page
| Python | bsd-3-clause | chadnickbok/librtcdcpp,chadnickbok/librtcdcpp |
dae9d7d67aaf2ab8d39b232d243d860d9597bbd2 | django_excel_tools/exceptions.py | django_excel_tools/exceptions.py | class BaseExcelError(Exception):
def __init__(self, message):
super(BaseExcelError, self).__init__()
self.message = message
class ValidationError(BaseExcelError):
pass
class ColumnNotEqualError(BaseExcelError):
pass
class FieldNotExist(BaseExcelError):
pass
| class BaseExcelError(Exception):
def __init__(self, message):
super(BaseExcelError, self).__init__()
self.message = message
class ValidationError(BaseExcelError):
pass
class ColumnNotEqualError(BaseExcelError):
pass
class FieldNotExist(BaseExcelError):
pass
class SerializerConfi... | Add error when serializer setup has error | Add error when serializer setup has error
| Python | mit | NorakGithub/django-excel-tools |
2e6f0934c67baf27cdf3930d48d6b733995e413f | benchmark/_interfaces.py | benchmark/_interfaces.py | # Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Interfaces for the benchmarking results server.
"""
from zope.interface import Interface
class IBackend(Interface):
"""
A backend for storing and querying the results.
"""
def store(result):
"""
Store a single benchmarking... | # Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Interfaces for the benchmarking results server.
"""
from zope.interface import Interface
class IBackend(Interface):
"""
A backend for storing and querying the results.
"""
def store(result):
"""
Store a single benchmarking... | Make the query docstring a bit clearer | Make the query docstring a bit clearer
| Python | apache-2.0 | ClusterHQ/benchmark-server,ClusterHQ/benchmark-server |
0039eefbfa546f24b3f10031e664341d60e4055c | ranger/commands.py | ranger/commands.py | from ranger.api.commands import Command
class fzf_select(Command):
"""
:fzf_select
Find a file using fzf.
With a prefix argument select only directories.
See: https://github.com/junegunn/fzf
"""
def execute(self):
import subprocess
import os.path
if self.quantifie... | from ranger.api.commands import Command
class fzf_select(Command):
"""
:fzf_select
Find a file using fzf.
With a prefix argument select only directories.
See: https://github.com/junegunn/fzf
"""
def execute(self):
import subprocess
import os.path
if self.quantifie... | Use previews in ranger fzf | Use previews in ranger fzf
| Python | mit | darthdeus/dotfiles,darthdeus/dotfiles,darthdeus/dotfiles,darthdeus/dotfiles |
f5e8bfaf5c4f7a2131fbe0ffd0f8d14a316b907e | camoco/Exceptions.py | camoco/Exceptions.py | # Exception abstract class
class CamocoError(Exception):
pass
class CamocoExistsError(CamocoError):
'''
You tried to create a camoco object which already exists
under the same name,type combination.
'''
def __init__(self,expr,message='',*args):
self.expr = expr
self.mess... | # Exception abstract class
class CamocoError(Exception):
pass
class CamocoExistsError(CamocoError):
'''
You tried to create a camoco object which already exists
under the same name,type combination.
'''
def __init__(self,expr,message='',*args):
self.expr = expr
self.mess... | Add exception for cli command line to run interactively. | Add exception for cli command line to run interactively.
| Python | mit | schae234/Camoco,schae234/Camoco |
5da928fd9b08aeb0028b71535413159da18393b4 | comics/sets/forms.py | comics/sets/forms.py | import datetime
from django import forms
from django.template.defaultfilters import slugify
from comics.core.models import Comic
from comics.sets.models import Set
class NewSetForm(forms.ModelForm):
class Meta:
model = Set
fields = ('name',)
def save(self, commit=True):
set = super(N... | import datetime
from django import forms
from django.template.defaultfilters import slugify
from comics.core.models import Comic
from comics.sets.models import Set
class NewSetForm(forms.ModelForm):
class Meta:
model = Set
fields = ('name',)
def save(self, commit=True):
set = super(N... | Exclude inactive comics from sets editing, effectively throwing them out of the set when saved | Exclude inactive comics from sets editing, effectively throwing them out of the set when saved
| Python | agpl-3.0 | datagutten/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics,klette/comics,datagutten/comics |
5425e10a39ce66d3c50e730d1e7b7878e8e88eb0 | dmoj/executors/PHP7.py | dmoj/executors/PHP7.py | from .php_executor import PHPExecutor
from dmoj.judgeenv import env
class Executor(PHPExecutor):
name = 'PHP7'
command = env['runtime'].get('php7')
fs = ['.*\.so', '/etc/localtime$', '.*\.ini$']
initialize = Executor.initialize
| from .php_executor import PHPExecutor
from dmoj.judgeenv import env
class Executor(PHPExecutor):
name = 'PHP7'
command = env['runtime'].get('php7')
fs = ['.*\.so', '/etc/localtime$', '.*\.ini$', '/dev/urandom$']
initialize = Executor.initialize
| Allow /dev/urandom for PHP 7 | Allow /dev/urandom for PHP 7 | Python | agpl-3.0 | DMOJ/judge,DMOJ/judge,DMOJ/judge |
ec8d7b035617f9239a0a52be346d8611cf77cb6f | integration-tests/features/src/utils.py | integration-tests/features/src/utils.py | """Unsorted utility functions used in integration tests."""
import requests
def download_file_from_url(url):
"""Download file from the given URL and do basic check of response."""
assert url
response = requests.get(url)
assert response.status_code == 200
assert response.text is not None
return... | """Unsorted utility functions used in integration tests."""
import requests
import subprocess
def download_file_from_url(url):
"""Download file from the given URL and do basic check of response."""
assert url
response = requests.get(url)
assert response.status_code == 200
assert response.text is n... | Add few oc wrappers for future resiliency testing | Add few oc wrappers for future resiliency testing
Not used anywhere yet.
| Python | apache-2.0 | jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common |
65266813c6438eeb67002e17dd4cd70a00e84b5d | meta-iotqa/lib/oeqa/runtime/boottime.py | meta-iotqa/lib/oeqa/runtime/boottime.py | #[PROTEXCAT]
#\License: ALL RIGHTS RESERVED
"""System boot time"""
import os
from oeqa.oetest import oeRuntimeTest
from oeqa.runtime.helper import collect_pnp_log
class BootTimeTest(oeRuntimeTest):
def _setup(self):
(status,output) = self.target.copy_to(os.path.join(os.path.dirname(__file__), 'files','sy... | #[PROTEXCAT]
#\License: ALL RIGHTS RESERVED
"""System boot time"""
import os
from oeqa.oetest import oeRuntimeTest
from oeqa.runtime.helper import collect_pnp_log
class BootTimeTest(oeRuntimeTest):
def _setup(self):
(status, output) = self.target.copy_to(
os.path.join(os.path.dirname(__file_... | Clean the code with autopen8 | Clean the code with autopen8
| Python | mit | daweiwu/meta-iotqa-1,ostroproject/meta-iotqa,ostroproject/meta-iotqa,ostroproject/meta-iotqa,daweiwu/meta-iotqa-1,wanghongjuan/meta-iotqa-1,wanghongjuan/meta-iotqa-1,ostroproject/meta-iotqa,daweiwu/meta-iotqa-1,daweiwu/meta-iotqa-1,wanghongjuan/meta-iotqa-1,wanghongjuan/meta-iotqa-1,ostroproject/meta-iotqa,daweiwu/meta... |
860e16f506d0a601540847fe21e617d8f7fbf882 | malware/pickle_tool.py | malware/pickle_tool.py | import os
import cPickle as pickle
import simplejson as json
def update_pickle(new_cache):
# print('Updated pickle')
pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2)
def check_pickle():
# print('Checking in pickle')
if not os.path.isfile('url_cache.pkl'):
malicious_url = {}
pic... | import os
import cPickle as pickle
import simplejson as json
def update_pickle(new_cache):
# print('Updated pickle')
pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2)
def check_pickle():
# print('Checking in pickle')
if not os.path.isfile('url_cache.pkl'):
malicious_url = {}
pic... | Add pickle convert to json method | Add pickle convert to json method
| Python | apache-2.0 | John-Lin/malware,John-Lin/malware |
45c4c1f627f224f36c24acebbec43a17a5c59fcb | nib/plugins/lesscss.py | nib/plugins/lesscss.py | from __future__ import absolute_import, division, print_function, unicode_literals
from os import path
import sh
from nib import Processor, resource
@resource('.less')
class LessCSSProcessor(Processor):
def resource(self, resource):
filepath = path.join(self.options['resource_path'],
... | from __future__ import absolute_import, division, print_function, unicode_literals
from os import path
import sh
from nib import Processor, resource
@resource('.less')
class LessCSSProcessor(Processor):
def resource(self, resource):
filepath = path.join(self.options['resource_path'],
... | Print out file being processed, need to do to other modules, add -v flag | Print out file being processed, need to do to other modules, add -v flag
| Python | mit | jreese/nib |
3266ecee8f9a6601d8678a91e8923c6d7137adb3 | oggm/tests/conftest.py | oggm/tests/conftest.py | import pytest
import logging
import multiprocessing as mp
from oggm import cfg, utils
import pickle
logger = logging.getLogger(__name__)
def pytest_configure(config):
if config.pluginmanager.hasplugin('xdist'):
try:
from ilock import ILock
utils.lock = ILock("oggm_xdist_download_lo... | import pytest
import logging
import getpass
from oggm import cfg, utils
logger = logging.getLogger(__name__)
def pytest_configure(config):
if config.pluginmanager.hasplugin('xdist'):
try:
from ilock import ILock
utils.lock = ILock("oggm_xdist_download_lock_" + getpass.getuser())
... | Make ilock lock name user specific | Make ilock lock name user specific
| Python | bsd-3-clause | OGGM/oggm,OGGM/oggm,bearecinos/oggm,bearecinos/oggm,juliaeis/oggm,TimoRoth/oggm,anoukvlug/oggm,TimoRoth/oggm,juliaeis/oggm,anoukvlug/oggm |
0ae9b232b82285f2fa275b8ffa5dced6b9377b0e | keyring/credentials.py | keyring/credentials.py | import os
import abc
class Credential(metaclass=abc.ABCMeta):
"""Abstract class to manage credentials"""
@abc.abstractproperty
def username(self):
return None
@abc.abstractproperty
def password(self):
return None
class SimpleCredential(Credential):
"""Simple credentials imp... | import os
import abc
class Credential(metaclass=abc.ABCMeta):
"""Abstract class to manage credentials"""
@abc.abstractproperty
def username(self):
return None
@abc.abstractproperty
def password(self):
return None
class SimpleCredential(Credential):
"""Simple credentials imp... | Add equality operator to EnvironCredential | Add equality operator to EnvironCredential
Equality operator is useful for testing EnvironCredential
| Python | mit | jaraco/keyring |
e8c180e65dda3422ab472a6580183c715ef325c3 | easyium/decorator.py | easyium/decorator.py | __author__ = 'karl.gong'
from .exceptions import UnsupportedOperationException
def SupportedBy(*web_driver_types):
def handle_func(func):
def handle_args(*args, **kwargs):
wd_types = []
for wd_type in web_driver_types:
if isinstance(wd_type, list):
... | __author__ = 'karl.gong'
from .exceptions import UnsupportedOperationException
def SupportedBy(*web_driver_types):
def handle_func(func):
def handle_args(*args, **kwargs):
wd_types = []
for wd_type in web_driver_types:
if isinstance(wd_type, list):
... | Update error message of UnsupportedOperationException. | Update error message of UnsupportedOperationException.
| Python | apache-2.0 | KarlGong/easyium-python,KarlGong/easyium |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.