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 |
|---|---|---|---|---|---|---|---|---|---|---|
bb59028a3dab81139a83f9a0eb8a4c58b9c25829 | sample_application/app.py | sample_application/app.py | import os
from flask import Blueprint, Flask
from flask import Flask, g
from views import blueprint, Resources, UnixTime, PrintArg, ExampleApiUsage
from flask.ext.restful import Api
from client import Client
def create_app():
api = Api(blueprint)
api.add_resource(Resources, '/resources')
api.add_resource(UnixTime, '/time')
api.add_resource(PrintArg,'/print/<string:arg>')
api.add_resource(ExampleApiUsage,'/search')
app = Flask(__name__, static_folder=None)
app.url_map.strict_slashes = False
app.config.from_object('sample_application.config')
try:
app.config.from_object('sample_application.local_config')
except ImportError:
pass
app.register_blueprint(blueprint)
app.client = Client(app.config['CLIENT'])
return app
| import os
from flask import Blueprint, Flask
from flask import Flask, g
from views import blueprint, Resources, UnixTime, PrintArg, ExampleApiUsage
from flask.ext.restful import Api
from client import Client
def create_app():
api = Api(blueprint)
api.add_resource(Resources, '/resources')
api.add_resource(UnixTime, '/time')
api.add_resource(PrintArg,'/print/<string:arg>')
api.add_resource(ExampleApiUsage,'/search')
app = Flask(__name__, static_folder=None)
app.url_map.strict_slashes = False
app.config.from_pyfile('config.py')
try:
app.config.from_pyfile('local_config.py')
except IOError:
pass
app.register_blueprint(blueprint)
app.client = Client(app.config['CLIENT'])
return app
| Change config import strategy to config.from_pyfile() | Change config import strategy to config.from_pyfile()
| Python | mit | adsabs/adsabs-webservices-blueprint,jonnybazookatone/adsabs-webservices-blueprint | ---
+++
@@ -14,10 +14,10 @@
app = Flask(__name__, static_folder=None)
app.url_map.strict_slashes = False
- app.config.from_object('sample_application.config')
+ app.config.from_pyfile('config.py')
try:
- app.config.from_object('sample_application.local_config')
- except ImportError:
+ app.config.from_pyfile('local_config.py')
+ except IOError:
pass
app.register_blueprint(blueprint)
app.client = Client(app.config['CLIENT']) |
20c8d494519b3d54bc3981aebdad18871deef3cb | src/sentry/auth/manager.py | src/sentry/auth/manager.py | from __future__ import absolute_import, print_function
__all__ = ['ProviderManager']
from .exceptions import ProviderNotRegistered
# Ideally this and PluginManager abstracted from the same base, but
# InstanceManager has become convulated and wasteful
class ProviderManager(object):
def __init__(self):
self.__values = {}
def __iter__(self):
return self.__values.iteritems()
def get(self, name, **kwargs):
try:
cls = self.__values[name]
except KeyError:
raise ProviderNotRegistered(name)
return cls(name=name, **kwargs)
def exists(self, name):
return name in self.__values
def register(self, name, cls):
self.__values[name] = cls
def unregister(self, name, cls):
if self.__values[name] != cls:
raise ProviderNotRegistered(name)
del self.__values[name]
| from __future__ import absolute_import, print_function
__all__ = ['ProviderManager']
from .exceptions import ProviderNotRegistered
# Ideally this and PluginManager abstracted from the same base, but
# InstanceManager has become convulated and wasteful
class ProviderManager(object):
def __init__(self):
self.__values = {}
def __iter__(self):
return self.__values.iteritems()
def get(self, key, **kwargs):
try:
cls = self.__values[key]
except KeyError:
raise ProviderNotRegistered(key)
return cls(key=key, **kwargs)
def exists(self, key):
return key in self.__values
def register(self, key, cls):
self.__values[key] = cls
def unregister(self, key, cls):
if self.__values[key] != cls:
raise ProviderNotRegistered(key)
del self.__values[key]
| Revert back to using key | Revert back to using key
| Python | bsd-3-clause | argonemyth/sentry,gencer/sentry,JamesMura/sentry,vperron/sentry,nicholasserra/sentry,alexm92/sentry,jokey2k/sentry,zenefits/sentry,jokey2k/sentry,zenefits/sentry,Kryz/sentry,llonchj/sentry,llonchj/sentry,daevaorn/sentry,zenefits/sentry,ewdurbin/sentry,TedaLIEz/sentry,boneyao/sentry,nicholasserra/sentry,felixbuenemann/sentry,BuildingLink/sentry,vperron/sentry,daevaorn/sentry,mitsuhiko/sentry,looker/sentry,JTCunning/sentry,kevinlondon/sentry,looker/sentry,wujuguang/sentry,looker/sentry,ifduyue/sentry,drcapulet/sentry,mvaled/sentry,fuziontech/sentry,fotinakis/sentry,ngonzalvez/sentry,BuildingLink/sentry,zenefits/sentry,alexm92/sentry,fotinakis/sentry,ifduyue/sentry,JamesMura/sentry,fotinakis/sentry,kevinastone/sentry,1tush/sentry,jean/sentry,daevaorn/sentry,gencer/sentry,ngonzalvez/sentry,kevinastone/sentry,songyi199111/sentry,alexm92/sentry,hongliang5623/sentry,hongliang5623/sentry,korealerts1/sentry,BuildingLink/sentry,pauloschilling/sentry,mvaled/sentry,fuziontech/sentry,mvaled/sentry,ifduyue/sentry,BayanGroup/sentry,Natim/sentry,ifduyue/sentry,JTCunning/sentry,zenefits/sentry,songyi199111/sentry,wong2/sentry,gencer/sentry,1tush/sentry,beeftornado/sentry,JTCunning/sentry,JackDanger/sentry,imankulov/sentry,jean/sentry,daevaorn/sentry,gg7/sentry,boneyao/sentry,nicholasserra/sentry,jean/sentry,TedaLIEz/sentry,argonemyth/sentry,korealerts1/sentry,wujuguang/sentry,wong2/sentry,Natim/sentry,mvaled/sentry,felixbuenemann/sentry,gencer/sentry,BayanGroup/sentry,jokey2k/sentry,pauloschilling/sentry,gg7/sentry,TedaLIEz/sentry,mitsuhiko/sentry,imankulov/sentry,ewdurbin/sentry,BayanGroup/sentry,beeftornado/sentry,JackDanger/sentry,imankulov/sentry,ifduyue/sentry,Kryz/sentry,JamesMura/sentry,1tush/sentry,kevinastone/sentry,fotinakis/sentry,songyi199111/sentry,BuildingLink/sentry,Natim/sentry,JamesMura/sentry,ngonzalvez/sentry,drcapulet/sentry,drcapulet/sentry,felixbuenemann/sentry,argonemyth/sentry,pauloschilling/sentry,llonchj/sentry,mvaled/sentry,jean/sentry,hongliang5623/sentry,beeftornado/sentry,jean/sentry,mvaled/sentry,JackDanger/sentry,ewdurbin/sentry,boneyao/sentry,wong2/sentry,looker/sentry,Kryz/sentry,gg7/sentry,vperron/sentry,looker/sentry,wujuguang/sentry,JamesMura/sentry,gencer/sentry,BuildingLink/sentry,kevinlondon/sentry,korealerts1/sentry,fuziontech/sentry,kevinlondon/sentry | ---
+++
@@ -14,20 +14,20 @@
def __iter__(self):
return self.__values.iteritems()
- def get(self, name, **kwargs):
+ def get(self, key, **kwargs):
try:
- cls = self.__values[name]
+ cls = self.__values[key]
except KeyError:
- raise ProviderNotRegistered(name)
- return cls(name=name, **kwargs)
+ raise ProviderNotRegistered(key)
+ return cls(key=key, **kwargs)
- def exists(self, name):
- return name in self.__values
+ def exists(self, key):
+ return key in self.__values
- def register(self, name, cls):
- self.__values[name] = cls
+ def register(self, key, cls):
+ self.__values[key] = cls
- def unregister(self, name, cls):
- if self.__values[name] != cls:
- raise ProviderNotRegistered(name)
- del self.__values[name]
+ def unregister(self, key, cls):
+ if self.__values[key] != cls:
+ raise ProviderNotRegistered(key)
+ del self.__values[key] |
2bf4aacbc2a43305506d2d16cef97c6c89c30ee9 | pythontutorials/books/AutomateTheBoringStuff/Ch13/P3_combinePDFs.py | pythontutorials/books/AutomateTheBoringStuff/Ch13/P3_combinePDFs.py | #! python3
"""Combine PDFs
Combines all the PDFs in the current working directory into a single PDF.
Note:
* Example PDFs can be downloaded from http://nostarch.com/automatestuff/
* Book uses PyPDF2; I'm an overachiever that uses PyPDF4
"""
def main():
import PyPDF4, os
# Get all the PDF filenames.
if os.path.exists("allminutes.pdf"):
os.remove("allminutes.pdf")
pdfFiles = []
for filename in os.listdir('.'):
if filename.endswith(".pdf"):
pdfFiles.append(filename)
pdfFiles.sort(key=str.lower)
pdfWriter = PyPDF4.PdfFileWriter()
# Loop through all the PDF files.
for filename in pdfFiles:
pdfFileObj = open(filename, "rb")
pdfReader = PyPDF4.PdfFileReader(pdfFileObj)
if pdfReader.isEncrypted and filename == "encrypted.pdf":
pdfReader.decrypt("rosebud")
if pdfReader.isEncrypted and filename == "encryptedminutes.pdf":
pdfReader.decrypt("swordfish")
# Loop through all the pages (except the first) and add them.
for pageNum in range(1, pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
# Save the resulting PDF to a file.
pdfOutput = open("allminutes.pdf", "wb")
pdfWriter.write(pdfOutput)
pdfOutput.close()
if __name__ == '__main__':
main()
| #! python3
"""Combine PDFs
Combines all the PDFs in the current working directory into a single PDF.
Note:
* Example PDFs can be downloaded from http://nostarch.com/automatestuff/
* Book uses :py:mod:`PyPDF2`; I'm an overachiever that uses PyPDF4
"""
def main():
import PyPDF4, os
# Get all the PDF filenames.
if os.path.exists("allminutes.pdf"):
os.remove("allminutes.pdf")
pdfFiles = []
for filename in os.listdir('.'):
if filename.endswith(".pdf"):
pdfFiles.append(filename)
pdfFiles.sort(key=str.lower)
pdfWriter = PyPDF4.PdfFileWriter()
# Loop through all the PDF files.
for filename in pdfFiles:
pdfFileObj = open(filename, "rb")
pdfReader = PyPDF4.PdfFileReader(pdfFileObj)
if pdfReader.isEncrypted and filename == "encrypted.pdf":
pdfReader.decrypt("rosebud")
if pdfReader.isEncrypted and filename == "encryptedminutes.pdf":
pdfReader.decrypt("swordfish")
# Loop through all the pages (except the first) and add them.
for pageNum in range(1, pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
# Save the resulting PDF to a file.
pdfOutput = open("allminutes.pdf", "wb")
pdfWriter.write(pdfOutput)
pdfOutput.close()
if __name__ == '__main__':
main()
| Update P2_combinePDF.py added module reference in docstring | Update P2_combinePDF.py
added module reference in docstring
| Python | mit | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials | ---
+++
@@ -5,7 +5,7 @@
Note:
* Example PDFs can be downloaded from http://nostarch.com/automatestuff/
- * Book uses PyPDF2; I'm an overachiever that uses PyPDF4
+ * Book uses :py:mod:`PyPDF2`; I'm an overachiever that uses PyPDF4
"""
|
ce25cea7e8d10f9c318e2e7ef1dc1013921ed062 | clint/textui/prompt.py | clint/textui/prompt.py | # -*- coding: utf8 -*-
"""
clint.textui.prompt
~~~~~~~~~~~~~~~~~~~
Module for simple interactive prompts handling
"""
from __future__ import absolute_import
from re import match, I
def yn(prompt, default='y', batch=False):
# A sanity check against default value
# If not y/n then y is assumed
if default not in ['y', 'n']:
default = 'y'
# Let's build the prompt
choicebox = '[Y/n]' if default == 'y' else '[y/N]'
prompt = prompt + ' ' + choicebox + ' '
# If input is not a yes/no variant or empty
# keep asking
while True:
# If batch option is True then auto reply
# with default input
if not batch:
input = raw_input(prompt).strip()
else:
print prompt
input = ''
# If input is empty default choice is assumed
# so we return True
if input == '':
return True
# Given 'yes' as input if default choice is y
# then return True, False otherwise
if match('y(?:es)?', input, I):
return True if default == 'y' else False
# Given 'no' as input if default choice is n
# then return True, False otherwise
elif match('n(?:o)?', input, I):
return True if default == 'n' else False
| # -*- coding: utf8 -*-
"""
clint.textui.prompt
~~~~~~~~~~~~~~~~~~~
Module for simple interactive prompts handling
"""
from __future__ import absolute_import, print_function
from re import match, I
def yn(prompt, default='y', batch=False):
# A sanity check against default value
# If not y/n then y is assumed
if default not in ['y', 'n']:
default = 'y'
# Let's build the prompt
choicebox = '[Y/n]' if default == 'y' else '[y/N]'
prompt = prompt + ' ' + choicebox + ' '
# If input is not a yes/no variant or empty
# keep asking
while True:
# If batch option is True then auto reply
# with default input
if not batch:
input = raw_input(prompt).strip()
else:
print(prompt)
input = ''
# If input is empty default choice is assumed
# so we return True
if input == '':
return True
# Given 'yes' as input if default choice is y
# then return True, False otherwise
if match('y(?:es)?', input, I):
return True if default == 'y' else False
# Given 'no' as input if default choice is n
# then return True, False otherwise
elif match('n(?:o)?', input, I):
return True if default == 'n' else False
| Use print() function to fix install on python 3 | Use print() function to fix install on python 3
clint 0.3.2 can't be installed on python 3.3 because of a print statement. | Python | isc | 1gitGrey/clint,thusoy/clint,wkentaro/clint,1gitGrey/clint,glorizen/clint,wkentaro/clint,tz70s/clint,Lh4cKg/clint,nathancahill/clint,kennethreitz/clint,nathancahill/clint | ---
+++
@@ -8,7 +8,7 @@
"""
-from __future__ import absolute_import
+from __future__ import absolute_import, print_function
from re import match, I
@@ -30,7 +30,7 @@
if not batch:
input = raw_input(prompt).strip()
else:
- print prompt
+ print(prompt)
input = ''
# If input is empty default choice is assumed |
9be4dcdf9ea312465a27d6f105213d88d8dd0909 | anchorhub/lib/tests/test_data/test_filetolist.py | anchorhub/lib/tests/test_data/test_filetolist.py | """
Tests for filetolist.py
filetolist.py:
http://www.github.com/samjabrahams/anchorhub/lib/filetolist.py
"""
from anchorhub.lib.filetolist import FileToList
from anchorhub.util.getanchorhubpath import get_anchorhub_path
from anchorhub.compatibility import get_path_separator
def test_file_to_list_basic():
sep = get_path_separator()
path = get_anchorhub_path() + sep + 'lib' + sep + 'tests' + sep + \
'test_data' + sep + 'filelist'
assert FileToList.to_list(path) == ['Hello!\n', 'My name\n', 'is\n',
'AnchorHub']
| """
Tests for filetolist.py
filetolist.py:
http://www.github.com/samjabrahams/anchorhub/lib/filetolist.py
"""
from anchorhub.lib.filetolist import FileToList
from anchorhub.util.getanchorhubpath import get_anchorhub_path
from anchorhub.compatibility import get_path_separator
def test_file_to_list_basic():
sep = get_path_separator()
path = get_anchorhub_path() + sep + 'lib' + sep + 'tests' + sep + \
'test_data' + sep + 'filelist'
assert FileToList.to_list(path) == ['Hello!\n', 'My name\n', 'is\n', \
'AnchorHub']
| Add expression slash to perhaps fix python3 bug | Add expression slash to perhaps fix python3 bug
| Python | apache-2.0 | samjabrahams/anchorhub | ---
+++
@@ -13,5 +13,5 @@
sep = get_path_separator()
path = get_anchorhub_path() + sep + 'lib' + sep + 'tests' + sep + \
'test_data' + sep + 'filelist'
- assert FileToList.to_list(path) == ['Hello!\n', 'My name\n', 'is\n',
+ assert FileToList.to_list(path) == ['Hello!\n', 'My name\n', 'is\n', \
'AnchorHub'] |
2b0f1c47a85c79c39e6066e0658c9b47090b46c4 | .ci-support/upload_label.py | .ci-support/upload_label.py | import os
travis_tag = os.getenv('TRAVIS_TAG')
appveyor_tag = os.getenv('APPVEYOR_REPO_TAG')
def generate_label(version):
dev_names = ['dev', 'alpha', 'beta', 'rc']
is_dev = any(name in version for name in dev_names)
# Output is the name of the label to which the package should be
# uploaded on anaconda.org
if is_dev:
print('pre-release')
else:
print('main')
if travis_tag:
generate_label(travis_tag)
elif appveyor_tag:
generate_label(appveyor_tag)
else:
print('main')
| import os
travis_tag = os.getenv('TRAVIS_TAG')
appveyor_tag = os.getenv('APPVEYOR_REPO_TAG_NAME')
def generate_label(version):
dev_names = ['dev', 'alpha', 'beta', 'rc']
is_dev = any(name in version for name in dev_names)
# Output is the name of the label to which the package should be
# uploaded on anaconda.org
if is_dev:
print('pre-release')
else:
print('main')
if travis_tag:
generate_label(travis_tag)
elif appveyor_tag:
generate_label(appveyor_tag)
else:
print('main')
| Fix name of environment variable on appveyor tht contains tag name | Fix name of environment variable on appveyor tht contains tag name | Python | mit | mwcraig/vpython-jupyter,mwcraig/vpython-jupyter,BruceSherwood/vpython-jupyter,BruceSherwood/vpython-jupyter,mwcraig/vpython-jupyter,BruceSherwood/vpython-jupyter,mwcraig/vpython-jupyter,BruceSherwood/vpython-jupyter | ---
+++
@@ -1,7 +1,7 @@
import os
travis_tag = os.getenv('TRAVIS_TAG')
-appveyor_tag = os.getenv('APPVEYOR_REPO_TAG')
+appveyor_tag = os.getenv('APPVEYOR_REPO_TAG_NAME')
def generate_label(version): |
d677f3762e0daf16e1be05a88b058194ddf43e15 | comics/comics/perrybiblefellowship.py | comics/comics/perrybiblefellowship.py | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "The Perry Bible Fellowship"
language = "en"
url = "http://www.pbfcomics.com/"
start_date = "2001-01-01"
rights = "Nicholas Gurewitch"
class Crawler(CrawlerBase):
history_capable_date = "2001-01-01"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.pbfcomics.com/feed/feed.xml")
for entry in feed.for_date(pub_date):
url = entry.summary.src('img[src*="/archive_b/"]')
title = entry.title
return CrawlerImage(url, title)
| from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "The Perry Bible Fellowship"
language = "en"
url = "http://www.pbfcomics.com/"
start_date = "2001-01-01"
rights = "Nicholas Gurewitch"
class Crawler(CrawlerBase):
history_capable_date = "2019-06-12"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.pbfcomics.com/feed/feed.xml")
for entry in feed.for_date(pub_date):
page = self.parse_page(entry.link)
images = page.root.xpath("//div[@id='comic']/img")
crawler_images = []
for image in images:
title = entry.title
crawler_images.append(CrawlerImage(image.get("src"), title))
| Rewrite "The Perry Bible Fellowship" after feed change | Rewrite "The Perry Bible Fellowship" after feed change
| Python | agpl-3.0 | datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics | ---
+++
@@ -11,12 +11,15 @@
class Crawler(CrawlerBase):
- history_capable_date = "2001-01-01"
+ history_capable_date = "2019-06-12"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.pbfcomics.com/feed/feed.xml")
for entry in feed.for_date(pub_date):
- url = entry.summary.src('img[src*="/archive_b/"]')
- title = entry.title
- return CrawlerImage(url, title)
+ page = self.parse_page(entry.link)
+ images = page.root.xpath("//div[@id='comic']/img")
+ crawler_images = []
+ for image in images:
+ title = entry.title
+ crawler_images.append(CrawlerImage(image.get("src"), title)) |
dc4307a781e34bf051b20b18935d4939b2de1f8e | examples/unicode_commands.py | examples/unicode_commands.py | #!/usr/bin/env python
# coding=utf-8
"""A simple example demonstrating support for unicode command names.
"""
import math
import cmd2
class UnicodeApp(cmd2.Cmd):
"""Example cmd2 application with unicode command names."""
def __init__(self):
super().__init__()
self.intro = 'Welcome the Unicode example app. Note the full Unicode support: 😇 💩'
def do_𝛑print(self, _):
"""This command prints 𝛑 to 5 decimal places."""
self.poutput("𝛑 = {0:.6}".format(math.pi))
def do_你好(self, arg):
"""This command says hello in Chinese (Mandarin)."""
self.poutput("你好 " + arg)
if __name__ == '__main__':
app = UnicodeApp()
app.cmdloop()
| #!/usr/bin/env python
# coding=utf-8
"""A simple example demonstrating support for unicode command names.
"""
import math
import cmd2
class UnicodeApp(cmd2.Cmd):
"""Example cmd2 application with unicode command names."""
def __init__(self):
super().__init__()
self.intro = 'Welcome the Unicode example app. Note the full Unicode support: 😇 💩'
def do_𝛑print(self, _):
"""This command prints 𝛑 to 5 decimal places."""
self.poutput("𝛑 = {0:.6}".format(math.pi))
def do_你好(self, arg):
"""This command says hello in Chinese (Mandarin)."""
self.poutput("你好 " + arg)
if __name__ == '__main__':
app = UnicodeApp()
app.cmdloop()
| Fix flake8 error due to extra blank line in example | Fix flake8 error due to extra blank line in example
| Python | mit | python-cmd2/cmd2,python-cmd2/cmd2 | ---
+++
@@ -25,4 +25,3 @@
if __name__ == '__main__':
app = UnicodeApp()
app.cmdloop()
- |
241d1e6b36eb8f87a5c6111bfa52104feb821bb8 | test/dependencies_test.py | test/dependencies_test.py | import luigi
import sciluigi as sl
import os
TESTFILE_PATH = '/tmp/test.out'
class TestTask(sl.Task):
def out_data(self):
return sl.TargetInfo(self, TESTFILE_PATH)
def run(self):
with self.out_data().open('w') as outfile:
outfile.write('File written by luigi\n')
class TestRunTask():
def setup(self):
wf = sl.WorkflowTask()
self.t = sl.new_task('testtask', TestTask, wf)
def teardown(self):
self.t = None
os.remove(TESTFILE_PATH)
def test_run(self):
# Run a task with a luigi worker
w = luigi.worker.Worker()
w.add(self.t)
w.run()
w.stop()
assert os.path.isfile(TESTFILE_PATH)
| import logging
import luigi
import sciluigi as sl
import os
TESTFILE_PATH = '/tmp/test.out'
log = logging.getLogger('sciluigi-interface')
log.setLevel(logging.WARNING)
class TestTask(sl.Task):
def out_data(self):
return sl.TargetInfo(self, TESTFILE_PATH)
def run(self):
with self.out_data().open('w') as outfile:
outfile.write('File written by luigi\n')
class TestRunTask():
def setup(self):
wf = sl.WorkflowTask()
self.t = sl.new_task('testtask', TestTask, wf)
def teardown(self):
self.t = None
os.remove(TESTFILE_PATH)
def test_run(self):
# Run a task with a luigi worker
w = luigi.worker.Worker()
w.add(self.t)
w.run()
w.stop()
assert os.path.isfile(TESTFILE_PATH)
| Set log level to WARNING when testing | Set log level to WARNING when testing
| Python | mit | pharmbio/sciluigi,samuell/sciluigi,pharmbio/sciluigi | ---
+++
@@ -1,8 +1,12 @@
+import logging
import luigi
import sciluigi as sl
import os
TESTFILE_PATH = '/tmp/test.out'
+
+log = logging.getLogger('sciluigi-interface')
+log.setLevel(logging.WARNING)
class TestTask(sl.Task):
|
758a8bff354d1e1542b5c4614276bdfa229f3dbc | extended_choices/__init__.py | extended_choices/__init__.py | """Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices, OrderedChoices
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1.1"
| """Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices, OrderedChoices
__all__ = ['Choices', 'OrderedChoices']
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1.1"
| Add `__all__` at package root level | Add `__all__` at package root level
| Python | bsd-3-clause | twidi/django-extended-choices | ---
+++
@@ -4,6 +4,7 @@
from .choices import Choices, OrderedChoices
+__all__ = ['Choices', 'OrderedChoices']
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices" |
389bd3773d2f89321c31b05da8a733b65ccbeef8 | tests/test_coefficient.py | tests/test_coefficient.py | # -*- coding: utf-8 -*-
from nose.tools import assert_equal
from openfisca_france.model.prelevements_obligatoires.prelevements_sociaux.cotisations_sociales.allegements import *
from openfisca_core.periods import *
from openfisca_france import FranceTaxBenefitSystem
def test_coefficient_proratisation_only_contract_periods():
tax_benefit_system = FranceTaxBenefitSystem()
scenario = tax_benefit_system.new_scenario()
scenario.init_single_entity(period='2017-11',
parent1=dict(salaire_de_base=2300,
effectif_entreprise=1,
code_postal_entreprise="75001",
categorie_salarie=u'prive_non_cadre',
contrat_de_travail_debut='2017-11-1',
allegement_fillon_mode_recouvrement=u'progressif'))
simulation = scenario.new_simulation()
assert_equal(simulation.calculate('coefficient_proratisation','2017-11'),1)
assert_equal(simulation.calculate('coefficient_proratisation','2017-12'),1)
assert_equal(simulation.calculate('coefficient_proratisation','2017-10'),0)
assert_equal(simulation.calculate_add('coefficient_proratisation','2017'),2)
| # -*- coding: utf-8 -*-
from nose.tools import assert_equal
from openfisca_france.model.prelevements_obligatoires.prelevements_sociaux.cotisations_sociales.allegements import *
from openfisca_core.periods import *
from openfisca_france import FranceTaxBenefitSystem
def test_coefficient_proratisation_only_contract_periods():
tax_benefit_system = FranceTaxBenefitSystem()
scenario = tax_benefit_system.new_scenario()
scenario.init_single_entity(period='2017',
parent1=dict(salaire_de_base=2300,
effectif_entreprise=1,
code_postal_entreprise="75001",
categorie_salarie=u'prive_non_cadre',
contrat_de_travail_debut='2017-11-1',
allegement_fillon_mode_recouvrement=u'progressif'))
simulation = scenario.new_simulation()
assert_equal(simulation.calculate('coefficient_proratisation','2017-11'),1)
assert_equal(simulation.calculate('coefficient_proratisation','2017-12'),1)
assert_equal(simulation.calculate('coefficient_proratisation','2017-10'),0)
assert_equal(simulation.calculate_add('coefficient_proratisation','2017'),2)
| Fix test to avoid weird period handling | Fix test to avoid weird period handling
| Python | agpl-3.0 | sgmap/openfisca-france,antoinearnoud/openfisca-france,sgmap/openfisca-france,antoinearnoud/openfisca-france | ---
+++
@@ -9,7 +9,7 @@
def test_coefficient_proratisation_only_contract_periods():
tax_benefit_system = FranceTaxBenefitSystem()
scenario = tax_benefit_system.new_scenario()
- scenario.init_single_entity(period='2017-11',
+ scenario.init_single_entity(period='2017',
parent1=dict(salaire_de_base=2300,
effectif_entreprise=1,
code_postal_entreprise="75001", |
ee4c8b806ecf0ada51916fe63f9da9e81c03850d | django_react_templatetags/tests/demosite/urls.py | django_react_templatetags/tests/demosite/urls.py | from django.urls import path
from django_react_templatetags.tests.demosite import views
urlpatterns = [
path(
'static-react-view',
views.StaticReactView.as_view(),
name='static_react_view',
),
]
| from django.conf.urls import url
from django_react_templatetags.tests.demosite import views
urlpatterns = [
url(
'static-react-view',
views.StaticReactView.as_view(),
name='static_react_view',
),
]
| Use url instead of path (to keep django 1 compat) | Use url instead of path (to keep django 1 compat)
| Python | mit | Frojd/django-react-templatetags,Frojd/django-react-templatetags,Frojd/django-react-templatetags | ---
+++
@@ -1,10 +1,11 @@
-from django.urls import path
+from django.conf.urls import url
+
from django_react_templatetags.tests.demosite import views
urlpatterns = [
- path(
+ url(
'static-react-view',
views.StaticReactView.as_view(),
name='static_react_view', |
4244e285c25c0c13a1f7f6e172b31ebb8f2bb7b1 | spacy/lang/es/__init__.py | spacy/lang/es/__init__.py | # coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
sytax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
| # coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lemmatizer import LOOKUP
from .syntax_iterators import SYNTAX_ITERATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class SpanishDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'es'
lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
syntax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
class Spanish(Language):
lang = 'es'
Defaults = SpanishDefaults
__all__ = ['Spanish']
| Fix Spanish noun_chunks failure caused by typo | Fix Spanish noun_chunks failure caused by typo | Python | mit | recognai/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,honnibal/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,honnibal/spaCy,recognai/spaCy,honnibal/spaCy | ---
+++
@@ -21,7 +21,7 @@
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
tag_map = TAG_MAP
stop_words = STOP_WORDS
- sytax_iterators = SYNTAX_ITERATORS
+ syntax_iterators = SYNTAX_ITERATORS
lemma_lookup = LOOKUP
|
78af5e585eb109049299bd1c826f93001e4f6c68 | adama/store.py | adama/store.py | import collections
import pickle
import redis
from .tools import location
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = location('redis', 6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
| import collections
import pickle
import redis
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = 'redis', 6379
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
| Use /etc/hosts to find redis | Use /etc/hosts to find redis | Python | mit | waltermoreira/adama-app,waltermoreira/adama-app,waltermoreira/adama-app | ---
+++
@@ -3,13 +3,11 @@
import redis
-from .tools import location
-
class Store(collections.MutableMapping):
def __init__(self, db=0):
- host, port = location('redis', 6379)
+ host, port = 'redis', 6379
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key): |
50f8e32521ccf871177b4402b6a410dad896b272 | src/schema_matching/collector/description/_argparser.py | src/schema_matching/collector/description/_argparser.py | import utilities
def parse(src):
if src == ':':
from ..description import default as desc
elif src.startswith(':'):
import importlib
desc = importlib.import_module(src[1:])
else:
import os, imp
from .. import description as parent_package # needs to be imported before its child modules
with open(src) as f:
module_name = \
'{0}._anonymous_{1.st_dev}_{1.st_ino}'.format(
parent_package.__name__, os.fstat(f.fileno()))
desc = imp.load_source(module_name, src, f)
assert isinstance(getattr(desc, '__file__', None), str)
utilities.setattr_default(desc, '__file__', '<unknown file>')
if not hasattr(desc, 'descriptions'):
raise NameError(
"The collector description module doesn't contain any collector description.",
desc, desc.__file__,
"missing attribute 'descriptions'")
return desc
| import importlib
def parse(src):
try:
if src == ':':
from ..description import default as desc
elif src.startswith(':'):
desc = importlib.import_module(src[1:], __package__.partition('.')[0])
else:
desc = importlib.machinery.SourceFileLoader(src, src).load_module()
except:
raise ImportError(src)
if not getattr(desc, 'descriptions', None):
raise NameError(
"The collector description module doesn't contain any collector description.",
desc, desc.__file__,
"missing attribute 'descriptions'")
return desc
| Use importlib in favour of imp | Use importlib in favour of imp
| Python | mit | davidfoerster/schema-matching | ---
+++
@@ -1,24 +1,18 @@
-import utilities
+import importlib
def parse(src):
- if src == ':':
- from ..description import default as desc
- elif src.startswith(':'):
- import importlib
- desc = importlib.import_module(src[1:])
- else:
- import os, imp
- from .. import description as parent_package # needs to be imported before its child modules
- with open(src) as f:
- module_name = \
- '{0}._anonymous_{1.st_dev}_{1.st_ino}'.format(
- parent_package.__name__, os.fstat(f.fileno()))
- desc = imp.load_source(module_name, src, f)
- assert isinstance(getattr(desc, '__file__', None), str)
+ try:
+ if src == ':':
+ from ..description import default as desc
+ elif src.startswith(':'):
+ desc = importlib.import_module(src[1:], __package__.partition('.')[0])
+ else:
+ desc = importlib.machinery.SourceFileLoader(src, src).load_module()
+ except:
+ raise ImportError(src)
- utilities.setattr_default(desc, '__file__', '<unknown file>')
- if not hasattr(desc, 'descriptions'):
+ if not getattr(desc, 'descriptions', None):
raise NameError(
"The collector description module doesn't contain any collector description.",
desc, desc.__file__, |
e94e3931ec254e432993d18d9f4ac79f559a2257 | scripts/starting_py_program.py | scripts/starting_py_program.py |
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def main(argv=None):
if argv is None:
argv = sys.argv
return 0
if __name__ == "__main__":
sys.exit(main())
| #!/usr/bin/env python3
# from __future__ import print_function #(if python2)
import sys
def eprint(*args, **kwargs):
""" Just like the print function, but on stderr
"""
print(*args, file=sys.stderr, **kwargs)
def main(argv=None):
""" Program starting point, it can started by the OS or as normal function
If it's a normal function argv won't be None if started by the OS
argv is initialized by the command line arguments
"""
if argv is None:
argv = sys.argv
return 0
if __name__ == "__main__":
sys.exit(main())
| Add docstrings to starting py program | Add docstrings to starting py program
| Python | unlicense | paolobolzoni/useful-conf,paolobolzoni/useful-conf,paolobolzoni/useful-conf | ---
+++
@@ -1,10 +1,21 @@
+#!/usr/bin/env python3
+
+# from __future__ import print_function #(if python2)
import sys
+
def eprint(*args, **kwargs):
+ """ Just like the print function, but on stderr
+ """
print(*args, file=sys.stderr, **kwargs)
def main(argv=None):
+ """ Program starting point, it can started by the OS or as normal function
+
+ If it's a normal function argv won't be None if started by the OS
+ argv is initialized by the command line arguments
+ """
if argv is None:
argv = sys.argv
return 0 |
13f8d6feebcfb28b96bb0f69d1e5625a337c22fa | demo/ok_test/tests/q1.py | demo/ok_test/tests/q1.py | test = {
'name': 'Question 1',
'points': 3,
'suites': [
{
'cases': [
{
'answer': 'Domain is numbers. Range is numbers',
'choices': [
'Domain is numbers. Range is numbers',
'Domain is numbers. Range is strings',
'Domain is strings. Range is numbers',
'Domain is strings. Range is strings'
],
'hidden': False,
'question': 'What is the domain and range of the square function?'
}
],
'scored': False,
'type': 'concept'
},
{
'cases': [
{
'code': r"""
>>> square(3)
9
""",
'hidden': False
},
{
'code': r"""
>>> square(2)
4
# explanation: Squaring a negative number
""",
'hidden': True
},
{
'code': r"""
>>> square(0)
0
# explanation: Squaring zero
""",
'hidden': True
},
{
'code': r"""
>>> 1 / square(0)
ZeroDivisionError
""",
'hidden': True
}
],
'scored': True,
'setup': r"""
>>> from hw1 import *
""",
'teardown': r"""
>>> print('Teardown code')
""",
'type': 'doctest'
}
]
} | test = {
'name': 'Question 1',
'points': 3,
'suites': [
{
'type': 'concept',
'cases': [
{
'answer': 'Domain is numbers. Range is numbers',
'choices': [
'Domain is numbers. Range is numbers',
'Domain is numbers. Range is strings',
'Domain is strings. Range is numbers',
'Domain is strings. Range is strings'
],
'hidden': False,
'question': 'What is the domain and range of the square function?'
}
],
},
{
'type': 'wwpp',
'cases': [
{
'code': r"""
>>> square(3)
9
>>> square(5)
25
"""
},
{
'code': r"""
>>> print(print(square(4)))
16
None
"""
}
],
},
{
'cases': [
{
'code': r"""
>>> square(3)
9
""",
'hidden': False
},
{
'code': r"""
>>> square(2)
4
# explanation: Squaring a negative number
""",
'hidden': True
},
{
'code': r"""
>>> square(0)
0
# explanation: Squaring zero
""",
'hidden': True
},
{
'code': r"""
>>> 1 / square(0)
ZeroDivisionError
""",
'hidden': True
}
],
'scored': True,
'setup': r"""
>>> from hw1 import *
""",
'teardown': r"""
>>> print('Teardown code')
""",
'type': 'doctest'
}
]
}
| Add a demo for wwpp | Add a demo for wwpp
| Python | apache-2.0 | jathak/ok-client,Cal-CS-61A-Staff/ok-client,jackzhao-mj/ok-client | ---
+++
@@ -3,6 +3,7 @@
'points': 3,
'suites': [
{
+ 'type': 'concept',
'cases': [
{
'answer': 'Domain is numbers. Range is numbers',
@@ -16,8 +17,26 @@
'question': 'What is the domain and range of the square function?'
}
],
- 'scored': False,
- 'type': 'concept'
+ },
+ {
+ 'type': 'wwpp',
+ 'cases': [
+ {
+ 'code': r"""
+ >>> square(3)
+ 9
+ >>> square(5)
+ 25
+ """
+ },
+ {
+ 'code': r"""
+ >>> print(print(square(4)))
+ 16
+ None
+ """
+ }
+ ],
},
{
'cases': [ |
6dadf50366b1e142f96ef3bf4a356f7aa98f37be | geokey_export/__init__.py | geokey_export/__init__.py | from geokey.extensions.base import register
VERSION = (0, 2, 0)
__version__ = '.'.join(map(str, VERSION))
register(
'geokey_export',
'Export',
display_admin=True,
superuser=False,
version=__version__
)
| from geokey.extensions.base import register
VERSION = (0, 2, 0)
__version__ = '.'.join(map(str, VERSION))
register(
'geokey_export',
'Export',
display_admin=True,
superuser=False
)
| Undo previous commit (should not been on new branch) - Sorry! | Undo previous commit (should not been on new branch) - Sorry!
Signed-off-by: Matthias Stevens <3e0606afd16757d2df162884117429808539458f@gmail.com>
| Python | mit | ExCiteS/geokey-export,ExCiteS/geokey-export,ExCiteS/geokey-export | ---
+++
@@ -8,6 +8,5 @@
'geokey_export',
'Export',
display_admin=True,
- superuser=False,
- version=__version__
+ superuser=False
) |
a6774092839f8c6aff743cf8f4cc982fe8ce2e63 | interfaces/cython/cantera/mixmaster/utilities.py | interfaces/cython/cantera/mixmaster/utilities.py | import string
import os, sys
import types, traceback
try:
if sys.version_info[0] == 3:
from tkinter import Tk
from tkinter import messagebox
else:
from Tkinter import Tk
import tkMessageBox
_hasTk = 1
except:
_hasTk = 0
def write_CSV(f,x):
"""write list x to file f in comma-separated-value format."""
for e in x:
f.write( repr(e)+',')
f.write('\n')
def _print_value(name, value, unitstr):
print(string.rjust(name, 15)+ \
string.rjust('%10.5e' %value, 15) + ' ' + \
string.ljust(unitstr,5))
def hasTk():
try:
import tkMessageBox
return 1
except:
return 0
def handleError(message = '<error>', window = None,
fatal = 0, warning = 0, options = None):
if warning:
messagebox.showwarning(title = 'Warning', message = message,
parent = window)
else:
m = messagebox.showerror(title = 'Error', message = message,
parent = window)
| import string
import os, sys
import types, traceback
try:
if sys.version_info[0] == 3:
from tkinter import Tk
from tkinter import messagebox
else:
from Tkinter import Tk
import tkMessageBox as messagebox
_hasTk = 1
except:
_hasTk = 0
def write_CSV(f,x):
"""write list x to file f in comma-separated-value format."""
for e in x:
f.write( repr(e)+',')
f.write('\n')
def _print_value(name, value, unitstr):
print(string.rjust(name, 15)+ \
string.rjust('%10.5e' %value, 15) + ' ' + \
string.ljust(unitstr,5))
def handleError(message = '<error>', window = None,
fatal = 0, warning = 0, options = None):
if warning:
messagebox.showwarning(title = 'Warning', message = message,
parent = window)
else:
m = messagebox.showerror(title = 'Error', message = message,
parent = window)
| Fix displaying of errors when using Python 2 | [MixMaster] Fix displaying of errors when using Python 2
| Python | bsd-3-clause | Heathckliff/cantera,imitrichev/cantera,imitrichev/cantera,imitrichev/cantera,Heathckliff/cantera,Heathckliff/cantera,Heathckliff/cantera,imitrichev/cantera,Heathckliff/cantera,imitrichev/cantera,Heathckliff/cantera,imitrichev/cantera | ---
+++
@@ -8,7 +8,7 @@
from tkinter import messagebox
else:
from Tkinter import Tk
- import tkMessageBox
+ import tkMessageBox as messagebox
_hasTk = 1
except:
_hasTk = 0
@@ -26,13 +26,6 @@
string.rjust('%10.5e' %value, 15) + ' ' + \
string.ljust(unitstr,5))
-def hasTk():
- try:
- import tkMessageBox
- return 1
- except:
- return 0
-
def handleError(message = '<error>', window = None,
fatal = 0, warning = 0, options = None):
if warning: |
f13e9ff10c79f58df2f6d43c8b840b642be56dab | core/admin.py | core/admin.py | # -*- encoding: UTF-8 -*-
#
# Copyright 2014-2015
#
# STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es>
#
# This file is part of Portal del Investigador.
#
# Portal del Investigador is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Portal del Investigador is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Portal del Investigador. If not, see
# <http://www.gnu.org/licenses/>.
#
import admin_advanced # Don't delete
import admin_basic # Don't delete
| # -*- encoding: UTF-8 -*-
#
# Copyright 2014-2015
#
# STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es>
#
# This file is part of Portal del Investigador.
#
# Portal del Investigador is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Portal del Investigador is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Portal del Investigador. If not, see
# <http://www.gnu.org/licenses/>.
#
from django.contrib.admin.templatetags.admin_modify import register
from django.contrib.admin.templatetags.admin_modify import submit_row as osr
# If the developer wants to enable/disable the save buttons,
# we want to give preference over Django's logic
# https://github.com/django/django/blob/master/django/contrib/admin/templatetags/admin_modify.py#L23
@register.inclusion_tag('admin/submit_line.html', takes_context=True)
def submit_row(context):
ctx = osr(context) # Here is Django's logic => it ignores the context
if 'show_save_and_continue' in context:
ctx['show_save_and_continue'] = context['show_save_and_continue']
if 'show_save' in context:
ctx['show_save'] = context['show_save']
return ctx
import admin_advanced # Don't delete
import admin_basic # Don't delete
| Patch django submit_row templatetag so it takes into account button config sent in context | Patch django submit_row templatetag so it takes into account button config sent in context
| Python | agpl-3.0 | tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador | ---
+++
@@ -21,6 +21,21 @@
# along with Portal del Investigador. If not, see
# <http://www.gnu.org/licenses/>.
#
+from django.contrib.admin.templatetags.admin_modify import register
+from django.contrib.admin.templatetags.admin_modify import submit_row as osr
+
+
+# If the developer wants to enable/disable the save buttons,
+# we want to give preference over Django's logic
+# https://github.com/django/django/blob/master/django/contrib/admin/templatetags/admin_modify.py#L23
+@register.inclusion_tag('admin/submit_line.html', takes_context=True)
+def submit_row(context):
+ ctx = osr(context) # Here is Django's logic => it ignores the context
+ if 'show_save_and_continue' in context:
+ ctx['show_save_and_continue'] = context['show_save_and_continue']
+ if 'show_save' in context:
+ ctx['show_save'] = context['show_save']
+ return ctx
import admin_advanced # Don't delete
import admin_basic # Don't delete |
6e43c5a69bd7b0291ef54d1936f64d0596189fa5 | userena/contrib/umessages/urls.py | userena/contrib/umessages/urls.py | from django.conf.urls import *
from userena.contrib.umessages import views as messages_views
from django.contrib.auth.decorators import login_required
urlpatterns = patterns('',
url(r'^compose/$',
messages_views.message_compose,
name='userena_umessages_compose'),
url(r'^compose/(?P<recipients>[\@\+\.\w-]+)/$',
messages_views.message_compose,
name='userena_umessages_compose_to'),
url(r'^reply/(?P<parent_id>[\d]+)/$',
messages_views.message_compose,
name='userena_umessages_reply'),
url(r'^view/(?P<username>[\@ \.\w-]+)/$',
login_required(messages_views.MessageDetailListView.as_view()),
name='userena_umessages_detail'),
url(r'^remove/$',
messages_views.message_remove,
name='userena_umessages_remove'),
url(r'^unremove/$',
messages_views.message_remove,
{'undo': True},
name='userena_umessages_unremove'),
url(r'^$',
login_required(messages_views.MessageListView.as_view()),
name='userena_umessages_list'),
)
| from django.conf.urls import *
from userena.contrib.umessages import views as messages_views
from django.contrib.auth.decorators import login_required
urlpatterns = patterns('',
url(r'^compose/$',
messages_views.message_compose,
name='userena_umessages_compose'),
url(r'^compose/(?P<recipients>[\@ \+\.\w-]+)/$',
messages_views.message_compose,
name='userena_umessages_compose_to'),
url(r'^reply/(?P<parent_id>[\d]+)/$',
messages_views.message_compose,
name='userena_umessages_reply'),
url(r'^view/(?P<username>[\@ \.\w-]+)/$',
login_required(messages_views.MessageDetailListView.as_view()),
name='userena_umessages_detail'),
url(r'^remove/$',
messages_views.message_remove,
name='userena_umessages_remove'),
url(r'^unremove/$',
messages_views.message_remove,
{'undo': True},
name='userena_umessages_unremove'),
url(r'^$',
login_required(messages_views.MessageListView.as_view()),
name='userena_umessages_list'),
)
| Allow spaces in username, cont'd: forgotten url pattern. | Allow spaces in username, cont'd: forgotten url pattern.
| Python | bsd-3-clause | ugoertz/django-userena,ugoertz/django-userena,ugoertz/django-userena | ---
+++
@@ -7,7 +7,7 @@
messages_views.message_compose,
name='userena_umessages_compose'),
- url(r'^compose/(?P<recipients>[\@\+\.\w-]+)/$',
+ url(r'^compose/(?P<recipients>[\@ \+\.\w-]+)/$',
messages_views.message_compose,
name='userena_umessages_compose_to'),
|
30bfe04e0fa1386e263cbd0e8dbc6f3689f9cb21 | connector_carepoint/migrations/9.0.1.3.0/pre-migrate.py | connector_carepoint/migrations/9.0.1.3.0/pre-migrate.py | # -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
def migrate(cr, version):
cr.execute('ALTER TABLE carepoint_medical_prescription_order_line '
'RENAME TO carepoint_rx_ord_ln')
cr.execute('ALTER TABLE carepoint_carepoint_organization '
'RENAME TO carepoint_org_bind')
| # -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
_logger = logging.getLogger(__name__)
def migrate(cr, version):
try:
cr.execute('ALTER TABLE carepoint_medical_prescription_order_line '
'RENAME TO carepoint_rx_ord_ln')
except Exception:
cr.rollback()
_logger.exception('Cannot perform migration')
try:
cr.execute('ALTER TABLE carepoint_carepoint_organization '
'RENAME TO carepoint_org_bind')
except Exception:
cr.rollback()
_logger.exception('Cannot perform migration')
| Fix prescription migration * Add try/catch & rollback to db alterations in case server re-upgrades | [FIX] connector_carepoint: Fix prescription migration
* Add try/catch & rollback to db alterations in case server re-upgrades
| Python | agpl-3.0 | laslabs/odoo-connector-carepoint | ---
+++
@@ -2,10 +2,22 @@
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
+import logging
+
+_logger = logging.getLogger(__name__)
+
def migrate(cr, version):
- cr.execute('ALTER TABLE carepoint_medical_prescription_order_line '
- 'RENAME TO carepoint_rx_ord_ln')
+ try:
+ cr.execute('ALTER TABLE carepoint_medical_prescription_order_line '
+ 'RENAME TO carepoint_rx_ord_ln')
+ except Exception:
+ cr.rollback()
+ _logger.exception('Cannot perform migration')
- cr.execute('ALTER TABLE carepoint_carepoint_organization '
- 'RENAME TO carepoint_org_bind')
+ try:
+ cr.execute('ALTER TABLE carepoint_carepoint_organization '
+ 'RENAME TO carepoint_org_bind')
+ except Exception:
+ cr.rollback()
+ _logger.exception('Cannot perform migration') |
259ac1bf6390c050892fa678842c1793e7f1dda0 | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
import unittest
from huey import tests
def _requirements_installed():
try:
import django
return True
except Exception:
return False
def run_tests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=1).run(suite)
if os.path.exists('huey.db'):
os.unlink('huey.db')
if result.failures:
sys.exit(1)
elif result.errors:
sys.exit(2)
def run_django_tests(*test_args):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "huey.contrib.djhuey.tests.settings")
from django.core.management import execute_from_command_line
args = sys.argv
args.insert(1, "test")
args.append('huey.contrib.djhuey.tests')
execute_from_command_line(args)
if __name__ == '__main__':
if not _requirements_installed():
print('Requirements are not installed. Run "pip install -r test_requirements.txt" to install all dependencies.')
sys.exit(2)
run_tests(*sys.argv[1:])
run_django_tests(*sys.argv[1:])
sys.exit(0)
| #!/usr/bin/env python
import os
import sys
import unittest
from huey import tests
def _requirements_installed():
try:
import django
return True
except Exception:
return False
def run_tests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=1).run(suite)
if os.path.exists('huey.db'):
os.unlink('huey.db')
if result.failures:
sys.exit(1)
elif result.errors:
sys.exit(2)
def run_django_tests(*test_args):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "huey.contrib.djhuey.tests.settings")
from django.core.management import execute_from_command_line
args = sys.argv
args.insert(1, "test")
args.append('huey.contrib.djhuey.tests')
execute_from_command_line(args)
if __name__ == '__main__':
run_tests(*sys.argv[1:])
if _requirements_installed():
run_django_tests(*sys.argv[1:])
else:
print('Django not installed, skipping Django tests.')
sys.exit(0)
| Allow running tests without Django. | Allow running tests without Django.
| Python | mit | coleifer/huey,rsalmaso/huey,pombredanne/huey | ---
+++
@@ -35,10 +35,10 @@
if __name__ == '__main__':
- if not _requirements_installed():
- print('Requirements are not installed. Run "pip install -r test_requirements.txt" to install all dependencies.')
- sys.exit(2)
run_tests(*sys.argv[1:])
- run_django_tests(*sys.argv[1:])
+ if _requirements_installed():
+ run_django_tests(*sys.argv[1:])
+ else:
+ print('Django not installed, skipping Django tests.')
sys.exit(0)
|
746cc719ce80636c19b2eea4b3d7328e680f7624 | 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).
"""
import logging
import os
import re
import yaml
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml')
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
LOGGING_LEVEL = logging.DEBUG
def get_csv_file_types():
csv_file_types = None
with open(SETTINGS_YAML_PATH) as r:
csv_file_types = yaml.load(r)
return csv_file_types
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
| """
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, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml')
#- file: %(pathname)s
# function: %(funcName)s
LOGGING_FORMAT = '''
- level: %(levelname)s
line: %(lineno)s
logger: %(name)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
LOGGING_LEVEL = logging.DEBUG
def get_csv_file_types():
csv_file_types = None
with open(SETTINGS_YAML_PATH) as r:
csv_file_types = yaml.load(r)
return csv_file_types
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
| Change file name to logger name in example settings | Change file name to logger name in example settings
| Python | mit | AustralianAntarcticDataCentre/save_emails_to_files,AustralianAntarcticDataCentre/save_emails_to_files | ---
+++
@@ -24,10 +24,12 @@
SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml')
+#- file: %(pathname)s
+# function: %(funcName)s
LOGGING_FORMAT = '''
-- file: %(pathname)s
- level: %(levelname)s
+- level: %(levelname)s
line: %(lineno)s
+ logger: %(name)s
message: |
%(message)s
time: %(asctime)s |
1ef0e4db1079995b5dd6a013d3fa51c1b61db178 | config-example.py | config-example.py | # Copy this file to config.py and change the settings. Don't forget to specify your own SECRET_KEY.
# The app name will be used in several places.
APP_NAME = 'Yelp Love'
APP_BASE_URL = 'https://PROJECT_ID.appspot.com/'
LOVE_SENDER_EMAIL = 'Yelp Love <love@PROJECT_ID.appspotmail.com>'
# Flask's secret key, used to encrypt the session cookie.
# Set this to any random string and make sure not to share this!
SECRET_KEY = 'YOUR_SECRET_HERE'
# Use default theme
THEME = 'default'
# Every employee needs a reference to a Google Account. This reference is based on the users
# Google Account email address and created when employee data is imported: we take the *username*
# and this DOMAIN
DOMAIN = 'example.com'
# Name of the S3 bucket used to import employee data from a file named employees.json
# Check out /import/employees.json.example to see how this file should look like.
S3_BUCKET = 'employees'
# When do we use Gravatar? Options are:
# * 'always' - prefers Gravatar over the Employee.photo_url
# * 'backup' - use Gravatar when photo_url is empty
# * anything else - disabled
GRAVATAR = 'backup'
ORG_TITLE = "Company"
| # Copy this file to config.py and change the settings. Don't forget to specify your own SECRET_KEY.
# The app name will be used in several places.
APP_NAME = 'Yelp Love'
APP_BASE_URL = 'https://PROJECT_ID.appspot.com/'
LOVE_SENDER_EMAIL = 'Yelp Love <love@PROJECT_ID.appspotmail.com>'
# Flask's secret key, used to encrypt the session cookie.
# Set this to any random string and make sure not to share this!
SECRET_KEY = 'YOUR_SECRET_HERE'
# Use default theme
THEME = 'default'
# Every employee needs a reference to a Google Account. This reference is based on the users
# Google Account email address and created when employee data is imported: we take the *username*
# and this DOMAIN
DOMAIN = 'example.com'
# Name of the S3 bucket used to import employee data from a file named employees.json
# Check out /import/employees.json.example to see how this file should look like.
S3_BUCKET = 'employees'
# When do we use Gravatar? Options are:
# * 'always' - prefers Gravatar over the Employee.photo_url
# * 'backup' - use Gravatar when photo_url is empty
# * anything else - disabled
GRAVATAR = 'backup'
ORG_TITLE = "All Company"
| Make ORG_TITLE the complete pre-existing title. | Make ORG_TITLE the complete pre-existing title. | Python | mit | Yelp/love,Yelp/love,Yelp/love | ---
+++
@@ -29,4 +29,4 @@
# * anything else - disabled
GRAVATAR = 'backup'
-ORG_TITLE = "Company"
+ORG_TITLE = "All Company" |
650c94107106cddafccaf5d2021a6407fcac990e | bend/src/users/jwt_util.py | bend/src/users/jwt_util.py | from jwt_auth.forms import JSONWebTokenForm
def loginUser(username, password):
"""Should login user and return a jwt token, piggyback on jwt_auth"""
request = {"username": username, "password": password}
form = JSONWebTokenForm(request)
if not form.is_valid():
return print("JWT form not valid")
context_dict = {
'token': form.object['token']
}
return context_dict
| from jwt_auth.forms import JSONWebTokenForm
def loginUser(username, password):
"""Should login user and return a jwt token, piggyback on jwt_auth"""
request = {"username": username, "password": password}
form = JSONWebTokenForm(request)
if not form.is_valid():
return print("JWT form not valid")
return form.object['token']
| Return the token string instead of object with string | Return the token string instead of object with string
| Python | mit | ncrmro/ango,ncrmro/reango,ncrmro/ango,ncrmro/reango,ncrmro/ango,ncrmro/reango | ---
+++
@@ -8,8 +8,4 @@
if not form.is_valid():
return print("JWT form not valid")
- context_dict = {
- 'token': form.object['token']
- }
-
- return context_dict
+ return form.object['token'] |
994e185e7bb8b2ffb78f20012121c441ea6b73a1 | comics/views.py | comics/views.py | from django.views import generic
from gallery.models import GalleryImage
from .models import Arc, Issue
class IndexView(generic.ListView):
model = Arc
template_name = "comics/index.html"
context_object_name = "arcs"
class IssueView(generic.DetailView):
model = Issue
template_name = "comics/issue.html"
class ComicPageView(generic.DetailView):
model = GalleryImage
template_name = "comics/comic_page.html"
def get_queryset(self):
query_set = (
super().get_queryset().filter(issue__slug=self.kwargs.get("issue_slug"))
)
return query_set
| from django.views import generic
from gallery.models import GalleryImage
from .models import Arc, Issue
class IndexView(generic.ListView):
model = Arc
template_name = "comics/index.html"
context_object_name = "arcs"
class IssueView(generic.DetailView):
model = Issue
template_name = "comics/issue.html"
def get_queryset(self):
query_set = super().get_queryset().filter(arc__slug=self.kwargs.get("arc_slug"))
return query_set
class ComicPageView(generic.DetailView):
model = GalleryImage
template_name = "comics/comic_page.html"
def get_queryset(self):
query_set = (
super().get_queryset().filter(issue__slug=self.kwargs.get("issue_slug"))
)
return query_set
| Fix bug where arc slug could be literally anything | Fix bug where arc slug could be literally anything
| Python | mit | evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca | ---
+++
@@ -14,6 +14,10 @@
model = Issue
template_name = "comics/issue.html"
+ def get_queryset(self):
+ query_set = super().get_queryset().filter(arc__slug=self.kwargs.get("arc_slug"))
+ return query_set
+
class ComicPageView(generic.DetailView):
model = GalleryImage |
d624a1e638cf6f1fca7b7d8966f3ab7c6c9f7300 | linter.py | linter.py | from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '${args}', '${file}')
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)?\s+'
r'((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):\s+'
r'(?P<message>.+)'
)
error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout
on_stderr = None # handle stderr via split_match
tempfile_suffix = '-'
defaults = {
'selector': 'source.c, source.c++',
'--std=,+': [], # example ['c99', 'c89']
'--enable=,': 'style',
}
def split_match(self, match):
"""
Return the components of the match.
We override this because included header files can cause linter errors,
and we only want errors from the linted file.
"""
if match:
if match.group('file') != self.filename:
return None
return super().split_match(match)
| from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = ('cppcheck', '--template={file}:{line}: {severity}: {message}', '--inline-suppr', '--quiet', '${args}', '${file}')
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)?\s+'
r'((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):\s+'
r'(?P<message>.+)'
)
error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout
on_stderr = None # handle stderr via split_match
tempfile_suffix = '-'
defaults = {
'selector': 'source.c, source.c++',
'--std=,+': [], # example ['c99', 'c89']
'--enable=,': 'style',
}
def split_match(self, match):
"""
Return the components of the match.
We override this because included header files can cause linter errors,
and we only want errors from the linted file.
"""
if match:
if match.group('file') != self.filename:
return None
return super().split_match(match)
| Use explicit template instead of 'gcc' | Use explicit template instead of 'gcc'
cppcheck 1.84 changed the meaning of --template=gcc to add a second line of output that confuses the linter plugin, so explicitly request the old format
see https://github.com/danmar/cppcheck/commit/f058d9ad083a6111e9339b4b3506c5da7db579e0 for the details of that change | Python | mit | SublimeLinter/SublimeLinter-cppcheck | ---
+++
@@ -2,7 +2,7 @@
class Cppcheck(Linter):
- cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '${args}', '${file}')
+ cmd = ('cppcheck', '--template={file}:{line}: {severity}: {message}', '--inline-suppr', '--quiet', '${args}', '${file}')
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)?\s+'
r'((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):\s+' |
2b81d198b7d3dd9094f47d2f8e51f0275ee31463 | osf/migrations/0084_migrate_node_info_for_target.py | osf/migrations/0084_migrate_node_info_for_target.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-13 16:14
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('osf', '0083_add_file_fields_for_target'),
]
operations = [
migrations.RunSQL(
["""
UPDATE osf_basefilenode
SET target_object_id = node_id;
UPDATE osf_basefilenode
SET target_content_type_id = (SELECT id FROM django_content_type WHERE app_label = 'osf' AND model = 'abstractnode');
"""], ["""
UPDATE osf_basefilenode
SET node_id = target_object_id;
"""]
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-13 16:14
from __future__ import unicode_literals
from django.db import migrations, models, connection
from django.contrib.contenttypes.models import ContentType
def set_basefilenode_target(apps, schema_editor):
BaseFileNode = apps.get_model('osf', 'basefilenode')
AbstractNode = apps.get_model('osf', 'abstractnode')
target_content_type_id = ContentType.objects.get_for_model(AbstractNode).id
BATCHSIZE = 5000
max_pk = BaseFileNode.objects.aggregate(models.Max('pk'))['pk__max']
if max_pk is not None:
for offset in range(0, max_pk + 1, BATCHSIZE):
(BaseFileNode.objects
.filter(pk__gte=offset)
.filter(pk__lt=offset + BATCHSIZE)
.filter(target_object_id__isnull=True)
.filter(target_content_type_id__isnull=True)
.update(
target_content_type_id=target_content_type_id,
target_object_id=models.F('node_id')
)
)
def reset_basefilenode_target_to_node(*args, **kwargs):
sql = "UPDATE osf_basefilenode SET node_id = target_object_id;"
with connection.cursor() as cursor:
cursor.execute(sql)
class Migration(migrations.Migration):
# Avoid locking basefilenode
atomic = False
dependencies = [
('osf', '0083_add_file_fields_for_target'),
]
operations = [
migrations.RunPython(set_basefilenode_target, reset_basefilenode_target_to_node),
]
| Use batches instead of raw sql for long migration | Use batches instead of raw sql for long migration
| Python | apache-2.0 | baylee-d/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,mattclark/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,adlius/osf.io,felliott/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,erinspace/osf.io,cslzchen/osf.io,aaxelb/osf.io,pattisdr/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,caseyrollins/osf.io,adlius/osf.io,mfraezz/osf.io,erinspace/osf.io,baylee-d/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,mfraezz/osf.io,adlius/osf.io,saradbowman/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,saradbowman/osf.io,caseyrollins/osf.io,caseyrollins/osf.io,aaxelb/osf.io,cslzchen/osf.io,pattisdr/osf.io,cslzchen/osf.io,felliott/osf.io,Johnetordoff/osf.io,felliott/osf.io,adlius/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io | ---
+++
@@ -2,25 +2,46 @@
# Generated by Django 1.11.4 on 2017-11-13 16:14
from __future__ import unicode_literals
-from django.db import migrations
+from django.db import migrations, models, connection
+from django.contrib.contenttypes.models import ContentType
+def set_basefilenode_target(apps, schema_editor):
+ BaseFileNode = apps.get_model('osf', 'basefilenode')
+ AbstractNode = apps.get_model('osf', 'abstractnode')
+ target_content_type_id = ContentType.objects.get_for_model(AbstractNode).id
+
+ BATCHSIZE = 5000
+
+ max_pk = BaseFileNode.objects.aggregate(models.Max('pk'))['pk__max']
+ if max_pk is not None:
+ for offset in range(0, max_pk + 1, BATCHSIZE):
+ (BaseFileNode.objects
+ .filter(pk__gte=offset)
+ .filter(pk__lt=offset + BATCHSIZE)
+ .filter(target_object_id__isnull=True)
+ .filter(target_content_type_id__isnull=True)
+ .update(
+ target_content_type_id=target_content_type_id,
+ target_object_id=models.F('node_id')
+ )
+ )
+
+
+def reset_basefilenode_target_to_node(*args, **kwargs):
+ sql = "UPDATE osf_basefilenode SET node_id = target_object_id;"
+ with connection.cursor() as cursor:
+ cursor.execute(sql)
+
class Migration(migrations.Migration):
+
+ # Avoid locking basefilenode
+ atomic = False
dependencies = [
('osf', '0083_add_file_fields_for_target'),
]
operations = [
- migrations.RunSQL(
- ["""
- UPDATE osf_basefilenode
- SET target_object_id = node_id;
- UPDATE osf_basefilenode
- SET target_content_type_id = (SELECT id FROM django_content_type WHERE app_label = 'osf' AND model = 'abstractnode');
- """], ["""
- UPDATE osf_basefilenode
- SET node_id = target_object_id;
- """]
- ),
+ migrations.RunPython(set_basefilenode_target, reset_basefilenode_target_to_node),
] |
d9d52d2ba93b29f04d1f0e6903a6a343718f7bce | Instanssi/dblog/models.py | Instanssi/dblog/models.py | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from Instanssi.kompomaatti.models import Event
class DBLogEntry(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
event = models.ForeignKey(Event, blank=True, null=True)
date = models.DateTimeField(auto_now_add=True)
module = models.CharField(max_length=64, blank=True)
level = models.CharField(max_length=10)
message = models.TextField()
def __unicode__(self):
if len(self.message) > 48:
return u' ...'.format(self.message[:48])
else:
return self.message
class Meta:
verbose_name = u"lokimerkintä"
verbose_name_plural = u"lokimerkinnät"
| # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from Instanssi.kompomaatti.models import Event
class DBLogEntry(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
event = models.ForeignKey(Event, blank=True, null=True)
date = models.DateTimeField(auto_now_add=True)
module = models.CharField(max_length=64, blank=True)
level = models.CharField(max_length=10)
message = models.TextField()
def __unicode__(self):
if len(self.message) > 64:
return u'{} ...'.format(self.message[:64])
else:
return self.message
class Meta:
verbose_name = u"lokimerkintä"
verbose_name_plural = u"lokimerkinnät"
| Fix log entry __unicode__ method functionality | dblog: Fix log entry __unicode__ method functionality
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | ---
+++
@@ -14,8 +14,8 @@
message = models.TextField()
def __unicode__(self):
- if len(self.message) > 48:
- return u' ...'.format(self.message[:48])
+ if len(self.message) > 64:
+ return u'{} ...'.format(self.message[:64])
else:
return self.message
|
77d3f60468fcf814c19d693e3401b1769e4993a9 | cob/cli/migrate_cli.py | cob/cli/migrate_cli.py | import click
import logbook
from .utils import appcontext_command
from ..ctx import context
import flask_migrate
_logger = logbook.Logger(__name__)
@click.group()
def migrate():
pass
@migrate.command()
@appcontext_command
def init():
flask_migrate.init('migrations', False)
@migrate.command()
@click.option('-m', '--message', default=None)
@appcontext_command
def revision(message):
if not context.db.metadata.tables:
_logger.warning('No tables loaded!')
flask_migrate.upgrade()
flask_migrate.revision(autogenerate=True, message=message)
@migrate.command()
@appcontext_command
def up():
flask_migrate.upgrade()
@migrate.command()
@appcontext_command
def down():
flask_migrate.upgrade()
| import click
import logbook
from .utils import appcontext_command
from ..ctx import context
import flask_migrate
_logger = logbook.Logger(__name__)
@click.group()
def migrate():
pass
@migrate.command()
@appcontext_command
def init():
flask_migrate.init('migrations', False)
@migrate.command()
@click.option('-m', '--message', default=None)
@appcontext_command
def revision(message):
if not context.db.metadata.tables:
_logger.warning('No tables loaded!')
flask_migrate.upgrade()
flask_migrate.revision(autogenerate=True, message=message)
@migrate.command()
@appcontext_command
def up():
flask_migrate.upgrade()
@migrate.command()
@appcontext_command
def down():
flask_migrate.downgrade()
| Fix typo in cob migrate down | Fix typo in cob migrate down
| Python | bsd-3-clause | getweber/weber-cli | ---
+++
@@ -37,4 +37,4 @@
@migrate.command()
@appcontext_command
def down():
- flask_migrate.upgrade()
+ flask_migrate.downgrade() |
56e2bea0798ae3afbc50d53947e505e7df9edba3 | config/invariant_checks.py | config/invariant_checks.py | from sts.invariant_checker import InvariantChecker
def check_for_loops_or_connectivity(simulation):
from sts.invariant_checker import InvariantChecker
result = InvariantChecker.check_loops(simulation)
if result:
return result
result = InvariantChecker.python_check_connectivity(simulation)
if not result:
print "Connectivity established - bailing out"
import sys
sys.exit(0)
return []
# Note: make sure to add new custom invariant checks to this dictionary!
name_to_invariant_check = {
"check_for_loops_or_connectivity" : check_for_loops_or_connectivity,
"InvariantChecker.check_liveness" : InvariantChecker.check_liveness,
"InvariantChecker.check_loops" : InvariantChecker.check_loops,
"InvariantChecker.python_check_connectivity" : InvariantChecker.python_check_connectivity,
"InvariantChecker.check_connectivity" : InvariantChecker.check_connectivity,
"InvariantChecker.check_blackholes" : InvariantChecker.check_blackholes,
"InvariantChecker.check_correspondence" : InvariantChecker.check_correspondence,
}
| from sts.invariant_checker import InvariantChecker
import sys
def bail_on_connectivity(simulation):
result = InvariantChecker.python_check_connectivity(simulation)
if not result:
print "Connectivity established - bailing out"
sys.exit(0)
return []
def check_for_loops_or_connectivity(simulation):
result = InvariantChecker.check_loops(simulation)
if result:
return result
return bail_on_connectivity(simulation)
def check_for_loops_blackholes_or_connectivity(simulation):
for check in [InvariantChecker.check_loops, InvariantChecker.check_blackholes]:
result = check(simulation)
if result:
return result
return bail_on_connectivity(simulation)
# Note: make sure to add new custom invariant checks to this dictionary!
name_to_invariant_check = {
"check_for_loops_or_connectivity" : check_for_loops_or_connectivity,
"check_for_loops_blackholes_or_connectivity" : check_for_loops_blackholes_or_connectivity,
"InvariantChecker.check_liveness" : InvariantChecker.check_liveness,
"InvariantChecker.check_loops" : InvariantChecker.check_loops,
"InvariantChecker.python_check_connectivity" : InvariantChecker.python_check_connectivity,
"InvariantChecker.check_connectivity" : InvariantChecker.check_connectivity,
"InvariantChecker.check_blackholes" : InvariantChecker.check_blackholes,
"InvariantChecker.check_correspondence" : InvariantChecker.check_correspondence,
}
| Add a new invariant check: check blackholes *or* loops | Add a new invariant check: check blackholes *or* loops
| Python | apache-2.0 | ucb-sts/sts,jmiserez/sts,jmiserez/sts,ucb-sts/sts | ---
+++
@@ -1,20 +1,30 @@
from sts.invariant_checker import InvariantChecker
+import sys
+
+def bail_on_connectivity(simulation):
+ result = InvariantChecker.python_check_connectivity(simulation)
+ if not result:
+ print "Connectivity established - bailing out"
+ sys.exit(0)
+ return []
def check_for_loops_or_connectivity(simulation):
- from sts.invariant_checker import InvariantChecker
result = InvariantChecker.check_loops(simulation)
if result:
return result
- result = InvariantChecker.python_check_connectivity(simulation)
- if not result:
- print "Connectivity established - bailing out"
- import sys
- sys.exit(0)
- return []
+ return bail_on_connectivity(simulation)
+
+def check_for_loops_blackholes_or_connectivity(simulation):
+ for check in [InvariantChecker.check_loops, InvariantChecker.check_blackholes]:
+ result = check(simulation)
+ if result:
+ return result
+ return bail_on_connectivity(simulation)
# Note: make sure to add new custom invariant checks to this dictionary!
name_to_invariant_check = {
"check_for_loops_or_connectivity" : check_for_loops_or_connectivity,
+ "check_for_loops_blackholes_or_connectivity" : check_for_loops_blackholes_or_connectivity,
"InvariantChecker.check_liveness" : InvariantChecker.check_liveness,
"InvariantChecker.check_loops" : InvariantChecker.check_loops,
"InvariantChecker.python_check_connectivity" : InvariantChecker.python_check_connectivity, |
d58c04d9745f1a0af46f35fba7b3e2aef704547e | application.py | application.py | import os
from flask import Flask
from whitenoise import WhiteNoise
from app import create_app
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static')
STATIC_URL = 'static/'
app = Flask('app')
create_app(app)
application = WhiteNoise(app, STATIC_ROOT, STATIC_URL)
| import os
from flask import Flask
from whitenoise import WhiteNoise
from app import create_app
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static')
STATIC_URL = 'static/'
app = Flask('app')
create_app(app)
app.wsgi_app = WhiteNoise(app.wsgi_app, STATIC_ROOT, STATIC_URL)
| Make Whitenoise serve static assets | Make Whitenoise serve static assets
Currently it’s not configured properly, so isn’t having any effect.
This change makes it wrap the Flask app, so it intercepts any requests
for static content.
Follows the pattern documented in http://whitenoise.evans.io/en/stable/flask.html#enable-whitenoise
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin | ---
+++
@@ -12,4 +12,4 @@
app = Flask('app')
create_app(app)
-application = WhiteNoise(app, STATIC_ROOT, STATIC_URL)
+app.wsgi_app = WhiteNoise(app.wsgi_app, STATIC_ROOT, STATIC_URL) |
7231111564145bdbc773ed2bb5479b6edc0c7426 | issues/admin.py | issues/admin.py | from django.contrib.admin import site, ModelAdmin
from .models import Issue, Jurisdiction, Service, Application
class ApplicationAdmin(ModelAdmin):
list_display = ('identifier', 'name', 'active')
list_filter = ('active',)
search_fields = ('identifier', 'name',)
def get_readonly_fields(self, request, obj=None):
fields = super().get_readonly_fields(request, obj)
if obj and obj.pk:
fields += ('key',)
return fields
site.register((Issue, Jurisdiction, Service))
site.register(Application, ApplicationAdmin)
| from django.contrib.admin import site, ModelAdmin
from parler.admin import TranslatableAdmin
from .models import Issue, Jurisdiction, Service, Application
class ApplicationAdmin(ModelAdmin):
list_display = ('identifier', 'name', 'active')
list_filter = ('active',)
search_fields = ('identifier', 'name',)
def get_readonly_fields(self, request, obj=None):
fields = super().get_readonly_fields(request, obj)
if obj and obj.pk:
fields += ('key',)
return fields
class ServiceAdmin(TranslatableAdmin):
list_display = ('service_code', 'service_name')
search_fields = ('translations__service_name',)
site.register((Issue, Jurisdiction))
site.register(Service, ServiceAdmin)
site.register(Application, ApplicationAdmin)
| Use a `TranslatableAdmin` for `Service`s | Use a `TranslatableAdmin` for `Service`s
Fixes #70
| Python | mit | 6aika/issue-reporting,6aika/issue-reporting,6aika/issue-reporting | ---
+++
@@ -1,4 +1,5 @@
from django.contrib.admin import site, ModelAdmin
+from parler.admin import TranslatableAdmin
from .models import Issue, Jurisdiction, Service, Application
@@ -7,7 +8,7 @@
list_display = ('identifier', 'name', 'active')
list_filter = ('active',)
search_fields = ('identifier', 'name',)
-
+
def get_readonly_fields(self, request, obj=None):
fields = super().get_readonly_fields(request, obj)
if obj and obj.pk:
@@ -15,5 +16,11 @@
return fields
-site.register((Issue, Jurisdiction, Service))
+class ServiceAdmin(TranslatableAdmin):
+ list_display = ('service_code', 'service_name')
+ search_fields = ('translations__service_name',)
+
+
+site.register((Issue, Jurisdiction))
+site.register(Service, ServiceAdmin)
site.register(Application, ApplicationAdmin) |
4d446f6b810fdb1a996ab9b65259c1212c6b951a | connect_to_postgres.py | connect_to_postgres.py | import os
import psycopg2
import urlparse
urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.environ["DATABASE_URL"])
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
cur = conn.cursor()
cur.execute("SELECT * FROM pitches LIMIT 10;")
print cur.fetchone()
cur.close()
conn.close() | import os
import psycopg2
import urlparse
# urlparse.uses_netloc.append("postgres")
# url = urlparse.urlparse(os.environ["DATABASE_URL"])
# conn = psycopg2.connect(
# database=url.path[1:],
# user=url.username,
# password=url.password,
# host=url.hostname,
# port=url.port
# )
# cur = conn.cursor()
# cur.execute("SELECT * FROM pitches LIMIT 10;")
# print cur.fetchone()
# cur.close()
# conn.close()
def run_query(query):
urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.environ["DATABASE_URL"])
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
cur = conn.cursor()
cur.execute(query)
result = cur.fetchone()
cur.close()
conn.close()
return result
query = "SELECT * FROM pitches LIMIT 10;"
query_result = run_query(query)
print query_result | Test functional version of connecting to postgres | Test functional version of connecting to postgres
| Python | mit | gsganden/pitcher-reports,gsganden/pitcher-reports | ---
+++
@@ -2,23 +2,49 @@
import psycopg2
import urlparse
-urlparse.uses_netloc.append("postgres")
-url = urlparse.urlparse(os.environ["DATABASE_URL"])
+# urlparse.uses_netloc.append("postgres")
+# url = urlparse.urlparse(os.environ["DATABASE_URL"])
-conn = psycopg2.connect(
- database=url.path[1:],
- user=url.username,
- password=url.password,
- host=url.hostname,
- port=url.port
-)
+# conn = psycopg2.connect(
+# database=url.path[1:],
+# user=url.username,
+# password=url.password,
+# host=url.hostname,
+# port=url.port
+# )
+# cur = conn.cursor()
+# cur.execute("SELECT * FROM pitches LIMIT 10;")
+# print cur.fetchone()
-cur = conn.cursor()
+# cur.close()
+# conn.close()
-cur.execute("SELECT * FROM pitches LIMIT 10;")
-print cur.fetchone()
+def run_query(query):
+ urlparse.uses_netloc.append("postgres")
+ url = urlparse.urlparse(os.environ["DATABASE_URL"])
-cur.close()
-conn.close()
+ conn = psycopg2.connect(
+ database=url.path[1:],
+ user=url.username,
+ password=url.password,
+ host=url.hostname,
+ port=url.port
+ )
+
+ cur = conn.cursor()
+
+ cur.execute(query)
+ result = cur.fetchone()
+
+ cur.close()
+ conn.close()
+
+ return result
+
+query = "SELECT * FROM pitches LIMIT 10;"
+
+query_result = run_query(query)
+
+print query_result |
5839e70f2ffab6640997e3a609a26e50ff2b4da6 | opps/containers/urls.py | opps/containers/urls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.conf import settings
from django.views.decorators.cache import cache_page
from .views import ContainerList, ContainerDetail
from .views import Search
from opps.contrib.feeds.views import ContainerFeed, ChannelFeed
urlpatterns = patterns(
'',
url(r'^$', ContainerList.as_view(), name='home'),
url(r'^(rss|feed)$', cache_page(settings.OPPS_CACHE_EXPIRE)(
ContainerFeed()), name='feed'),
url(r'^search/', Search(), name='search'),
url(r'^(?P<long_slug>[\w\b//-]+)/(rss|feed)$',
cache_page(settings.OPPS_CACHE_EXPIRE)(
ChannelFeed()), name='channel_feed'),
url(r'^(?P<channel__long_slug>[\w//-]+)/(?P<slug>[\w-]+)$',
cache_page(settings.OPPS_CACHE_EXPIRE_DETAIL)(
ContainerDetail.as_view()), name='open'),
url(r'^(?P<channel__long_slug>[\w\b//-]+)/$',
cache_page(settings.OPPS_CACHE_EXPIRE_LIST)(
ContainerList.as_view()), name='channel'),
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.conf import settings
from django.views.decorators.cache import cache_page
from .views import ContainerList, ContainerDetail
from .views import ContainerAPIList, ContainerAPIDetail
from .views import Search
from opps.contrib.feeds.views import ContainerFeed, ChannelFeed
urlpatterns = patterns(
'',
url(r'^$', ContainerList.as_view(), name='home'),
url(r'^(rss|feed)$', cache_page(settings.OPPS_CACHE_EXPIRE)(
ContainerFeed()), name='feed'),
url(r'^search/', Search(), name='search'),
url(r'^(?P<long_slug>[\w\b//-]+)/(rss|feed)$',
cache_page(settings.OPPS_CACHE_EXPIRE)(
ChannelFeed()), name='channel_feed'),
url(r'^(?P<channel__long_slug>[\w//-]+)/(?P<slug>[\w-]+).api$',
cache_page(settings.OPPS_CACHE_EXPIRE_DETAIL)(
ContainerAPIDetail.as_view()), name='open-api'),
url(r'^(?P<channel__long_slug>[\w//-]+)/(?P<slug>[\w-]+)$',
cache_page(settings.OPPS_CACHE_EXPIRE_DETAIL)(
ContainerDetail.as_view()), name='open'),
url(r'^(?P<channel__long_slug>[\w\b//-]+).api$',
cache_page(settings.OPPS_CACHE_EXPIRE_LIST)(
ContainerAPIList.as_view()), name='channel-api'),
url(r'^(?P<channel__long_slug>[\w\b//-]+)/$',
cache_page(settings.OPPS_CACHE_EXPIRE_LIST)(
ContainerList.as_view()), name='channel'),
)
| Add url entry container api | Add url entry container api
| Python | mit | jeanmask/opps,williamroot/opps,opps/opps,opps/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,YACOWS/opps | ---
+++
@@ -5,6 +5,7 @@
from django.views.decorators.cache import cache_page
from .views import ContainerList, ContainerDetail
+from .views import ContainerAPIList, ContainerAPIDetail
from .views import Search
from opps.contrib.feeds.views import ContainerFeed, ChannelFeed
@@ -22,10 +23,16 @@
cache_page(settings.OPPS_CACHE_EXPIRE)(
ChannelFeed()), name='channel_feed'),
+ url(r'^(?P<channel__long_slug>[\w//-]+)/(?P<slug>[\w-]+).api$',
+ cache_page(settings.OPPS_CACHE_EXPIRE_DETAIL)(
+ ContainerAPIDetail.as_view()), name='open-api'),
url(r'^(?P<channel__long_slug>[\w//-]+)/(?P<slug>[\w-]+)$',
cache_page(settings.OPPS_CACHE_EXPIRE_DETAIL)(
ContainerDetail.as_view()), name='open'),
+ url(r'^(?P<channel__long_slug>[\w\b//-]+).api$',
+ cache_page(settings.OPPS_CACHE_EXPIRE_LIST)(
+ ContainerAPIList.as_view()), name='channel-api'),
url(r'^(?P<channel__long_slug>[\w\b//-]+)/$',
cache_page(settings.OPPS_CACHE_EXPIRE_LIST)(
ContainerList.as_view()), name='channel'), |
959c317f9929dc781d9ad08611896963f1bc3172 | zou/app/blueprints/crud/notifications.py | zou/app/blueprints/crud/notifications.py | from zou.app.models.notifications import Notification
from zou.app.utils import permissions
from .base import BaseModelResource, BaseModelsResource
class NotificationsResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, Notification)
def check_create_permissions(self, data):
return permissions.check_admin_permissions()
class NotificationResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, NotificationResource)
def check_read_permissions(self, instance):
return permissions.check_admin_permissions()
def check_update_permissions(self, instance, data):
return permissions.check_admin_permissions()
def check_delete_permissions(self, instance):
return permissions.check_admin_permissions()
| from zou.app.models.notifications import Notification
from zou.app.utils import permissions
from .base import BaseModelResource, BaseModelsResource
class NotificationsResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, Notification)
def check_create_permissions(self, data):
return permissions.check_admin_permissions()
class NotificationResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, Notification)
def check_read_permissions(self, instance):
return permissions.check_admin_permissions()
def check_update_permissions(self, instance, data):
return permissions.check_admin_permissions()
def check_delete_permissions(self, instance):
return permissions.check_admin_permissions()
| Fix crud controller for notifacation | Fix crud controller for notifacation
It was not possible to get, update or retrieve a notification
| Python | agpl-3.0 | cgwire/zou | ---
+++
@@ -16,7 +16,7 @@
class NotificationResource(BaseModelResource):
def __init__(self):
- BaseModelResource.__init__(self, NotificationResource)
+ BaseModelResource.__init__(self, Notification)
def check_read_permissions(self, instance):
return permissions.check_admin_permissions() |
adc76c9a629cb9f6e70ea1780351304dfba16197 | pcad/gen.py | pcad/gen.py | from genshi.template import TemplateLoader
import os
import sys
if len(sys.argv) < 2:
print("I need the name of a file as the first argument!")
exit(1)
loader = TemplateLoader(os.path.dirname(__file__))
tmpl = loader.load(sys.argv[1])
print(tmpl.generate(r_outer=100,
r_inner=25,
spacing=3,
num_clicks=16,
flip=True,
debug=False))
| from genshi.template import TemplateLoader
import os
import sys
if len(sys.argv) < 2:
print("I need the name of a file as the first argument!")
exit(1)
loader = TemplateLoader(os.path.dirname(__file__))
tmpl = loader.load(sys.argv[1])
print(tmpl.generate(r_outer=100,
r_inner=25,
spacing=6,
num_clicks=16,
flip=True,
debug=False))
| Increase spacing for quadrature encoders | Increase spacing for quadrature encoders
| Python | mit | WesleyAC/toybox,WesleyAC/toybox,WesleyAC/toybox,WesleyAC/toybox,WesleyAC/toybox | ---
+++
@@ -10,7 +10,7 @@
tmpl = loader.load(sys.argv[1])
print(tmpl.generate(r_outer=100,
r_inner=25,
- spacing=3,
+ spacing=6,
num_clicks=16,
flip=True,
debug=False)) |
6c1b81705beeaf9981deb2890382622026a37ba9 | app/redidropper/startup/initializer.py | app/redidropper/startup/initializer.py | # Goal: Init the application routes and read the settings
#
# @authors:
# Andrei Sura <sura.andrei@gmail.com>
# Ruchi Vivek Desai <ruchivdesai@gmail.com>
# Sanath Pasumarthy <sanath@ufl.edu>
from flask_user import UserManager, SQLAlchemyAdapter
import logging
def do_init(app, db, extra_settings={}):
"""
Initialize the app
@see run.py
"""
# Load content from 'redidropper/startup/settings.py' file
app.config.from_object('redidropper.startup.settings')
# Override with special settings (example: tests/conftest.py)
app.config.update(extra_settings)
# load routes
from redidropper.routes import pages
from redidropper.routes import users
from redidropper.routes import api
# load models
#from redidropper.models import UserEntity
#from redidropper.models import UserAuthEntity
return app
| # Goal: Init the application routes and read the settings
#
# @authors:
# Andrei Sura <sura.andrei@gmail.com>
# Ruchi Vivek Desai <ruchivdesai@gmail.com>
# Sanath Pasumarthy <sanath@ufl.edu>
from flask_user import UserManager, SQLAlchemyAdapter
import logging
from logging import Formatter
def do_init(app, db, extra_settings={}):
"""
Initialize the app
@see run.py
"""
# Load content from 'redidropper/startup/settings.py' file
app.config.from_object('redidropper.startup.settings')
# Override with special settings (example: tests/conftest.py)
app.config.update(extra_settings)
# load routes
from redidropper.routes import pages
from redidropper.routes import users
from redidropper.routes import api
# load models
#from redidropper.models import UserEntity
#from redidropper.models import UserAuthEntity
configure_logging(app)
return app
def configure_logging(app):
"""
Set the log location and formatting
@see http://flask.pocoo.org/docs/0.10/errorhandling/
"""
handler = logging.StreamHandler()
fmt = Formatter(
'%(asctime)s %(levelname)s: %(message)s ' \
'[in %(pathname)s:%(lineno)d]'
)
handler.setFormatter(fmt)
if app.debug:
handler.setLevel(logging.DEBUG)
app.logger.addHandler(handler)
| Call `configure_logging` to enable more debug information | Call `configure_logging` to enable more debug information
| Python | bsd-3-clause | indera/redi-dropper-client,indera/redi-dropper-client,indera/redi-dropper-client,indera/redi-dropper-client,indera/redi-dropper-client | ---
+++
@@ -7,7 +7,7 @@
from flask_user import UserManager, SQLAlchemyAdapter
import logging
-
+from logging import Formatter
def do_init(app, db, extra_settings={}):
"""
@@ -30,5 +30,21 @@
#from redidropper.models import UserEntity
#from redidropper.models import UserAuthEntity
+ configure_logging(app)
+ return app
- return app
+def configure_logging(app):
+ """
+ Set the log location and formatting
+ @see http://flask.pocoo.org/docs/0.10/errorhandling/
+ """
+ handler = logging.StreamHandler()
+ fmt = Formatter(
+ '%(asctime)s %(levelname)s: %(message)s ' \
+ '[in %(pathname)s:%(lineno)d]'
+ )
+ handler.setFormatter(fmt)
+ if app.debug:
+ handler.setLevel(logging.DEBUG)
+
+ app.logger.addHandler(handler) |
0cf393c9bafbe99e29a76cf289f34ac8edcc9416 | pianette/PianetteApi.py | pianette/PianetteApi.py | # coding: utf-8
from pianette.utils import Debug
from flask import Flask, render_template, request
from threading import Thread
app = Flask(__name__, template_folder='../templates')
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
@app.route('/', methods = ['GET'])
def home():
return render_template('index.html', url_root=request.url_root)
@app.route('/console/play', methods = ['POST'])
def console_play():
command = "console.play %s" % (request.form.get('command'))
app.pianette.inputcmds(command, source="api")
return ('1', 200)
class PianetteApi:
def __init__(self, configobj=None, pianette=None, **kwargs):
super().__init__(**kwargs)
self.configobj = configobj
app.pianette = pianette
Debug.println("INFO", "Starting API thread")
t = Thread(target=self.startApi)
t.daemon = True
t.start()
def startApi(self):
app.run(debug=False, threaded=True)
| # coding: utf-8
from pianette.utils import Debug
from flask import Flask, render_template, request
from threading import Thread
app = Flask(__name__, template_folder='../templates')
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
@app.route('/', methods = ['GET'])
def home():
return render_template('index.html', url_root=request.url_root)
@app.route('/console/play', methods = ['POST'])
def console_play():
command = "console.play %s" % (request.form.get('command'))
app.pianette.inputcmds(command, source="api")
return ('1', 200)
class PianetteApi:
def __init__(self, configobj=None, pianette=None, **kwargs):
super().__init__(**kwargs)
self.configobj = configobj
app.pianette = pianette
Debug.println("INFO", "Starting API thread")
t = Thread(target=self.startApi)
t.daemon = True
t.start()
def startApi(self):
app.run(debug=False, threaded=True, host=0.0.0.0)
| Add external IP for Flask | Add external IP for Flask
| Python | mit | tchapi/pianette,tchapi/pianette,tchapi/pianette,tchapi/pianette | ---
+++
@@ -32,4 +32,4 @@
t.start()
def startApi(self):
- app.run(debug=False, threaded=True)
+ app.run(debug=False, threaded=True, host=0.0.0.0) |
2205ea40f64b09f611b7f6cb4c9716d8e29136d4 | grammpy/Rule.py | grammpy/Rule.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
class Rule:
pass
| #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from grammpy import EPSILON
class Rule:
right = [EPSILON]
left = [EPSILON]
rule = ([EPSILON], [EPSILON])
rules = [([EPSILON], [EPSILON])]
def is_regular(self):
return False
def is_contextfree(self):
return False
def is_context(self):
return False
def is_unrestricted(self):
return False
| Add base interface for rule | Add base interface for rule
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -7,6 +7,23 @@
"""
+from grammpy import EPSILON
+
class Rule:
- pass
+ right = [EPSILON]
+ left = [EPSILON]
+ rule = ([EPSILON], [EPSILON])
+ rules = [([EPSILON], [EPSILON])]
+
+ def is_regular(self):
+ return False
+
+ def is_contextfree(self):
+ return False
+
+ def is_context(self):
+ return False
+
+ def is_unrestricted(self):
+ return False |
0ea263fa9a496d8dbd8ff3f966cc23eba170842c | django_mfa/models.py | django_mfa/models.py | from django.db import models
from django.conf import settings
class UserOTP(models.Model):
OTP_TYPES = (
('HOTP', 'hotp'),
('TOTP', 'totp'),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL)
otp_type = models.CharField(max_length=20, choices=OTP_TYPES)
secret_key = models.CharField(max_length=100, blank=True)
def is_mfa_enabled(user):
try:
user_otp = user.userotp
return True
except:
return False
| from django.conf import settings
from django.db import models
class UserOTP(models.Model):
OTP_TYPES = (
('HOTP', 'hotp'),
('TOTP', 'totp'),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL)
otp_type = models.CharField(max_length=20, choices=OTP_TYPES)
secret_key = models.CharField(max_length=100, blank=True)
def is_mfa_enabled(user):
"""
Determine if a user has MFA enabled
"""
return hasattr(user, 'userotp')
| Remove try/except from determing if mfa is enabled | Remove try/except from determing if mfa is enabled
| Python | mit | MicroPyramid/django-mfa,MicroPyramid/django-mfa,MicroPyramid/django-mfa | ---
+++
@@ -1,12 +1,12 @@
+from django.conf import settings
from django.db import models
-from django.conf import settings
class UserOTP(models.Model):
OTP_TYPES = (
- ('HOTP', 'hotp'),
- ('TOTP', 'totp'),
+ ('HOTP', 'hotp'),
+ ('TOTP', 'totp'),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL)
@@ -15,8 +15,7 @@
def is_mfa_enabled(user):
- try:
- user_otp = user.userotp
- return True
- except:
- return False
+ """
+ Determine if a user has MFA enabled
+ """
+ return hasattr(user, 'userotp') |
2bdbcf41cc99f9c7430f8d429cc8d2a5e2ee6701 | pyrho/NEURON/minimal.py | pyrho/NEURON/minimal.py | # minNEURON.py
cell = h.SectionList()
soma = h.Section(name='soma') #create soma
soma.push()
#h.topology()
# Geometry
soma.nseg = 1
soma.L = 20
soma.diam = 20
# Biophysics
for sec in h.allsec():
sec.Ra = 100
sec.cm = 1
sec.insert('pas')
#sec.insert('hh') # insert hh
cell.append(sec)
#h('objref rho')
#h('rho = new ChR(0.5)')
#h.rho.Er = Prot.phis[0]
#setattr(h.rho, 'del', Prot.pulses[0][0]) # rho.del will not work because del is reserved word in python
#h.rho.ton = Prot.onDs[0]
#h.rho.toff = Prot.offDs[0]
#h.rho.num = Prot.nPulses
#h.rho.gbar = RhO.g/20000
# Pick a rhodopsin to record from
#rhoRec = h.ChR_apic.o(7)
h.pop_section()
return cell | # minNEURON.py
from neuron import h
cell = h.SectionList()
soma = h.Section(name='soma') #create soma
soma.push()
#h.topology()
# Geometry
soma.nseg = 1
soma.L = 20
soma.diam = 20
# Biophysics
for sec in h.allsec():
sec.Ra = 100
sec.cm = 1
sec.insert('pas')
#sec.insert('hh') # insert hh
cell.append(sec)
#h('objref rho')
#h('rho = new ChR(0.5)')
#h.rho.Er = Prot.phis[0]
#setattr(h.rho, 'del', Prot.pulses[0][0]) # rho.del will not work because del is reserved word in python
#h.rho.ton = Prot.onDs[0]
#h.rho.toff = Prot.offDs[0]
#h.rho.num = Prot.nPulses
#h.rho.gbar = RhO.g/20000
# Pick a rhodopsin to record from
#rhoRec = h.ChR_apic.o(7)
h.pop_section()
#return cell | Add import to stop warnings | Add import to stop warnings
| Python | bsd-3-clause | ProjectPyRhO/PyRhO,ProjectPyRhO/PyRhO | ---
+++
@@ -1,4 +1,5 @@
# minNEURON.py
+from neuron import h
cell = h.SectionList()
soma = h.Section(name='soma') #create soma
@@ -36,4 +37,4 @@
-return cell
+#return cell |
800d69acf0e7a68d39e0e258258b750d3b8e0ace | debugtools/__init__.py | debugtools/__init__.py | # following PEP 386
__version__ = "1.2"
VERSION = (1, 2)
# Make sure the ``{% print %}`` is always available, even without a {% load debug_tags %} call.
# **NOTE** this uses the undocumented, unofficial add_to_builtins() call. It's not promoted
# by Django developers because it's better to be explicit with a {% load .. %} in the templates.
#
# This function is used here nevertheless because the {% print %} tag is a debugging aid,
# and not a tag that should remain permanently in your templates. Convenience is preferred here.
#
from django.template.loader import add_to_builtins
add_to_builtins("debugtools.templatetags.debug_tags")
| # following PEP 386
__version__ = "1.2"
VERSION = (1, 2)
# Make sure the ``{% print %}`` is always available, even without a {% load debug_tags %} call.
# **NOTE** this uses the undocumented, unofficial add_to_builtins() call. It's not promoted
# by Django developers because it's better to be explicit with a {% load .. %} in the templates.
#
# This function is used here nevertheless because the {% print %} tag is a debugging aid,
# and not a tag that should remain permanently in your templates. Convenience is preferred here.
#
from django.template.base import add_to_builtins
add_to_builtins("debugtools.templatetags.debug_tags")
| Fix add_to_builtins import for Django 1.7 support | Fix add_to_builtins import for Django 1.7 support
Older Django versions also use this location already.
| Python | apache-2.0 | edoburu/django-debugtools,edoburu/django-debugtools,edoburu/django-debugtools | ---
+++
@@ -10,5 +10,5 @@
# This function is used here nevertheless because the {% print %} tag is a debugging aid,
# and not a tag that should remain permanently in your templates. Convenience is preferred here.
#
-from django.template.loader import add_to_builtins
+from django.template.base import add_to_builtins
add_to_builtins("debugtools.templatetags.debug_tags") |
be16b3c2b67f160e46ed951a8e9e691bc09b8d05 | easypyplot/pdf.py | easypyplot/pdf.py | """
* Copyright (c) 2016. Mingyu Gao
* All rights reserved.
*
"""
import matplotlib.backends.backend_pdf
from .format import paper_plot
def plot_setup(name, dims, fontsize=9):
""" Setup a PDF page for plot.
name: PDF file name. If not ending with .pdf, will automatically append.
dims: dimension of the plot in inches, should be an array of length two.
fontsize: fontsize for legends and labels.
"""
paper_plot(fontsize)
if not name.endswith('.pdf'):
name += '.pdf'
pdfpage = matplotlib.backends.backend_pdf.PdfPages(name)
fig = matplotlib.pyplot.figure(figsize=dims)
return pdfpage, fig
def plot_teardown(pdfpage):
""" Tear down a PDF page after plotting.
pdfpage: PDF page.
"""
pdfpage.savefig()
pdfpage.close()
| """
* Copyright (c) 2016. Mingyu Gao
* All rights reserved.
*
"""
from contextlib import contextmanager
import matplotlib.backends.backend_pdf
from .format import paper_plot
def plot_setup(name, figsize=None, fontsize=9):
""" Setup a PDF page for plot.
name: PDF file name. If not ending with .pdf, will automatically append.
figsize: dimension of the plot in inches, should be an array of length two.
fontsize: fontsize for legends and labels.
"""
paper_plot(fontsize)
if not name.endswith('.pdf'):
name += '.pdf'
pdfpage = matplotlib.backends.backend_pdf.PdfPages(name)
fig = matplotlib.pyplot.figure(figsize=figsize)
return pdfpage, fig
def plot_teardown(pdfpage):
""" Tear down a PDF page after plotting.
pdfpage: PDF page.
"""
pdfpage.savefig()
pdfpage.close()
@contextmanager
def plot_open(name, figsize=None, fontsize=9):
""" Open a context of PDF page for plot, used for the `with` statement.
name: PDF file name. If not ending with .pdf, will automatically append.
figsize: dimension of the plot in inches, should be an array of length two.
fontsize: fontsize for legends and labels.
"""
pdfpage, fig = plot_setup(name, figsize=figsize, fontsize=fontsize)
yield fig
plot_teardown(pdfpage)
| Add a context manager for PDF plot. | Add a context manager for PDF plot.
| Python | bsd-3-clause | gaomy3832/easypyplot,gaomy3832/easypyplot | ---
+++
@@ -3,22 +3,23 @@
* All rights reserved.
*
"""
+from contextlib import contextmanager
import matplotlib.backends.backend_pdf
+
from .format import paper_plot
-
-def plot_setup(name, dims, fontsize=9):
+def plot_setup(name, figsize=None, fontsize=9):
""" Setup a PDF page for plot.
name: PDF file name. If not ending with .pdf, will automatically append.
- dims: dimension of the plot in inches, should be an array of length two.
+ figsize: dimension of the plot in inches, should be an array of length two.
fontsize: fontsize for legends and labels.
"""
paper_plot(fontsize)
if not name.endswith('.pdf'):
name += '.pdf'
pdfpage = matplotlib.backends.backend_pdf.PdfPages(name)
- fig = matplotlib.pyplot.figure(figsize=dims)
+ fig = matplotlib.pyplot.figure(figsize=figsize)
return pdfpage, fig
@@ -31,3 +32,15 @@
pdfpage.close()
+@contextmanager
+def plot_open(name, figsize=None, fontsize=9):
+ """ Open a context of PDF page for plot, used for the `with` statement.
+
+ name: PDF file name. If not ending with .pdf, will automatically append.
+ figsize: dimension of the plot in inches, should be an array of length two.
+ fontsize: fontsize for legends and labels.
+ """
+ pdfpage, fig = plot_setup(name, figsize=figsize, fontsize=fontsize)
+ yield fig
+ plot_teardown(pdfpage)
+ |
792d0ace4f84023d1132f8d61a88bd48e3d7775d | test/contrib/test_pyopenssl.py | test/contrib/test_pyopenssl.py | from nose.plugins.skip import SkipTest
from urllib3.packages import six
if six.PY3:
raise SkipTest('Testing of PyOpenSSL disabled on PY3')
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
except ImportError as e:
raise SkipTest('Could not import PyOpenSSL: %r' % e)
from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1
from ..with_dummyserver.test_socketlevel import TestSNI, TestSocketClosing
def setup_module():
inject_into_urllib3()
def teardown_module():
extract_from_urllib3()
| from nose.plugins.skip import SkipTest
from urllib3.packages import six
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3,
extract_from_urllib3)
except ImportError as e:
raise SkipTest('Could not import PyOpenSSL: %r' % e)
from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1
from ..with_dummyserver.test_socketlevel import TestSNI, TestSocketClosing
def setup_module():
inject_into_urllib3()
def teardown_module():
extract_from_urllib3()
| Enable PyOpenSSL testing on Python 3. | Enable PyOpenSSL testing on Python 3.
| Python | mit | Lukasa/urllib3,haikuginger/urllib3,Disassem/urllib3,urllib3/urllib3,Disassem/urllib3,haikuginger/urllib3,urllib3/urllib3,sigmavirus24/urllib3,sigmavirus24/urllib3,Lukasa/urllib3 | ---
+++
@@ -1,8 +1,5 @@
from nose.plugins.skip import SkipTest
from urllib3.packages import six
-
-if six.PY3:
- raise SkipTest('Testing of PyOpenSSL disabled on PY3')
try:
from urllib3.contrib.pyopenssl import (inject_into_urllib3, |
ad4ecad2e5785ddeb7bbd595e59dc12345c4b256 | xbob/blitz/__init__.py | xbob/blitz/__init__.py | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Fri 20 Sep 14:45:01 2013
"""Blitz++ Array bindings for Python"""
import pkg_resources
from ._library import array, as_blitz
from . import version
from .version import module as __version__
from .version import api as __api_version__
def get_include():
"""Returns the directory containing the C/C++ API include directives"""
return pkg_resources.resource_filename(__name__, 'include')
def get_config():
"""Returns a string containing the configuration information.
"""
from .version import externals
packages = pkg_resources.require(__name__)
this = packages[0]
deps = packages[1:]
retval = "%s: %s (%s)\n" % (this.key, this.version, this.location)
retval += " - c/c++ dependencies:\n"
for k in sorted(externals): retval += " - %s: %s\n" % (k, externals[k])
retval += " - python dependencies:\n"
for d in deps: retval += " - %s: %s (%s)\n" % (d.key, d.version, d.location)
return retval.strip()
# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')]
| #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Fri 20 Sep 14:45:01 2013
"""Blitz++ Array bindings for Python"""
import pkg_resources
from ._library import array, as_blitz
from . import version
from .version import module as __version__
from .version import api as __api_version__
def get_include():
"""Returns the directory containing the C/C++ API include directives"""
return pkg_resources.resource_filename(__name__, 'include')
def get_config():
"""Returns a string containing the configuration information.
"""
from .version import externals
packages = pkg_resources.require(__name__)
this = packages[0]
deps = packages[1:]
retval = "%s: %s [api=0x%04x] (%s)\n" % (this.key, this.version,
version.api, this.location)
retval += " - c/c++ dependencies:\n"
for k in sorted(externals): retval += " - %s: %s\n" % (k, externals[k])
retval += " - python dependencies:\n"
for d in deps: retval += " - %s: %s (%s)\n" % (d.key, d.version, d.location)
return retval.strip()
# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')]
| Add API number in get_config() | Add API number in get_config()
| Python | bsd-3-clause | tiagofrepereira2012/bob.blitz,tiagofrepereira2012/bob.blitz,tiagofrepereira2012/bob.blitz | ---
+++
@@ -27,7 +27,8 @@
this = packages[0]
deps = packages[1:]
- retval = "%s: %s (%s)\n" % (this.key, this.version, this.location)
+ retval = "%s: %s [api=0x%04x] (%s)\n" % (this.key, this.version,
+ version.api, this.location)
retval += " - c/c++ dependencies:\n"
for k in sorted(externals): retval += " - %s: %s\n" % (k, externals[k])
retval += " - python dependencies:\n" |
0388ab2bb8ad50aa40716a1c5f83f5e1f400bb32 | scripts/start_baxter.py | scripts/start_baxter.py | #!/usr/bin/python
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
s.move_loop()
if __name__ == "__main__":
main()
| #!/usr/bin/python
import time
import rospy
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
while not rospy.is_shutdown():
s.step()
if __name__ == "__main__":
main()
| Enable ctrl-c control with rospy | Enable ctrl-c control with rospy
| Python | mit | ipab-rad/baxter_myo,ipab-rad/myo_baxter_pc,ipab-rad/myo_baxter_pc,ipab-rad/baxter_myo | ---
+++
@@ -1,4 +1,6 @@
#!/usr/bin/python
+import time
+import rospy
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
@@ -8,7 +10,8 @@
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
- s.move_loop()
+ while not rospy.is_shutdown():
+ s.step()
if __name__ == "__main__":
main() |
f198941de6191ef9f729d1d8758c588654598f48 | runtests.py | runtests.py | #!/usr/bin/env python
from __future__ import unicode_literals
import os, sys
import six
try:
from django.conf import settings
except ImportError:
print("Django has not been installed.")
sys.exit(0)
if not settings.configured:
settings.configure(
INSTALLED_APPS=["jstemplate"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3"}})
def runtests(*test_args):
if not test_args:
test_args = ["jstemplate"]
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
import django
if six.PY3 and django.VERSION < (1, 5):
print("Django " + '.'.join([str(i) for i in django.VERSION]) +
" is not compatible with Python 3. Skipping tests.")
sys.exit(0)
runtests()
| #!/usr/bin/env python
from __future__ import unicode_literals
import os, sys
try:
import six
from django.conf import settings
except ImportError:
print("Django has not been installed.")
sys.exit(0)
if not settings.configured:
settings.configure(
INSTALLED_APPS=["jstemplate"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3"}})
def runtests(*test_args):
if not test_args:
test_args = ["jstemplate"]
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
import django
if six.PY3 and django.VERSION < (1, 5):
print("Django " + '.'.join([str(i) for i in django.VERSION]) +
" is not compatible with Python 3. Skipping tests.")
sys.exit(0)
runtests()
| Check whether six has been installed before running tests | Check whether six has been installed before running tests
| Python | bsd-3-clause | mjumbewu/django-jstemplate,mjumbewu/django-jstemplate,bopo/django-jstemplate,bopo/django-jstemplate,bopo/django-jstemplate,mjumbewu/django-jstemplate | ---
+++
@@ -2,9 +2,9 @@
from __future__ import unicode_literals
import os, sys
-import six
try:
+ import six
from django.conf import settings
except ImportError:
print("Django has not been installed.") |
0b8e99a6c7ecf5b35c61ce4eed1b2eec3110d41d | runtests.py | runtests.py | import os
import sys
# Force this to happen before loading django
try:
os.environ["DJANGO_SETTINGS_MODULE"] = "testtinymce.settings"
test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, test_dir)
except ImportError:
pass
else:
import django
from django.conf import settings
from django.test.utils import get_runner
def runtests():
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(["tinymce"])
sys.exit(bool(failures))
if __name__ == "__main__":
runtests()
| import argparse
import os
import sys
# Force this to happen before loading django
try:
os.environ["DJANGO_SETTINGS_MODULE"] = "testtinymce.settings"
test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, test_dir)
except ImportError:
pass
else:
import django
from django.conf import settings
from django.test.utils import get_runner
def runtests(verbosity=1, failfast=False):
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(interactive=True, verbosity=verbosity, failfast=failfast)
failures = test_runner.run_tests(["tinymce"])
sys.exit(bool(failures))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run the django-tinymce test suite.")
parser.add_argument(
"-v",
"--verbosity",
default=1,
type=int,
choices=[0, 1, 2, 3],
help="Verbosity level; 0=minimal output, 1=normal output, 2=all output",
)
parser.add_argument(
"--failfast",
action="store_true",
help="Stop running the test suite after first failed test.",
)
options = parser.parse_args()
runtests(verbosity=options.verbosity, failfast=options.failfast)
| Add ability to run tests with verbosity and failfast options | Add ability to run tests with verbosity and failfast options
| Python | mit | aljosa/django-tinymce,aljosa/django-tinymce,aljosa/django-tinymce,aljosa/django-tinymce | ---
+++
@@ -1,3 +1,4 @@
+import argparse
import os
import sys
@@ -14,13 +15,28 @@
from django.test.utils import get_runner
-def runtests():
+def runtests(verbosity=1, failfast=False):
django.setup()
TestRunner = get_runner(settings)
- test_runner = TestRunner(verbosity=1, interactive=True)
+ test_runner = TestRunner(interactive=True, verbosity=verbosity, failfast=failfast)
failures = test_runner.run_tests(["tinymce"])
sys.exit(bool(failures))
if __name__ == "__main__":
- runtests()
+ parser = argparse.ArgumentParser(description="Run the django-tinymce test suite.")
+ parser.add_argument(
+ "-v",
+ "--verbosity",
+ default=1,
+ type=int,
+ choices=[0, 1, 2, 3],
+ help="Verbosity level; 0=minimal output, 1=normal output, 2=all output",
+ )
+ parser.add_argument(
+ "--failfast",
+ action="store_true",
+ help="Stop running the test suite after first failed test.",
+ )
+ options = parser.parse_args()
+ runtests(verbosity=options.verbosity, failfast=options.failfast) |
50a88c05c605f5157eebadb26e30f418dc3251b6 | tests/teamscale_client_test.py | tests/teamscale_client_test.py | import requests
import responses
from teamscale_client.teamscale_client import TeamscaleClient
def get_client():
return TeamscaleClient("http://localhost:8080", "admin", "admin", "foo")
@responses.activate
def test_put():
responses.add(responses.PUT, 'http://localhost:8080',
body='success', status=200)
resp = get_client().put("http://localhost:8080", "[]", {})
assert resp.text == "success"
| import requests
import responses
import re
from teamscale_client.teamscale_client import TeamscaleClient
URL = "http://localhost:8080"
def get_client():
return TeamscaleClient(URL, "admin", "admin", "foo")
def get_project_service_mock(service_id):
return re.compile(r'%s/p/foo/%s/.*' % (URL, service_id))
def get_global_service_mock(service_id):
return re.compile(r'%s/%s/.*' % (URL, service_id))
@responses.activate
def test_put():
responses.add(responses.PUT, 'http://localhost:8080',
body='success', status=200)
resp = get_client().put("http://localhost:8080", "[]", {})
assert resp.text == "success"
@responses.activate
def test_upload_findings():
responses.add(responses.PUT, get_project_service_mock('add-external-findings'),
body='success', status=200)
resp = get_client().upload_findings([], 18073649127634, "Test message", "partition-name")
assert resp.text == "success"
@responses.activate
def test_upload_metrics():
responses.add(responses.PUT, get_project_service_mock('add-external-metrics'),
body='success', status=200)
resp = get_client().upload_metrics([], 18073649127634, "Test message", "partition-name")
assert resp.text == "success"
@responses.activate
def test_upload_metric_description():
responses.add(responses.PUT, get_global_service_mock('add-external-metric-description'),
body='success', status=200)
resp = get_client().upload_metric_definitions([])
assert resp.text == "success"
| Add basic execution tests for upload methods | Add basic execution tests for upload methods
| Python | apache-2.0 | cqse/teamscale-client-python | ---
+++
@@ -1,9 +1,18 @@
import requests
import responses
+import re
from teamscale_client.teamscale_client import TeamscaleClient
+URL = "http://localhost:8080"
+
def get_client():
- return TeamscaleClient("http://localhost:8080", "admin", "admin", "foo")
+ return TeamscaleClient(URL, "admin", "admin", "foo")
+
+def get_project_service_mock(service_id):
+ return re.compile(r'%s/p/foo/%s/.*' % (URL, service_id))
+
+def get_global_service_mock(service_id):
+ return re.compile(r'%s/%s/.*' % (URL, service_id))
@responses.activate
def test_put():
@@ -11,3 +20,25 @@
body='success', status=200)
resp = get_client().put("http://localhost:8080", "[]", {})
assert resp.text == "success"
+
+@responses.activate
+def test_upload_findings():
+ responses.add(responses.PUT, get_project_service_mock('add-external-findings'),
+ body='success', status=200)
+ resp = get_client().upload_findings([], 18073649127634, "Test message", "partition-name")
+ assert resp.text == "success"
+
+@responses.activate
+def test_upload_metrics():
+ responses.add(responses.PUT, get_project_service_mock('add-external-metrics'),
+ body='success', status=200)
+ resp = get_client().upload_metrics([], 18073649127634, "Test message", "partition-name")
+ assert resp.text == "success"
+
+@responses.activate
+def test_upload_metric_description():
+ responses.add(responses.PUT, get_global_service_mock('add-external-metric-description'),
+ body='success', status=200)
+ resp = get_client().upload_metric_definitions([])
+ assert resp.text == "success"
+ |
441eac1b7d9d3f2fb30fbd2faf1dbe8fe3908402 | 99_misc/control_flow.py | 99_misc/control_flow.py | #!/usr/bin/env python
# function
def sum(op1, op2):
return op1 + op2
my_sum = sum
print my_sum(1, 2)
print my_sum("I am ", "zzz");
# pass
print "press ctrl + c to continue"
while True:
pass
| #!/usr/bin/env python
# function
def sum(op1, op2):
return op1 + op2
my_sum = sum
print my_sum(1, 2)
print my_sum("I am ", "zzz");
# Default value in a fuction
init = 12
def accumulate(val = init):
val += val
return val
my_accu = accumulate
init = 11
print my_accu() # is 12 + 12 rather than 11 + 11
# pass
print "press ctrl + c to continue"
while True:
pass
| Test default value of a function | Test default value of a function
| Python | bsd-2-clause | zzz0072/Python_Exercises,zzz0072/Python_Exercises | ---
+++
@@ -7,6 +7,15 @@
print my_sum(1, 2)
print my_sum("I am ", "zzz");
+# Default value in a fuction
+init = 12
+def accumulate(val = init):
+ val += val
+ return val
+
+my_accu = accumulate
+init = 11
+print my_accu() # is 12 + 12 rather than 11 + 11
# pass
print "press ctrl + c to continue" |
c4cdb8429ab9eeeeb7182191589e0594c201d0d2 | glue/_mpl_backend.py | glue/_mpl_backend.py | class MatplotlibBackendSetter(object):
"""
Import hook to make sure the proper Qt backend is set when importing
Matplotlib.
"""
enabled = True
def find_module(self, mod_name, pth):
if self.enabled and 'matplotlib' in mod_name:
self.enabled = False
set_mpl_backend()
return
def set_mpl_backend():
from matplotlib import rcParams, rcdefaults
# standardize mpl setup
rcdefaults()
from glue.external.qt import is_pyqt5
if is_pyqt5():
rcParams['backend'] = 'Qt5Agg'
else:
rcParams['backend'] = 'Qt4Agg'
# The following is a workaround for the fact that Matplotlib checks the
# rcParams at import time, not at run-time. I have opened an issue with
# Matplotlib here: https://github.com/matplotlib/matplotlib/issues/5513
from matplotlib import get_backend
from matplotlib import backends
backends.backend = get_backend()
| class MatplotlibBackendSetter(object):
"""
Import hook to make sure the proper Qt backend is set when importing
Matplotlib.
"""
enabled = True
def find_module(self, mod_name, pth):
if self.enabled and 'matplotlib' in mod_name:
self.enabled = False
set_mpl_backend()
def find_spec(self, name, import_path, target_module=None):
pass
def set_mpl_backend():
from matplotlib import rcParams, rcdefaults
# standardize mpl setup
rcdefaults()
from glue.external.qt import is_pyqt5
if is_pyqt5():
rcParams['backend'] = 'Qt5Agg'
else:
rcParams['backend'] = 'Qt4Agg'
# The following is a workaround for the fact that Matplotlib checks the
# rcParams at import time, not at run-time. I have opened an issue with
# Matplotlib here: https://github.com/matplotlib/matplotlib/issues/5513
from matplotlib import get_backend
from matplotlib import backends
backends.backend = get_backend()
| Add missing find_spec for import hook, to avoid issues when trying to set colormap | Add missing find_spec for import hook, to avoid issues when trying to set colormap | Python | bsd-3-clause | stscieisenhamer/glue,saimn/glue,saimn/glue,stscieisenhamer/glue | ---
+++
@@ -10,8 +10,9 @@
if self.enabled and 'matplotlib' in mod_name:
self.enabled = False
set_mpl_backend()
- return
+ def find_spec(self, name, import_path, target_module=None):
+ pass
def set_mpl_backend():
|
db61a650413d7cf9b225fc3d6f79c706afd33871 | grum/api/__init__.py | grum/api/__init__.py | from flask import Blueprint
from flask.ext.restful import Api
api = Blueprint("api", __name__, template_folder="templates")
rest = Api(api)
# Import the non-restful resources
from grum.api import mailgun
# Let's get restful!
from grum.api.inbox import Inbox
rest.add_resource(Inbox, '/inbox')
from grum.api.messages import Messages
rest.add_resource(Messages, '/messages/<string:message_id>')
from grum.api.accounts import Account, Accounts
rest.add_resource(Accounts, '/accounts')
rest.add_resource(Account, '/account/<string:address>') | from flask import Blueprint
from flask.ext.restful import Api
api = Blueprint("api", __name__, template_folder="templates")
rest = Api(api)
# Import the non-restful resources
from grum.api import mailgun
# Let's get restful!
from grum.api.inbox import Inbox
rest.add_resource(Inbox, '/inbox')
from grum.api.messages import Messages
rest.add_resource(Messages, '/messages/<string:message_id>')
from grum.api.accounts import Account, Accounts
rest.add_resource(Accounts, '/accounts')
rest.add_resource(Account, '/accounts/<string:address>') | Move where to post for sending emails | Move where to post for sending emails
| Python | mit | Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web | ---
+++
@@ -17,4 +17,4 @@
from grum.api.accounts import Account, Accounts
rest.add_resource(Accounts, '/accounts')
-rest.add_resource(Account, '/account/<string:address>')
+rest.add_resource(Account, '/accounts/<string:address>') |
a2cd647966df4f4af5cfd4679ae3c5793c40ee5d | neo/test/iotest/test_asciisignalio.py | neo/test/iotest/test_asciisignalio.py | # -*- coding: utf-8 -*-
"""
Tests of neo.io.asciisignalio
"""
# needed for python 3 compatibility
from __future__ import absolute_import, division
import unittest
from neo.io import AsciiSignalIO
from neo.test.iotest.common_io_test import BaseTestIO
class TestAsciiSignalIO(BaseTestIO, unittest.TestCase, ):
ioclass = AsciiSignalIO
files_to_download = ['File_asciisignal_1.asc',
'File_asciisignal_2.txt',
'File_asciisignal_3.txt',
]
files_to_test = files_to_download
if __name__ == "__main__":
unittest.main()
| # -*- coding: utf-8 -*-
"""
Tests of neo.io.asciisignalio
"""
# needed for python 3 compatibility
from __future__ import absolute_import, division
import unittest
from neo.io import AsciiSignalIO
from neo.test.iotest.common_io_test import BaseTestIO
class TestAsciiSignalIO(BaseTestIO, unittest.TestCase, ):
ioclass = AsciiSignalIO
files_to_download = [#'File_asciisignal_1.asc',
'File_asciisignal_2.txt',
'File_asciisignal_3.txt',
]
files_to_test = files_to_download
if __name__ == "__main__":
unittest.main()
| Remove problematic file from testing | Remove problematic file from testing
| Python | bsd-3-clause | apdavison/python-neo,NeuralEnsemble/python-neo,rgerkin/python-neo,INM-6/python-neo,samuelgarcia/python-neo,JuliaSprenger/python-neo | ---
+++
@@ -14,7 +14,7 @@
class TestAsciiSignalIO(BaseTestIO, unittest.TestCase, ):
ioclass = AsciiSignalIO
- files_to_download = ['File_asciisignal_1.asc',
+ files_to_download = [#'File_asciisignal_1.asc',
'File_asciisignal_2.txt',
'File_asciisignal_3.txt',
] |
a65eb4af0c35c8e79d44efa6acb546e19008a8ee | elmo/moon_tracker/forms.py | elmo/moon_tracker/forms.py | from django import forms
import csv
from io import StringIO
class BatchMoonScanForm(forms.Form):
data = forms.CharField(
widget=forms.Textarea(attrs={'class':'form-control monospace'}),
)
def clean(self):
cleaned_data = super(BatchMoonScanForm, self).clean()
raw = StringIO(cleaned_data['data'])
reader = csv.reader(raw, delimiter='\t')
next(reader)
res = []
for x in reader:
print(x)
if len(x) == 1:
assert(len(x[0]) > 0)
current_moon = 0
current_scan = {}
res.append(current_scan)
else:
assert(len(x[0]) == 0)
moon_id = int(x[6])
ore_id = int(x[3])
percentage = int(round(100 * float(x[2])))
if current_moon == 0:
current_moon = moon_id
else:
assert(moon_id == current_moon)
assert(ore_id not in current_scan)
current_scan[ore_id] = percentage
print(res)
cleaned_data['data'] = res
| from django import forms
import csv
from io import StringIO
class BatchMoonScanForm(forms.Form):
data = forms.CharField(
widget=forms.Textarea(attrs={'class':'form-control monospace'}),
)
def clean(self):
cleaned_data = super(BatchMoonScanForm, self).clean()
raw = StringIO(cleaned_data['data'])
reader = csv.reader(raw, delimiter='\t')
next(reader)
res = {}
current_moon = 0
percentage_sum = 0
current_scan = {}
for x in reader:
print(x)
if len(x) == 1:
if len(x[0]) == 0:
raise forms.ValidationError('Invalid input format.')
if current_moon != 0 and percentage_sum != 100:
raise forms.ValidationError('Sum of percentages must be 100.')
if len(current_scan) > 0 and current_moon != 0:
res[current_moon] = current_scan
current_moon = 0
percentage_sum = 0
current_scan = {}
else:
if len(x[0]) != 0:
raise forms.ValidationError('Invalid input format.')
moon_id = int(x[6])
ore_id = int(x[3])
percentage = int(round(100 * float(x[2])))
percentage_sum += percentage
if current_moon == 0:
current_moon = moon_id
elif moon_id != current_moon:
raise forms.ValidationError('Unexpected moon ID.')
if ore_id in current_scan:
raise forms.ValidationError('Unexpected moon ID.')
current_scan[ore_id] = percentage
print(res)
cleaned_data['data'] = res
| Improve batch form return data structure. | Improve batch form return data structure.
| Python | mit | StephenSwat/eve_lunar_mining_organiser,StephenSwat/eve_lunar_mining_organiser | ---
+++
@@ -15,29 +15,43 @@
next(reader)
- res = []
+ res = {}
+ current_moon = 0
+ percentage_sum = 0
+ current_scan = {}
for x in reader:
print(x)
if len(x) == 1:
- assert(len(x[0]) > 0)
+ if len(x[0]) == 0:
+ raise forms.ValidationError('Invalid input format.')
+
+ if current_moon != 0 and percentage_sum != 100:
+ raise forms.ValidationError('Sum of percentages must be 100.')
+
+ if len(current_scan) > 0 and current_moon != 0:
+ res[current_moon] = current_scan
current_moon = 0
+ percentage_sum = 0
current_scan = {}
- res.append(current_scan)
else:
- assert(len(x[0]) == 0)
+ if len(x[0]) != 0:
+ raise forms.ValidationError('Invalid input format.')
moon_id = int(x[6])
ore_id = int(x[3])
percentage = int(round(100 * float(x[2])))
+ percentage_sum += percentage
+
if current_moon == 0:
current_moon = moon_id
- else:
- assert(moon_id == current_moon)
+ elif moon_id != current_moon:
+ raise forms.ValidationError('Unexpected moon ID.')
- assert(ore_id not in current_scan)
+ if ore_id in current_scan:
+ raise forms.ValidationError('Unexpected moon ID.')
current_scan[ore_id] = percentage
|
83fed17149a8b65491b3f418a9f147e3ffe46e9d | prepare_data.py | prepare_data.py | # TODO: Load the csv files into dataframes here.
class data_preparer():
def __init__():
| # TODO: Load the csv files into dataframes here.
import csv
import pandas
class data_preparer():
def __init__(self):
pass
def load(self, filename):
# X = pandas.DataFrame()
# with open(filename) as csvfile:
# filereader = csv.reader(csvfile,delimiter=',')
X = pandas.read_csv(filename)
return X
| Use 'pandas.read_csv' method to create dataframe | feat: Use 'pandas.read_csv' method to create dataframe
| Python | mit | bwc126/MLND-Subvocal | ---
+++
@@ -1,5 +1,13 @@
# TODO: Load the csv files into dataframes here.
+import csv
+import pandas
class data_preparer():
- def __init__():
-
+ def __init__(self):
+ pass
+ def load(self, filename):
+ # X = pandas.DataFrame()
+ # with open(filename) as csvfile:
+ # filereader = csv.reader(csvfile,delimiter=',')
+ X = pandas.read_csv(filename)
+ return X |
d1d7ec0765b842758b35ee1b5d069536bcd33d59 | ereuse_workbench/config.py | ereuse_workbench/config.py | from decouple import AutoConfig
from ereuse_workbench.test import TestDataStorageLength
class WorkbenchConfig:
# Path where find .env file
config = AutoConfig(search_path='/home/user/')
# Env variables for DH parameters
DH_TOKEN = config('DH_TOKEN')
DH_HOST = config('DH_HOST')
DH_DATABASE = config('DH_DATABASE')
DEVICEHUB_URL = 'https://{host}/{db}/'.format(
host=DH_HOST,
db=DH_DATABASE
) # type: str
## Env variables for WB parameters
WB_BENCHMARK = config('WB_BENCHMARK', default=True, cast=bool)
WB_STRESS_TEST = config('WB_STRESS_TEST', default=0, cast=int)
WB_SMART_TEST = config('WB_SMART_TEST', default='')
## Erase parameters
WB_ERASE = config('WB_ERASE')
WB_ERASE_STEPS = config('WB_ERASE_STEPS', default=1, cast=int)
WB_ERASE_LEADING_ZEROS = config('WB_ERASE_LEADING_ZERO', default=False, cast=bool)
WB_DEBUG = config('WB_DEBUG', default=True, cast=bool)
| from decouple import AutoConfig
from ereuse_workbench.test import TestDataStorageLength
class WorkbenchConfig:
# Path where find settings.ini file
config = AutoConfig(search_path='/home/user/')
# Env variables for DH parameters
DH_TOKEN = config('DH_TOKEN')
DH_HOST = config('DH_HOST')
DH_DATABASE = config('DH_DATABASE')
DEVICEHUB_URL = 'https://{host}/{db}/'.format(
host=DH_HOST,
db=DH_DATABASE
) # type: str
## Env variables for WB parameters
WB_BENCHMARK = config('WB_BENCHMARK', default=False, cast=bool)
WB_STRESS_TEST = config('WB_STRESS_TEST', default=0, cast=int)
WB_SMART_TEST = config('WB_SMART_TEST', default='')
## Erase parameters
WB_ERASE = config('WB_ERASE')
WB_ERASE_STEPS = config('WB_ERASE_STEPS', default=1, cast=int)
WB_ERASE_LEADING_ZEROS = config('WB_ERASE_LEADING_ZERO', default=False, cast=bool)
WB_DEBUG = config('WB_DEBUG', default=True, cast=bool)
| Change .env to settings.ini file | Change .env to settings.ini file
| Python | agpl-3.0 | eReuse/workbench,eReuse/workbench | ---
+++
@@ -4,7 +4,7 @@
class WorkbenchConfig:
- # Path where find .env file
+ # Path where find settings.ini file
config = AutoConfig(search_path='/home/user/')
# Env variables for DH parameters
@@ -17,7 +17,7 @@
) # type: str
## Env variables for WB parameters
- WB_BENCHMARK = config('WB_BENCHMARK', default=True, cast=bool)
+ WB_BENCHMARK = config('WB_BENCHMARK', default=False, cast=bool)
WB_STRESS_TEST = config('WB_STRESS_TEST', default=0, cast=int)
WB_SMART_TEST = config('WB_SMART_TEST', default='')
|
1e7dd0a322e32621468ade5bf390664f1b8b7a8b | fixture/application.py | fixture/application.py | from selenium.webdriver.firefox.webdriver import WebDriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.contact import ContactHelper
class Application:
def __init__(self):
self.wd = WebDriver()
self.wd.implicitly_wait(60)
self.session = SessionHelper(self)
self.group = GroupHelper(self)
self.contact = ContactHelper(self)
def open_home_page(self):
wd = self.wd
wd.get("http://localhost/addressbook/")
def destroy(self):
self.wd.quit()
def is_valid(self):
try:
self.wd.current_url
return True
except:
return False | from selenium.webdriver.firefox.webdriver import WebDriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.contact import ContactHelper
class Application:
def __init__(self):
self.wd = WebDriver()
self.wd.implicitly_wait(5)
self.session = SessionHelper(self)
self.group = GroupHelper(self)
self.contact = ContactHelper(self)
def open_home_page(self):
wd = self.wd
wd.get("http://localhost/addressbook/")
def destroy(self):
self.wd.quit()
def is_valid(self):
try:
self.wd.current_url
return True
except:
return False | Change Wait time from 60 to 5 sec | Change Wait time from 60 to 5 sec
| Python | apache-2.0 | tkapriyan/python_training | ---
+++
@@ -8,7 +8,7 @@
def __init__(self):
self.wd = WebDriver()
- self.wd.implicitly_wait(60)
+ self.wd.implicitly_wait(5)
self.session = SessionHelper(self)
self.group = GroupHelper(self)
self.contact = ContactHelper(self) |
2b4b4ac3ec238a039717feff727316217c13d294 | test/test_cronquot.py | test/test_cronquot.py | import unittest
from cronquot.cronquot import has_directory
class CronquotTest(unittest.TestCase):
def test_has_directory(self):
self.assertTrue(has_directory('/tmp'))
if __name__ == '__main__':
unittest.test()
| import unittest
import os
from cronquot.cronquot import has_directory
class CronquotTest(unittest.TestCase):
def test_has_directory(self):
sample_dir = os.path.join(
os.path.dirname(__file__), 'crontab')
self.assertTrue(has_directory(sample_dir))
if __name__ == '__main__':
unittest.test()
| Fix to test crontab dir | Fix to test crontab dir
| Python | mit | pyohei/cronquot,pyohei/cronquot | ---
+++
@@ -1,11 +1,14 @@
import unittest
+import os
from cronquot.cronquot import has_directory
class CronquotTest(unittest.TestCase):
def test_has_directory(self):
- self.assertTrue(has_directory('/tmp'))
+ sample_dir = os.path.join(
+ os.path.dirname(__file__), 'crontab')
+ self.assertTrue(has_directory(sample_dir))
if __name__ == '__main__':
unittest.test() |
038e619e47a05aadf7e0641dd87b6dc573abe3e5 | massa/domain.py | massa/domain.py | # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
def make_tables():
metadata.create_all()
| # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
def make_tables():
metadata.create_all()
def drop_tables():
metadata.drop_all()
| Add a function to drop db tables. | Add a function to drop db tables. | Python | mit | jaapverloop/massa | ---
+++
@@ -31,3 +31,6 @@
def make_tables():
metadata.create_all()
+
+def drop_tables():
+ metadata.drop_all() |
5425c2419b7365969ea8b211432858d599214201 | tests/test_archive.py | tests/test_archive.py | from json import load
from django_archive import __version__
from .base import BaseArchiveTestCase
from .sample.models import Sample
class ArchiveTestCase(BaseArchiveTestCase):
"""
Test that the archive command includes correct data in the archive
"""
def setUp(self):
Sample().save()
super().setUp()
def test_data(self):
"""
Confirm that the model was archived
"""
with self.tarfile.extractfile('data.json') as fileobj:
data = load(fileobj)
self.assertEqual(len(data), 1)
self.assertEqual(data[0]['model'], 'sample.sample')
def test_meta(self):
"""
Confirm that meta information is present
"""
with self.tarfile.extractfile('meta.json') as fileobj:
data = load(fileobj)
self.assertEqual(data['version'], __version__)
| from json import load
from django.core.files.base import ContentFile
from django_archive import __version__
from .base import BaseArchiveTestCase
from .sample.models import Sample
class ArchiveTestCase(BaseArchiveTestCase):
"""
Test that the archive command includes correct data in the archive
"""
_ATTACHMENT_FILENAME = 'sample.txt'
_ATTACHMENT_CONTENT = b'sample'
def setUp(self):
sample = Sample()
sample.attachment.save(
self._ATTACHMENT_FILENAME,
ContentFile(self._ATTACHMENT_CONTENT),
)
super().setUp()
def test_data(self):
"""
Confirm that the model and attached files were archived
"""
with self.tarfile.extractfile('data.json') as fileobj:
data = load(fileobj)
self.assertEqual(len(data), 1)
self.assertEqual(data[0]['model'], 'sample.sample')
with self.tarfile.extractfile(data[0]['fields']['attachment']) as fileobj:
content = fileobj.read()
self.assertEqual(content, self._ATTACHMENT_CONTENT)
def test_meta(self):
"""
Confirm that meta information is present
"""
with self.tarfile.extractfile('meta.json') as fileobj:
data = load(fileobj)
self.assertEqual(data['version'], __version__)
| Update test to ensure attached files are present in archives. | Update test to ensure attached files are present in archives.
| Python | mit | nathan-osman/django-archive,nathan-osman/django-archive | ---
+++
@@ -1,5 +1,6 @@
from json import load
+from django.core.files.base import ContentFile
from django_archive import __version__
from .base import BaseArchiveTestCase
@@ -11,18 +12,28 @@
Test that the archive command includes correct data in the archive
"""
+ _ATTACHMENT_FILENAME = 'sample.txt'
+ _ATTACHMENT_CONTENT = b'sample'
+
def setUp(self):
- Sample().save()
+ sample = Sample()
+ sample.attachment.save(
+ self._ATTACHMENT_FILENAME,
+ ContentFile(self._ATTACHMENT_CONTENT),
+ )
super().setUp()
def test_data(self):
"""
- Confirm that the model was archived
+ Confirm that the model and attached files were archived
"""
with self.tarfile.extractfile('data.json') as fileobj:
data = load(fileobj)
- self.assertEqual(len(data), 1)
- self.assertEqual(data[0]['model'], 'sample.sample')
+ self.assertEqual(len(data), 1)
+ self.assertEqual(data[0]['model'], 'sample.sample')
+ with self.tarfile.extractfile(data[0]['fields']['attachment']) as fileobj:
+ content = fileobj.read()
+ self.assertEqual(content, self._ATTACHMENT_CONTENT)
def test_meta(self):
""" |
1b5fc874924958664797ba2f1e73835b4cbcef57 | mfr/__init__.py | mfr/__init__.py | """The mfr core module."""
# -*- coding: utf-8 -*-
import os
__version__ = '0.1.0-alpha'
__author__ = 'Center for Open Science'
from mfr.core import (render, detect, FileHandler, get_file_extension,
register_filehandler, export, get_file_exporters,
config, collect_static
)
from mfr._config import Config
PACKAGE_DIR = os.path.abspath(os.path.dirname(__file__))
| """The mfr core module."""
# -*- coding: utf-8 -*-
import os
__version__ = '0.1.0-alpha'
__author__ = 'Center for Open Science'
from mfr.core import (
render,
detect,
FileHandler,
get_file_extension,
register_filehandler,
export,
get_file_exporters,
config,
collect_static,
RenderResult,
)
from mfr._config import Config
PACKAGE_DIR = os.path.abspath(os.path.dirname(__file__))
| Add RenderResult to mfr namespace | Add RenderResult to mfr namespace
| Python | apache-2.0 | TomBaxter/modular-file-renderer,chrisseto/modular-file-renderer,mfraezz/modular-file-renderer,haoyuchen1992/modular-file-renderer,haoyuchen1992/modular-file-renderer,erinspace/modular-file-renderer,rdhyee/modular-file-renderer,CenterForOpenScience/modular-file-renderer,icereval/modular-file-renderer,TomBaxter/modular-file-renderer,erinspace/modular-file-renderer,Johnetordoff/modular-file-renderer,TomBaxter/modular-file-renderer,AddisonSchiller/modular-file-renderer,AddisonSchiller/modular-file-renderer,icereval/modular-file-renderer,Johnetordoff/modular-file-renderer,haoyuchen1992/modular-file-renderer,felliott/modular-file-renderer,Johnetordoff/modular-file-renderer,chrisseto/modular-file-renderer,felliott/modular-file-renderer,icereval/modular-file-renderer,CenterForOpenScience/modular-file-renderer,felliott/modular-file-renderer,haoyuchen1992/modular-file-renderer,mfraezz/modular-file-renderer,mfraezz/modular-file-renderer,mfraezz/modular-file-renderer,chrisseto/modular-file-renderer,AddisonSchiller/modular-file-renderer,rdhyee/modular-file-renderer,AddisonSchiller/modular-file-renderer,CenterForOpenScience/modular-file-renderer,erinspace/modular-file-renderer,rdhyee/modular-file-renderer,CenterForOpenScience/modular-file-renderer,Johnetordoff/modular-file-renderer,felliott/modular-file-renderer,TomBaxter/modular-file-renderer,rdhyee/modular-file-renderer | ---
+++
@@ -6,9 +6,17 @@
__author__ = 'Center for Open Science'
-from mfr.core import (render, detect, FileHandler, get_file_extension,
- register_filehandler, export, get_file_exporters,
- config, collect_static
+from mfr.core import (
+ render,
+ detect,
+ FileHandler,
+ get_file_extension,
+ register_filehandler,
+ export,
+ get_file_exporters,
+ config,
+ collect_static,
+ RenderResult,
)
from mfr._config import Config |
0a5331c36cb469b2af10d87ab375d9bd0c6c3fb8 | tests/test_lattice.py | tests/test_lattice.py | import rml.lattice
def test_create_lattice():
l = rml.lattice.Lattice()
assert(len(l)) == 0
| import rml.lattice
def test_create_lattice():
l = rml.lattice.Lattice()
assert(len(l)) == 0
def test_non_negative_lattice():
l = rml.lattice.Lattice()
assert(len(l)) >= 0
| Test lattince length for non-negative values | Test lattince length for non-negative values
| Python | apache-2.0 | willrogers/pml,razvanvasile/RML,willrogers/pml | ---
+++
@@ -4,3 +4,6 @@
l = rml.lattice.Lattice()
assert(len(l)) == 0
+def test_non_negative_lattice():
+ l = rml.lattice.Lattice()
+ assert(len(l)) >= 0 |
19dc8b7e1535c4cc431b765f95db117175fc7d24 | server/admin.py | server/admin.py | from django.contrib import admin
from server.models import *
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
admin.site.register(UserProfile)
admin.site.register(BusinessUnit)
admin.site.register(MachineGroup, MachineGroupAdmin)
admin.site.register(Machine, MachineAdmin)
admin.site.register(Fact)
admin.site.register(PluginScriptSubmission)
admin.site.register(PluginScriptRow)
admin.site.register(HistoricalFact)
admin.site.register(Condition)
admin.site.register(PendingUpdate)
admin.site.register(InstalledUpdate)
admin.site.register(PendingAppleUpdate)
admin.site.register(ApiKey)
admin.site.register(Plugin)
admin.site.register(Report)
# admin.site.register(OSQueryResult)
# admin.site.register(OSQueryColumn)
admin.site.register(SalSetting)
admin.site.register(UpdateHistory)
admin.site.register(UpdateHistoryItem)
admin.site.register(MachineDetailPlugin)
| from django.contrib import admin
from server.models import *
class ApiKeyAdmin(admin.ModelAdmin):
list_display = ('name', 'public_key', 'private_key')
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
admin.site.register(ApiKey, ApiKeyAdmin)
admin.site.register(BusinessUnit)
admin.site.register(Condition)
admin.site.register(Fact)
admin.site.register(HistoricalFact)
admin.site.register(InstalledUpdate)
admin.site.register(Machine, MachineAdmin)
admin.site.register(MachineDetailPlugin)
admin.site.register(MachineGroup, MachineGroupAdmin)
# admin.site.register(OSQueryColumn)
# admin.site.register(OSQueryResult)
admin.site.register(PendingAppleUpdate)
admin.site.register(PendingUpdate)
admin.site.register(Plugin)
admin.site.register(PluginScriptRow)
admin.site.register(PluginScriptSubmission)
admin.site.register(Report)
admin.site.register(SalSetting)
admin.site.register(UpdateHistory)
admin.site.register(UpdateHistoryItem)
admin.site.register(UserProfile)
| Sort registrations. Separate classes of imports. Add API key display. | Sort registrations. Separate classes of imports. Add API key display.
| Python | apache-2.0 | salopensource/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal | ---
+++
@@ -1,33 +1,38 @@
from django.contrib import admin
+
from server.models import *
+
+
+class ApiKeyAdmin(admin.ModelAdmin):
+ list_display = ('name', 'public_key', 'private_key')
+
+
+class MachineAdmin(admin.ModelAdmin):
+ list_display = ('hostname', 'serial')
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
-class MachineAdmin(admin.ModelAdmin):
- list_display = ('hostname', 'serial')
-
-
-admin.site.register(UserProfile)
+admin.site.register(ApiKey, ApiKeyAdmin)
admin.site.register(BusinessUnit)
+admin.site.register(Condition)
+admin.site.register(Fact)
+admin.site.register(HistoricalFact)
+admin.site.register(InstalledUpdate)
+admin.site.register(Machine, MachineAdmin)
+admin.site.register(MachineDetailPlugin)
admin.site.register(MachineGroup, MachineGroupAdmin)
-admin.site.register(Machine, MachineAdmin)
-admin.site.register(Fact)
+# admin.site.register(OSQueryColumn)
+# admin.site.register(OSQueryResult)
+admin.site.register(PendingAppleUpdate)
+admin.site.register(PendingUpdate)
+admin.site.register(Plugin)
+admin.site.register(PluginScriptRow)
admin.site.register(PluginScriptSubmission)
-admin.site.register(PluginScriptRow)
-admin.site.register(HistoricalFact)
-admin.site.register(Condition)
-admin.site.register(PendingUpdate)
-admin.site.register(InstalledUpdate)
-admin.site.register(PendingAppleUpdate)
-admin.site.register(ApiKey)
-admin.site.register(Plugin)
admin.site.register(Report)
-# admin.site.register(OSQueryResult)
-# admin.site.register(OSQueryColumn)
admin.site.register(SalSetting)
admin.site.register(UpdateHistory)
admin.site.register(UpdateHistoryItem)
-admin.site.register(MachineDetailPlugin)
+admin.site.register(UserProfile) |
b5aacae66d4395a3c507c661144b21f9b2838a0f | utils/dakota_utils.py | utils/dakota_utils.py | #! /usr/bin/env python
#
# Dakota utility programs.
#
# Mark Piper (mark.piper@colorado.edu)
import numpy as np
def get_names(dat_file):
'''
Reads the header from Dakota tabular graphics file. Returns a list
of variable names.
'''
fp = open(dat_file, 'r')
return fp.readline().split()
def get_data(dat_file):
'''
Reads the data from Dakota tabular graphics file. Returns a numpy array.
'''
return np.loadtxt(dat_file, skiprows=1, unpack=True)
def read_tabular(dat_file):
'''
Reads a Dakota tabular graphics file. Returns a dict with variable
names and a numpy array with data.
'''
names = get_names(dat_file)
data = get_data(dat_file)
return {'names':names, 'data':data}
| #! /usr/bin/env python
#
# Dakota utility programs.
#
# Mark Piper (mark.piper@colorado.edu)
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def get_names(dat_file):
'''
Reads the header from Dakota tabular graphics file. Returns a list
of variable names.
'''
fp = open(dat_file, 'r')
return fp.readline().split()
def get_data(dat_file):
'''
Reads the data from Dakota tabular graphics file. Returns a numpy array.
'''
return np.loadtxt(dat_file, skiprows=1, unpack=True)
def read_tabular(dat_file):
'''
Reads a Dakota tabular graphics file. Returns a dict with variable
names and a numpy array with data.
'''
names = get_names(dat_file)
data = get_data(dat_file)
return {'names':names, 'data':data}
def plot_tabular_2d(tab_data, column_index=-1):
'''
Surface plot.
'''
x = tab_data.get('data')[1,]
y = tab_data.get('data')[2,]
z = tab_data.get('data')[column_index,]
m = len(set(x))
n = len(set(y))
X = x.reshape(m,n)
Y = y.reshape(m,n)
Z = z.reshape(m,n)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1)
ax.set_xlabel(tab_data.get('names')[1])
ax.set_ylabel(tab_data.get('names')[2])
ax.set_zlabel(tab_data.get('names')[column_index])
plt.show(block=False)
| Add routine to make surface plot from Dakota output | Add routine to make surface plot from Dakota output
| Python | mit | mdpiper/dakota-experiments,mdpiper/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments,mcflugen/dakota-experiments | ---
+++
@@ -5,6 +5,8 @@
# Mark Piper (mark.piper@colorado.edu)
import numpy as np
+from mpl_toolkits.mplot3d import Axes3D
+import matplotlib.pyplot as plt
def get_names(dat_file):
@@ -19,7 +21,7 @@
def get_data(dat_file):
'''
Reads the data from Dakota tabular graphics file. Returns a numpy array.
- '''
+ '''
return np.loadtxt(dat_file, skiprows=1, unpack=True)
@@ -31,3 +33,26 @@
names = get_names(dat_file)
data = get_data(dat_file)
return {'names':names, 'data':data}
+
+def plot_tabular_2d(tab_data, column_index=-1):
+ '''
+ Surface plot.
+ '''
+ x = tab_data.get('data')[1,]
+ y = tab_data.get('data')[2,]
+ z = tab_data.get('data')[column_index,]
+
+ m = len(set(x))
+ n = len(set(y))
+
+ X = x.reshape(m,n)
+ Y = y.reshape(m,n)
+ Z = z.reshape(m,n)
+
+ fig = plt.figure()
+ ax = fig.add_subplot(111, projection='3d')
+ ax.plot_surface(X, Y, Z, rstride=1, cstride=1)
+ ax.set_xlabel(tab_data.get('names')[1])
+ ax.set_ylabel(tab_data.get('names')[2])
+ ax.set_zlabel(tab_data.get('names')[column_index])
+ plt.show(block=False) |
1c22c7806f459ae385c38a0d952ab324fdbc02d9 | lib/ansiblelint/formatters/__init__.py | lib/ansiblelint/formatters/__init__.py | class Formatter(object):
def format(self, match):
formatstr = "[{0}] {1}\n{2}:{3}\n{4}\n"
return formatstr.format(match.rule.id,
match.message,
match.filename,
match.linenumber,
match.line)
class QuietFormatter(object):
def format(self, match):
formatstr = "[{0}] {1}:{2}"
return formatstr.format(match.rule.id, match.filename,
match.linenumber)
class ParseableFormatter(object):
def format(self, match):
formatstr = "{0}:{1}: [{2}] {3}"
return formatstr.format(match.filename,
match.linenumber,
match.rule.id,
match.message,
)
| class Formatter(object):
def format(self, match):
formatstr = u"[{0}] {1}\n{2}:{3}\n{4}\n"
return formatstr.format(match.rule.id,
match.message,
match.filename,
match.linenumber,
match.line)
class QuietFormatter(object):
def format(self, match):
formatstr = u"[{0}] {1}:{2}"
return formatstr.format(match.rule.id, match.filename,
match.linenumber)
class ParseableFormatter(object):
def format(self, match):
formatstr = u"{0}:{1}: [{2}] {3}"
return formatstr.format(match.filename,
match.linenumber,
match.rule.id,
match.message,
)
| Fix crash tasks with unicode string name (like name: héhé). | Fix crash tasks with unicode string name (like name: héhé).
| Python | mit | MatrixCrawler/ansible-lint,willthames/ansible-lint,dataxu/ansible-lint | ---
+++
@@ -1,7 +1,7 @@
class Formatter(object):
def format(self, match):
- formatstr = "[{0}] {1}\n{2}:{3}\n{4}\n"
+ formatstr = u"[{0}] {1}\n{2}:{3}\n{4}\n"
return formatstr.format(match.rule.id,
match.message,
match.filename,
@@ -12,7 +12,7 @@
class QuietFormatter(object):
def format(self, match):
- formatstr = "[{0}] {1}:{2}"
+ formatstr = u"[{0}] {1}:{2}"
return formatstr.format(match.rule.id, match.filename,
match.linenumber)
@@ -20,7 +20,7 @@
class ParseableFormatter(object):
def format(self, match):
- formatstr = "{0}:{1}: [{2}] {3}"
+ formatstr = u"{0}:{1}: [{2}] {3}"
return formatstr.format(match.filename,
match.linenumber,
match.rule.id, |
64368ac4d5d90de7df92110364b165be975719c9 | manager/apps/brand/urls.py | manager/apps/brand/urls.py | from django.conf.urls import patterns, url
from manager.apps.brand.views import BrandListView, BrandView
from manager.apps.brand.views import OwnerListView, OwnerView
urlpatterns = patterns(
'',
url(r'^brand$', BrandListView.as_view(), name='brandlist'),
url(r'^brand/(?P<bsin>[1-9A-NP-Z]{6})', BrandView.as_view(), name='brand'),
url(r'^owner$', OwnerListView.as_view(), name='ownerlist'),
url(r'^owner/(?P<cd>[1-9]+)', OwnerView.as_view(), name='owner'),
)
| from django.conf.urls import patterns, url
from manager.apps.brand.views import BrandListView, BrandView
from manager.apps.brand.views import OwnerListView, OwnerView
urlpatterns = patterns(
'',
url(r'^brand/$', BrandListView.as_view(), name='brandlist'),
url(r'^brand/(?P<bsin>[1-9A-NP-Z]{6})', BrandView.as_view(), name='brand'),
url(r'^owner/$', OwnerListView.as_view(), name='ownerlist'),
url(r'^owner/(?P<cd>[1-9]+)', OwnerView.as_view(), name='owner'),
)
| Fix Brand and Owner public links (missing / would get a 404 on brand/ and owner/) | Fix Brand and Owner public links (missing / would get a 404 on brand/ and owner/)
Also follow the same URL scheme as admin (which always have trailing
slash)
| Python | mit | okfn/opd-brand-manager,okfn/opd-brand-manager,okfn/brand-manager,okfn/brand-manager | ---
+++
@@ -4,9 +4,9 @@
urlpatterns = patterns(
'',
- url(r'^brand$', BrandListView.as_view(), name='brandlist'),
+ url(r'^brand/$', BrandListView.as_view(), name='brandlist'),
url(r'^brand/(?P<bsin>[1-9A-NP-Z]{6})', BrandView.as_view(), name='brand'),
- url(r'^owner$', OwnerListView.as_view(), name='ownerlist'),
+ url(r'^owner/$', OwnerListView.as_view(), name='ownerlist'),
url(r'^owner/(?P<cd>[1-9]+)', OwnerView.as_view(), name='owner'),
) |
50ca3fa53b6bb22dbd38b75cc4cf2244b0a2767c | python/setup.py | python/setup.py | # coding: utf-8
from distutils.core import setup
setup(
name = 'gherkin3',
packages = ['gherkin3'],
version = '3.0.0',
description = 'Gherkin parser',
author = 'Björn Rasmusson',
author_email = 'cukes@googlegroups.com',
url = 'https://github.com/cucumber/gherkin-python',
license = 'MIT',
download_url = 'https://github.com/cucumber/gherkin-ruby/archive/v3.0.0.tar.gz',
keywords = ['gherkin', 'cucumber', 'bdd'],
classifiers = [],
)
| # coding: utf-8
from distutils.core import setup
setup(
name = 'gherkin3',
packages = ['gherkin3'],
version = '3.0.0',
description = 'Gherkin parser',
author = 'Björn Rasmusson',
author_email = 'cukes@googlegroups.com',
url = 'https://github.com/cucumber/gherkin-python',
license = 'MIT',
download_url = 'https://github.com/cucumber/gherkin-python/archive/v3.0.0.tar.gz',
keywords = ['gherkin', 'cucumber', 'bdd'],
classifiers = [],
)
| Correct the download url for gherkin-python | Correct the download url for gherkin-python
| Python | mit | chebizarro/gherkin3,curzona/gherkin3,Zearin/gherkin3,thetutlage/gherkin3,Zearin/gherkin3,hayd/gherkin3,thiblahute/gherkin3,thetutlage/gherkin3,SabotageAndi/gherkin,concertman/gherkin3,SabotageAndi/gherkin,moreirap/gherkin3,concertman/gherkin3,concertman/gherkin3,concertman/gherkin3,concertman/gherkin3,SabotageAndi/gherkin,dg-ratiodata/gherkin3,Zearin/gherkin3,thiblahute/gherkin3,araines/gherkin3,moreirap/gherkin3,SabotageAndi/gherkin,cucumber/gherkin3,thetutlage/gherkin3,chebizarro/gherkin3,Zearin/gherkin3,moreirap/gherkin3,araines/gherkin3,moreirap/gherkin3,thiblahute/gherkin3,pjlsergeant/gherkin,amaniak/gherkin3,curzona/gherkin3,SabotageAndi/gherkin,hayd/gherkin3,concertman/gherkin3,dirkrombauts/gherkin3,hayd/gherkin3,hayd/gherkin3,vincent-psarga/gherkin3,dirkrombauts/gherkin3,amaniak/gherkin3,moreirap/gherkin3,pjlsergeant/gherkin,dg-ratiodata/gherkin3,vincent-psarga/gherkin3,cucumber/gherkin3,chebizarro/gherkin3,dg-ratiodata/gherkin3,pjlsergeant/gherkin,chebizarro/gherkin3,curzona/gherkin3,dirkrombauts/gherkin3,thiblahute/gherkin3,thetutlage/gherkin3,thiblahute/gherkin3,cucumber/gherkin3,chebizarro/gherkin3,curzona/gherkin3,curzona/gherkin3,moreirap/gherkin3,hayd/gherkin3,moreirap/gherkin3,Zearin/gherkin3,vincent-psarga/gherkin3,thetutlage/gherkin3,curzona/gherkin3,pjlsergeant/gherkin,concertman/gherkin3,curzona/gherkin3,vincent-psarga/gherkin3,thiblahute/gherkin3,dirkrombauts/gherkin3,thiblahute/gherkin3,cucumber/gherkin3,araines/gherkin3,amaniak/gherkin3,thiblahute/gherkin3,thetutlage/gherkin3,amaniak/gherkin3,Zearin/gherkin3,amaniak/gherkin3,pjlsergeant/gherkin,dirkrombauts/gherkin3,thetutlage/gherkin3,hayd/gherkin3,hayd/gherkin3,SabotageAndi/gherkin,dg-ratiodata/gherkin3,dirkrombauts/gherkin3,araines/gherkin3,dirkrombauts/gherkin3,thetutlage/gherkin3,amaniak/gherkin3,SabotageAndi/gherkin,dg-ratiodata/gherkin3,vincent-psarga/gherkin3,SabotageAndi/gherkin,cucumber/gherkin3,cucumber/gherkin3,concertman/gherkin3,curzona/gherkin3,araines/gherkin3,cucumber/gherkin3,dg-ratiodata/gherkin3,amaniak/gherkin3,pjlsergeant/gherkin,pjlsergeant/gherkin,vincent-psarga/gherkin3,araines/gherkin3,moreirap/gherkin3,Zearin/gherkin3,SabotageAndi/gherkin,Zearin/gherkin3,cucumber/gherkin3,vincent-psarga/gherkin3,pjlsergeant/gherkin,araines/gherkin3,amaniak/gherkin3,dirkrombauts/gherkin3,hayd/gherkin3,cucumber/gherkin3,vincent-psarga/gherkin3,araines/gherkin3,dg-ratiodata/gherkin3,pjlsergeant/gherkin,chebizarro/gherkin3,chebizarro/gherkin3,chebizarro/gherkin3,dg-ratiodata/gherkin3 | ---
+++
@@ -9,7 +9,7 @@
author_email = 'cukes@googlegroups.com',
url = 'https://github.com/cucumber/gherkin-python',
license = 'MIT',
- download_url = 'https://github.com/cucumber/gherkin-ruby/archive/v3.0.0.tar.gz',
+ download_url = 'https://github.com/cucumber/gherkin-python/archive/v3.0.0.tar.gz',
keywords = ['gherkin', 'cucumber', 'bdd'],
classifiers = [],
) |
f5a3148ed638c65a3de3e1de0e5dece96f0c049b | placidity/plugin_loader.py | placidity/plugin_loader.py | class PluginLoader:
def load(self, directory):
ret = []
for plugin in directory.children:
plugin_file = plugin.find(name=plugin.name, type='py')
plugin_class = plugin_file.classes[plugin.name]
self._check_attributes(plugin_class)
plugin_instance = plugin_class()
ret.append(plugin_instance)
return ret
def _check_attributes(self, klass):
self._check_aliases(klass)
self._check_matches(klass)
self._check_priority(klass)
def _check_aliases(self, klass):
self._check_attribute(klass, 'aliases', '')
def _check_matches(self, klass):
def matches(self, expression):
if isinstance(self.aliases, str):
return expression == self.aliases
return expression in self.aliases
self._check_attribute(klass, 'matches', matches)
def _check_priority(self, klass):
self._check_attribute(klass, 'priority', 'normal')
if klass.priority not in ('low', 'normal', 'high'):
klass.priority = 'normal'
def _check_attribute(self, klass, attribute, value):
if not hasattr(klass, attribute):
setattr(klass, attribute, value)
| class PluginLoader:
def load(self, directory):
ret = []
for plugin in directory.children:
plugin_file = plugin.find(name=plugin.name, type='py')
if not plugin_file:
continue
plugin_class = plugin_file.classes[plugin.name]
self._check_attributes(plugin_class)
plugin_instance = plugin_class()
ret.append(plugin_instance)
return ret
def _check_attributes(self, klass):
self._check_aliases(klass)
self._check_matches(klass)
self._check_priority(klass)
def _check_aliases(self, klass):
self._check_attribute(klass, 'aliases', '')
def _check_matches(self, klass):
def matches(self, expression):
if isinstance(self.aliases, str):
return expression == self.aliases
return expression in self.aliases
self._check_attribute(klass, 'matches', matches)
def _check_priority(self, klass):
self._check_attribute(klass, 'priority', 'normal')
if klass.priority not in ('low', 'normal', 'high'):
klass.priority = 'normal'
def _check_attribute(self, klass, attribute, value):
if not hasattr(klass, attribute):
setattr(klass, attribute, value)
| Make plugin loader more robust | Make plugin loader more robust
| Python | mit | bebraw/Placidity | ---
+++
@@ -5,6 +5,10 @@
for plugin in directory.children:
plugin_file = plugin.find(name=plugin.name, type='py')
+
+ if not plugin_file:
+ continue
+
plugin_class = plugin_file.classes[plugin.name]
self._check_attributes(plugin_class) |
d39edc6d3e02adeb3cd89ca13fdb9660be3247b4 | hydromet/__init__.py | hydromet/__init__.py | from hydromet import disaggregate
from hydromet import models
from hydromet import stats
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
| from hydromet import disaggregate
#from hydromet import models
from hydromet import stats
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
| Disable import so that hydromet can be used w/o hydromath.so | Disable import so that hydromet can be used w/o hydromath.so
Should make the code for finding/not working if hydromath.so isn't
available a bit more robust, but in the mean time disabling an import so
that other parts of hydromet can be used without requiring hydromath.
| Python | bsd-3-clause | amacd31/hydromet-toolkit,amacd31/hydromet-toolkit | ---
+++
@@ -1,5 +1,5 @@
from hydromet import disaggregate
-from hydromet import models
+#from hydromet import models
from hydromet import stats
from ._version import get_versions |
b1b8c9b4e392d4865756ece6528e6668e2bc8975 | wafw00f/plugins/expressionengine.py | wafw00f/plugins/expressionengine.py | #!/usr/bin/env python
NAME = 'Expression Engine (EllisLab)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
response, page = r
# There are traces found where cookie is returning values like:
# Set-Cookie: exp_last_query=834y8d73y94d8g983u4shn8u4shr3uh3
# Set-Cookie: exp_last_id=b342b432b1a876r8
if 'exp_last_' in response.getheader('Set-Cookie'):
return True
# In-page fingerprints vary a lot in different sites. Hence these are not quite reliable.
if any(i in page for i in (b'Invalid GET Data', b'Invalid URI')):
return True
return False | #!/usr/bin/env python
NAME = 'Expression Engine (EllisLab)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
response, page = r
# There are traces found where cookie is returning values like:
# Set-Cookie: exp_last_query=834y8d73y94d8g983u4shn8u4shr3uh3
# Set-Cookie: exp_last_id=b342b432b1a876r8
if response.getheader('Set-Cookie'):
if 'exp_last_' in response.getheader('Set-Cookie'):
return True
# In-page fingerprints vary a lot in different sites. Hence these are not quite reliable.
if any(i in page for i in (b'Invalid GET Data', b'Invalid URI')):
return True
return False | Fix to avoid NoneType bugs | Fix to avoid NoneType bugs
| Python | bsd-3-clause | EnableSecurity/wafw00f | ---
+++
@@ -13,8 +13,9 @@
# There are traces found where cookie is returning values like:
# Set-Cookie: exp_last_query=834y8d73y94d8g983u4shn8u4shr3uh3
# Set-Cookie: exp_last_id=b342b432b1a876r8
- if 'exp_last_' in response.getheader('Set-Cookie'):
- return True
+ if response.getheader('Set-Cookie'):
+ if 'exp_last_' in response.getheader('Set-Cookie'):
+ return True
# In-page fingerprints vary a lot in different sites. Hence these are not quite reliable.
if any(i in page for i in (b'Invalid GET Data', b'Invalid URI')):
return True |
bf241d6c7aa96c5fca834eb1063fc009a9320329 | portfolio/urls.py | portfolio/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^projects/$', views.projects, name='projects'),
url(r'^tribute/$', views.tribute, name='tribute'),
url(r'^weather/$', views.weather, name='weather'),
url(r'^randomquote/$', views.randomquote, name='randomquote'),
url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'),
url(r'^twitch/$', views.twitch, name='twitch'),
url(r'^tictactoe/$', views.tictactoe, name='tictactoe'),
# url(r'^react/', views.react, name='react'),
url(r'^react/simon', views.react, name='simon'),
url(r'^react/pomodoro', views.react, name='clock'),
url(r'^react/calculator', views.react, name='calc'),
]
| from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'),
# url(r'^contact/$', views.contact, name='contact'),
url(r'^projects/$', views.projects, name='projects'),
url(r'^tribute/$', views.tribute, name='tribute'),
url(r'^weather/$', views.weather, name='weather'),
url(r'^randomquote/$', views.randomquote, name='randomquote'),
url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'),
url(r'^twitch/$', views.twitch, name='twitch'),
url(r'^tictactoe/$', views.tictactoe, name='tictactoe'),
# url(r'^react/', views.react, name='react'),
url(r'^react/simon', views.react, name='simon'),
url(r'^react/pomodoro', views.react, name='clock'),
url(r'^react/calculator', views.react, name='calc'),
]
| Change URL pattern for contacts | Change URL pattern for contacts
| Python | mit | bacarlino/portfolio,bacarlino/portfolio,bacarlino/portfolio | ---
+++
@@ -1,10 +1,12 @@
from django.conf.urls import url
+from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
- url(r'^contact/$', views.contact, name='contact'),
+ url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'),
+ # url(r'^contact/$', views.contact, name='contact'),
url(r'^projects/$', views.projects, name='projects'),
url(r'^tribute/$', views.tribute, name='tribute'),
url(r'^weather/$', views.weather, name='weather'), |
6e433c59348ed4c47c040efb50c891c4759bcee4 | jedihttp/__main__.py | jedihttp/__main__.py | # Copyright 2015 Cedraro Andrea <a.cedraro@gmail.com>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import utils
utils.AddVendorFolderToSysPath()
import argparse
import waitress
import handlers
def ParseArgs():
parser = argparse.ArgumentParser()
parser.add_argument( '--port', type = int, default = 0,
help = 'server port')
return parser.parse_args()
def Main():
args = ParseArgs()
waitress.serve( handlers.app,
host = '127.0.0.1',
port = args.port )
if __name__ == "__main__":
Main()
| # Copyright 2015 Cedraro Andrea <a.cedraro@gmail.com>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import utils
utils.AddVendorFolderToSysPath()
import argparse
import waitress
import handlers
def ParseArgs():
parser = argparse.ArgumentParser()
parser.add_argument( '--host', type = str, default = '127.0.0.1',
help = 'server host' )
parser.add_argument( '--port', type = int, default = 0,
help = 'server port' )
return parser.parse_args()
def Main():
args = ParseArgs()
waitress.serve( handlers.app,
host = args.host,
port = args.port )
if __name__ == "__main__":
Main()
| Add command-line argument for server host | Add command-line argument for server host
| Python | apache-2.0 | vheon/JediHTTP,micbou/JediHTTP,micbou/JediHTTP,vheon/JediHTTP | ---
+++
@@ -21,16 +21,17 @@
def ParseArgs():
parser = argparse.ArgumentParser()
+ parser.add_argument( '--host', type = str, default = '127.0.0.1',
+ help = 'server host' )
parser.add_argument( '--port', type = int, default = 0,
- help = 'server port')
-
+ help = 'server port' )
return parser.parse_args()
def Main():
args = ParseArgs()
waitress.serve( handlers.app,
- host = '127.0.0.1',
+ host = args.host,
port = args.port )
if __name__ == "__main__": |
2ee8011b6c793c862b55272bf76c109c71fb5aaa | eigen/3.2/test/conanfile.py | eigen/3.2/test/conanfile.py | from conans.model.conan_file import ConanFile
from conans import CMake
import os
class DefaultNameConan(ConanFile):
name = "DefaultName"
version = "0.1"
settings = "os", "compiler", "arch", "build_type"
generators = "cmake"
requires = "eigen/3.2@jslee02/testing"
def build(self):
cmake = CMake(self.settings)
self.run('cmake . %s' % cmake.command_line)
self.run("cmake --build . %s" % cmake.build_config)
def imports(self):
self.copy(pattern="*.dll", dst="bin", src="bin")
self.copy(pattern="*.dylib", dst="bin", src="lib")
def test(self):
self.run("cd bin && .%smytest" % os.sep)
| from conans.model.conan_file import ConanFile
from conans import CMake
import os
class DefaultNameConan(ConanFile):
name = "DefaultName"
version = "0.1"
settings = "os", "compiler", "arch", "build_type"
generators = "cmake"
requires = "eigen/3.2@jslee02/stable"
def build(self):
cmake = CMake(self.settings)
self.run('cmake . %s' % cmake.command_line)
self.run("cmake --build . %s" % cmake.build_config)
def imports(self):
self.copy(pattern="*.dll", dst="bin", src="bin")
self.copy(pattern="*.dylib", dst="bin", src="lib")
def test(self):
self.run("cd bin && .%smytest" % os.sep)
| Test stable channel instead of testing channel for eigen | Test stable channel instead of testing channel for eigen
| Python | bsd-2-clause | jslee02/conan-dart,jslee02/conan-dart,jslee02/conan-dart | ---
+++
@@ -7,7 +7,7 @@
version = "0.1"
settings = "os", "compiler", "arch", "build_type"
generators = "cmake"
- requires = "eigen/3.2@jslee02/testing"
+ requires = "eigen/3.2@jslee02/stable"
def build(self):
cmake = CMake(self.settings) |
bd4506dc95ee7a778a5b0f062d6d0423ade5890c | alerts/lib/alert_plugin_set.py | alerts/lib/alert_plugin_set.py | from mozdef_util.plugin_set import PluginSet
from mozdef_util.utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
if 'utctimestamp' in message and 'summary' in message:
message_log_str = '{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary'])
logger.info(message_log_str)
return plugin_class.onMessage(message), metadata
| from mozdef_util.plugin_set import PluginSet
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
return plugin_class.onMessage(message), metadata
| Remove logger entry for alert plugins receiving alerts | Remove logger entry for alert plugins receiving alerts
| Python | mpl-2.0 | mozilla/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mozilla/MozDef,mozilla/MozDef | ---
+++
@@ -1,12 +1,7 @@
from mozdef_util.plugin_set import PluginSet
-from mozdef_util.utilities.logger import logger
class AlertPluginSet(PluginSet):
def send_message_to_plugin(self, plugin_class, message, metadata=None):
- if 'utctimestamp' in message and 'summary' in message:
- message_log_str = '{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary'])
- logger.info(message_log_str)
-
return plugin_class.onMessage(message), metadata |
1a4d2ea23ad37b63bab1751b7f3b7572f6804f14 | api/base/exceptions.py | api/base/exceptions.py |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response is not None:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
errors.append({'detail': {key: value}})
elif isinstance(message, list):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
errors.append({'detail': {key: value}})
elif isinstance(message, list):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
| Use if response since 'is not None' is unnecessary. | Use if response since 'is not None' is unnecessary.
| Python | apache-2.0 | Johnetordoff/osf.io,njantrania/osf.io,pattisdr/osf.io,baylee-d/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,mfraezz/osf.io,TomHeatwole/osf.io,cosenal/osf.io,erinspace/osf.io,caneruguz/osf.io,crcresearch/osf.io,binoculars/osf.io,RomanZWang/osf.io,samanehsan/osf.io,doublebits/osf.io,caseyrygt/osf.io,TomHeatwole/osf.io,njantrania/osf.io,zamattiac/osf.io,SSJohns/osf.io,samanehsan/osf.io,erinspace/osf.io,samanehsan/osf.io,laurenrevere/osf.io,doublebits/osf.io,mattclark/osf.io,MerlinZhang/osf.io,kch8qx/osf.io,mluo613/osf.io,aaxelb/osf.io,caseyrollins/osf.io,baylee-d/osf.io,KAsante95/osf.io,mluo613/osf.io,acshi/osf.io,zachjanicki/osf.io,sloria/osf.io,alexschiller/osf.io,TomHeatwole/osf.io,cosenal/osf.io,rdhyee/osf.io,cwisecarver/osf.io,rdhyee/osf.io,brianjgeiger/osf.io,amyshi188/osf.io,amyshi188/osf.io,jnayak1/osf.io,abought/osf.io,Nesiehr/osf.io,SSJohns/osf.io,kwierman/osf.io,KAsante95/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,cwisecarver/osf.io,saradbowman/osf.io,Nesiehr/osf.io,njantrania/osf.io,DanielSBrown/osf.io,ticklemepierce/osf.io,monikagrabowska/osf.io,emetsger/osf.io,Ghalko/osf.io,chennan47/osf.io,GageGaskins/osf.io,adlius/osf.io,binoculars/osf.io,arpitar/osf.io,monikagrabowska/osf.io,jnayak1/osf.io,billyhunt/osf.io,DanielSBrown/osf.io,sloria/osf.io,ZobairAlijan/osf.io,mluke93/osf.io,acshi/osf.io,monikagrabowska/osf.io,emetsger/osf.io,samchrisinger/osf.io,jmcarp/osf.io,mluke93/osf.io,arpitar/osf.io,acshi/osf.io,abought/osf.io,Nesiehr/osf.io,danielneis/osf.io,cwisecarver/osf.io,kwierman/osf.io,RomanZWang/osf.io,CenterForOpenScience/osf.io,MerlinZhang/osf.io,samchrisinger/osf.io,danielneis/osf.io,zamattiac/osf.io,sloria/osf.io,aaxelb/osf.io,wearpants/osf.io,leb2dg/osf.io,wearpants/osf.io,caseyrygt/osf.io,Nesiehr/osf.io,HalcyonChimera/osf.io,monikagrabowska/osf.io,RomanZWang/osf.io,jnayak1/osf.io,adlius/osf.io,sbt9uc/osf.io,zamattiac/osf.io,asanfilippo7/osf.io,Ghalko/osf.io,SSJohns/osf.io,zachjanicki/osf.io,caneruguz/osf.io,KAsante95/osf.io,pattisdr/osf.io,mluo613/osf.io,zamattiac/osf.io,acshi/osf.io,MerlinZhang/osf.io,kch8qx/osf.io,Ghalko/osf.io,CenterForOpenScience/osf.io,TomHeatwole/osf.io,chennan47/osf.io,kch8qx/osf.io,GageGaskins/osf.io,asanfilippo7/osf.io,binoculars/osf.io,felliott/osf.io,asanfilippo7/osf.io,petermalcolm/osf.io,cslzchen/osf.io,icereval/osf.io,chennan47/osf.io,caseyrygt/osf.io,TomBaxter/osf.io,kwierman/osf.io,haoyuchen1992/osf.io,kwierman/osf.io,petermalcolm/osf.io,crcresearch/osf.io,brandonPurvis/osf.io,amyshi188/osf.io,haoyuchen1992/osf.io,SSJohns/osf.io,ckc6cz/osf.io,GageGaskins/osf.io,petermalcolm/osf.io,ckc6cz/osf.io,billyhunt/osf.io,ZobairAlijan/osf.io,ckc6cz/osf.io,sbt9uc/osf.io,RomanZWang/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,mluke93/osf.io,sbt9uc/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,alexschiller/osf.io,leb2dg/osf.io,DanielSBrown/osf.io,danielneis/osf.io,felliott/osf.io,ticklemepierce/osf.io,alexschiller/osf.io,doublebits/osf.io,jmcarp/osf.io,rdhyee/osf.io,caseyrollins/osf.io,brandonPurvis/osf.io,arpitar/osf.io,laurenrevere/osf.io,jmcarp/osf.io,jnayak1/osf.io,mfraezz/osf.io,haoyuchen1992/osf.io,aaxelb/osf.io,samchrisinger/osf.io,emetsger/osf.io,njantrania/osf.io,brianjgeiger/osf.io,ckc6cz/osf.io,petermalcolm/osf.io,alexschiller/osf.io,GageGaskins/osf.io,cslzchen/osf.io,emetsger/osf.io,ticklemepierce/osf.io,mattclark/osf.io,saradbowman/osf.io,Ghalko/osf.io,alexschiller/osf.io,Johnetordoff/osf.io,cosenal/osf.io,ticklemepierce/osf.io,KAsante95/osf.io,chrisseto/osf.io,cslzchen/osf.io,zachjanicki/osf.io,hmoco/osf.io,zachjanicki/osf.io,caseyrollins/osf.io,brandonPurvis/osf.io,brandonPurvis/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,leb2dg/osf.io,icereval/osf.io,mattclark/osf.io,erinspace/osf.io,amyshi188/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,doublebits/osf.io,leb2dg/osf.io,billyhunt/osf.io,hmoco/osf.io,mluo613/osf.io,wearpants/osf.io,kch8qx/osf.io,abought/osf.io,danielneis/osf.io,TomBaxter/osf.io,jmcarp/osf.io,pattisdr/osf.io,mfraezz/osf.io,DanielSBrown/osf.io,sbt9uc/osf.io,MerlinZhang/osf.io,icereval/osf.io,billyhunt/osf.io,adlius/osf.io,doublebits/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,billyhunt/osf.io,samanehsan/osf.io,kch8qx/osf.io,chrisseto/osf.io,caseyrygt/osf.io,samchrisinger/osf.io,adlius/osf.io,wearpants/osf.io,aaxelb/osf.io,hmoco/osf.io,hmoco/osf.io,caneruguz/osf.io,ZobairAlijan/osf.io,brianjgeiger/osf.io,ZobairAlijan/osf.io,mluke93/osf.io,cwisecarver/osf.io,chrisseto/osf.io,crcresearch/osf.io,mluo613/osf.io,baylee-d/osf.io,rdhyee/osf.io,acshi/osf.io,cosenal/osf.io,felliott/osf.io,caneruguz/osf.io,haoyuchen1992/osf.io,felliott/osf.io,arpitar/osf.io,asanfilippo7/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,abought/osf.io,RomanZWang/osf.io,KAsante95/osf.io | ---
+++
@@ -14,7 +14,7 @@
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
- if response is not None:
+ if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems(): |
b5c9931d75b64d11681f40a7c7badea810f8592a | spiff/__init__.py | spiff/__init__.py | import logging
import inspect
def funcLog():
frame = inspect.stack()[1]
localVars = frame[0].f_locals
if 'self' in localVars:
logName = '%s.%s.%s'%(localVars['self'].__class__.__module__, localVars['self'].__class__.__name__, frame[3])
else:
logName = '%s.%s'%(frame[0].f_globals['__name__'], frame[3])
return logging.getLogger(logName)
| import logging
import inspect
def funcLog(*args, **kwargs):
frame = inspect.stack()[1]
localVars = frame[0].f_locals
if 'self' in localVars:
logName = '%s.%s.%s'%(localVars['self'].__class__.__module__, localVars['self'].__class__.__name__, frame[3])
else:
logName = '%s.%s'%(frame[0].f_globals['__name__'], frame[3])
logger = logging.getLogger(logName)
if len(args):
return logger.debug(*args, **kwargs)
return logger
| Add a funcLog shortcut to debug | Add a funcLog shortcut to debug
| Python | agpl-3.0 | SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff | ---
+++
@@ -1,11 +1,14 @@
import logging
import inspect
-def funcLog():
+def funcLog(*args, **kwargs):
frame = inspect.stack()[1]
localVars = frame[0].f_locals
if 'self' in localVars:
logName = '%s.%s.%s'%(localVars['self'].__class__.__module__, localVars['self'].__class__.__name__, frame[3])
else:
logName = '%s.%s'%(frame[0].f_globals['__name__'], frame[3])
- return logging.getLogger(logName)
+ logger = logging.getLogger(logName)
+ if len(args):
+ return logger.debug(*args, **kwargs)
+ return logger |
d87cb6b401e38a06c5d594e40ad813a9db0738e6 | taca/analysis/cli.py | taca/analysis/cli.py | """ CLI for the analysis subcommand
"""
import click
from taca.analysis import analysis as an
@click.group()
def analysis():
""" Analysis methods entry point """
pass
# analysis subcommands
@analysis.command()
@click.option('-r', '--run', type=click.Path(exists=True), default=None,
help='Demultiplex only a particular run')
def demultiplex(run):
""" Demultiplex all runs present in the data directories
"""
an.run_preprocessing(run)
@analysis.command()
@click.argument('rundir')
def transfer(rundir):
"""Transfers the run without qc"""
an.transfer_run(rundir)
| """ CLI for the analysis subcommand
"""
import click
from taca.analysis import analysis as an
@click.group()
def analysis():
""" Analysis methods entry point """
pass
# analysis subcommands
@analysis.command()
@click.option('-r', '--run', type=click.Path(exists=True), default=None,
help='Demultiplex only a particular run')
def demultiplex(run):
""" Demultiplex all runs present in the data directories
"""
an.run_preprocessing(run)
@analysis.command()
@click.option('-a','--analysis', is_flag=True, help='Trigger the analysis for the transferred flowcell')
@click.argument('rundir')
def transfer(rundir, analysis):
"""Transfers the run without qc"""
an.transfer_run(rundir, analysis=analysis)
| Add option for triggering or not the analysis | Add option for triggering or not the analysis
| Python | mit | senthil10/TACA,kate-v-stepanova/TACA,SciLifeLab/TACA,SciLifeLab/TACA,vezzi/TACA,guillermo-carrasco/TACA,senthil10/TACA,b97pla/TACA,kate-v-stepanova/TACA,SciLifeLab/TACA,b97pla/TACA,guillermo-carrasco/TACA,vezzi/TACA | ---
+++
@@ -19,7 +19,8 @@
an.run_preprocessing(run)
@analysis.command()
+@click.option('-a','--analysis', is_flag=True, help='Trigger the analysis for the transferred flowcell')
@click.argument('rundir')
-def transfer(rundir):
+def transfer(rundir, analysis):
"""Transfers the run without qc"""
- an.transfer_run(rundir)
+ an.transfer_run(rundir, analysis=analysis) |
74a76dd7e21c4248d6a19e55fde69b92169d4008 | osmfilter/parsing.py | osmfilter/parsing.py | from .compat import etree
from .entities import Node, Way, Relation
def parse(fp):
context = etree.iterparse(fp, events=('end',))
for action, elem in context:
# Act only on node, ways and relations
if elem.tag not in ('node', 'way', 'relation'):
continue
tags = {t.get('k'): t.get('v') for t in elem if t.tag == 'tag'}
osmid = int(elem.get('id'))
version = int(elem.get('version'))
if elem.tag == 'node':
e = Node(osmid, tags, version, elem.get('lat'), elem.get('lon'))
elif elem.tag == 'way':
nodes = [n.get('ref') for n in elem if n.tag == 'nd']
e = Way(osmid, tags, version, nodes)
elif elem.tag == 'relation':
members = [(m.get('type'), m.get('ref'), m.get('role')) for m in elem if m.tag == 'member']
e = Relation(osmid, tags, version, members)
xml_node_cleanup(elem)
yield e
def xml_node_cleanup(elem):
elem.clear()
while elem.getprevious() is not None:
del elem.getparent()[0]
| from threading import Thread
from .compat import etree
from .entities import Node, Way, Relation
def xml_node_cleanup(elem):
elem.clear()
while elem.getprevious() is not None:
del elem.getparent()[0]
def parse(fp):
context = etree.iterparse(fp, events=('end',))
for action, elem in context:
# Act only on node, ways and relations
if elem.tag not in ('node', 'way', 'relation'):
continue
tags = {t.get('k'): t.get('v') for t in elem if t.tag == 'tag'}
osmid = int(elem.get('id'))
version = int(elem.get('version'))
if elem.tag == 'node':
e = Node(osmid, tags, version, elem.get('lat'), elem.get('lon'))
elif elem.tag == 'way':
nodes = [n.get('ref') for n in elem if n.tag == 'nd']
e = Way(osmid, tags, version, nodes)
elif elem.tag == 'relation':
members = [(m.get('type'), m.get('ref'), m.get('role'))
for m in elem if m.tag == 'member']
e = Relation(osmid, tags, version, members)
xml_node_cleanup(elem)
yield e
class Reader(Thread):
def __init__(self, fp, queue):
super().__init__()
self.fp = fp
self.queue = queue
def run(self):
for item in parse(self.fp):
self.queue.put(item)
| Make Reader subclass of Thread | Make Reader subclass of Thread
| Python | mit | gileri/osmfiltering | ---
+++
@@ -1,5 +1,13 @@
+from threading import Thread
+
from .compat import etree
from .entities import Node, Way, Relation
+
+
+def xml_node_cleanup(elem):
+ elem.clear()
+ while elem.getprevious() is not None:
+ del elem.getparent()[0]
def parse(fp):
@@ -20,14 +28,20 @@
nodes = [n.get('ref') for n in elem if n.tag == 'nd']
e = Way(osmid, tags, version, nodes)
elif elem.tag == 'relation':
- members = [(m.get('type'), m.get('ref'), m.get('role')) for m in elem if m.tag == 'member']
+ members = [(m.get('type'), m.get('ref'), m.get('role'))
+ for m in elem if m.tag == 'member']
e = Relation(osmid, tags, version, members)
xml_node_cleanup(elem)
yield e
-def xml_node_cleanup(elem):
- elem.clear()
- while elem.getprevious() is not None:
- del elem.getparent()[0]
+class Reader(Thread):
+ def __init__(self, fp, queue):
+ super().__init__()
+ self.fp = fp
+ self.queue = queue
+
+ def run(self):
+ for item in parse(self.fp):
+ self.queue.put(item) |
675c6d78738a56cc556984553216ce92cf0ecd94 | test/parseResults.py | test/parseResults.py | #!/usr/bin/env python3
import json
import sys
PREFIXES = [
["FAIL", "PASS"],
["EXPECTED FAIL", "UNEXPECTED PASS"],
]
def parse_expected_failures():
expected_failures = set()
with open("expected-failures.txt", "r") as fp:
for line in fp:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
expected_failures.add(line)
return expected_failures
def main(filename):
expected_failures = parse_expected_failures()
with open(filename, "r") as fp:
results = json.load(fp)
unexpected_results = []
for test in results:
expected_failure = test["file"] in expected_failures
actual_result = test["result"]["pass"]
print("{} {}".format(PREFIXES[expected_failure][actual_result], test["file"]))
if actual_result == expected_failure:
if not actual_result:
print(test["rawResult"]["stderr"])
print(test["rawResult"]["stdout"])
print(test["result"]["message"])
unexpected_results.append(test)
if unexpected_results:
print("{} unexpected results:".format(len(unexpected_results)))
for unexpected in unexpected_results:
print("- {}".format(unexpected["file"]))
return False
print("All results as expected.")
return True
if __name__ == "__main__":
sys.exit(0 if main(sys.argv[1]) else 1)
| #!/usr/bin/env python3
import json
import sys
PREFIXES = [
["FAIL", "PASS"],
["EXPECTED FAIL", "UNEXPECTED PASS"],
]
def parse_expected_failures():
expected_failures = set()
with open("expected-failures.txt", "r") as fp:
for line in fp:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
expected_failures.add(line)
return expected_failures
def main(filename):
expected_failures = parse_expected_failures()
with open(filename, "r") as fp:
results = json.load(fp)
unexpected_results = []
for test in results:
expected_failure = test["file"] in expected_failures
actual_result = test["result"]["pass"]
print("{} {} ({})".format(PREFIXES[expected_failure][actual_result], test["file"], test["scenario"]))
if actual_result == expected_failure:
if not actual_result:
print(test["rawResult"]["stderr"])
print(test["rawResult"]["stdout"])
print(test["result"]["message"])
unexpected_results.append(test)
if unexpected_results:
print("{} unexpected results:".format(len(unexpected_results)))
for unexpected in unexpected_results:
print("- {}".format(unexpected["file"]))
return False
print("All results as expected.")
return True
if __name__ == "__main__":
sys.exit(0 if main(sys.argv[1]) else 1)
| Print the scenario when running 262-style tests. | Print the scenario when running 262-style tests.
| Python | isc | js-temporal/temporal-polyfill,js-temporal/temporal-polyfill,js-temporal/temporal-polyfill | ---
+++
@@ -31,7 +31,7 @@
for test in results:
expected_failure = test["file"] in expected_failures
actual_result = test["result"]["pass"]
- print("{} {}".format(PREFIXES[expected_failure][actual_result], test["file"]))
+ print("{} {} ({})".format(PREFIXES[expected_failure][actual_result], test["file"], test["scenario"]))
if actual_result == expected_failure:
if not actual_result:
print(test["rawResult"]["stderr"]) |
da516d06ab294dc2dde4bb671ab16653b1421314 | tests/performance.py | tests/performance.py | """Script to run performance check."""
import time
from examples.game_of_life import GameOfLife, GOLExperiment
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
]
NUM_STEPS = 10000
if __name__ == "__main__":
for name, model, experiment in MODELS:
ca = model(experiment)
start_time = time.time()
for j in range(NUM_STEPS):
ca.step()
time_passed = time.time() - start_time
speed = NUM_STEPS * ca.cells_num // time_passed
print("%s: %s cells/s" % (name, sizeof_fmt(speed)))
del ca
| """Script to run performance check."""
import time
from examples.game_of_life import (
GameOfLife, GOLExperiment
)
from examples.shifting_sands import (
ShiftingSands, ShiftingSandsExperiment
)
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
("Shifting Sands", ShiftingSands, ShiftingSandsExperiment),
]
NUM_STEPS = 10000
if __name__ == "__main__":
for name, model, experiment in MODELS:
ca = model(experiment)
start_time = time.time()
for j in range(NUM_STEPS):
ca.step()
time_passed = time.time() - start_time
speed = NUM_STEPS * ca.cells_num // time_passed
print("%s: %s cells/s" % (name, sizeof_fmt(speed)))
del ca
| Add Shifting Sands to benchmark tests | Add Shifting Sands to benchmark tests
| Python | mit | a5kin/hecate,a5kin/hecate | ---
+++
@@ -1,12 +1,18 @@
"""Script to run performance check."""
import time
-from examples.game_of_life import GameOfLife, GOLExperiment
+from examples.game_of_life import (
+ GameOfLife, GOLExperiment
+)
+from examples.shifting_sands import (
+ ShiftingSands, ShiftingSandsExperiment
+)
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
+ ("Shifting Sands", ShiftingSands, ShiftingSandsExperiment),
]
NUM_STEPS = 10000
|
d2130b64c63bdcfdea854db39fb21c7efe0b24e1 | tests/test_httpheader.py | tests/test_httpheader.py | # MIT licensed
# Copyright (c) 2021 lilydjwg <lilydjwg@gmail.com>, et al.
import pytest
pytestmark = pytest.mark.asyncio
async def test_redirection(get_version):
assert await get_version("jmeter-plugins-manager", {
"source": "httpheader",
"url": "https://www.unifiedremote.com/download/linux-x64-deb",
"regex": r'urserver-([\d.]+).deb',
}) != None
| # MIT licensed
# Copyright (c) 2021 lilydjwg <lilydjwg@gmail.com>, et al.
import pytest
pytestmark = pytest.mark.asyncio
async def test_redirection(get_version):
assert await get_version("unifiedremote", {
"source": "httpheader",
"url": "https://www.unifiedremote.com/download/linux-x64-deb",
"regex": r'urserver-([\d.]+).deb',
}) != None
| Correct package name in httpheader test | Correct package name in httpheader test
| Python | mit | lilydjwg/nvchecker | ---
+++
@@ -6,7 +6,7 @@
pytestmark = pytest.mark.asyncio
async def test_redirection(get_version):
- assert await get_version("jmeter-plugins-manager", {
+ assert await get_version("unifiedremote", {
"source": "httpheader",
"url": "https://www.unifiedremote.com/download/linux-x64-deb",
"regex": r'urserver-([\d.]+).deb', |
361a1a1ca88630981bb83a85648714c5bc4c5a89 | thinc/neural/_classes/feed_forward.py | thinc/neural/_classes/feed_forward.py | from .model import Model
from ... import describe
def _run_child_hooks(model, X, y):
for layer in model._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
X = layer(X)
@describe.on_data(_run_child_hooks)
class FeedForward(Model):
'''A feed-forward network, that chains multiple Model instances together.'''
name = 'feed-forward'
def __init__(self, layers, **kwargs):
self._layers = []
for layer in layers:
if isinstance(layer, FeedForward):
self._layers.extend(layer._layers)
else:
self._layers.append(layer)
Model.__init__(self, **kwargs)
@property
def input_shape(self):
return self._layers[0].input_shape
@property
def output_shape(self):
return self._layers[-1].output_shape
def begin_update(self, X, drop=0.):
callbacks = []
for layer in self._layers:
X, inc_layer_grad = layer.begin_update(X, drop=drop)
callbacks.append(inc_layer_grad)
def continue_update(gradient, sgd=None):
for callback in reversed(callbacks):
if gradient is None or callback == None:
break
gradient = callback(gradient, sgd)
return gradient
return X, continue_update
| from .model import Model
from ... import describe
def _run_child_hooks(model, X, y):
for layer in model._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
X = layer(X)
@describe.on_data(_run_child_hooks)
class FeedForward(Model):
'''A feed-forward network, that chains multiple Model instances together.'''
name = 'feed-forward'
def __init__(self, layers, **kwargs):
self._layers = []
for layer in layers:
if isinstance(layer, FeedForward):
self._layers.extend(layer._layers)
else:
self._layers.append(layer)
Model.__init__(self, **kwargs)
@property
def input_shape(self):
return self._layers[0].input_shape
@property
def output_shape(self):
return self._layers[-1].output_shape
def predict(self, X):
for layer in self._layers:
X = layer(X)
return X
def begin_update(self, X, drop=0.):
callbacks = []
for layer in self._layers:
X, inc_layer_grad = layer.begin_update(X, drop=drop)
callbacks.append(inc_layer_grad)
def continue_update(gradient, sgd=None):
for callback in reversed(callbacks):
if gradient is None or callback == None:
break
gradient = callback(gradient, sgd)
return gradient
return X, continue_update
| Add predict() path to feed-forward | Add predict() path to feed-forward
| Python | mit | explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc | ---
+++
@@ -30,6 +30,11 @@
def output_shape(self):
return self._layers[-1].output_shape
+ def predict(self, X):
+ for layer in self._layers:
+ X = layer(X)
+ return X
+
def begin_update(self, X, drop=0.):
callbacks = []
for layer in self._layers: |
76d9d1beaebf5b7d8e2ef051c8b8926724542387 | regenesis/storage.py | regenesis/storage.py | import os
import json
from regenesis.core import app
def cube_path(cube_name, ext):
return os.path.join(
app.config.get('DATA_DIRECTORY'),
cube_name + '.' + ext
)
def store_cube_raw(cube_name, cube_data):
fh = open(cube_path(cube_name, 'raw'), 'wb')
fh.write(cube_data.encode('utf-8'))
fh.close()
def load_cube_raw(cube_name):
fh = open(cube_path(cube_name, 'raw'), 'rb')
data = fh.read().decode('utf-8')
fh.close()
return data
def dump_cube_json(cube):
fh = open(cube_path(cube.name, 'json'), 'wb')
json.dump(cube, fh, cls=JSONEncoder, indent=2)
fh.close()
| import os
import json
from regenesis.core import app
def cube_path(cube_name, ext):
return os.path.join(
app.config.get('DATA_DIRECTORY'),
cube_name + '.' + ext
)
def exists_raw(cube_name):
return os.path.isfile(cube_path(cube_name, 'raw'))
def store_cube_raw(cube_name, cube_data):
fh = open(cube_path(cube_name, 'raw'), 'wb')
fh.write(cube_data.encode('utf-8'))
fh.close()
def load_cube_raw(cube_name):
fh = open(cube_path(cube_name, 'raw'), 'rb')
data = fh.read().decode('utf-8')
fh.close()
return data
def dump_cube_json(cube):
fh = open(cube_path(cube.name, 'json'), 'wb')
json.dump(cube, fh, cls=JSONEncoder, indent=2)
fh.close()
| Check if a cube exists on disk. | Check if a cube exists on disk. | Python | mit | pudo/regenesis,pudo/regenesis | ---
+++
@@ -7,6 +7,9 @@
app.config.get('DATA_DIRECTORY'),
cube_name + '.' + ext
)
+
+def exists_raw(cube_name):
+ return os.path.isfile(cube_path(cube_name, 'raw'))
def store_cube_raw(cube_name, cube_data):
fh = open(cube_path(cube_name, 'raw'), 'wb')
@@ -23,3 +26,4 @@
fh = open(cube_path(cube.name, 'json'), 'wb')
json.dump(cube, fh, cls=JSONEncoder, indent=2)
fh.close()
+ |
593c2ec0d62049cee9bedc282903491b670d811f | ci/set_secrets_file.py | ci/set_secrets_file.py | """
Move the right secrets file into place for Travis CI.
"""
| """
Move the right secrets file into place for Travis CI.
"""
import os
import shutil
from pathlib import Path
def move_secrets_file() -> None:
"""
Move the right secrets file to the current directory.
"""
branch = os.environ['TRAVIS_BRANCH']
is_pr = os.environ['TRAVIS_PULL_REQUEST'] != 'false'
is_master = branch == 'master'
secrets_dir = Path('ci_secrets')
if is_master and not is_pr:
secrets_path = secrets_dir / 'vuforia_secrets_master.env'
secrets_path = secrets_dir / 'vuforia_secrets.env'
shutil.copy(secrets_path, '.')
if __name__ == '__main__':
move_secrets_file()
| Add script to move secrets file | Add script to move secrets file
| Python | mit | adamtheturtle/vws-python,adamtheturtle/vws-python | ---
+++
@@ -1,3 +1,28 @@
"""
Move the right secrets file into place for Travis CI.
"""
+
+import os
+import shutil
+from pathlib import Path
+
+
+def move_secrets_file() -> None:
+ """
+ Move the right secrets file to the current directory.
+ """
+ branch = os.environ['TRAVIS_BRANCH']
+ is_pr = os.environ['TRAVIS_PULL_REQUEST'] != 'false'
+ is_master = branch == 'master'
+
+ secrets_dir = Path('ci_secrets')
+
+ if is_master and not is_pr:
+ secrets_path = secrets_dir / 'vuforia_secrets_master.env'
+
+ secrets_path = secrets_dir / 'vuforia_secrets.env'
+ shutil.copy(secrets_path, '.')
+
+
+if __name__ == '__main__':
+ move_secrets_file() |
982e523807b42d8258ddcc4b984399b46e8ad74f | tools/tsv_gen_embeddings.py | tools/tsv_gen_embeddings.py | #! /usr/bin/python3
import sys
import argparse
import xml_utils as u
import datetime
from collections import defaultdict
##------------------------------------------------------------
## can be called with:
## tsv_gen_embeddings *.xml dirs
##------------------------------------------------------------
def main (argv) :
parser = argparse.ArgumentParser(description='Generate tsv of embeddings from xml.',
formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=50))
parser.add_argument ('files', nargs='+')
parser.add_argument ('-v', '--verbosity', type=int, default=1,
choices=[0, 1, 2, 3], help='')
# help="increase output verbosity"
u.set_argv (argv)
args = parser.parse_args()
u.set_verbosity (args.verbosity)
u.set_argv (argv)
u.set_filetype ('embeddings')
verbose = 0
if verbose > 0:
print("files: ", args.files)
xml_files = u.generate_xml_file_list (args.files)
u.plot_embeddings (xml_files)
if __name__ == "__main__":
main (sys.argv)
| #! /usr/bin/python3
import sys
import argparse
import xml_utils as u
import datetime
from collections import defaultdict
##------------------------------------------------------------
## can be called with:
## tsv_gen_embeddings *.xml dirs
##------------------------------------------------------------
def main (argv) :
parser = argparse.ArgumentParser(description='Generate tsv of embeddings from xml.',
formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=50))
parser.add_argument ('files', nargs='+')
parser.add_argument ('-v', '--verbosity', type=int, default=1,
choices=[0, 1, 2, 3], help='')
# help="increase output verbosity"
u.set_argv (argv)
args = parser.parse_args()
u.set_verbosity (args.verbosity)
u.set_argv (argv)
u.set_filetype ('embeddings')
verbose = 0
if verbose > 0:
print("files: ", args.files)
xml_files = u.generate_xml_file_list (args.files)
u.write_embed_tsv (xml_files)
if __name__ == "__main__":
main (sys.argv)
| Write out tsv embedding files instead of plotting them. | Write out tsv embedding files instead of plotting them.
| Python | mit | hypraptive/bearid,hypraptive/bearid,hypraptive/bearid | ---
+++
@@ -27,7 +27,7 @@
print("files: ", args.files)
xml_files = u.generate_xml_file_list (args.files)
- u.plot_embeddings (xml_files)
+ u.write_embed_tsv (xml_files)
if __name__ == "__main__":
main (sys.argv) |
663edbc7b19d5cb99a78bc380359a0dbfae1f1aa | cmsplugin_rst/forms.py | cmsplugin_rst/forms.py | from cmsplugin_rst.models import RstPluginModel, rst_help_text
from django import forms
class RstPluginForm(forms.ModelForm):
body = forms.CharField(
widget=forms.Textarea(attrs={
'rows':30,
'cols':80,
'style':'font-family:monospace'
}),
help_text=rst_help_text
)
class Meta:
model = RstPluginModel
fields = ["name", "header_level", "body"] | from cmsplugin_rst.models import RstPluginModel, rst_help_text
from django import forms
class RstPluginForm(forms.ModelForm):
body = forms.CharField(
widget=forms.Textarea(attrs={
'rows':20,
'cols':80,
'style':'font-family:monospace'
}),
help_text=rst_help_text
)
class Meta:
model = RstPluginModel
fields = ["name", "header_level", "body"] | Tweak too high textarea for RST text. | Tweak too high textarea for RST text.
| Python | bsd-3-clause | ojii/cmsplugin-rst,pakal/cmsplugin-rst | ---
+++
@@ -7,7 +7,7 @@
body = forms.CharField(
widget=forms.Textarea(attrs={
- 'rows':30,
+ 'rows':20,
'cols':80,
'style':'font-family:monospace'
}), |
255a93e2e075a8db914e4736cb79fbdb58b41a24 | file_transfer/baltrad_to_s3.py | file_transfer/baltrad_to_s3.py | """
Baltrad to S3 porting
"""
import sys
from creds import URL, LOGIN, PASSWORD
import datamover as dm
def main():
"""Run data transfer from Baltrad to S3"""
# ------------------
# DATA TRANSFER
# ------------------
# Setup the connection of the Baltrad and S3
btos = dm.BaltradToS3(URL, LOGIN, PASSWORD, "lw-enram")
# Execute the transfer
btos.transfer(name_match="_vp_", overwrite=False, limit=None)
btos.report(reset_file=False, transfertype="Baltrad to S3")
# ------------------
# UPDATE COVERAGE
# ------------------
# Connect to S3 client
s3client = dm.S3EnramHandler("lw-enram")
# Rerun file list overview to extract the current coverage
coverage_count = s3client.count_enram_coverage(level='day')
with open("coverage.csv", 'w') as outfile:
dm.coverage_to_csv(outfile, coverage_count)
s3client.upload_file("coverage.csv", "coverage.csv")
# ----------------------------
# UPDATE ZIP FILE AVAILABILITY
# ----------------------------
# Rerun ZIP handling of S3 for the transferred files, given by report
s3client.create_zip_version(btos.transferred)
if __name__ == "__main__":
sys.exit(main())
| """
Baltrad to S3 porting
"""
import sys
from creds import URL, LOGIN, PASSWORD
import datamover as dm
def main():
"""Run data transfer from Baltrad to S3"""
# ------------------
# DATA TRANSFER
# ------------------
# Setup the connection of the Baltrad and S3
btos = dm.BaltradToS3(URL, LOGIN, PASSWORD, "lw-enram")
# Execute the transfer
btos.transfer(name_match="_vp_", overwrite=False, limit=None)
btos.report(reset_file=False, transfertype="Baltrad to S3")
# ---------------------------------------------
# UPDATE COVERAGE AND MOST RECENT FILE DATETIME
# ---------------------------------------------
# Connect to S3 client
s3client = dm.S3EnramHandler("lw-enram")
# Rerun file list overview to extract the current coverage
coverage_count, most_recent = s3client.count_enram_coverage(level='day')
# Save the coverage information on S3
with open("coverage.csv", 'w') as outfile:
dm.coverage_to_csv(outfile, coverage_count)
s3client.upload_file("coverage.csv", "coverage.csv")
# Save the last provided radar file information on S3
with open("radars.csv", 'w') as outfile:
dm.most_recent_to_csv(outfile, most_recent)
s3client.upload_file("radars.csv", "radars.csv")
# ----------------------------
# UPDATE ZIP FILE AVAILABILITY
# ----------------------------
# Rerun ZIP handling of S3 for the transferred files, given by report
s3client.create_zip_version(btos.transferred)
if __name__ == "__main__":
sys.exit(main())
| Extend data pipeline from baltrad | Extend data pipeline from baltrad
| Python | mit | enram/data-repository,enram/data-repository,enram/data-repository,enram/data-repository,enram/infrastructure,enram/infrastructure | ---
+++
@@ -23,18 +23,25 @@
btos.transfer(name_match="_vp_", overwrite=False, limit=None)
btos.report(reset_file=False, transfertype="Baltrad to S3")
- # ------------------
- # UPDATE COVERAGE
- # ------------------
+ # ---------------------------------------------
+ # UPDATE COVERAGE AND MOST RECENT FILE DATETIME
+ # ---------------------------------------------
# Connect to S3 client
s3client = dm.S3EnramHandler("lw-enram")
# Rerun file list overview to extract the current coverage
- coverage_count = s3client.count_enram_coverage(level='day')
+ coverage_count, most_recent = s3client.count_enram_coverage(level='day')
+
+ # Save the coverage information on S3
with open("coverage.csv", 'w') as outfile:
dm.coverage_to_csv(outfile, coverage_count)
s3client.upload_file("coverage.csv", "coverage.csv")
+
+ # Save the last provided radar file information on S3
+ with open("radars.csv", 'w') as outfile:
+ dm.most_recent_to_csv(outfile, most_recent)
+ s3client.upload_file("radars.csv", "radars.csv")
# ----------------------------
# UPDATE ZIP FILE AVAILABILITY |
fd721c76e30f776b04c7691ce536525561dd2cfa | sympy/matrices/expressions/transpose.py | sympy/matrices/expressions/transpose.py | from matexpr import MatrixExpr
from sympy import Basic
class Transpose(MatrixExpr):
"""Matrix Transpose
Represents the transpose of a matrix expression.
Use .T as shorthand
>>> from sympy import MatrixSymbol, Transpose
>>> A = MatrixSymbol('A', 3, 5)
>>> B = MatrixSymbol('B', 5, 3)
>>> Transpose(A)
A'
>>> A.T
A'
>>> Transpose(A*B)
B'*A'
"""
is_Transpose = True
def __new__(cls, mat):
if not mat.is_Matrix:
return mat
if hasattr(mat, '_eval_transpose'):
return mat._eval_transpose()
return Basic.__new__(cls, mat)
@property
def arg(self):
return self.args[0]
@property
def shape(self):
return self.arg.shape[::-1]
def _entry(self, i, j):
return self.arg._entry(j, i)
def _eval_transpose(self):
return self.arg
from matmul import MatMul
from matadd import MatAdd
| from matexpr import MatrixExpr
from sympy import Basic
class Transpose(MatrixExpr):
"""Matrix Transpose
Represents the transpose of a matrix expression.
Use .T as shorthand
>>> from sympy import MatrixSymbol, Transpose
>>> A = MatrixSymbol('A', 3, 5)
>>> B = MatrixSymbol('B', 5, 3)
>>> Transpose(A)
A'
>>> A.T
A'
>>> Transpose(A*B)
B'*A'
"""
is_Transpose = True
def __new__(cls, mat):
if not mat.is_Matrix:
return mat
if hasattr(mat, '_eval_transpose'):
return mat._eval_transpose()
return Basic.__new__(cls, mat)
@property
def arg(self):
return self.args[0]
@property
def shape(self):
return self.arg.shape[::-1]
def _entry(self, i, j):
return self.arg._entry(j, i)
def _eval_transpose(self):
return self.arg
| Remove unnecessary MatAdd and MatMul imports | Remove unnecessary MatAdd and MatMul imports
| Python | bsd-3-clause | drufat/sympy,hrashk/sympy,toolforger/sympy,yashsharan/sympy,AunShiLord/sympy,oliverlee/sympy,MridulS/sympy,Arafatk/sympy,shikil/sympy,MechCoder/sympy,lindsayad/sympy,kevalds51/sympy,iamutkarshtiwari/sympy,cswiercz/sympy,mafiya69/sympy,AkademieOlympia/sympy,Designist/sympy,garvitr/sympy,sahmed95/sympy,pandeyadarsh/sympy,vipulroxx/sympy,amitjamadagni/sympy,emon10005/sympy,ga7g08/sympy,postvakje/sympy,beni55/sympy,farhaanbukhsh/sympy,dqnykamp/sympy,pbrady/sympy,Mitchkoens/sympy,Titan-C/sympy,ga7g08/sympy,souravsingh/sympy,AkademieOlympia/sympy,Shaswat27/sympy,drufat/sympy,sahilshekhawat/sympy,chaffra/sympy,sahmed95/sympy,iamutkarshtiwari/sympy,Arafatk/sympy,yukoba/sympy,madan96/sympy,maniteja123/sympy,MridulS/sympy,kevalds51/sympy,maniteja123/sympy,atsao72/sympy,cswiercz/sympy,mafiya69/sympy,Sumith1896/sympy,Mitchkoens/sympy,Curious72/sympy,ahhda/sympy,pandeyadarsh/sympy,sahilshekhawat/sympy,ChristinaZografou/sympy,meghana1995/sympy,chaffra/sympy,dqnykamp/sympy,liangjiaxing/sympy,jamesblunt/sympy,lindsayad/sympy,Vishluck/sympy,grevutiu-gabriel/sympy,pbrady/sympy,Davidjohnwilson/sympy,atsao72/sympy,jbbskinny/sympy,sunny94/temp,Vishluck/sympy,sampadsaha5/sympy,ChristinaZografou/sympy,hrashk/sympy,mcdaniel67/sympy,kevalds51/sympy,debugger22/sympy,VaibhavAgarwalVA/sympy,sunny94/temp,hargup/sympy,Davidjohnwilson/sympy,drufat/sympy,jaimahajan1997/sympy,postvakje/sympy,ga7g08/sympy,kaichogami/sympy,moble/sympy,cccfran/sympy,Arafatk/sympy,debugger22/sympy,Sumith1896/sympy,asm666/sympy,sahmed95/sympy,cccfran/sympy,rahuldan/sympy,cswiercz/sympy,moble/sympy,skidzo/sympy,asm666/sympy,Davidjohnwilson/sympy,pbrady/sympy,meghana1995/sympy,hargup/sympy,Titan-C/sympy,bukzor/sympy,AunShiLord/sympy,madan96/sympy,Sumith1896/sympy,MechCoder/sympy,kumarkrishna/sympy,mafiya69/sympy,Gadal/sympy,AunShiLord/sympy,madan96/sympy,lindsayad/sympy,garvitr/sympy,kaushik94/sympy,grevutiu-gabriel/sympy,souravsingh/sympy,emon10005/sympy,chaffra/sympy,Vishluck/sympy,MridulS/sympy,abloomston/sympy,jerli/sympy,jamesblunt/sympy,vipulroxx/sympy,shipci/sympy,skidzo/sympy,saurabhjn76/sympy,yukoba/sympy,Titan-C/sympy,lidavidm/sympy,kumarkrishna/sympy,kmacinnis/sympy,Curious72/sympy,beni55/sympy,ahhda/sympy,jaimahajan1997/sympy,shipci/sympy,rahuldan/sympy,toolforger/sympy,atsao72/sympy,farhaanbukhsh/sympy,shikil/sympy,Gadal/sympy,Designist/sympy,cccfran/sympy,ChristinaZografou/sympy,Shaswat27/sympy,Mitchkoens/sympy,pandeyadarsh/sympy,liangjiaxing/sympy,asm666/sympy,VaibhavAgarwalVA/sympy,sampadsaha5/sympy,jbbskinny/sympy,aktech/sympy,atreyv/sympy,abloomston/sympy,skirpichev/omg,hrashk/sympy,jerli/sympy,toolforger/sympy,kaushik94/sympy,yukoba/sympy,rahuldan/sympy,wanglongqi/sympy,souravsingh/sympy,VaibhavAgarwalVA/sympy,abhiii5459/sympy,AkademieOlympia/sympy,jbbskinny/sympy,oliverlee/sympy,Gadal/sympy,lidavidm/sympy,saurabhjn76/sympy,flacjacket/sympy,beni55/sympy,Curious72/sympy,emon10005/sympy,yashsharan/sympy,kmacinnis/sympy,postvakje/sympy,shipci/sympy,abhiii5459/sympy,jerli/sympy,wyom/sympy,debugger22/sympy,grevutiu-gabriel/sympy,atreyv/sympy,oliverlee/sympy,aktech/sympy,bukzor/sympy,skidzo/sympy,saurabhjn76/sympy,MechCoder/sympy,wanglongqi/sympy,amitjamadagni/sympy,yashsharan/sympy,sahilshekhawat/sympy,jaimahajan1997/sympy,maniteja123/sympy,mcdaniel67/sympy,atreyv/sympy,garvitr/sympy,kumarkrishna/sympy,sampadsaha5/sympy,srjoglekar246/sympy,abhiii5459/sympy,farhaanbukhsh/sympy,kaichogami/sympy,iamutkarshtiwari/sympy,shikil/sympy,kaichogami/sympy,jamesblunt/sympy,meghana1995/sympy,wyom/sympy,wanglongqi/sympy,bukzor/sympy,Designist/sympy,abloomston/sympy,liangjiaxing/sympy,lidavidm/sympy,kaushik94/sympy,ahhda/sympy,hargup/sympy,wyom/sympy,dqnykamp/sympy,moble/sympy,aktech/sympy,kmacinnis/sympy,Shaswat27/sympy,diofant/diofant,vipulroxx/sympy,mcdaniel67/sympy,sunny94/temp | ---
+++
@@ -42,6 +42,3 @@
def _eval_transpose(self):
return self.arg
-
-from matmul import MatMul
-from matadd import MatAdd |
ed40088b5e913e70c161e8148ab76fdc0b6c5c46 | clt_utils/argparse.py | clt_utils/argparse.py | from datetime import datetime
import argparse
import os
def is_dir(string):
"""
Type check for a valid directory for ArgumentParser.
"""
if not os.path.isdir(string):
msg = '{0} is not a directory'.format(string)
raise argparse.ArgumentTypeError(msg)
return string
def is_file(string):
"""
Type check for a valid file for ArgumentParser.
"""
if not os.path.isfile(string):
msg = u'{0} is not a file'.format(string)
raise argparse.ArgumentTypeError(msg)
return string
def gt_zero(string):
"""
Type check for int > 0 for ArgumentParser.
"""
if not int(string) > 0:
msg = u'limit must be > 0'
raise argparse.ArgumentTypeError(msg)
return int(string)
def isodate(string):
try:
return datetime.strptime(string, '%Y-%m-%d').date()
except ValueError:
msg = u'date input must in the format of yyyy-mm-dd'
raise argparse.ArgumentTypeError(msg)
| from __future__ import absolute_import
from datetime import datetime
import argparse as _argparse
import os
def is_dir(string):
"""
Type check for a valid directory for ArgumentParser.
"""
if not os.path.isdir(string):
msg = '{0} is not a directory'.format(string)
raise _argparse.ArgumentTypeError(msg)
return string
def is_file(string):
"""
Type check for a valid file for ArgumentParser.
"""
if not os.path.isfile(string):
msg = u'{0} is not a file'.format(string)
raise _argparse.ArgumentTypeError(msg)
return string
def gt_zero(string):
"""
Type check for int > 0 for ArgumentParser.
"""
if not int(string) > 0:
msg = u'limit must be > 0'
raise _argparse.ArgumentTypeError(msg)
return int(string)
def isodate(string):
try:
return datetime.strptime(string, '%Y-%m-%d').date()
except ValueError:
msg = u'date input must in the format of yyyy-mm-dd'
raise _argparse.ArgumentTypeError(msg)
| Fix bug with self reference | Fix bug with self reference
| Python | apache-2.0 | 55minutes/clt-utils | ---
+++
@@ -1,5 +1,7 @@
+from __future__ import absolute_import
+
from datetime import datetime
-import argparse
+import argparse as _argparse
import os
@@ -9,7 +11,7 @@
"""
if not os.path.isdir(string):
msg = '{0} is not a directory'.format(string)
- raise argparse.ArgumentTypeError(msg)
+ raise _argparse.ArgumentTypeError(msg)
return string
@@ -19,7 +21,7 @@
"""
if not os.path.isfile(string):
msg = u'{0} is not a file'.format(string)
- raise argparse.ArgumentTypeError(msg)
+ raise _argparse.ArgumentTypeError(msg)
return string
@@ -29,7 +31,7 @@
"""
if not int(string) > 0:
msg = u'limit must be > 0'
- raise argparse.ArgumentTypeError(msg)
+ raise _argparse.ArgumentTypeError(msg)
return int(string)
@@ -38,4 +40,4 @@
return datetime.strptime(string, '%Y-%m-%d').date()
except ValueError:
msg = u'date input must in the format of yyyy-mm-dd'
- raise argparse.ArgumentTypeError(msg)
+ raise _argparse.ArgumentTypeError(msg) |
923ae01ab8beadfd73c5275f0c954510d3a13832 | coherence/__init__.py | coherence/__init__.py | import platform
import sys
__version_info__ = (0, 6, 7)
__version__ = '.'.join(map(str, __version_info__))
SERVER_ID = ','.join([platform.system(),
platform.release(),
'UPnP/1.0,Coherence UPnP framework',
__version__])
try:
from twisted import version as twisted_version
from twisted.web import version as twisted_web_version
from twisted.python.versions import Version
except ImportError, exc:
# log error to stderr, might be useful for debugging purpose
sys.stderr.write("Twisted >= 2.5 and Twisted.Web >= 2.5 are required. " \
"Please install them.\n")
raise
try:
if twisted_version < Version("twisted", 2, 5, 0):
raise ImportError("Twisted >= 2.5 is required. Please install it.")
except ImportError, exc:
# log error to stderr, might be useful for debugging purpose
for arg in exc.args:
sys.stderr.write("%s\n" % arg)
raise
| import platform
import sys
__version__ = "0.6.7.dev0"
SERVER_ID = ','.join([platform.system(),
platform.release(),
'UPnP/1.0,Coherence UPnP framework',
__version__])
try:
from twisted import version as twisted_version
from twisted.web import version as twisted_web_version
from twisted.python.versions import Version
except ImportError, exc:
# log error to stderr, might be useful for debugging purpose
sys.stderr.write("Twisted >= 2.5 and Twisted.Web >= 2.5 are required. " \
"Please install them.\n")
raise
try:
if twisted_version < Version("twisted", 2, 5, 0):
raise ImportError("Twisted >= 2.5 is required. Please install it.")
except ImportError, exc:
# log error to stderr, might be useful for debugging purpose
for arg in exc.args:
sys.stderr.write("%s\n" % arg)
raise
| Switch to PEP 440 compliant version string and bump to 0.6.7.dev0. | Switch to PEP 440 compliant version string and bump to 0.6.7.dev0.
| Python | mit | coherence-project/Coherence,coherence-project/Coherence | ---
+++
@@ -1,8 +1,7 @@
import platform
import sys
-__version_info__ = (0, 6, 7)
-__version__ = '.'.join(map(str, __version_info__))
+__version__ = "0.6.7.dev0"
SERVER_ID = ','.join([platform.system(),
platform.release(), |
0202320f5f07437292bfa293c2a6711416dab048 | vumi/transports/integrat/failures.py | vumi/transports/integrat/failures.py | # -*- test-case-name: vumi.transports.intergrat.tests.test_failures -*-
from vumi.transports.failures import FailureWorker
class IntegratFailureWorker(FailureWorker):
def do_retry(self, message, reason):
message = self.update_retry_metadata(message)
self.store_failure(message, reason, message['retry_metadata']['delay'])
def handle_failure(self, message, reason):
if reason == "connection refused":
self.do_retry(message, reason)
else:
self.store_failure(message, reason)
| # -*- test-case-name: vumi.transports.integrat.tests.test_failures -*-
from vumi.transports.failures import FailureWorker
class IntegratFailureWorker(FailureWorker):
def do_retry(self, message, reason):
message = self.update_retry_metadata(message)
self.store_failure(message, reason, message['retry_metadata']['delay'])
def handle_failure(self, message, reason):
if reason == "connection refused":
self.do_retry(message, reason)
else:
self.store_failure(message, reason)
| Fix link to failure tests. | Fix link to failure tests.
| Python | bsd-3-clause | TouK/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,harrissoerja/vumi,harrissoerja/vumi | ---
+++
@@ -1,4 +1,4 @@
-# -*- test-case-name: vumi.transports.intergrat.tests.test_failures -*-
+# -*- test-case-name: vumi.transports.integrat.tests.test_failures -*-
from vumi.transports.failures import FailureWorker
|
b5663776e89b1d406b2b93d291a346bd9235fcf1 | wafer/utils.py | wafer/utils.py | import functools
import unicodedata
from django.core.cache import get_cache
from django.conf import settings
def normalize_unicode(u):
"""Replace non-ASCII characters with closest ASCII equivalents
where possible.
"""
return unicodedata.normalize('NFKD', u).encode('ascii', 'ignore')
def cache_result(cache_key, timeout):
"""A decorator for caching the result of a function."""
def decorator(f):
cache_name = settings.WAFER_CACHE
@functools.wraps(f)
def wrapper(*args, **kw):
# replace this with cache.caches when we drop Django 1.6
# compatibility
cache = get_cache(cache_name)
result = cache.get(cache_key)
if result is None:
result = f(*args, **kw)
cache.set(cache_key, result, timeout)
return result
def invalidate():
cache = get_cache(cache_name)
cache.delete(cache_key)
wrapper.invalidate = invalidate
return wrapper
return decorator
| import functools
import unicodedata
from django.core.cache import get_cache
from django.conf import settings
def normalize_unicode(u):
"""Replace non-ASCII characters with closest ASCII equivalents
where possible.
"""
return unicodedata.normalize('NFKD', u).encode('ascii', 'ignore')
def cache_result(cache_key, timeout):
"""A decorator for caching the result of a function."""
def decorator(f):
cache_name = settings.WAFER_CACHE
@functools.wraps(f)
def wrapper(*args, **kw):
# replace this with cache.caches when we drop Django 1.6
# compatibility
cache = get_cache(cache_name)
result = cache.get(cache_key)
if result is None:
result = f(*args, **kw)
cache.set(cache_key, result, timeout)
return result
def invalidate():
cache = get_cache(cache_name)
cache.delete(cache_key)
wrapper.invalidate = invalidate
return wrapper
return decorator
class QueryTracker(object):
""" Track queries to database. """
def __enter__(self):
from django.conf import settings
from django.db import connection
self._debug = settings.DEBUG
settings.DEBUG = True
connection.queries = []
return self
def __exit__(self, *args, **kw):
from django.conf import settings
settings.DEBUG = self._debug
@property
def queries(self):
from django.db import connection
return connection.queries[:]
| Add query tracking utility for use in tests. | Add query tracking utility for use in tests.
| Python | isc | CarlFK/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CarlFK/wafer | ---
+++
@@ -34,3 +34,24 @@
wrapper.invalidate = invalidate
return wrapper
return decorator
+
+
+class QueryTracker(object):
+ """ Track queries to database. """
+
+ def __enter__(self):
+ from django.conf import settings
+ from django.db import connection
+ self._debug = settings.DEBUG
+ settings.DEBUG = True
+ connection.queries = []
+ return self
+
+ def __exit__(self, *args, **kw):
+ from django.conf import settings
+ settings.DEBUG = self._debug
+
+ @property
+ def queries(self):
+ from django.db import connection
+ return connection.queries[:] |
29f91d362689a53e04557588e47f1ac3e8d0fadc | server/lib/pricing.py | server/lib/pricing.py | def price(printTime, filamentUsed, filament=None):
return round((printTime/60/60)*filament['price'])
| def price(printTime, filamentUsed, filament=None):
return round((printTime/60/60)*200)
| Set constant price for all filaments | Set constant price for all filaments
| Python | agpl-3.0 | MakersLab/custom-print | ---
+++
@@ -1,2 +1,2 @@
def price(printTime, filamentUsed, filament=None):
- return round((printTime/60/60)*filament['price'])
+ return round((printTime/60/60)*200) |
edd2cc66fff3159699c28c8f86c52e6524ce9d86 | social_auth/fields.py | social_auth/fields.py | from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value):
"""
Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted.
"""
if self.blank and not value:
return None
if isinstance(value, basestring):
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
else:
return value
def validate(self, value, model_instance):
"""Check value is a valid JSON string, raise ValidationError on
error."""
super(JSONField, self).validate(value, model_instance)
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
def get_db_prep_value(self, value, connection, prepared=False):
"""Convert value to JSON string before save"""
try:
return simplejson.dumps(value)
except Exception, e:
raise ValidationError(str(e))
| from django.core.exceptions import ValidationError
from django.db import models
from django.utils import simplejson
class JSONField(models.TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
__metaclass__ = models.SubfieldBase
def to_python(self, value):
"""
Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted.
"""
if self.blank and not value:
return None
if isinstance(value, basestring):
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
else:
return value
def validate(self, value, model_instance):
"""Check value is a valid JSON string, raise ValidationError on
error."""
super(JSONField, self).validate(value, model_instance)
try:
return simplejson.loads(value)
except Exception, e:
raise ValidationError(str(e))
def get_prep_value(self, value):
"""Convert value to JSON string before save"""
try:
return simplejson.dumps(value)
except Exception, e:
raise ValidationError(str(e))
| Use get_prep_value instead of the database related one. Closes gh-42 | Use get_prep_value instead of the database related one. Closes gh-42
| Python | bsd-3-clause | vuchau/django-social-auth,getsentry/django-social-auth,1st/django-social-auth,michael-borisov/django-social-auth,michael-borisov/django-social-auth,beswarm/django-social-auth,lovehhf/django-social-auth,omab/django-social-auth,adw0rd/django-social-auth,mayankcu/Django-social,caktus/django-social-auth,antoviaque/django-social-auth-norel,vuchau/django-social-auth,thesealion/django-social-auth,dongguangming/django-social-auth,limdauto/django-social-auth,dongguangming/django-social-auth,vxvinh1511/django-social-auth,omab/django-social-auth,duoduo369/django-social-auth,VishvajitP/django-social-auth,brianmckinneyrocks/django-social-auth,beswarm/django-social-auth,MjAbuz/django-social-auth,brianmckinneyrocks/django-social-auth,czpython/django-social-auth,lovehhf/django-social-auth,MjAbuz/django-social-auth,sk7/django-social-auth,qas612820704/django-social-auth,gustavoam/django-social-auth,caktus/django-social-auth,gustavoam/django-social-auth,vxvinh1511/django-social-auth,krvss/django-social-auth,VishvajitP/django-social-auth,WW-Digital/django-social-auth,qas612820704/django-social-auth,thesealion/django-social-auth,limdauto/django-social-auth | ---
+++
@@ -34,7 +34,7 @@
except Exception, e:
raise ValidationError(str(e))
- def get_db_prep_value(self, value, connection, prepared=False):
+ def get_prep_value(self, value):
"""Convert value to JSON string before save"""
try:
return simplejson.dumps(value) |
111682e3c19784aa87d5f3d4b56149226e6f9d3b | app/tests/archives_tests/test_models.py | app/tests/archives_tests/test_models.py | import pytest
from tests.archives_tests.factories import ArchiveFactory
from tests.model_helpers import do_test_factory
@pytest.mark.django_db
class TestArchivesModels:
# test functions are added dynamically to this class
def test_study_str(self):
model = ArchiveFactory()
assert str(model) == "<{} {}>".format(
model.__class__.__name__, model.name
)
@pytest.mark.django_db
@pytest.mark.parametrize("factory", (ArchiveFactory,))
class TestFactories:
def test_factory_creation(self, factory):
do_test_factory(factory)
| import pytest
from django.core.exceptions import ObjectDoesNotExist
from tests.archives_tests.factories import ArchiveFactory
from tests.cases_tests.factories import ImageFactoryWithImageFile
from tests.model_helpers import do_test_factory
@pytest.mark.django_db
class TestArchivesModels:
# test functions are added dynamically to this class
def test_str(self):
model = ArchiveFactory()
assert str(model) == "<{} {}>".format(
model.__class__.__name__, model.name
)
@pytest.mark.django_db
@pytest.mark.parametrize("factory", (ArchiveFactory,))
class TestFactories:
def test_factory_creation(self, factory):
do_test_factory(factory)
@pytest.mark.django_db
class TestCascadeDelete:
def test_removes_all_related_models(
self, ArchivePatientStudyImageSet, AnnotationSetForImage
):
apsi_set = ArchivePatientStudyImageSet
annotation_set = AnnotationSetForImage(
retina_grader=True, image=apsi_set.images111[0]
)
image_not_in_archive = ImageFactoryWithImageFile(
study=apsi_set.study111
)
apsi_set.archive1.delete()
all_deleted_models = (
apsi_set.archive1,
apsi_set.patient11,
apsi_set.patient12,
apsi_set.study111,
apsi_set.study112,
apsi_set.study113,
apsi_set.study121,
apsi_set.study122,
*apsi_set.images111,
*apsi_set.images112,
*apsi_set.images113,
*apsi_set.images122,
*apsi_set.images121,
annotation_set.measurement,
annotation_set.boolean,
annotation_set.polygon,
annotation_set.coordinatelist,
annotation_set.singlelandmarks[0],
annotation_set.etdrs,
annotation_set.integer,
image_not_in_archive,
)
for model in all_deleted_models:
with pytest.raises(ObjectDoesNotExist):
assert model.refresh_from_db()
not_deleted_models = (
apsi_set.archive2,
*apsi_set.images211,
annotation_set.landmark,
*annotation_set.singlelandmarks[1:],
)
for model in not_deleted_models:
assert model.refresh_from_db() is None
| Add test for cascading deletion of archive | Add test for cascading deletion of archive
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django | ---
+++
@@ -1,12 +1,15 @@
import pytest
+from django.core.exceptions import ObjectDoesNotExist
+
from tests.archives_tests.factories import ArchiveFactory
+from tests.cases_tests.factories import ImageFactoryWithImageFile
from tests.model_helpers import do_test_factory
@pytest.mark.django_db
class TestArchivesModels:
# test functions are added dynamically to this class
- def test_study_str(self):
+ def test_str(self):
model = ArchiveFactory()
assert str(model) == "<{} {}>".format(
model.__class__.__name__, model.name
@@ -18,3 +21,53 @@
class TestFactories:
def test_factory_creation(self, factory):
do_test_factory(factory)
+
+
+@pytest.mark.django_db
+class TestCascadeDelete:
+ def test_removes_all_related_models(
+ self, ArchivePatientStudyImageSet, AnnotationSetForImage
+ ):
+ apsi_set = ArchivePatientStudyImageSet
+ annotation_set = AnnotationSetForImage(
+ retina_grader=True, image=apsi_set.images111[0]
+ )
+ image_not_in_archive = ImageFactoryWithImageFile(
+ study=apsi_set.study111
+ )
+ apsi_set.archive1.delete()
+ all_deleted_models = (
+ apsi_set.archive1,
+ apsi_set.patient11,
+ apsi_set.patient12,
+ apsi_set.study111,
+ apsi_set.study112,
+ apsi_set.study113,
+ apsi_set.study121,
+ apsi_set.study122,
+ *apsi_set.images111,
+ *apsi_set.images112,
+ *apsi_set.images113,
+ *apsi_set.images122,
+ *apsi_set.images121,
+ annotation_set.measurement,
+ annotation_set.boolean,
+ annotation_set.polygon,
+ annotation_set.coordinatelist,
+ annotation_set.singlelandmarks[0],
+ annotation_set.etdrs,
+ annotation_set.integer,
+ image_not_in_archive,
+ )
+ for model in all_deleted_models:
+ with pytest.raises(ObjectDoesNotExist):
+ assert model.refresh_from_db()
+
+ not_deleted_models = (
+ apsi_set.archive2,
+ *apsi_set.images211,
+ annotation_set.landmark,
+ *annotation_set.singlelandmarks[1:],
+ )
+ for model in not_deleted_models:
+ assert model.refresh_from_db() is None |
0acbe43b91fab6a01b5a773c4ac494d01138f216 | engines/mako_engine.py | engines/mako_engine.py | #!/usr/bin/env python3
"""Provide the mako templating engine."""
from __future__ import print_function
from mako.template import Template
from mako.lookup import TemplateLookup
from . import Engine
class MakoEngine(Engine):
"""Mako templating engine."""
handle = 'mako'
def __init__(self, template, tolerant=False, **kwargs):
"""Initialize mako template."""
super(MakoEngine, self).__init__(**kwargs)
encoding_errors = 'replace' if tolerant else 'strict'
lookup = TemplateLookup(directories=['.'])
self.template = Template(template,
lookup=lookup,
encoding_errors=encoding_errors,
)
def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
return self.template.render(**mapping)
| #!/usr/bin/env python3
"""Provide the mako templating engine."""
from __future__ import print_function
from mako.template import Template
from mako.lookup import TemplateLookup
from . import Engine
class MakoEngine(Engine):
"""Mako templating engine."""
handle = 'mako'
def __init__(self, template, tolerant=False, **kwargs):
"""Initialize mako template."""
super(MakoEngine, self).__init__(**kwargs)
default_filters = ['filter_undefined'] if tolerant else None
encoding_errors = 'replace' if tolerant else 'strict'
imports = ['def filter_undefined(value):\n'
' if value is UNDEFINED:\n'
' return \'<UNDEFINED>\'\n'
' return value\n']
lookup = TemplateLookup(directories=['.'])
self.template = Template(template,
default_filters=default_filters,
encoding_errors=encoding_errors,
imports=imports,
lookup=lookup,
strict_undefined=not tolerant,
)
def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
return self.template.render(**mapping)
| Handle undefined names in tolerant mode in the mako engine. | Handle undefined names in tolerant mode in the mako engine.
| Python | mit | blubberdiblub/eztemplate | ---
+++
@@ -20,11 +20,19 @@
"""Initialize mako template."""
super(MakoEngine, self).__init__(**kwargs)
+ default_filters = ['filter_undefined'] if tolerant else None
encoding_errors = 'replace' if tolerant else 'strict'
+ imports = ['def filter_undefined(value):\n'
+ ' if value is UNDEFINED:\n'
+ ' return \'<UNDEFINED>\'\n'
+ ' return value\n']
lookup = TemplateLookup(directories=['.'])
self.template = Template(template,
+ default_filters=default_filters,
+ encoding_errors=encoding_errors,
+ imports=imports,
lookup=lookup,
- encoding_errors=encoding_errors,
+ strict_undefined=not tolerant,
)
def apply(self, mapping): |
d2a3f9b1118a965774e0002b2a7b480213bb3fde | alignak_backend_client/__init__.py | alignak_backend_client/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Alignak REST backend client library
This module is a Python library used the REST API of the Alignak backend
"""
# Application version and manifest
VERSION = (0, 5, 0)
__application__ = u"Alignak Backend client"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Alignak team"
__copyright__ = u"(c) 2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak backend client library"
__releasenotes__ = u"""Alignak backend client library"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend-client"
# Application manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Alignak REST backend client library
This module is a Python library used the REST API of the Alignak backend
"""
# Application version and manifest
VERSION = (0, 5, 1)
__application__ = u"Alignak Backend client"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Alignak team"
__copyright__ = u"(c) 2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak backend client library"
__releasenotes__ = u"""Alignak backend client library"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend-client"
# Application manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
| Set version number as 0.5.1 | Set version number as 0.5.1
| Python | agpl-3.0 | Alignak-monitoring-contrib/alignak-backend-client,Alignak-monitoring-contrib/alignakbackend-api-client,Alignak-monitoring-contrib/alignakbackend-api-client,Alignak-monitoring-contrib/alignak-backend-client | ---
+++
@@ -8,7 +8,7 @@
This module is a Python library used the REST API of the Alignak backend
"""
# Application version and manifest
-VERSION = (0, 5, 0)
+VERSION = (0, 5, 1)
__application__ = u"Alignak Backend client"
__short_version__ = '.'.join((str(each) for each in VERSION[:2])) |
c2364bfe321bc19ab2d648fc77c8111522654237 | adhocracy/migration/versions/032_remove_comment_title.py | adhocracy/migration/versions/032_remove_comment_title.py | from datetime import datetime
from sqlalchemy import MetaData, Column, ForeignKey, Table
from sqlalchemy import DateTime, Integer, Unicode, UnicodeText
metadata = MetaData()
old_revision_table = Table('revision', metadata,
Column('id', Integer, primary_key=True),
Column('create_time', DateTime, default=datetime.utcnow),
Column('text', UnicodeText(), nullable=False),
Column('sentiment', Integer, default=0),
Column('user_id', Integer, ForeignKey('user.id'), nullable=False),
Column('comment_id', Integer, ForeignKey('comment.id'), nullable=False),
Column('title', Unicode(255), nullable=True)
)
def upgrade(migrate_engine):
metadata.bind = migrate_engine
revisions_table = Table('revision', metadata, autoload=True)
q = migrate_engine.execute(revisions_table.select())
for (id, _, text, _, _, _, title) in q:
title = title and title.strip() or ''
if len(title) < 5:
continue
if title.startswith('Re: '):
continue
new_text = ('**%(title)s**\n'
'\n'
'%(text)s') % {'title': title,
'text': text}
update_statement = revisions_table.update(
revisions_table.c.id == id, {'text': new_text})
migrate_engine.execute(update_statement)
revisions_table.c.title.drop()
raise Exception('ksjdfkl')
def downgrade(migrate_engine):
raise NotImplementedError()
| from datetime import datetime
from sqlalchemy import MetaData, Column, ForeignKey, Table
from sqlalchemy import DateTime, Integer, Unicode, UnicodeText
metadata = MetaData()
old_revision_table = Table('revision', metadata,
Column('id', Integer, primary_key=True),
Column('create_time', DateTime, default=datetime.utcnow),
Column('text', UnicodeText(), nullable=False),
Column('sentiment', Integer, default=0),
Column('user_id', Integer, ForeignKey('user.id'), nullable=False),
Column('comment_id', Integer, ForeignKey('comment.id'), nullable=False),
Column('title', Unicode(255), nullable=True)
)
def upgrade(migrate_engine):
metadata.bind = migrate_engine
revisions_table = Table('revision', metadata, autoload=True)
q = migrate_engine.execute(revisions_table.select())
for (id, _, text, _, _, _, title) in q:
title = title and title.strip() or ''
if len(title) < 5:
continue
if title.startswith('Re: '):
continue
new_text = ('**%(title)s**\n'
'\n'
'%(text)s') % {'title': title,
'text': text}
update_statement = revisions_table.update(
revisions_table.c.id == id, {'text': new_text})
migrate_engine.execute(update_statement)
revisions_table.c.title.drop()
def downgrade(migrate_engine):
raise NotImplementedError()
| Remove silly exception inserted for testing | Remove silly exception inserted for testing
| Python | agpl-3.0 | SysTheron/adhocracy,DanielNeugebauer/adhocracy,SysTheron/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,SysTheron/adhocracy,alkadis/vcv,liqd/adhocracy,alkadis/vcv,phihag/adhocracy,liqd/adhocracy,alkadis/vcv,liqd/adhocracy,phihag/adhocracy,liqd/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,alkadis/vcv,phihag/adhocracy | ---
+++
@@ -36,7 +36,6 @@
migrate_engine.execute(update_statement)
revisions_table.c.title.drop()
- raise Exception('ksjdfkl')
def downgrade(migrate_engine): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.