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 |
|---|---|---|---|---|---|---|---|---|---|---|
200f3a0bd0edd5a7409f36769cc8401b468bdb64 | puzzlehunt_server/settings/travis_settings.py | puzzlehunt_server/settings/travis_settings.py | from .base_settings import *
import os
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
SECRET_KEY = '$1B&VUf$OdUEfMJXd40qdakA36@%2NE_41Dz9tFs6l=z4v_3P-'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'puzzlehunt_db',
'HOST': '127.0.... | from .base_settings import *
import os
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
SECRET_KEY = '$1B&VUf$OdUEfMJXd40qdakA36@%2NE_41Dz9tFs6l=z4v_3P-'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'puzzlehunt_db',
'HOST': '1... | Fix database for testing environment | Fix database for testing environment
| Python | mit | dlareau/puzzlehunt_server,dlareau/puzzlehunt_server,dlareau/puzzlehunt_server,dlareau/puzzlehunt_server | ---
+++
@@ -7,12 +7,11 @@
SECRET_KEY = '$1B&VUf$OdUEfMJXd40qdakA36@%2NE_41Dz9tFs6l=z4v_3P-'
DATABASES = {
'default': {
- 'ENGINE': 'django.db.backends.mysql',
+ 'ENGINE': 'django.db.backends.postgresql',
'NAME': 'puzzlehunt_db',
'HOST': '127.0.0.1',
'USER': 'root',
... |
fc1e05658eb7e1fb2722467b5da5df622145eece | server/lib/python/cartodb_services/setup.py | server/lib/python/cartodb_services/setup.py | """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.13.0',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/dataservices-api',
author='Data... | """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.14.0',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/dataservices-api',
author='Data... | Bump version of python library to 0.14.0 | Bump version of python library to 0.14.0
| Python | bsd-3-clause | CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/geocoder-api | ---
+++
@@ -10,7 +10,7 @@
setup(
name='cartodb_services',
- version='0.13.0',
+ version='0.14.0',
description='CartoDB Services API Python Library',
|
022f2cc6d067769a6c8e56601c0238aac69ec9ab | jfr_playoff/settings.py | jfr_playoff/settings.py | import glob, json, os, readline, sys
def complete_filename(text, state):
return (glob.glob(text+'*')+[None])[state]
class PlayoffSettings:
def __init__(self):
self.interactive = False
self.settings_file = None
if len(sys.argv) > 1:
self.settings_file = sys.argv[1]
... | import glob, json, os, readline, sys
def complete_filename(text, state):
return (glob.glob(text+'*')+[None])[state]
class PlayoffSettings:
def __init__(self):
self.settings = None
self.interactive = False
self.settings_file = None
if len(sys.argv) > 1:
self.setting... | Load config file only once | Load config file only once
| Python | bsd-2-clause | emkael/jfrteamy-playoff,emkael/jfrteamy-playoff | ---
+++
@@ -6,6 +6,7 @@
class PlayoffSettings:
def __init__(self):
+ self.settings = None
self.interactive = False
self.settings_file = None
if len(sys.argv) > 1:
@@ -20,7 +21,8 @@
readline.set_completer(complete_filename)
self.settings_file = raw_in... |
19faa280c924254b960a8b9fcb716017e51db09f | pymks/tests/test_mksRegressionModel.py | pymks/tests/test_mksRegressionModel.py | from pymks import MKSRegressionModel
import numpy as np
def test():
Nbin = 2
Nspace = 81
Nsample = 400
def filter(x):
return np.where(x < 10,
np.exp(-abs(x)) * np.cos(x * np.pi),
np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi))
coeff = np.l... | from pymks import MKSRegressionModel
import numpy as np
def test():
Nbin = 2
Nspace = 81
Nsample = 400
def filter(x):
return np.where(x < 10,
np.exp(-abs(x)) * np.cos(x * np.pi),
np.exp(-abs(x - 20)) * np.cos((x - 20) * np.pi))
coeff = np.l... | Fix test due to addition of coeff property | Fix test due to addition of coeff property
Address #49
Add fftshift to test coefficients as model.coeff now returns the
shifted real versions.
| Python | mit | davidbrough1/pymks,XinyiGong/pymks,awhite40/pymks,davidbrough1/pymks,fredhohman/pymks | ---
+++
@@ -26,9 +26,8 @@
model = MKSRegressionModel(Nbin=Nbin)
model.fit(X, y)
- model.coeff = np.fft.ifft(model.Fcoeff, axis=0)
- assert np.allclose(coeff, model.coeff)
+ assert np.allclose(np.fft.fftshift(coeff, axes=(0,)), model.coeff)
if __name__ == '__main__':
test() |
0336651c6538d756eb40babe086975a0f7fcabd6 | qual/tests/test_historical_calendar.py | qual/tests/test_historical_calendar.py | from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet... | from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet... | Correct test for the right missing days and present days. | Correct test for the right missing days and present days.
1st and 2nd of September 1752 happened, so did 14th. 3rd to 13th did not.
| Python | apache-2.0 | jwg4/qual,jwg4/calexicon | ---
+++
@@ -20,6 +20,6 @@
class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest):
calendar_type = EnglishHistoricalCalendar
- gregorian_triplets = [(1752, 9, 13)]
- julian_triplets = [(1752, 9, 1)]
- transition_triplets = [(1752, 9, 6)]
+ gregorian_triplets = [(1752, 9, 14)]
+ ... |
d595f953a8993afd94f1616fbf815afe0b85a646 | scripts/master/factory/dart/channels.py | scripts/master/factory/dart/channels.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + na... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + na... | Make stable builders pull from 1.8 | Make stable builders pull from 1.8
Review URL: https://codereview.chromium.org/760053002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@293121 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -19,7 +19,7 @@
CHANNELS = [
Channel('be', 'branches/bleeding_edge', 0, '', 4),
Channel('dev', 'trunk', 1, '-dev', 2),
- Channel('stable', 'branches/1.7', 2, '-stable', 1),
+ Channel('stable', 'branches/1.8', 2, '-stable', 1),
Channel('integration', 'branches/dartium_integration', 3, '-integrati... |
2eff8e08e1e16463e526503db46ae5c21138d776 | tests/storage/servers/fastmail/__init__.py | tests/storage/servers/fastmail/__init__.py | import os
import pytest
class ServerMixin:
@pytest.fixture
def get_storage_args(self, item_type, slow_create_collection):
if item_type == "VTODO":
# Fastmail has non-standard support for TODOs
# See https://github.com/pimutils/vdirsyncer/issues/824
pytest.skip("Fas... | import os
import pytest
class ServerMixin:
@pytest.fixture
def get_storage_args(self, item_type, slow_create_collection, aio_connector):
if item_type == "VTODO":
# Fastmail has non-standard support for TODOs
# See https://github.com/pimutils/vdirsyncer/issues/824
p... | Fix breakage in Fastmail tests | Fix breakage in Fastmail tests
Some code that wasn't updated with the switch to asyncio.
| Python | mit | untitaker/vdirsyncer,untitaker/vdirsyncer,untitaker/vdirsyncer | ---
+++
@@ -5,7 +5,7 @@
class ServerMixin:
@pytest.fixture
- def get_storage_args(self, item_type, slow_create_collection):
+ def get_storage_args(self, item_type, slow_create_collection, aio_connector):
if item_type == "VTODO":
# Fastmail has non-standard support for TODOs
... |
6833865ff35d451a8215803b9fa74cd57167ed82 | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'aa4874a6bcc51fdd87ca7ae0928514ce83645988'
| #!/usr/bin/env python
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '9c654df782c77449e7d8fa741843143145260aeb'
| Update libchromiumcontent: Contain linux symbols. | Update libchromiumcontent: Contain linux symbols.
| Python | mit | trankmichael/electron,gabrielPeart/electron,felixrieseberg/electron,seanchas116/electron,bitemyapp/electron,xfstudio/electron,leolujuyi/electron,pombredanne/electron,astoilkov/electron,gabriel/electron,mubassirhayat/electron,smczk/electron,Jacobichou/electron,medixdev/electron,yalexx/electron,natgolov/electron,rsvip/el... | ---
+++
@@ -2,4 +2,4 @@
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
-LIBCHROMIUMCONTENT_COMMIT = 'aa4874a6bcc51fdd87ca7ae0928514ce83645988'
+LIBCHROMIUMCONTENT_COMMIT = '9c654df782c77449e7d8fa741843143145260aeb' |
c56480fd8905332e54649dac0ade95c825e8ba23 | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'b27290717c08f8c6a58067d3c3725d68b4e6a2e5'
| #!/usr/bin/env python
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'fe05f53f3080889ced2696b2741d93953e654b49'
| Update libchromiumcontent to use the thin version. | Update libchromiumcontent to use the thin version.
| Python | mit | cos2004/electron,rajatsingla28/electron,bobwol/electron,tonyganch/electron,gbn972/electron,deed02392/electron,natgolov/electron,felixrieseberg/electron,bright-sparks/electron,adcentury/electron,jhen0409/electron,soulteary/electron,pandoraui/electron,subblue/electron,matiasinsaurralde/electron,jlord/electron,rreimann/el... | ---
+++
@@ -2,4 +2,4 @@
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
-LIBCHROMIUMCONTENT_COMMIT = 'b27290717c08f8c6a58067d3c3725d68b4e6a2e5'
+LIBCHROMIUMCONTENT_COMMIT = 'fe05f53f3080889ced2696b2741d93953e654b49' |
1c32b17bd4c85165f91fbb188b22471a296c6176 | kajiki/i18n.py | kajiki/i18n.py | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .ir import TranslatableTextNode
def gettext(s):
return s
def extract(fileobj, keywords, comment_tags, options):
'''Babel entry point that extracts translation strings fr... | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .ir import TranslatableTextNode
def gettext(s):
return s
def extract(fileobj, keywords, comment_tags, options):
'''Babel entry point that extracts translation strings fr... | Fix issue with message extractor on Py2 | Fix issue with message extractor on Py2
| Python | mit | ollyc/kajiki,ollyc/kajiki,ollyc/kajiki | ---
+++
@@ -13,7 +13,10 @@
'''Babel entry point that extracts translation strings from XML templates.
'''
from .xml_template import _Parser, _Compiler, expand
- doc = _Parser(filename='<string>', source=fileobj.read()).parse()
+ source = fileobj.read()
+ if isinstance(source, bytes):
+ ... |
c1785e0713a5af6b849baaa1b314a13ac777f3f5 | tests/test_str_py3.py | tests/test_str_py3.py | from os import SEEK_SET
from random import choice, seed
from string import ascii_uppercase, digits
import fastavro
from fastavro.compat import BytesIO
letters = ascii_uppercase + digits
id_size = 100
seed('str_py3') # Repeatable results
def gen_id():
return ''.join(choice(letters) for _ in range(id_size))
k... | # -*- coding: utf-8 -*-
"""Python3 string tests for fastavro"""
from __future__ import absolute_import
from os import SEEK_SET
from random import choice, seed
from string import ascii_uppercase, digits
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
import fastavro
... | Test files shouldn't import 'fastavro.compat'. Just import BytesIO manually. | Test files shouldn't import 'fastavro.compat'. Just import BytesIO
manually.
| Python | mit | e-heller/fastavro,e-heller/fastavro | ---
+++
@@ -1,9 +1,19 @@
+# -*- coding: utf-8 -*-
+"""Python3 string tests for fastavro"""
+
+from __future__ import absolute_import
+
from os import SEEK_SET
from random import choice, seed
from string import ascii_uppercase, digits
+try:
+ from cStringIO import StringIO as BytesIO
+except ImportError:
+ ... |
1d839a0207058bd08de4be9a821337c9bdb1bcf8 | rock/utils.py | rock/utils.py | import StringIO
import os
class shell(object):
def __enter__(self):
self.stdin = StringIO.StringIO()
return self
def __exit__(self, type, value, traceback):
os.execl('/usr/bin/bash', 'bash', '-c', self.stdin.getvalue())
def write(self, text):
self.stdin.write(text + '\n'... | import StringIO
import os
class shell(object):
def __enter__(self):
self.stdin = StringIO.StringIO()
return self
def __exit__(self, type, value, traceback):
os.execl('/usr/bin/env', 'bash', 'bash', '-c', self.stdin.getvalue())
def write(self, text):
self.stdin.write(text... | Use env instead of hard coding bash path | Use env instead of hard coding bash path
| Python | mit | silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock | ---
+++
@@ -9,7 +9,7 @@
return self
def __exit__(self, type, value, traceback):
- os.execl('/usr/bin/bash', 'bash', '-c', self.stdin.getvalue())
+ os.execl('/usr/bin/env', 'bash', 'bash', '-c', self.stdin.getvalue())
def write(self, text):
self.stdin.write(text + '\n') |
df1397dcf6fe849b87db139e8ea3087a5f73649a | tests/graphics/toolbuttons.py | tests/graphics/toolbuttons.py | from gi.repository import Gtk
from sugar3.graphics.toolbarbox import ToolbarBox
from sugar3.graphics.colorbutton import ColorToolButton
from sugar3.graphics.radiotoolbutton import RadioToolButton
from sugar3.graphics.toggletoolbutton import ToggleToolButton
import common
test = common.Test()
test.show()
vbox = Gtk... | from gi.repository import Gtk
from sugar3.graphics.toolbarbox import ToolbarBox
from sugar3.graphics.colorbutton import ColorToolButton
from sugar3.graphics.radiotoolbutton import RadioToolButton
from sugar3.graphics.toggletoolbutton import ToggleToolButton
import common
test = common.Test()
test.show()
vbox = Gtk... | Update toolbar buttons testcase with API change for the icon name | Update toolbar buttons testcase with API change for the icon name
Follow up of fe11a3aa23c0e7fbc3c0c498e147b0a20348cc12 .
Signed-off-by: Manuel Quiñones <6f5069c5b6be23302a13accec56587944be09079@laptop.org>
| Python | lgpl-2.1 | i5o/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,sugarlabs/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,Daksh/... | ---
+++
@@ -19,11 +19,11 @@
vbox.pack_start(toolbar_box, False, False, 0)
toolbar_box.show()
-radial_button = RadioToolButton(named_icon='view-radial')
+radial_button = RadioToolButton(icon_name='view-radial')
toolbar_box.toolbar.insert(radial_button, -1)
radial_button.show()
-list_button = RadioToolButton(na... |
e907c7de622c54556df10155caddbb05c8235d19 | resolwe_bio/__about__.py | resolwe_bio/__about__.py | """Central place for package metadata."""
# NOTE: We use __title__ instead of simply __name__ since the latter would
# interfere with a global variable __name__ denoting object's name.
__title__ = 'resolwe-bio'
__summary__ = 'Bioinformatics pipelines for the Resolwe platform'
__url__ = 'https://github.com/genial... | """Central place for package metadata."""
# NOTE: We use __title__ instead of simply __name__ since the latter would
# interfere with a global variable __name__ denoting object's name.
__title__ = 'resolwe-bio'
__summary__ = 'Bioinformatics pipelines for the Resolwe platform'
__url__ = 'https://github.com/genial... | Change author in about file | Change author in about file
| Python | apache-2.0 | genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio | ---
+++
@@ -10,7 +10,7 @@
# https://packaging.python.org/en/latest/distributing/#semantic-versioning-preferred
__version__ = '12.0.0a2'
-__author__ = 'Genialis d.o.o.'
+__author__ = 'Genialis, Inc.'
__email__ = 'dev-team@genialis.com'
__license__ = 'Apache License (2.0)' |
2f56d481c05e28a4434a038a356f521b4ea5cbca | tests/test_simple_features.py | tests/test_simple_features.py | from wordgraph.points import Point
import wordgraph
EPOCH_START = 1407109280
def time_values(values, start=EPOCH_START, increment=1):
datapoints = []
for index, value in enumerate(values):
datapoints.append(Point(x=value, y=start + (increment * index)))
return datapoints
def test_monotonic_up_per... | from wordgraph.points import Point
import wordgraph
EPOCH_START = 1407109280
def time_values(values, start=EPOCH_START, increment=1):
datapoints = []
for index, value in enumerate(values):
datapoints.append(Point(x=value, y=start + (increment * index)))
return datapoints
def test_monotonic_up_per... | Test case for step function in time series | Test case for step function in time series
Test a graph function that is linear in two time periods, jumping
between linear values.
| Python | apache-2.0 | tleeuwenburg/wordgraph,tleeuwenburg/wordgraph | ---
+++
@@ -20,9 +20,16 @@
assert "" in features
def test_tent_map():
- values = list(float(i) for i in range(10))
+ values = [float(i) for i in range(10)]
values.append(11.0)
- values+= list(10.0 - i for i in range(10))
+ values += [10.0 - i for i in range(10)]
datapoints = time_values(... |
9051fc68b2c542f7a201a969340b1f1f5d0f660c | test_openfolder.py | test_openfolder.py | import pytest
from mock import patch, MagicMock
from open_folder import *
def test_folder_exists():
with patch('subprocess.check_call', MagicMock(return_value="NOOP")):
result = open_folder(".")
assert result == None
def test_folder_does_not_exists():
with patch('subprocess.check_call', Magic... | import pytest
from mock import patch, MagicMock
from open_folder import *
def test_folder_exists():
with patch('subprocess.check_call', MagicMock(return_value="NOOP")):
result = open_folder(".")
assert result == None
def test_folder_does_not_exists():
with patch('subprocess.check_call', Magic... | Check to ensure the exceptions return the text we expect. | Check to ensure the exceptions return the text we expect.
| Python | mit | golliher/dg-tickler-file | ---
+++
@@ -10,14 +10,17 @@
def test_folder_does_not_exists():
with patch('subprocess.check_call', MagicMock(return_value="NOOP")):
- with pytest.raises(Exception):
+ with pytest.raises(Exception) as excinfo:
open_folder("it_is_very_unlikely_that_this_file_exists_20150718")
+ ... |
e5fa10e27d9c5911b0238d23fc13acc081accc79 | utils/dates.py | utils/dates.py | # This file is part of e-Giełda.
# Copyright (C) 2014-2015 Mateusz Maćkowski and Tomasz Zieliński
#
# e-Giełda is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at ... | # This file is part of e-Giełda.
# Copyright (C) 2014-2015 Mateusz Maćkowski and Tomasz Zieliński
#
# e-Giełda is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at ... | Fix error on date save | Fix error on date save
| Python | agpl-3.0 | m4tx/egielda,m4tx/egielda,m4tx/egielda | ---
+++
@@ -18,8 +18,8 @@
return date.strftime("%Y-%m-%dT%H:%M")
-def datetime_to_string(datetime):
- return datetime.strftime(datetime, DT_FORMAT)
+def datetime_to_string(date):
+ return date.strftime(DT_FORMAT)
def string_to_datetime(date): |
ca430300c08f78b7c2de4153e08c1645996f85b7 | tests/test_parsers.py | tests/test_parsers.py | import unittest
from brew.parsers import JSONDataLoader
class TestJSONDataLoader(unittest.TestCase):
def setUp(self):
self.parser = JSONDataLoader('./')
def test_format_name(self):
name_list = [('pale malt 2-row us', 'pale_malt_2_row_us'),
('caramel crystal malt 20l', '... | import unittest
from brew.parsers import DataLoader
from brew.parsers import JSONDataLoader
class TestDataLoader(unittest.TestCase):
def setUp(self):
self.parser = DataLoader('./')
def test_read_data_raises(self):
with self.assertRaises(NotImplementedError):
self.parser.read_dat... | Add test to DataLoader base class | Add test to DataLoader base class
| Python | mit | chrisgilmerproj/brewday,chrisgilmerproj/brewday | ---
+++
@@ -1,6 +1,17 @@
import unittest
+from brew.parsers import DataLoader
from brew.parsers import JSONDataLoader
+
+
+class TestDataLoader(unittest.TestCase):
+
+ def setUp(self):
+ self.parser = DataLoader('./')
+
+ def test_read_data_raises(self):
+ with self.assertRaises(NotImplemented... |
17d2d4eaf58011ceb33a4d5944253578c2b5edd1 | pmdarima/preprocessing/endog/tests/test_log.py | pmdarima/preprocessing/endog/tests/test_log.py | # -*- coding: utf-8 -*-
import numpy as np
from numpy.testing import assert_array_almost_equal
from scipy import stats
import pytest
from pmdarima.preprocessing import LogEndogTransformer
from pmdarima.preprocessing import BoxCoxEndogTransformer
def test_same():
y = [1, 2, 3]
trans = BoxCoxEndogTransformer()... | # -*- coding: utf-8 -*-
import numpy as np
from numpy.testing import assert_array_almost_equal
from scipy import stats
import pytest
from pmdarima.preprocessing import LogEndogTransformer
from pmdarima.preprocessing import BoxCoxEndogTransformer
def test_same():
y = [1, 2, 3]
trans = BoxCoxEndogTransformer(... | Add test_invertible to log transformer test | Add test_invertible to log transformer test
| Python | mit | alkaline-ml/pmdarima,tgsmith61591/pyramid,tgsmith61591/pyramid,alkaline-ml/pmdarima,alkaline-ml/pmdarima,tgsmith61591/pyramid | ---
+++
@@ -8,10 +8,19 @@
from pmdarima.preprocessing import LogEndogTransformer
from pmdarima.preprocessing import BoxCoxEndogTransformer
+
def test_same():
y = [1, 2, 3]
- trans = BoxCoxEndogTransformer()
+ trans = BoxCoxEndogTransformer(lmbda=0)
log_trans = LogEndogTransformer()
y_t, _ = ... |
5c1f9b0a70fe47bbfa7d3813a47e2da81cd81506 | tests/runalldoctests.py | tests/runalldoctests.py | import doctest
import glob
import pkg_resources
try:
pkg_resources.require('OWSLib')
except (ImportError, pkg_resources.DistributionNotFound):
pass
testfiles = glob.glob('*.txt')
for file in testfiles:
doctest.testfile(file)
| import doctest
import getopt
import glob
import sys
import pkg_resources
try:
pkg_resources.require('OWSLib')
except (ImportError, pkg_resources.DistributionNotFound):
pass
def run(pattern):
if pattern is None:
testfiles = glob.glob('*.txt')
else:
testfiles = glob.glob(pattern)
fo... | Add option to pick single test file from the runner | Add option to pick single test file from the runner
git-svn-id: 8e0fbe17d71f9a07a4f24b82f5b9fb44b438f95e@620 b426a367-1105-0410-b9ff-cdf4ab011145
| Python | bsd-3-clause | sabman/OWSLib,monoid/owslib,monoid/owslib | ---
+++
@@ -1,5 +1,8 @@
import doctest
+import getopt
import glob
+import sys
+
import pkg_resources
try:
@@ -7,8 +10,23 @@
except (ImportError, pkg_resources.DistributionNotFound):
pass
-testfiles = glob.glob('*.txt')
+def run(pattern):
+ if pattern is None:
+ testfiles = glob.glob('*.txt')
+... |
60d71f0f6dc9de01442c304978ee7966319a5049 | zarya/settings/dev.py | zarya/settings/dev.py | from __future__ import absolute_import, unicode_literals
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'l33th4x0rs'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
... | from __future__ import absolute_import, unicode_literals
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'l33th4x0rs'
DATABASES = {
'default': {
'ENGINE': 'django.db.backend... | Change database connections for data migration tool | Change database connections for data migration tool
| Python | mit | davidjrichardson/uwcs-zarya,davidjrichardson/uwcs-zarya | ---
+++
@@ -8,9 +8,22 @@
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'l33th4x0rs'
+DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.postgresql_psycopg2',
+ 'NAME': 'uwcs_zarya',
+ 'USER': 'uwcs_zarya',
+ 'PASSWORD': 'doyouevenlift',
+ ... |
61bbd4e8fc0712fe56614481173eb86d409eb8d7 | tests/test_linked_list.py | tests/test_linked_list.py | from unittest import TestCase
from pystructures.linked_lists import LinkedList, Node
class TestNode(TestCase):
def test_value(self):
""" A simple test to check the Node's value """
node = Node(10)
self.assertEqual(10, node.value)
def test_improper_node(self):
""" A test to che... | from builtins import range
from unittest import TestCase
from pystructures.linked_lists import LinkedList, Node
class TestNode(TestCase):
def test_value(self):
""" A simple test to check the Node's value """
node = Node(10)
self.assertEqual(10, node.value)
def test_improper_node(self)... | Fix range issue with travis | Fix range issue with travis
| Python | mit | apranav19/pystructures | ---
+++
@@ -1,3 +1,4 @@
+from builtins import range
from unittest import TestCase
from pystructures.linked_lists import LinkedList, Node
@@ -18,7 +19,7 @@
def test_insert(self):
""" A simple test to check if insertion works as expected in a singly linked list """
l = LinkedList()
- results = [l.insert(va... |
01c0dd4d34e61df589b3dd9ee3c5f8b96cf5486b | tests/test_transformer.py | tests/test_transformer.py | from __future__ import unicode_literals
import functools
from scrapi.base import XMLHarvester
from scrapi.linter import RawDocument
from .utils import get_leaves
from .utils import TEST_SCHEMA, TEST_NAMESPACES, TEST_XML_DOC
class TestHarvester(XMLHarvester):
def harvest(self, days_back=1):
return [Raw... | from __future__ import unicode_literals
import functools
from scrapi.base import XMLHarvester
from scrapi.linter import RawDocument
from .utils import get_leaves
from .utils import TEST_SCHEMA, TEST_NAMESPACES, TEST_XML_DOC
class TestHarvester(XMLHarvester):
def harvest(self, days_back=1):
return [Raw... | Update tests with required properties | Update tests with required properties
| Python | apache-2.0 | CenterForOpenScience/scrapi,jeffreyliu3230/scrapi,fabianvf/scrapi,felliott/scrapi,erinspace/scrapi,icereval/scrapi,mehanig/scrapi,ostwald/scrapi,erinspace/scrapi,alexgarciac/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,fabianvf/scrapi,felliott/scrapi | ---
+++
@@ -20,10 +20,23 @@
}) for _ in xrange(days_back)]
+ @property
+ def name(self):
+ return 'TEST'
+
+ @property
+ def namespaces(self):
+ return TEST_NAMESPACES
+
+ @property
+ def schema(self):
+ return TEST_SCHEMA
+
+
class TestTransformer(object):
... |
46d274401080d47f3a9974c6ee80f2f3b9c0c8b0 | metakernel/magics/tests/test_download_magic.py | metakernel/magics/tests/test_download_magic.py |
from metakernel.tests.utils import (get_kernel, get_log_text,
clear_log_text, EvalKernel)
import os
def test_download_magic():
kernel = get_kernel(EvalKernel)
kernel.do_execute("%download --filename TEST.txt https://raw.githubusercontent.com/blink1073/metakernel/master/LIC... |
from metakernel.tests.utils import (get_kernel, get_log_text,
clear_log_text, EvalKernel)
import os
def test_download_magic():
kernel = get_kernel(EvalKernel)
kernel.do_execute("%download --filename TEST.txt https://raw.githubusercontent.com/blink1073/metakernel/master/LIC... | Add download test without filename | Add download test without filename
| Python | bsd-3-clause | Calysto/metakernel | ---
+++
@@ -10,8 +10,17 @@
assert "Downloaded 'TEST.txt'" in text, text
assert os.path.isfile("TEST.txt"), "File does not exist: TEST.txt"
+ clear_log_text(kernel)
+
+ kernel.do_execute("%download https://raw.githubusercontent.com/blink1073/metakernel/master/LICENSE.txt")
+ text = get_log_text(ke... |
6220c36f046b2b504cc2ebbbc04a34c4d826564d | IPython/extensions/tests/test_storemagic.py | IPython/extensions/tests/test_storemagic.py | import tempfile, os
import nose.tools as nt
ip = get_ipython()
ip.magic('load_ext storemagic')
def test_store_restore():
ip.user_ns['foo'] = 78
ip.magic('alias bar echo "hello"')
tmpd = tempfile.mkdtemp()
ip.magic('cd ' + tmpd)
ip.magic('store foo')
ip.magic('store bar')
# Check stor... | import tempfile, os
from IPython.config.loader import Config
import nose.tools as nt
ip = get_ipython()
ip.magic('load_ext storemagic')
def test_store_restore():
ip.user_ns['foo'] = 78
ip.magic('alias bar echo "hello"')
tmpd = tempfile.mkdtemp()
ip.magic('cd ' + tmpd)
ip.magic('store foo')
ip... | Add test for StoreMagics.autorestore option | Add test for StoreMagics.autorestore option
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -1,5 +1,6 @@
import tempfile, os
+from IPython.config.loader import Config
import nose.tools as nt
ip = get_ipython()
@@ -30,3 +31,20 @@
nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh'])
os.rmdir(tmpd)
+
+def test_autorestore():
+ ip.user_ns['foo'] = 95
+ ip.magic('store ... |
975a5010e97b11b9b6f00923c87268dd883b1cfa | 2017-code/opt/test1.py | 2017-code/opt/test1.py | # test1.py
# Ronald L. Rivest and Karim Husayn Karimi
# August 17, 2017
# Routine to experiment with scipy.optimize.minimize
import scipy.optimize
from scipy.stats import norm
# function to minimize:
def g(xy):
(x,y) = xy
print("g({},{})".format(x,y))
return x + y
# constraints
noise_level = 0.0000005
... | # test1.py
# Ronald L. Rivest and Karim Husayn Karimi
# August 17, 2017
# Routine to experiment with scipy.optimize.minimize
import scipy.optimize
from scipy.stats import norm
# function to minimize:
def g(xy):
(x,y) = xy
print("g({},{})".format(x,y))
return x + y
# constraints
noise_level = 0.05
# co... | Switch to COBYLA optimization method. Works much better. | Switch to COBYLA optimization method. Works much better.
| Python | mit | ron-rivest/2017-bayes-audit,ron-rivest/2017-bayes-audit | ---
+++
@@ -14,7 +14,7 @@
# constraints
-noise_level = 0.0000005
+noise_level = 0.05
# constraint 1: y <= x/2
def f1(xy):
@@ -35,6 +35,10 @@
}
]
-print(scipy.optimize.minimize(g, (11, 5), constraints=constraints))
+print(scipy.optimize.minimize(g,
+ ... |
76cf350b4ca48455e9ae7d6288d992389a8ec0b5 | src/toil/provisioners/azure/__init__.py | src/toil/provisioners/azure/__init__.py | # Copyright (C) 2015-2016 Regents of the University of California
#
# 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 app... | # Copyright (C) 2015-2016 Regents of the University of California
#
# 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 app... | Remove getAzureZone from init, no longer needed. | Remove getAzureZone from init, no longer needed.
| Python | apache-2.0 | BD2KGenomics/slugflow,BD2KGenomics/slugflow | ---
+++
@@ -11,17 +11,3 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
-import os
-
-def getAzureZone(defaultZone=None):
- """
- Find an appropriate azure zone.
-
- Look ... |
6941d9048a8c630244bb48100864872b35a1a307 | tests/functional/test_layout_and_styling.py | tests/functional/test_layout_and_styling.py | import os
from .base import FunctionalTest
class LayoutStylingTest(FunctionalTest):
def test_bootstrap_links_loaded_successfully(self):
self.browser.get(self.live_server_url)
self.assertIn(
"//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css",
self.browser.p... | from .base import FunctionalTest
class LayoutStylingTest(FunctionalTest):
def test_bootstrap_links_loaded_successfully(self):
self.browser.get(self.live_server_url)
links = [link.get_attribute("href")
for link in self.browser.find_elements_by_tag_name('link')]
scripts = ... | Fix bootstrap and jQuery link checking in homepage | Fix bootstrap and jQuery link checking in homepage
| Python | bsd-3-clause | andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,kevgathuku/compshop,kevgathuku/compshop,kevgathuku/compshop,andela-kndungu/compshop,andela-kndungu/compshop | ---
+++
@@ -1,5 +1,3 @@
-import os
-
from .base import FunctionalTest
@@ -8,14 +6,19 @@
def test_bootstrap_links_loaded_successfully(self):
self.browser.get(self.live_server_url)
- self.assertIn(
- "//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css",
- s... |
7375c41b1d9bd5ca153df80705ae1887e6f2e70b | api/base/exceptions.py | api/base/exceptions.py |
def jsonapi_exception_handler(exc, context):
"""
Custom exception handler that nests detail inside errors.
"""
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
if response is not None:
if 'detail' in response.data:
response.data ... |
def jsonapi_exception_handler(exc, context):
"""
Custom exception handler that returns errors object as an array with a 'detail' member
"""
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
if response is not None:
if 'detail' in response.dat... | Change docstring for exception handler | Change docstring for exception handler
| Python | apache-2.0 | RomanZWang/osf.io,felliott/osf.io,cosenal/osf.io,caseyrollins/osf.io,aaxelb/osf.io,aaxelb/osf.io,ckc6cz/osf.io,zamattiac/osf.io,emetsger/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,petermalcolm/osf.io,mfraezz/osf.io,crcresearch/osf.io,MerlinZhang/osf.io,mluke93/osf.io,hmoco/osf.io,emetsger/osf.io,felliott/osf.io,... | ---
+++
@@ -1,7 +1,7 @@
def jsonapi_exception_handler(exc, context):
"""
- Custom exception handler that nests detail inside errors.
+ Custom exception handler that returns errors object as an array with a 'detail' member
"""
from rest_framework.views import exception_handler
response = e... |
6d624d693a05749879f4184231e727590542db03 | backend/globaleaks/tests/utils/test_zipstream.py | backend/globaleaks/tests/utils/test_zipstream.py | # -*- encoding: utf-8 -*-
import StringIO
from twisted.internet.defer import inlineCallbacks
from zipfile import ZipFile
from globaleaks.tests import helpers
from globaleaks.utils.zipstream import ZipStream
class TestZipStream(helpers.TestGL):
@inlineCallbacks
def setUp(self):
yield helpers.TestGL.s... | # -*- encoding: utf-8 -*-
import os
import StringIO
from twisted.internet.defer import inlineCallbacks
from zipfile import ZipFile
from globaleaks.tests import helpers
from globaleaks.utils.zipstream import ZipStream
class TestZipStream(helpers.TestGL):
@inlineCallbacks
def setUp(self):
yield helper... | Improve unit testing of zipstream utilities | Improve unit testing of zipstream utilities
| Python | agpl-3.0 | vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks | ---
+++
@@ -1,4 +1,6 @@
# -*- encoding: utf-8 -*-
+
+import os
import StringIO
from twisted.internet.defer import inlineCallbacks
@@ -7,16 +9,17 @@
from globaleaks.tests import helpers
from globaleaks.utils.zipstream import ZipStream
-
class TestZipStream(helpers.TestGL):
@inlineCallbacks
def setU... |
92138f23dfc5dbbcb81aeb1f429e68a63a9d5005 | apps/organizations/admin.py | apps/organizations/admin.py | from django.contrib import admin
from apps.organizations.models import (
Organization, OrganizationAddress, OrganizationMember
)
class OrganizationAddressAdmin(admin.StackedInline):
model = OrganizationAddress
extra = 0
class OrganizationAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("nam... | from django.contrib import admin
from apps.organizations.models import (
Organization, OrganizationAddress, OrganizationMember
)
class OrganizationAddressAdmin(admin.StackedInline):
model = OrganizationAddress
extra = 0
class OrganizationAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("nam... | Add a custom Admin page for organization members. | Add a custom Admin page for organization members.
This is a partial fix for BB-66.
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site | ---
+++
@@ -17,7 +17,13 @@
search_fields = ('name', 'description')
-
admin.site.register(Organization, OrganizationAdmin)
-admin.site.register(OrganizationMember)
+
+class OrganizationMemberAdmin(admin.ModelAdmin):
+ list_display = ('user', 'function', 'organization')
+ list_filter = ('function',)
+... |
60a5104f0138af7bbfc5056fae01898c148b10a0 | benchmarks/serialization.py | benchmarks/serialization.py | """
Benchmark of message serialization.
The goal here is to mostly focus on performance of serialization, in a vaguely
realistic manner. That is, mesages are logged in context of a message with a
small number of fields.
"""
from __future__ import unicode_literals
import time
from eliot import Message, start_action,... | """
Benchmark of message serialization.
The goal here is to mostly focus on performance of serialization, in a vaguely
realistic manner. That is, mesages are logged in context of a message with a
small number of fields.
"""
from __future__ import unicode_literals
import time
from eliot import Message, start_action,... | Fix the benchmark so it's not throwing exceptions every time a message is written | Fix the benchmark so it's not throwing exceptions every time a message is written | Python | apache-2.0 | ScatterHQ/eliot,ScatterHQ/eliot,ClusterHQ/eliot,ScatterHQ/eliot | ---
+++
@@ -13,7 +13,7 @@
from eliot import Message, start_action, to_file
# Ensure JSON serialization is part of benchmark:
-to_file(open("/dev/null"))
+to_file(open("/dev/null", "w"))
N = 10000
|
38d80f89abc4c39d077505c4d6f27c4db699eeee | examples/calculations/Parse_Angles.py | examples/calculations/Parse_Angles.py | # Copyright (c) 2015-2018 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""
Parse angles
============
Demonstrate how to convert direction strings to angles.
The code below shows how to parse directional text into angles.
It also demons... | # Copyright (c) 2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""
Parse angles
============
Demonstrate how to convert direction strings to angles.
The code below shows how to parse directional text into angles.
It also demonstrate... | Add parse_angle() example to calculations page. | Add parse_angle() example to calculations page.
| Python | bsd-3-clause | Unidata/MetPy,ahaberlie/MetPy,dopplershift/MetPy,dopplershift/MetPy,Unidata/MetPy,ShawnMurd/MetPy,ahaberlie/MetPy | ---
+++
@@ -1,4 +1,4 @@
-# Copyright (c) 2015-2018 MetPy Developers.
+# Copyright (c) 2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
""" |
539608a9ca9a21707184496e744fc40a8cb72cc1 | announce/management/commands/migrate_mailchimp_users.py | announce/management/commands/migrate_mailchimp_users.py | from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from announce.mailchimp import archive_members, list_members, batch_subscribe
from studygroups.models import Profile
import requests
import logging
logger = logging.getLogger(__name__)
class Command(BaseCo... | from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from announce.mailchimp import archive_members, list_members, batch_subscribe
from studygroups.models import Profile
import requests
import logging
logger = logging.getLogger(__name__)
class Command(BaseCo... | Remove once of code for mailchimp list migration | Remove once of code for mailchimp list migration
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | ---
+++
@@ -25,13 +25,3 @@
to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed))
print('{} users will be added to the mailchimp list'.format(len(to_sub)))
batch_subscribe(to_sub)
-
- # update profile.communication_opt_in = True for users subscribed to the mailchi... |
d8a5d6d6478ae8267ccd9d1e4db710f8decb7991 | wiki/achievements.py | wiki/achievements.py | import wikipedia
import sys
import random
import re
import nltk.data
def process_file(f):
names = {}
with open(f) as file:
for line in file:
l = line.strip().split('\t')
if len(l) != 2:
continue
(k, v) = l
names[k] = v
return names
... | import wikipedia
import sys
import random
import re
import nltk.data
def process_file(f):
names = {}
with open(f) as file:
for line in file:
l = line.strip().split('\t')
if len(l) != 2:
continue
(k, v) = l
names[k] = v
return names
... | Use print as a statement | janitoring: Use print as a statement
- Let's be Python 3 compatible.
Signed-off-by: mr.Shu <8e7be411ad89ade93d144531f3925d0bb4011004@shu.io>
| Python | apache-2.0 | Motivatix/wikipedia-achievements-processing | ---
+++
@@ -48,4 +48,4 @@
pageid = names[name]
print "Results of processing {} ({})".format(name, pageid)
for achievement in process_page(pageid):
- print "\t", achievement.encode('utf-8')
+ print ("\t", achievement.encode('utf-8')) |
5be55b944b52c047b6d91d46c23645c5fb79c342 | webapp/calendars/forms.py | webapp/calendars/forms.py | from django import forms
from django.contrib.admin import widgets
from datetimewidget.widgets import DateTimeWidget
from .models import Event
class LoginForm(forms.Form):
username = forms.CharField(label='Nazwa użytkownika')
password = forms.CharField(label='Hasło', widget=forms.PasswordInput())
date_time_o... | from django import forms
from django.contrib.admin import widgets
from datetimewidget.widgets import DateTimeWidget
from .models import Event
class LoginForm(forms.Form):
username = forms.CharField(label='Nazwa użytkownika')
password = forms.CharField(label='Hasło', widget=forms.PasswordInput())
date_time_o... | Use 24h time format in datetime-widget. | Use 24h time format in datetime-widget.
Signed-off-by: Mariusz Fik <e22610367d206dca7aa58af34ebf008b556228c5@fidano.pl>
| Python | agpl-3.0 | hackerspace-silesia/calendar-oswiecim,hackerspace-silesia/calendar-oswiecim,firemark/calendar-oswiecim,Fisiu/calendar-oswiecim,Fisiu/calendar-oswiecim,firemark/calendar-oswiecim,firemark/calendar-oswiecim,Fisiu/calendar-oswiecim,hackerspace-silesia/calendar-oswiecim | ---
+++
@@ -10,7 +10,7 @@
date_time_options = {
- 'format': 'dd.mm.yyyy HH:ii',
+ 'format': 'dd.mm.yyyy hh:ii',
'language': 'pl'
}
|
c93cb479446fbe12e019550f193cb45dbdc1e3e0 | pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py | pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py | # -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store',
dest='foo',
help='alias for --foo'
)
@pytest.fixture
def bar(request):
return request.config.option.f... | # -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store',
dest='foo',
help='Set the value for the fixture "bar".'
)
@pytest.fixture
def bar(request):
return re... | Optimize the help message for the option arg | Optimize the help message for the option arg
| Python | mit | luzfcb/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin,pytest-dev/cookiecutter-pytest-plugin | ---
+++
@@ -9,7 +9,7 @@
'--foo',
action='store',
dest='foo',
- help='alias for --foo'
+ help='Set the value for the fixture "bar".'
)
|
ca977a2a9c8f3c3b54f2bd516323fa9b1dc23b6c | pocs/utils/data.py | pocs/utils/data.py | import argparse
import os
import shutil
from astroplan import download_IERS_A
from astropy.utils import data
def download_all_files(data_folder=None):
download_IERS_A()
if data_folder is None:
data_folder = "{}/astrometry/data".format(os.getenv('PANDIR'))
for i in range(4214, 4219):
fn ... | import argparse
import os
import shutil
from astroplan import download_IERS_A
from astropy.utils import data
def download_all_files(data_folder=None):
download_IERS_A()
if data_folder is None:
data_folder = "{}/astrometry/data".format(os.getenv('PANDIR'))
for i in range(4214, 4220):
fn ... | Add one more index file for solver | Add one more index file for solver
| Python | mit | panoptes/POCS,joshwalawender/POCS,panoptes/POCS,AstroHuntsman/POCS,panoptes/POCS,panoptes/POCS,joshwalawender/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,joshwalawender/POCS | ---
+++
@@ -12,7 +12,7 @@
if data_folder is None:
data_folder = "{}/astrometry/data".format(os.getenv('PANDIR'))
- for i in range(4214, 4219):
+ for i in range(4214, 4220):
fn = 'index-{}.fits'.format(i)
dest = "{}/{}".format(data_folder, fn)
|
3d7bbd37485dca4782ad7e7fdb088b22db586b66 | pyscores/config.py | pyscores/config.py | BASE_URL = "http://api.football-data.org/v1"
LEAGUE_IDS = {
"PL": "426",
"ELC": "427",
"EL1": "428",
"FAC": "429",
"BL1": "430",
"BL2": "431",
"DFB": "432",
"DED": "433",
"FL1": "434",
"FL2": "435",
"PD": "436",
"SD": "437",
"SA": "438",
"PPL": "439",
"CL": "... | BASE_URL = "http://api.football-data.org/v1"
LEAGUE_IDS = {
"BSA": "444",
"PL": "445",
"ELC": "446",
"EL1": "447",
"EL2": "448",
"DED": "449",
"FL1": "450",
"FL2": "451",
"BL1": "452",
"BL2": "453",
"PD": "455",
"SA": "456",
"PPL": "457",
"DFB": "458",
"SB": ... | Update league codes for new season | Update league codes for new season
| Python | mit | conormag94/pyscores | ---
+++
@@ -1,22 +1,21 @@
BASE_URL = "http://api.football-data.org/v1"
LEAGUE_IDS = {
- "PL": "426",
- "ELC": "427",
- "EL1": "428",
- "FAC": "429",
- "BL1": "430",
- "BL2": "431",
- "DFB": "432",
- "DED": "433",
- "FL1": "434",
- "FL2": "435",
- "PD": "436",
- "SD": "437",
- ... |
1170aa08809b1c5b63e93f03864b4c76766064bc | content/test/gpu/gpu_tests/pixel_expectations.py | content/test/gpu/gpu_tests/pixel_expectations.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopar... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopar... | Mark the CSS3DBlueBox pixel test as failing. | Mark the CSS3DBlueBox pixel test as failing.
There seems to be a problem with this test, as it seems to change
often after being rebaselined recently.
BUG=416719
Review URL: https://codereview.chromium.org/587753004
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#296124}
| Python | bsd-3-clause | hgl888/chromium-crosswalk-efl,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-cross... | ---
+++
@@ -24,4 +24,6 @@
# self.Fail('Pixel.Canvas2DRedBox',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
+ self.Fail('Pixel.CSS3DBlueBox',bug=416719)
+
pass |
a476c42216af99488c2e02bacd29f7e3a869a3e7 | tests/retrieval_metrics/test_precision_at_k.py | tests/retrieval_metrics/test_precision_at_k.py | import numpy as np
import pytest
import tensorflow as tf
from tensorflow_similarity.retrieval_metrics import PrecisionAtK
testdata = [
(
"micro",
tf.constant(0.583333333),
),
(
"macro",
tf.constant(0.5),
),
]
@pytest.mark.parametrize("avg, expected", testdata, ids=["m... | import numpy as np
import pytest
import tensorflow as tf
from tensorflow_similarity.retrieval_metrics import PrecisionAtK
testdata = [
(
"micro",
tf.constant(0.583333333),
),
(
"macro",
tf.constant(0.5),
),
]
@pytest.mark.parametrize("avg, expected", testdata, ids=["m... | Update atol on precision at k test. | Update atol on precision at k test.
| Python | apache-2.0 | tensorflow/similarity | ---
+++
@@ -31,4 +31,4 @@
rm = PrecisionAtK(k=3, average=avg)
precision = rm.compute(query_labels=query_labels, match_mask=match_mask)
- np.testing.assert_allclose(precision, expected)
+ np.testing.assert_allclose(precision, expected, atol=1e-05) |
b1a3a17460ae1f68c6c9bf60ecbd6a3b80a95abe | billjobs/tests/tests_model.py | billjobs/tests/tests_model.py | from django.test import TestCase, Client
from django.contrib.auth.models import User
from billjobs.models import Bill, Service
from billjobs.settings import BILLJOBS_BILL_ISSUER
class BillingTestCase(TestCase):
''' Test billing creation and modification '''
fixtures = ['dev_data.json']
def setUp(self):
... | from django.test import TestCase, Client
from django.contrib.auth.models import User
from billjobs.models import Bill, Service
from billjobs.settings import BILLJOBS_BILL_ISSUER
class BillingTestCase(TestCase):
''' Test billing creation and modification '''
fixtures = ['dev_data.json']
def setUp(self):
... | Refactor test to use user | Refactor test to use user
| Python | mit | ioO/billjobs | ---
+++
@@ -8,11 +8,10 @@
fixtures = ['dev_data.json']
def setUp(self):
- self.client = Client()
- self.client.login(username='bill', password='jobs')
+ self.user = User.objects.get(username='bill')
def tearDown(self):
- self.client.logout()
+ pass
def test... |
ed8423041abc80b778bf9ffed61e3dad246d72ff | bucketeer/test/test_commit.py | bucketeer/test/test_commit.py | import unittest
import boto
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
def setUp(self):
# Create a bucket with one file
connection = boto.connect_s3()
bucket = connection.create_bucket('bucket.exists')
return
def tearDown(self):
# Remove all test-created buckets and... | import unittest
import boto
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
global existing_bucket
existing_bucket = 'bucket.exists'
def setUp(self):
# Create a bucket with one file
connection = boto.connect_s3()
bucket = connection.create_bucket(existing_bucket)
return
... | Refactor bucket name to global variable | Refactor bucket name to global variable
| Python | mit | mgarbacz/bucketeer | ---
+++
@@ -4,17 +4,20 @@
class BuckeeterTest(unittest.TestCase):
+ global existing_bucket
+ existing_bucket = 'bucket.exists'
+
def setUp(self):
# Create a bucket with one file
connection = boto.connect_s3()
- bucket = connection.create_bucket('bucket.exists')
+ bucket = connection.create_b... |
d0367aacfea7c238c476772a2c83f7826b1e9de5 | corehq/apps/export/tasks.py | corehq/apps/export/tasks.py | from celery.task import task
from corehq.apps.export.export import get_export_file, rebuild_export
from couchexport.models import Format
from couchexport.tasks import escape_quotes
from soil.util import expose_cached_download
@task
def populate_export_download_task(export_instances, filters, download_id, filename=No... | from celery.task import task
from corehq.apps.export.export import get_export_file, rebuild_export
from couchexport.models import Format
from couchexport.tasks import escape_quotes
from soil.util import expose_cached_download
@task
def populate_export_download_task(export_instances, filters, download_id, filename=No... | Fix botched keyword args in rebuild_export_task() | Fix botched keyword args in rebuild_export_task()
| Python | bsd-3-clause | dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq | ---
+++
@@ -26,6 +26,6 @@
export_file.file.delete()
-@task(queue='background_queue', ignore_result=True, last_access_cutoff=None, filter=None)
-def rebuild_export_task(export_instance):
- rebuild_export(export_instance)
+@task(queue='background_queue', ignore_result=True)
+def rebuild_export_task(export_i... |
641ac2d30b0eb2239444b022688195ff26bd70b4 | timeout_decorator/timeout_decorator.py | timeout_decorator/timeout_decorator.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2012-2013 by PN.
:license: MIT, see LICENSE for more details.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import signal
from functools import wraps
########################... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2012-2013 by PN.
:license: MIT, see LICENSE for more details.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import signal
from functools import wraps
########################... | Make timeout error an assertion error, not just any old exception | Make timeout error an assertion error, not just any old exception
This means that timeout failures are considered to be test failures, where a specific assertion (i.e. 'this function takes less than N seconds') has failed, rather than being a random error in the test that may indicate a bug. | Python | mit | pnpnpn/timeout-decorator,yetone/timeout-decorator | ---
+++
@@ -20,7 +20,7 @@
#http://www.saltycrane.com/blog/2010/04/using-python-timeout-decorator-uploading-s3/
-class TimeoutError(Exception):
+class TimeoutError(AssertionError):
def __init__(self, value="Timed Out"):
self.value = value
|
bddd7cb9131dd61a8167fe9db5bbc3b02f8e3add | tests/main.py | tests/main.py | #!/usr/bin/env python
"""
Tests for python-bna
>>> import bna
>>> serial = "US120910711868"
>>> secret = b"88aaface48291e09dc1ece9c2aa44d839983a7ff"
>>> bna.get_token(secret, time=1347279358)
(93461643, 2)
>>> bna.get_token(secret, time=1347279359)
(93461643, 1)
>>> bna.get_token(secret, time=1347279360)
(86031001, 30... | #!/usr/bin/env python
"""
Tests for python-bna
>>> import bna
>>> serial = "US120910711868"
>>> secret = b"88aaface48291e09dc1ece9c2aa44d839983a7ff"
>>> bna.get_token(secret, time=1347279358)
(93461643, 2)
>>> bna.get_token(secret, time=1347279359)
(93461643, 1)
>>> bna.get_token(secret, time=1347279360)
(86031001, 30... | Add a test for bna.get_otpauth_url | Add a test for bna.get_otpauth_url
| Python | mit | jleclanche/python-bna,Adys/python-bna | ---
+++
@@ -15,6 +15,8 @@
'4B91NQCYQ3'
>>> bna.normalize_serial(bna.prettify_serial(serial)) == serial
True
+>>> bna.get_otpauth_url(serial, secret)
+'otpauth://totp/Battle.net:US120910711868:?secret=HA4GCYLGMFRWKNBYGI4TCZJQHFSGGMLFMNSTSYZSMFQTINDEHAZTSOJYGNQTOZTG&issuer=Battle.net&digits=8'
"""
if __name__ ==... |
86a325777742e1fa79bc632fca9460f3b1b8eb16 | to_do/urls.py | to_do/urls.py | from django.conf.urls import patterns, include, url
from task.views import TaskList, TaskView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', TaskList.as_view(), name='TaskList'),
url(r'^task/', TaskView.as_view(),... | from django.conf.urls import patterns, include, url
from task.views import TaskList, TaskView, get_task_list
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', TaskList.as_view(), name='TaskList'),
url(r'^task/', Task... | Enable url to get all list of tasks by ajax | Enable url to get all list of tasks by ajax
| Python | mit | rosadurante/to_do,rosadurante/to_do | ---
+++
@@ -1,5 +1,5 @@
from django.conf.urls import patterns, include, url
-from task.views import TaskList, TaskView
+from task.views import TaskList, TaskView, get_task_list
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
@@ -8,6 +8,7 @@
urlpatterns = patterns('',
ur... |
49975504a590a1ae53e2e8cc81aadea277cc5600 | cvrminer/app/__init__.py | cvrminer/app/__init__.py | """cvrminer app."""
from __future__ import absolute_import, division, print_function
from flask import Flask
from flask_bootstrap import Bootstrap
def create_app(smiley=False):
"""Create app.
Factory for app.
Parameters
----------
smiley : bool, optional
Determines whether the smiley ... | """cvrminer app."""
from __future__ import absolute_import, division, print_function
from flask import Flask
from flask_bootstrap import Bootstrap, StaticCDN
def create_app(smiley=False):
"""Create app.
Factory for app.
Parameters
----------
smiley : bool, optional
Determines whether ... | Change to use local Javascript and CSS files | Change to use local Javascript and CSS files
| Python | apache-2.0 | fnielsen/cvrminer,fnielsen/cvrminer,fnielsen/cvrminer | ---
+++
@@ -4,7 +4,7 @@
from __future__ import absolute_import, division, print_function
from flask import Flask
-from flask_bootstrap import Bootstrap
+from flask_bootstrap import Bootstrap, StaticCDN
def create_app(smiley=False):
@@ -21,6 +21,10 @@
app = Flask(__name__)
Bootstrap(app)
+ # Se... |
3b4322b8de8ffdc691f08fbf7f35e6ec5293f41e | crm_job_position/models/crm_job_position.py | crm_job_position/models/crm_job_position.py | # -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, fields
class CrmJobPosition... | # -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, fields
class CrmJobPosition... | Set some fields as tranlate | Set some fields as tranlate
| Python | agpl-3.0 | acsone/partner-contact,Therp/partner-contact,diagramsoftware/partner-contact,Endika/partner-contact,open-synergy/partner-contact | ---
+++
@@ -12,7 +12,7 @@
_parent_store = True
_description = "Job position"
- name = fields.Char(required=True)
+ name = fields.Char(required=True, translate=True)
parent_id = fields.Many2one(comodel_name='crm.job_position')
children = fields.One2many(comodel_name='crm.job_position',
... |
f7bfcd7fee64ae9220710835974125f41dae1c50 | frappe/core/doctype/role/test_role.py | frappe/core/doctype/role/test_role.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import unittest
test_records = frappe.get_test_records('Role')
class TestUser(unittest.TestCase):
def test_disable_role(self):
frappe.get_doc("User", "test@exam... | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import unittest
test_records = frappe.get_test_records('Role')
class TestUser(unittest.TestCase):
def test_disable_role(self):
frappe.get_doc("User", "test@exam... | Test Case for disabled role | fix: Test Case for disabled role
| Python | mit | mhbu50/frappe,mhbu50/frappe,saurabh6790/frappe,frappe/frappe,saurabh6790/frappe,vjFaLk/frappe,StrellaGroup/frappe,vjFaLk/frappe,yashodhank/frappe,StrellaGroup/frappe,almeidapaulopt/frappe,adityahase/frappe,almeidapaulopt/frappe,adityahase/frappe,adityahase/frappe,adityahase/frappe,mhbu50/frappe,yashodhank/frappe,frappe... | ---
+++
@@ -10,20 +10,16 @@
class TestUser(unittest.TestCase):
def test_disable_role(self):
frappe.get_doc("User", "test@example.com").add_roles("_Test Role 3")
-
+
role = frappe.get_doc("Role", "_Test Role 3")
role.disabled = 1
role.save()
-
+
self.assertTrue("_Test Role 3" not in frappe.get_ro... |
82121f05032f83de538c4a16596b24b5b012a3be | chaco/shell/tests/test_tutorial_example.py | chaco/shell/tests/test_tutorial_example.py | """ Test script-oriented example from interactive plotting tutorial
source: docs/source/user_manual/chaco_tutorial.rst
"""
import unittest
from numpy import linspace, pi, sin
from enthought.chaco.shell import plot, show, title, ytitle
class InteractiveTestCase(unittest.TestCase):
def test_script(self):
... | """ Test script-oriented example from interactive plotting tutorial
source: docs/source/user_manual/chaco_tutorial.rst
"""
import unittest
from numpy import linspace, pi, sin
from chaco.shell import plot, title, ytitle
class InteractiveTestCase(unittest.TestCase):
def test_script(self):
x = linspace(-2... | Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later. | Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later.
| Python | bsd-3-clause | tommy-u/chaco,burnpanck/chaco,burnpanck/chaco,tommy-u/chaco,tommy-u/chaco,burnpanck/chaco | ---
+++
@@ -5,7 +5,7 @@
"""
import unittest
from numpy import linspace, pi, sin
-from enthought.chaco.shell import plot, show, title, ytitle
+from chaco.shell import plot, title, ytitle
class InteractiveTestCase(unittest.TestCase): |
e029998f73a77ebd8f4a6e32a8b03edcc93ec0d7 | dataproperty/__init__.py | dataproperty/__init__.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from ._align import Align
from ._align_getter import align_getter
from ._container import MinMaxContainer
from ._data_property import (
ColumnDataProperty,
DataProperty
)
from ._error impo... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from ._align import Align
from ._align_getter import align_getter
from ._container import MinMaxContainer
from ._data_property import (
ColumnDataProperty,
DataProperty
)
from ._error impo... | Delete import that no longer used | Delete import that no longer used
| Python | mit | thombashi/DataProperty | ---
+++
@@ -29,8 +29,7 @@
is_datetime,
get_integer_digit,
get_number_of_digit,
- get_text_len,
- strict_strtobool
+ get_text_len
)
from ._property_extractor import PropertyExtractor
from ._type import ( |
1a0e277d23dfc41fc03799edde2a650b89cbcced | src/utils/utils.py | src/utils/utils.py | import logging
LOGGER = logging.getLogger(__name__)
def tidy_up_url(url):
if url.startswith("//"):
# If no protocol was supplied, add https
url = "https:" + url
if '?' in url:
url = url[:url.rfind('?')]
return url
def limit_file_name(file_name, length=65):
if len(file_name)... | import logging
LOGGER = logging.getLogger(__name__)
def tidy_up_url(url):
if url.startswith("//"):
# If no protocol was supplied, add https
url = "https:" + url
if '?' in url:
url = url[:url.rfind('?')]
if url.endswith("/"):
url = url[:-1]
return url
def limit_file... | Make sure that the Imgur ID can be correctly extracted from the URL | Make sure that the Imgur ID can be correctly extracted from the URL
This was made to address the case where the URL might end with '/'
| Python | apache-2.0 | CharlieCorner/pymage_downloader | ---
+++
@@ -10,6 +10,9 @@
if '?' in url:
url = url[:url.rfind('?')]
+
+ if url.endswith("/"):
+ url = url[:-1]
return url
|
69abcf66d36079e100815f629487d121ae016ee9 | future/tests/test_standard_library_renames.py | future/tests/test_standard_library_renames.py | """
Tests for the future.standard_library_renames module
"""
from __future__ import absolute_import, unicode_literals, print_function
from future import standard_library_renames, six
import unittest
class TestStandardLibraryRenames(unittest.TestCase):
def test_configparser(self):
import configparser
... | """
Tests for the future.standard_library_renames module
"""
from __future__ import absolute_import, unicode_literals, print_function
from future import standard_library_renames, six
import unittest
class TestStandardLibraryRenames(unittest.TestCase):
def test_configparser(self):
import configparser
... | Fix test for queue module | Fix test for queue module
I was testing heapq before ;) ...
| Python | mit | QuLogic/python-future,QuLogic/python-future,krischer/python-future,michaelpacer/python-future,michaelpacer/python-future,krischer/python-future,PythonCharmers/python-future,PythonCharmers/python-future | ---
+++
@@ -29,9 +29,9 @@
def test_queue(self):
import queue
- heap = ['thing', 'another thing']
- queue.heapq.heapify(heap)
- self.assertEqual(heap, ['another thing', 'thing'])
+ q = queue.Queue()
+ q.put('thing')
+ self.assertFalse(q.empty())
# 'marku... |
f266132c05c37469290027e7aa8000d1f9a19a6c | tst/colors.py | tst/colors.py | YELLOW = '\033[1;33m'
LRED = '\033[1;31m'
LGREEN = '\033[1;32m'
GREEN="\033[9;32m"
WHITE="\033[1;37m"
LCYAN = '\033[1;36m'
LBLUE = '\033[1;34m'
RESET = '\033[0m'
| YELLOW = '\033[1;33m'
LRED = '\033[1;31m'
LGREEN = '\033[1;32m'
GREEN = '\033[9;32m'
WHITE = '\033[0;37m'
LWHITE = '\033[1;37m'
LCYAN = '\033[1;36m'
LBLUE = '\033[1;34m'
RESET = '\033[0m'
CRITICAL = '\033[41;37m'
| Add some new color codes | Add some new color codes
| Python | agpl-3.0 | daltonserey/tst,daltonserey/tst | ---
+++
@@ -1,8 +1,10 @@
YELLOW = '\033[1;33m'
LRED = '\033[1;31m'
LGREEN = '\033[1;32m'
-GREEN="\033[9;32m"
-WHITE="\033[1;37m"
+GREEN = '\033[9;32m'
+WHITE = '\033[0;37m'
+LWHITE = '\033[1;37m'
LCYAN = '\033[1;36m'
LBLUE = '\033[1;34m'
RESET = '\033[0m'
+CRITICAL = '\033[41;37m' |
9fb7d827007a7ed1aea505f88b3831f19b066d23 | webapp/titanembeds/database/disabled_guilds.py | webapp/titanembeds/database/disabled_guilds.py | from titanembeds.database import db
class DisabledGuilds(db.Model):
__tablename__ = "disabled_guilds" # Auto increment id
guild_id = db.Column(db.BigInteger, nullable=False, primary_key=True) # Server id that is disabled
def __init__(self, guild_id):
self.guild_id =... | from titanembeds.database import db
class DisabledGuilds(db.Model):
__tablename__ = "disabled_guilds" # Auto increment id
guild_id = db.Column(db.BigInteger, nullable=False, primary_key=True) # Server id that is disabled
def __init__(self, guild_id):
self.guild_id =... | Set disabled guild ids to string so it works again | Set disabled guild ids to string so it works again
| Python | agpl-3.0 | TitanEmbeds/Titan,TitanEmbeds/Titan,TitanEmbeds/Titan | ---
+++
@@ -11,5 +11,5 @@
q = db.session.query(DisabledGuilds).all()
their_ids = []
for guild in q:
- their_ids.append(guild.guild_id)
+ their_ids.append(str(guild.guild_id))
return their_ids |
038978f87883247a14e9bec08708452c98c91285 | test/test_chimera.py | test/test_chimera.py | import unittest
import utils
import os
import sys
import re
import shutil
import subprocess
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
utils.set_search_paths(TOPDIR)
import cryptosite.chimera
class Tests(unittest.TestCase):
def test_bad(self):
"""Test wrong arguments to chime... | import unittest
import utils
import os
import sys
import re
import shutil
import subprocess
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
utils.set_search_paths(TOPDIR)
import cryptosite.chimera
class Tests(unittest.TestCase):
def test_bad(self):
"""Test wrong arguments to chime... | Check generated file for sanity. | Check generated file for sanity.
| Python | lgpl-2.1 | salilab/cryptosite,salilab/cryptosite,salilab/cryptosite | ---
+++
@@ -24,6 +24,9 @@
def test_make_chimera_file(self):
"""Test make_chimera_file() function"""
cryptosite.chimera.make_chimera_file('url1', 'url2', 'out.chimerax')
+ with open('out.chimerax') as fh:
+ lines = fh.readlines()
+ self.assertEqual(lines[-4], 'open_files... |
05ddf0fff9469ae0173809eb559486ff216231a0 | test/test_scripts.py | test/test_scripts.py | import pytest
import subprocess
@pytest.mark.parametrize("script", [])
def test_script(script):
try:
subprocess.check_output([script, '-h'], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print e.output
assert e.returncode == 0
| import pytest
import subprocess
@pytest.mark.parametrize("script", ['bin/cast-example'])
def test_script(script):
try:
subprocess.check_output([script, '-h'], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print e.output
assert e.returncode == 0
| Add example-cast to sanity test | Add example-cast to sanity test
| Python | mit | maxzheng/clicast | ---
+++
@@ -2,7 +2,7 @@
import subprocess
-@pytest.mark.parametrize("script", [])
+@pytest.mark.parametrize("script", ['bin/cast-example'])
def test_script(script):
try: |
33598fd8baf527d63cef965eddfc90548b6c52b3 | go/apps/jsbox/definition.py | go/apps/jsbox/definition.py | import json
from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinition... | import json
from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinition... | Remove non-unicode endpoints from the endpoint list. | Remove non-unicode endpoints from the endpoint list.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -24,16 +24,18 @@
except Exception:
return []
- endpoints = set()
# vumi-jssandbox-toolkit v2 endpoints
try:
- endpoints.update(js_config["endpoints"].keys())
+ v2_endpoints = list(js_config["endpoints"].keys())
except Exception... |
fbc46862af7fa254f74f1108149fd0669c46f1ad | rplugin/python3/deoplete/sources/LanguageClientSource.py | rplugin/python3/deoplete/sources/LanguageClientSource.py | import re
from .base import Base
CompleteResults = "g:LanguageClient_completeResults"
def simplify_snippet(snip: str) -> str:
snip = re.sub(r'(?<!\\)\$(?P<num>\d+)', '<`\g<num>`>', snip)
return re.sub(r'(?<!\\)\${(?P<num>\d+):(?P<desc>.+?)}',
'<`\g<num>:\g<desc>`>', snip)
class Source(Ba... | from .base import Base
CompleteResults = "g:LanguageClient_completeResults"
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = "LanguageClient"
self.mark = "[LC]"
self.rank = 1000
self.filetypes = vim.eval(
"get(g:, 'LanguageClient... | Remove problematic deoplete source customization. | Remove problematic deoplete source customization.
Close #312.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/L... | ---
+++
@@ -1,14 +1,7 @@
-import re
from .base import Base
CompleteResults = "g:LanguageClient_completeResults"
-
-
-def simplify_snippet(snip: str) -> str:
- snip = re.sub(r'(?<!\\)\$(?P<num>\d+)', '<`\g<num>`>', snip)
- return re.sub(r'(?<!\\)\${(?P<num>\d+):(?P<desc>.+?)}',
- '<`\g<num... |
d6a3d43e58796299c55fe3a6c6d597edaf5cfc3c | troposphere/kms.py | troposphere/kms.py | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject
from .validators import boolean
try:
from awacs.aws import Policy
policytypes = (dict, Policy)
except ImportError:
policytypes = dict,
class Alias(AWSObject):
res... | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .validators import boolean
try:
from awacs.aws import Policy
policytypes = (dict, Policy)
except ImportError:
policytypes = dict,
class Alias(AWSObject):
... | Change KMS::Key to accept a standard Tags | Change KMS::Key to accept a standard Tags
| Python | bsd-2-clause | ikben/troposphere,pas256/troposphere,johnctitus/troposphere,cloudtools/troposphere,ikben/troposphere,cloudtools/troposphere,johnctitus/troposphere,pas256/troposphere | ---
+++
@@ -3,7 +3,7 @@
#
# See LICENSE file for full license.
-from . import AWSObject
+from . import AWSObject, Tags
from .validators import boolean
try:
from awacs.aws import Policy
@@ -29,5 +29,5 @@
'Enabled': (boolean, False),
'EnableKeyRotation': (boolean, False),
'KeyPolic... |
ca777965c26b8dfd43b472adeb032f048e2537ed | acceptancetests/tests/acc_test_login_page.py | acceptancetests/tests/acc_test_login_page.py | # (c) Crown Owned Copyright, 2016. Dstl.
import os
import unittest
from splinter import Browser
class TestLoginPage (unittest.TestCase):
def setUp(self):
self.browser = Browser('phantomjs')
def test_login_page_appears(self):
# This needs to come from an environment variable at some point
... | # (c) Crown Owned Copyright, 2016. Dstl.
import os
import unittest
from splinter import Browser
class TestLoginPage (unittest.TestCase):
def setUp(self):
self.browser = Browser('phantomjs')
def test_login_page_appears(self):
# This needs to come from an environment variable at some point
... | Check that expected title exists in the actual title, not the other way round | Check that expected title exists in the actual title, not the other way round
| Python | mit | dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse | ---
+++
@@ -21,6 +21,6 @@
self.assertEqual(self.browser.url, url)
self.assertEqual(self.browser.status_code.code, 200)
- self.assertIn(self.browser.title, title)
+ self.assertIn(title, self.browser.title)
self.assertIn('Login with ID.', self.browser.html) |
d5ee91ba36c7e3d2ce0720b5b047934d554041cd | app/__init__.py | app/__init__.py | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
bootstrap = Bootstrap()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
bootstrap.init_app(app)
from .aflafrettir import aflafrettir as afla_blueprint
app.register_bl... | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
bootstrap = Bootstrap()
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
bootstrap.init_app(app)
db.init_app... | Initialize the database in the application package constructor | Initialize the database in the application package constructor
| Python | mit | finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is | ---
+++
@@ -1,15 +1,18 @@
from flask import Flask
from flask.ext.bootstrap import Bootstrap
+from flask.ext.sqlalchemy import SQLAlchemy
from config import config
bootstrap = Bootstrap()
+db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
... |
c3d6613b4f611857bee1c1b9c414aebd9abf21d7 | amazon/ion/__init__.py | amazon/ion/__init__.py | # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at:
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... | # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at:
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... | Change self-reported version from 0.1.0 to 0.4.1 | Change self-reported version from 0.1.0 to 0.4.1
| Python | apache-2.0 | amznlabs/ion-python,almann/ion-python | ---
+++
@@ -18,7 +18,7 @@
from __future__ import print_function
__author__ = 'Amazon.com, Inc.'
-__version__ = '0.1.0'
+__version__ = '0.4.1'
__all__ = [
'core', |
154b64b2ee56fa4391251268ba4a85d178bedd60 | djangoautoconf/urls.py | djangoautoconf/urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# from mezzanine.core.views import direct_to_template
admin.autodiscover()
# Must be defined before aut... | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# from mezzanine.core.views import direct_to_template
admin.autodiscover()
# Must be defined before aut... | Fix the issue of override url by mistake. | Fix the issue of override url by mistake.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | ---
+++
@@ -30,8 +30,6 @@
# url(r'^obj_sys/', include('obj_sys.urls')),
# url("^$", direct_to_template, {"template": "index.html"}, name="home"),
)
-urlpatterns = [
- # ... the rest of your URLconf goes here ...
-] + static(settings.MEDIA_URL,... |
890841fb910112853306e2d6b4163cce12262fd5 | xdg/Config.py | xdg/Config.py | """
Functions to configure Basic Settings
"""
language = "C"
windowmanager = None
icon_theme = "highcolor"
icon_size = 48
cache_time = 5
root_mode = False
def setWindowManager(wm):
global windowmanager
windowmanager = wm
def setIconTheme(theme):
global icon_theme
icon_theme = theme
import xdg.Ico... | """
Functions to configure Basic Settings
"""
language = "C"
windowmanager = None
icon_theme = "hicolor"
icon_size = 48
cache_time = 5
root_mode = False
def setWindowManager(wm):
global windowmanager
windowmanager = wm
def setIconTheme(theme):
global icon_theme
icon_theme = theme
import xdg.IconT... | Correct spelling of default icon theme | Correct spelling of default icon theme
Closes fd.o bug #29294
| Python | lgpl-2.1 | 0312birdzhang/pyxdg | ---
+++
@@ -4,7 +4,7 @@
language = "C"
windowmanager = None
-icon_theme = "highcolor"
+icon_theme = "hicolor"
icon_size = 48
cache_time = 5
root_mode = False |
8703ff401b77333ca23a696026802bacebd879b1 | python-pscheduler/pscheduler/pscheduler/db.py | python-pscheduler/pscheduler/pscheduler/db.py | """
Functions for connecting to the pScheduler database
"""
import psycopg2
def pg_connection(dsn='', autocommit=True):
"""
Connect to the database, and return a handle to it
Arguments:
dsn - A data source name to use in connecting to the database. If
the string begins with an '@', the remainde... | """
Functions for connecting to the pScheduler database
"""
import psycopg2
from filestring import string_from_file
def pg_connection(dsn='', autocommit=True):
"""
Connect to the database, and return a handle to it
Arguments:
dsn - A data source name to use in connecting to the database. If
th... | Use string_from_file() to interpret file-based DSNs | Use string_from_file() to interpret file-based DSNs
| Python | apache-2.0 | perfsonar/pscheduler,mfeit-internet2/pscheduler-dev,perfsonar/pscheduler,perfsonar/pscheduler,perfsonar/pscheduler,mfeit-internet2/pscheduler-dev | ---
+++
@@ -3,6 +3,8 @@
"""
import psycopg2
+
+from filestring import string_from_file
def pg_connection(dsn='', autocommit=True):
"""
@@ -18,10 +20,7 @@
quesies are issued.
"""
- # Read the DSN from a file if requested
- if dsn.startswith('@'):
- with open(dsn[1:], 'r') as dsnfil... |
96f9819ab67b48135a61c8a1e15bc808cf82d194 | bokeh/models/widget.py | bokeh/models/widget.py | from __future__ import absolute_import
from ..plot_object import PlotObject
from ..properties import Bool
class Widget(PlotObject):
disabled = Bool(False)
| from __future__ import absolute_import
from ..plot_object import PlotObject
from ..properties import Bool
from ..embed import notebook_div
class Widget(PlotObject):
disabled = Bool(False)
def _repr_html_(self):
return notebook_div(self)
@property
def html(self):
from IPython.core.dis... | Implement display protocol for Widget (_repr_html_) | Implement display protocol for Widget (_repr_html_)
This effectively allows us to automatically display plots and widgets.
| Python | bsd-3-clause | evidation-health/bokeh,abele/bokeh,mutirri/bokeh,percyfal/bokeh,htygithub/bokeh,jakirkham/bokeh,rhiever/bokeh,DuCorey/bokeh,srinathv/bokeh,DuCorey/bokeh,awanke/bokeh,clairetang6/bokeh,ericdill/bokeh,ahmadia/bokeh,saifrahmed/bokeh,mutirri/bokeh,bokeh/bokeh,gpfreitas/bokeh,philippjfr/bokeh,xguse/bokeh,srinathv/bokeh,drap... | ---
+++
@@ -2,6 +2,15 @@
from ..plot_object import PlotObject
from ..properties import Bool
+from ..embed import notebook_div
class Widget(PlotObject):
disabled = Bool(False)
+
+ def _repr_html_(self):
+ return notebook_div(self)
+
+ @property
+ def html(self):
+ from IPython.core.d... |
5a6c809afc6b228d7f5d37154adda162802c0110 | botcommands/vimtips.py | botcommands/vimtips.py | # coding: utf-8
import requests
def vimtips(msg=None):
try:
tip = requests.get('http://vim-tips.com/random_tips/json').json()
except Exception as e:
return None
return u'%s\n%s' % (tip['Content'], tip['Comment'], )
| # coding: utf-8
import requests
from redis_wrap import get_hash
from rq.decorators import job
def vimtips(msg=None):
try:
existing_tips = get_hash('vimtips')
_len = len(existing_tips)
if _len > 0:
_index = randint(0, _len - 1)
_k = existing_tips.keys()[_index]
... | Use RQ to queue collecting job | Use RQ to queue collecting job
| Python | bsd-2-clause | JokerQyou/bot | ---
+++
@@ -1,9 +1,33 @@
# coding: utf-8
import requests
+from redis_wrap import get_hash
+from rq.decorators import job
def vimtips(msg=None):
try:
- tip = requests.get('http://vim-tips.com/random_tips/json').json()
+ existing_tips = get_hash('vimtips')
+ _len = len(existing_tips)
+ ... |
16d0f3f0ca4ce59f08e598b6f9f25bb6dc8e1713 | benchmark/benchmark.py | benchmark/benchmark.py | import time
import sys
from utils import format_duration
if sys.platform == "win32":
default_timer = time.clock
else:
default_timer = time.time
class Benchmark():
def __init__(self, func, name="", repeat=5):
self.func = func
self.repeat = repeat
self.name = name
self.verb... | import time
import sys
from utils import format_duration
if sys.platform == "win32":
default_timer = time.clock
else:
default_timer = time.time
class Benchmark():
def __init__(self, func, name="", repeat=5):
self.func = func
self.repeat = repeat
self.name = name
self.verb... | Fix bad console output formatting | Fix bad console output formatting
| Python | mit | jameshy/libtree,conceptsandtraining/libtree | ---
+++
@@ -37,4 +37,4 @@
s_all = [format_duration(t) for t in self.results]
s += "(min={} avg={} max={} all={})".format(s_min,
s_avg, s_max, s_all)
- return " ".join(s)
+ return s |
2cf8d03324af2fadf905da811cfab4a29a6bc93a | pony_barn/settings/django_settings.py | pony_barn/settings/django_settings.py | DATABASES = {
'default': {
'ENGINE': '{{ db_engine }}',
'NAME': '{{ db_name }}',
'USER': '{{ db_user}}',
'PASSWORD': '{{ db_pass }}',
},
'other': {
'ENGINE': 'django.db.backends.sqlite3',
'TEST_NAME': 'other_db'
}
}
| import os
pid = os.getpid()
DATABASES = {
'default': {
'ENGINE': '{{ db_engine }}',
'NAME': '{{ db_name }}',
'USER': '{{ db_user}}',
'PASSWORD': '{{ db_pass }}',
},
'other': {
'ENGINE': 'django.db.backends.sqlite3',
'TEST_NAME': 'other_db_%s' % pid,
}
}
| Append PID to Django database to avoid conflicts. | Append PID to Django database to avoid conflicts. | Python | mit | ericholscher/pony_barn,ericholscher/pony_barn | ---
+++
@@ -1,3 +1,6 @@
+import os
+pid = os.getpid()
+
DATABASES = {
'default': {
'ENGINE': '{{ db_engine }}',
@@ -7,6 +10,6 @@
},
'other': {
'ENGINE': 'django.db.backends.sqlite3',
- 'TEST_NAME': 'other_db'
+ 'TEST_NAME': 'other_db_%s' % pid,
}
} |
0d8a28b62c4e54ee84861da75b0f0626bc4e46e7 | get_data_from_twitter.py | get_data_from_twitter.py | # -*- coding: UTF-8 -*-
import numpy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
import config
#Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/
class StdOutListener(StreamListener):
def on_data(self, data_... | # -*- coding: UTF-8 -*-
import numpy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
import config
#Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/
class StdOutListener(StreamListener):
def on_data(self, data_... | Add back filter for Hillary2016 | Add back filter for Hillary2016
| Python | mpl-2.0 | aDataAlchemist/election-tweets | ---
+++
@@ -24,6 +24,4 @@
auth.set_access_token(config.access_token, config.access_token_secret)
stream = Stream(auth, l)
-#stream.filter(track=['#Trump2016', '#Hillary2016'])
-stream.filter(track=['#Trump2016'])
-
+stream.filter(track=['#Trump2016', '#Hillary2016']) |
8f1fd73d6a88436d24f936adec997f88ad7f1413 | neutron/tests/unit/objects/test_l3agent.py | neutron/tests/unit/objects/test_l3agent.py | # Copyright (c) 2016 Intel Corporation.
#
# 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 la... | # Copyright (c) 2016 Intel Corporation.
#
# 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 la... | Use unique binding_index for RouterL3AgentBinding | Use unique binding_index for RouterL3AgentBinding
This is because (router_id, binding_index) tuple is expected to be
unique, as per db model.
Closes-Bug: #1674434
Change-Id: I64fcee88f2ac942e6fa173644fbfb7655ea6041b
| Python | apache-2.0 | openstack/neutron,mahak/neutron,noironetworks/neutron,huntxu/neutron,eayunstack/neutron,openstack/neutron,huntxu/neutron,eayunstack/neutron,mahak/neutron,mahak/neutron,openstack/neutron,noironetworks/neutron | ---
+++
@@ -35,6 +35,8 @@
self._create_test_agent()
return self._agent['id']
+ index = iter(range(1, len(self.objs) + 1))
self.update_obj_fields(
{'router_id': self._router.id,
+ 'binding_index': lambda: next(index),
'l3_agent_id': get... |
867a8081646eb061555eda2471c5174a842dd6fd | tests/test_floodplain.py | tests/test_floodplain.py | from unittest import TestCase
import niche_vlaanderen as nv
import numpy as np
import rasterio
class TestFloodPlain(TestCase):
def test__calculate(self):
fp = nv.FloodPlain()
fp._calculate(depth=np.array([1, 2, 3]), frequency="T25",
period="winter", duration=1)
np.test... | from unittest import TestCase
import niche_vlaanderen as nv
import numpy as np
import rasterio
class TestFloodPlain(TestCase):
def test__calculate(self):
fp = nv.FloodPlain()
fp._calculate(depth=np.array([1, 2, 3]), frequency="T25",
period="winter", duration=1)
np.test... | Fix tests for running floodplain model in ci | Fix tests for running floodplain model in ci
| Python | mit | johanvdw/niche_vlaanderen | ---
+++
@@ -20,6 +20,12 @@
np.testing.assert_equal(expected, fp._veg[25])
def test_plot(self):
+ import matplotlib as mpl
+ mpl.use('agg')
+
+ import matplotlib.pyplot as plt
+ plt.show = lambda: None
+
fp = nv.FloodPlain()
fp.calculate("testcase/floodplai... |
fc8ac6ba5081e7847847d31588a65db8ea13416c | openprescribing/matrixstore/build/dates.py | openprescribing/matrixstore/build/dates.py | DEFAULT_NUM_MONTHS = 60
def generate_dates(end_str, months=None):
"""
Given an end date as a string in YYYY-MM form (or the underscore separated
equivalent), return a list of N consecutive months as strings in YYYY-MM-01
form, with that month as the final member
"""
if months is None:
... | DEFAULT_NUM_MONTHS = 60
def generate_dates(end_str, months=None):
"""
Given an end date as a string in YYYY-MM form (or the underscore separated
equivalent), return a list of N consecutive months as strings in YYYY-MM-01
form, with that month as the final member
"""
if months is None:
... | Fix another py27-ism which Black can't handle | Fix another py27-ism which Black can't handle
Not sure how I missed this one last time.
| Python | mit | ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc | ---
+++
@@ -29,11 +29,12 @@
return int(year_str), int(month_str)
-def increment_months((year, month), months):
+def increment_months(year_month, months):
"""
Given a pair of (year, month) integers return the (year, month) pair N
months in the future
"""
+ year, month = year_month
... |
68aeddc44d4c9ace7ab9d2475a92c5fd39b4a665 | ckanext/requestdata/controllers/request_data.py | ckanext/requestdata/controllers/request_data.py | from ckan.lib import base
from ckan.common import c, _
from ckan import logic
from ckanext.requestdata import emailer
from ckan.plugins import toolkit
import ckan.model as model
import ckan.plugins as p
import json
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
ValidationEr... | from ckan.lib import base
from ckan.common import c, _
from ckan import logic
from ckanext.requestdata import emailer
from ckan.plugins import toolkit
import ckan.model as model
import ckan.plugins as p
import json
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
ValidationEr... | Remove user_mail from request data | Remove user_mail from request data
| Python | agpl-3.0 | ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata | ---
+++
@@ -23,6 +23,7 @@
:param data: Contact form data.
:type data: object
+ :rtype: json
'''
print "Entered"
context = {'model': model, 'session': model.Session,
@@ -33,9 +34,7 @@
data = dict(toolkit.request.POST)
content = dat... |
73b61983de6ff655b4f11205c0acd2b2f92915f4 | eva/util/nutil.py | eva/util/nutil.py | import numpy as np
def to_rgb(pixels):
return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2)
def binarize(arr, generate=np.random.uniform):
"""
Stochastically binarize values in [0, 1] by treating them as p-values of
a Bernoulli distribution.
"""
return (generate(size=arr.shape) < arr... | import numpy as np
def to_rgb(pixels):
return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2)
def binarize(arr, generate=np.random.uniform):
return (generate(size=arr.shape) < arr).astype('i')
| Remove comment; change to int | Remove comment; change to int
| Python | apache-2.0 | israelg99/eva | ---
+++
@@ -5,8 +5,4 @@
return np.repeat(pixels, 3 if pixels.shape[2] == 1 else 1, 2)
def binarize(arr, generate=np.random.uniform):
- """
- Stochastically binarize values in [0, 1] by treating them as p-values of
- a Bernoulli distribution.
- """
- return (generate(size=arr.shape) < arr).astyp... |
a24c657ca84e553a39e23d201d605d84d828c322 | examples/hello.py | examples/hello.py | from cell import Actor, Agent
from cell.actors import Server
from kombu import Connection
from kombu.log import setup_logging
connection = Connection()
class GreetingActor(Server):
default_routing_key = 'GreetingActor'
class state:
def greet(self, who='world'):
return 'Hello %s' % who... | from cell import Actor, Agent
from cell.actors import Server
from kombu import Connection
from kombu.log import setup_logging
connection = Connection()
class GreetingActor(Server):
default_routing_key = 'GreetingActor'
class state:
def greet(self, who='world'):
return 'Hello %s' % who
... | Use the Server class (an Actor derived class) | Use the Server class (an Actor derived class)
| Python | bsd-3-clause | celery/cell,celery/cell | ---
+++
@@ -11,41 +11,17 @@
default_routing_key = 'GreetingActor'
class state:
-
def greet(self, who='world'):
return 'Hello %s' % who
greeting = GreetingActor(connection)
+
-class Printer(Actor):
- default_routing_key = 'Printer'
-
- class state:
- def ... |
d70ccd856bb4ddb061ff608716ef15f778380d62 | gnsq/stream/defalte.py | gnsq/stream/defalte.py | from __future__ import absolute_import
import zlib
from .compression import CompressionSocket
class DefalteSocket(CompressionSocket):
def __init__(self, socket, level):
self._decompressor = zlib.decompressobj(level)
self._compressor = zlib.compressobj(level)
super(DefalteSocket, self).__i... | from __future__ import absolute_import
import zlib
from .compression import CompressionSocket
class DefalteSocket(CompressionSocket):
def __init__(self, socket, level):
wbits = -zlib.MAX_WBITS
self._decompressor = zlib.decompressobj(wbits)
self._compressor = zlib.compressobj(level, zlib.D... | Set correct waits for deflate. | Set correct waits for deflate.
| Python | bsd-3-clause | wtolson/gnsq,hiringsolved/gnsq,wtolson/gnsq | ---
+++
@@ -6,8 +6,9 @@
class DefalteSocket(CompressionSocket):
def __init__(self, socket, level):
- self._decompressor = zlib.decompressobj(level)
- self._compressor = zlib.compressobj(level)
+ wbits = -zlib.MAX_WBITS
+ self._decompressor = zlib.decompressobj(wbits)
+ self.... |
90531ef7caf2ad3f6cd5a50fd2f0acdc1236abd4 | importer/importer/__init__.py | importer/importer/__init__.py | import aiohttp
from aioes import Elasticsearch
from .importer import Importer
from .kudago import KudaGo
ELASTIC_ENDPOINTS = ['localhost:9200']
ELASTIC_INDEX_NAME = 'theatrics'
async def update():
with aiohttp.ClientSession() as http_client:
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
kudago = K... | import aiohttp
from aioes import Elasticsearch
from .importer import Importer
from .kudago import KudaGo
ELASTIC_ENDPOINTS = ['localhost:9200']
ELASTIC_INDEX_NAME = 'theatrics'
async def update():
async with aiohttp.ClientSession() as http_client:
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
kuda... | Use async with with ClientSession | Use async with with ClientSession
| Python | mit | despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics | ---
+++
@@ -10,7 +10,7 @@
async def update():
- with aiohttp.ClientSession() as http_client:
+ async with aiohttp.ClientSession() as http_client:
elastic = Elasticsearch(ELASTIC_ENDPOINTS)
kudago = KudaGo(http_client)
importer = Importer(kudago, elastic, ELASTIC_INDEX_NAME) |
02ca8bc5908b0ff15cd97846e1fd1488eddb4087 | backend/schedule/models.py | backend/schedule/models.py | from django.db import models
class Event(models.Model):
setup_start = models.DateField
setup_end = model.DateField
event_start = model.DateField
event_end = model.DateField
teardown_start = model.DateField
teardown_end = model.DateField
needed_resources = models.ManyToMany(Resource)
sta... | from django.db import models
class Event(models.Model):
setup_start = models.DateField
setup_end = model.DateField
event_start = model.DateField
event_end = model.DateField
teardown_start = model.DateField
teardown_end = model.DateField
needed_resources = models.ManyToMany(Resource)
sta... | Add square feet to Location data model. | Add square feet to Location data model.
| Python | mit | bable5/schdlr,bable5/schdlr,bable5/schdlr,bable5/schdlr | ---
+++
@@ -15,6 +15,7 @@
class Location(models.Model):
personel = models.ForeignKey('User')
+ square_footage = models.IntegerField
capacity = models.IntegerField
location_name = models.CharField(length=255, blank=False)
availability = models.CharField(length=255, blank=False) |
1fbb58a3f6692a7467f758ccedca6f8baa96a165 | text/__init__.py | text/__init__.py | #! /usr/bin/env python
import os
def get_files(path, ext=None):
"""
Get all files in directory path, optionally with the specified extension
"""
if ext is None:
ext = ''
return [
os.path.abspath(fname)
for fname in os.listdir(path)
if os.path.isfile(fname)
... | #! /usr/bin/env python
import os
import re
def get_files(path, ext=None):
"""
Get all files in directory path, optionally with the specified extension
"""
if ext is None:
ext = ''
return [
os.path.abspath(fname)
for fname in os.listdir(path)
if os.path.isfile(fnam... | Add function to get the functions / classes that are defined | Add function to get the functions / classes that are defined
| Python | mit | IanLee1521/utilities | ---
+++
@@ -1,6 +1,7 @@
#! /usr/bin/env python
import os
+import re
def get_files(path, ext=None):
@@ -23,3 +24,28 @@
Create a blob of text by reading in all filenames into a string
"""
return '\n'.join([open(fname).read() for fname in filenames])
+
+
+def get_definition(text, startswith):
+ ... |
8e75605e0511b85dfd500b644613739f29705da6 | cfnf.py | cfnf.py | import sublime, sublime_plugin
import time
class cfnewfile(sublime_plugin.TextCommand):
def run(self, edit):
localtime = time.asctime( time.localtime(time.time()) )
self.view.insert(edit,0,"<!---\r\n Name:\r\n Description:\r\n Written By:\r\n Date Created: "+localtime+"\r\n History:\r\n--->\r\n")
|
import sublime, sublime_plugin
import time
class cfnfCommand(sublime_plugin.WindowCommand):
def run(self):
a = self.window.new_file()
a.run_command("addheader")
class addheaderCommand(sublime_plugin.TextCommand):
def run(self, edit):
localtime = time.asctime( time.localtime(time.time()) )
sel... | Send text to new file | Send text to new file
| Python | bsd-2-clause | dwkd/SublimeCFNewFile | ---
+++
@@ -1,7 +1,13 @@
+
import sublime, sublime_plugin
import time
-class cfnewfile(sublime_plugin.TextCommand):
- def run(self, edit):
+class cfnfCommand(sublime_plugin.WindowCommand):
+ def run(self):
+ a = self.window.new_file()
+ a.run_command("addheader")
+
+class addheaderCommand(sublime_plugin.TextCom... |
99af762edb7a8fa4b0914bdf157af151a814adb6 | backend/api.py | backend/api.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import boto3
table_name = os.environ.get("TABLE_NAME")
table = boto3.resource("dynamodb").Table(table_name)
def _log_dynamo(response):
print "HTTPStatusCode:{}, RetryAttempts:{}, ScannedCount:{}, Count:{}".format(
response.get("ResponseM... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import boto3
table_name = os.environ.get("TABLE_NAME")
table = boto3.resource("dynamodb").Table(table_name)
def _log_dynamo(response):
print "HTTPStatusCode:{}, RetryAttempts:{}, ScannedCount:{}, Count:{}".format(
response.get("ResponseM... | Add CORS header to function | Add CORS header to function
| Python | mit | Vilsepi/no-servers,Vilsepi/no-servers,Vilsepi/no-servers,Vilsepi/no-servers | ---
+++
@@ -21,7 +21,8 @@
_log_dynamo(response)
return {
"statusCode": 200,
- "body": json.dumps(response["Items"], indent=1)
+ "body": json.dumps(response["Items"], indent=1),
+ "headers": {"Access-Control-Allow-Origin": "*"}
}
def get_item(event, context): |
6589df70baad1b57c604736d75e424465cf8775e | djangoautoconf/auto_conf_admin_tools/reversion_feature.py | djangoautoconf/auto_conf_admin_tools/reversion_feature.py | from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase
from django.conf import settings
__author__ = 'weijia'
class ReversionFeature(AdminFeatureBase):
def __init__(self):
super(ReversionFeature, self).__init__()
self.related_search_fields = {}
def process_paren... | from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase
from django.conf import settings
__author__ = 'weijia'
class ReversionFeature(AdminFeatureBase):
def __init__(self):
super(ReversionFeature, self).__init__()
self.related_search_fields = {}
def process_paren... | Fix import issue for Django 1.5 above | Fix import issue for Django 1.5 above
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | ---
+++
@@ -11,5 +11,8 @@
def process_parent_class_list(self, parent_list, class_inst):
if "reversion" in settings.INSTALLED_APPS:
- from reversion import VersionAdmin
+ try:
+ from reversion import VersionAdmin # for Django 1.5
+ except:
+ ... |
6df7ee955c7dfaee9a597b331dbc4c448fe3738a | fpr/migrations/0017_ocr_unique_names.py | fpr/migrations/0017_ocr_unique_names.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def data_migration(apps, schema_editor):
"""Migration that causes each OCR text file to include the UUID of its
source file in its filename. This prevents OCR text files from overwriting
one another when the... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def data_migration(apps, schema_editor):
"""Migration that causes each OCR text file to include the UUID of its
source file in its filename. This prevents OCR text files from overwriting
one another when the... | Fix OCR command UUID typo | Fix OCR command UUID typo
| Python | agpl-3.0 | artefactual/archivematica-fpr-admin,artefactual/archivematica-fpr-admin,artefactual/archivematica-fpr-admin,artefactual/archivematica-fpr-admin | ---
+++
@@ -12,9 +12,9 @@
transfer. See
https://github.com/artefactual/archivematica-fpr-admin/issues/66
"""
- IDCommand = apps.get_model('fpr', 'IDCommand')
- ocr_command = IDCommand.objects.get(
- uuid='5d501dbf-76bb-4569-a9db-9e367800995e')
+ FPCommand = apps.get_model('fpr', 'FPComm... |
8c49359a79d815cc21acbd58adc36c52d75e20b7 | dash2012/auth/views.py | dash2012/auth/views.py | from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required
from cloudfish.models import Cloud
def login(... | from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required
from cloudfish.models import Cloud
def login(... | Add login failed flash message | Add login failed flash message
| Python | bsd-3-clause | losmiserables/djangodash2012,losmiserables/djangodash2012 | ---
+++
@@ -7,6 +7,7 @@
def login(r):
+ c = {}
if r.POST:
username = r.POST['username']
password = r.POST['password']
@@ -19,7 +20,8 @@
return HttpResponseRedirect(reverse('myservers-view'))
- return render(r, 'auth.html')
+ c['errors'] = "Login failed, please try... |
e170a96859232d1436930be7a0cbfc7f2295c8a7 | main.py | main.py | from twisted.internet import reactor
from twisted.web import server, resource
from teiler.server import FileServerResource
from teiler.client import FileRequestResource
import sys
from twisted.python import log
class HelloResource(resource.Resource):
isLeaf = False
numberRequests = 0
def render_GET(self... | from twisted.internet import reactor
from twisted.web import server, resource
from teiler.server import FileServerResource
from teiler.client import FileRequestResource
import sys
from twisted.python import log
class HelloResource(resource.Resource):
isLeaf = False
numberRequests = 0
def render_GET(self... | Set root resource to welcome | Set root resource to welcome
| Python | mit | derwolfe/teiler,derwolfe/teiler | ---
+++
@@ -12,9 +12,8 @@
numberRequests = 0
def render_GET(self, request):
- self.numberRequests += 1
request.setHeader("content-type", "text/plain")
- return "I am request #" + str(self.numberRequests) + "\n"
+ return "Welcome to teiler\n"
if __name__ == '__main__':
... |
73b6a84cfc0ccc20d04c3dd80c3e505cd118be4d | nsfw.py | nsfw.py | import random
from discord.ext import commands
from lxml import etree
class NSFW:
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=['gel'])
async def gelbooru(self, ctx, *, tags):
async with ctx.typing():
entries = []
url = 'http://gelbooru.com/in... | import random
from discord.ext import commands
from lxml import etree
class NSFW:
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=['gel'], hidden=True)
async def gelbooru(self, ctx, *, tags):
async with ctx.typing():
entries = []
url = 'http://ge... | Make command invisible by default | Make command invisible by default
| Python | mit | BeatButton/beattie-bot,BeatButton/beattie | ---
+++
@@ -8,7 +8,7 @@
def __init__(self, bot):
self.bot = bot
- @commands.command(aliases=['gel'])
+ @commands.command(aliases=['gel'], hidden=True)
async def gelbooru(self, ctx, *, tags):
async with ctx.typing():
entries = [] |
22e6cce28da8a700bd4cd45aa47913aaff559a9d | functional_tests/management/commands/create_testrecipe.py | functional_tests/management/commands/create_testrecipe.py | from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.management import call_command
import random
import string
from recipes.models import Recipe
class Command(BaseCommand):
def handle(self, *args, **options):
r = Recipe(name=''.join(random.choice(string.asc... | import datetime
from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.management import call_command
import random
import string
from recipes.models import Recipe
class Command(BaseCommand):
def handle(self, *args, **options):
r = Recipe(name=''.join(random.c... | Make sure that recipes created by the command show up | Make sure that recipes created by the command show up
| Python | agpl-3.0 | XeryusTC/rotd,XeryusTC/rotd,XeryusTC/rotd | ---
+++
@@ -1,3 +1,4 @@
+import datetime
from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.management import call_command
@@ -10,3 +11,5 @@
r = Recipe(name=''.join(random.choice(string.ascii_letters) for _
in range(10)), description='descrip... |
f96990118d51b56ad438a8efbf2a7f83ec0f3c63 | conference_scheduler/tests/test_parameters.py | conference_scheduler/tests/test_parameters.py | from conference_scheduler import parameters
def test_variables(shape):
X = parameters.variables(shape)
assert len(X) == 21
def test_schedule_all_events(shape, X):
constraints = [c for c in parameters._schedule_all_events(shape, X)]
assert len(constraints) == 3
def test_max_one_event_per_slot(shape... | from conference_scheduler import parameters
import numpy as np
def test_tags(events):
tags = parameters.tags(events)
assert np.array_equal(tags, np.array([[1, 0], [1, 1], [0, 1]]))
def test_variables(shape):
X = parameters.variables(shape)
assert len(X) == 21
def test_schedule_all_events(shape, X):
... | Add failing test to function to build tags matrix. | Add failing test to function to build tags matrix.
| Python | mit | PyconUK/ConferenceScheduler | ---
+++
@@ -1,5 +1,9 @@
from conference_scheduler import parameters
+import numpy as np
+def test_tags(events):
+ tags = parameters.tags(events)
+ assert np.array_equal(tags, np.array([[1, 0], [1, 1], [0, 1]]))
def test_variables(shape):
X = parameters.variables(shape) |
24e65db624221d559f46ce74d88ad28ec970d754 | profile_collection/startup/00-startup.py | profile_collection/startup/00-startup.py | import logging
session_mgr._logger.setLevel(logging.INFO)
from dataportal import (DataBroker as db,
StepScan as ss, DataBroker,
StepScan, DataMuxer)
from bluesky.standard_config import *
from ophyd.commands import *
gs.RE.md['config'] = {}
gs.RE.md['owner'] = 'xf28id1'... | import logging
session_mgr._logger.setLevel(logging.INFO)
from dataportal import (DataBroker as db,
StepScan as ss, DataBroker,
StepScan, DataMuxer)
from bluesky.standard_config import *
from ophyd.commands import *
gs.RE.md['config'] = {}
gs.RE.md['owner'] = 'xf28id1'... | Update bluesky's API to the qt_kicker. | Update bluesky's API to the qt_kicker.
| Python | bsd-2-clause | NSLS-II-XPD/ipython_ophyd,pavoljuhas/ipython_ophyd,pavoljuhas/ipython_ophyd,NSLS-II-XPD/ipython_ophyd | ---
+++
@@ -12,3 +12,8 @@
gs.RE.md['owner'] = 'xf28id1'
gs.RE.md['group'] = 'XPD'
gs.RE.md['beamline_id'] = 'xpd'
+
+
+import bluesky.qt_kicker
+bluesky.qt_kicker.install_qt_kicker()
+ |
54b2a6953a4da2b217052d166ad1f069f683b9ee | scripts/nomenclature/nomenclature_map.py | scripts/nomenclature/nomenclature_map.py | """Create a map from the input binomials to their ITIS accepted synonyms.
"""
import pandas as pd
itis_results = pd.read_csv("search_result.csv", encoding = "ISO-8859-1")
| """Create a map from the input binomials to their ITIS accepted synonyms.
"""
import pandas as pd
from PyFloraBook.in_out.data_coordinator import locate_nomenclature_folder
# Globals
INPUT_FILE_NAME = "search_results.csv"
# Input
nomenclature_folder = locate_nomenclature_folder()
itis_results = pd.read_csv(
str... | Implement locator in nomenclature map | Implement locator in nomenclature map
| Python | mit | jnfrye/local_plants_book | ---
+++
@@ -2,4 +2,13 @@
"""
import pandas as pd
-itis_results = pd.read_csv("search_result.csv", encoding = "ISO-8859-1")
+from PyFloraBook.in_out.data_coordinator import locate_nomenclature_folder
+
+
+# Globals
+INPUT_FILE_NAME = "search_results.csv"
+
+# Input
+nomenclature_folder = locate_nomenclature_folder... |
b77e39b21a326655a04dbd15fcacfd2cc57a6008 | core/emails.py | core/emails.py | from django.core.mail import EmailMessage
from django.template.loader import render_to_string
def notify_existing_user(user, event):
""" Sends e-mail to existing organizer, that they're added
to the new Event.
"""
content = render_to_string('emails/existing_user.html', {
'user': user,
... | from django.core.mail import EmailMessage
from django.template.loader import render_to_string
def notify_existing_user(user, event):
""" Sends e-mail to existing organizer, that they're added
to the new Event.
"""
content = render_to_string('emails/existing_user.html', {
'user': user,
... | Fix broken order of arguments in send_email | Fix broken order of arguments in send_email
Ticket #342
| Python | bsd-3-clause | patjouk/djangogirls,patjouk/djangogirls,patjouk/djangogirls,DjangoGirls/djangogirls,patjouk/djangogirls,DjangoGirls/djangogirls,DjangoGirls/djangogirls | ---
+++
@@ -27,7 +27,7 @@
send_email(content, subject, user)
-def send_email(user, content, subject):
+def send_email(content, subject, user):
msg = EmailMessage(subject,
content,
"Django Girls <hello@djangogirls.org>", |
96ef78f53b7762782491bdd635a2c2dd1d6c75d2 | dimod/package_info.py | dimod/package_info.py | # Copyright 2018 D-Wave Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2018 D-Wave Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Update version 0.7.10 -> 0.7.11 | Update version 0.7.10 -> 0.7.11 | Python | apache-2.0 | dwavesystems/dimod,dwavesystems/dimod | ---
+++
@@ -14,7 +14,7 @@
#
# ================================================================================================
-__version__ = '0.7.10'
+__version__ = '0.7.11'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model... |
5bdbdfa94d06065c0536b684e6694b94ad80047b | authentication/authentication.py | authentication/authentication.py | from flask import Flask, jsonify, request
from requests import codes
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
username = request.form['email']
password = request.form['password']
response_content = {'email': username, 'password': password}
return jsonify(response_conte... | from flask import Flask, jsonify, request
from requests import codes
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
email = request.form['email']
password = request.form['password']
response_content = {'email': email, 'password': password}
return jsonify(response_content), c... | Use email variable name where appropriate | Use email variable name where appropriate
| Python | mit | jenca-cloud/jenca-authentication | ---
+++
@@ -5,16 +5,17 @@
@app.route('/login', methods=['POST'])
def login():
- username = request.form['email']
+ email = request.form['email']
password = request.form['password']
- response_content = {'email': username, 'password': password}
+ response_content = {'email': email, 'password': pas... |
badddd6aa9533a01e07477174dc7422ee4941014 | wsgi.py | wsgi.py | # Yith Library Server is a password storage server.
# Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Library Server.
#
# Yith Library Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publ... | # Yith Library Server is a password storage server.
# Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Library Server.
#
# Yith Library Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publ... | Read the conf file using absolute paths | Read the conf file using absolute paths
| Python | agpl-3.0 | lorenzogil/yith-library-server,lorenzogil/yith-library-server,lorenzogil/yith-library-server | ---
+++
@@ -16,12 +16,28 @@
# You should have received a copy of the GNU Affero General Public License
# along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>.
+import os
+import os.path
+
from newrelic import agent
agent.initialize()
from paste.deploy import loadapp
+from pyramid.paste... |
a6300723150d7d1ff9a58f4f3f1297e0fe2c6f78 | css_updater/git/manager.py | css_updater/git/manager.py | """manages github repos"""
import os
import tempfile
from typing import Dict, Any
import pygit2 as git
from .webhook.handler import Handler
class Manager(object):
"""handles git repos"""
def __init__(self: Manager, handler: Handler) -> None:
self.webhook_handler: Handler = handler
self.temp... | """manages github repos"""
import os
import tempfile
from typing import Dict, Any
import pygit2 as git
from .webhook.handler import Handler
class Manager(object):
"""handles git repos"""
def __init__(self: Manager, handler: Handler) -> None:
self.webhook_handler: Handler = handler
self.temp... | Check for errors in config | Check for errors in config
| Python | mit | neoliberal/css-updater | ---
+++
@@ -19,7 +19,12 @@
with open(os.path.join(self.temp_dir.name, "css-updater.json")) as config:
import json
- self.config: Dict[str, Any] = json.loads(config.read())
+ try:
+ self.config: Dict[str, Any] = json.loads(config.read())["css_updater"]
+ ... |
3d64eb4a7438b6b4f46f1fdf7f47d530cb11b09c | spacy/tests/regression/test_issue2396.py | spacy/tests/regression/test_issue2396.py | # coding: utf-8
from __future__ import unicode_literals
from ..util import get_doc
import pytest
import numpy
@pytest.mark.parametrize('sentence,matrix', [
(
'She created a test for spacy',
numpy.array([
[0, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 2, 3, 3, 3... | # coding: utf-8
from __future__ import unicode_literals
from ..util import get_doc
import pytest
import numpy
from numpy.testing import assert_array_equal
@pytest.mark.parametrize('words,heads,matrix', [
(
'She created a test for spacy'.split(),
[1, 0, 1, -2, -1, -1],
numpy.array([
... | Update get_lca_matrix test for develop | Update get_lca_matrix test for develop
| Python | mit | explosion/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy | ---
+++
@@ -5,10 +5,13 @@
import pytest
import numpy
+from numpy.testing import assert_array_equal
-@pytest.mark.parametrize('sentence,matrix', [
+
+@pytest.mark.parametrize('words,heads,matrix', [
(
- 'She created a test for spacy',
+ 'She created a test for spacy'.split(),
+ [1, 0, 1... |
61b96e4f925831e64e80d0253428dbd1b2c8a6a4 | app/grandchallenge/annotations/validators.py | app/grandchallenge/annotations/validators.py | from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
"""
re... | from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
BEWARE! Va... | Add comment to clarify validation method usage | Add comment to clarify validation method usage
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django | ---
+++
@@ -6,6 +6,7 @@
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
+ BEWARE! Validation will pass if user is not logged in or request or request.user is not defined
"""
reque... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.