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
326ae45949c2ee4f53e9c377582313155d9d0b70
kk/models/base.py
kk/models/base.py
from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class ModifiableModel(models.Model): created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKe...
import base64 import struct from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ def generate_id(): t = time.time() * 1000000 b = base64.b32encode(struct.pack(">Q", int(t)).lstrip(b'\x00')).strip(b'=').lower() ...
Set char primary key. Generate ID.
Set char primary key. Generate ID.
Python
mit
vikoivun/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,vikoivun/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,vikoivun/kerrokantasi,stephawe/kerrokantasi
--- +++ @@ -1,16 +1,35 @@ +import base64 +import struct from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ +def generate_id(): + t = time.time() * 1000000 + b = base64.b32encode(struct.pack(">Q", int(t))...
aaf776b94416b63a0da6dfeca6ea04f6fe32d201
systemtests/test_cli.py
systemtests/test_cli.py
import os import os.path from scripttest import TestFileEnvironment def test_persists_data(): env = TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/frid...
import os import os.path import scripttest def test_persists_data(): env = scripttest.TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/fridge', 'commit')...
Fix number of skipped tests when running pytest.
Fix number of skipped tests when running pytest.
Python
mit
jgosmann/fridge,jgosmann/fridge
--- +++ @@ -1,11 +1,11 @@ import os import os.path -from scripttest import TestFileEnvironment +import scripttest def test_persists_data(): - env = TestFileEnvironment() + env = scripttest.TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../....
b21f540ca7b53aeb569f7034de41da0dc4dd7b03
__init__.py
__init__.py
from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config("./template_values.ini")
import os.path from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * _script_path = os.path.abspath(__file__) _script_path = os.path.split(_script_path)[0] config_path = os.path.join(_script_path, "template_values.ini...
Read the configuration file upon import
Read the configuration file upon import
Python
mit
bbayles/vod_metadata
--- +++ @@ -1,7 +1,12 @@ +import os.path from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * + +_script_path = os.path.abspath(__file__) +_script_path = os.path.split(_script_path)[0] +config_path = os.path.joi...
f691b8d997327a09824881810cf1edaeb53d7579
telemetry/telemetry/internal/backends/app_backend.py
telemetry/telemetry/internal/backends/app_backend.py
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, ...
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, ...
Remove custom destructor from AppBackend
[Telemetry] Remove custom destructor from AppBackend Closing the backend in the destructor is 1) Redundant since the backend is being closed from Browser.close() 2) Dangerous since it can happen at any moment due to garbage collection and cause deadlocks in tracing code (see the bug). Bug: chromium:1227504 Change-Id:...
Python
bsd-3-clause
catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult
--- +++ @@ -15,9 +15,6 @@ self._app = None self._app_type = app_type self._platform_backend = platform_backend - - def __del__(self): - self.Close() def SetApp(self, app): self._app = app
1fe88c1a619211a93297e1081133017ff2ef0370
scenario/__main__.py
scenario/__main__.py
import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: python -m foo <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ =...
import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: scenario <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__...
Update command line usage with scenario
Update command line usage with scenario
Python
mit
shlomihod/scenario,shlomihod/scenario,shlomihod/scenario
--- +++ @@ -7,7 +7,7 @@ if args is None: args = sys.argv[1:] - assert len(args) == 2, 'Usage: python -m foo <executable> <scenario>' + assert len(args) == 2, 'Usage: scenario <executable> <scenario>' executable_path = args[0] scenario_path = args[1] @@ -16,4 +16,3 @@ if __name...
c85631d77cd25de520688666a3d0e72537e482eb
acquisition_record.py
acquisition_record.py
""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the s...
""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the s...
Test of github push from Eclipse.
Test of github push from Eclipse.
Python
apache-2.0
ama-jharrison/agdc,GeoscienceAustralia/agdc,jeremyh/agdc,sixy6e/agdc,jeremyh/agdc,smr547/agdc,smr547/agdc,alex-ip/agdc,sixy6e/agdc,GeoscienceAustralia/agdc,alex-ip/agdc,ama-jharrison/agdc
--- +++ @@ -7,6 +7,8 @@ process. They are expected to be independent of the structure of any particular dataset, but will change if the database schema or tile store format changes. + +Test of github push. """ import logging
65734594816b158bdf08b93244795b5dcc8626ba
scrapy/core/downloader/handlers/__init__.py
scrapy/core/downloader/handlers/__init__.py
"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, craw...
"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, craw...
Fix minor typo in DownloaderHandlers comment
Fix minor typo in DownloaderHandlers comment
Python
bsd-3-clause
heamon7/scrapy,redapple/scrapy,Partoo/scrapy,ArturGaspar/scrapy,fpy171/scrapy,AaronTao1990/scrapy,fafaman/scrapy,agreen/scrapy,aivarsk/scrapy,Bourneer/scrapy,w495/scrapy,1yvT0s/scrapy,curita/scrapy,dhenyjarasandy/scrapy,rdowinton/scrapy,Allianzcortex/scrapy,zackslash/scrapy,ashishnerkar1/scrapy,AaronTao1990/scrapy,kmik...
--- +++ @@ -16,7 +16,7 @@ handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {})) for scheme, clspath in handlers.iteritems(): # Allow to disable a handler just like any other - # component (extension, middlware, etc). + # component (extension, middleware, e...
d6bfc8be7944bd8495a21d9db065990148e6c466
tests/template_error.py
tests/template_error.py
from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_va...
from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_va...
Fix test incompatibility with Python 3 versions
Fix test incompatibility with Python 3 versions Replaced 'print' instruction with call of a 'six' package's implementation compatible with Python 2 as well as Python 3.
Python
lgpl-2.1
elapouya/python-docx-template
--- +++ @@ -13,7 +13,7 @@ except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): - print "Context:" + six.print_("Context:") for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error....
6403229da220fddac236a8e3ccf061446c37e27c
auditlog/__openerp__.py
auditlog/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU ...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU ...
Add OCA as author of OCA addons
Add OCA as author of OCA addons In order to get visibility on https://www.odoo.com/apps the OCA board has decided to add the OCA as author of all the addons maintained as part of the association.
Python
agpl-3.0
Vauxoo/server-tools,Vauxoo/server-tools,Vauxoo/server-tools
--- +++ @@ -22,7 +22,7 @@ { 'name': "Audit Log", 'version': "1.0", - 'author': "ABF OSIELL", + 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [
33394f4081880c2718f1c017fb90588628c2bfcc
tests/test_extension.py
tests/test_extension.py
import unittest import mock from mopidy_spotify import Extension, backend as backend_lib class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[spotify]', config) self.assertIn('enabled = t...
import mock from mopidy_spotify import Extension, backend as backend_lib def test_get_default_config(): ext = Extension() config = ext.get_default_config() assert '[spotify]' in config assert 'enabled = true' in config def test_get_config_schema(): ext = Extension() schema = ext.get_conf...
Convert extension tests to pytest syntax
tests: Convert extension tests to pytest syntax
Python
apache-2.0
jodal/mopidy-spotify,kingosticks/mopidy-spotify,mopidy/mopidy-spotify
--- +++ @@ -1,35 +1,33 @@ -import unittest - import mock from mopidy_spotify import Extension, backend as backend_lib -class ExtensionTest(unittest.TestCase): +def test_get_default_config(): + ext = Extension() - def test_get_default_config(self): - ext = Extension() + config = ext.get_defau...
69d2620ee64d367331edcf0260c73034384aae8e
subprocrunner/retry.py
subprocrunner/retry.py
import time from random import uniform from typing import Callable, Optional class Retry: def __init__(self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter if self.total <=...
import time from random import uniform from typing import Callable, Optional class Retry: def __init__( self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2, quiet: bool = False ) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter...
Add quiet mode support for Retry
Add quiet mode support for Retry
Python
mit
thombashi/subprocrunner,thombashi/subprocrunner
--- +++ @@ -4,10 +4,13 @@ class Retry: - def __init__(self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2) -> None: + def __init__( + self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2, quiet: bool = False + ) -> None: self.total = total se...
d676065cb9f137c5feb18b125d0d30dfae4e0b65
Dice.py
Dice.py
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) ...
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) ...
Add get dice roll function
Add get dice roll function
Python
mit
achyutreddy24/DiceGame
--- +++ @@ -33,3 +33,5 @@ for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) + def get_dice_roll(self): + return self.dice_roll
8ea896e3290d441e6025822cc4e67b2fd86c3a8c
social_django/compat.py
social_django/compat.py
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse if django.VERSION >= (1, 10): from django.utils.deprecation import MiddlewareMixin else: MiddlewareMixin = object def get_rel_mod...
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object def get_rel_model(field):...
Remove version check in favor of import error check
Remove version check in favor of import error check
Python
bsd-3-clause
python-social-auth/social-app-django,python-social-auth/social-app-django,python-social-auth/social-app-django
--- +++ @@ -2,15 +2,16 @@ import six import django from django.db import models + try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse -if django.VERSION >= (1, 10): +try: from django.utils.deprecation import MiddlewareMixin -else: +except Impor...
342f2a948ba88d6c67c003457923b135234088a0
JSON.py
JSON.py
import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): dir_path = os.path.expanduser("~/.passman") file_path = os....
import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): global name dir_path = os.path.expanduser("~/.passman") f...
Call global name in getservicesoffline function
Call global name in getservicesoffline function
Python
mit
regexpressyourself/passman
--- +++ @@ -12,9 +12,8 @@ name = _name key = _key - - def getServicesOffline(): + global name dir_path = os.path.expanduser("~/.passman") file_path = os.path.expanduser("~/.passman/{}.json".format(name)) if not os.path.isfile(file_path) or \
a6ae05c13666b83a1f1a8707fe21972bd1f758d9
walltime.py
walltime.py
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import matplotlib.pyplot as plt import numpy as np import datetime import sys if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#...
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import time t0 = time.time() import matplotlib.pyplot as plt import numpy as np import datetime import sys t1 = time.time() print 'Importing took {} s'.format(t1-t0) if len(sys.argv) < 2: print 'USAGE: walltime filename...
Print statements added for profiling
Print statements added for profiling
Python
mit
ibackus/custom_python_packages,trquinn/custom_python_packages
--- +++ @@ -5,10 +5,16 @@ @author: ibackus """ +import time + +t0 = time.time() import matplotlib.pyplot as plt import numpy as np import datetime import sys + +t1 = time.time() +print 'Importing took {} s'.format(t1-t0) if len(sys.argv) < 2: @@ -27,4 +33,9 @@ print str(walltime_avg) ...
692a6d4480e917ff2648bac7ac4975f981e4c571
scripts/util/assignCounty.py
scripts/util/assignCounty.py
from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query("select s.id, c.name from stations s, counties c WHERE \ s.geom && c.the_geom and s.county IS NULL").dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.que...
from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query(""" select s.id, c.name from stations s, counties c, states t WHERE ST_Contains(c.the_geom, s.geom) and s.geom && c.the_geom and s.county IS NULL and s.state = t.state_abbr and t.state_fips = c.state_fips """).dictresul...
Make sure that the county is in the right state even.
Make sure that the county is in the right state even.
Python
mit
akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem
--- +++ @@ -4,8 +4,12 @@ i = iemdb.iemdb() mydb = i["mesosite"] -rs = mydb.query("select s.id, c.name from stations s, counties c WHERE \ - s.geom && c.the_geom and s.county IS NULL").dictresult() +rs = mydb.query(""" + select s.id, c.name from stations s, counties c, states t WHERE + ST_Contains(c.the_geom, ...
2dbd2d385e821cee9a8bc8414bfba71c8b4dbc06
tests/test_ehrcorral.py
tests/test_ehrcorral.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ import unittest from ehrcorral import ehrcorral class TestEhrcorral(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tear...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals import unittest from ehrcorral i...
Add test case setUp to generate fake patient info
Add test case setUp to generate fake patient info
Python
isc
nsh87/ehrcorral
--- +++ @@ -8,15 +8,25 @@ Tests for `ehrcorral` module. """ +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from __future__ import unicode_literals + import unittest from ehrcorral import ehrcorral +from faker import Faker + +fake = Faker() +fak...
4783f7047500865da06202a7d6d777801cf49c71
Box.py
Box.py
class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() def main(): N = input() box = list() for i in range(N): x = input() x = x.split('') b = Box(x[0], x[1], x[2]) ...
class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() self.plength = 0 def __lt__(self, other): return (self.length < other.length and self.width < other.width ...
Redefine function __lt__ and define a function to set link with others.
Redefine function __lt__ and define a function to set link with others.
Python
mit
hane1818/Algorithm_HW4_box_problem
--- +++ @@ -4,16 +4,34 @@ self.width = width self.height = height self.plist = list() + self.plength = 0 + + def __lt__(self, other): + return (self.length < other.length + and self.width < other.width + and self.height < other.height) + + d...
ea15b51ad444eeca3fdbc9eeb30fb8434ec3bfbd
pyscores/api_wrapper.py
pyscores/api_wrapper.py
import json import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { ...
import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-A...
Remove unused json import in api wrapper
Remove unused json import in api wrapper
Python
mit
conormag94/pyscores
--- +++ @@ -1,4 +1,3 @@ -import json import os import requests
3d48732d577514d888ba5769a27d811d55fd9979
app.py
app.py
from flask import Flask import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): current_repo = repos.get('key') remote_name = current_repo('remote_name') remote_branch = current_repo('remote_branch') local_dir = current_repo('local_dir') cmd =...
from flask import Flask from flask import request import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): repo_id = request.args.get('key') current_repo = repos.get(repo_id) remote_name = current_repo.get('remote_name') remote_branch = current_rep...
Send repo id in get param
Send repo id in get param
Python
mit
Heads-and-Hands/pullover
--- +++ @@ -1,4 +1,5 @@ from flask import Flask +from flask import request import subprocess from config import repos @@ -6,10 +7,11 @@ @app.route("/", methods=['GET']) def hello(): - current_repo = repos.get('key') - remote_name = current_repo('remote_name') - remote_branch = current_repo('remote_b...
69a294d2a7aeab592dfa08e42423d8741aeb3828
app.py
app.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('...
#!/usr/bin/env python # -*- coding: utf-8 -*- import random from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') retu...
Support IPv6 in random ip
Support IPv6 in random ip
Python
mit
lord63/pyhipku_web,lord63/pyhipku_web
--- +++ @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -from random import randint +import random from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode @@ -25,7 +25,12 @@ @app.route('/random') def random_ip(): - random_ip = '.'.join(map(str, [ran...
552ea94c9fe2a42a8041d986e929b7defcdc4a4e
bot.py
bot.py
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(i...
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(i...
Add link to foaas profile
Add link to foaas profile
Python
mit
Zauberstuhl/foaasBot
--- +++ @@ -26,7 +26,7 @@ else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" - "Check my profile description or " + "Check my [profile description](/people/448c48d02c1c013349f314dae9b624ce) or " "[fuck around with him...](/posts/0f99d95040130133bb...
2c4e93844c1b704e3435816737a6cfda624ff7b7
bot.py
bot.py
import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r'/', MainHandler), ]) if __name__...
import json import logging import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def post(self): logging.debug(json.dumps(self.request)) application = tornado.web.Application([...
Debug any incoming POST request.
Debug any incoming POST request.
Python
mit
pistonsky/pistonskybot
--- +++ @@ -1,3 +1,5 @@ +import json +import logging import tornado.httpserver import tornado.ioloop import tornado.web @@ -8,8 +10,8 @@ class MainHandler(tornado.web.RequestHandler): - def get(self): - self.write("Hello, world") + def post(self): + logging.debug(json.dumps(self.request)) ...
ea4949dab887a14a0ca8f5ffbcd3c578c61c005e
api/urls.py
api/urls.py
from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^services/$', views.services, name='api-services'), url(r'^collect/$', views.collect_response, name='api-collect'), url(r'^search/text/$', views.text_search, name='api-text-search'), url(r'^license/$', views.licensing...
from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^v1/services/$', views.services, name='api-services'), url(r'^v1/collect/$', views.collect_response, name='api-collect'), url(r'^v1/search/text/$', views.text_search, name='api-text-search'), url(r'^v1/license/$', vie...
Add API versioning at the url
Add API versioning at the url https://github.com/AudioCommons/ac-mediator/issues/13
Python
apache-2.0
AudioCommons/ac-mediator,AudioCommons/ac-mediator,AudioCommons/ac-mediator
--- +++ @@ -2,10 +2,10 @@ from api import views urlpatterns = [ - url(r'^services/$', views.services, name='api-services'), - url(r'^collect/$', views.collect_response, name='api-collect'), - url(r'^search/text/$', views.text_search, name='api-text-search'), - url(r'^license/$', views.licensing, name=...
21193559b063e85f26971d5ae6181a0bd097cda3
tests/utilities_test.py
tests/utilities_test.py
#pylint: disable=W0104,W0108 import pytest import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(cap...
#pylint: disable=W0104,W0108 import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @py...
Test vector, passes matrix and vector input.
Test vector, passes matrix and vector input.
Python
bsd-3-clause
ryanorendorff/pyop
--- +++ @@ -1,5 +1,4 @@ #pylint: disable=W0104,W0108 -import pytest import pyop import numpy as np @@ -29,3 +28,25 @@ np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 10)\n" + + +############ +# Vector # +############ +@pyop.vector +def multFirstColumn(column): + img = col...
98a6b04b83843861003862d835b3a2f6f2364506
tests/context_tests.py
tests/context_tests.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock()...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock()...
Update test to match last changes in the API
Update test to match last changes in the API
Python
mit
jstasiak/python-cg,jstasiak/python-cg
--- +++ @@ -16,16 +16,6 @@ context = cf.create() eq_(context._cgcontext, handle) - def test_opengl_states_are_set_on_context_creation(self): - handle = 'x' - bridge = Mock() - bridge.cgCreateContext.return_value = handle - - cf = ContextFactory(bridge) - context = cf.create() - - bridge.cgGLRegisterStat...
4fb1023c461498a080d371e50a5a4971924cb1bc
third_party/__init__.py
third_party/__init__.py
import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.append(os.path.dirname(__file__))
import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.insert(1, os.path.dirname(__file__))
Insert third_party into the second slot of sys.path rather than the last slot
Insert third_party into the second slot of sys.path rather than the last slot
Python
apache-2.0
somehume/namebench
--- +++ @@ -2,4 +2,4 @@ import sys # This bit of evil should inject third_party into the path for relative imports. -sys.path.append(os.path.dirname(__file__)) +sys.path.insert(1, os.path.dirname(__file__))
377beee13a8cd0ca23f8f2e37dd2816571721921
tests/sources_tests.py
tests/sources_tests.py
import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_s...
import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_s...
Add test for fetching local package sources
Add test for fetching local package sources
Python
bsd-2-clause
mwilliamson/whack
--- +++ @@ -18,6 +18,16 @@ repo_uri = "git+file://{0}".format(package_source_dir) with source_fetcher.fetch(repo_uri) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) + + +@istest +def can_fetch_package_source_from_local_path(): + with crea...
c4db09cd2d4dac37afcf75d5cf4d8c8f881aac2d
tests/test_examples.py
tests/test_examples.py
'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker #...
'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer.expressions def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marke...
Test the doc comments in the expressions module.
Test the doc comments in the expressions module.
Python
mit
jvs/sourcer
--- +++ @@ -1,6 +1,6 @@ '''Search all our doc comments for "Example" blocks and try executing them.''' import re -import sourcer +import sourcer.expressions def run_examples(package): @@ -30,4 +30,4 @@ if __name__ == '__main__': - run_examples(sourcer) + run_examples(sourcer.expressions)
aaae301f62b4e0b3cdd5d1756a03b619a8f18222
tests/test_hamilton.py
tests/test_hamilton.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def te...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def te...
Add test for invalid 'convention' in hamilton method
Add test for invalid 'convention' in hamilton method
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
--- +++ @@ -31,3 +31,13 @@ model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) + + +@pytest.mark.parametrize("convention", ["a", "1", None]) +def test_invalid_convention(get_model, convention): + """ + Test that giving an invalid 'convent...
08730308134d0a15be996e8e7bb1a19bc1930f12
tests/test_plotting.py
tests/test_plotting.py
from contextlib import contextmanager import os import tempfile import unittest from matplotlib.pyplot import Artist, savefig from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries @contextmanager def get_tempfile(): f, path = tempfile.mkstemp() try: yield path f...
import os import unittest from matplotlib.pyplot import Artist, savefig from matplotlib.testing.decorators import image_comparison from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries # If set to True, generate images rather than perform tests (all tests will pass!) GENERATE_BASELI...
Use matplotlib image_comparison to actually compare plot output
TST: Use matplotlib image_comparison to actually compare plot output
Python
bsd-3-clause
jorisvandenbossche/geopandas,jorisvandenbossche/geopandas,jdmcbr/geopandas,koldunovn/geopandas,ozak/geopandas,maxalbert/geopandas,IamJeffG/geopandas,ozak/geopandas,geopandas/geopandas,fonnesbeck/geopandas,kwinkunks/geopandas,geopandas/geopandas,geopandas/geopandas,jorisvandenbossche/geopandas,urschrei/geopandas,snario/...
--- +++ @@ -1,38 +1,32 @@ -from contextlib import contextmanager import os -import tempfile import unittest from matplotlib.pyplot import Artist, savefig +from matplotlib.testing.decorators import image_comparison from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries +# If...
331060f37841dccbd8974f01c063dc1b5c112121
formula/openssl.py
formula/openssl.py
import winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1f.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') ...
import winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1g.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') ...
Upgrade to OpenSSL 1.0.1g to avoid heartbleed bug
Upgrade to OpenSSL 1.0.1g to avoid heartbleed bug
Python
mit
mfichman/winbrew
--- +++ @@ -1,7 +1,7 @@ import winbrew class Openssl(winbrew.Formula): - url = 'http://www.openssl.org/source/openssl-1.0.1f.tar.gz' + url = 'http://www.openssl.org/source/openssl-1.0.1g.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = ()
5b8b210a73282f6176883f3fab1dd0b2801b3f34
wsgi/app.py
wsgi/app.py
# flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False if newrelic: newrelic_ini = config('NEWRELIC_PYTHON_INI_F...
# flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False else: newrelic.agent.initialize() import os from bedrock...
Remove unused ability to use custom newrelic.ini
Remove unused ability to use custom newrelic.ini
Python
mpl-2.0
flodolo/bedrock,craigcook/bedrock,hoosteeno/bedrock,sylvestre/bedrock,craigcook/bedrock,pascalchevrel/bedrock,kyoshino/bedrock,kyoshino/bedrock,sgarrity/bedrock,ericawright/bedrock,ericawright/bedrock,MichaelKohler/bedrock,mozilla/bedrock,alexgibson/bedrock,alexgibson/bedrock,hoosteeno/bedrock,ericawright/bedrock,sgarr...
--- +++ @@ -5,14 +5,9 @@ import newrelic.agent except ImportError: newrelic = False +else: + newrelic.agent.initialize() - -if newrelic: - newrelic_ini = config('NEWRELIC_PYTHON_INI_FILE', default='') - if newrelic_ini: - newrelic.agent.initialize(newrelic_ini) - else: - newreli...
0e533ad0cc42431a57758b577cf96783ee4b7484
spacy/tests/test_download.py
spacy/tests/test_download.py
# coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize(...
# coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest @pytest.mark.slow def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest...
Mark compatibility table test as slow (temporary)
Mark compatibility table test as slow (temporary) Prevent Travis from running test test until models repo is published
Python
mit
oroszgy/spaCy.hu,oroszgy/spaCy.hu,aikramer2/spaCy,spacy-io/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,raphael0202/spaCy,...
--- +++ @@ -5,6 +5,7 @@ import pytest +@pytest.mark.slow def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict
a6a4c2920abd099a97839584b96af10dcd25afe2
tests/test_public_api.py
tests/test_public_api.py
# This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStr...
# This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStr...
Add a test for get_available_markups() function
Add a test for get_available_markups() function
Python
bsd-3-clause
mitya57/pymarkups,retext-project/pymarkups
--- +++ @@ -20,5 +20,10 @@ markup = markups.get_markup_for_file_name('myfile.mkd') self.assertIsInstance(markup, markups.MarkdownMarkup) + @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') + def test_available_markups(self): + available_markups = markups.get_available_markups...
9ce5a020ac6e9bbdf7e2fc0c34c98cdfaf9e0a45
tests/formatters/conftest.py
tests/formatters/conftest.py
import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.append('description', 'Fee fie foe fum') char.append('type', 'human') return char
import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.tags('description').append('Fee fie foe fum') char.tags('type').append('human') return char
Set up defaults using tag syntax
Set up defaults using tag syntax
Python
mit
aurule/npc,aurule/npc
--- +++ @@ -4,6 +4,6 @@ @pytest.fixture(scope="module") def character(): char = npc.character.Character() - char.append('description', 'Fee fie foe fum') - char.append('type', 'human') + char.tags('description').append('Fee fie foe fum') + char.tags('type').append('human') return char
69ec55e0a6b4d314eb1381afc09236a5aa01d3d8
util/git-author-comm.py
util/git-author-comm.py
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two git repositories.' print 'python2 git-author-comm.py [path-to-git-repo] [path-to-git-repo]' def sysout(command): return os.popen(command).read() d...
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two local git repositories.' print 'python2 git-author-comm.py [path-to-local-git-repo] [path-to-local-git-repo]' def sysout(command): return os.popen(...
Make it more obvious that you need to use a local repository as an argument, not a url
Make it more obvious that you need to use a local repository as an argument, not a url
Python
mit
baykovr/toolbox,baykovr/toolbox,baykovr/toolbox,baykovr/toolbox,baykovr/toolbox
--- +++ @@ -6,8 +6,8 @@ import os,sys def usage(): - print 'Show authors which appear in two git repositories.' - print 'python2 git-author-comm.py [path-to-git-repo] [path-to-git-repo]' + print 'Show authors which appear in two local git repositories.' + print 'python2 git-author-comm.py [path-to-local-git-repo]...
4669a033ee4fbde5e3c2447778657a20a73d5df8
thefuck/shells/powershell.py
thefuck/shells/powershell.py
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' { \n' \ ' $fuck = $(thefuck (Get-History -Count 1).CommandLine);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuc...
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' {\n' \ ' $history = (Get-History -Count 1).CommandLine;\n' \ ' if (-not [string]::IsNullOrWhiteSpace($history)) {\n' \ ' $fuck = $(thef...
Update PowerShell alias to handle no history
Update PowerShell alias to handle no history If history is cleared (or the shell is new and there is no history), invoking thefuck results in an error because the alias attempts to execute the usage string. The fix is to check if Get-History returns anything before invoking thefuck.
Python
mit
Clpsplug/thefuck,scorphus/thefuck,nvbn/thefuck,nvbn/thefuck,scorphus/thefuck,mlk/thefuck,Clpsplug/thefuck,mlk/thefuck,SimenB/thefuck,SimenB/thefuck
--- +++ @@ -3,11 +3,14 @@ class Powershell(Generic): def app_alias(self, fuck): - return 'function ' + fuck + ' { \n' \ - ' $fuck = $(thefuck (Get-History -Count 1).CommandLine);\n' \ - ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ - ' if ...
7654d9dcebb0ad1e862e376b5b694234173289ed
twitter_helper/util.py
twitter_helper/util.py
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline ...
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline ...
Reset pointer to the beginning of file once read it
Reset pointer to the beginning of file once read it Be polite, put things back in the place you found them
Python
mit
kuzeko/Twitter-Importer,kuzeko/Twitter-Importer
--- +++ @@ -7,6 +7,8 @@ if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline + #Be polite, put things back in the place you found them + afile.seek(0) return line def prepare_quote(text_file, signat...
8307188a5cbaf0dab824b58a6436affdea1b039b
mesonwrap/inventory.py
mesonwrap/inventory.py
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wr...
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_...
Add wrapdevtools to restricted projects
Add wrapdevtools to restricted projects
Python
apache-2.0
mesonbuild/wrapweb,mesonbuild/wrapweb,mesonbuild/wrapweb
--- +++ @@ -3,6 +3,7 @@ 'meson', 'meson-ci', 'mesonwrap', + 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [
82f2fb3c3956e4ad4c65b03b3918ea409593d4ef
gcloud/__init__.py
gcloud/__init__.py
"""GCloud API access in idiomatic Python.""" __version__ = '0.02.2'
"""GCloud API access in idiomatic Python.""" from pkg_resources import get_distribution __version__ = get_distribution('gcloud').version
Read module version from setup.py
Read module version from setup.py
Python
apache-2.0
googleapis/google-cloud-python,blowmage/gcloud-python,thesandlord/gcloud-python,calpeyser/google-cloud-python,CyrusBiotechnology/gcloud-python,waprin/gcloud-python,VitalLabs/gcloud-python,waprin/google-cloud-python,jonparrott/google-cloud-python,Fkawala/gcloud-python,tswast/google-cloud-python,waprin/gcloud-python,dher...
--- +++ @@ -1,4 +1,5 @@ """GCloud API access in idiomatic Python.""" +from pkg_resources import get_distribution -__version__ = '0.02.2' +__version__ = get_distribution('gcloud').version
2e88154eb9ea86bcf686e3cf4c92d5b696ec6efc
neo4j/__init__.py
neo4j/__init__.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li...
Add option to import neo4j for latest version
Add option to import neo4j for latest version
Python
apache-2.0
neo4j/neo4j-python-driver,neo4j/neo4j-python-driver
--- +++ @@ -20,3 +20,12 @@ from .meta import version as __version__ + +# Export current (v1) API. This should be updated to export the latest +# version of the API when a new one is added. This gives the option to +# `import neo4j.vX` for a specific version or `import neo4j` for the +# latest. +from .v1.constant...
dda54c9826b79e213432e5da1d03d171a293d42b
utils/celery_worker.py
utils/celery_worker.py
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery app = Celery('celery_worker', broker='pyamqp://guest@localhost//') @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' ...
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery RABBIT_USER = 'guest' RABBIT_HOST = 'localhost' app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST)) @app.task def ...
Move rabbit vars to globals
Move rabbit vars to globals
Python
mpl-2.0
MITRECND/multiscanner,mitre/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,awest1339/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner
--- +++ @@ -6,11 +6,15 @@ from celery import Celery -app = Celery('celery_worker', broker='pyamqp://guest@localhost//') +RABBIT_USER = 'guest' +RABBIT_HOST = 'localhost' + +app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST)) @app.task def multiscanner_celery(filelist, config...
205682120cfa77aca2b279e2ee87065e489b5e69
settings_example.py
settings_example.py
""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ # TODO: Allow separate settings for different subject matches. # Email formats and CSV names ...
""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ import logging import os import re import yaml from imap import EmailCheckError, EmailServe...
Remove TODO from settings example.
Remove TODO from settings example. This work has been started with the Yaml settings file.
Python
mit
AustralianAntarcticDataCentre/save_emails_to_files,AustralianAntarcticDataCentre/save_emails_to_files
--- +++ @@ -6,10 +6,6 @@ That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ - -# TODO: Allow separate settings for different subject matches. -# Email formats and CSV names may change over the years, and this could -# be detected by subject ...
df3ab8bcae326ceb157106d076eaa90f13717107
astroquery/astrometry_net/tests/setup_package.py
astroquery/astrometry_net/tests/setup_package.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_ne...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] + [os.path.join('data', '*.fit.gz')] # finally construct and return a dict for the sub module ...
Include gzipped fits files in test data
Include gzipped fits files in test data
Python
bsd-3-clause
imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery,imbasimba/astroquery
--- +++ @@ -5,6 +5,6 @@ def get_package_data(): - paths = [os.path.join('data', '*.fit')] + paths = [os.path.join('data', '*.fit')] + [os.path.join('data', '*.fit.gz')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_net.tests': paths}
cee291799e9aa19e23593b3618a45f7cee16d0ed
modules/cah/CAHGame.py
modules/cah/CAHGame.py
#Cards Against Humanity game engine class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active pl...
#Cards Against Humanity game engine from cards import Deck, NoMoreCards class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False ...
Use the new Deck class
Use the new Deck class
Python
mit
tcoppi/scrappy,tcoppi/scrappy,johnmiked15/scrappy,johnmiked15/scrappy
--- +++ @@ -1,4 +1,6 @@ #Cards Against Humanity game engine + +from cards import Deck, NoMoreCards class CAHGame: def __init__(self): @@ -13,33 +15,14 @@ #dummy with a small deck for testing. #replace with actual card loading from DB later - ...
962fd486afe25031d5fb6332f623e970b694b321
tsstats/tests/test_config.py
tsstats/tests/test_config.py
import pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('...
import pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('...
Test reading config from disk again
Test reading config from disk again
Python
mit
Thor77/TeamspeakStats,Thor77/TeamspeakStats
--- +++ @@ -18,3 +18,12 @@ assert config.get('General', 'log') == 'tsstats/tests/res/test.log' config.set('General', 'output', 'output.html') assert config.get('General', 'output') == 'output.html' + + +def test_read(): + config = load(path='tsstats/tests/res/config.ini') + # test defaults + a...
a2f4b30cab3dafe119e42181772f4d77b575ec0e
05/test_find_password.py
05/test_find_password.py
import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30'
import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' assert find_password('abc', length=8, complex=True) == '05ace8e3'
Add test for part 2 of day 5.
Add test for part 2 of day 5.
Python
mit
machinelearningdeveloper/aoc_2016
--- +++ @@ -6,3 +6,4 @@ class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' + assert find_password('abc', length=8, complex=True) == '05ace8e3'
6943bb0c665cd40e7516b7277fe55af95b814ccb
playa/conf.py
playa/conf.py
""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = ['/Volumes/Storage/Music/iTunes/iTunes Me...
""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = [] WEB_HOST = '0.0.0.0' WEB_PORT...
Remove my awesome default audio path
Remove my awesome default audio path
Python
apache-2.0
disqus/playa,disqus/playa
--- +++ @@ -13,7 +13,7 @@ SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') - AUDIO_PATHS = ['/Volumes/Storage/Music/iTunes/iTunes Media/Music/Blink-182/'] + AUDIO_PATHS = [] WEB_HOST = '0.0.0.0' WEB_PORT = 9000
e64101e31fadaf54f8c1d7a6acb9b302060efefc
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'c01b10faf0d478e48f537210ec263fabd551578d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }...
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'e0213676879061470efe50720368bce9b99aaa12' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }...
Upgrade libchromiumcontent to use the static_library build
Upgrade libchromiumcontent to use the static_library build
Python
mit
wan-qy/electron,deed02392/electron,John-Lin/electron,aliib/electron,nicobot/electron,Andrey-Pavlov/electron,leethomas/electron,Jonekee/electron,simongregory/electron,leolujuyi/electron,michaelchiche/electron,greyhwndz/electron,sircharleswatson/electron,jacksondc/electron,jsutcodes/electron,bpasero/electron,tylergibson/...
--- +++ @@ -4,7 +4,7 @@ import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = 'c01b10faf0d478e48f537210ec263fabd551578d' +LIBCHROMIUMCONTENT_COMMIT = 'e0213676879061470efe50720368bce9b99aaa12' ARCH = { 'cygwin': '32bit',
d5a578e6b72fae3c92827895055ed32baf8aa806
coney/response_codes.py
coney/response_codes.py
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 1 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 2 CALL_REPLY_TIMEOUT...
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START MALFORMED_REQUEST = RESERVED_CODE_START + 1 REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 2 REMOTE_UNHANDLED_EXCEPTION ...
Add additional codes used by server implementation
Add additional codes used by server implementation
Python
mit
cbigler/jackrabbit
--- +++ @@ -8,17 +8,26 @@ RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START - REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 1 - REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 2 - CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 3 + MALFORMED_REQUEST = RESERVED_CODE_STA...
adc3fa70c32bce764a6b6a7efd7a39c349d3a685
quick_sort.py
quick_sort.py
"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, l...
"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, l...
Update index error in _sort method
Update index error in _sort method
Python
mit
jonathanstallings/data-structures
--- +++ @@ -20,8 +20,8 @@ while True: while left <= right and un_list[left] <= pivot: left += 1 - while right >= left and un_list[right] >= pivot: - right += 1 + while un_list[right] >= pivot and right >= left: + right -= 1 if right < left: ...
fc7aac4f68c4b694162ed146b8b5ab2b4401895c
test/features/test_create_pages.py
test/features/test_create_pages.py
import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): ...
import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): ...
Test for page existing on master branch
Test for page existing on master branch
Python
mit
alphagov/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer
--- +++ @@ -18,6 +18,6 @@ def test_about_page(self): with Browser() as browser: - browser.visit("http://0.0.0.0:8000/aboutData") - assert_that(browser.is_text_present('About the transactions data'), + browser.visit("http://0.0.0.0:8000/high-volume-services/by-transacti...
209fef39f72a625e154f4455eaa6754d6a85e98b
zeus/utils/revisions.py
zeus/utils/revisions.py
from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committe...
from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committe...
Fix invalid next() call on api result
Fix invalid next() call on api result
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
--- +++ @@ -35,7 +35,11 @@ if not with_vcs: raise UnknownRevision - result = next(vcs_client.log(repository.id, parent=ref, limit=1)) + try: + result = vcs_client.log(repository.id, parent=ref, limit=1)[0] + except IndexError: + raise UnknownRevision + revision = Revision.q...
4ab14b3de299b58aee94511910d199cd1d1737a5
zou/app/utils/emails.py
zou/app/utils/emails.py
from flask_mail import Message from zou.app import mail def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body message = Message( body=body, html=html, subject=su...
from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( body=bo...
Fix email sending in production environment
Fix email sending in production environment
Python
agpl-3.0
cgwire/zou
--- +++ @@ -1,6 +1,6 @@ from flask_mail import Message -from zou.app import mail +from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): @@ -9,10 +9,11 @@ """ if html is None: html = body - message = Message( - body=body, - html=html, - ...
8639f91fba318c4b8c64f7c25885f8fe95e0ebe4
robot/game.py
robot/game.py
import logging import time from enum import Enum from threading import Thread from typing import NewType import _thread from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. ...
import logging import signal from enum import Enum from typing import NewType from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def timeout_handler(signum, stack): """ Handle the `SIGALRM` to kill the current process. """ raise SystemExit("Timeout expire...
Replace thread killing with SIGALRM
Replace thread killing with SIGALRM
Python
mit
sourcebots/robot-api,sourcebots/robot-api
--- +++ @@ -1,10 +1,8 @@ import logging -import time +import signal from enum import Enum -from threading import Thread from typing import NewType -import _thread from robot.board import Board Zone = NewType('Zone', int) @@ -12,26 +10,20 @@ LOGGER = logging.getLogger(__name__) +def timeout_handler(signu...
5c88f210644cbe59cf3b3a71345a3fc64dfc542a
spiff/api/plugins.py
spiff/api/plugins.py
from django.conf import settings import importlib import inspect def find_api_classes(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in in...
from django.conf import settings import importlib import inspect def find_api_classes(*args, **kwargs): for app, cls in find_api_implementations(*args, **kwargs): yield cls def find_api_implementations(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_AP...
Add a method to also easily find what app an api object was found in
Add a method to also easily find what app an api object was found in
Python
agpl-3.0
SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff
--- +++ @@ -2,7 +2,11 @@ import importlib import inspect -def find_api_classes(module, superclass, test=lambda x: True): +def find_api_classes(*args, **kwargs): + for app, cls in find_api_implementations(*args, **kwargs): + yield cls + +def find_api_implementations(module, superclass, test=lambda x: True): ...
d36ac9a113608aadbda79c724f6aa6f6da5ec0bd
cellcounter/mixins.py
cellcounter/mixins.py
import simplejson as json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get...
import json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response...
Use json rather than simplejson
Use json rather than simplejson
Python
mit
haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,haematologic/cellcounter
--- +++ @@ -1,4 +1,4 @@ -import simplejson as json +import json from django.http import HttpResponse
85e10e4c4eaf46ed89bc4b148b9c483df79cf410
test/test_fields.py
test/test_fields.py
import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1
import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 def test_field_component_boundary_1(): fc = fds.FieldComponent(100) fc.values = np.random.rand(100) fc.boundaries ...
Add test cases for FieldComponent class.
Add test cases for FieldComponent class.
Python
bsd-3-clause
emtpb/pyfds
--- +++ @@ -6,3 +6,30 @@ dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 + + +def test_field_component_boundary_1(): + fc = fds.FieldComponent(100) + fc.values = np.random.rand(100) + fc.boundaries = [fds.Boundary(fds.LineReg...
32d23eb7764178cedcf6b648f959fbf49d7ff657
app/models.py
app/models.py
from . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.C...
from . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.C...
Modify repr of model Essay
Modify repr of model Essay
Python
apache-2.0
kigawas/essai,kigawas/essai
--- +++ @@ -12,5 +12,5 @@ coherence = db.Column(db.Text) def __repr__(self): - return '<Essay {0}>: {1}. Created at:{2}'.format(self.text, self.score, + return u'<Essay {0}>: {1}. Created at:{2}'.format(self.id, self.score, self.time)
845192bb91a2421c54a9bbb924e1e09e700aee66
Lib/dialogKit/__init__.py
Lib/dialogKit/__init__.py
""" dialogKit: easy bake dialogs """ # determine the environment try: import FL haveFL = True except ImportError: haveFL = False try: import vanilla haveVanilla = True except ImportError: haveVanilla = False # perform the environment specific import if haveFL: from _dkFL import * if haveVan...
""" dialogKit: easy bake dialogs """ # determine the environment haveFL = False haveVanilla = False try: import FL haveFL = True except ImportError: pass if not haveFL: try: import vanilla haveVanilla = True except ImportError: pass # perform the environment specific import ...
Stop trying imports after something has been successfully loaded.
Stop trying imports after something has been successfully loaded.
Python
mit
anthrotype/dialogKit,daltonmaag/dialogKit,typesupply/dialogKit
--- +++ @@ -3,20 +3,23 @@ """ # determine the environment +haveFL = False +haveVanilla = False try: import FL haveFL = True except ImportError: - haveFL = False -try: - import vanilla - haveVanilla = True -except ImportError: - haveVanilla = False + pass +if not haveFL: + try: + ...
992e0e2f50418bd87052741f7f1937f8efd052c0
tests/mpath_test.py
tests/mpath_test.py
import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = ...
import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = ...
Make the tearDown method of the mpath test case better visible
Make the tearDown method of the mpath test case better visible By moving it to the beginning of the file.
Python
lgpl-2.1
vpodzime/libblockdev,atodorov/libblockdev,vpodzime/libblockdev,vpodzime/libblockdev,snbueno/libblockdev,dashea/libblockdev,atodorov/libblockdev,snbueno/libblockdev,rhinstaller/libblockdev,atodorov/libblockdev,rhinstaller/libblockdev,dashea/libblockdev,rhinstaller/libblockdev
--- +++ @@ -14,13 +14,6 @@ raise RuntimeError("Failed to setup loop device for testing") self.loop_dev = "/dev/%s" % loop - def test_is_mpath_member(self): - """Verify that is_mpath_member works as expected""" - - # just test that some non-mpath is not reported as a multipath ...
437c8b59148ccb31ac7480ab6c9e9784e2dd6295
js2xml/__init__.py
js2xml/__init__.py
import lxml.etree from slimit.parser import Parser from js2xml.xmlvisitor import XmlVisitor _parser = Parser() _visitor = XmlVisitor() def parse(text, debug=False): tree = _parser.parse(text, debug=debug) xml = _visitor.visit(tree) return xml
Add js2xml.parse() method that wraps the slimit visitor/xml-builder
Add js2xml.parse() method that wraps the slimit visitor/xml-builder
Python
mit
redapple/js2xml,redapple/js2xml,redapple/js2xml,redapple/js2xml
--- +++ @@ -1 +1,11 @@ +import lxml.etree +from slimit.parser import Parser +from js2xml.xmlvisitor import XmlVisitor +_parser = Parser() +_visitor = XmlVisitor() + +def parse(text, debug=False): + tree = _parser.parse(text, debug=debug) + xml = _visitor.visit(tree) + return xml
290f0beb0103ee8f8d3d59bf2fabc227ed743d30
lib/smisk/mvc/model.py
lib/smisk/mvc/model.py
# encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADepr...
# encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADepr...
Set sqlalchemy option shortnames to True by default.
Set sqlalchemy option shortnames to True by default.
Python
mit
rsms/smisk,rsms/smisk,rsms/smisk
--- +++ @@ -17,3 +17,8 @@ # Disable autosetup by recommendation from Jason R. Coombs: # http://groups.google.com/group/sqlelixir/msg/ed698d986bfeefdb options_defaults['autosetup'] = False + +# Control wheretere to include module name or not in table names. +# If True, project.fruits.Apple -> table apples. +# If Fa...
80b8ef8b227baa1f4af842716ebfb83dcabf9703
tests/scoring_engine/web/views/test_auth.py
tests/scoring_engine/web/views/test_auth.py
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code...
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code...
Add test for incorrect password auth view
Add test for incorrect password auth view
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
--- +++ @@ -23,3 +23,11 @@ assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services') + + def test_wrong_password_login(self): + user = self.create_default_user() + user.username = 'RandomName' + self.session.add(u...
a23774fe4646db1bf4b25cf67d855dcc4cc4c8f7
celery/loaders/default.py
celery/loaders/default.py
from celery.loaders.base import BaseLoader DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") return not is_private class Loader(BaseLoader): ...
import os from celery.loaders.base import BaseLoader DEFAULT_CONFIG_MODULE = "celeryconfig" DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") r...
Add possibility to set celeryconfig module with ENV["CELERY_CONFIG_MODULE"] + always add celery to INSTALLED_APPS
Add possibility to set celeryconfig module with ENV["CELERY_CONFIG_MODULE"] + always add celery to INSTALLED_APPS
Python
bsd-3-clause
ask/celery,frac/celery,mitsuhiko/celery,ask/celery,cbrepo/celery,frac/celery,mitsuhiko/celery,WoLpH/celery,WoLpH/celery,cbrepo/celery
--- +++ @@ -1,4 +1,7 @@ +import os from celery.loaders.base import BaseLoader + +DEFAULT_CONFIG_MODULE = "celeryconfig" DEFAULT_SETTINGS = { "DEBUG": False, @@ -21,9 +24,12 @@ """ def read_configuration(self): - """Read configuration from ``celeryconf.py`` and configure + """Read co...
349bb1ce2c15239ae3f9c066ed774b20369b9c0d
src/ggrc/settings/app_engine.py
src/ggrc/settings/app_engine.py
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FU...
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FU...
Enable Calendar integration on App Engine deployments
Enable Calendar integration on App Engine deployments
Python
apache-2.0
NejcZupec/ggrc-core,uskudnik/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,hyperNURb/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,vladan-m/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,vladan-m/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/...
--- +++ @@ -11,3 +11,4 @@ AUTOBUILD_ASSETS = False SQLALCHEMY_RECORD_QUERIES = True MEMCACHE_MECHANISM = True +CALENDAR_MECHANISM = True
5a84249b7e96d9d2f82ee1b27a33b7978d63b16e
src/urls.py
src/urls.py
# -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. try: from django.conf.urls import patterns, include, url except ImportError: # pragma: no cover # for Django version less than 1.4 from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from dja...
# -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Show...
Remove django < 1.4 code
Remove django < 1.4 code
Python
agpl-3.0
rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud
--- +++ @@ -1,11 +1,7 @@ # -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. -try: - from django.conf.urls import patterns, include, url -except ImportError: # pragma: no cover - # for Django version less than 1.4 - from django.conf.urls.defaults import patterns, include, url +from ...
8ec8929595bd7c4d9b794fe016da64532e517a53
producers/producers.py
producers/producers.py
class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` - to run the producer - ``configure(jvm, *options)`` - to configure itself with the given jvm and options (must set configured to True if ...
class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` to run the producer, after running `out` attribute has to be set to path to produced output - ``configure(jvm, *options)`` to configure i...
Add `is_runable` to Producer base class.
Add `is_runable` to Producer base class. Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
Python
mit
fhirschmann/penchy,fhirschmann/penchy
--- +++ @@ -3,9 +3,11 @@ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - - ``_run`` - to run the producer - - ``configure(jvm, *options)`` - to configure itself with the given jvm + - ``_run`` to run the producer, after running `...
b704a92c919d7fa950a65ee0c569864c4549331f
glue/core/tests/util.py
glue/core/tests/util.py
from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Con...
from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Con...
Add workaround for failing unlink on Windows
Add workaround for failing unlink on Windows
Python
bsd-3-clause
saimn/glue,stscieisenhamer/glue,JudoWill/glue,saimn/glue,JudoWill/glue,stscieisenhamer/glue
--- +++ @@ -28,7 +28,10 @@ outfile.write(contents) yield fname finally: - os.unlink(fname) + try: + os.unlink(fname) + except WindowsError: # on Windows the unlink can fail + pass @contextmanager
17fe6d36a34218e74b53e9617212f0e67b05297d
pysteps/io/__init__.py
pysteps/io/__init__.py
from .interface import get_method from .archive import * from .importers import * from .readers import *
from .interface import get_method from .archive import * from .exporters import * from .importers import * from .readers import *
Add missing import of the exporters module
Add missing import of the exporters module
Python
bsd-3-clause
pySTEPS/pysteps
--- +++ @@ -1,4 +1,5 @@ from .interface import get_method from .archive import * +from .exporters import * from .importers import * from .readers import *
29b7a69a39ac66ebd8f61c6c9c65e7e60b40b4a0
numpy/_array_api/_types.py
numpy/_array_api/_types.py
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPac...
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPac...
Use better type definitions for the array API custom types
Use better type definitions for the array API custom types
Python
bsd-3-clause
anntzer/numpy,simongibbons/numpy,jakirkham/numpy,rgommers/numpy,pdebuyl/numpy,endolith/numpy,simongibbons/numpy,mhvk/numpy,pdebuyl/numpy,charris/numpy,rgommers/numpy,jakirkham/numpy,mattip/numpy,mhvk/numpy,mattip/numpy,rgommers/numpy,charris/numpy,numpy/numpy,simongibbons/numpy,endolith/numpy,anntzer/numpy,anntzer/nump...
--- +++ @@ -14,10 +14,13 @@ from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) -Array = ndarray -Device = TypeVar('device') -Dtype = Literal[int8, int16, int32, int64, uint8, uint16, - uint32, uint64, float32, float64] -SupportsDLPack = ...
5277d6d5caf075ce6fbb8d46c558bdc29eb62e19
docs/conf.py
docs/conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relati...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relati...
Update org URL for issue linkage
Update org URL for issue linkage
Python
mit
pytest-dev/pytest-runner
--- +++ @@ -28,7 +28,7 @@ replace=[ dict( pattern=r"(Issue )?#(?P<issue>\d+)", - url='{GH}/jaraco/{project}/issues/{issue}', + url='{GH}/pytest-dev/{project}/issues/{issue}', ), dict( pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n",
56856ac1103ec9f3ba0f2da81832a59e7e773256
doc/ext/nova_autodoc.py
doc/ext/nova_autodoc.py
import os from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0]
import gettext import os gettext.install('nova') from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0]
Fix doc building endpoint for gettext.
Fix doc building endpoint for gettext.
Python
apache-2.0
blueboxgroup/nova,BeyondTheClouds/nova,russellb/nova,Brocade-OpenSource/OpenStack-DNRM-Nova,SUSE-Cloud/nova,termie/nova-migration-demo,shahar-stratoscale/nova,rajalokan/nova,devendermishrajio/nova_test_latest,aristanetworks/arista-ovs-nova,NoBodyCam/TftpPxeBootBareMetal,virtualopensystems/nova,dims/nova,bclau/nova,good...
--- +++ @@ -1,4 +1,7 @@ +import gettext import os + +gettext.install('nova') from nova import utils
74a2e0825f3029b6d3a3164221d11fbdf551b8d1
demo/demo/widgets/live.py
demo/demo/widgets/live.py
from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <ul id="data"/> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """
from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <form onsubmit="return send_msg()"> <input name="text" id="text"/> </form> <ul id="data"/> <script> ...
Allow people to send messages in our basic HelloWorldWidget demo
Allow people to send messages in our basic HelloWorldWidget demo
Python
apache-2.0
ralphbean/moksha,ralphbean/moksha,lmacken/moksha,mokshaproject/moksha,mokshaproject/moksha,lmacken/moksha,ralphbean/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,pombredanne/moksha,lmacken/moksha
--- +++ @@ -4,7 +4,19 @@ topic = "helloworld" template = """ <b>Hello World Widget</b> + <form onsubmit="return send_msg()"> + <input name="text" id="text"/> + </form> + <ul id="data"/> + + <script> + function send_msg() { + moksha....
26581b24dd00c3b0a0928fe0b24ae129c701fb58
jarbas/frontend/tests/test_bundle_dependecies.py
jarbas/frontend/tests/test_bundle_dependecies.py
from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): files = set(get_all_bundle_files(elm)) self.assertEqual(9, len(files), files)
from glob import glob from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = set(get_all_...
Fix test for Elm files lookup
Fix test for Elm files lookup
Python
mit
datasciencebr/jarbas,rogeriochaves/jarbas,Guilhermeslucas/jarbas,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor,Guilhermeslucas/jarbas,datasciencebr/jarbas,Guilhermeslucas/jarbas,rogeriochaves/jarbas,rogeriochaves/jarbas,Guilhermeslucas/jarbas,datasciencebr/jarb...
--- +++ @@ -1,3 +1,4 @@ +from glob import glob from django.test import TestCase from webassets.bundle import get_all_bundle_files @@ -7,5 +8,6 @@ class TestDependencies(TestCase): def test_dependencies(self): + expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = se...
cd199c379145c6dcabd66f1771397c82e445c932
test_installation.py
test_installation.py
#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: ...
#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: ...
Make test script more extensive (conda, notebook, matplotlib)
Make test script more extensive (conda, notebook, matplotlib)
Python
bsd-3-clause
sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial
--- +++ @@ -35,3 +35,26 @@ except: print("sympy.utilities.autowrap.ufuncify does not work") raise + +try: + import conda +except ImportError: + print("conda is needed (either anaconda or miniconda from https://www.continuum.io/downloads)") + print("(try rerunning this script under conda if you are...
4a8170079e2b715d40e94f5d407d110a635f8a5d
InvenTree/common/apps.py
InvenTree/common/apps.py
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): """ Will be called when the Common app is first loaded """ self.add_instance_name() self.add_default_settin...
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): pass
Remove code which automatically created settings objects on server launch
Remove code which automatically created settings objects on server launch
Python
mit
inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree
--- +++ @@ -6,87 +6,4 @@ name = 'common' def ready(self): - - """ Will be called when the Common app is first loaded """ - self.add_instance_name() - self.add_default_settings() - - def add_instance_name(self): - """ - Check if an InstanceName has been defined for thi...
f9dca979768ea17cee0993dac5bac4257bda623e
settings.py
settings.py
from settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar INSTALLED_APPS += ('debug_to...
from settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar #INSTALLED_APPS += ('debug_t...
Comment out the debug tool bar
Comment out the debug tool bar
Python
agpl-3.0
sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer
--- +++ @@ -10,7 +10,7 @@ DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar -INSTALLED_APPS += ('debug_toolbar',) -MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) +#INSTALLED_APPS += ('debug_toolbar',) +#MIDDLEWARE_CLASSES += ('deb...
ec42a3cfcb491b265c87160ed9dae0005552acb4
tests/test_result.py
tests/test_result.py
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject @pytest.mark.django_db def test_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh fr...
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject, RelatableObject @pytest.mark.django_db def test_simple_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let t...
Work on testing, bulk indexing, etc
Work on testing, bulk indexing, etc
Python
mit
theonion/djes
--- +++ @@ -3,11 +3,11 @@ from model_mommy import mommy import time -from example.app.models import SimpleObject +from example.app.models import SimpleObject, RelatableObject @pytest.mark.django_db -def test_get(es_client): +def test_simple_get(es_client): management.call_command("sync_es") @@ -20,3...
517bb590edb65baedc603d8ea64a5b6f5988f076
polyaxon/polyaxon/config_settings/scheduler/__init__.py
polyaxon/polyaxon/config_settings/scheduler/__init__.py
from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from .apps import *
from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from polyaxon.config_settings.volume_claims import * from .apps import *
Add volume claims to scheduler
Add volume claims to scheduler
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
--- +++ @@ -3,4 +3,5 @@ from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * +from polyaxon.config_settings.volume_claims import * from .apps import *
39077720e2fcc340b0cc26a4720aa8d895c53263
src/txamqp/queue.py
src/txamqp/queue.py
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: ...
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: ...
Remove call to setTimeout and use callLater instead.
Remove call to setTimeout and use callLater instead.
Python
apache-2.0
williamsjj/txamqp,dotsent/txamqp,txamqp/txamqp
--- +++ @@ -17,7 +17,9 @@ self.waiting.remove(deferred) deferred.errback(Empty()) - def _raiseIfClosed(self, result): + def _raiseIfClosed(self, result, call_id): + if call_id is not None: + call_id.cancel() if result == TimeoutDeferredQueue.END: ...
7eeb990644f387741ff4c217e1eaeddbe250988f
style_grader_main.py
style_grader_main.py
#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): student_file_names = get_arguments(sys.argv[1:]) sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), ...
#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), ...
Check at least one file was provided
Check at least one file was provided
Python
mit
vianuevm/cppStyle,vianuevm/cppStyle,vianuevm/cppStyle,vianuevm/cppStyle
--- +++ @@ -3,11 +3,19 @@ #TODO: Set up standard error to print properly def main(): - student_file_names = get_arguments(sys.argv[1:]) + sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), cod...
baabb3a84418516e5a76a61b334b7879737b3d4b
goog/urls.py
goog/urls.py
from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cover third_party as an URL... url('^third_party/(?P<path>.*)$', 'serve_closure_thirdparty', ...
try: from django.conf.urls.defaults import patterns, url except ImportError: # Django >= 1.6 from django.conf.urls import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cove...
Fix imports for Django >= 1.6
Fix imports for Django >= 1.6
Python
bsd-3-clause
andialbrecht/django-goog
--- +++ @@ -1,4 +1,7 @@ -from django.conf.urls.defaults import patterns, url +try: + from django.conf.urls.defaults import patterns, url +except ImportError: # Django >= 1.6 + from django.conf.urls import patterns, url urlpatterns = patterns( 'goog.views',
ed46ee16ed1b8efcee3697d3da909f72b0755a13
webcomix/tests/test_docker.py
webcomix/tests/test_docker.py
import docker from webcomix.docker import DockerManager def test_no_javascript_spawns_no_container(): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(): manager = DockerManager(True)...
import docker import pytest from webcomix.docker import DockerManager, CONTAINER_NAME @pytest.fixture def cleanup_container(test): yield None client = docker.from_env() for container in client.containers().list(): if container.attrs["Config"]["Image"] == CONTAINER_NAME: container.kill(...
Add test fixture for docker tests
Add test fixture for docker tests
Python
mit
J-CPelletier/webcomix,J-CPelletier/webcomix
--- +++ @@ -1,20 +1,29 @@ import docker +import pytest -from webcomix.docker import DockerManager +from webcomix.docker import DockerManager, CONTAINER_NAME -def test_no_javascript_spawns_no_container(): +@pytest.fixture +def cleanup_container(test): + yield None + client = docker.from_env() + for conta...
16b07dd961cbe55ee452ed6057048ec452ffbd72
custom/icds/management/commands/copy_icds_app.py
custom/icds/management/commands/copy_icds_app.py
from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a sp...
from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a sp...
Replace old config IDs with the new ones
Replace old config IDs with the new ones
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -23,3 +23,18 @@ old_app = wrap_app(old_app) old_app.convert_build_to_app() new_app = import_app(old_app.to_json(), domain, source_properties={'name': new_name}) + + old_to_new = get_old_to_new_config_ids(old_app, new_app) + for form in new_app.get_forms(): + ...
6f356a94c56053b47fb38670a93e04f46740f21e
tartpy/eventloop.py
tartpy/eventloop.py
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton clas...
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton clas...
Make sure that 'stop' works from everywhere
Make sure that 'stop' works from everywhere
Python
mit
waltermoreira/tartpy
--- +++ @@ -55,7 +55,7 @@ self.thread.start() def stop(self): - self.loop.stop() + self.thread_do(self.loop.stop) def stop_later(self): self.do = self.sync_do
39b5f794503149351d03879083d336dfe5f2351b
openprescribing/frontend/tests/test_api_utils.py
openprescribing/frontend/tests/test_api_utils.py
from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = conn...
from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = conn...
Add a missing test for param-parsing
Add a missing test for param-parsing
Python
mit
ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc
--- +++ @@ -12,3 +12,12 @@ cursor = connection.cursor() cursor.execute("select pg_sleep(0.01);") self.assertRaises(OperationalError, do_long_running_query) + + def test_param_to_list(self): + from api.view_utils import param_to_list + + self.assertEquals(par...
bed98e0769d067857dadf69079dc049d76d65fd0
kitchen/lib/__init__.py
kitchen/lib/__init__.py
import os import json from kitchen.settings import KITCHEN_LOCATION def load_nodes(): retval = {} nodes_dir = os.path.join(KITCHEN_LOCATION, 'nodes') for filename in os.listdir(nodes_dir): f = open(os.path.join(nodes_dir, filename), 'r') retval[filename[:-5]] = json.load(f) f.close...
Add function to load data from nodes files
Add function to load data from nodes files
Python
apache-2.0
edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen
--- +++ @@ -0,0 +1,13 @@ +import os +import json + +from kitchen.settings import KITCHEN_LOCATION + +def load_nodes(): + retval = {} + nodes_dir = os.path.join(KITCHEN_LOCATION, 'nodes') + for filename in os.listdir(nodes_dir): + f = open(os.path.join(nodes_dir, filename), 'r') + retval[filenam...
27467c09abe01a6e6a2b66f9f7553bb36cb8a977
uploader/uploader.py
uploader/uploader.py
#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = list(f for f in os.listdir(directory) if f.endswith('.warc.gz')) if len(fnames): ...
#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = sorted(list(f for f in os.listdir(directory) if f.endswith('.warc.gz'))) if len(fna...
Sort files before choosing one to upload
Sort files before choosing one to upload
Python
mit
Frogging101/ArchiveBot,emijrp/ArchiveBot,emijrp/ArchiveBot,Frogging101/ArchiveBot,Asparagirl/ArchiveBot,ArchiveTeam/ArchiveBot,JesseWeinstein/ArchiveBot,falconkirtaran/ArchiveBot,emijrp/ArchiveBot,Frogging101/ArchiveBot,JesseWeinstein/ArchiveBot,Asparagirl/ArchiveBot,Frogging101/ArchiveBot,emijrp/ArchiveBot,emijrp/Arch...
--- +++ @@ -13,7 +13,7 @@ directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: - fnames = list(f for f in os.listdir(directory) if f.endswith('.warc.gz')) + fnames = sorted(list(f for f in os.listdir(directory) if f.endswith('.warc.gz'))) if len(fnames): ...
d108f090f198cba47083225c0de46e77b22ab5cc
serfclient/__init__.py
serfclient/__init__.py
from pkg_resources import get_distribution __version__ = get_distribution('serfclient').version from serfclient.client import SerfClient
from pkg_resources import get_distribution from serfclient.client import SerfClient __version__ = get_distribution('serfclient').version
Move module level import to top of file (PEP8)
Move module level import to top of file (PEP8) Error: E402 module level import not at top of file
Python
mit
charleswhchan/serfclient-py,KushalP/serfclient-py
--- +++ @@ -1,5 +1,4 @@ from pkg_resources import get_distribution +from serfclient.client import SerfClient __version__ = get_distribution('serfclient').version - -from serfclient.client import SerfClient
b26aaf9bdc80760236d4369f67ea803becc733b7
test_squarespace.py
test_squarespace.py
# coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.1 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, W...
# coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.2 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, W...
Increment the version in the test too
Increment the version in the test too
Python
mit
skullydazed/squarespace-python,skullydazed/squarespace-python
--- +++ @@ -5,7 +5,7 @@ def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' - assert store.useragent == 'Squarespace python API v0.0.1 by Zach White.' + assert store.useragent == 'Squarespace python API v0.0.2 by Zach White.' def test_squarespace_useragent():
375fd952e4495a07cb2031c7d380bdb4a535defc
tests/test_dimension.py
tests/test_dimension.py
from devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=...
from devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=...
Change from is_Stepping to is_Derived wherever appropriate
Change from is_Stepping to is_Derived wherever appropriate
Python
mit
opesci/devito,opesci/devito
--- +++ @@ -19,5 +19,5 @@ save_eqn = Eq(u_s, u) #fwd_op = Operator([fwd_eqn]) fwd_op = Operator([fwd_eqn, fwd_eqn_2, save_eqn]) - pprint(fwd_op) - print(fwd_op) + #pprint(fwd_op) + #print(fwd_op)
01a8fcb70ea75d854aaf16547b837d861750c160
tilequeue/queue/file.py
tilequeue/queue/file.py
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) ...
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) ...
Use readline() instead of next() to detect changes.
Use readline() instead of next() to detect changes. tilequeue/queue/file.py -`readline()` will pick up new lines appended to the file, whereas `next()` will not since the iterator will just hit `StopIteration` and stop generating new lines. Use `readline()` instead, then, since it might be desirable to append some...
Python
mit
tilezen/tilequeue,mapzen/tilequeue
--- +++ @@ -24,11 +24,11 @@ with self.lock: coords = [] for _ in range(max_to_read): - try: - coord = next(self.fp) - except StopIteration: + coord = self.fp.readline() + if coord: + co...
5456ae0af9ad83b8e0339c671ce8954bb48d62cf
database.py
database.py
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = crea...
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker, class_mapper from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self...
Add ImposterBase mixin class so we can add methods and properties to the sqlalchemy based models
Add ImposterBase mixin class so we can add methods and properties to the sqlalchemy based models
Python
bsd-2-clause
jkossen/imposter,jkossen/imposter
--- +++ @@ -1,5 +1,5 @@ from sqlalchemy import create_engine -from sqlalchemy.orm import scoped_session, sessionmaker +from sqlalchemy.orm import scoped_session, sessionmaker, class_mapper from sqlalchemy.ext.declarative import declarative_base import config as cfg @@ -20,3 +20,16 @@ def get_base(self): ...
be1e31c78f17961851d41dea11cd912d237cf5fb
lib/rapidsms/message.py
lib/rapidsms/message.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text # initialize some empty attributes self.received = None ...
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text self.responses = [] def __unicode__(self): return self.text ...
Remove unused attributes; also, empty responses after it's flushed.
Remove unused attributes; also, empty responses after it's flushed.
Python
bsd-3-clause
unicefuganda/edtrac,caktus/rapidsms,eHealthAfrica/rapidsms,dimagi/rapidsms,catalpainternational/rapidsms,peterayeni/rapidsms,peterayeni/rapidsms,ken-muturi/rapidsms,ehealthafrica-ci/rapidsms,rapidsms/rapidsms-core-dev,eHealthAfrica/rapidsms,lsgunth/rapidsms,dimagi/rapidsms-core-dev,ehealthafrica-ci/rapidsms,catalpainte...
--- +++ @@ -8,10 +8,6 @@ self._backend = backend self.caller = caller self.text = text - - # initialize some empty attributes - self.received = None - self.sent = None self.responses = [] def __unicode__(self): @@ -31,6 +27,7 @@ def flus...
536575db87968014f75d2ad68456c3684d6c92de
auditlog/__manifest__.py
auditlog/__manifest__.py
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'categ...
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'categ...
Remove pre_init_hook reference from openerp, no pre_init hook exists any more
auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
Python
agpl-3.0
brain-tec/server-tools,brain-tec/server-tools,bmya/server-tools,brain-tec/server-tools,bmya/server-tools,bmya/server-tools
--- +++ @@ -22,5 +22,4 @@ 'images': [], 'application': True, 'installable': True, - 'pre_init_hook': 'pre_init_hook', }
7f2e91064eabc020cbe660639713278fc187a034
tests/test_result.py
tests/test_result.py
import pytest from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, b...
from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'ba...
Remove unused import of pytest
Remove unused import of pytest
Python
mit
charleswhchan/serfclient-py,KushalP/serfclient-py
--- +++ @@ -1,5 +1,3 @@ -import pytest - from serfclient import result
a9cd0a385253cef42d03d6a45e81ef4dd582e9de
base/settings/testing.py
base/settings/testing.py
# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': ...
# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', ...
Use SQLite in an attempt to speed up the tests.
Use SQLite in an attempt to speed up the tests.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
--- +++ @@ -7,8 +7,8 @@ # -------------------------------------------------------------------------- DATABASES = { 'default': { - 'ENGINE': 'django.db.backends.postgresql_psycopg2', - 'NAME': 'test', + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': ':m...
211ee03b811cb196dd9f36026fcfc6e75dda2ec6
byceps/config_defaults.py
byceps/config_defaults.py
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after...
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after...
Set session cookie flag `SameSite` to `Lax` (instead of `None`)
Set session cookie flag `SameSite` to `Lax` (instead of `None`)
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
--- +++ @@ -35,6 +35,7 @@ # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) +SESSION_COOKIE_SAMESITE = 'Lax' # localization LOCALE = 'de_DE.UTF-8'