commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
40af69656b71cda7f775cface3478106f070ed35 | numba/__init__.py | numba/__init__.py | import sys
import logging
# NOTE: Be sure to keep the logging level commented out before commiting. See:
# https://github.com/numba/numba/issues/31
# A good work around is to make your tests handle a debug flag, per
# numba.tests.test_support.main().
logging.basicConfig(#level=logging.DEBUG,
for... | import sys
import logging
# NOTE: Be sure to keep the logging level commented out before commiting. See:
# https://github.com/numba/numba/issues/31
# A good work around is to make your tests handle a debug flag, per
# numba.tests.test_support.main().
class _RedirectingHandler(logging.Handler):
'''
A log ha... | Update logging facility. Don't overide root logger with basicConfig. | Update logging facility. Don't overide root logger with basicConfig.
| Python | bsd-2-clause | numba/numba,stefanseefeld/numba,pitrou/numba,stonebig/numba,ssarangi/numba,ssarangi/numba,seibert/numba,gmarkall/numba,seibert/numba,pombredanne/numba,sklam/numba,shiquanwang/numba,stefanseefeld/numba,cpcloud/numba,gmarkall/numba,numba/numba,jriehl/numba,cpcloud/numba,seibert/numba,jriehl/numba,jriehl/numba,pitrou/numb... | ---
+++
@@ -5,8 +5,39 @@
# https://github.com/numba/numba/issues/31
# A good work around is to make your tests handle a debug flag, per
# numba.tests.test_support.main().
-logging.basicConfig(#level=logging.DEBUG,
- format="\n\033[1m%(levelname)s -- %(module)s:%(lineno)d:%(funcName)s\033[0m\n%... |
4aa9e487cceccf81608dfb4ac9a1f85587298415 | edit.py | edit.py | # request handler for editing page (/edit) goes here
# assume admin login has already been handled
import cgi
from google.appengine.api import users
import webapp2
class DateHandler(webapp2.RequestHandler):
def get(self):
template_values = {
}
template = jinja_environment.get_t... | # request handler for editing page (/edit) goes here
# assume admin login has already been handled
import cgi
from google.appengine.api import users
import webapp2
class DateHandler(webapp2.RequestHandler):
def get(self):
date = self.request.get(date)
template_values = {
}
templ... | Put in date = self.request.get(date) in order to call the date from the HTML. | Put in date = self.request.get(date) in order to call the date from the HTML.
| Python | mit | shickey/BearStatus,shickey/BearStatus,shickey/BearStatus | ---
+++
@@ -8,7 +8,7 @@
class DateHandler(webapp2.RequestHandler):
def get(self):
-
+ date = self.request.get(date)
template_values = {
} |
eee35fdd148c825c492333d933eaaf8503bb09f2 | pydrm/image.py | pydrm/image.py | from .format import DrmFormat
from .framebuffer import DrmFramebuffer
from .buffer import DrmDumbBuffer
class DrmImageFramebuffer(DrmFramebuffer):
def __init__(self, drm=None, format_=None, width=None, height=None, bo=None):
if drm and format_ and width and height and bo is None:
bo = DrmDumbB... | from .format import DrmFormat
from .framebuffer import DrmFramebuffer
from .buffer import DrmDumbBuffer
class DrmImageFramebuffer(DrmFramebuffer):
def __init__(self, drm=None, format_=None, width=None, height=None, bo=None):
if drm and format_ and width and height and bo is None:
bo = DrmDumbB... | Write bytes object to mmap instead of string | Write bytes object to mmap instead of string
This fixes compatibility with python3 | Python | mit | notro/pydrm | ---
+++
@@ -26,5 +26,5 @@
# Convert RGBX -> Little Endian XRGB
b = bytearray(self.image.tobytes())
b[0::4], b[2::4] = b[2::4], b[0::4]
- self.bo.map[:] = str(b)
+ self.bo.map[:] = bytes(b)
super(DrmImageFramebuffer, self).flush(x1, y1, x2, y2) |
e75cba739b92a7209cee87f66d2c8c9df3f97799 | bumper_kilt/scripts/run_kilt.py | bumper_kilt/scripts/run_kilt.py | #!/usr/bin/python
import time
import serial
# configure the serial connections (the parameters differs on the
# device you are connecting to)
class Bumper(object):
def __init__(self):
try:
self.ser = serial.Serial(
port="/dev/ttyS0",
baudrate=9600,
... | #!/usr/bin/python
import time
import serial
# configure the serial connections (the parameters differs on the
# device you are connecting to)
class Bumper(object):
def __init__(self):
try:
self.ser = serial.Serial(
port="/dev/ttyS0",
baudrate=38400,
... | Set parameters of serial class to match with kilt | Set parameters of serial class to match with kilt
| Python | mit | ipab-rad/rad_youbot_stack,ipab-rad/rad_youbot_stack,ipab-rad/rad_youbot_stack,ipab-rad/rad_youbot_stack | ---
+++
@@ -11,10 +11,10 @@
try:
self.ser = serial.Serial(
port="/dev/ttyS0",
- baudrate=9600,
+ baudrate=38400,
parity=serial.PARITY_ODD,
- stopbits=serial.STOPBITS_TWO,
- bytesize=serial.SEVENBITS
+ ... |
be03e3d6c1323e8c750afc1d4e80997f3d9d52f3 | cyder/cydhcp/interface/dynamic_intr/forms.py | cyder/cydhcp/interface/dynamic_intr/forms.py | from django import forms
from cyder.cydhcp.interface.dynamic_intr.models import (DynamicInterface,
DynamicIntrKeyValue)
from cyder.base.mixins import UsabilityFormMixin
from cyder.cydhcp.forms import RangeWizard
class DynamicInterfaceForm(RangeWizard, UsabilityF... | from django import forms
from cyder.cydhcp.interface.dynamic_intr.models import (DynamicInterface,
DynamicIntrKeyValue)
from cyder.base.mixins import UsabilityFormMixin
from cyder.cydhcp.forms import RangeWizard
class DynamicInterfaceForm(RangeWizard, UsabilityF... | Reset range to be required in dynamic intr form | Reset range to be required in dynamic intr form
| Python | bsd-3-clause | akeym/cyder,akeym/cyder,OSU-Net/cyder,akeym/cyder,zeeman/cyder,zeeman/cyder,murrown/cyder,OSU-Net/cyder,drkitty/cyder,drkitty/cyder,zeeman/cyder,murrown/cyder,drkitty/cyder,OSU-Net/cyder,murrown/cyder,akeym/cyder,drkitty/cyder,OSU-Net/cyder,murrown/cyder,zeeman/cyder | ---
+++
@@ -12,6 +12,7 @@
self.fields.keyOrder = ['system', 'domain', 'mac', 'vrf',
'site', 'range', 'workgroup', 'dhcp_enabled',
'dns_enabled', 'ctnr']
+ self.fields['range'].required = True
class Meta:
model = DynamicI... |
bda8f2a258023c14849119b6ac2856253e9c68b4 | herd-code/herd-tools/herd-content-loader/herdcl/logger.py | herd-code/herd-tools/herd-content-loader/herdcl/logger.py | """
Copyright 2015 herd contributors
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 wr... | """
Copyright 2015 herd contributors
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 wr... | Manage Content Loader as Herd/DM tool - Lower log size cap | DM-12174: Manage Content Loader as Herd/DM tool
- Lower log size cap
| Python | apache-2.0 | FINRAOS/herd,FINRAOS/herd,FINRAOS/herd,FINRAOS/herd,FINRAOS/herd | ---
+++
@@ -29,7 +29,7 @@
log_format = logging.Formatter("%(asctime)s - %(module)s - Line %(lineno)d - %(levelname)s \n%(message)s",
"%Y-%m-%d %H:%M:%S")
- log_handler = logging.handlers.RotatingFileHandler('debug.log', mode='a', maxBytes=1024 * 1024)
+ log_handler = l... |
f67abceeae7716cd385a308b26ce447e0277518f | tests/git_wrapper_integration_tests.py | tests/git_wrapper_integration_tests.py | import unittest
import util
from git_wrapper import GitWrapper
class GitWrapperIntegrationTest(util.RepoTestCase):
def test_paths(self):
self.open_tar_repo('project01')
assert('test_file.txt' in self.repo.paths)
assert('hello_world.rb' in self.repo.paths)
def test_stage(self):
... | import unittest
import util
from git_wrapper import GitWrapper
class GitWrapperIntegrationTest(util.RepoTestCase):
def test_paths(self):
self.open_tar_repo('project01')
assert('test_file.txt' in self.repo.paths)
assert('hello_world.rb' in self.repo.paths)
def test_stage(self):
... | Move external git folder integration tests to a separate class | Move external git folder integration tests to a separate class
| Python | mit | siu/git_repo | ---
+++
@@ -13,12 +13,13 @@
assert('not_committed_file.txt' in self.repo.stage)
assert('second_not_committed_file.txt' in self.repo.stage)
- def test_paths_external_git_folder(self):
+class GitWrapperIntegrationTestExternalGitFolder(util.RepoTestCase):
+ def test_paths_external(self):
... |
feef7985133241c5e11622b0932d3eb629e7fbfe | craigschart/craigschart.py | craigschart/craigschart.py |
def main():
print('Hello, World.')
if __name__ == '__main__':
main()
| from bs4 import BeautifulSoup
import requests
def get_html():
r = requests.get('http://vancouver.craigslist.ca/search/cto?query=Expedition')
print(r.status_code)
print(r.text)
return r.text
def main():
html = get_html()
soup = BeautifulSoup(html, 'lxml')
print(soup.prettify())
mydivs ... | Add soup extraction of links in results page | Add soup extraction of links in results page
| Python | mit | supermitch/craigschart | ---
+++
@@ -1,5 +1,21 @@
+from bs4 import BeautifulSoup
+import requests
+
+def get_html():
+ r = requests.get('http://vancouver.craigslist.ca/search/cto?query=Expedition')
+ print(r.status_code)
+ print(r.text)
+ return r.text
def main():
+ html = get_html()
+
+ soup = BeautifulSoup(html, 'lxml'... |
8c6b4396047736d5caf00ec30b4283ee7cdc793e | lighty/wsgi/decorators.py | lighty/wsgi/decorators.py | '''
'''
import functools
import operator
from .. import monads
def view(func, **constraints):
'''Functions that decorates a view. This function can also checks the
argument values
'''
func.is_view = True
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
if not funct... | '''
'''
import functools
import operator
from .. import monads
def view(func, **constraints):
'''Functions that decorates a view. This function can also checks the
argument values
'''
func.is_view = True
@functools.wraps(func)
@monads.handle_exception
def wrapper(*args, **kwargs):
... | Use exception handling with decorator | Use exception handling with decorator
| Python | bsd-3-clause | GrAndSE/lighty | ---
+++
@@ -11,14 +11,11 @@
'''
func.is_view = True
@functools.wraps(func)
+ @monads.handle_exception
def wrapper(*args, **kwargs):
- try:
- if not functools.reduce(operator.__and__,
- [constraints[arg](kwargs[arg])
- ... |
7ef1717f34360ae48f640439fd6d6706ae755e90 | functional_tests/base.py | functional_tests/base.py | from selenium import webdriver
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.core.cache import cache
class BrowserTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.PhantomJS()
self.browser.set_window_size(1024, 768)
def tearDown(s... | from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.chrome.options import Options
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.core.cache import cache
class BrowserTest(StaticLiveServerTestCase):
def setUp(self):
chrome_options = Options... | Use headless chrome for functional test | Use headless chrome for functional test
| Python | mit | essanpupil/cashflow,essanpupil/cashflow | ---
+++
@@ -1,12 +1,15 @@
-from selenium import webdriver
-
+from selenium.webdriver.chrome.webdriver import WebDriver
+from selenium.webdriver.chrome.options import Options
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.core.cache import cache
class BrowserTest(StaticLiveS... |
9fdea42df37c722aefb5e8fb7c04c45c06c20f17 | tests/test_client_users.py | tests/test_client_users.py | import pydle
from .fixtures import with_client
from .mocks import Mock
@with_client()
def test_user_creation(server, client):
client._create_user('WiZ')
assert 'WiZ' in client.users
assert client.users['WiZ']['nickname'] == 'WiZ'
@with_client()
def test_user_renaming(server, client):
client._create_u... | import pydle
from .fixtures import with_client
@with_client()
def test_client_same_nick(server, client):
assert client.is_same_nick('WiZ', 'WiZ')
assert not client.is_same_nick('WiZ', 'jilles')
assert not client.is_same_nick('WiZ', 'wiz')
@with_client()
def test_user_creation(server, client):
client.... | Extend client:users tests to renaming and synchronization. | tests: Extend client:users tests to renaming and synchronization.
| Python | bsd-3-clause | Shizmob/pydle | ---
+++
@@ -1,13 +1,23 @@
import pydle
from .fixtures import with_client
-from .mocks import Mock
+
+@with_client()
+def test_client_same_nick(server, client):
+ assert client.is_same_nick('WiZ', 'WiZ')
+ assert not client.is_same_nick('WiZ', 'jilles')
+ assert not client.is_same_nick('WiZ', 'wiz')
@w... |
b5fc673d44624dfddfbdd98c9806b7e7e2f67331 | simplekv/memory/memcachestore.py | simplekv/memory/memcachestore.py | #!/usr/bin/env python
# coding=utf8
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from .. import KeyValueStore
class MemcacheStore(KeyValueStore):
def __contains__(self, key):
try:
return key in self.mc
except TypeError:
rai... | #!/usr/bin/env python
# coding=utf8
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from .. import KeyValueStore
class MemcacheStore(KeyValueStore):
def __contains__(self, key):
try:
return key in self.mc
except TypeError:
rai... | Check if putting/getting was actually successful. | Check if putting/getting was actually successful.
| Python | mit | fmarczin/simplekv,fmarczin/simplekv,karteek/simplekv,mbr/simplekv,karteek/simplekv,mbr/simplekv | ---
+++
@@ -21,7 +21,8 @@
self.mc = mc
def _delete(self, key):
- self.mc.delete(key)
+ if not self.mc.delete(key):
+ raise IOError('Error deleting key')
def _get(self, key):
rv = self.mc.get(key)
@@ -36,12 +37,15 @@
return StringIO(self._get(key))
... |
67710f78677c4ad2737504d9815154c8e9f3bb18 | django_prometheus/utils.py | django_prometheus/utils.py | import time
from prometheus_client import _INF
# TODO(korfuri): if python>3.3, use perf_counter() or monotonic().
def Time():
"""Returns some representation of the current time.
This wrapper is meant to take advantage of a higher time
resolution when available. Thus, its return value should be
treat... | import time
from prometheus_client import _INF
# TODO(korfuri): if python>3.3, use perf_counter() or monotonic().
def Time():
"""Returns some representation of the current time.
This wrapper is meant to take advantage of a higher time
resolution when available. Thus, its return value should be
treat... | Fix PowersOf to return `count` items, not "numbers up to base**count". | Fix PowersOf to return `count` items, not "numbers up to base**count".
| Python | apache-2.0 | obytes/django-prometheus,wangwanzhong/django-prometheus,wangwanzhong/django-prometheus,korfuri/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus,DingaGa/django-prometheus,DingaGa/django-prometheus | ---
+++
@@ -27,6 +27,6 @@
def PowersOf(logbase, count, lower=0, include_zero=True):
"""Returns a list of count powers of logbase (from logbase**lower)."""
if not include_zero:
- return [logbase ** i for i in range(lower, count)] + [_INF]
+ return [logbase ** i for i in range(lower, count+lowe... |
ef576a884bd4155fbc8bec8615c25544e74b98c3 | samsungctl/__init__.py | samsungctl/__init__.py | """Remote control Samsung televisions via TCP/IP connection"""
from .remote import Remote
__title__ = "samsungctl"
__version__ = "0.6.0-git"
__url__ = "https://github.com/Ape/samsungctl"
__author__ = "Lauri Niskanen"
__author_email__ = "ape@ape3000.com"
__license__ = "MIT"
| """Remote control Samsung televisions via TCP/IP connection"""
from .remote import Remote
__title__ = "samsungctl"
__version__ = "0.6.0+1"
__url__ = "https://github.com/Ape/samsungctl"
__author__ = "Lauri Niskanen"
__author_email__ = "ape@ape3000.com"
__license__ = "MIT"
| Use PEP 440 compatible local version identifier | Use PEP 440 compatible local version identifier
| Python | mit | Ape/samsungctl | ---
+++
@@ -3,7 +3,7 @@
from .remote import Remote
__title__ = "samsungctl"
-__version__ = "0.6.0-git"
+__version__ = "0.6.0+1"
__url__ = "https://github.com/Ape/samsungctl"
__author__ = "Lauri Niskanen"
__author_email__ = "ape@ape3000.com" |
c037b0a9ef8424737b978dda0400a1c31d5cb300 | app/state.py | app/state.py | import multiprocessing
import unicornhat
import importlib
import sys
import os
class State:
''' Handles the Unicorn HAT state'''
def __init__(self):
self.process = None
def start_program(self, name, params={}):
self.stop_program()
if "brightness" in params:
unicornha... | import multiprocessing
import unicornhat
import importlib
import sys
import os
class State:
''' Handles the Unicorn HAT state'''
def __init__(self):
self._process = None
def start_program(self, name, params={}):
self.stop_program()
if "brightness" in params:
unicornh... | Mark process member variable for internal use | Mark process member variable for internal use
| Python | mit | njbbaer/unicorn-remote,njbbaer/unicorn-remote,njbbaer/unicorn-remote | ---
+++
@@ -9,7 +9,7 @@
''' Handles the Unicorn HAT state'''
def __init__(self):
- self.process = None
+ self._process = None
def start_program(self, name, params={}):
self.stop_program()
@@ -21,12 +21,12 @@
unicornhat.rotation(int(params["rotation"]))
... |
f4c99f4a1b3e49e0768af1b4b6444ee33bef49ac | microauth/urls.py | microauth/urls.py | """microauth URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/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')
Class-b... | """microauth URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/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')
Class-b... | Add a missing route leading to the login page. | Add a missing route leading to the login page.
| Python | mit | microserv/microauth,microserv/microauth,microserv/microauth | ---
+++
@@ -24,6 +24,8 @@
url(r'^oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')),
url(r'^', include('apps.authentication.urls', namespace='microauth_authentication')),
url(r'^api/', include('apps.api.urls', namespace='microauth_api')),
+ url(r'^accounts/login/$', 'django.cont... |
49f332149ae8a9a3b5faf82bc20b46dfaeb0a3ad | indra/sources/ctd/api.py | indra/sources/ctd/api.py | import pandas
from .processor import CTDChemicalDiseaseProcessor, \
CTDGeneDiseaseProcessor, CTDChemicalGeneProcessor
base_url = 'http://ctdbase.org/reports/'
urls = {
'chemical_gene': base_url + 'CTD_chem_gene_ixns.tsv.gz',
'chemical_disease': base_url + 'CTD_chemicals_diseases.tsv.gz',
'gene_disease... | import pandas
from .processor import CTDChemicalDiseaseProcessor, \
CTDGeneDiseaseProcessor, CTDChemicalGeneProcessor
base_url = 'http://ctdbase.org/reports/'
urls = {
'chemical_gene': base_url + 'CTD_chem_gene_ixns.tsv.gz',
'chemical_disease': base_url + 'CTD_chemicals_diseases.tsv.gz',
'gene_disease... | Refactor API to have single pandas load | Refactor API to have single pandas load
| Python | bsd-2-clause | sorgerlab/indra,bgyori/indra,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/belpy,bgyori/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,johnbachman/belpy,sorgerlab/indra,sorgerlab/indra | ---
+++
@@ -17,22 +17,26 @@
}
-def process_from_web(subset):
+def process_from_web(subset, url=None):
if subset not in urls:
- raise ValueError('%s is not a valid CTD subset.')
- df = pandas.read_csv(urls[subset], sep='\t', comment='#',
- header=None)
- return process_da... |
d7e0fd7027f4a4a5024d136c0ab96b244d761c99 | pucas/__init__.py | pucas/__init__.py | default_app_config = 'pucas.apps.PucasConfig'
__version_info__ = (0, 5, 1, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
| default_app_config = 'pucas.apps.PucasConfig'
__version_info__ = (0, 6, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
| Set develop version back to 0.6-dev | Set develop version back to 0.6-dev
| Python | apache-2.0 | Princeton-CDH/django-pucas,Princeton-CDH/django-pucas | ---
+++
@@ -1,6 +1,6 @@
default_app_config = 'pucas.apps.PucasConfig'
-__version_info__ = (0, 5, 1, None)
+__version_info__ = (0, 6, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]]) |
71cdbeada7e11634e1168ca2e825167cbe87b4de | spacy/lang/de/norm_exceptions.py | spacy/lang/de/norm_exceptions.py | # coding: utf8
from __future__ import unicode_literals
# Here we only want to include the absolute most common words. Otherwise,
# this list would get impossibly long for German – especially considering the
# old vs. new spelling rules, and all possible cases.
_exc = {
"daß": "dass"
}
NORM_EXCEPTIONS = {}
for... | # coding: utf8
from __future__ import unicode_literals
# Here we only want to include the absolute most common words. Otherwise,
# this list would get impossibly long for German – especially considering the
# old vs. new spelling rules, and all possible cases.
_exc = {
"daß": "dass"
}
NORM_EXCEPTIONS = {}
for... | Revert "Also include lowercase norm exceptions" | Revert "Also include lowercase norm exceptions"
This reverts commit 70f4e8adf37cfcfab60be2b97d6deae949b30e9e.
| Python | mit | aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spa... | ---
+++
@@ -14,5 +14,4 @@
NORM_EXCEPTIONS = {}
for string, norm in _exc.items():
- NORM_EXCEPTIONS[string] = norm
NORM_EXCEPTIONS[string.title()] = norm |
a3689129e2938dd7f2213ea11ac36a854cc0a31e | test/test_jarvis.py | test/test_jarvis.py | import unittest
from collections import namedtuple
# TODO: Move this code to a module so we don't depend on PYTHONPATH and that sort
# of ugliness.
from jarvis import convert_file_to_json, get_tags
JarvisSettings = namedtuple('JarvisSettings', ['tags_directory'])
class TestJarvis(unittest.TestCase):
def setUp(se... | import unittest
from collections import namedtuple
# TODO: Move this code to a module so we don't depend on PYTHONPATH and that sort
# of ugliness.
from jarvis import convert_file_to_json, get_tags
JarvisSettings = namedtuple('JarvisSettings', ['tags_directory'])
class TestJarvis(unittest.TestCase):
def setUp(se... | Change test method name to better match | Change test method name to better match
| Python | apache-2.0 | clb6/jarvis-cli | ---
+++
@@ -14,7 +14,7 @@
self.js = JarvisSettings('fixtures/tags')
- def test_convert_log(self):
+ def test_convert_file_to_json(self):
try:
j = convert_file_to_json(self.test_log)
# Version 0.2.0 |
346f726a12078e7667ef32808feda0618f568839 | lino_extjs6/projects/mysite/settings/demo.py | lino_extjs6/projects/mysite/settings/demo.py | import datetime
from lino_extjs6.projects.mysite.settings import *
class Site(Site):
project_name = 'extjs_demo'
is_demo_site = True
# ignore_dates_after = datetime.date(2019, 05, 22)
the_demo_date = datetime.date(2015, 03, 12)
SITE = Site(globals())
SECRET_KEY = "1234"
# ALLOWED_HOSTS = ['*']
DEBU... | import datetime
from lino_extjs6.projects.mysite.settings import *
class Site(Site):
project_name = 'extjs_demo'
is_demo_site = True
# ignore_dates_after = datetime.date(2019, 05, 22)
the_demo_date = datetime.date(2015, 3, 12)
SITE = Site(globals())
SECRET_KEY = "1234"
# ALLOWED_HOSTS = ['*']
DEBUG... | Add support to Py3 for datetime | Add support to Py3 for datetime
| Python | agpl-3.0 | lino-framework/extjs6,lsaffre/lino_extjs6,lsaffre/lino_extjs6,lsaffre/lino_extjs6,lsaffre/lino_extjs6,lino-framework/extjs6,lsaffre/lino_extjs6,lino-framework/extjs6 | ---
+++
@@ -7,7 +7,7 @@
project_name = 'extjs_demo'
is_demo_site = True
# ignore_dates_after = datetime.date(2019, 05, 22)
- the_demo_date = datetime.date(2015, 03, 12)
+ the_demo_date = datetime.date(2015, 3, 12)
SITE = Site(globals())
|
f5c74e6869b54bf6d16bb8493d3c76e9fb65bec5 | createdb.py | createdb.py | #!/usr/bin/env python
import sys
import fedmsg.config
import fmn.lib.models
config = fedmsg.config.load_config()
uri = config.get('fmn.sqlalchemy.uri')
if not uri:
raise ValueError("fmn.sqlalchemy.uri must be present")
if '-h' in sys.argv or '--help'in sys.argv:
print "createdb.py [--with-dev-data]"
sys.... | #!/usr/bin/env python
import sys
import fedmsg.config
import fmn.lib.models
config = fedmsg.config.load_config()
uri = config.get('fmn.sqlalchemy.uri')
if not uri:
raise ValueError("fmn.sqlalchemy.uri must be present")
if '-h' in sys.argv or '--help'in sys.argv:
print "createdb.py [--with-dev-data]"
sys.... | Add the desktop context to the setup script. | Add the desktop context to the setup script.
| Python | lgpl-2.1 | jeremycline/fmn,jeremycline/fmn,jeremycline/fmn | ---
+++
@@ -31,4 +31,9 @@
detail_name="registration id", icon="phone",
placeholder="laksdjfasdlfkj183097falkfj109f"
)
+ context4 = fmn.lib.models.Context.create(
+ session, name="desktop", description="fedmsg-notify",
+ detail_name="None", icon="console",
+ placeholder="... |
e8795b5f45ea67c83f7e99c54b04e0dceb1fee34 | run-cron.py | run-cron.py | #!/usr/bin/env python
"""Executes a Django cronjob"""
import os
# Activate the virtualenv
path = os.path.dirname(os.path.abspath( __file__ ))
activate_this = os.path.join(path, 'env/bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
import sys
import logging
from django.core.management impo... | #!/usr/bin/env python
"""Executes a Django cronjob"""
import os
# Activate the virtualenv
path = os.path.dirname(os.path.abspath( __file__ ))
os.chdir(path)
activate_this = os.path.join(path, 'env/bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
import sys
import logging
from django.core.... | Change to the root directory before executing (stops Mumble ICE file errors) | Change to the root directory before executing (stops Mumble ICE file errors)
This was causing the SSO job to fail, thanks for psu3d0 for pointing it out.
| Python | bsd-3-clause | nikdoof/test-auth | ---
+++
@@ -5,6 +5,7 @@
# Activate the virtualenv
path = os.path.dirname(os.path.abspath( __file__ ))
+os.chdir(path)
activate_this = os.path.join(path, 'env/bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
|
cd944a2606159c8ea11ffe8075ce4ec186fd799c | tests/basic_test.py | tests/basic_test.py | import unittest
from either_or import either_or
class nxppyTests(unittest.TestCase):
"""Basic tests for the NXP Read Library python wrapper."""
def test_import(self):
"""Test that it can be imported"""
import nxppy
@either_or('detect')
def test_detect_mifare_present(self):
"""... | import unittest
from tests.either_or import either_or
class nxppyTests(unittest.TestCase):
"""Basic tests for the NXP Read Library python wrapper."""
def test_import(self):
"""Test that it can be imported"""
import nxppy
@either_or('detect')
def test_detect_mifare_present(self):
... | Update tests to use class-based interface | Update tests to use class-based interface
| Python | mit | AlterCodex/nxppy,Schoberm/nxppy,AlterCodex/nxppy,tuvaergun/nxppy,Schoberm/nxppy,tuvaergun/nxppy,Schoberm/nxppy,tuvaergun/nxppy,AlterCodex/nxppy | ---
+++
@@ -1,5 +1,5 @@
import unittest
-from either_or import either_or
+from tests.either_or import either_or
class nxppyTests(unittest.TestCase):
"""Basic tests for the NXP Read Library python wrapper."""
@@ -15,7 +15,9 @@
Either this test or the "absent" test below will pass, but never both.
... |
eb03de241f3d47173381ee22f85b5cdf5d9c1fb4 | examples/monitoring/worker.py | examples/monitoring/worker.py | import random
import time
from os import getenv
from aiographite.aiographite import connect
from aiographite.protocol import PlaintextProtocol
GRAPHITE_HOST = getenv('GRAPHITE_HOST', 'localhost')
async def run(worker, *args, **kwargs):
value = random.randrange(10)
try:
connection = await connect(GRAPHI... | import random
import time
from os import getenv
from aiographite.aiographite import connect
from aiographite.protocol import PlaintextProtocol
GRAPHITE_HOST = getenv('GRAPHITE_HOST', 'localhost')
async def run(worker, *args, **kwargs):
value = random.randrange(10)
try:
connection = await connect(GRA... | Fix flake8 issues in examples | Fix flake8 issues in examples
| Python | apache-2.0 | aioworkers/aioworkers | ---
+++
@@ -11,8 +11,8 @@
async def run(worker, *args, **kwargs):
value = random.randrange(10)
try:
- connection = await connect(GRAPHITE_HOST, 2003, PlaintextProtocol(), loop=worker.loop)
- await connection.send('workers.worker', value, time.time())
- await connection.close()
- except Excep... |
d799b3fdf6365fb54f0a1553b9a68c4334dd5482 | examples/project_one/input.py | examples/project_one/input.py | def read_file(filename):
# Open the file
file_obj = open(filename)
# Iterate over lines in the file
for line in file_obj:
# Split line by spaces (creates a list)
# Alternatives: split(',')
numbers = line.split()
if len(numbers) != 2:
# Convert strings to nu... | Convert list, for later reference. | Convert list, for later reference.
| Python | mit | dokterbob/slf-programming-workshops,dokterbob/slf-programming-workshops,dokterbob/slf-programming-workshops,dokterbob/slf-programming-workshops | ---
+++
@@ -0,0 +1,33 @@
+def read_file(filename):
+ # Open the file
+ file_obj = open(filename)
+
+ # Iterate over lines in the file
+ for line in file_obj:
+
+ # Split line by spaces (creates a list)
+ # Alternatives: split(',')
+ numbers = line.split()
+
+ if len(numbers) !=... | |
8396ac44d434a06c410c516b6109ec6ace030601 | examples/pyuv_cffi_example.py | examples/pyuv_cffi_example.py | """A simple example demonstrating basic usage of pyuv_cffi
This example creates a timer handle and a signal handle, then starts the loop. The timer callback is
run after 1 second, and repeating every 1 second thereafter. The signal handle registers a listener
for the INT signal and allows us to exit the loop by pressi... | """A simple example demonstrating basic usage of pyuv_cffi
This example creates a timer handle and a signal handle, then starts the loop. The timer callback is
run after 1 second, and repeating every 1 second thereafter. The signal handle registers a listener
for the INT signal and allows us to exit the loop by pressi... | Add inline comment regarding freeing resources | Add inline comment regarding freeing resources
| Python | mit | veegee/guv,veegee/guv | ---
+++
@@ -30,8 +30,11 @@
status = loop.run()
- timer_h.close() # stop and free any timers before freeing the loop
+ timer_h.close() # we must stop and free any other handles before freeing the loop
print('loop.run() -> ', status)
+
+ # all handles in pyuv_cffi (including the loop) are autom... |
c28ae7e4b0637a2c4db120d9add13d5589ddca40 | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
try:
django... | #!/usr/bin/env python
import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
django.setup()
... | Remove compat shim as it doesn't apply | Remove compat shim as it doesn't apply
| Python | mit | sergei-maertens/django-systemjs,sergei-maertens/django-systemjs,sergei-maertens/django-systemjs,sergei-maertens/django-systemjs | ---
+++
@@ -12,10 +12,7 @@
from django.test.utils import get_runner
from django.conf import settings
- try:
- django.setup()
- except AttributeError: # 1.6 or lower
- pass
+ django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interacti... |
0dddfcbdb46ac91ddc0bfed4482bce049a8593c2 | lazyblacksmith/views/blueprint.py | lazyblacksmith/views/blueprint.py | # -*- encoding: utf-8 -*-
from flask import Blueprint
from flask import render_template
from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region
blueprint = Blueprint('blueprint', __name__)
@blueprint.route('/manufacturing/<int:item_id>')
def manufac... | # -*- encoding: utf-8 -*-
import config
from flask import Blueprint
from flask import render_template
from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region
blueprint = Blueprint('blueprint', __name__)
@blueprint.route('/manufacturing/<int:item_id>... | Change region list to match config | Change region list to match config
| Python | bsd-3-clause | Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith | ---
+++
@@ -1,7 +1,8 @@
# -*- encoding: utf-8 -*-
+import config
+
from flask import Blueprint
from flask import render_template
-
from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region
@@ -18,7 +19,11 @@
activity = item.activities.filter_... |
563220ef19395201aed7f6392519f84db4ec7a77 | tests/test_midas.py | tests/test_midas.py | import datetime
from midas import mix
from midas.midas import estimate, forecast
def test_estimate(gdp_data, farmpay_data):
y, yl, x, yf, ylf, xf = mix.mix_freq(gdp_data.gdp, farmpay_data.farmpay, 3, 1, 1,
start_date=datetime.datetime(1985, 1, 1),
... | import datetime
import numpy as np
from midas import mix
from midas.midas import estimate, forecast
def test_estimate(gdp_data, farmpay_data):
y, yl, x, yf, ylf, xf = mix.mix_freq(gdp_data.gdp, farmpay_data.farmpay, 3, 1, 1,
start_date=datetime.datetime(1985, 1, 1),
... | Add assertion for forecast test | Add assertion for forecast test
| Python | mit | mikemull/midaspy | ---
+++
@@ -1,4 +1,5 @@
import datetime
+import numpy as np
from midas import mix
from midas.midas import estimate, forecast
@@ -16,4 +17,4 @@
print(fc)
- assert False
+ assert np.isclose(fc.loc['2011-04-01'][0], 1.336844, rtol=1e-6) |
1f9a11640463df94166be8dffa824e57485154f8 | tests/vaspy_test.py | tests/vaspy_test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from arc_test import ArcTest
from incar_test import InCarTest
from oszicar_test import OsziCarTest
from outcar_test import OutCarTest
from xsd_test import XsdTest
from xtd_test import XtdTest
from poscar_test import PosCarTest
from xyzfile_test import XyzFi... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from arc_test import ArcTest
from incar_test import InCarTest
from oszicar_test import OsziCarTest
from outcar_test import OutCarTest
from xsd_test import XsdTest
from xtd_test import XtdTest
from poscar_test import PosCarTest
from xyzfile_test import XyzFi... | Add test for animation file. | Add test for animation file.
| Python | mit | PytLab/VASPy,PytLab/VASPy | ---
+++
@@ -11,6 +11,7 @@
from poscar_test import PosCarTest
from xyzfile_test import XyzFileTest
from cif_test import CifFileTest
+from ani_test import AniFileTest
def suite():
suite = unittest.TestSuite([
@@ -23,6 +24,7 @@
unittest.TestLoader().loadTestsFromTestCase(PosCarTest),
unittes... |
b8a22c1dfe58802665231e8a82bb546bfd1dbbc8 | pybossa/sentinel/__init__.py | pybossa/sentinel/__init__.py | from redis import sentinel
class Sentinel(object):
def __init__(self, app=None):
self.app = app
if app is not None: # pragma: no cover
self.init_app(app)
def init_app(self, app):
self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],
... | from redis import sentinel
class Sentinel(object):
def __init__(self, app=None):
self.app = app
if app is not None: # pragma: no cover
self.init_app(app)
def init_app(self, app):
self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],
... | Use config redis database in sentinel connections | Use config redis database in sentinel connections
| Python | agpl-3.0 | inteligencia-coletiva-lsd/pybossa,geotagx/pybossa,jean/pybossa,PyBossa/pybossa,PyBossa/pybossa,stefanhahmann/pybossa,OpenNewsLabs/pybossa,OpenNewsLabs/pybossa,stefanhahmann/pybossa,Scifabric/pybossa,geotagx/pybossa,jean/pybossa,Scifabric/pybossa,inteligencia-coletiva-lsd/pybossa | ---
+++
@@ -11,5 +11,7 @@
def init_app(self, app):
self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],
socket_timeout=0.1)
- self.master = self.connection.master_for('mymaster')
- self.slave = self.connection.slave_for('mymas... |
695dad10b6d27e2b45a7b98abad29b9d922b976f | pylisp/packet/ip/protocol.py | pylisp/packet/ip/protocol.py | '''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class Protocol(object):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
self.next_header = next_he... | '''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class ProtocolElement(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
'''
Constructor
'''
def __repr__(self):
# This works as long as we accept all properties... | Split Protocol class in Protocol and ProtocolElement | Split Protocol class in Protocol and ProtocolElement
| Python | bsd-3-clause | steffann/pylisp | ---
+++
@@ -6,18 +6,14 @@
from abc import abstractmethod, ABCMeta
-class Protocol(object):
+class ProtocolElement(object):
__metaclass__ = ABCMeta
- header_type = None
-
@abstractmethod
- def __init__(self, next_header=None, payload=''):
+ def __init__(self):
'''
Constructo... |
90d1a40175675b2950cb41b85434b522d6e21c4d | mass/cli.py | mass/cli.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: set hls is ai et sw=4 sts=4 ts=8 nu ft=python:
# built-in modules
# 3rd-party modules
import click
# local modules
from mass.monitor.app import app
from mass.scheduler.swf import utils
from mass.scheduler.swf import SWFWorker
@click.group()
def cli():
pass
... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: set hls is ai et sw=4 sts=4 ts=8 nu ft=python:
# built-in modules
# 3rd-party modules
import click
# local modules
from mass.monitor.app import app
from mass.scheduler.swf import utils
from mass.scheduler.swf import SWFWorker
@click.group()
def cli():
pass
... | Add arguments --domain and --region to mass init. | Add arguments --domain and --region to mass init.
| Python | apache-2.0 | badboy99tw/mass,KKBOX/mass,badboy99tw/mass,badboy99tw/mass,KKBOX/mass,KKBOX/mass | ---
+++
@@ -19,10 +19,12 @@
@cli.command()
-def init():
- utils.register_domain()
- utils.register_workflow_type()
- utils.register_activity_type()
+@click.option('-d', '--domain', help='Amazon SWF Domain.')
+@click.option('-r', '--region', help='Amazon Region.')
+def init(domain, region):
+ utils.re... |
75457e90381b6ff38becfed0befe214c9d6c0fc1 | skyscanner/__init__.py | skyscanner/__init__.py | # -*- coding: utf-8 -*-
__author__ = 'Ardy Dedase'
__email__ = 'ardy.dedase@skyscanner.net'
__version__ = '1.1.3'
__copyright__ = "Copyright (C) 2016 Skyscanner Ltd"
__license__ = """
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may... | # -*- coding: utf-8 -*-
__author__ = 'Ardy Dedase'
__email__ = 'ardy.dedase@skyscanner.net'
__version__ = '1.1.4'
__copyright__ = "Copyright (C) 2016 Skyscanner Ltd"
__license__ = """
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may... | Include skyscanner version to be used by doc. | Include skyscanner version to be used by doc.
| Python | apache-2.0 | Skyscanner/skyscanner-python-sdk | ---
+++
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
__author__ = 'Ardy Dedase'
__email__ = 'ardy.dedase@skyscanner.net'
-__version__ = '1.1.3'
+__version__ = '1.1.4'
__copyright__ = "Copyright (C) 2016 Skyscanner Ltd"
__license__ = """
Licensed under the Apache License, Version 2.0 (the "License"); |
a1c7773eb889ece3233b910c559b4e22ade3bb32 | timpani/settings.py | timpani/settings.py | from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = ... | from . import database
def getAllSettings():
databaseConnection = database.ConnectionManager.getConnection("main")
query = databaseConnection.session.query(database.tables.Setting)
settings = query.all()
return {setting.name: setting.value for setting in settings}
def getSettingValue(name):
databaseConnection = ... | Use setting validation function in setSettingValue | Use setting validation function in setSettingValue
| Python | mit | ollien/Timpani,ollien/Timpani,ollien/Timpani | ---
+++
@@ -16,10 +16,15 @@
return None
def setSettingValue(name, value):
- databaseConnection = database.ConnectionManager.getConnection("main")
- settingObj = database.tables.Setting(name = name, value = value)
- databaseConnection.session.merge(settingObj)
- databaseConnection.session.commit()
+ valid = valid... |
d6224333a8c815086cf8f10b0bb9ee23f7aec3ef | numpy/fft/info.py | numpy/fft/info.py | """\
Core FFT routines
==================
Standard FFTs
fft
ifft
fft2
ifft2
fftn
ifftn
Real FFTs
refft
irefft
refft2
irefft2
refftn
irefftn
Hermite FFTs
hfft
ihfft
"""
depends = ['core']
| """\
Core FFT routines
==================
Standard FFTs
fft
ifft
fft2
ifft2
fftn
ifftn
Real FFTs
rfft
irfft
rfft2
irfft2
rfftn
irfftn
Hermite FFTs
hfft
ihfft
"""
depends = ['core']
| Fix documentation of fft sub-package to eliminate references to refft. | Fix documentation of fft sub-package to eliminate references to refft.
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@3226 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | illume/numpy3k,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,illume/numpy3k,chadnetzer/numpy-gaurdro,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,efiring/numpy-work,efiring/numpy-work,chadnetzer/numpy-gaurdro,teoliphant/numpy-refactor,efi... | ---
+++
@@ -13,12 +13,12 @@
Real FFTs
- refft
- irefft
- refft2
- irefft2
- refftn
- irefftn
+ rfft
+ irfft
+ rfft2
+ irfft2
+ rfftn
+ irfftn
Hermite FFTs
|
ee99527185268ac386aad0c54056ac640c197e42 | dbmigrator/commands/init.py | dbmigrator/commands/init.py | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_d... | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_d... | Stop changing schema_migrations data if the table already exists | Stop changing schema_migrations data if the table already exists
| Python | agpl-3.0 | karenc/db-migrator | ---
+++
@@ -15,12 +15,18 @@
@utils.with_cursor
def cli_command(cursor, migrations_directory='', version=None, **kwargs):
cursor.execute("""\
- CREATE TABLE IF NOT EXISTS schema_migrations (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_name = 'schema_migrations'""")
+ table_ex... |
30f03692eff862f1456b9c376c21fe8e57de7eaa | dbt/clients/agate_helper.py | dbt/clients/agate_helper.py |
import agate
DEFAULT_TYPE_TESTER = agate.TypeTester(types=[
agate.data_types.Number(),
agate.data_types.Date(),
agate.data_types.DateTime(),
agate.data_types.Boolean(),
agate.data_types.Text()
])
def table_from_data(data, column_names):
"Convert list of dictionaries into an Agate table"
... |
import agate
DEFAULT_TYPE_TESTER = agate.TypeTester(types=[
agate.data_types.Boolean(true_values=('true',),
false_values=('false',),
null_values=('null',)),
agate.data_types.Number(null_values=('null',)),
agate.data_types.TimeDelta(null_values=('nu... | Make the agate table type tester more restrictive on what counts as null/true/false | Make the agate table type tester more restrictive on what counts as null/true/false
| Python | apache-2.0 | analyst-collective/dbt,nave91/dbt,nave91/dbt,fishtown-analytics/dbt,fishtown-analytics/dbt,fishtown-analytics/dbt,analyst-collective/dbt | ---
+++
@@ -2,11 +2,14 @@
import agate
DEFAULT_TYPE_TESTER = agate.TypeTester(types=[
- agate.data_types.Number(),
- agate.data_types.Date(),
- agate.data_types.DateTime(),
- agate.data_types.Boolean(),
- agate.data_types.Text()
+ agate.data_types.Boolean(true_values=('true',),
+ ... |
52fa6cff088e2032fc8a3a9d732bf8affb9bccae | config/template.py | config/template.py | DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
| DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
TWILIO_NUMBERS = ['']
| Allow for representative view display with sample configuration | Allow for representative view display with sample configuration
| Python | mit | AKVorrat/ueberwachungspaket.at,AKVorrat/ueberwachungspaket.at,AKVorrat/ueberwachungspaket.at | ---
+++
@@ -2,3 +2,5 @@
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
+
+TWILIO_NUMBERS = [''] |
068862dc72fa82ec35e7fabc6a0a99dc10f7f034 | octavia/common/service.py | octavia/common/service.py | # Copyright 2014 Rackspace
#
# 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 t... | # Copyright 2014 Rackspace
#
# 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 t... | Remove bad INFO log "Starting Octavia API server" | Remove bad INFO log "Starting Octavia API server"
This log is also display for health_manager and house_keeping service.
Api service already display "Starting API server on..." in INFO level.
Change-Id: I0a3ff91b556accdfadbad797488d17ae7a95d85b
| Python | apache-2.0 | openstack/octavia,openstack/octavia,openstack/octavia | ---
+++
@@ -16,7 +16,6 @@
from oslo_log import log
from octavia.common import config
-from octavia.i18n import _LI
LOG = log.getLogger(__name__)
@@ -25,6 +24,5 @@
"""Sets global config from config file and sets up logging."""
argv = argv or []
config.init(argv[1:])
- LOG.info(_LI('Starting ... |
d568e040293da3438293fb007a762fd35b8c7483 | extras/client.py | extras/client.py | import os
from email.utils import formatdate
from datetime import datetime
from time import mktime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keybar.settings')
import django
django.setup()
from django.conf import settings
from httpsig.requests_auth import HTTPSignatureAuth
import requests
from keybar.models.u... | import os
from email.utils import formatdate
from datetime import datetime
from time import mktime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keybar.settings')
import django
django.setup()
from django.conf import settings
from httpsig.requests_auth import HTTPSignatureAuth
import requests
from keybar.models.u... | Fix path, use rsa-sha256 algorithm to actually use the rsa-base verification | Fix path, use rsa-sha256 algorithm to actually use the rsa-base verification
| Python | bsd-3-clause | keybar/keybar | ---
+++
@@ -15,7 +15,7 @@
from keybar.models.user import User
# TODO: Use a secret RSA key as secret.
-secret = open('example_keys/private_key.pem', 'rb').read()
+secret = open('extras/example_keys/private_key.pem', 'rb').read()
user = User.objects.get(username='admin')
signature_headers = ['(request-target)'... |
41c6b1820e8b23079d9098526854c9a60859d128 | gcloud_expenses/test_views.py | gcloud_expenses/test_views.py | import unittest
class ViewTests(unittest.TestCase):
def setUp(self):
from pyramid import testing
self.config = testing.setUp()
def tearDown(self):
from pyramid import testing
testing.tearDown()
def test_my_view(self):
from pyramid import testing
from .view... | import unittest
class ViewTests(unittest.TestCase):
def setUp(self):
from pyramid import testing
self.config = testing.setUp()
def tearDown(self):
from pyramid import testing
testing.tearDown()
def test_home_page(self):
from pyramid import testing
from .vi... | Fix test broken in rename. | Fix test broken in rename.
| Python | apache-2.0 | GoogleCloudPlatform/google-cloud-python-expenses-demo,GoogleCloudPlatform/google-cloud-python-expenses-demo | ---
+++
@@ -10,9 +10,9 @@
from pyramid import testing
testing.tearDown()
- def test_my_view(self):
+ def test_home_page(self):
from pyramid import testing
- from .views import my_view
+ from .views import home_page
request = testing.DummyRequest()
- inf... |
4691e024986a24930c88646cf3a3ae95683dc880 | main.py | main.py | """pluss, a feed proxy for G+"""
import logging
from pluss.app import app
@app.before_first_request
def setup_logging():
if not app.debug:
# In production mode, add log handler to sys.stderr.
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
"%(asctime)s... | """pluss, a feed proxy for G+"""
import logging
from pluss.app import app
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
@app.before_first_request
def setup_logging():
if not app.debug:
# In production mode, add log handler to sys.stderr.
handler = logging.Strea... | Add proxyfix for X-Forwarded-For header | Add proxyfix for X-Forwarded-For header
| Python | mit | ayust/pluss,ayust/pluss | ---
+++
@@ -2,6 +2,8 @@
import logging
from pluss.app import app
+from werkzeug.contrib.fixers import ProxyFix
+app.wsgi_app = ProxyFix(app.wsgi_app)
@app.before_first_request
def setup_logging(): |
769c83564d5f2272837c2fbea6d781110b71b8ca | main.py | main.py | from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vect... | from sys import argv, stderr
from drawer import *
from kmeans import kmeans
def read_vectors(file_name):
result = None
with open(file_name, 'r') as f:
vector_length = int(f.readline())
vectors = list(map(lambda line: tuple(map(int, line.split())), f.readlines()))
if all((len(x) == vect... | Fix trying to display result in case of not 2D vectors | Fix trying to display result in case of not 2D vectors
| Python | mit | vanashimko/k-means | ---
+++
@@ -17,10 +17,10 @@
vectors = read_vectors(argv[1])
clusters_count = int(argv[2])
if vectors:
+ clusters = kmeans(vectors, clusters_count=clusters_count)
if len(vectors[0]) == 2:
display_source(vectors)
- clusters = kmeans(vectors, clusters_count=clusters_cou... |
03430a5b0abbd051e878274a669edf5afaa656b3 | sc2/helpers/control_group.py | sc2/helpers/control_group.py | class ControlGroup(set):
def __init__(self, units):
super().__init__({unit.tag for unit in units})
def __hash__(self):
return hash(tuple(sorted(list(self))))
def select_units(self, units):
return units.filter(lambda unit: unit.tag in self)
def missing_unit_tags(self, units):
... | class ControlGroup(set):
def __init__(self, units):
super().__init__({unit.tag for unit in units})
def __hash__(self):
return hash(tuple(sorted(list(self))))
def select_units(self, units):
return units.filter(lambda unit: unit.tag in self)
def missing_unit_tags(self, units):
... | Add modification operations to control groups | Add modification operations to control groups
| Python | mit | Dentosal/python-sc2 | ---
+++
@@ -14,3 +14,17 @@
@property
def empty(self):
return self.amount == 0
+
+ def add_unit(self, units):
+ self.add(unit.tag)
+
+ def add_units(self, units):
+ for unit in units:
+ self.add_unit(unit)
+
+ def remove_unit(self, units):
+ self.remove(unit.... |
6820de9ccdb7cc7263142108881cf98aab85adb1 | space-age/space_age.py | space-age/space_age.py | # File: space_age.py
# Purpose: Write a program that, given an age in seconds, calculates
# how old someone is in terms of a given planet's solar years.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Saturday 17 September 2016, 06:09 PM
class SpaceAge(object):
"""docstrin... | # File: space_age.py
# Purpose: Write a program that, given an age in seconds, calculates
# how old someone is in terms of a given planet's solar years.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Saturday 17 September 2016, 06:09 PM
class SpaceAge(object):
"""docstrin... | Add other planets age function | Add other planets age function
| Python | mit | amalshehu/exercism-python | ---
+++
@@ -15,7 +15,32 @@
return round((self._seconds / 31557600), 2)
def on_mercury(self):
- return round((self._seconds / 31557600) * 0.240846, 2)
+ planet = self.on_earth() * 0.2408467
+ return planet
+
+ def on_venus(self):
+ planet = self.on_earth() * 0.61519726
+ ... |
eb2b91d30244fd44b45ffc21b963256150b59152 | frappe/patches/v11_0/reload_and_rename_view_log.py | frappe/patches/v11_0/reload_and_rename_view_log.py | import frappe
def execute():
if frappe.db.exists('DocType', 'View log'):
frappe.reload_doc('core', 'doctype', 'view_log', force=True)
frappe.db.sql("INSERT INTO `tabView Log` SELECT * from `tabView log`")
frappe.delete_doc('DocType', 'View log')
frappe.reload_doc('core', 'doctype', 'view_log', force=True)
el... | import frappe
def execute():
if frappe.db.exists('DocType', 'View log'):
# for mac users direct renaming would not work since mysql for mac saves table name in lower case
# so while renaming `tabView log` to `tabView Log` we get "Table 'tabView Log' already exists" error
# more info https://stackoverflow.com/a/... | Fix rename view log patch for mac users | Fix rename view log patch for mac users
for mac users direct renaming would not work
since mysql for mac saves table name in lower case,
so while renaming `tabView log` to `tabView Log` we get
"Table 'tabView Log' already exists" error
# more info https://stackoverflow.com/a/44753093/5955589
https://dev.mysql.com/doc... | Python | mit | mhbu50/frappe,yashodhank/frappe,vjFaLk/frappe,adityahase/frappe,mhbu50/frappe,almeidapaulopt/frappe,saurabh6790/frappe,adityahase/frappe,vjFaLk/frappe,yashodhank/frappe,saurabh6790/frappe,frappe/frappe,frappe/frappe,vjFaLk/frappe,yashodhank/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,mhbu50/f... | ---
+++
@@ -2,9 +2,26 @@
def execute():
if frappe.db.exists('DocType', 'View log'):
- frappe.reload_doc('core', 'doctype', 'view_log', force=True)
- frappe.db.sql("INSERT INTO `tabView Log` SELECT * from `tabView log`")
+ # for mac users direct renaming would not work since mysql for mac saves table name in l... |
53c39934e19fdad7926a8ad7833cd1737b47cf58 | utilities/errors.py | utilities/errors.py | import os
import simulators
import numpy as np
import json
"""Calculate Errors on the Spectrum.
For a first go using an fixed SNR of 200 for all observations.
"""
def get_snrinfo(star, obs_num, chip):
"""Load SNR info from json file."""
snr_file = os.path.join(simulators.paths["spectra"], "detector_snrs.... | import os
import simulators
import numpy as np
import json
import warnings
"""Calculate Errors on the Spectrum.
For a first go using an fixed SNR of 200 for all observations.
"""
def get_snrinfo(star, obs_num, chip):
"""Load SNR info from json file."""
snr_file = os.path.join(simulators.paths["spectra"],... | Handle no snr information in snr file. (for fake simualtions mainly) | Handle no snr information in snr file. (for fake simualtions mainly)
| Python | mit | jason-neal/companion_simulations,jason-neal/companion_simulations | ---
+++
@@ -2,6 +2,7 @@
import simulators
import numpy as np
import json
+import warnings
"""Calculate Errors on the Spectrum.
@@ -17,8 +18,9 @@
try:
return snr_data[str(star)][str(obs_num)][str(chip)]
except KeyError as e:
- print("No snr data present for {0}-{1}_{2}".format(star, o... |
f1cabc889dd93e26295501097ac9cbf90890a1cd | solvent/config.py | solvent/config.py | import yaml
import os
LOCAL_OSMOSIS = 'localhost:1010'
OFFICIAL_OSMOSIS = None
OFFICIAL_BUILD = False
WITH_OFFICIAL_OBJECT_STORE = True
CLEAN = False
def load(filename):
with open(filename) as f:
data = yaml.load(f.read())
if data is None:
raise Exception("Configuration file must not be empty... | import yaml
import os
LOCAL_OSMOSIS_IF_ROOT = 'localhost:1010'
LOCAL_OSMOSIS_IF_NOT_ROOT = 'localhost:1010'
LOCAL_OSMOSIS = None
OFFICIAL_OSMOSIS = None
OFFICIAL_BUILD = False
WITH_OFFICIAL_OBJECT_STORE = True
CLEAN = False
def load(filename):
with open(filename) as f:
data = yaml.load(f.read())
if d... | Select local osmosis depends if user is root, to avoid permission denied on /var/lib/osmosis | Bugfix: Select local osmosis depends if user is root, to avoid permission denied on /var/lib/osmosis
| Python | apache-2.0 | Stratoscale/solvent,Stratoscale/solvent | ---
+++
@@ -1,7 +1,9 @@
import yaml
import os
-LOCAL_OSMOSIS = 'localhost:1010'
+LOCAL_OSMOSIS_IF_ROOT = 'localhost:1010'
+LOCAL_OSMOSIS_IF_NOT_ROOT = 'localhost:1010'
+LOCAL_OSMOSIS = None
OFFICIAL_OSMOSIS = None
OFFICIAL_BUILD = False
WITH_OFFICIAL_OBJECT_STORE = True
@@ -22,6 +24,12 @@
CLEAN = True... |
536801f970702792b0b23e4795929746ae2f92f8 | src/ggrc/settings/default.py | src/ggrc/settings/default.py |
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By:
# Maintained By:
DEBUG = False
TESTING = False
AUTOBUILD_ASSETS = False
ENABLE_JASMINE = False
FULLTEXT_INDEXER = None
# Deployment-specific vari... | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
DEBUG = False
TESTING = False
# Flask-SQLAlchemy fix to be less than `wait_time` ... | Set SQLALCHEMY_POOL_RECYCLE to be less than `wait_time` | Set SQLALCHEMY_POOL_RECYCLE to be less than `wait_time`
* should fix "MySQL server has gone away" errors in development mode
| Python | apache-2.0 | j0gurt/ggrc-core,vladan-m/ggrc-core,jmakov/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,2947721120/sagacious-capsicum,prasannav7/ggrc-core,hasanalom/ggrc-core,kr41/ggrc-core,2947721120/sagacious-capsicum,VinnieJohns/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-c... | ---
+++
@@ -1,11 +1,15 @@
-
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
-# Created By:
-# Maintained By:
+# Created By: dan@reciprocitylabs.com
+# Maintained By: dan@reciprocitylabs.com
DEBUG = False... |
967240f95edb300d731f24cfb259a1fe4f3bdae5 | webapp_health_monitor/management/commands/verify.py | webapp_health_monitor/management/commands/verify.py | import importlib
import sys
from django.apps import apps
from django.core.management.base import BaseCommand
from webapp_health_monitor.verification_suit import VerificationSuit
class Command(BaseCommand):
SUBMODULE_NAME = 'verificators'
def handle(self, *args, **options):
submodules = self._get_ve... | import importlib
import sys
from django.apps import apps
from django.core.management.base import BaseCommand
from webapp_health_monitor.verification_suit import VerificationSuit
class Command(BaseCommand):
SUBMODULE_NAME = 'verificators'
def handle(self, *args, **options):
submodules = self._get_ve... | Fix python2 django module importerror. | Fix python2 django module importerror.
| Python | mit | pozytywnie/webapp-health-monitor | ---
+++
@@ -16,7 +16,7 @@
try:
importlib.import_module(submodule)
except ImportError as e:
- if str(e) != "No module named '{}'".format(submodule):
+ if not self._import_error_concerns_verificator(submodule, e):
raise e
... |
80529d5032b6728adcaad426310c30b5e6366ad4 | solution.py | solution.py | class Kiosk():
def __init__(self, visit_cost, location):
self.visit_cost = visit_cost
self.location = location
print 'initializing Kiosk'
#patient shold be Person
def visit(self, patient):
if not patient.location == self.location:
print 'patient not in correct lo... | class Kiosk():
def __init__(self, location, visit_cost, diabetes_threshold,
cardio_threshold):
self.location = location
self.visit_cost = visit_cost
self.diabetes_threshold = diabetes_threshold
self.cardio_threshold = cardio_threshold
#Initial cost to create kiosk... | Clean up and finish Kiosk class | Clean up and finish Kiosk class
There was some redundancy because I merged it poorly
| Python | bsd-3-clause | rkawauchi/IHK,rkawauchi/IHK | ---
+++
@@ -1,7 +1,12 @@
class Kiosk():
- def __init__(self, visit_cost, location):
+ def __init__(self, location, visit_cost, diabetes_threshold,
+ cardio_threshold):
+ self.location = location
self.visit_cost = visit_cost
- self.location = location
+ self.diabetes_thr... |
4dbd402879a626d7fb1d6fe5108695d1eeb32c42 | hiispider/servers/mixins/amqp.py | hiispider/servers/mixins/amqp.py | class AMQPMixin(object):
amqp_setup = False
def setupAMQP(self, config):
if not self.amqp_setup:
# Create AMQP Connection
# AMQP connection parameters
self.amqp_host = config["amqp_host"]
self.amqp_port = config.get("amqp_port", 5672)
self.am... | class AMQPMixin(object):
amqp_setup = False
def setupAMQP(self, config):
if not self.amqp_setup:
# Create AMQP Connection
# AMQP connection parameters
self.amqp_host = config["amqp_host"]
self.amqp_port = config.get("amqp_port", 5672)
self.am... | Set prefetch count to 1000. | Set prefetch count to 1000.
| Python | mit | hiidef/hiispider,hiidef/hiispider | ---
+++
@@ -12,5 +12,5 @@
self.amqp_password = config["amqp_password"]
self.amqp_queue = config["amqp_queue"]
self.amqp_exchange = config["amqp_exchange"]
- self.amqp_prefetch_count = 100
+ self.amqp_prefetch_count = 1000
self.amqp_setup = True |
be8344c2f796ecab60669630f4729c4ffa41c83b | web/impact/impact/v1/views/utils.py | web/impact/impact/v1/views/utils.py | def merge_data_by_id(data):
result = {}
for datum in data:
id = datum["id"]
item = result.get(id, {})
item.update(datum)
result[id] = item
return result.values()
def map_data(klass, query, order, data_keys, output_keys):
result = klass.objects.filter(query).order_by(ord... | def coalesce_dictionaries(data, merge_field="id"):
"Takes a sequence of dictionaries, merges those that share the
same merge_field, and returns a list of resulting dictionaries"
result = {}
for datum in data:
merge_id = datum[merge_field]
item = result.get(merge_id, {})
item.upda... | Rename merge_data_by_id, add doc-string, get rid of id as a local | [AC-4835] Rename merge_data_by_id, add doc-string, get rid of id as a local
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | ---
+++
@@ -1,10 +1,12 @@
-def merge_data_by_id(data):
+def coalesce_dictionaries(data, merge_field="id"):
+ "Takes a sequence of dictionaries, merges those that share the
+ same merge_field, and returns a list of resulting dictionaries"
result = {}
for datum in data:
- id = datum["id"]
- ... |
028903036ac4bd3bf4a7b91ceda43a6c450f7e20 | pipeline_notifier/main.py | pipeline_notifier/main.py | import os
import cherrypy
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
def run_server():
cherrypy.tree.graft(app, '/')
cherrypy.config.update({
'engine.autoreload_on': True,
'log.screen': True,
'server.socket_port': 8080,
... | import os
import cherrypy
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
def run_server():
cherrypy.tree.graft(app, '/')
cherrypy.config.update({
'engine.autoreload_on': True,
'log.screen': True,
'server.socket_port': int(os.envir... | Use port from env if available | Use port from env if available
| Python | mit | pimterry/pipeline-notifier | ---
+++
@@ -14,7 +14,7 @@
cherrypy.config.update({
'engine.autoreload_on': True,
'log.screen': True,
- 'server.socket_port': 8080,
+ 'server.socket_port': int(os.environ.get('PORT', '8080')),
'server.socket_host': '0.0.0.0'
})
|
269474608221e35907896f5f618e69d6e5136388 | facepy/exceptions.py | facepy/exceptions.py | class FacepyError(Exception):
"""Base class for exceptions raised by Facepy."""
def __init__(self, message):
self.message = message
def _get_message(self):
return self._message
def _set_message(self, message):
self._message = message
message = property(_get_message, _set_... | class FacepyError(Exception):
"""Base class for exceptions raised by Facepy."""
def __init__(self, message):
self.message = message
| Remove uneccessary getter and setter | Remove uneccessary getter and setter
| Python | mit | merwok-forks/facepy,jwjohns/facepy,jgorset/facepy,Spockuto/facepy,liorshahverdi/facepy,buzzfeed/facepy,jwjohns/facepy | ---
+++
@@ -3,11 +3,3 @@
def __init__(self, message):
self.message = message
-
- def _get_message(self):
- return self._message
-
- def _set_message(self, message):
- self._message = message
-
- message = property(_get_message, _set_message) |
23e1868aa9d0c0a6611914b0f648c46d329e00db | genes/gnu_coreutils/commands.py | genes/gnu_coreutils/commands.py | #!/usr/bin/env python
from genes.process.commands import run
from genes.posix.traits import only_posix
@only_posix()
def chgrp(path, group):
run(['chgrp', group, path])
@only_posix()
def chown(path, user):
run(['chown', user, path])
@only_posix()
def mkdir(path, mode=None):
if mode:
run(['mkdir... | #!/usr/bin/env python
from typing import Optional, Dict
from genes.process.commands import run
from genes.posix.traits import only_posix
@only_posix()
def chgrp(path, group):
run(['chgrp', group, path])
@only_posix()
def chown(path, user):
run(['chown', user, path])
@only_posix()
def mkdir(path, mode=None... | Create some coreutils bindings. they're not good | Create some coreutils bindings. they're not good
| Python | mit | hatchery/genepool,hatchery/Genepool2 | ---
+++
@@ -1,4 +1,6 @@
#!/usr/bin/env python
+from typing import Optional, Dict
+
from genes.process.commands import run
from genes.posix.traits import only_posix
@@ -21,10 +23,13 @@
@only_posix()
-def useradd():
- pass
+def useradd(*args):
+ # FIXME: this is a bad way to do things
+ # FIXME: sigh... |
6d8b99b5e4dab49c5a2e90b07f02072c116a7367 | robots/models.py | robots/models.py | from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
class File(models.Model):
site = models.OneToOneField(Site, verbose_name=_(u'site'))
content = models.TextField(_(u'file content'))
objects = models.Manager()
class Meta... | from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
class File(models.Model):
site = models.OneToOneField(Site, verbose_name=_(u'site'))
content = models.TextField(_(u'file content'))
class Meta:
verbose_name = _(u'rob... | Remove unnecessary manager declaration from File model | Remove unnecessary manager declaration from File model
| Python | isc | trilan/lemon-robots,trilan/lemon-robots | ---
+++
@@ -8,8 +8,6 @@
site = models.OneToOneField(Site, verbose_name=_(u'site'))
content = models.TextField(_(u'file content'))
- objects = models.Manager()
-
class Meta:
verbose_name = _(u'robots.txt file')
verbose_name_plural = _(u'robots.txt files') |
aae85883bb99ac15f6922506fa64c4492101b602 | utils/lit/tests/shared-output.py | utils/lit/tests/shared-output.py | # RUN: rm -rf %t && mkdir -p %t
# RUN: echo 'lit_config.load_config(config, "%{inputs}/shared-output/lit.cfg")' > %t/lit.site.cfg
# RUN: %{lit} %t
# RUN: FileCheck %s < %t/Output/Shared/SHARED.tmp
# RUN: FileCheck -check-prefix=NEGATIVE %s < %t/Output/Shared/SHARED.tmp
# RUN: FileCheck -check-prefix=OTHER %s < %t/Outp... | # RUN: rm -rf %t && mkdir -p %t
# RUN: echo 'lit_config.load_config(config, os.path.join("%{inputs}", "shared-output", "lit.cfg"))' > %t/lit.site.cfg
# RUN: %{lit} %t
# RUN: FileCheck %s < %t/Output/Shared/SHARED.tmp
# RUN: FileCheck -check-prefix=NEGATIVE %s < %t/Output/Shared/SHARED.tmp
# RUN: FileCheck -check-prefix... | Fix new test for systems that don't use / as os.path.sep | lit.py: Fix new test for systems that don't use / as os.path.sep
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@315773 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llv... | ---
+++
@@ -1,5 +1,5 @@
# RUN: rm -rf %t && mkdir -p %t
-# RUN: echo 'lit_config.load_config(config, "%{inputs}/shared-output/lit.cfg")' > %t/lit.site.cfg
+# RUN: echo 'lit_config.load_config(config, os.path.join("%{inputs}", "shared-output", "lit.cfg"))' > %t/lit.site.cfg
# RUN: %{lit} %t
# RUN: FileCheck %s < %t... |
5867a09fb43f8c4480d7aef89a200e952406a648 | dbaas/integrations/credentials/admin/__init__.py | dbaas/integrations/credentials/admin/__init__.py | # -*- coding:utf-8 -*-
from django.contrib import admin
from .. import models
admin.site.register(models.IntegrationType, )
admin.site.register(models.IntegrationCredential, )
| # -*- coding:utf-8 -*-
from django.contrib import admin
from .integration_credential import IntegrationCredentialAdmin
from .integration_type import IntegrationTypeAdmin
from .. import models
admin.site.register(models.IntegrationType, IntegrationTypeAdmin)
admin.site.register(models.IntegrationCredential, Integration... | Enable integration credential and integration type admin | Enable integration credential and integration type admin
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -1,6 +1,8 @@
# -*- coding:utf-8 -*-
from django.contrib import admin
+from .integration_credential import IntegrationCredentialAdmin
+from .integration_type import IntegrationTypeAdmin
from .. import models
-admin.site.register(models.IntegrationType, )
-admin.site.register(models.IntegrationCredentia... |
c08c437b22982667e8ed413739147caec6c5d1ca | api/preprints/urls.py | api/preprints/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),
url(r'^(?P<node_id>\w+)/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),
url(r'^(?P<node_id>\w+)/contributors/$', views.PreprintContrib... | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),
url(r'^(?P<node_id>\w+)/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),
url(r'^(?P<node_id>\w+)/contributors/$', views.PreprintContrib... | Add URL route for updating provider relationship | Add URL route for updating provider relationship
| Python | apache-2.0 | mluo613/osf.io,rdhyee/osf.io,samchrisinger/osf.io,leb2dg/osf.io,cslzchen/osf.io,chrisseto/osf.io,leb2dg/osf.io,binoculars/osf.io,mluo613/osf.io,Nesiehr/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,emetsger/osf.io,monikagrabowska/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,icereval/osf.io,binocu... | ---
+++
@@ -6,4 +6,5 @@
url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),
url(r'^(?P<node_id>\w+)/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),
url(r'^(?P<node_id>\w+)/contributors/$', views.PreprintContributorsList.as_view(), name=views.PreprintCo... |
597f586d2cf42f31a0179efc7ac8441f33b3d637 | lib/mysql.py | lib/mysql.py | import pymysql
class MySQL():
def __init__(self, host, user, password, port):
self._host = host
self._user = user
self._password = password
self._conn = pymysql.connect(host=host, port=port,
user=user, passwd=password)
self._cursor = self._conn.cursor... | import pymysql
class MySQL():
def __init__(self, host, user, password, port):
self._host = host
self._user = user
self._password = password
self._port = port
self._conn = pymysql.connect(host=host, port=port,
user=user, passwd=password)
self._... | Define the port variable for reconnection | Define the port variable for reconnection | Python | mit | ImShady/Tubey | ---
+++
@@ -6,6 +6,7 @@
self._host = host
self._user = user
self._password = password
+ self._port = port
self._conn = pymysql.connect(host=host, port=port,
user=user, passwd=password)
self._cursor = self._conn.cursor() |
999752ec378bbf6d3017f7afc964090c6871b7d4 | app/user_administration/tests.py | app/user_administration/tests.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
class LoginRequiredTest(TestCase):
def test_login_required(self):
response = self.client.get('/')
self.assertEqual(
response.status_code,
302,
msg="Login Required Va... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Clients
class LoginRequiredTest(TestCase):
def test_login_required(self):
response = self.client.get('/')
self.assertEqual(
r... | Add TestCase for ClientListView and ClientCreateView | Add TestCase for ClientListView and ClientCreateView
| Python | mit | rexhepberlajolli/RHChallenge,rexhepberlajolli/RHChallenge | ---
+++
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
+from django.contrib.auth.models import User
+from .models import Clients
class LoginRequiredTest(TestCase):
@@ -16,3 +18,46 @@
'/login?next=/',
msg="Login Require... |
912c8f8f3626c7da92b6864e02dfc2534f4f7873 | exercises/leap/leap_test.py | exercises/leap/leap_test.py | import unittest
from leap import is_leap_year
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.5.1
class LeapTest(unittest.TestCase):
def test_year_not_divisible_by_4(self):
self.assertIs(is_leap_year(2015), False)
def year_divisible_by_2_not_divisible_by_4(self):
sel... | import unittest
from leap import is_leap_year
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.5.1
class LeapTest(unittest.TestCase):
def test_year_not_divisible_by_4(self):
self.assertIs(is_leap_year(2015), False)
def test_year_divisible_by_2_not_divisible_by_4(self):
... | Stop leep test being ignored | Stop leep test being ignored
| Python | mit | N-Parsons/exercism-python,exercism/python,behrtam/xpython,exercism/xpython,jmluy/xpython,smalley/python,exercism/xpython,behrtam/xpython,N-Parsons/exercism-python,jmluy/xpython,exercism/python,smalley/python | ---
+++
@@ -5,11 +5,12 @@
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.5.1
+
class LeapTest(unittest.TestCase):
def test_year_not_divisible_by_4(self):
self.assertIs(is_leap_year(2015), False)
- def year_divisible_by_2_not_divisible_by_4(self):
+ def test_year_di... |
8b07dde78e753f6dce663481a68856024ed2fc49 | plutokore/__init__.py | plutokore/__init__.py | from .environments.makino import MakinoProfile
from .environments.king import KingProfile
from .jet import AstroJet
from . import luminosity
from . import plotting
from . import simulations
from . import helpers
from . import io
__all__ = [
'environments',
'luminosity',
'plotting',
'simulations',
... | from .environments.makino import MakinoProfile
from .environments.king import KingProfile
from .jet import AstroJet
from . import luminosity
from . import plotting
from . import simulations
from . import helpers
from . import io
from . import configuration
__all__ = [
'environments',
'luminosity',
'plotti... | Add configuration module to package exports | Add configuration module to package exports
| Python | mit | opcon/plutokore,opcon/plutokore | ---
+++
@@ -7,6 +7,7 @@
from . import simulations
from . import helpers
from . import io
+from . import configuration
__all__ = [
'environments',
@@ -16,4 +17,5 @@
'jet',
'helpers',
'io',
+ 'configuration',
] |
fcd2328549dcec2986e3b972f1a8bcfb0cf2e21b | rst2pdf/utils.py | rst2pdf/utils.py | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (ca... | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of f... | Add unit support for spacers | Add unit support for spacers | Python | mit | pombreda/rst2pdf,liuyi1112/rst2pdf,pombreda/rst2pdf,liuyi1112/rst2pdf,rst2pdf/rst2pdf,rst2pdf/rst2pdf | ---
+++
@@ -9,7 +9,7 @@
from reportlab.platypus import Spacer
from flowables import *
-
+from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
@@ -34,7 +34,8 @@
else:
elements.append(MyPageBreak(tokens[1]))
... |
6b0167514bb41f877945b408638fab72873f2da8 | postgres_copy/__init__.py | postgres_copy/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.db import connection
from .copy_from import CopyMapping
from .copy_to import SQLCopyToCompiler, CopyToQuery
__version__ = '2.0.0'
class CopyQuerySet(models.QuerySet):
"""
Subclass of QuerySet that adds from_csv and to_csv m... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.db import models
from django.db import connection
from .copy_from import CopyMapping
from .copy_to import SQLCopyToCompiler, CopyToQuery
__version__ = '2.0.0'
class CopyQuerySet(models.QuerySet):
"""
Subclass of QuerySet that adds from_csv and to_csv m... | Add CopyToQuerySet to available imports | Add CopyToQuerySet to available imports
| Python | mit | california-civic-data-coalition/django-postgres-copy | ---
+++
@@ -32,8 +32,9 @@
__all__ = (
+ 'CopyManager',
'CopyMapping',
+ 'CopyToQuery',
+ 'CopyToQuerySet',
'SQLCopyToCompiler',
- 'CopyToQuery',
- 'CopyManager',
) |
639032215f7a51ca146810e8261448f4d0a318aa | downstream_node/models.py | downstream_node/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from downstream_node.startup import db
class Files(db.Model):
__tablename__ = 'files'
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
filepath = db.Column('filepath', db.String())
class Challenges(db.Model):
__tablename__ = 'challenge... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from downstream_node.startup import db
class Files(db.Model):
__tablename__ = 'files'
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
filepath = db.Column('filepath', db.String())
class Challenges(db.Model):
__tablename__ = 'challenge... | Add root seed to model | Add root seed to model
| Python | mit | Storj/downstream-node,Storj/downstream-node | ---
+++
@@ -15,6 +15,7 @@
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
filepath = db.Column(db.ForeignKey('files.filepath'))
- block = db.Column('block', db.String())
- seed = db.Column('seed', db.String())
- response = db.Column('response', db.String(), nullable=True)
+ ... |
c11fd9f792afb71e01224f149121bc13a6a9bed8 | scripts/utils.py | scripts/utils.py | #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
import json
import os
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSO... | #!/usr/bin/env python3
# Touhou Community Reliant Automatic Patcher
# Scripts
#
# ----
#
"""Utility functions shared among all the scripts."""
from collections import OrderedDict
import json
import os
json_load_params = {
'object_pairs_hook': OrderedDict
}
json_dump_params = {
'ensure_ascii': False,
'in... | Use the OrderedDict class for JSON objects. | scripts: Use the OrderedDict class for JSON objects.
| Python | unlicense | thpatch/thcrap,thpatch/thcrap,VBChunguk/thcrap,thpatch/thcrap,VBChunguk/thcrap,thpatch/thcrap,thpatch/thcrap,VBChunguk/thcrap | ---
+++
@@ -7,8 +7,13 @@
#
"""Utility functions shared among all the scripts."""
+from collections import OrderedDict
import json
import os
+
+json_load_params = {
+ 'object_pairs_hook': OrderedDict
+}
json_dump_params = {
'ensure_ascii': False,
@@ -20,7 +25,7 @@
# Default parameters for JSON input ... |
0e22a642526612ff9d19d1b421a1aacea4109f15 | pylearn2/datasets/hdf5.py | pylearn2/datasets/hdf5.py | """Objects for datasets serialized in HDF5 format (.h5)."""
import h5py
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
class HDF5Dataset(DenseDesignMatrix):
"""Dense dataset loaded from an HDF5 file."""
def __init__(self, filename, key):
with h5py.File(filename) as f:
d... | """Objects for datasets serialized in HDF5 format (.h5)."""
import h5py
from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix
class HDF5Dataset(DenseDesignMatrix):
"""Dense dataset loaded from an HDF5 file."""
def __init__(self, filename, X=None, topo_view=None, y=None, **kwargs):
"""
... | Support for targets in HDF5 datasets | Support for targets in HDF5 datasets
| Python | bsd-3-clause | alexjc/pylearn2,pombredanne/pylearn2,kose-y/pylearn2,TNick/pylearn2,lancezlin/pylearn2,theoryno3/pylearn2,aalmah/pylearn2,se4u/pylearn2,woozzu/pylearn2,daemonmaker/pylearn2,daemonmaker/pylearn2,goodfeli/pylearn2,JesseLivezey/pylearn2,nouiz/pylearn2,ddboline/pylearn2,CIFASIS/pylearn2,w1kke/pylearn2,lamblin/pylearn2,kast... | ---
+++
@@ -4,10 +4,26 @@
class HDF5Dataset(DenseDesignMatrix):
"""Dense dataset loaded from an HDF5 file."""
- def __init__(self, filename, key):
+ def __init__(self, filename, X=None, topo_view=None, y=None, **kwargs):
+ """
+ Loads data and labels from HDF5 file.
+
+ Parameters
+... |
b824cadfe61de19b5ff0f7391fe2b21b034c71b4 | readdata.py | readdata.py | import os,sys
import json
import csv
import soundfile as sf
from scipy.fftpack import dct
from features import mfcc,fbank,sigproc,logfbank
def parseJSON(directory, filename):
data=[]
jsonMeta=[]
#open all files that end with .json in <path> directory
#and store certain attributes
try:
json_... | import os,sys
import json
import csv
from yaafelib import *
def parseJSON(directory, filename):
data=[]
jsonMeta=[]
#open all files that end with .json in <path> directory
#and store certain attributes
try:
json_data=open(os.path.join(directory, filename))
except(IOError, RuntimeError )... | Use yaafe for feature extraction | Use yaafe for feature extraction
Right now we extract two features (mfcc and perceptual spread)
but there is a lot of work to be done on the feature extraction method
so this is probably going to change
| Python | mit | lOStres/JaFEM | ---
+++
@@ -1,9 +1,7 @@
import os,sys
import json
import csv
-import soundfile as sf
-from scipy.fftpack import dct
-from features import mfcc,fbank,sigproc,logfbank
+from yaafelib import *
def parseJSON(directory, filename):
data=[]
@@ -30,17 +28,18 @@
return list(csvMeta)[0]
-#returns a vect... |
b0d9a11292b6d6b17fe8b72d7735d26c47599187 | linkatos/printer.py | linkatos/printer.py | def bot_says(channel, text, slack_client):
return slack_client.api_call("chat.postMessage",
channel=channel,
text=text,
as_user=True)
def compose_explanation(url):
return "If you would like {} to be stored pleas... | def bot_says(channel, text, slack_client):
return slack_client.api_call("chat.postMessage",
channel=channel,
text=text,
as_user=True)
def compose_explanation(url):
return "If you would like {} to be stored pleas... | Change iteration over a collection based on ags suggestion | refactor: Change iteration over a collection based on ags suggestion
| Python | mit | iwi/linkatos,iwi/linkatos | ---
+++
@@ -20,13 +20,10 @@
if len(url_cache_list) == 0:
return "The list is empty"
- list_message = "The list of urls to be confirmed is: \n"
+ intro = "The list of urls to be confirmed is: \n"
+ options = ["{} - {}".format(i, v['url']) for i, v in enumerate(url_cache_list)]
- for index... |
547725be668e1e639ec0e6569e18a1e8bf03585c | tictactoe/settings_production.py | tictactoe/settings_production.py | from django.core.exceptions import ImproperlyConfigured
from .settings import *
def get_env_variable(var_name):
"""
Get the environment variable or return exception.
"""
try:
return os.environ[var_name]
except KeyError:
error_msg = 'Set the %s environment variable' % var_name
... | from django.core.exceptions import ImproperlyConfigured
from .settings import *
def get_env_variable(var_name):
"""
Get the environment variable or return exception.
"""
try:
return os.environ[var_name]
except KeyError:
error_msg = 'Set the %s environment variable' % var_name
... | Add Heroku DNS to allowed hosts | Add Heroku DNS to allowed hosts
| Python | apache-2.0 | NejcZupec/tictactoe,NejcZupec/tictactoe,NejcZupec/tictactoe | ---
+++
@@ -16,8 +16,10 @@
DEBUG = False
-# TODO: temporarily disabled to test Heroku
-# ALLOWED_HOSTS = ['tictactoe.zupec.net']
+ALLOWED_HOSTS = [
+ 'tictactoe.zupec.net',
+ 'tictactoe-zupec.herokuapp.com',
+]
SECRET_KEY = get_env_variable('SECRET_KEY')
|
221f77cfba10cb52ab9fbb639cc948d7a61beb98 | electionleaflets/settings/zappa.py | electionleaflets/settings/zappa.py | import os
from .base import *
# GEOS_LIBRARY_PATH = '/var/task/libgeos_c.so'
ALLOWED_HOSTS = ['*']
# Override the database name and user if needed
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'HOST': os.environ.get('DATABASE_HOST'),
'USER': os.environ.ge... | import os
from .base import *
GEOS_LIBRARY_PATH = '/var/task/libgeos_c.so'
ALLOWED_HOSTS = ['*']
# Override the database name and user if needed
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'HOST': os.environ.get('DATABASE_HOST'),
'USER': os.environ.get(... | Fix the geos library location | Fix the geos library location
| Python | mit | DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets | ---
+++
@@ -2,7 +2,7 @@
from .base import *
-# GEOS_LIBRARY_PATH = '/var/task/libgeos_c.so'
+GEOS_LIBRARY_PATH = '/var/task/libgeos_c.so'
ALLOWED_HOSTS = ['*']
|
32e2d6e866cee45d4955aa020d9b9bd3c0a2b700 | pudb/__init__.py | pudb/__init__.py | VERSION = "0.91.2"
CURRENT_DEBUGGER = [None]
def set_trace():
if CURRENT_DEBUGGER[0] is None:
from pudb.debugger import Debugger
dbg = Debugger()
CURRENT_DEBUGGER[0] = dbg
import sys
dbg.set_trace(sys._getframe().f_back)
def post_mortem(t):
p = Debugger()
p.r... | VERSION = "0.91.2"
CURRENT_DEBUGGER = [None]
def set_trace():
if CURRENT_DEBUGGER[0] is None:
from pudb.debugger import Debugger
dbg = Debugger()
CURRENT_DEBUGGER[0] = dbg
import sys
dbg.set_trace(sys._getframe().f_back)
def post_mortem(t):
p = Debugger()
p.r... | Print a warning about the move to '-m pudb.run'. | Print a warning about the move to '-m pudb.run'.
| Python | mit | amigrave/pudb,albfan/pudb,amigrave/pudb,albfan/pudb | ---
+++
@@ -29,3 +29,10 @@
def pm():
import sys
post_mortem(sys.last_traceback)
+
+
+
+
+if __name__ == "__main__":
+ print "To keep Python 2.6 happy, you now need to type 'python -m pudb.run'."
+ print "Sorry for the inconvenience." |
bace1847cb9479bfeb271f38eef502f8d3ac240a | qipr/registry/forms/facet_form.py | qipr/registry/forms/facet_form.py | from registry.models import *
from operator import attrgetter
facet_Models = [
BigAim,
Category,
ClinicalArea,
ClinicalSetting,
Keyword,
SafetyTarget,
]
class FacetForm:
def __init__(self):
self.facet_categories = [model.__name__ for model in facet_Models]
for model in face... | from registry.models import *
from operator import attrgetter
facet_Models = [
BigAim,
ClinicalArea,
ClinicalSetting,
Keyword,
]
class FacetForm:
def __init__(self):
self.facet_categories = [model.__name__ for model in facet_Models]
for model in facet_Models:
models = l... | Remove facets from main registry project page | Remove facets from main registry project page
| Python | apache-2.0 | ctsit/qipr,ctsit/qipr,ctsit/qipr,ctsit/qipr,ctsit/qipr | ---
+++
@@ -3,11 +3,9 @@
facet_Models = [
BigAim,
- Category,
ClinicalArea,
ClinicalSetting,
Keyword,
- SafetyTarget,
]
class FacetForm: |
4792515739c4ee671b86aeed39022ad8934d5d7c | artie/applications.py | artie/applications.py | import os
import re
import sys
import settings
triggers = set()
timers = set()
class BadApplicationError(Exception): pass
def trigger(expression):
def decorator(func):
triggers.add((re.compile(expression), func))
return decorator
def timer(time):
def decorator(func):
timers.add((time, f... | import os
import re
import sys
import settings
triggers = set()
timers = set()
class BadApplicationError(Exception): pass
def trigger(expression):
def decorator(func):
triggers.add((re.compile(expression), func))
return decorator
def timer(time):
def decorator(func):
timers.add((time, f... | Use `endswith` instead of string indeces. | Use `endswith` instead of string indeces.
| Python | mit | sumeet/artie | ---
+++
@@ -22,7 +22,7 @@
sys.path.insert(0, settings.APPLICATION_PATH)
for filename in os.listdir(settings.APPLICATION_PATH):
- if filename != '__init__.py' and filename[-3:] == '.py':
+ if filename != '__init__.py' and filename.endswith('.py'):
if filename == 'triggers.py':
raise Bad... |
46e1672bb0226ae8157d63a2d73edbfefcd644e9 | src/test/test_google_maps.py | src/test/test_google_maps.py | import unittest
import googlemaps
from pyrules2.googlemaps import driving_roundtrip
COP = 'Copenhagen, Denmark'
MAD = 'Madrid, Spain'
BER = 'Berlin, Germany'
LIS = 'Lisbon, Portugal'
KM = 1000
class Test(unittest.TestCase):
def setUp(self):
# TODO: Sane way to import key
with open('/Users/nhc/gi... | from os import environ
import unittest
import googlemaps
from pyrules2.googlemaps import driving_roundtrip
COP = 'Copenhagen, Denmark'
MAD = 'Madrid, Spain'
BER = 'Berlin, Germany'
LIS = 'Lisbon, Portugal'
KM = 1000
class Test(unittest.TestCase):
def setUp(self):
try:
key = environ['GOOGLE_M... | Move API key to environment variable | Move API key to environment variable
| Python | mit | mr-niels-christensen/pyrules | ---
+++
@@ -1,3 +1,4 @@
+from os import environ
import unittest
import googlemaps
from pyrules2.googlemaps import driving_roundtrip
@@ -12,17 +13,18 @@
class Test(unittest.TestCase):
def setUp(self):
- # TODO: Sane way to import key
- with open('/Users/nhc/git/pyrules/google-maps-api-key.txt'... |
1bc3bd857e6b62d9cd63c6b2edfd7003dd8110b4 | modules/apis/sr_com.py | modules/apis/sr_com.py | #! /usr/bin/env python2.7
import modules.apis.api_base as api
class SRcomAPI(api.API):
def __init(self, session = None):
super(SRcomAPI, self).__init__("http://www.speedrun.com/api/v1", session)
def get_user_pbs(self, user, embeds = "", **kwargs):
# Embeds should be list of parameters
... | #! /usr/bin/env python2.7
import modules.apis.api_base as api
class SRcomAPI(api.API):
def __init__(self, session = None):
super(SRcomAPI, self).__init__("http://www.speedrun.com/api/v1", session)
def get_user_pbs(self, user, embeds = "", **kwargs):
# Embeds should be list of parameters
... | Fix forgotten __ for init | Fix forgotten __ for init
| Python | mit | BatedUrGonnaDie/salty_bot | ---
+++
@@ -4,7 +4,7 @@
class SRcomAPI(api.API):
- def __init(self, session = None):
+ def __init__(self, session = None):
super(SRcomAPI, self).__init__("http://www.speedrun.com/api/v1", session)
def get_user_pbs(self, user, embeds = "", **kwargs): |
51d1701bbc8b25bfd7b4f70c83fec7a46d965bef | fireplace/cards/brawl/decks_assemble.py | fireplace/cards/brawl/decks_assemble.py | """
Decks Assemble
"""
from ..utils import *
# Tarnished Coin
class TB_011:
play = ManaThisTurn(CONTROLLER, 1)
| """
Decks Assemble
"""
from ..utils import *
# Deckbuilding Enchant
class TB_010:
events = (
OWN_TURN_BEGIN.on(Discover(CONTROLLER, RandomCollectible())),
Play(CONTROLLER).on(Shuffle(CONTROLLER, Copy(Play.CARD))),
OWN_TURN_END.on(Shuffle(CONTROLLER, FRIENDLY_HAND))
)
# Tarnished Coin
class TB_011:
play = M... | Implement Decks Assemble brawl rules on the Deckbuilding Enchant | Implement Decks Assemble brawl rules on the Deckbuilding Enchant
| Python | agpl-3.0 | Ragowit/fireplace,NightKev/fireplace,beheh/fireplace,smallnamespace/fireplace,Ragowit/fireplace,jleclanche/fireplace,smallnamespace/fireplace | ---
+++
@@ -5,6 +5,14 @@
from ..utils import *
+# Deckbuilding Enchant
+class TB_010:
+ events = (
+ OWN_TURN_BEGIN.on(Discover(CONTROLLER, RandomCollectible())),
+ Play(CONTROLLER).on(Shuffle(CONTROLLER, Copy(Play.CARD))),
+ OWN_TURN_END.on(Shuffle(CONTROLLER, FRIENDLY_HAND))
+ )
+
# Tarnished Coin
class T... |
3f4415bd551b52418a5999a1ea64e31d15097802 | framework/transactions/commands.py | framework/transactions/commands.py | # -*- coding: utf-8 -*-
from framework.mongo import database as proxy_database
def begin(database=None):
database = database or proxy_database
database.command('beginTransaction')
def rollback(database=None):
database = database or proxy_database
database.command('rollbackTransaction')
def commit... | # -*- coding: utf-8 -*-
from framework.mongo import database as proxy_database
from pymongo.errors import OperationFailure
def begin(database=None):
database = database or proxy_database
database.command('beginTransaction')
def rollback(database=None):
database = database or proxy_database
try:
... | Fix rollback transaction issue bby adding except for Operation Failure to rollback | Fix rollback transaction issue bby adding except for Operation Failure to rollback
| Python | apache-2.0 | erinspace/osf.io,doublebits/osf.io,brandonPurvis/osf.io,brandonPurvis/osf.io,kwierman/osf.io,GageGaskins/osf.io,hmoco/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,felliott/osf.io,cosenal/osf.io,abought/osf.io,kch8qx/osf.io,haoyuchen1992/osf.io,himanshuo/osf.io,sbt9uc/osf.io,bdyetton/prettychart,samchrisinger/osf.io,mon... | ---
+++
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from framework.mongo import database as proxy_database
+from pymongo.errors import OperationFailure
def begin(database=None):
@@ -10,7 +11,10 @@
def rollback(database=None):
database = database or proxy_database
- database.command('rollbackTransactio... |
7076e7eb0fcce37159aa58c2c0699674434115d9 | relaygram/http_server.py | relaygram/http_server.py | import http.server
from threading import Thread
import os.path
class HTTPHandler:
def __init__(self, config):
self.config = config
handler = HTTPHandler.make_http_handler(self.config['media_dir'])
self.httpd = http.server.HTTPServer(('', self.config['media']['port']), handler)
se... | import http.server
from threading import Thread
import os.path
class HTTPHandler:
def __init__(self, config):
self.config = config
handler = HTTPHandler.make_http_handler(self.config['media_dir'])
self.httpd = http.server.HTTPServer(('', self.config['media']['port']), handler)
se... | Use commonprefix to break dep on 3.5 | Use commonprefix to break dep on 3.5
| Python | mit | Surye/relaygram | ---
+++
@@ -28,7 +28,7 @@
def do_GET(self):
file_path = os.path.abspath(root_path + self.path)
- if os.path.commonpath([root_path, file_path]) != os.path.abspath(root_path): # Detect path traversal attempt
+ if os.path.commonprefix([root_path, file_path])... |
43dca4ad969e44bb753c152e8f7768febea6fb68 | quantecon/__init__.py | quantecon/__init__.py | """
Import the main names to top level.
"""
from .compute_fp import compute_fixed_point
from .discrete_rv import DiscreteRV
from .ecdf import ECDF
from .estspec import smooth, periodogram, ar_periodogram
from .graph_tools import DiGraph
from .gridtools import cartesian, mlinspace
from .kalman import Kalman
from .lae i... | """
Import the main names to top level.
"""
try:
import numba
except:
raise ImportError("Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.")
from .compute_fp import compute_fixed_point
from .discrete_rv import DiscreteRV
from .ecdf import ECDF
fr... | Add Check for numba in base anaconda distribution. If not found issue meaningful warning message | Add Check for numba in base anaconda distribution. If not found issue meaningful warning message
| Python | bsd-3-clause | oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,QuantEcon/QuantEcon.py,oyamad/QuantEcon.py | ---
+++
@@ -1,6 +1,11 @@
"""
Import the main names to top level.
"""
+
+try:
+ import numba
+except:
+ raise ImportError("Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.")
from .compute_fp import compute_fixed_point
from .discrete_rv impor... |
191812e1e16aea352c1a47cd5bd6cd3f0ed67802 | runtests.py | runtests.py | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
settings.configure(
DEBUG = True,
TEMPLATE_DEBUG = True,
DATABASES = {
'default': {
'ENGINE': 'django.db.bac... | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
settings.configure(
DEBUG = True,
TEMPLATE_DEBUG = True,
DATABASES = {
'default': {
'ENGINE': 'django.db.bac... | Remove warning for Django 1.7 | Remove warning for Django 1.7
| Python | bsd-3-clause | edoburu/django-template-analyzer,edoburu/django-template-analyzer | ---
+++
@@ -18,7 +18,8 @@
),
INSTALLED_APPS = (
'template_analyzer',
- )
+ ),
+ MIDDLEWARE_CLASSES = (),
)
def runtests(): |
37fcbbe7bb8a46bd32fc92341d1b42f2400abc9b | runtests.py | runtests.py | #!/usr/bin/python
import unittest
from firmant.utils import get_module
# Import this now to avoid it throwing errors.
import pytz
from firmant.configuration import settings
from test.configuration import suite as configuration_tests
from test.datasource.atom import suite as atom_tests
from test.plugins.datasource.flat... | #!/usr/bin/python
import unittest
from firmant.utils import get_module
# Import this now to avoid it throwing errors.
import pytz
from firmant.configuration import settings
from test.configuration import suite as configuration_tests
from test.datasource.atom import suite as atom_tests
from test.plugins.datasource.flat... | Disable flatfile tests until atom tests complete. | Disable flatfile tests until atom tests complete.
| Python | bsd-3-clause | rescrv/firmant | ---
+++
@@ -20,6 +20,6 @@
suite = unittest.TestSuite()
suite.addTests(configuration_tests)
suite.addTests(atom_tests)
- suite.addTests(flatfile_atom_tests)
+ #suite.addTests(flatfile_atom_tests)
suite.addTests(resolvers_tests)
unittest.TextTestRunner(verbosity=2).run(suite) |
2a5b81ff6272f346bcca3bdc97e3d6d9dfe2b017 | src/mmw/apps/bigcz/models.py | src/mmw/apps/bigcz/models.py | # -*- coding: utf-8 -*-
from django.contrib.gis.geos import Polygon
class ResourceLink(object):
def __init__(self, type, href):
self.type = type
self.href = href
class Resource(object):
def __init__(self, id, description, author, links, title,
created_at, updated_at, geom):
... | # -*- coding: utf-8 -*-
from django.contrib.gis.geos import Polygon
class ResourceLink(object):
def __init__(self, type, href):
self.type = type
self.href = href
class Resource(object):
def __init__(self, id, description, author, links, title,
created_at, updated_at, geom):
... | Set SRID the new way | Set SRID the new way
| Python | apache-2.0 | WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed | ---
+++
@@ -43,6 +43,6 @@
polygon = Polygon.from_bbox((
self.xmin, self.ymin,
self.xmax, self.ymax))
- polygon.set_srid(4326)
+ polygon.srid = 4326
return polygon.transform(5070, clone=True).area |
9d3d2beab6ec06ce13126b818029258a66f450f6 | babelfish/__init__.py | babelfish/__init__.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 the BabelFish authors. All rights reserved.
# Use of this source code is governed by the 3-clause BSD license
# that can be found in the LICENSE file.
#
__title__ = 'babelfish'
__version__ = '0.4.1'
__author__ = 'Antoine Bertin'
__license__ = 'BSD'
__copyright__ = 'Copyrig... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 the BabelFish authors. All rights reserved.
# Use of this source code is governed by the 3-clause BSD license
# that can be found in the LICENSE file.
#
__title__ = 'babelfish'
__version__ = '0.4.1'
__author__ = 'Antoine Bertin'
__license__ = 'BSD'
__copyright__ = 'Copyrig... | Add SCRIPT_MATRIX to babelfish module imports | Add SCRIPT_MATRIX to babelfish module imports
| Python | bsd-3-clause | Diaoul/babelfish | ---
+++
@@ -15,4 +15,4 @@
from .country import country_converters, COUNTRIES, COUNTRY_MATRIX, Country
from .exceptions import Error, LanguageConvertError, LanguageReverseError, CountryConvertError, CountryReverseError
from .language import language_converters, LANGUAGES, LANGUAGE_MATRIX, Language
-from .script imp... |
2ad21d67ccde2e25ea5c6d64cdee36dbc6425cbc | construct/tests/test_mapping.py | construct/tests/test_mapping.py | import unittest
from construct import Flag
class TestFlag(unittest.TestCase):
def test_parse(self):
flag = Flag("flag")
self.assertTrue(flag.parse("\x01"))
def test_parse_flipped(self):
flag = Flag("flag", truth=0, falsehood=1)
self.assertFalse(flag.parse("\x01"))
def te... | import unittest
from construct import Flag
class TestFlag(unittest.TestCase):
def test_parse(self):
flag = Flag("flag")
self.assertTrue(flag.parse("\x01"))
def test_parse_flipped(self):
flag = Flag("flag", truth=0, falsehood=1)
self.assertFalse(flag.parse("\x01"))
def te... | Add a couple more Flag tests. | tests: Add a couple more Flag tests.
| Python | mit | riggs/construct,mosquito/construct,gkonstantyno/construct,MostAwesomeDude/construct,0000-bigtree/construct,riggs/construct,mosquito/construct,0000-bigtree/construct,gkonstantyno/construct,MostAwesomeDude/construct | ---
+++
@@ -12,6 +12,14 @@
flag = Flag("flag", truth=0, falsehood=1)
self.assertFalse(flag.parse("\x01"))
+ def test_parse_default(self):
+ flag = Flag("flag")
+ self.assertFalse(flag.parse("\x02"))
+
+ def test_parse_default_true(self):
+ flag = Flag("flag", default=Tru... |
b2dd21b2240eec28881d6162f9e35b16df906219 | arris_cli.py | arris_cli.py | #!/usr/bin/env python
# CLI frontend to Arris modem stat scraper library arris_scraper.py
import argparse
import arris_scraper
import json
import pprint
default_url = 'http://192.168.100.1/cgi-bin/status_cgi'
parser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status ... | #!/usr/bin/env python
# CLI frontend to Arris modem stat scraper library arris_scraper.py
import argparse
import arris_scraper
import json
import pprint
default_url = 'http://192.168.100.1/cgi-bin/status_cgi'
parser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status ... | Tweak formatting of argparse section to minimize lines extending past 80 chars. | Tweak formatting of argparse section to minimize lines extending past 80 chars.
| Python | mit | wolrah/arris_stats | ---
+++
@@ -10,8 +10,15 @@
default_url = 'http://192.168.100.1/cgi-bin/status_cgi'
parser = argparse.ArgumentParser(description='CLI tool to scrape information from Arris cable modem status pages.')
-parser.add_argument('-f', '--format', choices=['ascii', 'json', 'pprint'], default='ascii', dest='output_format', ... |
4d7dff1c335a49d13d420f3c62b1a2d2382351dd | trajprocess/tests/utils.py | trajprocess/tests/utils.py | """Tools for setting up a fake directory structure for processing."""
from tempfile import mkdtemp
import os
import shutil
import json
from pkg_resources import resource_filename
def write_run_clone(proj, run, clone, gens=None):
if gens is None:
gens = [0, 1]
rc = "data/PROJ{proj}/RUN{run}/CLONE{cl... | """Tools for setting up a fake directory structure for processing."""
from tempfile import mkdtemp
import os
import shutil
import json
from pkg_resources import resource_filename
# command for generating reference data:
# gmx mdrun -nsteps 5000 -s frame0.tpr -cpi -noappend
#
# Do that three times.
def write_run_c... | Add note about how to generate trajectories | Add note about how to generate trajectories
| Python | mit | mpharrigan/trajprocess,mpharrigan/trajprocess | ---
+++
@@ -6,6 +6,12 @@
import json
from pkg_resources import resource_filename
+
+
+# command for generating reference data:
+# gmx mdrun -nsteps 5000 -s frame0.tpr -cpi -noappend
+#
+# Do that three times.
def write_run_clone(proj, run, clone, gens=None): |
a465922385ef12cf01f2a8a75928470c33f39569 | snakepit/directory.py | snakepit/directory.py | """
HiveDB client access via SQLAlchemy
"""
import sqlalchemy as sq
metadata = sq.MetaData()
hive_primary = sq.Table(
'hive_primary_DIMENSION',
metadata,
sq.Column('id', sq.Integer,
nullable=False,
index=True,
),
sq.Column('node', sq.SmallInteger,
... | """
HiveDB client access via SQLAlchemy
"""
import sqlalchemy as sq
metadata = sq.MetaData()
hive_primary = sq.Table(
'hive_primary_DIMENSION',
metadata,
sq.Column('id', sq.Integer, primary_key=True),
sq.Column('node', sq.SmallInteger,
nullable=False,
index=True,
... | Make hive_primary_DIMENSION.id primary key, so autoincrement works. | Make hive_primary_DIMENSION.id primary key, so autoincrement works.
| Python | mit | tv42/snakepit,tv42/snakepit | ---
+++
@@ -9,10 +9,7 @@
hive_primary = sq.Table(
'hive_primary_DIMENSION',
metadata,
- sq.Column('id', sq.Integer,
- nullable=False,
- index=True,
- ),
+ sq.Column('id', sq.Integer, primary_key=True),
sq.Column('node', sq.SmallInteger,
nulla... |
6f22416734525376b0a2143972b9546df3164751 | databaker/databaker_nbconvert.py | databaker/databaker_nbconvert.py | #!/usr/bin/env python
import os
import subprocess
import sys
def main(argv):
if len(argv) == 0 or len(argv) > 2:
print("Usage: databaker_process.py <notebook_file> <input_file>")
print()
print("<input_file> is optional; it replaces DATABAKER_INPUT_FILE")
print("in the notebook.")
... | #!/usr/bin/env python
import os
import subprocess
import sys
def main(argv=None):
if argv is None or len(argv) == 0 or len(argv) > 2:
print("Usage: databaker_process.py <notebook_file> <input_file>")
print()
print("<input_file> is optional; it replaces DATABAKER_INPUT_FILE")
print(... | Set default argv to None | Set default argv to None
| Python | agpl-3.0 | scraperwiki/databaker,scraperwiki/databaker | ---
+++
@@ -4,8 +4,8 @@
import sys
-def main(argv):
- if len(argv) == 0 or len(argv) > 2:
+def main(argv=None):
+ if argv is None or len(argv) == 0 or len(argv) > 2:
print("Usage: databaker_process.py <notebook_file> <input_file>")
print()
print("<input_file> is optional; it repl... |
34d1bbc36f7d5c66000eec0d6debfd3ede74366f | bottle_auth/custom.py | bottle_auth/custom.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from bottle import redirect
log = logging.getLogger('bottle-auth.custom')
class Custom(object):
def __init__(self, login_url="/login",
callback_url="http://127.0.0.1:8000"):
self.login_url = login_url
self.callback_url... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from bottle import redirect
log = logging.getLogger('bottle-auth.custom')
class Custom(object):
def __init__(self, login_url="/login",
callback_url="http://127.0.0.1:8000"):
self.login_url = login_url
self.callback_url... | Fix Custom class, user exit in beaker.session redirect to login page | Fix Custom class, user exit in beaker.session
redirect to login page
| Python | mit | avelino/bottle-auth | ---
+++
@@ -20,4 +20,4 @@
session = environ.get('beaker.session')
if session.get("username", None) and session.get("apikey", None):
return session
- return {}
+ self.redirect(environ) |
66edf9f04c1b23681fae4234a8b297868e66b7aa | osmaxx-py/osmaxx/excerptexport/models/excerpt.py | osmaxx-py/osmaxx/excerptexport/models/excerpt.py | from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
class Excerpt(models.Model):
name = models.CharField(max_length=128, verbose_name=_('name'), blank=False)
is_public = models.BooleanField(default=False, verbose_name=_('is public'))
... | from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
class Excerpt(models.Model):
name = models.CharField(max_length=128, verbose_name=_('name'))
is_public = models.BooleanField(default=False, verbose_name=_('is public'))
is_active... | Remove value which is already default | Remove value which is already default
| Python | mit | geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/drf-utm-zone-info,geometalab/osmaxx | ---
+++
@@ -4,7 +4,7 @@
class Excerpt(models.Model):
- name = models.CharField(max_length=128, verbose_name=_('name'), blank=False)
+ name = models.CharField(max_length=128, verbose_name=_('name'))
is_public = models.BooleanField(default=False, verbose_name=_('is public'))
is_active = models.Bool... |
e0a9b97792f48efdfb166b785a8ba1fd2448a171 | cref/structure/__init__.py | cref/structure/__init__.py | # import porter_paleale
def predict_secondary_structure(sequence):
"""
Predict the secondary structure of a given sequence
:param sequence: Amino acid sequence
:return: Secondary structure prediction as a string
H = helix
E = Strand
C =r coil
"""
# return porter_palea... | Add skeleton for secondary structure and write pdb module | Add skeleton for secondary structure and write pdb module
| Python | mit | mchelem/cref2,mchelem/cref2,mchelem/cref2 | ---
+++
@@ -0,0 +1,28 @@
+# import porter_paleale
+
+
+def predict_secondary_structure(sequence):
+ """
+ Predict the secondary structure of a given sequence
+
+ :param sequence: Amino acid sequence
+
+ :return: Secondary structure prediction as a string
+ H = helix
+ E = Strand
+ C =... | |
cddb0309eaa0c31569f791b8b9f2c8666b65b8b4 | openrcv/test/test_models.py | openrcv/test/test_models.py |
from openrcv.models import ContestInfo
from openrcv.utiltest.helpers import UnitCase
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
|
from textwrap import dedent
from openrcv.models import BallotsResource, BallotStreamResource, ContestInfo
from openrcv.utils import StringInfo
from openrcv.utiltest.helpers import UnitCase
class BallotsResourceTest(UnitCase):
def test(self):
ballots = [1, 3, 2]
ballot_resource = BallotsResource... | Add tests for ballots resource classes. | Add tests for ballots resource classes.
| Python | mit | cjerdonek/open-rcv,cjerdonek/open-rcv | ---
+++
@@ -1,6 +1,37 @@
-from openrcv.models import ContestInfo
+from textwrap import dedent
+
+from openrcv.models import BallotsResource, BallotStreamResource, ContestInfo
+from openrcv.utils import StringInfo
from openrcv.utiltest.helpers import UnitCase
+
+
+class BallotsResourceTest(UnitCase):
+
+ def tes... |
1a65ebc4a36da37840b3bd74666bf7f607ed190b | oshot/context_processors.py | oshot/context_processors.py | from django.contrib.auth.forms import AuthenticationForm
from django.contrib.sites.models import get_current_site
from django.conf import settings
from haystack.forms import SearchForm
from entities.models import Entity
from oshot.forms import EntityChoiceForm
def forms(request):
context = {"search_form": Search... | from django.contrib.auth.forms import AuthenticationForm
from django.contrib.sites.models import get_current_site
from django.conf import settings
from haystack.forms import SearchForm
from entities.models import Entity
from oshot.forms import EntityChoiceForm
def forms(request):
context = {"search_form": Search... | Clean bug with static file serving | Clean bug with static file serving
| Python | bsd-3-clause | hasadna/open-shot,hasadna/open-shot,hasadna/open-shot | ---
+++
@@ -9,16 +9,19 @@
def forms(request):
context = {"search_form": SearchForm()}
- kwargs = request.resolver_match.kwargs
- if 'entity_slug' in kwargs:
- entity = Entity.objects.get(slug=kwargs['entity_slug'])
- initial = {'entity': entity.id}
- elif 'entity_id' in kwargs:
- ... |
771f429433d201463ab94439870d1bc803022722 | nap/auth.py | nap/auth.py | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args... | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args... | Make it DRYer for people | Make it DRYer for people
| Python | bsd-3-clause | limbera/django-nap | ---
+++
@@ -17,16 +17,20 @@
return _wrapped_view
return decorator
-permit_logged_in = permit(
- lambda self, *args, **kwargs: self.request.user.is_authenticated()
-)
-permit_staff = permit(
- lambda self, *args, **kwargs: self.request.user.is_staff
-)
+# Helpers for people wanting to control r... |
a3a9da03da0691af53526096992a56fcaeecb642 | py/test/selenium/webdriver/common/proxy_tests.py | py/test/selenium/webdriver/common/proxy_tests.py | #!/usr/bin/python
# Copyright 2012 Software Freedom Conservancy.
#
# 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 appl... | #!/usr/bin/python
# Copyright 2012 Software Freedom Conservancy.
#
# 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 appl... | Fix test as well :) | DanielWagnerHall: Fix test as well :)
git-svn-id: aa1aa1384423cb28c2b1e29129bb3a91de1d9196@17825 07704840-8298-11de-bf8c-fd130f914ac9
| Python | apache-2.0 | jmt4/Selenium2,jmt4/Selenium2,yumingjuan/selenium,jmt4/Selenium2,jmt4/Selenium2,yumingjuan/selenium,jmt4/Selenium2,yumingjuan/selenium,yumingjuan/selenium,yumingjuan/selenium,yumingjuan/selenium,jmt4/Selenium2,jmt4/Selenium2,yumingjuan/selenium,jmt4/Selenium2,yumingjuan/selenium,jmt4/Selenium2,yumingjuan/selenium | ---
+++
@@ -30,7 +30,7 @@
expected_capabilities = {
'proxy': {
- 'proxyType': 'manual',
+ 'proxyType': 'MANUAL',
'httpProxy': 'some.url:1234'
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.