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
5a4f52348d8174e9cb3c4c0b8bfe0baa50f70f31
tests/test_bot.py
tests/test_bot.py
from mock import patch import logging import congressbot @patch('congressbot.house_collection') @patch('congressbot.Reddit') def test_feed_parse(reddit_mock, house_mock): house_mock.find_one.return_value = False congressbot.parse() assert False
from mock import patch import logging import congressbot @patch('congressbot.house_collection') @patch('congressbot.Reddit') def test_feed_parse(reddit_mock, house_mock): house_mock.find_one.return_value = False congressbot.parse() assert False def test_google_feed(): # Will need to be updated in the...
Add test for google feed
Add test for google feed
Python
unlicense
koshea/congressbot
--- +++ @@ -9,3 +9,7 @@ house_mock.find_one.return_value = False congressbot.parse() assert False + +def test_google_feed(): + # Will need to be updated in the event of lasting world peace + assert congressbot.find_news_stories('war')
e88a0a27a4960f6b41170cffa0809423987db888
tests/test_transpiler.py
tests/test_transpiler.py
import os import unittest import transpiler class TestTranspiler: def test_transpiler_creates_files_without_format(self): try: os.remove("/tmp/auto_functions.cpp") os.remove("/tmp/auto_functions.h") except FileNotFoundError: pass transpiler.main(["--ou...
import os import unittest import transpiler class TestTranspiler: def test_transpiler_creates_files_without_format(self): try: os.remove("/tmp/auto_functions.cpp") os.remove("/tmp/auto_functions.h") except OSError: pass transpiler.main(["--output-dir",...
Fix error testing on python 2.7
Fix error testing on python 2.7
Python
mit
WesleyAC/lemonscript-transpiler,WesleyAC/lemonscript-transpiler,WesleyAC/lemonscript-transpiler
--- +++ @@ -9,7 +9,7 @@ try: os.remove("/tmp/auto_functions.cpp") os.remove("/tmp/auto_functions.h") - except FileNotFoundError: + except OSError: pass transpiler.main(["--output-dir", "/tmp"]) @@ -21,7 +21,7 @@ try: os.rem...
cddcc7e5735022c7a4faeee5331e7b80a6349406
src/functions.py
src/functions.py
def getTableColumnLabel(c): label = '' while True: label += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] if c <= 26: break c = int(c/26) return label def parseTableColumnLabel(label): ret = 0 for c in map(ord, reversed(label)): if 0x41 <= c <= 0x5A: ret = ret*26 + (c-0x41) else: ...
def getTableColumnLabel(c): label = '' while True: label = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] + label if c < 26: break c = c//26-1 return label def parseTableColumnLabel(label): if not label: raise ValueError('Invalid label: %s' % label) ret = -1 for c in map(ord, label): if 0x4...
Fix (parse|generate) table header label function
Fix (parse|generate) table header label function
Python
mit
takumak/tuna,takumak/tuna
--- +++ @@ -1,17 +1,19 @@ def getTableColumnLabel(c): label = '' while True: - label += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] - if c <= 26: + label = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] + label + if c < 26: break - c = int(c/26) + c = c//26-1 return label def parseTableColumnLabe...
41a59d72049c8c33dc4531df3561186e3852c328
pack/util/codec.py
pack/util/codec.py
import urllib def url_decode(string, encoding='utf8'): return urllib.unquote(string) def url_encode(string, encoding='utf8'): return urllib.urlencode(string)
import urllib def url_decode(string, encoding='utf8'): return urllib.unquote_plus(string) def url_encode(string, encoding='utf8'): return urllib.urlencode(string)
Fix URL decoding (need to use urllib.unquote_plus).
Fix URL decoding (need to use urllib.unquote_plus).
Python
mit
adeel/pump
--- +++ @@ -1,7 +1,7 @@ import urllib def url_decode(string, encoding='utf8'): - return urllib.unquote(string) + return urllib.unquote_plus(string) def url_encode(string, encoding='utf8'): return urllib.urlencode(string)
c4d4ba61d1948bebecfadd540a77603fc9dda204
benchfunk/core/plotters.py
benchfunk/core/plotters.py
import numpy as np from jug import TaskGenerator import ezplot __all__ = ['plot_stack'] @TaskGenerator def plot_stack(stack_results, problems=None, policies=None, name=''): problems = problems if problems is not None else stack_results.key() nfigs = len(problems) fig = ezplot.figure(figsize=(5*nfigs, 4...
import matplotlib matplotlib.use('Agg') import numpy as np from jug import TaskGenerator import ezplot __all__ = ['plot_stack'] @TaskGenerator def plot_stack(stack_results, problems=None, policies=None, name=''): problems = problems if problems is not None else stack_results.key() nfigs = len(problems) ...
Fix plotter to use 'Agg'.
Fix plotter to use 'Agg'.
Python
bsd-2-clause
mwhoffman/benchfunk
--- +++ @@ -1,3 +1,5 @@ +import matplotlib +matplotlib.use('Agg') import numpy as np from jug import TaskGenerator import ezplot
c970661c4525e0f3a9c77935ccfbef62742b18d4
csympy/__init__.py
csympy/__init__.py
from .lib.csympy_wrapper import (Symbol, Integer, sympify, SympifyError, Add, Mul, Pow, sin, cos, sqrt, function_symbol, I) from .utilities import var
from .lib.csympy_wrapper import (Symbol, Integer, sympify, SympifyError, Add, Mul, Pow, sin, cos, sqrt, function_symbol, I) from .utilities import var def test(): import pytest, os return not pytest.cmdline.main( [os.path.dirname(os.path.abspath(__file__))])
Add test function so tests can be run from within python terminal
Add test function so tests can be run from within python terminal import csympy csympy.test()
Python
mit
symengine/symengine.py,bjodah/symengine.py,bjodah/symengine.py,symengine/symengine.py,symengine/symengine.py,bjodah/symengine.py
--- +++ @@ -1,3 +1,8 @@ from .lib.csympy_wrapper import (Symbol, Integer, sympify, SympifyError, Add, Mul, Pow, sin, cos, sqrt, function_symbol, I) from .utilities import var + +def test(): + import pytest, os + return not pytest.cmdline.main( + [os.path.dirname(os.path.abspath(__file__))])
fc350215a32586ac2233749924fa61078e8c780a
cosmic_ray/testing/unittest_runner.py
cosmic_ray/testing/unittest_runner.py
from itertools import chain import unittest from .test_runner import TestRunner class UnittestRunner(TestRunner): # pylint:disable=no-init, too-few-public-methods """A TestRunner using `unittest`'s discovery mechanisms. This treats the first element of `test_args` as a directory. This discovers all tes...
from itertools import chain import unittest from .test_runner import TestRunner class UnittestRunner(TestRunner): # pylint:disable=no-init, too-few-public-methods """A TestRunner using `unittest`'s discovery mechanisms. This treats the first element of `test_args` as a directory. This discovers all tes...
Return a list of strings for unittest results, not list of tuples
Return a list of strings for unittest results, not list of tuples This is needed so the reporter can print a nicely formatted traceback when the job is killed.
Python
mit
sixty-north/cosmic-ray
--- +++ @@ -22,6 +22,4 @@ return ( result.wasSuccessful(), - [(str(r[0]), r[1]) - for r in chain(result.errors, - result.failures)]) + [r[1] for r in chain(result.errors, result.failures)])
f0ed7130172a3c5c70c2147919b6e213f065c2c2
open_journal.py
open_journal.py
import sublime, sublime_plugin import os, string import re from datetime import date try: from MarkdownEditing.wiki_page import * except ImportError: from wiki_page import * try: from MarkdownEditing.mdeutils import * except ImportError: from mdeutils import * class OpenJournalComm...
import sublime, sublime_plugin import os, string import re from datetime import date try: from MarkdownEditing.wiki_page import * except ImportError: from wiki_page import * try: from MarkdownEditing.mdeutils import * except ImportError: from mdeutils import * DEFAULT_DATE_FORMAT = '...
Add parameter to choose journal date format
Add parameter to choose journal date format This allows for other journal date formats to be permissible, adding an optional date format parameter to the setting file.
Python
mit
SublimeText-Markdown/MarkdownEditing
--- +++ @@ -14,12 +14,14 @@ except ImportError: from mdeutils import * - +DEFAULT_DATE_FORMAT = '%Y-%m-%d' + class OpenJournalCommand(MDETextCommand): def run(self, edit): print("Running OpenJournalCommand") today = date.today() - name = today.strftime('%Y-%m-%d') + ...
7a2fd849a80db2407fb6c734c02c21a2a9b9a66e
forms/management/commands/assign_missing_perms.py
forms/management/commands/assign_missing_perms.py
from django.core.management.base import BaseCommand from django.contrib.auth.models import User, Group from django.contrib import admin from gmmp.models import Monitor from forms.admin import ( RadioSheetAdmin, TwitterSheetAdmin, InternetNewsSheetAdmin, NewspaperSheetAdmin, TelevisionSheetAdmin) from forms.mo...
from django.core.management.base import BaseCommand from django.contrib.auth.models import User, Group from django.contrib import admin from gmmp.models import Monitor from forms.admin import ( RadioSheetAdmin, TwitterSheetAdmin, InternetNewsSheetAdmin, NewspaperSheetAdmin, TelevisionSheetAdmin) from forms.mo...
Revert "Clean up a bit"
Revert "Clean up a bit" This reverts commit 4500b571e2fd7a35cf722c3c9cc2fab7ea942cba.
Python
apache-2.0
Code4SA/gmmp,Code4SA/gmmp,Code4SA/gmmp
--- +++ @@ -15,17 +15,17 @@ newspaper_sheets, television_sheets) +sheet_types = [ + (RadioSheet, RadioSheetAdmin, radio_sheets), + (TwitterSheet, TwitterSheetAdmin, twitter_sheets), + (InternetnewsSheet, InternetNewsSheetAdmin, internetnews_sheets), + (NewspaperSheet, NewspaperSheetAdmin, newspap...
2a99fc24fec47b741359e3118969ba0f4d874e41
SettingsObject.py
SettingsObject.py
""" This class is used in kaggle competitions """ import json class Settings(): train_path = None test_path = None model_path = None submission_path = None string_train_path = "TRAIN_DATA_PATH" string_test_path = "TEST_DATA_PATH" string_model_path = "MODEL_PATH" string_submission_path ...
""" This class is used in kaggle competitions """ import json class Settings(): train_path = None test_path = None model_path = None submission_path = None string_train_path = "TRAIN_DATA_PATH" string_test_path = "TEST_DATA_PATH" string_model_path = "MODEL_PATH" string_submission_path ...
Remove not necessary code in Setting class
Remove not necessary code in Setting class
Python
apache-2.0
Gabvaztor/TFBoost
--- +++ @@ -34,6 +34,3 @@ self.model_path=settings[self.string_model_path] self.submission_path=settings[self.string_submission_path] - -s = Settings() -
ec032ab20de8d3f4d56d7d6901dd73c2bc2ada56
back_end/api.py
back_end/api.py
from bottle import get, route import redis import json from datetime import datetime RED = redis.ConnectionPool(host='redis_01',port=6379,db=0) #RED = redis.ConnectionPool(host='tuchfarber.com',port=6379,db=0) LENGTH_OF_PREG = 280 @get('/api/test') def index(): return {'status':'fuck you'} @get('/api/onthislay/<da...
from bottle import get, route import redis import json import sys import random from datetime import date, timedelta #RED = redis.ConnectionPool(host='redis_01',port=6379,db=0) RED = redis.ConnectionPool(host='tuchfarber.com',port=6379,db=0) LENGTH_OF_PREG = 280 WEEK = 7 @get('/api/test') def index(): return {'stat...
Return details from possible conception date
Return details from possible conception date
Python
mit
tuchfarber/tony-hawkathon-2016,tuchfarber/tony-hawkathon-2016,tuchfarber/tony-hawkathon-2016
--- +++ @@ -1,23 +1,54 @@ from bottle import get, route import redis import json -from datetime import datetime +import sys +import random +from datetime import date, timedelta -RED = redis.ConnectionPool(host='redis_01',port=6379,db=0) -#RED = redis.ConnectionPool(host='tuchfarber.com',port=6379,db=0) +#RED = r...
60150d28ed815095cfe16bd7c7170fd4f47cf86e
bacman/mysql.py
bacman/mysql.py
import os from .bacman import BacMan class MySQL(BacMan): """Take a snapshot of a MySQL DB.""" filename_prefix = os.environ.get('BACMAN_PREFIX', 'mysqldump') def get_command(self, path): command_string = "mysqldump -u {user} -p{password} -h {host} {name} > {path}" command = command_stri...
import os from .bacman import BacMan class MySQL(BacMan): """Take a snapshot of a MySQL DB.""" filename_prefix = os.environ.get('BACMAN_PREFIX', 'mysqldump') def get_command(self, path): command_string = "mysqldump -u {user} -p{password} -h {host} {name} > {path}" command = command_stri...
Add whitespace in order to be PEP8 compliant
Add whitespace in order to be PEP8 compliant
Python
bsd-3-clause
willandskill/bacman
fe07b97223dfffb789611b8b2cd043b628f8cef6
preview.py
preview.py
from PySide import QtGui, QtCore, QtWebKit class Preview(QtWebKit.QWebView): def __init__(self, parent=None): super(Preview, self).__init__(parent) self.load(QtCore.QUrl.fromLocalFile("/Users/audreyr/code/pydream-repos/rstpreviewer/testfiles/contributing.html"))
from PySide import QtGui, QtCore, QtWebKit from unipath import Path class Preview(QtWebKit.QWebView): def __init__(self, parent=None): super(Preview, self).__init__(parent) # TODO: Load HTML from real Sphinx output file output_html_path = Path("testfiles/contributing.html").absolute() self.load(QtCore.QUr...
Use Unipath for relative paths.
Use Unipath for relative paths.
Python
bsd-3-clause
techdragon/sphinx-gui,audreyr/sphinx-gui,techdragon/sphinx-gui,audreyr/sphinx-gui
--- +++ @@ -1,7 +1,11 @@ from PySide import QtGui, QtCore, QtWebKit +from unipath import Path class Preview(QtWebKit.QWebView): def __init__(self, parent=None): super(Preview, self).__init__(parent) - self.load(QtCore.QUrl.fromLocalFile("/Users/audreyr/code/pydream-repos/rstpreviewer/testfiles/contributin...
c51cdb577a97817569deac68f5f07401eb99cf38
pygp/inference/basic.py
pygp/inference/basic.py
""" Simple wrapper class for a Basic GP. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import numpy as np # local imports from .exact import ExactGP from ..likelihoods import Gaussian from ..kernels import SE, Matern...
""" Simple wrapper class for a Basic GP. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import numpy as np # local imports from .exact import ExactGP from ..likelihoods import Gaussian from ..kernels import SE, Matern...
Make BasicGP kernel strings lowercase.
Make BasicGP kernel strings lowercase.
Python
bsd-2-clause
mwhoffman/pygp
--- +++ @@ -24,13 +24,13 @@ # that we use the __repr__ method defined there and override the base method. class BasicGP(Printable, ExactGP): - def __init__(self, sn, sf, ell, ndim=None, kernel='SE'): + def __init__(self, sn, sf, ell, ndim=None, kernel='se'): likelihood = Gaussian(sn) kerne...
b64e2c30b0b3da3b77295469fac944ae18d4e6dc
publish/twitter.py
publish/twitter.py
"""Twitter delivery mechanism for botfriend.""" from nose.tools import set_trace import tweepy from bot import Publisher class TwitterPublisher(Publisher): def __init__( self, bot, full_config, kwargs ): for key in ['consumer_key', 'consumer_secret', 'access_token', 'ac...
# encoding: utf-8 """Twitter delivery mechanism for botfriend.""" import re import unicodedata from nose.tools import set_trace import tweepy from bot import Publisher class TwitterPublisher(Publisher): def __init__( self, bot, full_config, kwargs ): for key in ['consumer_key', 'consumer_s...
Replace initial D. and M. with similar-looking characters to get around archaic Twitter restriction.
Replace initial D. and M. with similar-looking characters to get around archaic Twitter restriction.
Python
mit
leonardr/botfriend
--- +++ @@ -1,4 +1,7 @@ +# encoding: utf-8 """Twitter delivery mechanism for botfriend.""" +import re +import unicodedata from nose.tools import set_trace import tweepy from bot import Publisher @@ -17,13 +20,9 @@ auth = tweepy.OAuthHandler(kwargs['consumer_key'], kwargs['consumer_secret']) auth...
41e426457c93fc5e0a785614c090a24aaf2e37f5
py/foxgami/user.py
py/foxgami/user.py
from . import db class Users(object): @classmethod def get_current(cls): return { 'data': { 'id': 1, 'type': 'user', 'name': 'Albert Sheu', 'short_name': 'Albert', 'profile_image_url': 'https://google.com' ...
from . import db class Users(object): @classmethod def get_current(cls): return { 'data': { 'id': 1, 'type': 'user', 'name': 'Albert Sheu', 'short_name': 'Albert', 'profile_image_url': 'http://flubstep.com/imag...
Make stub image url a real one
Make stub image url a real one
Python
mit
flubstep/foxgami.com,flubstep/foxgami.com
--- +++ @@ -10,6 +10,6 @@ 'type': 'user', 'name': 'Albert Sheu', 'short_name': 'Albert', - 'profile_image_url': 'https://google.com' + 'profile_image_url': 'http://flubstep.com/images/sunglasses.jpg' } }
171b0c16698b47a6b0771f2ec2de01079c9a8041
src/armet/connectors/cyclone/http.py
src/armet/connectors/cyclone/http.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division from armet import utils from armet.http import request, response class Request(request.Request): """Implements the request abstraction for cyclone. """ @property @utils.memoize_single def method(self): ...
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division from armet.http import request, response class Request(request.Request): """Implements the request abstraction for cyclone. """ def __init__(self, handler): self.handler = handler # This is the pyth...
Implement the cyclone request/response object
Implement the cyclone request/response object
Python
mit
armet/python-armet
--- +++ @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division -from armet import utils from armet.http import request, response @@ -8,21 +7,58 @@ """Implements the request abstraction for cyclone. """ + def __init__(self, handler): + sel...
ce9f5551ec7173cc132eb1271e0fc2c1bbfaa7ce
apps/worker/src/main/core/node.py
apps/worker/src/main/core/node.py
from syft.core.node.vm.vm import VirtualMachine node = VirtualMachine(name="om-vm")
from syft.core.node.device.device import Device from syft.grid.services.vm_management_service import CreateVMService node = Device(name="om-device") node.immediate_services_with_reply.append(CreateVMService) node._register_services() # re-register all services including SignalingService
ADD CreateVMService at Device APP
ADD CreateVMService at Device APP
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
--- +++ @@ -1,3 +1,6 @@ -from syft.core.node.vm.vm import VirtualMachine +from syft.core.node.device.device import Device +from syft.grid.services.vm_management_service import CreateVMService -node = VirtualMachine(name="om-vm") +node = Device(name="om-device") +node.immediate_services_with_reply.append(CreateVMSer...
a4dc87b5a9b555f74efa9bfe2bd16af5340d1199
googlesearch/googlesearch.py
googlesearch/googlesearch.py
#!/usr/bin/python import json import urllib def showsome(searchfor): query = urllib.urlencode({'q': searchfor}) url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query search_response = urllib.urlopen(url) search_results = search_response.read() results = json.loads(search_results) dat...
#!/usr/bin/python import json import urllib import sys def showsome(searchfor): query = urllib.urlencode({'q': searchfor}) url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query search_response = urllib.urlopen(url) search_results = search_response.read() results = json.loads(search_res...
Update of the google search code to be a command line program.
Update of the google search code to be a command line program.
Python
apache-2.0
phpsystems/code,phpsystems/code
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/python import json import urllib +import sys def showsome(searchfor): query = urllib.urlencode({'q': searchfor}) @@ -15,4 +16,11 @@ for h in hits: print ' ', h['url'] print 'For more results, see %s' % data['cursor']['moreResultsUrl'] -showsome('gallery.php-systems....
afb58da6ecc11a1c92d230bc2dcbb06464cc4f32
percept/workflows/commands/run_flow.py
percept/workflows/commands/run_flow.py
""" Given a config file, run a given workflow """ from percept.management.commands import BaseCommand from percept.utils.registry import registry, find_in_registry from percept.workflows.base import NaiveWorkflow from percept.utils.workflow import WorkflowWrapper, WorkflowLoader import logging log = logging.getLogger...
""" Given a config file, run a given workflow """ from percept.management.commands import BaseCommand from percept.utils.registry import registry, find_in_registry from percept.workflows.base import NaiveWorkflow from percept.utils.workflow import WorkflowWrapper, WorkflowLoader from optparse import make_option import...
Add in a way to start a shell using the results of a workflow
Add in a way to start a shell using the results of a workflow
Python
apache-2.0
VikParuchuri/percept,VikParuchuri/percept
--- +++ @@ -6,6 +6,8 @@ from percept.utils.registry import registry, find_in_registry from percept.workflows.base import NaiveWorkflow from percept.utils.workflow import WorkflowWrapper, WorkflowLoader +from optparse import make_option +import IPython import logging log = logging.getLogger(__name__) @@ -13,9 +...
3a9359660ff4c782e0de16e8115b754a3e17d7e7
inthe_am/taskmanager/models/usermetadata.py
inthe_am/taskmanager/models/usermetadata.py
from django.conf import settings from django.contrib.auth.models import User from django.db import models class UserMetadata(models.Model): user = models.ForeignKey( User, related_name="metadata", unique=True, on_delete=models.CASCADE ) tos_version = models.IntegerField(default=0) tos_accepted...
from django.conf import settings from django.contrib.auth.models import User from django.db import models class UserMetadata(models.Model): user = models.OneToOneField( User, related_name="metadata", on_delete=models.CASCADE ) tos_version = models.IntegerField(default=0) tos_accepted = models....
Change mapping to avoid warning
Change mapping to avoid warning
Python
agpl-3.0
coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am
--- +++ @@ -4,8 +4,8 @@ class UserMetadata(models.Model): - user = models.ForeignKey( - User, related_name="metadata", unique=True, on_delete=models.CASCADE + user = models.OneToOneField( + User, related_name="metadata", on_delete=models.CASCADE ) tos_version = models.IntegerField(d...
e1b36955d2a4e3eb4f36d75b4393cd510e3ddcab
workshopper/exercises.py
workshopper/exercises.py
class Exercise(object): name = None title = None def __init__(self, workshop): self.workshop = workshop def get_name(self): return self.name def get_title(self): return self.title
class Exercise(object): title = None def __init__(self, workshop): self.workshop = workshop @property def name(self): # TODO: Get from file return ''
Add name property to exercise.
Add name property to exercise.
Python
mit
pyschool/story
--- +++ @@ -1,13 +1,11 @@ class Exercise(object): - name = None title = None def __init__(self, workshop): self.workshop = workshop - def get_name(self): - return self.name - - def get_title(self): - return self.title + @property + def name(self): + # TODO...
81756324744334de39a0b151d9acac9e24774b9d
api/management/commands/deleteuselessactivities.py
api/management/commands/deleteuselessactivities.py
from django.core.management.base import BaseCommand, CommandError from api import models from django.db.models import Count, Q class Command(BaseCommand): can_import_settings = True def handle(self, *args, **options): if 'NR' in args: print 'Delete activities of N/R cards' act...
from django.core.management.base import BaseCommand, CommandError from api import models from django.db.models import Count, Q class Command(BaseCommand): can_import_settings = True def handle(self, *args, **options): if 'NR' in args: print 'Delete activities of N/R cards' act...
Use list of values and not subquery (less efficient but do not use limit)
Use list of values and not subquery (less efficient but do not use limit)
Python
apache-2.0
rdsathene/SchoolIdolAPI,rdsathene/SchoolIdolAPI,laurenor/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,laurenor/SchoolIdolAPI,laurenor/SchoolIdolAPI,dburr/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,dburr/SchoolIdolAPI,rdsathene/SchoolIdolAPI,dburr/SchoolIdolAPI
--- +++ @@ -18,7 +18,7 @@ accounts = models.Account.objects.all() for account in accounts: to_keep = models.Activity.objects.filter(account=account).order_by('-creation')[:50] - to_delete = models.Activity.objects.filter(account=account).exclude(pk__in=to_keep) + t...
1e45a5d781f426a383721b9c293f3d4b976fabed
image_cropping/thumbnail_processors.py
image_cropping/thumbnail_processors.py
import logging logger = logging.getLogger(__name__) def crop_corners(image, box=None, **kwargs): """ Crop corners to the selection defined by image_cropping `box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers. """ if not box: return image if not isinstance(box...
import logging logger = logging.getLogger(__name__) def crop_corners(image, box=None, **kwargs): """ Crop corners to the selection defined by image_cropping `box` is a string of the format 'x1,y1,x2,y2' or a four-tuple of integers. """ if not box: return image if not isinstance(box...
Correct typo in documentation of crop_corners
Correct typo in documentation of crop_corners
Python
bsd-3-clause
henriquechehad/django-image-cropping,winzard/django-image-cropping,winzard/django-image-cropping,henriquechehad/django-image-cropping,winzard/django-image-cropping,henriquechehad/django-image-cropping
--- +++ @@ -8,7 +8,7 @@ """ Crop corners to the selection defined by image_cropping - `box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers. + `box` is a string of the format 'x1,y1,x2,y2' or a four-tuple of integers. """ if not box: return image
7892e34e31ebfe7d3aba27bf147b6c669b428c07
journal.py
journal.py
# -*- coding: utf-8 -*- from flask import Flask from contextlib import closing import os, psycopg2 DB_SCHEMA= """ DROP TABLE IF EXISTS entries; CREATE TABLE entries ( id serial PRIMARY KEY, title VARCHAR (127) NOT NULL, text TEXT NOT NULL, created TIMESTAMP NOT NULL ) """ app= Flask(__name__) app....
# -*- coding: utf-8 -*- from flask import Flask from flask import g from contextlib import closing import os, psycopg2 DB_SCHEMA= """ DROP TABLE IF EXISTS entries; CREATE TABLE entries ( id serial PRIMARY KEY, title VARCHAR (127) NOT NULL, text TEXT NOT NULL, created TIMESTAMP NOT NULL ) """ app= ...
Add functionality to establish connection with database, and disallow operation on said database if there is a problem with the connection
Add functionality to establish connection with database, and disallow operation on said database if there is a problem with the connection
Python
mit
charlieRode/learning_journal
--- +++ @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from flask import Flask +from flask import g from contextlib import closing import os, psycopg2 @@ -31,6 +32,25 @@ db.cursor().execute(DB_SCHEMA) db.commit() +def get_database_connection(): + db= getattr(g, 'db', None) + if g.db is None: ...
faa0e5fd214151e8b0bb8fb18772807aa020c4bf
infrastructure/crowdin/crowdin_bot_python_package/crowdin_bot/get_crowdin_languages.py
infrastructure/crowdin/crowdin_bot_python_package/crowdin_bot/get_crowdin_languages.py
"""Script to print list of all crowdin language codes for project.""" from crowdin_bot import api NS_DICT = { 'ns': "urn:oasis:names:tc:xliff:document:1.2" } def get_project_languages(): """Get list of crowdin language codes. Returns: (list) list of project crowdin language codes """ inf...
"""Script to print list of all crowdin language codes for project.""" from crowdin_bot import api NS_DICT = { 'ns': "urn:oasis:names:tc:xliff:document:1.2" } def get_project_languages(): """Get list of crowdin language codes. Returns: (list) list of project crowdin language codes """ act...
Modify crowdin_bot to only include languages that have >0 translations
Modify crowdin_bot to only include languages that have >0 translations
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
--- +++ @@ -12,14 +12,14 @@ Returns: (list) list of project crowdin language codes """ - info_xml = api.api_call_xml("info") - languages = info_xml.find('languages') - translatable_languages = [] - for language in languages: - # Check it's not the incontext pseudo language - ...
d5cfb72626d486276af842b152d19c19d6d7b58c
bika/lims/subscribers/objectmodified.py
bika/lims/subscribers/objectmodified.py
from Products.CMFCore.utils import getToolByName def ObjectModifiedEventHandler(obj, event): """ Various types need automation on edit. """ if not hasattr(obj, 'portal_type'): return if obj.portal_type == 'Calculation': pr = getToolByName(obj, 'portal_repository') uc = getToolB...
from Products.CMFCore.utils import getToolByName from Products.CMFCore import permissions def ObjectModifiedEventHandler(obj, event): """ Various types need automation on edit. """ if not hasattr(obj, 'portal_type'): return if obj.portal_type == 'Calculation': pr = getToolByName(obj, ...
Fix missing import in Client modified subscriber
Fix missing import in Client modified subscriber
Python
agpl-3.0
anneline/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS,veroc/Bika-LIMS,DeBortoliWines/Bika-LIMS,rockfruit/bika.lims,veroc/Bika-LIMS,rockfruit/bika.lims,labsanmartin/Bika-LIMS,labsanmartin/Bika-LIMS,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS
--- +++ @@ -1,4 +1,6 @@ from Products.CMFCore.utils import getToolByName +from Products.CMFCore import permissions + def ObjectModifiedEventHandler(obj, event): """ Various types need automation on edit. @@ -13,9 +15,10 @@ backrefs = obj.getBackReferences('AnalysisServiceCalculation') for i...
13a698e9ca9c46e31fa369af811a68e705571aca
tests/test_installation.py
tests/test_installation.py
""" Role tests """ from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner('.molecule/ansible_inventory').get_hosts('all') def test_packages(host): """ Check if packages are installed """ packages = [] if host.system_info.distribution == 'debian': packa...
""" Role tests """ from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner('.molecule/ansible_inventory').get_hosts('all') def test_packages(host): """ Check if packages are installed """ packages = [] if host.system_info.distribution == 'debian': packa...
Update tests with new default language
Update tests with new default language
Python
mit
infOpen/ansible-role-locales
--- +++ @@ -21,7 +21,7 @@ elif host.system_info.distribution == 'ubuntu': packages = [ 'locales', - 'language-pack-fr', + 'language-pack-en', ] for package in packages:
0cb3aa5947b5c5da802c05ae16bc138441c2c921
accounts/views.py
accounts/views.py
from django.shortcuts import render def index(request): if not request.user.is_authenticated(): return render(request, 'account/index.html') else: return render(request, 'account/user_home.html')
from django.core.urlresolvers import reverse from django.shortcuts import redirect, render def index(request): if not request.user.is_authenticated(): return render(request, 'account/index.html') else: return redirect(reverse('quizzes:index'))
Use quiz index as user home temporarily
Use quiz index as user home temporarily
Python
mit
lockhawksp/beethoven,lockhawksp/beethoven
--- +++ @@ -1,4 +1,5 @@ -from django.shortcuts import render +from django.core.urlresolvers import reverse +from django.shortcuts import redirect, render def index(request): @@ -6,4 +7,4 @@ return render(request, 'account/index.html') else: - return render(request, 'account/user_home.html'...
b02c5736a6a0875da7e7feeaa433f4870d1f4bca
indra/sources/eidos/eidos_reader.py
indra/sources/eidos/eidos_reader.py
from indra.java_vm import autoclass, JavaException from .scala_utils import get_python_json class EidosReader(object): """Reader object keeping an instance of the Eidos reader as a singleton. This allows the Eidos reader to need initialization when the first piece of text is read, the subsequent readings ...
import json from indra.java_vm import autoclass, JavaException class EidosReader(object): """Reader object keeping an instance of the Eidos reader as a singleton. This allows the Eidos reader to need initialization when the first piece of text is read, the subsequent readings are done with the same in...
Simplify Eidos reader, use Eidos JSON String call
Simplify Eidos reader, use Eidos JSON String call
Python
bsd-2-clause
sorgerlab/belpy,bgyori/indra,pvtodorov/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,johnbachman/indra,bgyori/indra,pvtodorov/indra
--- +++ @@ -1,5 +1,5 @@ +import json from indra.java_vm import autoclass, JavaException -from .scala_utils import get_python_json class EidosReader(object): """Reader object keeping an instance of the Eidos reader as a singleton. @@ -36,7 +36,7 @@ mentions = self.eidos_reader.extractFrom(text) ...
f34d0d43311e51bcb04c5cbdf5bb31b7a8093feb
pyconde/tagging.py
pyconde/tagging.py
""" This abstracts some of the functionality provided by django-taggit in order to normalize the tags provided by the users. """ from taggit import managers as taggit_managers def _normalize_tag(t): if isinstance(t, unicode): return t.lower() return t class _TaggableManager(taggit_managers._Taggabl...
""" This abstracts some of the functionality provided by django-taggit in order to normalize the tags provided by the users. """ from taggit import managers as taggit_managers def _normalize_tag(t): if isinstance(t, unicode): return t.lower() return t class _TaggableManager(taggit_managers._Taggabl...
Fix regression introduced by updating taggit (27971d6eed)
Fix regression introduced by updating taggit (27971d6eed) django-taggit 0.11+ introduced support for prefetch_related which breaks our taggit wrapping: alex/django-taggit@4f2e47f833
Python
bsd-3-clause
pysv/djep,pysv/djep,EuroPython/djep,pysv/djep,pysv/djep,pysv/djep,EuroPython/djep,EuroPython/djep,EuroPython/djep
--- +++ @@ -24,6 +24,9 @@ raise ValueError("%s objects need to have a primary key value " "before you can access their tags." % model.__name__) manager = _TaggableManager( - through=self.through, model=model, instance=instance + through=self.through, + ...
65d8715705e07dc7f091e2da47a7ada923c6cfbb
release.py
release.py
""" Setuptools is released using 'jaraco.packaging.release'. To make a release, install jaraco.packaging and run 'python -m jaraco.packaging.release' """ import os import subprocess import pkg_resources pkg_resources.require('jaraco.packaging>=2.0') pkg_resources.require('wheel') def before_upload(): Bootstrap...
""" Setuptools is released using 'jaraco.packaging.release'. To make a release, install jaraco.packaging and run 'python -m jaraco.packaging.release' """ import os import subprocess import pkg_resources pkg_resources.require('jaraco.packaging>=2.0') pkg_resources.require('wheel') def before_upload(): Bootstrap...
Remove lingering reference to linked changelog.
Remove lingering reference to linked changelog.
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
--- +++ @@ -17,7 +17,6 @@ def after_push(): - os.remove('CHANGES (links).txt') BootstrapBookmark.push() files_with_versions = (
ae3d94fbc9a53df6bbeb0fedf6bb660ba6cd4b40
rpy2_helpers.py
rpy2_helpers.py
#! /usr/bin/env python2.7 """Avoid some boilerplate rpy2 usage code with helpers. Mostly I wrote this so that I can use xyplot without having to remember a lot of details. """ import click from rpy2.robjects import Formula, globalenv from rpy2.robjects.packages import importr grdevices = importr('grDevices') latti...
#! /usr/bin/env python2.7 """Avoid some boilerplate rpy2 usage code with helpers. Mostly I wrote this so that I can use xyplot without having to remember a lot of details. """ import click from rpy2.robjects import DataFrame, Formula, globalenv from rpy2.robjects.packages import importr grdevices = importr('grDevi...
Make DataFrame available to module user
Make DataFrame available to module user
Python
mit
ecashin/rpy2_helpers
--- +++ @@ -7,7 +7,7 @@ """ import click -from rpy2.robjects import Formula, globalenv +from rpy2.robjects import DataFrame, Formula, globalenv from rpy2.robjects.packages import importr @@ -29,7 +29,6 @@ import numpy as np from rpy2.robjects import numpy2ri numpy2ri.activate() - from rpy2....
13d1895a979cfb210e097e4d471238bf36c88c65
website/db_create.py
website/db_create.py
#!/usr/bin/env python3 from database import db from database import bdb from database import bdb_refseq from import_data import import_data import argparse def restet_relational_db(): print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') ...
#!/usr/bin/env python3 from database import db from database import bdb from database import bdb_refseq from import_data import import_data import argparse def restet_relational_db(): print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') ...
Use store true in db creation script
Use store true in db creation script
Python
lgpl-2.1
reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visua...
--- +++ @@ -30,13 +30,13 @@ parser.add_argument( '-i', '--import_mappings', - default=False, + action='store_true', help='Should mappings be (re)imported' ) parser.add_argument( '-r', '--reload_relational', - default=False, + acti...
e12eb10d699fce8e0081acc44025035f703b4dc5
crits/core/user_migrate.py
crits/core/user_migrate.py
def migrate_user(self): """ Migrate to latest schema version. """ migrate_1_to_2(self) migrate_2_to_3(self) def migrate_1_to_2(self): """ Migrate from schema 1 to schema 2. """ if self.schema_version == 1: self.schema_version = 2 notify_email = getattr(self.unsupp...
def migrate_user(self): """ Migrate to latest schema version. """ migrate_1_to_2(self) migrate_2_to_3(self) def migrate_1_to_2(self): """ Migrate from schema 1 to schema 2. """ if self.schema_version == 1: self.schema_version = 2 notify_email = getattr(self.unsupp...
Add default exploit to user migration.
Add default exploit to user migration.
Python
mit
cdorer/crits,DukeOfHazard/crits,korrosivesec/crits,Lambdanaut/crits,DukeOfHazard/crits,jinverar/crits,jinverar/crits,jhuapl-marti/marti,korrosivesec/crits,Magicked/crits,kaoscoach/crits,blaquee/crits,kaoscoach/crits,blaquee/crits,ckane/crits,HardlyHaki/crits,Magicked/crits,cdorer/crits,korrosivesec/crits,cfossace/crits...
--- +++ @@ -36,6 +36,7 @@ self.schema_version = 3 self.favorites['Backdoor'] = [] + self.favorites['Exploit'] = [] self.save() self.reload()
f09f33a6ddf0cf397838068e9cc3bc82464bf699
labelme/labelme/spiders/__init__.py
labelme/labelme/spiders/__init__.py
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders.
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders. import scrapy ANNOTATION_URL = 'http://people.csail.mit.edu/brussell/research/LabelMe/Annotations/' IMG_URL = 'http://people.csail.mit.edu/brussell/research/L...
Add a scaffold for spiders to crawl annotations and images
Add a scaffold for spiders to crawl annotations and images
Python
mit
paopow/LabelMeCrawler
--- +++ @@ -2,3 +2,29 @@ # # Please refer to the documentation for information on how to create and manage # your spiders. +import scrapy + +ANNOTATION_URL = 'http://people.csail.mit.edu/brussell/research/LabelMe/Annotations/' +IMG_URL = 'http://people.csail.mit.edu/brussell/research/LabelMe/Images/' + + +class An...
ba8de67d006c461b736f98f2bb1fcb876ec06830
svs_interface.py
svs_interface.py
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) ...
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os GPG = 'gpg2' SERVER_KEY = '' # replace with gpg key ID of server key class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.tex...
Add method to encrypt files
Add method to encrypt files
Python
agpl-3.0
mark-in/securedrop-prov-upstream,mark-in/securedrop-prov-upstream,mark-in/securedrop-prov-upstream,mark-in/securedrop-prov-upstream
--- +++ @@ -4,6 +4,9 @@ from Tkinter import * from tkFileDialog import * import os + +GPG = 'gpg2' +SERVER_KEY = '' # replace with gpg key ID of server key class GpgApp(object): def __init__(self, master): @@ -24,6 +27,9 @@ if fin: self.text.insert(END,fin) return fin + ...
70fb3744c07d14e5796e62992775cc97046f60ce
package/scripts/ambari_helpers.py
package/scripts/ambari_helpers.py
from resource_management import * import os def create_hdfs_dir(path, owner, perms): Execute('hadoop fs -mkdir -p '+path, user='hdfs') Execute('hadoop fs -chown ' + owner + ' ' + path, user='hdfs') Execute('hadoop fs -chmod ' + perms + ' ' + path, user='hdfs') def package(name): import params Execute(params...
from resource_management import * import os def create_hdfs_dir(path, owner, perms): Execute('hadoop fs -mkdir -p '+path, user='hdfs') Execute('hadoop fs -chown ' + owner + ' ' + path, user='hdfs') Execute('hadoop fs -chmod ' + str(perms) + ' ' + path, user='hdfs') def package(name): import params Execute(p...
Convert perms to a string
Convert perms to a string
Python
apache-2.0
cdapio/cdap-ambari-service,cdapio/cdap-ambari-service
--- +++ @@ -4,7 +4,7 @@ def create_hdfs_dir(path, owner, perms): Execute('hadoop fs -mkdir -p '+path, user='hdfs') Execute('hadoop fs -chown ' + owner + ' ' + path, user='hdfs') - Execute('hadoop fs -chmod ' + perms + ' ' + path, user='hdfs') + Execute('hadoop fs -chmod ' + str(perms) + ' ' + path, user='hdf...
2be69ba584b76134fc055ea17b476ce32ce5bf1e
haas/drivers/__init__.py
haas/drivers/__init__.py
"""Network switch drivers for the HaaS. This package provides HaaS drivers for various network switches. The functions in the top-level module should not be used; they only exist as a place to document the interface shared by all of the drivers. Port IDs and network IDs should both be strings. The content of them wi...
"""Network switch drivers for the HaaS. This package provides HaaS drivers for various network switches. The functions in the top-level module should not be used; they only exist as a place to document the interface shared by all of the drivers. Port IDs and network IDs should both be strings. The content of them wi...
Document reason for previous change
Document reason for previous change
Python
apache-2.0
meng-sun/hil,henn/haas,kylehogan/hil,henn/hil,henn/hil_sahil,henn/hil,kylehogan/hil,SahilTikale/haas,lokI8/haas,CCI-MOC/haas,meng-sun/hil,apoorvemohan/haas,kylehogan/haas,SahilTikale/switchHaaS,apoorvemohan/haas,henn/hil_sahil
--- +++ @@ -6,6 +6,15 @@ Port IDs and network IDs should both be strings. The content of them will be driver-specific. + +Note that get_new_network_id and free_network_id both accept a database +connection. They should not commit any changes---this way, if there is a +crash between the function returning, and t...
2781d26ecd6440a97e168f3b6a51c96eae25c004
examples/guv_simple_http_response.py
examples/guv_simple_http_response.py
import guv guv.monkey_patch() import guv.server import logging import time from util import create_example import logger if not hasattr(time, 'perf_counter'): time.perf_counter = time.clock logger.configure() log = logging.getLogger() response_times = [] def get_avg_time(): global response_times time...
# FIXME: pyuv_cffi needs to build the library BEFORE the standard library is patched import pyuv_cffi print('pyuv_cffi imported', pyuv_cffi) import guv guv.monkey_patch() import guv.server import logging import time from util import create_example import logger if not hasattr(time, 'perf_counter'): time.perf_co...
Add temporary workaround for monkey-patching bug
Add temporary workaround for monkey-patching bug pyuv_cffi needs to be imported BEFORE monkey-patching the standard library in order to successfully build the shared library. Need to find a workaround for this. Once the library is built, subsequent imports will work fine even after monkey-patching.
Python
mit
veegee/guv,veegee/guv
--- +++ @@ -1,3 +1,7 @@ +# FIXME: pyuv_cffi needs to build the library BEFORE the standard library is patched +import pyuv_cffi + +print('pyuv_cffi imported', pyuv_cffi) import guv guv.monkey_patch()
82ba04d609c80fd2bf8034cf38654d10bb72aca5
src/app/actions/psmtable/filter_confidence.py
src/app/actions/psmtable/filter_confidence.py
from app.readers import tsv as tsvreader def filter_psms(psms, confkey, conflvl, lower_is_better): for psm in psms: if passes_filter(psm, conflvl, confkey, lower_is_better): yield psm def passes_filter(psm, threshold, confkey, lower_is_better): if psm[confkey] in ['NA', '', None, False]:...
from app.readers import tsv as tsvreader def filter_psms(psms, confkey, conflvl, lower_is_better): for psm in psms: if passes_filter(psm, conflvl, confkey, lower_is_better): yield psm def passes_filter(psm, threshold, confkey, lower_is_better): try: confval = float(psm[confkey]) ...
Fix confidence filtering removed confidence=0 (False) items
Fix confidence filtering removed confidence=0 (False) items
Python
mit
glormph/msstitch
--- +++ @@ -8,7 +8,10 @@ def passes_filter(psm, threshold, confkey, lower_is_better): - if psm[confkey] in ['NA', '', None, False]: + try: + confval = float(psm[confkey]) + except (TypeError, ValueError): return False - lower = float(psm[confkey]) < float(threshold) - return lower ...
6a754b4a52619f84346a1cc89148884cefb3bc78
motobot/irc_level.py
motobot/irc_level.py
class IRCLevel: """ Enum class (Not really) for userlevels. """ user = 0 voice = 1 hop = 2 op = 3 aop = 4 sop = 5 def get_userlevels(nick): """ Return the userlevels in a list from a nick. """ mapping = { '+': IRCLevel.voice, '%': IRCLevel.hop, '@': IRCLevel...
class IRCLevel: """ Enum class (Not really) for userlevels. """ user = 0 vop = 1 hop = 2 aop = 3 sop = 4 owner = 5 master = 6
Update IRCLevel and remove get_userlevels
Update IRCLevel and remove get_userlevels
Python
mit
Motoko11/MotoBot
--- +++ @@ -1,26 +1,9 @@ class IRCLevel: """ Enum class (Not really) for userlevels. """ user = 0 - voice = 1 + vop = 1 hop = 2 - op = 3 - aop = 4 - sop = 5 - - -def get_userlevels(nick): - """ Return the userlevels in a list from a nick. """ - mapping = { - '+': IRCLevel.v...
ac725f0d96cfe6ef989d3377e5e7ed9e339fe7e5
djangoautoconf/auth/ldap_backend_wrapper.py
djangoautoconf/auth/ldap_backend_wrapper.py
from django_auth_ldap.backend import LDAPBackend class LDAPBackendWrapper(LDAPBackend): # def authenticate(self, identification, password, **kwargs): # return super(LDAPBackendWrapper, self).authenticate(identification, password, **kwargs) def authenticate(self, **kwargs): if "username" in kwa...
from django_auth_ldap.backend import LDAPBackend class LDAPBackendWrapper(LDAPBackend): # def authenticate(self, identification, password, **kwargs): # return super(LDAPBackendWrapper, self).authenticate(identification, password, **kwargs) def authenticate(self, **kwargs): if "username" in kwa...
Update codes for ldap wrapper so the username and password are passed to authenticate correctly.
Update codes for ldap wrapper so the username and password are passed to authenticate correctly.
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
--- +++ @@ -11,8 +11,7 @@ elif "identification" in kwargs: username = kwargs["identification"] del kwargs["identification"] - password = kwargs["password"] del kwargs["password"] - return super(LDAPBackendWrapper, self).authenticate(username, password, **kwa...
bc2246e8efa3a8d196c95ceb6d028f3b655b70c5
hooks/pre_gen_project.py
hooks/pre_gen_project.py
import re MODULE_REGEX = r"^[_a-zA-Z][_a-zA-Z0-9]*$" ENVIRON_REGEX = r"^[_a-zA-Z][_a-zA-Z0-9]*$" PYTHONVERSION_REGEX = r"^(3)\.[6-9]$" module_name = "{{ cookiecutter.project_slug}}" if not re.match(MODULE_REGEX, module_name): raise ValueError( f""" ERROR: The project slug ({module_name}) is not a valid...
import re MODULE_REGEX = r"^[-_a-zA-Z0-9]*$" ENVIRON_REGEX = r"^[-_a-zA-Z0-9]*$" PYTHONVERSION_REGEX = r"^(3)\.[6-9]$" module_name = "{{ cookiecutter.project_slug}}" if not re.match(MODULE_REGEX, module_name): raise ValueError( f""" ERROR: The project slug ({module_name}) is not a valid name. Please d...
Allow for minus signs in project slug.
Allow for minus signs in project slug.
Python
bsd-3-clause
hmgaudecker/econ-project-templates,hmgaudecker/econ-project-templates,hmgaudecker/econ-project-templates
--- +++ @@ -1,8 +1,8 @@ import re -MODULE_REGEX = r"^[_a-zA-Z][_a-zA-Z0-9]*$" -ENVIRON_REGEX = r"^[_a-zA-Z][_a-zA-Z0-9]*$" +MODULE_REGEX = r"^[-_a-zA-Z0-9]*$" +ENVIRON_REGEX = r"^[-_a-zA-Z0-9]*$" PYTHONVERSION_REGEX = r"^(3)\.[6-9]$" module_name = "{{ cookiecutter.project_slug}}" @@ -11,10 +11,10 @@ rai...
4c4bfbce3658fdac1e774a9aa2037fb1c466e21d
features/support/splinter_client.py
features/support/splinter_client.py
from pymongo import MongoClient from splinter import Browser from features.support.support import Api class SplinterClient(object): def __init__(self, database_name): self.database_name = database_name self._write_api = Api.start('write', '5001') def storage(self): return MongoClien...
from pymongo import MongoClient from splinter import Browser from features.support.support import Api class SplinterClient(object): def __init__(self, database_name): self.database_name = database_name self._write_api = Api.start('write', '5001') def storage(self): return MongoClien...
Decrease splinter timeout to 3 seconds
Decrease splinter timeout to 3 seconds @alexmuller @maxfliri
Python
mit
alphagov/backdrop,alphagov/backdrop,alphagov/backdrop
--- +++ @@ -14,7 +14,7 @@ return MongoClient('localhost', 27017)[self.database_name] def before_scenario(self): - self.browser = Browser('phantomjs', wait_time=15) + self.browser = Browser('phantomjs', wait_time=3) def after_scenario(self): self.browser.quit()
7e44e92e574efe110546a9d3a5e4807fa74fec6e
sympy/interactive/ipythonprinting.py
sympy/interactive/ipythonprinting.py
""" A print function that pretty prints SymPy objects. :moduleauthor: Brian Granger Usage ===== To use this extension, execute: %load_ext sympy.interactive.ipythonprinting Once the extension is loaded, SymPy Basic objects are automatically pretty-printed in the terminal and rendered in LaTeX in the Qt console ...
""" A print function that pretty prints SymPy objects. :moduleauthor: Brian Granger Usage ===== To use this extension, execute: %load_ext sympy.interactive.ipythonprinting Once the extension is loaded, SymPy Basic objects are automatically pretty-printed in the terminal and rendered in LaTeX in the Qt console ...
Fix testing error when IPython not installed
Fix testing error when IPython not installed
Python
bsd-3-clause
moble/sympy,jaimahajan1997/sympy,pbrady/sympy,yukoba/sympy,cccfran/sympy,asm666/sympy,kaushik94/sympy,jbbskinny/sympy,garvitr/sympy,lindsayad/sympy,dqnykamp/sympy,oliverlee/sympy,abloomston/sympy,dqnykamp/sympy,grevutiu-gabriel/sympy,hrashk/sympy,maniteja123/sympy,liangjiaxing/sympy,rahuldan/sympy,Designist/sympy,debug...
--- +++ @@ -26,7 +26,6 @@ # Imports #----------------------------------------------------------------------------- -import IPython from sympy.interactive.printing import init_printing #----------------------------------------------------------------------------- @@ -37,6 +36,8 @@ def load_ipython_extension...
5c928ea4c3f45cb32f7209a2c63a1c010d5860e0
app/models.py
app/models.py
from app import db class Base(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, default=db.func.current_timestamp()) class Route(Base): __tablename__ = 'route...
from app import db class Base(db.Model): __abstract__ = True pk = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, default=db.func.current_timestamp()) class Route(Base): __tablename__ = 'route...
Change field "id" to "pk" in order to not conflict with Python "id" keyword
Change field "id" to "pk" in order to not conflict with Python "id" keyword
Python
mit
mdsrosa/routes_api_python
--- +++ @@ -5,7 +5,7 @@ __abstract__ = True - id = db.Column(db.Integer, primary_key=True) + pk = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, default=db.func.current_timestamp())
1b093c116ff7fa926caa166c835fb3add4bf0036
scale/util/dcos.py
scale/util/dcos.py
from __future__ import absolute_import from __future__ import unicode_literals import json import requests from django.conf import settings from mesoshttp.acs import DCOSServiceAuth DCOS_AUTH = None DCOS_VERIFY = True if settings.SERVICE_SECRET: # We are in Enterprise mode and using service account DCOS_AUT...
from __future__ import absolute_import from __future__ import unicode_literals import json import requests from django.conf import settings from mesoshttp.acs import DCOSServiceAuth DCOS_AUTH = None DCOS_VERIFY = True if settings.SERVICE_SECRET: # We are in Enterprise mode and using service account DCOS_AUT...
Fix typo in requests helper
Fix typo in requests helper
Python
apache-2.0
ngageoint/scale,ngageoint/scale,ngageoint/scale,ngageoint/scale
--- +++ @@ -39,6 +39,6 @@ host_address.hostname, host_address.port, relative_url), - param=params, + params=params, au...
3c13870ffd25a31006cadbf9a9793566cffaecb6
win-installer/gaphor-script.py
win-installer/gaphor-script.py
if __name__ == "__main__": import gaphor from gaphor import core from gaphor.core.modeling import ElementFactory from gaphor.plugins.console import ConsoleWindow from gaphor.plugins.diagramexport import DiagramExport from gaphor.plugins.xmiexport import XMIExport from gaphor.services.compone...
if __name__ == "__main__": import gaphor from gaphor import core from gaphor.core.modeling import ElementFactory from gaphor.plugins.console import ConsoleWindow from gaphor.plugins.diagramexport import DiagramExport from gaphor.plugins.xmiexport import XMIExport from gaphor.services.compone...
Fix sanitizer service reference for windows
Fix sanitizer service reference for windows
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
--- +++ @@ -10,7 +10,7 @@ from gaphor.core.eventmanager import EventManager from gaphor.services.helpservice import HelpService from gaphor.services.properties import Properties - from gaphor.services.sanitizerservice import SanitizerService + from gaphor.UML.sanitizerservice import SanitizerServ...
3b21be6f0711163fdb6f1cf99514fae04f395b62
romanesco/plugins/swift/tests/swift_test.py
romanesco/plugins/swift/tests/swift_test.py
import romanesco import unittest class TestSwiftMode(unittest.TestCase): def testSwiftMode(self): task = { 'mode': 'swift', 'script': """ type file; app (file out) echo_app (string s) { echo s stdout=filename(out); } string a = arg("a", "10"); file out <"out.csv">; out = echo...
import os import romanesco import shutil import unittest def setUpModule(): global _tmp global _cwd _cwd = os.getcwd() _tmp = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'tmp', 'swift') if not os.path.isdir(_tmp): os.makedirs(_tmp) os.chdir(_tmp) def tearDownMod...
Clean up after swift run
Clean up after swift run
Python
apache-2.0
girder/girder_worker,Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,girder/girder_worker,Kitware/romanesco,girder/girder_worker
--- +++ @@ -1,5 +1,24 @@ +import os import romanesco +import shutil import unittest + + +def setUpModule(): + global _tmp + global _cwd + _cwd = os.getcwd() + _tmp = os.path.join( + os.path.dirname(os.path.abspath(__file__)), 'tmp', 'swift') + if not os.path.isdir(_tmp): + os.makedirs(_...
78deb7cc734bd5eaca9678bd61fa164699f21121
tohu/cloning.py
tohu/cloning.py
__all__ = ['CloneableMeta'] def attach_new_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the _clones attribute to an empty list. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): orig_init(self, *args, **kwargs)...
__all__ = ['CloneableMeta'] def attach_new_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the _clones attribute to an empty list. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): orig_init(self, *args, **kwargs)...
Add newline at end of file
Add newline at end of file
Python
mit
maxalbert/tohu
f2fd224b5e3c8cb4a919e082c47c603d4469a564
jacquard/buckets/tests/test_bucket.py
jacquard/buckets/tests/test_bucket.py
import pytest from jacquard.odm import Session from jacquard.buckets import Bucket from jacquard.buckets.constants import NUM_BUCKETS @pytest.mark.parametrize('divisor', ( 2, 3, 4, 5, 6, 10, 100, )) def test_divisible(divisor): assert NUM_BUCKETS % divisor == 0 def test_at_least_thr...
import pytest from jacquard.odm import Session from jacquard.buckets import Bucket from jacquard.buckets.constants import NUM_BUCKETS @pytest.mark.parametrize('divisor', ( 2, 3, 4, 5, 6, 10, 100, )) def test_divisible(divisor): assert NUM_BUCKETS % divisor == 0 def test_at_least_thr...
Use an explicit test here
Use an explicit test here
Python
mit
prophile/jacquard,prophile/jacquard
--- +++ @@ -25,4 +25,6 @@ def test_can_get_empty_bucket_from_old_format(): session = Session({'buckets/1': []}) bucket = session.get(Bucket, 1) - assert not bucket.needs_constraints() + # Force bucket to a string in order to reify the fields. This validates + # that the fields are accessible. + ...
7a0ed88e1775429ce283cc315cc05ea3dbde229f
tests/response_construction_tests.py
tests/response_construction_tests.py
from django.test.client import RequestFactory from mock import Mock from unittest2 import TestCase from .helpers import RequestPatchMixin from .test_views import TestProxy class ResponseConstructionTest(TestCase, RequestPatchMixin): def setUp(self): self.proxy = TestProxy.as_view() self.browser_r...
from django.test.client import RequestFactory from mock import Mock from unittest2 import TestCase from .helpers import RequestPatchMixin from .test_views import TestProxy class ResponseConstructionTest(TestCase, RequestPatchMixin): def get_request(self): return RequestFactory().get('/') def setUp(s...
Add test coverage for 1.10 CONTENT_LENGTH hack
Add test coverage for 1.10 CONTENT_LENGTH hack
Python
mit
thomasw/djproxy
--- +++ @@ -7,9 +7,12 @@ class ResponseConstructionTest(TestCase, RequestPatchMixin): + def get_request(self): + return RequestFactory().get('/') + def setUp(self): self.proxy = TestProxy.as_view() - self.browser_request = RequestFactory().get('/') + self.browser_request = s...
83ca7677ac77d55f9ba978f2988b18faa9e74424
secondhand/urls.py
secondhand/urls.py
from django.conf.urls import patterns, include, url from tastypie.api import Api from tracker.api import UserResource, TaskResource, WorkSessionResource # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() # tracker API. v1_api = Api(api_name='v1') v1_api.regis...
from django.conf.urls import patterns, include, url from tastypie.api import Api from tracker.api import UserResource, TaskResource, WorkSessionResource, \ RegistrationResource # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() # tracker API. v1_api = Api...
Fix minor issue, reorganize imports, and register the RegistrationResource with the API.
Fix minor issue, reorganize imports, and register the RegistrationResource with the API.
Python
mit
GeneralMaximus/secondhand
--- +++ @@ -1,6 +1,7 @@ from django.conf.urls import patterns, include, url from tastypie.api import Api -from tracker.api import UserResource, TaskResource, WorkSessionResource +from tracker.api import UserResource, TaskResource, WorkSessionResource, \ + RegistrationResource # Uncomment the next two lines to...
06f10e09f5b1c5766815b6e7eb219b4e33082709
check_urls.py
check_urls.py
#!/usr/bin/env python2.7 import re, sys, markdown, requests, bs4 as BeautifulSoup reload(sys) sys.setdefaultencoding('utf8') def check_url(url): try: return bool(requests.head(url, allow_redirects=True)) except Exception as e: print 'Error checking URL %s: %s' % (url, e) return False ...
#!/usr/bin/env python2.7 from __future__ import print_function import re, sys, markdown, requests, bs4 as BeautifulSoup try: # Python 2 reload except NameError: # Python 3 from importlib import reload reload(sys) sys.setdefaultencoding('utf8') def check_url(url): try: return bool(...
Add Python 3 compatibility and flake8 testing
Add Python 3 compatibility and flake8 testing
Python
unlicense
ligurio/free-software-testing-books
--- +++ @@ -1,6 +1,12 @@ #!/usr/bin/env python2.7 +from __future__ import print_function import re, sys, markdown, requests, bs4 as BeautifulSoup + +try: # Python 2 + reload +except NameError: # Python 3 + from importlib import reload reload(sys) sys.setdefaultencoding('utf8') @@ -9,7 +15...
9d1dc2ef7db2f883e05286edd3865acfdadc19be
django-oracle-drcp/base.py
django-oracle-drcp/base.py
# pylint: disable=W0401 from django.core.exceptions import ImproperlyConfigured from django.db.backends.oracle.base import * from django.db.backends.oracle.base import DatabaseWrapper as DjDatabaseWrapper import cx_Oracle class DatabaseWrapper(DjDatabaseWrapper): def __init__(self, *args, **kwargs): sup...
# pylint: disable=W0401 from django.core.exceptions import ImproperlyConfigured from django.db.backends.oracle.base import * from django.db.backends.oracle.base import DatabaseWrapper as DjDatabaseWrapper import cx_Oracle class DatabaseWrapper(DjDatabaseWrapper): def __init__(self, *args, **kwargs): sup...
Change variable name consistently to pool_config
Change variable name consistently to pool_config
Python
bsd-2-clause
JohnPapps/django-oracle-drcp
--- +++ @@ -15,7 +15,7 @@ 'max': 2, 'increment': 1, } - poolconfig = self.settings_dict.get('POOL', default_pool) + pool_config = self.settings_dict.get('POOL', default_pool) if set(pool_config.keys()) != {'min', 'max', 'increment'}: raise Imprope...
c5ff897355fb7fce5022127bcae756e8c68dc864
data/views.py
data/views.py
import os from django.shortcuts import render, redirect from django.template import Context from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from chemtools.extractor import CORES, RGROUPS, ARYL from data.models import JobTemplate def frag_index(request): xrnames = ["H", "...
import os from django.shortcuts import render, redirect from django.template import Context from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from chemtools.extractor import CORES, RGROUPS, ARYL from data.models import JobTemplate def frag_index(request): xrnames = ["H", "...
Add new fragments to data.frag_index
Add new fragments to data.frag_index
Python
mit
crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp
--- +++ @@ -10,9 +10,10 @@ def frag_index(request): xrnames = ["H", "Cl", "Br", "CN", "CCH", "OH", - "SH", "NH_2", "CH_3", "phenyl", "TMS", "OCH_3"] - arylnames = ["double bond", "triple bond", "phenyl", - "thiophene", "pyridine", "carbazole", "TZ", "EDOT"] + "SH", "NH_...
edec252d9a050ead0084280f9772f05a2a3d7608
preferences/forms.py
preferences/forms.py
from registration.forms import RegistrationFormUniqueEmail class RegistrationUserForm(RegistrationFormUniqueEmail): class Meta: model = User fields = ("email")
from django import forms from registration.forms import RegistrationFormUniqueEmail from preferences.models import Preferences # from django.forms import ModelForm # class RegistrationUserForm(RegistrationFormUniqueEmail): # class Meta: # model = User # fields = ("email") class PreferencesForm...
Add preferences form built off model
Add preferences form built off model
Python
mit
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
--- +++ @@ -1,7 +1,19 @@ +from django import forms from registration.forms import RegistrationFormUniqueEmail -class RegistrationUserForm(RegistrationFormUniqueEmail): +from preferences.models import Preferences +# from django.forms import ModelForm + +# class RegistrationUserForm(RegistrationFormUniqueEmail): +...
e6026134e02f516cc84e499494205efa0ad7441f
tests/test_autoconfig.py
tests/test_autoconfig.py
# coding: utf-8 import os import pytest from mock import patch from decouple import AutoConfig def test_autoconfig_env(): config = AutoConfig() path = os.path.join(os.getcwd(), 'autoconfig', 'env', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'ENV' == config('KEY...
# coding: utf-8 import os import pytest from mock import patch from decouple import AutoConfig def test_autoconfig_env(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'ENV' ...
Replace cwd with current module's path
Replace cwd with current module's path
Python
mit
mrkschan/python-decouple,flaviohenriqu/python-decouple,henriquebastos/django-decouple,liukaijv/python-decouple,henriquebastos/python-decouple
--- +++ @@ -7,14 +7,14 @@ def test_autoconfig_env(): config = AutoConfig() - path = os.path.join(os.getcwd(), 'autoconfig', 'env', 'project') + path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project') with patch.object(config, '_caller_path', return_value=path): asser...
ec884c9db173f093d1398de54d00f1c36f22d8e4
examples/random_valid_test_generator.py
examples/random_valid_test_generator.py
import sys import time from random import shuffle from FairDistributor import FairDistributor def main(): # User input for the number of targets and objects. number_of_targets = int(sys.argv[1]) number_of_objects = int(sys.argv[2]) # Generate dummy lists for objects, targets and dummy matrix for weigh...
import sys import time from random import shuffle from vania.fair_distributor import FairDistributor def main(): # User input for the number of targets and objects. number_of_targets = int(sys.argv[1]) number_of_objects = int(sys.argv[2]) # Generate dummy lists for objects, targets and dummy matrix f...
Reformat random generator reformat code
Reformat random generator reformat code
Python
mit
Hackathonners/vania
--- +++ @@ -1,13 +1,14 @@ import sys import time from random import shuffle -from FairDistributor import FairDistributor +from vania.fair_distributor import FairDistributor def main(): # User input for the number of targets and objects. number_of_targets = int(sys.argv[1]) number_of_objects = i...
6c0be372323393bdd8f7c734f7cf5f6e5f14a1a2
tof_server/versioning.py
tof_server/versioning.py
"""Module for handling server and client versions""" SERVER_VERSION = '0.1.0' CLIENT_VERSIONS = ['0.5.0'] def validate(request): for acceptable_version in CLIENT_VERSIONS: if request.user_agent.string == 'ToF/' + acceptable_version: return { 'status' : 'ok' } ...
"""Module for handling server and client versions""" SERVER_VERSION = '0.1.0' CLIENT_VERSIONS = ['0.5.0', '0.5.1'] def validate(request): for acceptable_version in CLIENT_VERSIONS: if request.user_agent.string == 'ToF/' + acceptable_version: return { 'status' : 'ok' ...
Add client beta version 0.5.1
Add client beta version 0.5.1
Python
mit
P1X-in/Tanks-of-Freedom-Server
--- +++ @@ -1,7 +1,7 @@ """Module for handling server and client versions""" SERVER_VERSION = '0.1.0' -CLIENT_VERSIONS = ['0.5.0'] +CLIENT_VERSIONS = ['0.5.0', '0.5.1'] def validate(request):
6e535ccc43a090112ba140ff0eca533eed9c9935
kafka_influxdb/reader/kafka_reader.py
kafka_influxdb/reader/kafka_reader.py
# -*- coding: utf-8 -*- import logging import time from kafka.client import KafkaClient from kafka.consumer import SimpleConsumer class KafkaReader(object): def __init__(self, host, port, group, topic, reconnect_wait_time=2): """ Initialize Kafka reader """ self.host = host ...
# -*- coding: utf-8 -*- import logging import time from kafka.client import KafkaClient from kafka.consumer import SimpleConsumer class KafkaReader(object): def __init__(self, host, port, group, topic, reconnect_wait_time=2): """ Initialize Kafka reader """ self.host = host ...
Make handle_read a private method
Make handle_read a private method
Python
apache-2.0
mre/kafka-influxdb,mre/kafka-influxdb
--- +++ @@ -34,10 +34,10 @@ Read from Kafka. Reconnect on error. """ while True: - for msg in self.handle_read(): + for msg in self._handle_read(): yield msg - def handle_read(self): + def _handle_read(self): """ Yield message...
a55bd9116114b546c06685e413209ab4279aaef5
genes/terraform/main.py
genes/terraform/main.py
from genes.mac.traits import is_osx from genes.brew import brew def main(): if is_osx(): brew.install()
from genes.mac.traits import is_osx from genes.brew.command import Brew def main(): if is_osx(): brew = Brew() brew.install()
Change the brew instruction. kinda dumb
Change the brew instruction. kinda dumb
Python
mit
hatchery/genepool,hatchery/Genepool2
--- +++ @@ -1,8 +1,9 @@ from genes.mac.traits import is_osx -from genes.brew import brew +from genes.brew.command import Brew def main(): if is_osx(): + brew = Brew() brew.install()
49fc55369d4755148d3db58c593d0b6f4d60582d
run_tests.py
run_tests.py
import sys import os import unittest import subprocess import time cmd = 'python -m pretenders.server.server --host 127.0.0.1 --port 50000' p = subprocess.Popen(cmd) time.sleep(2) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'lib'))) sys.path.append(os.path.abspath(os.path.join(os.path.dir...
import sys import os import unittest import subprocess import time import shlex cmd = 'python -m pretenders.server.server --host 127.0.0.1 --port 50000' p = subprocess.Popen(shlex.split(cmd)) time.sleep(2) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'lib'))) sys.path.append(os.path.abspat...
Fix test run on linux / travis
Fix test run on linux / travis
Python
mit
ucoin-io/cutecoin,ucoin-io/cutecoin,ucoin-io/cutecoin
--- +++ @@ -3,10 +3,11 @@ import unittest import subprocess import time +import shlex cmd = 'python -m pretenders.server.server --host 127.0.0.1 --port 50000' -p = subprocess.Popen(cmd) +p = subprocess.Popen(shlex.split(cmd)) time.sleep(2) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__fil...
6297eddaceb996a2c76825295af6a37e81d5c2fb
ain7/organizations/autocomplete_light_registry.py
ain7/organizations/autocomplete_light_registry.py
# -*- coding: utf-8 """ ain7/annuaire/autocomplete_light_registry.py """ # # Copyright © 2007-2015 AIn7 Devel Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of ...
# -*- coding: utf-8 """ ain7/annuaire/autocomplete_light_registry.py """ # # Copyright © 2007-2015 AIn7 Devel Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of ...
Allow to autocomplete on office & organization names
Allow to autocomplete on office & organization names
Python
lgpl-2.1
ain7/www.ain7.org,ain7/www.ain7.org,ain7/www.ain7.org,ain7/www.ain7.org
--- +++ @@ -28,6 +28,9 @@ ) -autocomplete_light.register(Office) +autocomplete_light.register( + Office, + search_fields=['name', 'organization__name'], +) autocomplete_light.register(Organization) autocomplete_light.register(OrganizationActivityField, search_fields=['label'])
db7e0e2ddff42081bc46002c656611ce5a5ba7b5
allauth/socialaccount/providers/kakao/provider.py
allauth/socialaccount/providers/kakao/provider.py
from allauth.account.models import EmailAddress from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KakaoAccount(ProviderAccount): @property def properties(self): return self.account.extra_data.get('propertie...
from allauth.account.models import EmailAddress from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KakaoAccount(ProviderAccount): @property def properties(self): return self.account.extra_data.get('propertie...
Change field name from 'nickname' to 'username'
fix(kakao): Change field name from 'nickname' to 'username'
Python
mit
pennersr/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,bittner/django-allauth,bittner/django-allauth,lukeburden/django-allauth,pennersr/django-allauth,bittner/django-allauth,rsalmaso/django-allauth,pennersr/django-allauth
--- +++ @@ -28,7 +28,7 @@ email = data['kakao_account'].get('email') nickname = data['properties'].get('nickname') - return dict(email=email, nickname=nickname) + return dict(email=email, username=nickname) def extract_email_addresses(self, data): ret = []
5fef3e5a5425ab71abb4c3b8a36a2273c9947b2e
bcbio/chipseq/__init__.py
bcbio/chipseq/__init__.py
from bcbio.ngsalign.bowtie2 import filter_multimappers import bcbio.pipeline.datadict as dd def clean_chipseq_alignment(data): aligner = dd.get_aligner(data) data["raw_bam"] = dd.get_work_bam(data) if aligner: assert aligner == "bowtie2", "ChIP-seq only supported for bowtie2." unique_bam = ...
from bcbio.ngsalign.bowtie2 import filter_multimappers import bcbio.pipeline.datadict as dd def clean_chipseq_alignment(data): aligner = dd.get_aligner(data) data["raw_bam"] = dd.get_work_bam(data) if aligner: assert aligner == "bowtie2", "ChIP-seq only supported for bowtie2." unique_bam = ...
Add warning when aligner is false
Chipseq: Add warning when aligner is false
Python
mit
biocyberman/bcbio-nextgen,biocyberman/bcbio-nextgen,chapmanb/bcbio-nextgen,vladsaveliev/bcbio-nextgen,lbeltrame/bcbio-nextgen,brainstorm/bcbio-nextgen,a113n/bcbio-nextgen,lbeltrame/bcbio-nextgen,biocyberman/bcbio-nextgen,vladsaveliev/bcbio-nextgen,chapmanb/bcbio-nextgen,a113n/bcbio-nextgen,lbeltrame/bcbio-nextgen,brain...
--- +++ @@ -8,4 +8,7 @@ assert aligner == "bowtie2", "ChIP-seq only supported for bowtie2." unique_bam = filter_multimappers(dd.get_work_bam(data), data) data["work_bam"] = unique_bam + else: + logger.info("When BAM file is given, bcbio skips multimappers removal.") + logge...
5b616f5b3d605b1831d4ca8ca0a9be561f399a89
falmer/events/admin.py
falmer/events/admin.py
from django.contrib import admin from django.contrib.admin import register from falmer.events.models import Event @register(Event) class EventModelAdmin(admin.ModelAdmin): pass
from django.contrib import admin from django.contrib.admin import register from falmer.events.models import Event, MSLEvent @register(Event) class EventModelAdmin(admin.ModelAdmin): list_display = ('title', 'start_time', 'end_time', ) @register(MSLEvent) class MSLEventModelAdmin(admin.ModelAdmin): pass
Improve list display of events
Improve list display of events
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
--- +++ @@ -1,9 +1,13 @@ from django.contrib import admin from django.contrib.admin import register -from falmer.events.models import Event +from falmer.events.models import Event, MSLEvent @register(Event) class EventModelAdmin(admin.ModelAdmin): + list_display = ('title', 'start_time', 'end_time', ) + ...
cbb6f7495123f1745284d0b098dcfaae0b31c5f3
bin/commands/utils/git.py
bin/commands/utils/git.py
"""A collection of common git actions.""" from subprocess import check_output, PIPE, Popen, STDOUT def is_valid_reference(reference): """Determines if a reference is valid. :param str reference: name of the reference to validate :return bool: whether or not the reference is valid """ show_ref_...
"""A collection of common git actions.""" import os from subprocess import check_output, PIPE, Popen, STDOUT def is_valid_reference(reference): """Determines if a reference is valid. :param str reference: name of the reference to validate :return bool: whether or not the reference is valid """ ...
Add type checking and piping to /dev/null
Add type checking and piping to /dev/null
Python
mit
Brickstertwo/git-commands
--- +++ @@ -1,5 +1,6 @@ """A collection of common git actions.""" +import os from subprocess import check_output, PIPE, Popen, STDOUT @@ -11,6 +12,8 @@ :return bool: whether or not the reference is valid """ + assert isinstance(reference, str), "'reference' must be a str. Given: " + type(refere...
25e2c37bb9dc17f0c10ae744b1554b94c4e5a7ff
doj/monkey/__init__.py
doj/monkey/__init__.py
# -*- coding: utf-8 -*- import doj.monkey.django_utils_functional_lazy import doj.monkey.django_http_response_streaminghttpresponse import doj.monkey.inspect_getcallargs def install_monkey_patches(): doj.monkey.django_utils_functional_lazy.install() doj.monkey.django_http_response_streaminghttpresponse.insta...
# -*- coding: utf-8 -*- import doj.monkey.django_utils_functional_lazy import doj.monkey.django_http_response_streaminghttpresponse import doj.monkey.inspect_getcallargs def install_monkey_patches(): # Make sure we install monkey patches only once if not getattr(install_monkey_patches, 'installed', False): ...
Make sure we install monkey patches only once
Make sure we install monkey patches only once
Python
bsd-3-clause
beachmachine/django-jython
--- +++ @@ -6,6 +6,10 @@ def install_monkey_patches(): - doj.monkey.django_utils_functional_lazy.install() - doj.monkey.django_http_response_streaminghttpresponse.install() - doj.monkey.inspect_getcallargs.install() + # Make sure we install monkey patches only once + if not getattr(install_monkey_...
109018326b317a160e0ba555b23b7b4401f44ed3
website/views.py
website/views.py
from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from news.models import Article, Event from door.models import DoorStatus from datetime import datetime from itertools import chain def index(request): number_of_news = 3 # Sorts the ...
from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from news.models import Article, Event from door.models import DoorStatus from datetime import datetime from itertools import chain def index(request): number_of_news = 3 # Sorts the ...
Change redirect to application redirect
Change redirect to application redirect
Python
mit
hackerspace-ntnu/website,hackerspace-ntnu/website,hackerspace-ntnu/website
--- +++ @@ -28,7 +28,7 @@ def opptak(request): - return HttpResponseRedirect(reverse('application_form')) + return HttpResponseRedirect(reverse('article', args=[6])) def test404(request):
23450c05921ecadedc03a273804e8e6ddaa5439a
meetup_facebook_bot/models/speaker.py
meetup_facebook_bot/models/speaker.py
from sqlalchemy import Column, BIGINT, String, Integer from meetup_facebook_bot.models.base import Base class Speaker(Base): __tablename__ = 'speakers' id = Column(Integer, primary_key=True, autoincrement=True) page_scoped_id = Column(BIGINT, unique=True) name = Column(String(128), nullable=False) ...
from sqlalchemy import Column, BIGINT, String, Integer from meetup_facebook_bot.models.base import Base class Speaker(Base): __tablename__ = 'speakers' id = Column(Integer, primary_key=True, autoincrement=True) page_scoped_id = Column(BIGINT, unique=True) name = Column(String(128), nullable=False) ...
Fix repr calling unknown attribute
Fix repr calling unknown attribute
Python
mit
Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot
--- +++ @@ -11,4 +11,4 @@ token = Column(String(128), unique=True, nullable=False) def __repr__(self): - return '<Speaker %r>' % self.facebook_id + return '<Speaker %r>' % self.id
198a941c8c71802b72c33f5ef89d1d4d46e52eac
scripts/fetch_all_urls_to_disk.py
scripts/fetch_all_urls_to_disk.py
import urllib import os import hashlib with open('media_urls.txt','r') as f: for url in f: imagename = os.path.basename(url) m = hashlib.md5(url).hexdigest() if '.jpg' in url: shortname = m + '.jpg' elif '.png' in url: shortname = m + '.png' else: print ...
import urllib import os import hashlib with open('media_urls.txt','r') as f: for url in f: imagename = os.path.basename(url) m = hashlib.md5(url).hexdigest() if '.jpg' in url: shortname = m + '.jpg' elif '.png' in url: shortname = m + '.png' else: print ...
Add continue when no extension ".jpg" nor ".png" is found in URL
Add continue when no extension ".jpg" nor ".png" is found in URL
Python
mit
mixbe/kerstkaart2013,mixbe/kerstkaart2013
--- +++ @@ -14,6 +14,7 @@ shortname = m + '.png' else: print 'no jpg nor png' + continue print shortname with open(shortname, 'wb') as imgfile:
1c1c7dd151b3b7894fff74b31c15bded4ac4dc96
lintrain/solvers/ridgeregression.py
lintrain/solvers/ridgeregression.py
from solver import Solver import numpy as np class RidgeRegression(Solver): """ Analytically performs ridge regression, where coefficients are regularized by learning rate alpha. This constrains coefficients and can be effective in situations where over- or under-fitting arise. Based off of: https...
from solver import Solver import numpy as np class RidgeRegression(Solver): """ Analytically performs ridge regression, where coefficients are regularized by learning rate alpha. This constrains coefficients and can be effective in situations where over- or under-fitting arise. Parameters `alpha` is t...
Allow setting ridge regression parameters during creation
Allow setting ridge regression parameters during creation
Python
mit
nathanntg/lin-train,nathanntg/lin-train
--- +++ @@ -5,16 +5,21 @@ class RidgeRegression(Solver): """ Analytically performs ridge regression, where coefficients are regularized by learning rate alpha. This constrains - coefficients and can be effective in situations where over- or under-fitting arise. + coefficients and can be effective in ...
f8b4f4a2c5a7f529816f78344509a3536a0f3254
datapipe/targets/filesystem.py
datapipe/targets/filesystem.py
import os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 de...
import os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 de...
Fix another situation where targets didn't get rebuilt
Fix another situation where targets didn't get rebuilt
Python
mit
ibab/datapipe
--- +++ @@ -34,5 +34,8 @@ if mem is None or not 'timestamp' in mem: return True + if not self.exists(): + return True + return self._memory['timestamp'] > mem['timestamp']
7bb93bfdf2b75ba8df0983d058854a1d00d75c16
geotrek/feedback/tests/test_commands.py
geotrek/feedback/tests/test_commands.py
from io import StringIO from django.core.management import call_command from django.test import TestCase from django.utils import timezone from geotrek.feedback.models import Report from geotrek.feedback.factories import ReportFactory class TestRemoveEmailsOlders(TestCase): """Test command erase_emails, if olde...
from io import StringIO from django.core.management import call_command from django.test import TestCase from django.utils import timezone from geotrek.feedback.models import Report from geotrek.feedback.factories import ReportFactory class TestRemoveEmailsOlders(TestCase): """Test command erase_emails, if olde...
Test dry run mode in erase_mail
Test dry run mode in erase_mail
Python
bsd-2-clause
makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin
--- +++ @@ -13,8 +13,8 @@ def setUp(self): # Create two reports - self.old_report = ReportFactory() - self.recent_report = ReportFactory() + self.old_report = ReportFactory(email="to_erase@you.com") + self.recent_report = ReportFactory(email="yeah@you.com") # Mod...
924766a6b56aba3a462600a70e5f4b7b322c677e
test/test_utils.py
test/test_utils.py
from piper.utils import DotDict from piper.utils import dynamic_load import pytest class TestDotDict(object): def test_get_nonexistant_raises_keyerror(self): with pytest.raises(KeyError): dd = DotDict({}) dd.does_not_exist def test_get_item(self): dd = DotDict({'dange...
from piper.utils import DotDict from piper.utils import dynamic_load import pytest class TestDotDict(object): def test_get_nonexistant_raises_keyerror(self): with pytest.raises(KeyError): dd = DotDict({}) dd.does_not_exist def test_get_item(self): dd = DotDict({'dange...
Add extra DotDict subscriptability test
Add extra DotDict subscriptability test
Python
mit
thiderman/piper
--- +++ @@ -22,6 +22,10 @@ dd = DotDict({'highway': {'danger': 'zone'}}) assert isinstance(dd.highway, DotDict) is True + def test_dict_items_become_dotdicts_when_using_dict_access(self): + dd = DotDict({'highway': {'danger': 'zone'}}) + assert isinstance(dd['highway'], DotDict) i...
0515f71d861529262aada1ad416c626277e11d9e
django_excel_to_model/forms.py
django_excel_to_model/forms.py
from django.utils.translation import ugettext_lazy as _ from django import forms from models import ExcelImportTask from django.forms import ModelForm class ExcelFormatTranslateForm(forms.Form): # title = forms.CharField(max_length=50) import_file = forms.FileField( label=_('File to import') ) ...
from django.contrib.contenttypes.models import ContentType from django.utils.translation import ugettext_lazy as _ from django import forms from models import ExcelImportTask from django.forms import ModelForm class ExcelFormatTranslateForm(forms.Form): # title = forms.CharField(max_length=50) import_file = f...
Sort content for data import.
Sort content for data import.
Python
bsd-3-clause
weijia/django-excel-to-model,weijia/django-excel-to-model
--- +++ @@ -1,3 +1,4 @@ +from django.contrib.contenttypes.models import ContentType from django.utils.translation import ugettext_lazy as _ from django import forms from models import ExcelImportTask @@ -16,8 +17,10 @@ class ExcelImportTaskForm(ModelForm): + content = forms.ModelChoiceField(queryset=Conten...
ef9d7cbbd79078e494faed730318a18f995f3a78
cla_public/libs/zendesk.py
cla_public/libs/zendesk.py
# -*- coding: utf-8 -*- "Zendesk" import json import requests from flask import current_app TICKETS_URL = 'https://ministryofjustice.zendesk.com/api/v2/tickets.json' def create_ticket(payload): "Create a new Zendesk ticket" return requests.post( TICKETS_URL, data=json.dumps(payload), ...
# -*- coding: utf-8 -*- "Zendesk" import json import requests from flask import current_app TICKETS_URL = 'https://ministryofjustice.zendesk.com/api/v2/tickets.json' def zendesk_auth(): return ( '{username}/token'.format( username=current_app.config['ZENDESK_API_USERNAME']), current...
Refactor Zendesk client code for smoketest
Refactor Zendesk client code for smoketest
Python
mit
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
--- +++ @@ -9,14 +9,27 @@ TICKETS_URL = 'https://ministryofjustice.zendesk.com/api/v2/tickets.json' +def zendesk_auth(): + return ( + '{username}/token'.format( + username=current_app.config['ZENDESK_API_USERNAME']), + current_app.config['ZENDESK_API_TOKEN'] + ) + + def create_tic...
0722b517f5b5b9a84b7521b6b7d350cbc6537948
src/core/models.py
src/core/models.py
from django.db import models class BigForeignKey(models.ForeignKey): def db_type(self, connection): """ Adds support for foreign keys to big integers as primary keys. """ presumed_type = super().db_type(connection) if presumed_type == 'integer': return 'bigint' ...
from django.apps import apps from django.db import models class BigForeignKey(models.ForeignKey): def db_type(self, connection): """ Adds support for foreign keys to big integers as primary keys. Django's AutoField is actually an IntegerField (SQL integer field), but in some cases we are ...
Add some explaination on BigForeignKey
Add some explaination on BigForeignKey
Python
mit
uranusjr/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016
--- +++ @@ -1,11 +1,19 @@ +from django.apps import apps from django.db import models class BigForeignKey(models.ForeignKey): def db_type(self, connection): """ Adds support for foreign keys to big integers as primary keys. + + Django's AutoField is actually an IntegerField (SQL integer fiel...
e6fcb5122b7132e03257ac5c883f5e44ccdd1ef5
quokka/ext/before_request.py
quokka/ext/before_request.py
# coding: utf-8 def configure(app): @app.before_first_request def initialize(): print "Called only once, when the first request comes in"
# coding: utf-8 from quokka.core.models import Channel def configure(app): @app.before_first_request def initialize(): print "Called only once, when the first request comes in" if not Channel.objects.count(): # Create homepage if it does not exists Channel.objects.crea...
Create channel homepage if not exists in before request
Create channel homepage if not exists in before request
Python
mit
fdumpling/quokka,lnick/quokka,CoolCloud/quokka,Ckai1991/quokka,felipevolpone/quokka,romulocollopy/quokka,cbeloni/quokka,ChengChiongWah/quokka,cbeloni/quokka,CoolCloud/quokka,romulocollopy/quokka,fdumpling/quokka,fdumpling/quokka,maurobaraldi/quokka,maurobaraldi/quokka,Ckai1991/quokka,lnick/quokka,ChengChiongWah/quokka,...
--- +++ @@ -1,7 +1,23 @@ # coding: utf-8 + +from quokka.core.models import Channel def configure(app): @app.before_first_request def initialize(): print "Called only once, when the first request comes in" + if not Channel.objects.count(): + # Create homepage if it does not e...
2eb9220ee2043c2355682cab9094c8cd201bc2f7
yolk/__init__.py
yolk/__init__.py
""" __init__.py Author: Rob Cakebread <cakebread at gmail> License : BSD """ __docformat__ = 'restructuredtext' __version__ = '0.5'
""" __init__.py Author: Rob Cakebread <cakebread at gmail> License : BSD """ __docformat__ = 'restructuredtext' __version__ = '0.5.1'
Increment patch version to 0.5.1
Increment patch version to 0.5.1
Python
bsd-3-clause
myint/yolk,myint/yolk
--- +++ @@ -10,4 +10,4 @@ """ __docformat__ = 'restructuredtext' -__version__ = '0.5' +__version__ = '0.5.1'
266968b5f5188c526506782a47ea03aa3d32bf7a
kb/core.py
kb/core.py
import abc from collections import namedtuple Key = namedtuple('Key', ['x', 'y']) class Keyboard(metaclass=abc.ABCMeta): def __init__(self): pass @abc.abstractproperty def keys(self): """ Return the keys of this keyboard. :returns: An iterable of keys """ pass ...
import abc from collections import namedtuple Key = namedtuple('Key', ['y', 'x']) class Keyboard(metaclass=abc.ABCMeta): def __init__(self): pass @abc.abstractproperty def keys(self): """ Return the keys of this keyboard. :returns: An iterable of keys """ pass ...
Swap order of Key x and y to make Keys sortable
Swap order of Key x and y to make Keys sortable
Python
mit
Cyanogenoid/kb-project
--- +++ @@ -2,7 +2,7 @@ from collections import namedtuple -Key = namedtuple('Key', ['x', 'y']) +Key = namedtuple('Key', ['y', 'x']) class Keyboard(metaclass=abc.ABCMeta):
cf626539192ff60a0c2ffd06c61fb35f2d8861a1
tests/test_data.py
tests/test_data.py
from unittest import TestCase from chatterbot_corpus import corpus class CorpusUtilsTestCase(TestCase): """ This test case is designed to make sure that all corpus data adheres to a few general rules. """ def test_character_count(self): """ Test that no line in the corpus exceeds ...
from unittest import TestCase from chatterbot_corpus import corpus class CorpusUtilsTestCase(TestCase): """ This test case is designed to make sure that all corpus data adheres to a few general rules. """ def test_character_count(self): """ Test that no line in the corpus exceeds ...
Add test for data type validation
Add test for data type validation
Python
bsd-3-clause
gunthercox/chatterbot-corpus
--- +++ @@ -22,8 +22,20 @@ for statement in conversation: if len(statement) > DIALOG_MAXIMUM_CHARACTER_LENGTH: self.fail( - u'"{}" cannot be longer than {} characters'.format( + '"{}" cannot be longer ...
876ff2e147aaa751d2ab2f5423b30fcfcc02fba9
tests/test_main.py
tests/test_main.py
import os import sys import pytest from hypothesis_auto import auto_pytest_magic from isort import main auto_pytest_magic(main.sort_imports) def test_is_python_file(): assert main.is_python_file("file.py") assert main.is_python_file("file.pyi") assert main.is_python_file("file.pyx") assert not main...
import os import sys import pytest from hypothesis_auto import auto_pytest_magic from isort import main from isort.settings import DEFAULT_CONFIG auto_pytest_magic(main.sort_imports) def test_iter_source_code(tmpdir): tmp_file = tmpdir.join("file.py") tmp_file.write("import os, sys\n") assert tuple(mai...
Add test case for iter_source_code
Add test case for iter_source_code
Python
mit
PyCQA/isort,PyCQA/isort
--- +++ @@ -5,8 +5,15 @@ from hypothesis_auto import auto_pytest_magic from isort import main +from isort.settings import DEFAULT_CONFIG auto_pytest_magic(main.sort_imports) + + +def test_iter_source_code(tmpdir): + tmp_file = tmpdir.join("file.py") + tmp_file.write("import os, sys\n") + assert tuple(...
de97d95d7746cbbf6c2c53a660553ce56d294288
tests/test_unit.py
tests/test_unit.py
# -*- coding: utf-8 -*- """ tests.test_unit ~~~~~~~~~~~~~~~ Module dedicated to testing the unit utility functions. :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import (division, unicode_literals, print_function,...
# -*- coding: utf-8 -*- """ tests.test_unit ~~~~~~~~~~~~~~~ Module dedicated to testing the unit utility functions. :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import (division, unicode_literals, print_function,...
Add missing test for to_float applied on a float (when pint is present).
Add missing test for to_float applied on a float (when pint is present).
Python
bsd-3-clause
MatthieuDartiailh/lantz_core
--- +++ @@ -51,4 +51,5 @@ """ val = 1.0 + assert to_float(val) == val assert to_float(to_quantity(val, 'A')) == val
7158d44eaf764b8140675bbe7b8e2bea857edd25
coinotomy/main.py
coinotomy/main.py
import logging import os from threading import Thread from coinotomy.config.config import STORAGE_CLASS, STORAGE_DIRECTORY, WATCHERS log = logging.getLogger("main") logging.basicConfig(filename=os.path.join(STORAGE_DIRECTORY, 'log.txt'), filemode='a', datefmt='%H:%M:%S', ...
#!/usr/bin/env python3 import logging import os from threading import Thread from coinotomy.config.config import STORAGE_CLASS, STORAGE_DIRECTORY, WATCHERS log = logging.getLogger("main") logging.basicConfig(filename=os.path.join(STORAGE_DIRECTORY, 'log.txt'), filemode='a', ...
Add shebang for the linux folks out there.
Add shebang for the linux folks out there.
Python
mit
sDessens/coinotomy
--- +++ @@ -1,3 +1,5 @@ +#!/usr/bin/env python3 + import logging import os
b8f604e11270b889bafc38709814df4e1bb961dd
dthm4kaiako/config/__init__.py
dthm4kaiako/config/__init__.py
"""Configuration for Django system.""" __version__ = "0.16.3" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
"""Configuration for Django system.""" __version__ = "0.16.4" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
Increment version number to 0.16.4
Increment version number to 0.16.4
Python
mit
uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers
--- +++ @@ -1,6 +1,6 @@ """Configuration for Django system.""" -__version__ = "0.16.3" +__version__ = "0.16.4" __version_info__ = tuple( [ int(num) if num.isdigit() else num
db7d56453e09981c3a3d57deb9ad3460ac086857
apps/api/rfid/user.py
apps/api/rfid/user.py
# -*- coding: utf-8 -*- import logging from django.core.exceptions import PermissionDenied from tastypie.resources import ModelResource, ALL from tastypie.authorization import Authorization from apps.authentication.models import OnlineUser as User from apps.api.rfid.auth import RfidAuthentication class UserResourc...
# -*- coding: utf-8 -*- import logging from django.core.exceptions import PermissionDenied from tastypie.resources import ModelResource, ALL from tastypie.authorization import Authorization from apps.authentication.models import OnlineUser as User from apps.api.rfid.auth import RfidAuthentication class UserResourc...
Comment out logger until resolved properly
Comment out logger until resolved properly
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
--- +++ @@ -35,6 +35,6 @@ 'Kun oppdatering av %s er tillatt.' % ', '.join(self._meta.allowed_update_fields) ) - logging.getLogger(__name__).debug('User patched: %s' % repr(original_bundle)) + # logging.getLogger(__name__).debug('User patched: %s' % unicode(original_bundle...
f8aa722b9b56ca543f73a40f22fd682a1c71fb4c
clowder_server/management/commands/send_alerts.py
clowder_server/management/commands/send_alerts.py
import datetime from django.core.management.base import BaseCommand, CommandError from clowder_server.emailer import send_alert from clowder_server.models import Alert class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **options): alerts = Alert.objects.filter(notif...
import datetime from django.core.management.base import BaseCommand, CommandError from clowder_account.models import ClowderUser from clowder_server.emailer import send_alert from clowder_server.models import Alert, Ping class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **...
Delete old unused pings from users
Delete old unused pings from users
Python
agpl-3.0
keithhackbarth/clowder_server,keithhackbarth/clowder_server,keithhackbarth/clowder_server,framewr/clowder_server,framewr/clowder_server,keithhackbarth/clowder_server,framewr/clowder_server,framewr/clowder_server
--- +++ @@ -2,13 +2,22 @@ from django.core.management.base import BaseCommand, CommandError +from clowder_account.models import ClowderUser from clowder_server.emailer import send_alert -from clowder_server.models import Alert +from clowder_server.models import Alert, Ping class Command(BaseCommand): he...
10d09367111d610e82344e9616aab98815bf9397
capture_chessboard.py
capture_chessboard.py
#! /usr/bin/env python # -*- coding:utf-8 -*- # # Capture calibration chessboard # # External dependencies import time import cv2 import Calibration # Calibration pattern size pattern_size = ( 9, 6 ) # Get the camera camera = cv2.VideoCapture( 1 ) # Acquisition loop while( True ) : # Capture image-by-image _...
#! /usr/bin/env python # -*- coding:utf-8 -*- # # Capture calibration chessboard # # External dependencies import time import cv2 import numpy as np import Calibration # Calibration pattern size pattern_size = ( 9, 6 ) # Get the camera camera = cv2.VideoCapture( 0 ) # Acquisition loop while( True ) : # Capture i...
Change camera index, and fix the chessboard preview.
Change camera index, and fix the chessboard preview.
Python
mit
microy/RobotVision,microy/RobotVision
--- +++ @@ -8,18 +8,21 @@ # External dependencies import time import cv2 +import numpy as np import Calibration # Calibration pattern size pattern_size = ( 9, 6 ) # Get the camera -camera = cv2.VideoCapture( 1 ) +camera = cv2.VideoCapture( 0 ) # Acquisition loop while( True ) : # Capture image-by-imag...
e7825da0f8467717aac9857bbc046d946aa2ce66
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '56984fa0e4c3c745652510f342c0fb2724d846c2' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', ...
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '2dfdf169b582e3f051e1fec3dd7df2bc179e1aa6' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', ...
Upgrade libchromiumcontent to discard iframe security settings
Upgrade libchromiumcontent to discard iframe security settings
Python
mit
astoilkov/electron,tylergibson/electron,yalexx/electron,bruce/electron,stevekinney/electron,kikong/electron,beni55/electron,nagyistoce/electron-atom-shell,GoooIce/electron,xiruibing/electron,timruffles/electron,thomsonreuters/electron,thomsonreuters/electron,gabrielPeart/electron,stevemao/electron,baiwyc119/electron,jc...
--- +++ @@ -4,7 +4,7 @@ import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = '56984fa0e4c3c745652510f342c0fb2724d846c2' +LIBCHROMIUMCONTENT_COMMIT = '2dfdf169b582e3f051e1fec3dd7df2bc179e1aa6' ARCH = { 'cygwin': '32bit',
6ad448568acc130118d382b29a2ea1930f738a3f
tohu/derived_generators_NEW.py
tohu/derived_generators_NEW.py
import logging from operator import attrgetter from .base_NEW import TohuUltraBaseGenerator __all__ = ['ExtractAttribute'] logger = logging.getLogger('tohu') class ExtractAttribute(TohuUltraBaseGenerator): """ Generator which produces items that are attributes extracted from the items produced by a diff...
import logging from operator import attrgetter from .base_NEW import TohuUltraBaseGenerator __all__ = ['ExtractAttribute'] logger = logging.getLogger('tohu') class ExtractAttribute(TohuUltraBaseGenerator): """ Generator which produces items that are attributes extracted from the items produced by a diff...
Add reset methods to ExtractAttribute
Add reset methods to ExtractAttribute
Python
mit
maxalbert/tohu
--- +++ @@ -29,3 +29,10 @@ def __next__(self): return self.attrgetter(next(self.gen)) + + def reset(self, seed): + logger.debug(f"Ignoring explicit reset() on derived generator: {self}") + + def reset_clone(self, seed): + logger.warning("TODO: rename method reset_clone() to reset_d...
21f152589550c1c168a856798690b9cf957653db
akanda/horizon/routers/views.py
akanda/horizon/routers/views.py
from django.utils.translation import ugettext_lazy as _ # noqa from horizon import exceptions from openstack_dashboard import api def get_interfaces_data(self): try: router_id = self.kwargs['router_id'] router = api.quantum.router_get(self.request, router_id) # Note(rods): Right now we a...
from django.utils.translation import ugettext_lazy as _ # noqa from horizon import exceptions from openstack_dashboard import api def get_interfaces_data(self): try: router_id = self.kwargs['router_id'] router = api.quantum.router_get(self.request, router_id) # Note(rods): Filter off the...
Modify the interfaces listing view to filter only the port on the mgt network
Modify the interfaces listing view to filter only the port on the mgt network DHC-1512 Change-Id: If7e5aebf7cfd7e87df0dea8cd749764c142f1676 Signed-off-by: Rosario Di Somma <73b2fe5f91895aea2b4d0e8942a5edf9f18fa897@dreamhost.com>
Python
apache-2.0
dreamhost/akanda-horizon,dreamhost/akanda-horizon
--- +++ @@ -8,13 +8,9 @@ try: router_id = self.kwargs['router_id'] router = api.quantum.router_get(self.request, router_id) - # Note(rods): Right now we are listing, for both normal and - # admin users, all the ports on the user's networks - # the ro...
c1e17f9501fb9afc69f9fba288fa9e4cfac262e2
tviit/models.py
tviit/models.py
from __future__ import unicode_literals from django.conf import settings import uuid from django.db import models class Tviit(models.Model): uuid = models.CharField(unique=True, max_length=40, default=uuid.uuid4().int, editable=False) sender = models.ForeignKey( settings.AUTH_USER_MODEL, on_d...
from __future__ import unicode_literals from django.conf import settings from django.db import models from django.utils.deconstruct import deconstructible from django.dispatch import receiver from django.forms import ModelForm import uuid, os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @dec...
Add image into Tviit Model Add PathAndRename function to rename image path Add TviitForm
Add image into Tviit Model Add PathAndRename function to rename image path Add TviitForm
Python
mit
DeWaster/Tviserrys,DeWaster/Tviserrys
--- +++ @@ -1,11 +1,31 @@ from __future__ import unicode_literals from django.conf import settings -import uuid +from django.db import models +from django.utils.deconstruct import deconstructible +from django.dispatch import receiver +from django.forms import ModelForm +import uuid, os + +BASE_DIR = os.path.dirname...
030a786db1c0602125bfe4093c6a5709b0202858
app/hooks/views.py
app/hooks/views.py
from __future__ import absolute_import from __future__ import unicode_literals from app import app, webhooks @webhooks.hook(app.config.get('GITLAB_HOOK'), handler='gitlab') class Gitlab: def issue(self, data): pass def push(self, data): pass def tag_push(self, data): pass de...
from __future__ import absolute_import from __future__ import unicode_literals from app import app, webhooks @webhooks.hook( app.config.get('GITLAB_HOOK','/hooks/gitlab'), handler='gitlab') class Gitlab: def issue(self, data): pass def push(self, data): pass def tag_push(self, da...
Add default hook url for gitlab
Add default hook url for gitlab
Python
apache-2.0
pipex/gitbot,pipex/gitbot,pipex/gitbot
--- +++ @@ -3,7 +3,9 @@ from app import app, webhooks -@webhooks.hook(app.config.get('GITLAB_HOOK'), handler='gitlab') +@webhooks.hook( + app.config.get('GITLAB_HOOK','/hooks/gitlab'), + handler='gitlab') class Gitlab: def issue(self, data): pass
99580712595402cc84db3eed37e913b18cae1703
examples/marginal_ticks.py
examples/marginal_ticks.py
""" Scatterplot with marginal ticks =============================== _thumb: .68, .32 """ import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set(style="white", color_codes=True) # Generate a random bivariate dataset rs = np.random.RandomState(9) mean = [0, 0] cov = [(1, 0), (0, 2)] x, y = rs....
""" Scatterplot with marginal ticks =============================== _thumb: .62, .39 """ import numpy as np import seaborn as sns sns.set(style="white", color_codes=True) # Generate a random bivariate dataset rs = np.random.RandomState(9) mean = [0, 0] cov = [(1, 0), (0, 2)] x, y = rs.multivariate_normal(mean, cov, 1...
Fix thumbnail on gallery page
Fix thumbnail on gallery page
Python
bsd-3-clause
mwaskom/seaborn,arokem/seaborn,anntzer/seaborn,mwaskom/seaborn,anntzer/seaborn,arokem/seaborn
--- +++ @@ -2,11 +2,10 @@ Scatterplot with marginal ticks =============================== -_thumb: .68, .32 +_thumb: .62, .39 """ import numpy as np import seaborn as sns -import matplotlib.pyplot as plt sns.set(style="white", color_codes=True) # Generate a random bivariate dataset @@ -16,6 +15,6 @@ x, y ...
8d339d610b57b40534af2a8d7cdbdaec041a995a
test/TestNGrams.py
test/TestNGrams.py
import unittest import NGrams class TestNGrams(unittest.TestCase): def test_unigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 1) self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'], ...
import unittest import sys sys.path.append('../src') import NGrams class TestNGrams(unittest.TestCase): def test_unigrams(self): sentence = 'this is a random piece of text' ngram_list = NGrams.generate_ngrams(sentence, 1) self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'], ...
Add path in test to src
Add path in test to src
Python
bsd-2-clause
ambidextrousTx/RNLTK
--- +++ @@ -1,4 +1,6 @@ import unittest +import sys +sys.path.append('../src') import NGrams
0243b5d468593edda6c207aaa124e8911a824751
src/argparser.py
src/argparser.py
"""ArgumentParser with Italian translation.""" import argparse import sys def _callable(obj): return hasattr(obj, '__call__') or hasattr(obj, '__bases__') class ArgParser(argparse.ArgumentParser): def __init__(self, prog=None, usage=None, description=None,...
"""ArgumentParser with Italian translation.""" import argparse import sys def _callable(obj): return hasattr(obj, '__call__') or hasattr(obj, '__bases__') class ArgParser(argparse.ArgumentParser): def __init__(self, **kwargs): if kwargs.get('parent', None) is None: kwargs['parents'] = [...
Fix crash in python 3.8 due to a mismatch on the ArgumentParser parameter
Fix crash in python 3.8 due to a mismatch on the ArgumentParser parameter
Python
mit
claudio-unipv/pvcheck,claudio-unipv/pvcheck
--- +++ @@ -9,25 +9,11 @@ class ArgParser(argparse.ArgumentParser): - def __init__(self, - prog=None, - usage=None, - description=None, - epilog=None, - parents=None, - formatter_class=argparse.HelpFormatter, - ...
314ba088f0c2cb8e47da22a8841127a17e4e222d
openacademy/model/openacademy_course.py
openacademy/model/openacademy_course.py
from openerp import models, fields ''' This module create model of Course ''' class Course(models.Model): ''' this class model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) description = fields.Text(string='Description') re...
from openerp import api, models, fields ''' This module create model of Course ''' class Course(models.Model): ''' this class model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) description = fields.Text(string='Description') ...
Modify copy method into inherit
[REF] openacademy: Modify copy method into inherit
Python
apache-2.0
GavyMG/openacademy-proyect
--- +++ @@ -1,4 +1,4 @@ -from openerp import models, fields +from openerp import api, models, fields ''' This module create model of Course ''' @@ -17,6 +17,20 @@ session_ids = fields.One2many( 'openacademy.session', 'course_id', string="Sessions") + @api.one + def copy(self, default=None): +...