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 |
|---|---|---|---|---|---|---|---|---|---|
46d64030c8724f016233703922cbc619eef2c179 | examples/push_pull/architect.py | examples/push_pull/architect.py | from functions import print_message
from osbrain.core import Proxy
pusher = Proxy('Pusher')
puller = Proxy('Puller')
addr = pusher.bind('push')
puller.connect(addr, print_message)
puller.run()
pusher.send(addr, 'Hello world!')
| from functions import print_message
from osbrain.core import Proxy
pusher = Proxy('Pusher')
puller = Proxy('Puller')
addr = pusher.bind('PUSH', alias='push')
puller.connect(addr, handler=print_message)
puller.run()
pusher.send('push', 'Hello, world!')
| Update push_pull example to work with latest changes | Update push_pull example to work with latest changes
| Python | apache-2.0 | opensistemas-hub/osbrain |
39da25f8d221605012c629b3d08478cfe858df36 | poradnia/cases/migrations/0024_auto_20150809_2148.py | poradnia/cases/migrations/0024_auto_20150809_2148.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.models import Count
def delete_empty(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly import it, it'll be the wrong version
Case = apps.get_mod... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.models import Count
def delete_empty(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly import it, it'll be the wrong version
Case = apps.get_mod... | Fix case migrations for MySQL | Fix case migrations for MySQL
| Python | mit | watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl |
286cba2b3e7cf323835acd07f1e3bb510d74bcb2 | biopsy/tests.py | biopsy/tests.py | # -*- coding: utf-8 -*-
from django.test import TestCase
from django.db import models
from biopsy.models import Biopsy
class BiopsyTest(TestCase):
def biopy_test(self):
biopsy = Biopsy(
clinical_information= "clinica",
macroscopic= "macroscopia",
microscopic= "microscopia",
conclusion= "conclusao",
... | # -*- coding: utf-8 -*-
from django.test import TestCase
from django.db import models
from biopsy.models import Biopsy
class BiopsyTest(TestCase):
def biopy_test(self):
biopsy = Biopsy(
clinical_information= "clinica",
macroscopic= "macroscopia",
microscopic= "microscopia",
conclusion= "conclusao",
... | Add status and exam in test Biopsy | Add status and exam in test Biopsy
| Python | mit | msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub |
d0ec3ee9b974fb6956c32e8dfdd6d20ea4da7cff | pwndbg/inthook.py | pwndbg/inthook.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This hook is necessary for compatibility with Python2.7 versions of GDB
since they cannot directly cast to integer a gdb.Value object that is
not already an integer type.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import p... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This hook is necessary for compatibility with Python2.7 versions of GDB
since they cannot directly cast to integer a gdb.Value object that is
not already an integer type.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import p... | Add int hook to Python3 | Add int hook to Python3
Fixes #120
| Python | mit | pwndbg/pwndbg,cebrusfs/217gdb,cebrusfs/217gdb,pwndbg/pwndbg,cebrusfs/217gdb,chubbymaggie/pwndbg,disconnect3d/pwndbg,disconnect3d/pwndbg,pwndbg/pwndbg,0xddaa/pwndbg,zachriggle/pwndbg,0xddaa/pwndbg,disconnect3d/pwndbg,anthraxx/pwndbg,chubbymaggie/pwndbg,0xddaa/pwndbg,cebrusfs/217gdb,anthraxx/pwndbg,zachriggle/pwndbg,anth... |
c8a0279d421c2837e4f7e4ef1eaf2cc9cb94210c | scripts/mkstdlibs.py | scripts/mkstdlibs.py | #!/usr/bin/env python3
from sphinx.ext.intersphinx import fetch_inventory
URL = "https://docs.python.org/{}/objects.inv"
PATH = "isort/stdlibs/py{}.py"
VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8")]
DOCSTRING = """
File contains the standard library of Python {}.
DO NOT EDIT. If the standar... | #!/usr/bin/env python3
from sphinx.ext.intersphinx import fetch_inventory
URL = "https://docs.python.org/{}/objects.inv"
PATH = "isort/stdlibs/py{}.py"
VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8"), ("3", "9")]
DOCSTRING = """
File contains the standard library of Python {}.
DO NOT EDIT. If... | Update script to include empty user agent | Update script to include empty user agent
| Python | mit | PyCQA/isort,PyCQA/isort |
4160fd07d428e26c4de6aee280d948f5044f2c9e | kimochi/scripts/initializedb.py | kimochi/scripts/initializedb.py | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
User,
Site,
SiteAPIKey,
)
def usage(argv):
cmd ... | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Base,
User,
Site,
SiteAPIKey,
)
def usage(argv):
cmd ... | Make sure we add the user to the site as well | Make sure we add the user to the site as well
| Python | mit | matslindh/kimochi,matslindh/kimochi |
525bfce19f593cb598669cdf2eec46747a4b6952 | goodreadsapi.py | goodreadsapi.py | #!/usr/bin/env python
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(r... | #!/usr/bin/env python
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(r... | Add `publication_year` to return data | Add `publication_year` to return data
| Python | mit | avinassh/Reddit-GoodReads-Bot |
4c2dd9dd6dc0f9ff66a36a114c90897dab8da7e5 | goodreadsapi.py | goodreadsapi.py | #!/usr/bin/env python
import re
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(regex, comment_msg))
def get_book_detail... | #!/usr/bin/env python
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(r... | Update GR API to handle Expat Error | Update GR API to handle Expat Error
| Python | mit | avinassh/Reddit-GoodReads-Bot |
7615bfa2a58db373c3e102e7d0205f265d9c4d57 | dxtbx/tst_dxtbx.py | dxtbx/tst_dxtbx.py | from boost.python import streambuf
from dxtbx import read_uint16
f = open('/Users/graeme/data/demo/insulin_1_001.img', 'rb')
hdr = f.read(512)
l = read_uint16(streambuf(f), 2304 * 2304)
print sum(l)
| from boost.python import streambuf
from dxtbx import read_uint16
import sys
from dxtbx.format.Registry import Registry
format = Registry.find(sys.argv[1])
i = format(sys.argv[1])
size = i.get_detector().get_image_size()
f = open(sys.argv[1], 'rb')
hdr = f.read(512)
l = read_uint16(streambuf(f), int(size[0] * size... | Clean up test case: not finished yet though | Clean up test case: not finished yet though | Python | bsd-3-clause | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials |
675c05bd685d550e3c46137f2f52dcdb125cefa0 | tests/test_speed.py | tests/test_speed.py | import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import glob
import fnmatch
import traceback
import logging
import numpy
import pytest
import lasio
test_dir = os.path.dirname(__file__)
egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn)
stegfn = lambda vers, fn: o... | import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import glob
import fnmatch
import traceback
import logging
import numpy
import pytest
import lasio
test_dir = os.path.dirname(__file__)
egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn)
stegfn = lambda vers, fn: o... | Add benchmark test for the speed of reading a LAS file | Add benchmark test for the speed of reading a LAS file
To run it you need to have `pytest-benchmark` installed, and
run the tests using:
```
$ pytest lasio/tests/tests_speed.py
```
To compare two branches, you need to run and store the benchmark from the first branch e.g. master
and then run and compare the benchmar... | Python | mit | kwinkunks/lasio,kinverarity1/lasio,kinverarity1/las-reader |
16bd36fe6fdcbd267413eabe1997337165775f28 | taOonja/game/admin.py | taOonja/game/admin.py | from django.contrib import admin
# Register your models here.
| from django.contrib import admin
from game.models import *
class LocationAdmin(admin.ModelAdmin):
model = Location
admin.site.register(Location, LocationAdmin)
class DetailAdmin(admin.ModelAdmin):
model = Detail
admin.site.register(Detail, DetailAdmin)
| Add models to Admin Panel | Add models to Admin Panel
| Python | mit | Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja |
f620dde75d65e1175829b524eec00d54e20bb2be | tests/test_views.py | tests/test_views.py | from __future__ import unicode_literals
from djet.testcases import ViewTestCase
from pgallery.views import TaggedPhotoListView
class TaggedPhotoListViewTestCase(ViewTestCase):
view_class = TaggedPhotoListView
def test_tag_in_response(self):
request = self.factory.get()
response = self.view(... | from __future__ import unicode_literals
from django.contrib.auth.models import AnonymousUser
from djet.testcases import ViewTestCase
from pgallery.views import GalleryListView, TaggedPhotoListView
from .factories import GalleryFactory, UserFactory
class GalleryListViewTestCase(ViewTestCase):
view_class = Galle... | Test drafts visible for staff users only. | Test drafts visible for staff users only.
| Python | mit | zsiciarz/django-pgallery,zsiciarz/django-pgallery |
7f1db4023f2310529822d721379b1019aaf320fc | tablib/formats/_df.py | tablib/formats/_df.py | """ Tablib - DataFrame Support.
"""
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
from pandas import DataFrame
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if gi... | """ Tablib - DataFrame Support.
"""
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
try:
from pandas import DataFrame
except ImportError:
DataFrame = None
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df'... | Raise NotImplementedError if pandas is not installed | Raise NotImplementedError if pandas is not installed
| Python | mit | kennethreitz/tablib |
5761364149b3171521cb4f72f591dc5f5cbd77d6 | temp-sensor02/main.py | temp-sensor02/main.py | from machine import Pin
from ds18x20 import DS18X20
import onewire
import time
import machine
import ujson
import urequests
def posttocloud(temperature):
keystext = open("sparkfun_keys.json").read()
keys = ujson.loads(keystext)
url = keys['inputUrl'] + "?private_key=" + keys['privateKey'] + "&temp=" + str(temper... | from machine import Pin
from ds18x20 import DS18X20
import onewire
import time
import ujson
import urequests
def posttocloud(temperature):
keystext = open("sparkfun_keys.json").read()
keys = ujson.loads(keystext)
params = {}
params['temp'] = temperature
params['private_key'] = keys['privateKey']
#dat... | Build a query string with params in a dictionary and append it to the URL. Makes the code readale. Remove commented code | Build a query string with params in a dictionary and append it to the URL. Makes the code readale. Remove commented code
| Python | mit | fuzzyhandle/esp8266hangout,fuzzyhandle/esp8266hangout,fuzzyhandle/esp8266hangout |
327ba1797045235a420ce095d2cd2cac5257a1e9 | tutorials/models.py | tutorials/models.py | from django.db import models
# Create your models here.
class Tutorial(models.Model):
title = models.TextField()
html = models.TextField()
markdown = models.TextField() | from django.db import models
from markdownx.models import MarkdownxField
# Create your models here.
class Tutorial(models.Model):
# ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ??
# Category = models.TextField()
title = models.TextField()
html = models.TextFie... | Add missing Fields according to mockup, Add markdownfield | Add missing Fields according to mockup, Add markdownfield
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform |
ea164b66cc93d5d7fb1f89a0297ea0a8da926b54 | server/core/views.py | server/core/views.py | from django.shortcuts import render
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def app(request):
return render(request, 'html.html')
| from django.shortcuts import render
def app(request):
return render(request, 'html.html')
| Stop inserting the CSRF token into the main app page | Stop inserting the CSRF token into the main app page
| Python | mit | Techbikers/techbikers,mwillmott/techbikers,mwillmott/techbikers,Techbikers/techbikers,mwillmott/techbikers,Techbikers/techbikers,Techbikers/techbikers,mwillmott/techbikers |
6c314451e002db3213ff61d1e6935c091b605a8d | server/nurly/util.py | server/nurly/util.py | import traceback
class NurlyResult():
def __init__(self, code='200 OK', head=None, body=''):
self.head = {} if type(head) != dict else head
self.body = body
self.code = code
class NurlyStatus():
ST_IDLE = 0
ST_BUSY = 1
ST_STOP = 2
ST_MAP = {
ST_IDLE: 'IDLE',
... | import traceback
import types
class NurlyResult():
def __init__(self, code='200 OK', head=None, body=''):
self.head = {} if type(head) != dict else head
self.body = body
self.code = code
class NurlyStatus():
ST_IDLE = 0
ST_BUSY = 1
ST_STOP = 2
ST_MAP = {
ST_IDLE: ... | Support using a module as a call back if it has an function attribute by the same name. | Support using a module as a call back if it has an function attribute by the same name.
| Python | mit | mk23/nurly,mk23/nurly,mk23/nurly,mk23/nurly |
293d50438fab81e74ab4559df7a4f7aa7cfd8f03 | etcdocker/container.py | etcdocker/container.py | import docker
from etcdocker import util
class Container:
def __init__(self, name, params):
self.name = name
self.params = params
def set_or_create_param(self, key, value):
self.params[key] = value
def ensure_running(self, force_restart=False):
# Ensure container is runn... | import ast
import docker
from etcdocker import util
class Container:
def __init__(self, name, params):
self.name = name
self.params = params
def set_or_create_param(self, key, value):
self.params[key] = value
def ensure_running(self, force_restart=False):
# Ensure contai... | Convert port list to dict | Convert port list to dict
| Python | mit | CloudBrewery/docrane |
c30181eed55cc1f2af6da4ee8608f4f2052ceb38 | serverless_helpers/__init__.py | serverless_helpers/__init__.py | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
def load_envs(path):
"""Recursively load .env files starting from `path`
Given the path "foo/bar/.env" and a directory structure like:
foo
\-... | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give... | Document calling with __file__ as starting env path | Document calling with __file__ as starting env path
| Python | mit | serverless/serverless-helpers-py |
922acafc793b3d32f625fe18cd52b2bfd59a5f96 | ansible/wsgi.py | ansible/wsgi.py | from pecan.deploy import deploy
app = deploy('/opt/web/draughtcraft/src/production.py')
from paste.exceptions.errormiddleware import ErrorMiddleware
app = ErrorMiddleware(
app,
error_email=app.conf.error_email,
from_address=app.conf.error_email,
smtp_server=app.conf.error_smtp_server,
smtp_username... | from pecan import conf
from pecan.deploy import deploy
app = deploy('/opt/web/draughtcraft/src/production.py')
from paste.exceptions.errormiddleware import ErrorMiddleware
app = ErrorMiddleware(
app,
error_email=conf.error_email,
from_address=conf.error_email,
smtp_server=conf.error_smtp_server,
sm... | Fix a bug in the WSGI entrypoint. | Fix a bug in the WSGI entrypoint.
| Python | bsd-3-clause | ryanpetrello/draughtcraft,ryanpetrello/draughtcraft,ryanpetrello/draughtcraft,ryanpetrello/draughtcraft |
b78b14214e317d1149b37bcdcf5ba0681212431b | rapidsms/contrib/httptester/models.py | rapidsms/contrib/httptester/models.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.db import models
DIRECTION_CHOICES = (
("I", "Incoming"),
("O", "Outgoing"))
class HttpTesterMessage(models.Model):
direction = models.CharField(max_length=1, choices=DIRECTION_CHOICES)
identity = models.CharField(max_length=100)
te... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.db import models
DIRECTION_CHOICES = (
("I", "Incoming"),
("O", "Outgoing"))
class HttpTesterMessage(models.Model):
direction = models.CharField(max_length=1, choices=DIRECTION_CHOICES)
identity = models.CharField(max_length=100)
te... | Sort HTTP Tester Message model by id so they'll naturally be displayed in the order they were added. Branch: feature/httptester-update | Sort HTTP Tester Message model by id so they'll naturally be displayed in the order they were added.
Branch: feature/httptester-update
| Python | bsd-3-clause | eHealthAfrica/rapidsms,peterayeni/rapidsms,ehealthafrica-ci/rapidsms,ehealthafrica-ci/rapidsms,lsgunth/rapidsms,lsgunth/rapidsms,eHealthAfrica/rapidsms,lsgunth/rapidsms,caktus/rapidsms,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,catalpainternational/rapidsms,peterayeni/rapidsms,catalpainternational/rapidsms... |
92eaa47b70d48874da032a21fbbd924936c0d518 | code/csv2map.py | code/csv2map.py | # csv2map.py -- Convert .csv into a .map format
# Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map
#
# jean-daniel.granet@mines-paristech.fr
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='Convert .csv to .map')
parser.add_argument('cs... | # csv2map.py -- Convert .csv into a .map format
# Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map
#
# jean-daniel.granet@mines-paristech.fr
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='Convert .csv to .map')
parser.add_argument('cs... | Add info about csv fields | Add info about csv fields
| Python | mit | chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan |
891a85fc427b16295c6f792d7311eca1e497332e | api/__init__.py | api/__init__.py | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import getenv
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URL',
default='postgresql://postgres@localhost:5432/loadstone')
db = SQLAlchemy(app)
import api.views
| from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import getenv
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DATABASE_URL', default='sqlite://')
db = SQLAlchemy(app)
import api.views
| Set default to sqlite memory | Set default to sqlite memory
| Python | mit | Demotivated/loadstone |
8c8eb5207fd34ba381b89cb147dd3c38b68cf3ad | stocks.py | stocks.py | #!/usr/bin/env python
def find_points(prices, window):
pivot = None
next_pivot = None
profit = 0
for i, price in enumerate(prices):
if pivot is None or price < prices[pivot]:
pivot = i
next_pivot = max(next_pivot, pivot + 1)
if pivot != i and (next_pivot is No... | #!/usr/bin/env python
def find_profit(prices, window):
pivot = None
next_pivot = None
profit = 0
for i, price in enumerate(prices):
if pivot is None or price < prices[pivot]:
pivot = i
next_pivot = max(next_pivot, pivot + 1)
if pivot != i and (next_pivot is No... | Change the name of the function | Change the name of the function
| Python | mit | jrasky/planetlabs-challenge |
15a7ced2d0da014e5d5508ed50c045de3cc9e9d2 | _lib/wordpress_faq_processor.py | _lib/wordpress_faq_processor.py | import sys
import json
import os.path
import requests
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
url = os.path.expandvars(url)
resp = requests.get(url, params={'page': current_page, 'count': '-1'})
results = json.loads(resp.conte... | import sys
import json
import os.path
import requests
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
url = os.path.expandvars(url)
resp = requests.get(url, params={'page': current_page, 'count': '-1'})
results = json.loads(resp.conte... | Change faq processor to bulk index | Change faq processor to bulk index
| Python | cc0-1.0 | imuchnik/cfgov-refresh,imuchnik/cfgov-refresh,imuchnik/cfgov-refresh,imuchnik/cfgov-refresh |
f45e182ec206ab08b1bea699033938b562558670 | test/test_compression.py | test/test_compression.py | import unittest
import bmemcached
import bz2
class MemcachedTests(unittest.TestCase):
def setUp(self):
self.server = '127.0.0.1:11211'
self.client = bmemcached.Client(self.server, 'user', 'password')
self.bzclient = bmemcached.Client(self.server, 'user', 'password', bz2)
self.data =... | import unittest
import bz2
import bmemcached
class MemcachedTests(unittest.TestCase):
def setUp(self):
self.server = '127.0.0.1:11211'
self.client = bmemcached.Client(self.server, 'user', 'password')
self.bzclient = bmemcached.Client(self.server, 'user', 'password',
... | Use keyword arguments to avoid accidentally setting timeout | Use keyword arguments to avoid accidentally setting timeout
| Python | mit | xmonster-tech/python-binary-memcached,jaysonsantos/python-binary-memcached,xmonster-tech/python-binary-memcached,jaysonsantos/python-binary-memcached |
6bbd81efbd4821a3963a021d8456531f01edfd6c | tests/test_rover_instance.py | tests/test_rover_instance.py |
from unittest import TestCase
from rover import Rover
class TestRover(TestCase):
def setUp(self):
self.rover = Rover()
def test_rover_compass(self):
assert self.rover.compass == ['N', 'E', 'S', 'W']
def test_rover_position(self):
assert self.rover.position == (self.rover.x, self... |
from unittest import TestCase
from rover import Rover
class TestRover(TestCase):
def setUp(self):
self.rover = Rover()
def test_rover_compass(self):
assert self.rover.compass == ['N', 'E', 'S', 'W']
def test_rover_position(self):
assert self.rover.position == (self.rover.x, self... | Add failing test for set position method | Add failing test for set position method
| Python | mit | authentik8/rover |
31eae0aee3a6ae9fa7abea312ff1ea843a98e853 | graphene/contrib/django/tests/models.py | graphene/contrib/django/tests/models.py | from __future__ import absolute_import
from django.db import models
class Pet(models.Model):
name = models.CharField(max_length=30)
class Film(models.Model):
reporters = models.ManyToManyField('Reporter',
related_name='films')
class Reporter(models.Model):
first... | from __future__ import absolute_import
from django.db import models
class Pet(models.Model):
name = models.CharField(max_length=30)
class Film(models.Model):
reporters = models.ManyToManyField('Reporter',
related_name='films')
class Reporter(models.Model):
first... | Improve Django field conversion real-life tests | Improve Django field conversion real-life tests
| Python | mit | graphql-python/graphene,sjhewitt/graphene,Globegitter/graphene,sjhewitt/graphene,Globegitter/graphene,graphql-python/graphene |
6d1117fbba83b258162cc0f397573e21cd31543e | batch_effect.py | batch_effect.py | #!/usr/bin/env python
import argparse
import csv
import shutil
import subprocess
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Chain together Inkscape extensions")
parser.add_argument('--id', type=str, action='append', dest='ids', default=[],
help=... | #!/usr/bin/env python
import csv
import optparse
import shutil
import subprocess
import sys
if __name__ == '__main__':
parser = optparse.OptionParser(description="Chain together Inkscape extensions",
usage="%prog [options] svgpath")
parser.add_option('--id', dest='ids', acti... | Make compatible with Python <2.7 | Make compatible with Python <2.7
The argparse module was added in Python 2.7, but the Python bundled
with Inkscape is 2.6. Switching to optparse makes this extension
compatible with the Python bundled with Inkscape.
| Python | mit | jturner314/inkscape-batch-effect |
25ebc324c0af6e1ce74535cc75227071637a7a18 | areaScraper.py | areaScraper.py | # Craigslist City Scraper
# By Marshall Ehlinger
# For sp2015 Systems Analysis and Design
from bs4 import BeautifulSoup
import re
fh = open("sites.htm", "r")
soup = BeautifulSoup(fh, "html.parser")
for columnDiv in soup.h1.next_sibling.next_sibling:
for state in columnDiv:
for city in state:
print(city)
#prin... | #!/usr/bin/python3.4
# Craigslist City Scraper
# By Marshall Ehlinger
# For sp2015 Systems Analysis and Design
# Returns dictionary of 'city name string' : 'site url'
# for all American cities in states/territories @ CL
from bs4 import BeautifulSoup
import re
def getCities():
fh = open("sites.htm", "r")
soup = B... | Complete site scraper for all American cities | Complete site scraper for all American cities
areaScraper.py contains the getCities() function, which will
return a dictionary of 'city name string' : 'url string'
for each Craigslist "site", corresponding to American cities,
regions, etc.
| Python | mit | MuSystemsAnalysis/craigslist_area_search,MuSystemsAnalysis/craigslist_area_search |
49a7968e51ce850428936fb2fc66c905ce8b8998 | head1stpython/Chapter3/sketch.py | head1stpython/Chapter3/sketch.py | #Import dependencies
#Load OS functions from the standard library
import os
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
#Change path for the current directory
data = open('sketch.txt')
#Start iteration over the text file
for each_line in data:
try:
... | #Import dependencies
#Load OS functions from the standard library
import os
#Change path for the current directory
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
#Check if file exists
if os.path.exists('sketch.txt'):
#Load the text file into 'data' variable
... | Validate if the file exists (if/else) | Validate if the file exists (if/else)
| Python | unlicense | israelzuniga/python-octo-wookie |
a15d1df33fece7ddeefcbeb5a8094df2ebccd7c6 | tests/test_dict_utils.py | tests/test_dict_utils.py | import unittest
from dict_utils import dict_utils
class DictUtilsTestCase(unittest.TestCase):
def test_dict_search(self):
pass
| import unittest
from dict_utils import dict_utils
class DictUtilsTestCase(unittest.TestCase):
def test_dict_search_found(self):
dict_1 = {'first_level': {'second_level': {'name': 'Joe', 'Age': 30}}}
found_value = dict_utils.dict_search_value(dict_1, 'name')
self.assertEqual(found_value, '... | Add some tests for the implemented methods | Add some tests for the implemented methods
| Python | mit | glowdigitalmedia/dict-utils |
07a8ca051b46a04df806647202144bd563d5dc5a | tests/locale_utils.py | tests/locale_utils.py |
import subprocess
"""Helper functions, decorators,... for working with locales"""
def get_avail_locales():
return {loc.strip() for loc in subprocess.check_output(["locale", "-a"]).split()}
def requires_locales(locales):
"""A decorator factory to skip tests that require unavailable locales
:param set lo... |
import subprocess
"""Helper functions, decorators,... for working with locales"""
def get_avail_locales():
return {loc.decode(errors="replace").strip() for loc in subprocess.check_output(["locale", "-a"]).split()}
def requires_locales(locales):
"""A decorator factory to skip tests that require unavailable l... | Fix checking for available locales | Fix checking for available locales
"subprocess.check" returns bytes, so we need to decode the lang
codes before comparing them with required languages.
| Python | lgpl-2.1 | rhinstaller/libbytesize,rhinstaller/libbytesize,rhinstaller/libbytesize |
e366f6da5673a4c92ffcf65492951e0c6fc886ed | tests/test_element.py | tests/test_element.py | import rml.element
def test_create_element():
e = rml.element.Element('BPM', 6.0)
assert e.get_type() == 'BPM'
assert e.get_length() == 6.0
def test_add_element_to_family():
e = rml.element.Element('dummy', 0.0)
e.add_to_family('fam')
assert 'fam' in e.get_families()
| import pkg_resources
pkg_resources.require('cothread')
import cothread
import rml.element
def test_create_element():
e = rml.element.Element('BPM', 6.0)
assert e.get_type() == 'BPM'
assert e.get_length() == 6.0
def test_add_element_to_family():
e = rml.element.Element('dummy', 0.0)
e.add_to_fami... | Test before creating the get_pv() method | Test before creating the get_pv() method
| Python | apache-2.0 | razvanvasile/RML,willrogers/pml,willrogers/pml |
0b884ed68f2c4b482f9eadbf38adc01f7d869f1a | tests/test_exports.py | tests/test_exports.py | import unittest
import websockets
import websockets.client
import websockets.exceptions
import websockets.legacy.auth
import websockets.legacy.client
import websockets.legacy.protocol
import websockets.legacy.server
import websockets.server
import websockets.typing
import websockets.uri
combined_exports = (
webs... | import unittest
import websockets
import websockets.client
import websockets.exceptions
import websockets.legacy.auth
import websockets.legacy.client
import websockets.legacy.protocol
import websockets.legacy.server
import websockets.server
import websockets.typing
import websockets.uri
combined_exports = (
webs... | Rename test class consistently with others. | Rename test class consistently with others.
| Python | bsd-3-clause | aaugustin/websockets,aaugustin/websockets,aaugustin/websockets,aaugustin/websockets |
3bbe539f387697137040f665958e0e0e27e6a420 | tests/test_session.py | tests/test_session.py | # Local imports
from uplink import session
def test_base_url(uplink_builder_mock):
# Setup
uplink_builder_mock.base_url = "https://api.github.com"
sess = session.Session(uplink_builder_mock)
# Run & Verify
assert uplink_builder_mock.base_url == sess.base_url
def test_headers(uplink_builder_mock... | # Local imports
from uplink import session
def test_base_url(uplink_builder_mock):
# Setup
uplink_builder_mock.base_url = "https://api.github.com"
sess = session.Session(uplink_builder_mock)
# Run & Verify
assert uplink_builder_mock.base_url == sess.base_url
def test_headers(uplink_builder_mock... | Fix `assert_called` usage for Python 3.5 build | Fix `assert_called` usage for Python 3.5 build
The `assert_called` method seems to invoke a bug caused by a type in the
unittest mock module. (The bug was ultimately tracked and fix here:
https://bugs.python.org/issue24656)
| Python | mit | prkumar/uplink |
cdf60bc0b07c282e75fba747c8adedd165aa0abd | index.py | index.py | #!/usr/bin/env python2.7
from werkzeug.wrappers import Request, Response
from get_html import get_html, choose_lang
@Request.application
def run(request):
lang = choose_lang(request)
if request.url.startswith("https://") or request.args.get("forcenossl") == "true":
html = get_html("launch", lang)
else:
html = ... | #!/usr/bin/env python2.7
from werkzeug.wrappers import Request, Response
from get_html import get_html, choose_lang
@Request.application
def run(request):
lang = request.args.get("lang") if request.args.get("lang") else choose_lang(request)
if request.url.startswith("https://") or request.args.get("forcenossl") == ... | Make the language changeable via a GET parameter. | Make the language changeable via a GET parameter.
| Python | mit | YtvwlD/dyluna,YtvwlD/dyluna,YtvwlD/dyluna |
8a9f707960c3b39488c9bbee6ce7f22c6fbfc853 | web/config/local_settings.py | web/config/local_settings.py | import os
from datetime import datetime
LOG_DIR = '/var/log/graphite'
if os.getenv("CARBONLINK_HOSTS"):
CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',')
if os.getenv("CLUSTER_SERVERS"):
CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',')
if os.getenv("MEMCACHE_HOSTS"):
CLUSTER_SERVERS = ... | import os
from datetime import datetime
LOG_DIR = '/var/log/graphite'
if os.getenv("CARBONLINK_HOSTS"):
CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',')
if os.getenv("CLUSTER_SERVERS"):
CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',')
if os.getenv("MEMCACHE_HOSTS"):
MEMCACHE_HOSTS = o... | Fix memcache hosts setting from env | Fix memcache hosts setting from env
Before this fix if one had set OS env vars for both CLUSTER_SERVERS and
MEMCACHE_HOSTS the value of later would override the former and the
graphite web application fails to show any metrics.
| Python | apache-2.0 | Banno/graphite-setup,Banno/graphite-setup,Banno/graphite-setup |
17224d7db16865bc735f27b1f919c6146089d4fd | vumi/dispatchers/__init__.py | vumi/dispatchers/__init__.py | """The vumi.dispatchers API."""
__all__ = ["BaseDispatchWorker", "BaseDispatchRouter", "SimpleDispatchRouter",
"TransportToTransportRouter", "ToAddrRouter",
"FromAddrMultiplexRouter", "UserGroupingRouter"]
from vumi.dispatchers.base import (BaseDispatchWorker, BaseDispatchRouter,
... | """The vumi.dispatchers API."""
__all__ = ["BaseDispatchWorker", "BaseDispatchRouter", "SimpleDispatchRouter",
"TransportToTransportRouter", "ToAddrRouter",
"FromAddrMultiplexRouter", "UserGroupingRouter",
"ContentKeywordRouter"]
from vumi.dispatchers.base import (BaseDispatchWorker, ... | Add ContentKeywordRouter to vumi.dispatchers API. | Add ContentKeywordRouter to vumi.dispatchers API.
| Python | bsd-3-clause | TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,TouK/vumi |
c7f1759ef02c0fa12ca408dfac9d25227fbceba7 | nova/policies/server_password.py | nova/policies/server_password.py | # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | Introduce scope_types in server password policy | Introduce scope_types in server password policy
oslo.policy introduced the scope_type feature which can
control the access level at system-level and project-level.
- https://docs.openstack.org/oslo.policy/latest/user/usage.html#setting-scope
- http://specs.openstack.org/openstack/keystone-specs/specs/keystone/queens... | Python | apache-2.0 | klmitch/nova,openstack/nova,klmitch/nova,openstack/nova,mahak/nova,mahak/nova,mahak/nova,klmitch/nova,klmitch/nova,openstack/nova |
0aba3f8d1131b502beff1c249e55af88115950ae | migrations/versions/20140430220209_4093ccb6d914.py | migrations/versions/20140430220209_4093ccb6d914.py | """empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
... | """empty message
Revision ID: 4093ccb6d914
Revises: None
Create Date: 2014-04-30 22:02:09.991428
"""
# revision identifiers, used by Alembic.
revision = '4093ccb6d914'
down_revision = None
from alembic import op
import sqlalchemy as sa
from datetime import datetime
def upgrade():
op.create_table('gallery',
... | Convert text columns to varchar for mysql | Convert text columns to varchar for mysql
| Python | mit | taeram/ineffable,taeram/ineffable,taeram/ineffable |
93d2e33795e240407ab7e18aec67514124ff6713 | app/__init__.py | app/__init__.py | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from instance.config import app_config
app = Flask(__name__)
def EnvironmentName(environ):
app.config.from_object(app_config[environ])
EnvironmentName('TestingConfig')
databases = SQLAlchemy(app)
from app.v1 import bucketlist
| from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from instance.config import app_config
app = Flask(__name__)
def EnvironmentName(environ):
app.config.from_object(app_config[environ])
EnvironmentName('DevelopmentEnviron')
databases = SQLAlchemy(app)
from app.v1 import bucketlist
| Change postman testing environment to development | Change postman testing environment to development
| Python | mit | paulupendo/CP-2-Bucketlist-Application |
5f1ccd3845e198495e33748b460ef6fa9858e925 | app/settings.py | app/settings.py | import os
EQ_RABBITMQ_URL = os.getenv('EQ_RABBITMQ_URL', 'amqp://admin:admin@localhost:5672/%2F')
EQ_RABBITMQ_QUEUE_NAME = os.getenv('EQ_RABBITMQ_QUEUE_NAME', 'eq-submissions')
EQ_RABBITMQ_TEST_QUEUE_NAME = os.getenv('EQ_RABBITMQ_TEST_QUEUE_NAME', 'eq-test')
EQ_PRODUCTION = os.getenv("EQ_PRODUCTION", 'True')
EQ_RRM_P... | import os
EQ_RABBITMQ_URL = os.getenv('EQ_RABBITMQ_URL', 'amqp://admin:admin@localhost:5672/%2F')
EQ_RABBITMQ_QUEUE_NAME = os.getenv('EQ_RABBITMQ_QUEUE_NAME', 'eq-submissions')
EQ_RABBITMQ_TEST_QUEUE_NAME = os.getenv('EQ_RABBITMQ_TEST_QUEUE_NAME', 'eq-test')
EQ_PRODUCTION = os.getenv("EQ_PRODUCTION", 'True')
EQ_RRM_P... | Make sure there is a default for LOG Group | Make sure there is a default for LOG Group
| Python | mit | ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner |
257d3bf6cee059de50872cd02b682e1a05d467e9 | phylocommons/get_treestore.py | phylocommons/get_treestore.py | from treestore import Treestore
import settings
def get_treestore():
return Treestore(**settings.TREESTORE_KWARGS)
def uri_from_tree_id(tree_id):
return (settings.TREE_URI + tree_id)
def tree_id_from_uri(uri):
if uri.startswith(settings.TREE_URI):
uri = uri.replace(settings.TREE_URI, '', 1)
... | from treestore import Treestore
import settings
def get_treestore():
return Treestore(**settings.TREESTORE_KWARGS)
def uri_from_tree_id(tree_id):
return Treestore.uri_from_id(tree_id, base_uri=settings.TREE_URI)
def tree_id_from_uri(uri):
if uri.startswith(settings.TREE_URI):
uri = uri.replace(s... | Use treestore to get URIs from IDs. | Use treestore to get URIs from IDs.
| Python | mit | NESCent/phylocommons,NESCent/phylocommons |
853dc6b254c66807fd6c44b374c89b90069f55b5 | Lib/test/test_startfile.py | Lib/test/test_startfile.py | # Ridiculously simple test of the os.startfile function for Windows.
#
# empty.vbs is an empty file (except for a comment), which does
# nothing when run with cscript or wscript.
#
# A possible improvement would be to have empty.vbs do something that
# we can detect here, to make sure that not only the os.startfile()
#... | # Ridiculously simple test of the os.startfile function for Windows.
#
# empty.vbs is an empty file (except for a comment), which does
# nothing when run with cscript or wscript.
#
# A possible improvement would be to have empty.vbs do something that
# we can detect here, to make sure that not only the os.startfile()
#... | Change the import statement so that the test is skipped when os.startfile is not present. | Change the import statement so that the test is skipped when
os.startfile is not present.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
4a5ea880b77e44fa20129e6195cf37d5d72427f3 | webpay/model/model.py | webpay/model/model.py | import json
class Model:
def __init__(self, client, data, conversion = None):
self._client = client
self._data = data
for k, v in data.items():
if conversion is None:
self.__dict__[k] = v
else:
conv = conversion(k)
sel... | import json
class Model:
def __init__(self, client, data, conversion = None):
self._client = client
self._data = data
for k, v in data.items():
if conversion is None:
self.__dict__[k] = v
else:
conv = conversion(k)
sel... | Use type's module and name to show full class path correctly | Use type's module and name to show full class path correctly
| Python | mit | yamaneko1212/webpay-python |
9e22082a280babb1e0880fe24fa17c45aac09515 | docker-nodev.py | docker-nodev.py |
from __future__ import print_function
import subprocess
import sys
DOCKER_CREATE_IN = 'docker create -it nodev {}'
DOCKER_SIMPLE_CMD_IN = 'docker {} {container_id}'
def nodev(argv=()):
container_id = subprocess.check_output(DOCKER_CREATE_IN.format(' '.join(argv)), shell=True).strip()
print('creating conta... |
from __future__ import print_function
import subprocess
import sys
DOCKER_CREATE_IN = 'docker create -it nodev {}'
DOCKER_SIMPLE_CMD_IN = 'docker {} {container_id}'
def nodev(argv=()):
container_id = subprocess.check_output(DOCKER_CREATE_IN.format(' '.join(argv)), shell=True).decode('utf-8').strip()
print... | Fix python3 crash and cleaner error reporting. | Fix python3 crash and cleaner error reporting.
| Python | mit | nodev-io/nodev-starter-kit,nodev-io/nodev-tutorial,nodev-io/nodev-starter-kit |
87bb90370b8d7439989072ae17634dd30276f24c | yanico/config.py | yanico/config.py | # Copyright 2015-2016 Masayuki Yamamoto
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | # Copyright 2015-2016 Masayuki Yamamoto
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | Add docstring into load function | Add docstring into load function
Describe which file parse at least.
| Python | apache-2.0 | ma8ma/yanico |
3ce0aef8d546f83485c1048dac9e9524f2501552 | src/wagtail_personalisation/blocks.py | src/wagtail_personalisation/blocks.py | from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from wagtail.core import blocks
from wagtail_personalisation.adapters import get_segment_adapter
from wagtail_personalisation.models import Segment
def list_segment_choices():
for pk, name in Segment... | from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from wagtail.core import blocks
from wagtail_personalisation.adapters import get_segment_adapter
from wagtail_personalisation.models import Segment
def list_segment_choices():
yield -1, ("Show to eve... | Add an option to show a personalised block to everyone | Add an option to show a personalised block to everyone
| Python | mit | LabD/wagtail-personalisation,LabD/wagtail-personalisation,LabD/wagtail-personalisation |
cbeabd95e172ae213a3e95f2285b4ccc00a80254 | src/you_get/extractors/dailymotion.py | src/you_get/extractors/dailymotion.py | #!/usr/bin/env python
__all__ = ['dailymotion_download']
from ..common import *
def dailymotion_download(url, output_dir = '.', merge = True, info_only = False):
"""Downloads Dailymotion videos by URL.
"""
html = get_content(url)
info = json.loads(match1(html, r'qualities":({.+?}),"'))
title = m... | #!/usr/bin/env python
__all__ = ['dailymotion_download']
from ..common import *
def dailymotion_download(url, output_dir = '.', merge = True, info_only = False):
"""Downloads Dailymotion videos by URL.
"""
html = get_content(url)
info = json.loads(match1(html, r'qualities":({.+?}),"'))
title = m... | Fix problems with videos that do not have 720p mode | Fix problems with videos that do not have 720p mode
| Python | mit | linhua55/you-get,jindaxia/you-get,qzane/you-get,cnbeining/you-get,zmwangx/you-get,linhua55/you-get,Red54/you-get,lilydjwg/you-get,xyuanmu/you-get,qzane/you-get,zmwangx/you-get,lilydjwg/you-get,smart-techs/you-get,specter4mjy/you-get,xyuanmu/you-get,smart-techs/you-get,cnbeining/you-get |
62c51799953c1299e7c89c61a23270bf55e9cd69 | PortalEnrollment/models.py | PortalEnrollment/models.py | from django.db import models
# Create your models here.
| from django.db import models
from Portal.models import CharacterAttribute
from django.utils.translation import ugettext as _
# Create your models here.
class Enrollment(models.Model):
roles = models.ManyToManyField(_('Role'), CharacterAttribute)
open = models.BooleanField(_('Open Enrollment'), default=False)
... | Add first model for Enrollment application | Add first model for Enrollment application
| Python | mit | elryndir/GuildPortal,elryndir/GuildPortal |
2896d1d0507ac312ab6246c3ccb33bbb6bc6d331 | bluebottle/common/management/commands/makemessages.py | bluebottle/common/management/commands/makemessages.py | import json
import codecs
import tempfile
from django.core.management.commands.makemessages import Command as BaseCommand
class Command(BaseCommand):
""" Extend the makemessages to include some of the fixtures """
fixtures = [
('bb_projects', 'project_data.json'),
('bb_tasks', 'skills.json'),... | import json
import codecs
import tempfile
from django.core.management.commands.makemessages import Command as BaseCommand
class Command(BaseCommand):
""" Extend the makemessages to include some of the fixtures """
fixtures = [
('bb_projects', 'project_data.json'),
('bb_tasks', 'skills.json'),... | Add a context to the fixture translations | Add a context to the fixture translations
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle |
cea2d67bf2f806c295a6c03894efa5c8bc0644a1 | steamplaytime/app.py | steamplaytime/app.py | class App(object):
def __init__(self, ID, name):
self.ID = ID
self.name = name
self.date = []
self.minutes = []
self.last_day = []
def id_str(self):
return str(self.ID)
def get_db_playtime(self, cursor):
query = 'SELECT time_of_record, minutes_played... | class App(object):
def __init__(self, ID, name):
self.ID = ID
self.name = name
self.date = []
self.minutes = []
self.last_day = []
def id_str(self):
return str(self.ID)
def get_db_playtime(self, cursor):
query = 'SELECT time_of_record, minutes_played... | Fix abnormally big spikes in graph | FIX: Fix abnormally big spikes in graph
| Python | mit | fsteffek/steamplog |
675f5a269859f1e38419b23a82b732f22f858b74 | setup.py | setup.py | from distutils.core import setup
setup(
name="sqlite_object",
version="0.3.3",
author_email="luke@hospadaruk.org",
description="sqlite-backed collection objects",
author="Luke Hospadaruk",
url="https://github.com/hospadar/sqlite_object",
packages=["sqlite_object"],
)
| from distutils.core import setup
setup(
name="sqlite_object",
version="0.3.3",
author_email="matt@genges.com",
description="sqlite-backed collection objects",
author="Matt Stancliff via originally Luke Hospadaruk",
url="https://github.com/mattsta/sqlite_object",
packages=["sqlite_object"],
... | Update package details to point to my repo | Update package details to point to my repo
Is this right? I guess it's right since I'm taking over
responsibility for this fork. Would be nice if the package
ecosystem had a full "history of ownership" feature instead
of just overwriting everything in your own name?
| Python | mit | hospadar/sqlite_object |
8e14f3a7d40d386185d445afc18e6add57cd107e | LR/lr/lib/helpers.py | LR/lr/lib/helpers.py | """Helper functions
Consists of functions to typically be used within templates, but also
available to Controllers. This module is available to templates as 'h'.
"""
# Import helpers as desired, or define your own, ie:
#from webhelpers.html.tags import checkbox, password
def importModuleFromFile(fullpath):
"""Load... |
from datetime import datetime
import time
"""Helper functions
Consists of functions to typically be used within templates, but also
available to Controllers. This module is available to templates as 'h'.
"""
# Import helpers as desired, or define your own, ie:
#from webhelpers.html.tags import checkbox, password
def ... | Add Method the return time now in complete UTC iso complete format | Add Method the return time now in complete UTC iso complete format
| Python | apache-2.0 | jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,jimklo... |
9e9256a65afa8569950ca344b3d074afcd6293c5 | flocker/cli/test/test_deploy_script.py | flocker/cli/test/test_deploy_script.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Unit tests for the implementation ``flocker-deploy``.
"""
from twisted.trial.unittest import TestCase, SynchronousTestCase
from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin
from ..script import DeployScript, DeployOptions
cl... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Unit tests for the implementation ``flocker-deploy``.
"""
from twisted.trial.unittest import TestCase, SynchronousTestCase
from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin
from ..script import DeployScript, DeployOptions
cl... | Test for a deferred result of DeployScript.main | Test for a deferred result of DeployScript.main
| Python | apache-2.0 | moypray/flocker,LaynePeng/flocker,1d4Nf6/flocker,LaynePeng/flocker,AndyHuu/flocker,hackday-profilers/flocker,LaynePeng/flocker,agonzalezro/flocker,achanda/flocker,agonzalezro/flocker,Azulinho/flocker,adamtheturtle/flocker,beni55/flocker,agonzalezro/flocker,mbrukman/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,... |
16c0a0341ad61b164b5d2bf750b6f5319c74b245 | refresh_html.py | refresh_html.py | import os
template_header = """<html>
<head><title>Littlefield Charts</title></head>
<body>
<table>"""
template_footer = """</table>
<p><a href="production.csv">Download production data</a></p>
<p><a href="rankings.csv">Download latest rankings</a></p>
</body>
</html>"""
root = os.path.abspath(os.path.dirname(__file... | import datetime
import os
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
template_header = """<html>
<head><title>Littlefield Charts</title></head>
<body>
<p>Data last collected: %s</p>
<table>""" % now
template_footer = """</table>
<p><a href="production.csv">Download production data</a></p>
<p><a href... | Add current date to generated HTML | Add current date to generated HTML
| Python | mit | eallrich/littlefield,eallrich/littlefield |
c2fb76dfa3b6b7a7723bb667a581c6f583710d89 | lsync/templates.py | lsync/templates.py | #!/usr/bin/python
settings = """settings = {
logfile = "/var/log/lsyncd/lsyncd.log",
statusFile = "/var/log/lsyncd/lsyncd-status.log",
statusInterval = 5,
pidfile = "/var/run/lsyncd.pid"
}
"""
sync = """sync{
default.rsync,
source="%(source)s",
target="%(target)s",
rsyn... | #!/usr/bin/python
settings = """-- This file is now generated by a simple config generator.
-- Just run http://github.com/rcbau/hacks/lsync/generator.py from the
-- /etc/lsync directory and pipe the output to /etc/lsync/lsyncd.conf.lua
settings = {
logfile = "/var/log/lsyncd/lsyncd.log",
statusFile = "/var/l... | Add a simple block comment explaining what happens. | Add a simple block comment explaining what happens.
| Python | apache-2.0 | rcbau/hacks,rcbau/hacks,rcbau/hacks |
ad1e635688dffe5a5ba3f7f30f31d804f695d201 | string/anagram.py | string/anagram.py | # Return true if two strings are anagrams of one another
def is_anagram(str_one, str_two):
# lower case both strings to account for case insensitivity
a = str_one.lower()
b = str_two.lower()
# convert strings into lists and sort each
a = list(a).sort()
b = list(b).sort()
# convert lists back into strings
a =... | # Return true if two strings are anagrams of one another
def is_anagram(str_one, str_two):
# lower case both strings to account for case insensitivity
a = str_one.lower()
b = str_two.lower()
# convert strings into lists and sort each
a = list(a)
b = list(b)
# sort lists
a.sort()
b.sort()
# consolidate lis... | Debug and add test cases | Debug and add test cases
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep |
1bc61edde0e41ec3f2fe66758654b55ed51ec36a | test/test_repo.py | test/test_repo.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from asv import config
from asv import repo
def test_repo(tmpdir):
conf = config.Config()
conf.pro... | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from asv import config
from asv import repo
def _test_generic_repo(conf,
hash_range=... | Add test for mercurial repo | Add test for mercurial repo
| Python | bsd-3-clause | pv/asv,waylonflinn/asv,airspeed-velocity/asv,pv/asv,qwhelan/asv,mdboom/asv,waylonflinn/asv,waylonflinn/asv,ericdill/asv,giltis/asv,ericdill/asv,airspeed-velocity/asv,mdboom/asv,qwhelan/asv,giltis/asv,airspeed-velocity/asv,qwhelan/asv,edisongustavo/asv,mdboom/asv,spacetelescope/asv,edisongustavo/asv,ericdill/asv,pv/asv,... |
f668f6066864b1efe3863cdb43b8fee4e08a312b | test/test_mk_dirs.py | test/test_mk_dirs.py | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_makevers import create_update_dir
import os
def test_mk_dirs(create_update_dir):
"""Test that ensures that downlaods directory is created properly"""
assert not os.path.isdir(Launcher.updatedir)
... | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_makevers import create_update_dir
import os
def test_mk_dirs(create_update_dir):
"""Test that ensures that downlaods directory is created properly"""
assert not os.path.isdir(Launcher.updatedir)
... | Remove Launcher.updatedir after mkdirs test | Remove Launcher.updatedir after mkdirs test
Should go into fixture later
| Python | lgpl-2.1 | rlee287/pyautoupdate,rlee287/pyautoupdate |
b5d812504924af2e2781f4be63a6191e5c47879d | test_project/urls.py | test_project/urls.py | """test_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... | """test_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... | Support multiple templates in TEST_TEMPLATES setting. | Support multiple templates in TEST_TEMPLATES setting.
Unit tests need to be able to test redirects and other features
involving multiple web pages. This commit changes the singleton
TEST_TEMPLATE setting to TEST_TEMPLATES, which is a list of
path, template tuples.
| Python | bsd-3-clause | nimbis/django-selenium-testcase,nimbis/django-selenium-testcase |
d0b2b0aa3674fb6b85fd788e88a3a54f4cc22046 | pytablewriter/_excel_workbook.py | pytablewriter/_excel_workbook.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import xlsxwriter
class ExcelWorkbookXlsx(object):
@property
def workbook(self):
return self.__workbook
@property
def file_path(self):
return self.__file_path
... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import abc
import six
import xlsxwriter
@six.add_metaclass(abc.ABCMeta)
class ExcelWorkbookInterface(object):
@abc.abstractproperty
def workbook(self):
pass
@abc.abstractpr... | Add an interface class and a base class of for Excel Workbook | Add an interface class and a base class of for Excel Workbook
| Python | mit | thombashi/pytablewriter |
15c474fb25479f044e0199a26e5f0ec95c2bb0ec | tests/test_api.py | tests/test_api.py | import json
def test_get_user_list(client, user):
response = client.get("/api/v1/users")
user_list = json.loads(str(response.data))
user_data = user_list["data"][0]
assert user_data["github_name"] == user.github_name
assert user_data["github_url"] == user.github_url
def test_get_user(client, use... | import json
def test_get_user_list(client, user):
response = client.get("/api/v1/users")
user_list = json.loads(response.get_data().decode("utf-8"))
user_data = user_list["data"][0]
assert user_data["github_name"] == user.github_name
assert user_data["github_url"] == user.github_url
def test_get... | Fix tests to correctly decode utf-8 bytestrings. | Fix tests to correctly decode utf-8 bytestrings.
| Python | mit | PythonClutch/python-clutch,PythonClutch/python-clutch,PythonClutch/python-clutch |
9247021be1dc60acd11104ec1de04ea5718c054c | tests/test_config.py | tests/test_config.py | import sys
import unittest
from skeletor.config import Config
from .helpers import nostdout
class ConfigTests(unittest.TestCase):
""" Argument Passing & Config Tests. """
def setUp(self):
self._old_sys_argv = sys.argv
sys.argv = [self._old_sys_argv[0].replace('nosetests', 'skeletor')]
... | import sys
import unittest
from skeletor.config import Config
from .helpers import nostdout
class ConfigTests(unittest.TestCase):
""" Argument Passing & Config Tests. """
def setUp(self):
self._old_sys_argv = sys.argv
sys.argv = [self._old_sys_argv[0].replace('nosetests', 'skeletor')]
... | Test for valid and invalid project names | Test for valid and invalid project names
| Python | bsd-3-clause | krak3n/Facio,krak3n/Facio,krak3n/Facio,krak3n/Facio,krak3n/Facio |
fc91e70bfa2d46ce923cdd3e2f2d591f8a5b367b | tests/test_person.py | tests/test_person.py | import unittest
from classes.person import Person
class PersonClassTest(unittest.TestCase):
pass
# def test_add_person_successfully(self):
# my_class_instance = Person()
# initial_person_count = len(my_class_instance.all_persons)
# staff_neil = my_class_instance.add_person("Neil Armstr... | import unittest
from classes.person import Person
class PersonClassTest(unittest.TestCase):
def test_full_name_only_returns_strings(self):
with self.assertRaises(ValueError, msg='Only strings are allowed as names'):
my_class_instance = Person("staff", "Peter", "Musonye")
my_class_i... | Add tests for class Person | Add tests for class Person
| Python | mit | peterpaints/room-allocator |
a98b8e78d48ce28e63ed0be2a9dbc008cc21ba97 | pi_broadcast_service/rabbit.py | pi_broadcast_service/rabbit.py | import json
import pika
class Publisher(object):
def __init__(self, rabbit_url, exchange):
self._rabbit_url = rabbit_url
self._exchange = exchange
self._connection = pika.BlockingConnection(pika.URLParameters(self._rabbit_url))
self._channel = self._connection.channel()
def s... | import json
import pika
class Publisher(object):
def __init__(self, rabbit_url, exchange):
self._rabbit_url = rabbit_url
self._exchange = exchange
self._connection = pika.BlockingConnection(pika.URLParameters(self._rabbit_url))
self._channel = self._connection.channel()
def s... | Add a stop method to base class | Add a stop method to base class
| Python | mit | projectweekend/Pi-Broadcast-Service |
3964606d6f0e28b127af57b1d13c12b3352f861a | ggd/__main__.py | ggd/__main__.py | import sys
import argparse
from .__init__ import __version__
from . make_bash import add_make_bash
from . check_recipe import add_check_recipe
from . list_files import add_list_files
from . search import add_search
from . show_env import add_show_env
def main(args=None):
if args is None:
args = sys.argv[1:... | import sys
import argparse
from .__init__ import __version__
from . make_bash import add_make_bash
from . check_recipe import add_check_recipe
from . list_files import add_list_files
from . search import add_search
from . show_env import add_show_env
from . install import add_install
from . uninstall import add_uninsta... | Add installer and uninstaller to main | Add installer and uninstaller to main
| Python | mit | gogetdata/ggd-cli,gogetdata/ggd-cli |
ca94513b3487232a2f9714ddc129d141c011b4af | dadd/master/admin.py | dadd/master/admin.py | from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
from dadd.master import models
class ProcessModelView(ModelView):
# Make the latest first
column_default_sort = ('start_time', True)
def __init__(self, session):
super(ProcessModelView, self).__init__(models.Pro... | from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
from dadd.master import models
class ProcessModelView(ModelView):
# Make the latest first
column_default_sort = ('start_time', True)
def __init__(self, session):
super(ProcessModelView, self).__init__(models.Pro... | Sort the logfile by added time. | Sort the logfile by added time.
| Python | bsd-3-clause | ionrock/dadd,ionrock/dadd,ionrock/dadd,ionrock/dadd |
5cfb7a1b0feca5cd33f93447cfc43c1c944d4810 | tests/test_dragon.py | tests/test_dragon.py | import pytest
from mugloar import dragon
def test_partition():
for solution in dragon.partition(20, 4, 0, 10):
print(solution)
assert abs(solution[0]) + abs(solution[1]) + abs(solution[2]) + abs(solution[3]) == 20
| import pytest
from mugloar import dragon
@pytest.fixture
def dragon_instance():
return dragon.Dragon()
@pytest.fixture
def knight():
return [('endurance', 8), ('attack', 5), ('armor', 4), ('agility', 3)]
@pytest.fixture
def dragon_stats():
return 10, 10, 0, 0
def test_set_relative_stats(dragon_insta... | Implement rudimentary unit tests for dragon class | Implement rudimentary unit tests for dragon class
| Python | mit | reinikai/mugloar |
3afe14ee6beb1a3177d929bacb20b3c4bb9363d7 | tests/test_parser.py | tests/test_parser.py | import unittest
from xhtml2pdf.parser import pisaParser
from xhtml2pdf.context import pisaContext
_data = b"""
<!doctype html>
<html>
<title>TITLE</title>
<body>
BODY
</body>
</html>
"""
class TestCase(unittest.TestCase):
def testParser(self):
c = pisaContext(".")
r = pisaParser(_data, c)
... | import unittest
from xhtml2pdf.parser import pisaParser
from xhtml2pdf.context import pisaContext
_data = b"""
<!doctype html>
<html>
<title>TITLE</title>
<body>
BODY
</body>
</html>
"""
class TestCase(unittest.TestCase):
def testParser(self):
c = pisaContext(".")
r = pisaParser(_data, c)
... | Add tests for base64 image | Add tests for base64 image
| Python | apache-2.0 | trib3/xhtml2pdf,chrisglass/xhtml2pdf,jensadne/xhtml2pdf,tinjyuu/xhtml2pdf,xhtml2pdf/xhtml2pdf,orbitvu/xhtml2pdf,chrisglass/xhtml2pdf,trib3/xhtml2pdf,tinjyuu/xhtml2pdf,orbitvu/xhtml2pdf,jensadne/xhtml2pdf,xhtml2pdf/xhtml2pdf |
432233a99d9036f358716b48a0e26054a7e217bf | SlugifyCommand.py | SlugifyCommand.py | # encoding: utf-8
'''This adds a "slugify" command to be invoked by Sublime Text. It is made
available as "Slugify" in the command palette by Default.sublime-commands.
Parts of these commands are borrowed from the sublime-slug package:
https://github.com/madeingnecca/sublime-slug
'''
from __future__ import unicode_li... | # encoding: utf-8
'''This adds a "slugify" command to be invoked by Sublime Text. It is made
available as "Slugify" in the command palette by Default.sublime-commands.
Parts of these commands are borrowed from the sublime-slug package:
https://github.com/madeingnecca/sublime-slug
'''
from __future__ import unicode_li... | Fix broken plugin on Windows. | Fix broken plugin on Windows.
| Python | mit | alimony/sublime-slugify |
c347e6e763b79a9c4af6d7776093ce9ed711c43d | monkeys/release.py | monkeys/release.py | from invoke import task, run
@task
def makerelease(ctx, version, local_only=False):
if not version:
raise Exception("You must specify a version!")
# FoodTruck assets.
print("Update node modules")
run("npm install")
print("Generating Wikked assets")
run("gulp")
if not local_only:
... | from invoke import task, run
@task
def makerelease(ctx, version, local_only=False):
if not version:
raise Exception("You must specify a version!")
# FoodTruck assets.
print("Update node modules")
run("npm install")
print("Generating Wikked assets")
run("gulp")
if not local_only:
... | Use `twine` to deploy Wikked to Pypi. | cm: Use `twine` to deploy Wikked to Pypi.
| Python | apache-2.0 | ludovicchabant/Wikked,ludovicchabant/Wikked,ludovicchabant/Wikked |
cbe447825408d7178e1b4eb4bf981600001ada32 | rymtracks/services/archiveorg.py | rymtracks/services/archiveorg.py | # -*- coding: utf-8 -*-
"""
This module contains Service implementation of Archive.org.
http://archive.org
"""
from . import Service, JSONMixin
from six import text_type
from tornado.httpclient import HTTPRequest
##############################################################################
class ArchiveOrg(JSON... | # -*- coding: utf-8 -*-
"""
This module contains Service implementation of Archive.org.
http://archive.org
"""
from . import Service, JSONMixin
from six import text_type
from tornado.httpclient import HTTPRequest
##############################################################################
class ArchiveOrg(JSON... | Put weaker requirements on Archive.org service | Put weaker requirements on Archive.org service
| Python | mit | 9seconds/rymtracks |
bcb383612625d9a59f9e5b4174e44700b26bd0e5 | crosscompute/macros/security.py | crosscompute/macros/security.py | from datetime import datetime, timedelta
from invisibleroads_macros_security import make_random_string
class DictionarySafe(dict):
def __init__(self, key_length):
self.key_length = key_length
def put(self, value, time_in_seconds=None):
while True:
key = make_random_string(self.k... | from datetime import datetime, timedelta
from invisibleroads_macros_security import make_random_string
class DictionarySafe(dict):
def __init__(self, key_length):
self.key_length = key_length
def put(self, value, time_in_seconds=None):
while True:
key = make_random_string(self.k... | Support case when expiration_datetime is None | Support case when expiration_datetime is None
| Python | mit | crosscompute/crosscompute,crosscompute/crosscompute,crosscompute/crosscompute,crosscompute/crosscompute |
4bcb7efc2c95280323995cb0de27cf6449f060b8 | external_tools/src/main/python/images/common.py | external_tools/src/main/python/images/common.py | #!/usr/bin/python
splitString='images/clean/impc/' | #!/usr/bin/python
#splitString='images/clean/impc/'
splitString='images/holding_area/impc/'
| Change to use holding_area directory | Change to use holding_area directory
| Python | apache-2.0 | mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData |
7db970b508c9d7ea3d659fe8b2fa5a852f16abd1 | tcconfig/_common.py | tcconfig/_common.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import dataproperty
import six
from ._error import NetworkInterfaceNotFoundError
def verify_network_interface(device):
try:
import netifaces
except ImportError:
return
... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import dataproperty
import six
from ._error import NetworkInterfaceNotFoundError
def verify_network_interface(device):
try:
import netifaces
except ImportError:
return
... | Add special case for "anywhere" | Add special case for "anywhere"
| Python | mit | thombashi/tcconfig,thombashi/tcconfig |
9495a43e0797d1a089df644663900957cadc3ac0 | tests/agents_tests/test_iqn.py | tests/agents_tests/test_iqn.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
from builtins import * # NOQA
standard_library.install_aliases() # NOQA
import chainer.functions as F
import chainer.links as L
imp... | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
from builtins import * # NOQA
standard_library.install_aliases() # NOQA
import chainer.functions as F
import chainer.links as L
from... | Test multiple values of N and N_prime | Test multiple values of N and N_prime
| Python | mit | toslunar/chainerrl,toslunar/chainerrl |
eaa3d6094c92eb17f5074279a0c23ec363cddd1b | rnacentral/portal/models/secondary_structure.py | rnacentral/portal/models/secondary_structure.py | """
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | """
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | Use OneToOneField on SecondaryStructure model | Use OneToOneField on SecondaryStructure model
| Python | apache-2.0 | RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode |
5743d7cfbc93b1c806e8f0a38d8000b82445810b | __init__.py | __init__.py | """
Python Bayesian hierarchical clustering (PyBHC).
Heller, K. A., & Ghahramani, Z. (2005). Bayesian Hierarchical
Clustering. Neuroscience, 6(section 2), 297-304.
doi:10.1145/1102351.1102389
"""
from bhc import bhc
from dists import NormalInverseWishart
| """
Python Bayesian hierarchical clustering (PyBHC).
Heller, K. A., & Ghahramani, Z. (2005). Bayesian Hierarchical
Clustering. Neuroscience, 6(section 2), 297-304.
doi:10.1145/1102351.1102389
"""
from bhc import bhc
from dists import NormalInverseWishart, NormalFixedCovar
from rbhc import rbhc
| Update importing of prob dists | Update importing of prob dists
Import the newly created fixed variance probability dist into
__init__.py for easier use outside of module.
| Python | bsd-3-clause | stuartsale/pyBHC |
69d3ec01ec3e9e9369b5c0425bc63cc7f2797b52 | __init__.py | __init__.py | import pyOmicron
import STS
__all__=["pyOmicron","STS"]
__version__ = 0.1
| import pyOmicron
try:
import STS
except:
import pyOmicron.STS
__all__=["pyOmicron","STS"]
__version__ = 0.1
| Fix import for python 3 | Fix import for python 3
| Python | apache-2.0 | scholi/pyOmicron |
c1acb68ef54309584816fbf5c93e38266accb2f0 | nova/db/sqlalchemy/session.py | nova/db/sqlalchemy/session.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | Add the pool_recycle setting to enable connection pooling features for the sql engine. The setting is hard-coded to 3600 seconds (one hour) per the recommendation provided on sqlalchemy's site | Add the pool_recycle setting to enable connection pooling features for the sql engine. The setting is hard-coded to 3600 seconds (one hour) per the recommendation provided on sqlalchemy's site | Python | apache-2.0 | qwefi/nova,tanglei528/nova,houshengbo/nova_vmware_compute_driver,SUSE-Cloud/nova,gooddata/openstack-nova,gspilio/nova,TwinkleChawla/nova,felixma/nova,viggates/nova,TieWei/nova,varunarya10/nova_test_latest,Yusuke1987/openstack_template,eonpatapon/nova,ruslanloman/nova,petrutlucian94/nova_dev,fajoy/nova,gooddata/openstac... |
13fec51e6fa3f47d2f3669e789e9d432e092944a | celeryconfig.py | celeryconfig.py | from datetime import timedelta
from private import CELERY_BROKER_URL, CELERY_RESULT_BACKEND
BROKER_URL = CELERY_BROKER_URL
CELERY_RESULT_BACKEND = CELERY_RESULT_BACKEND
CELERY_TIMEZONE = 'UTC'
CELERY_INCLUDE = ['tasks.scraper_task']
CELERYBEAT_SCHEDULE = {
'scrape_users': {
'task': 'tasks.scraper_task.... | from datetime import timedelta
from private import CELERY_BROKER_URL, CELERY_RESULT_BACKEND
#-------------------------------------------------------------------------------
BROKER_URL = CELERY_BROKER_URL
CELERY_RESULT_BACKEND = CELERY_RESULT_BACKEND
#------------------------------------------------------... | Use json for task serialization | Use json for task serialization
| Python | mit | Trinovantes/MyAnimeList-Cover-CSS-Generator,Trinovantes/MyAnimeList-Cover-CSS-Generator |
bdeb1196025c8f982390f0f298fa8b16b1883bce | mediaman/management/commands/generate_thumbs.py | mediaman/management/commands/generate_thumbs.py | from django.core.management.base import BaseCommand
import easy_thumbnails
from mediaman.models import ArtefactRepresentation
import os
class Command(BaseCommand):
help = "Generate thumbnails for Artefact Representations"
def handle(self, *args, **options):
unbuffered = os.fdopen(self.stdout.fileno()... | from django.core.management.base import BaseCommand
import easy_thumbnails
from mediaman.models import ArtefactRepresentation
import os
#import ImageFile
from PIL import ImageFile
class Command(BaseCommand):
help = "Generate thumbnails for Artefact Representations"
def handle(self, *args, **options):
... | Update bulk image generation command | Update bulk image generation command
| Python | bsd-3-clause | uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam |
07ea0d8ec5c65f0fc94dc29f8b03402c571d3a42 | qipipe/interfaces/fix_dicom.py | qipipe/interfaces/fix_dicom.py | import os
from nipype.interfaces.base import (BaseInterface, BaseInterfaceInputSpec, traits,
InputMultiPath, File, Directory, TraitedSpec)
from qipipe.staging.fix_dicom import fix_dicom_headers
class FixDicomInputSpec(BaseInterfaceInputSpec):
collection = traits.Str(desc='The image collection', mandatory=True)... | import os
from nipype.interfaces.base import (BaseInterface, BaseInterfaceInputSpec, traits,
InputMultiPath, File, Directory, TraitedSpec)
from qipipe.staging.fix_dicom import fix_dicom_headers
class FixDicomInputSpec(BaseInterfaceInputSpec):
collection = traits.Str(desc='The image collection', mandatory=True)... | Fix only one file at a time. | Fix only one file at a time.
| Python | bsd-2-clause | ohsu-qin/qipipe |
ee8f04c2e68eddad48db3907d1d5e4ecc5daa4a4 | Functions/Conversation.py | Functions/Conversation.py | from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from Function import Function
from GlobalVars import *
import re
class Instantiate(Function):
Help = 'Responds to greetings and such'
def GetResponse(self, message):
if message.Type != 'PRIVMSG':
... | from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from Function import Function
from GlobalVars import *
import re
class Instantiate(Function):
Help = 'Responds to greetings and such'
def GetResponse(self, message):
if message.Type != 'PRIVMSG':
... | Add more greetings to the needs-multilining regex | Add more greetings to the needs-multilining regex | Python | mit | MatthewCox/PyMoronBot,Heufneutje/PyMoronBot,DesertBot/DesertBot |
8808fe8a4d3a8cf36a91fe69b2d1002eddc534a3 | py/garage/garage/startups/sql.py | py/garage/garage/startups/sql.py | """Template of DbEngineComponent."""
__all__ = [
'make_db_engine_component',
]
import logging
import garage.sql.sqlite
from garage import components
from garage.startups.logging import LoggingComponent
def make_db_engine_component(
*,
package_name,
argument_group,
argument_prefi... | __all__ = [
'make_db_engine_component',
]
import logging
import garage.sql.sqlite
from garage import components
from garage.startups.logging import LoggingComponent
def make_db_engine_component(
*, package_name,
argument_group, argument_prefix,
check_same_thread=False):
"""DbEngineCo... | Add check_same_thread argument to make_db_engine_component | Add check_same_thread argument to make_db_engine_component
| Python | mit | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage |
5124e59cf6bb264da6d58043e068b63647685167 | accounts/tests.py | accounts/tests.py | """accounts app unittests
"""
from django.test import TestCase
from django.contrib.auth import get_user_model
from accounts.models import LoginToken
TEST_EMAIL = 'newvisitor@example.com'
class WelcomePageTest(TestCase):
"""Tests relating to the welcome_page view.
"""
def test_uses_welcome_template(se... | """accounts app unittests
"""
from time import sleep
from django.contrib.auth import get_user_model
from django.test import TestCase
from accounts.token import LoginTokenGenerator
TEST_EMAIL = 'newvisitor@example.com'
class WelcomePageTest(TestCase):
"""Tests relating to the welcome_page view.
"""
de... | Update test to not use a db model | Update test to not use a db model
| Python | mit | randomic/aniauth-tdd,randomic/aniauth-tdd |
74a5cad21fb726384ab53f2ca9b711cc8298bfb9 | accounts/tests.py | accounts/tests.py | """accounts app unittests
"""
from django.test import TestCase
class WelcomePageTest(TestCase):
def test_uses_welcome_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'accounts/welcome.html')
| """accounts app unittests
"""
from django.test import TestCase
class WelcomePageTest(TestCase):
"""Tests relating to the welcome_page view.
"""
def test_uses_welcome_template(self):
"""The root url should response with the welcome page template.
"""
response = self.client.get('/... | Add docstrings to unit test | Add docstrings to unit test
| Python | mit | randomic/aniauth-tdd,randomic/aniauth-tdd |
268976034ad508c2ef48dec60da40dec57af824f | setup.py | setup.py | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = "DragonCreole",
packages = ["dragoncreole"],
version = "0.1.0",
description = "Optimized parser for creole-like markup language",
author = "Zauber Paracelsus",
author_email = "admin@zau... | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = "DragonCreole",
packages = ["dragoncreole"],
version = "0.1.0",
description = "Optimized parser for creole-like markup language",
author = "Zauber Paracelsus",
author_email = "admin@zau... | Tweak for building with cython | Tweak for building with cython
| Python | mpl-2.0 | zauberparacelsus/dragoncreole,zauberparacelsus/dragoncreole |
1f03b2945b4e52ce22a3b9e6143d02d3bd9aef99 | overtime_calculator/tests/auth_test.py | overtime_calculator/tests/auth_test.py | import shutil
import pytest
import hug
from overtime_calculator.src import api
from overtime_calculator.src.auth import get_user_folder
def test_register():
user_name = 'test1'
response = hug.test.post(
api,
'/register',
{'username': user_name, 'password': user_name},
)
asser... | import shutil
import pytest
import hug
from overtime_calculator.src import api
from overtime_calculator.src.auth import get_user_folder
EXISTING_USER = 'test1'
UNREGISTERED_USER = 'test2'
def test_registration_of_new_user():
response = hug.test.post(
api,
'/register',
{'username': EXIST... | Add test for already registered user | Feature: Add test for already registered user
| Python | mit | x10an14/overtime-calculator |
77ee44b0af8a80babf0a88ddd4f53f2f4ad10d2d | tests/test_event.py | tests/test_event.py | import unittest
from evesp.event import Event
class TestEvent(unittest.TestCase):
def setUp(self):
self.evt = Event(foo='bar')
def test_event_creation(self):
self.assertEqual(self.evt.foo, 'bar')
self.assertRaises(AttributeError, getattr, self.evt, 'non_existing')
def test_event_... | import unittest
from evesp.event import Event
class TestEvent(unittest.TestCase):
def setUp(self):
self.evt = Event(foo='bar')
def test_event_creation(self):
self.assertEqual(self.evt.foo, 'bar')
def test_non_existing_event(self):
self.assertRaises(AttributeError, getattr, self.e... | Split one test into two tests | Split one test into two tests
| Python | apache-2.0 | BlackLight/evesp |
a27b03a89af6442dc8e1be3d310a8fc046a98ed4 | foampy/tests.py | foampy/tests.py | """
Tests for foamPy.
"""
from .core import *
from .dictionaries import *
from .types import *
from .foil import *
| """Tests for foamPy."""
from .core import *
from .dictionaries import *
from .types import *
from .foil import *
def test_load_all_torque_drag():
"""Test the `load_all_torque_drag` function."""
t, torque, drag = load_all_torque_drag(casedir="test")
assert t.max() == 4.0
| Add test for loading all torque and drag data | Add test for loading all torque and drag data
| Python | mit | petebachant/foamPy,petebachant/foamPy,petebachant/foamPy |
f2d91d2c296e3662a1b656f0fdf5191665ff363b | skimage/transform/__init__.py | skimage/transform/__init__.py | from .hough_transform import *
from .radon_transform import *
from .finite_radon_transform import *
from .integral import *
from ._geometric import (warp, warp_coords, estimate_transform,
SimilarityTransform, AffineTransform,
ProjectiveTransform, PolynomialTransform,
... | from .hough_transform import *
from .radon_transform import *
from .finite_radon_transform import *
from .integral import *
from ._geometric import (warp, warp_coords, estimate_transform,
SimilarityTransform, AffineTransform,
ProjectiveTransform, PolynomialTransform,
... | Remove deprecated import of hompgraphy | Remove deprecated import of hompgraphy
| Python | bsd-3-clause | youprofit/scikit-image,almarklein/scikit-image,keflavich/scikit-image,pratapvardhan/scikit-image,vighneshbirodkar/scikit-image,almarklein/scikit-image,almarklein/scikit-image,chriscrosscutler/scikit-image,ajaybhat/scikit-image,SamHames/scikit-image,oew1v07/scikit-image,vighneshbirodkar/scikit-image,youprofit/scikit-ima... |
589534c52ceff1d4aabb8d72b779359ce2032827 | tests/integration/integration/runner.py | tests/integration/integration/runner.py | import os
import subprocess
def load_variables_from_env(prefix="XII_INTEGRATION_"):
length = len(prefix)
vars = {}
for var in filter(lambda x: x.startswith(prefix), os.environ):
vars[var[length:]] = os.environ[var]
return vars
def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None)... | import os
import subprocess
def load_variables_from_env(prefix="XII_INTEGRATION_"):
length = len(prefix)
vars = {}
for var in filter(lambda x: x.startswith(prefix), os.environ):
vars[var[length:]] = os.environ[var]
return vars
def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None)... | Make cargs and gargs truly optional | Make cargs and gargs truly optional
| Python | apache-2.0 | xii/xii,xii/xii |
705e9ee8ebe1a1c590ccbec8eed9d18abbf8e914 | tests/similarity/test_new_similarity.py | tests/similarity/test_new_similarity.py | import unittest
from similarity.nw_similarity import NWAlgorithm
class Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_nw_algorithm(self):
t = NWAlgorithm('abcdefghij', 'dgj')
t.print_matrix()
(a, b) = t.alignments()
prin... | import unittest
from similarity.nw_similarity import NWAlgorithm
class Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_nw_algorithm(self):
t = NWAlgorithm('abcdefghij', 'dgj')
t.print_matrix()
(a, b) = t.alignments()
prin... | Fix incorrect import reference to nw_similarity | Fix incorrect import reference to nw_similarity
| Python | mit | dpazel/tryinggithub |
b36f89088ab1270054140a3d3020960f23c9790b | aldryn_blog/cms_toolbar.py | aldryn_blog/cms_toolbar.py | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
@toolbar_pool.register
class BlogToolbar(CMSToolbar):
def... | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
@toolbar_pool.register
class BlogToolbar(CMSToolbar):
def... | Remove '?_popup' from toolbar urls | Remove '?_popup' from toolbar urls
| Python | bsd-3-clause | aldryn/aldryn-blog,aldryn/aldryn-blog |
33dd6ab01cea7a2a83d3d9d0c7682f716cbcb8b2 | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
def te... | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
"""Basic checks on the host."""
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
... | Fix lint errors in tests | Fix lint errors in tests
| Python | apache-2.0 | brucellino/cvmfs-client-2.2,brucellino/cvmfs-client-2.2,AAROC/cvmfs-client-2.2,AAROC/cvmfs-client-2.2 |
7930f968830efd40e1fb200ef331f0c4d955db65 | api/base.py | api/base.py | from django.contrib.auth.models import User
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from builds.models im... | from django.contrib.auth.models import User
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from builds.models im... | Make API read-only and publically available. | Make API read-only and publically available.
| Python | mit | d0ugal/readthedocs.org,atsuyim/readthedocs.org,clarkperkins/readthedocs.org,soulshake/readthedocs.org,agjohnson/readthedocs.org,SteveViss/readthedocs.org,jerel/readthedocs.org,raven47git/readthedocs.org,rtfd/readthedocs.org,johncosta/private-readthedocs.org,ojii/readthedocs.org,Carreau/readthedocs.org,sid-kap/readthedo... |
bd193b0fdb7fec412aed24ad8f4c6353372d634f | polling_stations/apps/data_collection/management/commands/import_westberks.py | polling_stations/apps/data_collection/management/commands/import_westberks.py | """
Import Wokingham Polling stations
"""
from data_collection.management.commands import BaseShpImporter, import_polling_station_shapefiles
class Command(BaseShpImporter):
"""
Imports the Polling Station data from Wokingham Council
"""
council_id = 'E06000037'
districts_name = 'polling_distri... | """
Import Wokingham Polling stations
"""
from data_collection.management.commands import BaseShpShpImporter
class Command(BaseShpShpImporter):
"""
Imports the Polling Station data from Wokingham Council
"""
council_id = 'E06000037'
districts_name = 'polling_districts'
stations_name = 'po... | Refactor West Berks to use new BaseShpShpImporter | Refactor West Berks to use new BaseShpShpImporter
| Python | bsd-3-clause | chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.