Datasets:

commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
538f8e3382e274402f2f71ba79439fae0828b3cf
IPython/html.py
IPython/html.py
# Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import sys from warnings import warn warn("The `IPython.html` package has been deprecated. " "You should import from jupyter_notebook instead.") from IPython.utils.shimmodule import ShimModule sys.modules['IPython.html'] = ShimModule( src='IPython.html', mirror='jupyter_notebook') if __name__ == '__main__': from jupyter_notebook import notebookapp as app app.launch_new_instance()
# Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import sys from warnings import warn warn("The `IPython.html` package has been deprecated. " "You should import from `jupyter_notebook` and `jupyter_widgets` instead.") from IPython.utils.shimmodule import ShimModule sys.modules['IPython.html'] = ShimModule( src='IPython.html', mirror='jupyter_notebook') sys.modules['IPython.html.widgets'] = ShimModule( src='IPython.html.widgets', mirror='jupyter_widgets') if __name__ == '__main__': from jupyter_notebook import notebookapp as app app.launch_new_instance()
Add shim to new widgets repository.
Add shim to new widgets repository.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
# Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import sys from warnings import warn warn("The `IPython.html` package has been deprecated. " - "You should import from jupyter_notebook instead.") + "You should import from `jupyter_notebook` and `jupyter_widgets` instead.") from IPython.utils.shimmodule import ShimModule sys.modules['IPython.html'] = ShimModule( src='IPython.html', mirror='jupyter_notebook') + sys.modules['IPython.html.widgets'] = ShimModule( + src='IPython.html.widgets', mirror='jupyter_widgets') if __name__ == '__main__': from jupyter_notebook import notebookapp as app app.launch_new_instance()
Add shim to new widgets repository.
## Code Before: # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import sys from warnings import warn warn("The `IPython.html` package has been deprecated. " "You should import from jupyter_notebook instead.") from IPython.utils.shimmodule import ShimModule sys.modules['IPython.html'] = ShimModule( src='IPython.html', mirror='jupyter_notebook') if __name__ == '__main__': from jupyter_notebook import notebookapp as app app.launch_new_instance() ## Instruction: Add shim to new widgets repository. ## Code After: # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import sys from warnings import warn warn("The `IPython.html` package has been deprecated. " "You should import from `jupyter_notebook` and `jupyter_widgets` instead.") from IPython.utils.shimmodule import ShimModule sys.modules['IPython.html'] = ShimModule( src='IPython.html', mirror='jupyter_notebook') sys.modules['IPython.html.widgets'] = ShimModule( src='IPython.html.widgets', mirror='jupyter_widgets') if __name__ == '__main__': from jupyter_notebook import notebookapp as app app.launch_new_instance()
0b5a657339870c7669082c39f8290c88732aa92e
extractor.py
extractor.py
from extraction.core import ExtractionRunner from extraction.runnables import Extractor, RunnableError, Filter, ExtractorResult import os import sys import grobid import pdfbox import filters if __name__ == '__main__': runner = ExtractionRunner() runner.add_runnable(pdfbox.PDFBoxPlainTextExtractor) runner.add_runnable(filters.AcademicPaperFilter) argc = len(sys.argv) if argc == 2: runner.run_from_file(sys.argv[1]) elif argc == 3: runner.run_from_file(sys.argv[1], output_dir = sys.argv[2]) else: print("USAGE: python {0} path_to_pdf [output_directory]")
from extraction.core import ExtractionRunner from extraction.runnables import Extractor, RunnableError, Filter, ExtractorResult import os import sys import grobid import pdfbox import filters def get_extraction_runner(): runner = ExtractionRunner() runner.add_runnable(grobid.GrobidPlainTextExtractor) # OR # runner.add_runnable(pdfbox.PDFBoxPlainTextExtractor) runner.add_runnable(filters.AcademicPaperFilter) return runner if __name__ == '__main__': runner = get_extraction_runner() argc = len(sys.argv) if argc == 2: runner.run_from_file(sys.argv[1]) elif argc == 3: runner.run_from_file(sys.argv[1], output_dir = sys.argv[2]) else: print("USAGE: python {0} path_to_pdf [output_directory]")
Make code a little cleaner
Make code a little cleaner
Python
apache-2.0
Tiger66639/new-csx-extractor,SeerLabs/new-csx-extractor,Tiger66639/new-csx-extractor,SeerLabs/new-csx-extractor,Tiger66639/new-csx-extractor,Tiger66639/new-csx-extractor,SeerLabs/new-csx-extractor,SeerLabs/new-csx-extractor
from extraction.core import ExtractionRunner from extraction.runnables import Extractor, RunnableError, Filter, ExtractorResult import os import sys import grobid import pdfbox import filters - if __name__ == '__main__': + def get_extraction_runner(): runner = ExtractionRunner() + + runner.add_runnable(grobid.GrobidPlainTextExtractor) + # OR - runner.add_runnable(pdfbox.PDFBoxPlainTextExtractor) + # runner.add_runnable(pdfbox.PDFBoxPlainTextExtractor) + runner.add_runnable(filters.AcademicPaperFilter) + + return runner + + + if __name__ == '__main__': + runner = get_extraction_runner() argc = len(sys.argv) if argc == 2: runner.run_from_file(sys.argv[1]) elif argc == 3: runner.run_from_file(sys.argv[1], output_dir = sys.argv[2]) else: print("USAGE: python {0} path_to_pdf [output_directory]")
Make code a little cleaner
## Code Before: from extraction.core import ExtractionRunner from extraction.runnables import Extractor, RunnableError, Filter, ExtractorResult import os import sys import grobid import pdfbox import filters if __name__ == '__main__': runner = ExtractionRunner() runner.add_runnable(pdfbox.PDFBoxPlainTextExtractor) runner.add_runnable(filters.AcademicPaperFilter) argc = len(sys.argv) if argc == 2: runner.run_from_file(sys.argv[1]) elif argc == 3: runner.run_from_file(sys.argv[1], output_dir = sys.argv[2]) else: print("USAGE: python {0} path_to_pdf [output_directory]") ## Instruction: Make code a little cleaner ## Code After: from extraction.core import ExtractionRunner from extraction.runnables import Extractor, RunnableError, Filter, ExtractorResult import os import sys import grobid import pdfbox import filters def get_extraction_runner(): runner = ExtractionRunner() runner.add_runnable(grobid.GrobidPlainTextExtractor) # OR # runner.add_runnable(pdfbox.PDFBoxPlainTextExtractor) runner.add_runnable(filters.AcademicPaperFilter) return runner if __name__ == '__main__': runner = get_extraction_runner() argc = len(sys.argv) if argc == 2: runner.run_from_file(sys.argv[1]) elif argc == 3: runner.run_from_file(sys.argv[1], output_dir = sys.argv[2]) else: print("USAGE: python {0} path_to_pdf [output_directory]")
af182857b4a70245b0b06bbf37e2d67e0ded493f
ez_gpg/ui.py
ez_gpg/ui.py
import gi import gnupg # Requires python3-gnupg gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="EZ GPG") self.connect("delete-event", Gtk.main_quit) self.set_border_width(30) gpg_keys_list = Gtk.ListStore(str, str) for key in self._get_gpg_keys(): gpg_keys_list.append([key['keyid'], "%s %s" % (key['keyid'], key['uids'][0])]) gpg_key_combo_box = Gtk.ComboBox.new_with_model_and_entry(gpg_keys_list) gpg_key_combo_box.set_entry_text_column(1) self.add(gpg_key_combo_box) def _get_gpg_keys(self): gpg = gnupg.GPG() return gpg.list_keys() class EzGpg(Gtk.Window): def launch(self): MainWindow().show_all() Gtk.main()
import gi import gnupg # Requires python3-gnupg gi.require_version('Gtk', '3.0') from gi.repository import Gtk class GpgKeyList(Gtk.ComboBox): def __init__(self): Gtk.ComboBox.__init__(self) gpg_keys_list = Gtk.ListStore(str, str) for key in self._get_gpg_keys(): key_id = key['keyid'] key_name = "%s %s" % (key['keyid'], key['uids'][0]) gpg_keys_list.append([key_id, key_name]) cell = Gtk.CellRendererText() self.pack_start(cell, True) self.add_attribute(cell, 'text', 1) self.set_model(gpg_keys_list) self.set_entry_text_column(1) def _get_gpg_keys(self): gpg = gnupg.GPG() return gpg.list_keys() class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="EZ GPG") self.connect("delete-event", Gtk.main_quit) self.set_border_width(30) self.set_position(Gtk.WindowPosition.CENTER) gpg_key_combo = GpgKeyList() self.add(gpg_key_combo) class EzGpg(Gtk.Window): def launch(self): MainWindow().show_all() Gtk.main()
Split out gpg key list into its own class
Split out gpg key list into its own class This will make it easy to break out into a module when we need it. In the process, window was also set to be in the center of the user's screen.
Python
lgpl-2.1
sgnn7/ez_gpg,sgnn7/ez_gpg
import gi import gnupg # Requires python3-gnupg gi.require_version('Gtk', '3.0') from gi.repository import Gtk + class GpgKeyList(Gtk.ComboBox): + def __init__(self): + Gtk.ComboBox.__init__(self) + + gpg_keys_list = Gtk.ListStore(str, str) + for key in self._get_gpg_keys(): + key_id = key['keyid'] + key_name = "%s %s" % (key['keyid'], key['uids'][0]) + + gpg_keys_list.append([key_id, key_name]) + + cell = Gtk.CellRendererText() + self.pack_start(cell, True) + self.add_attribute(cell, 'text', 1) + + self.set_model(gpg_keys_list) + self.set_entry_text_column(1) + + def _get_gpg_keys(self): + gpg = gnupg.GPG() + + return gpg.list_keys() + + class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="EZ GPG") self.connect("delete-event", Gtk.main_quit) self.set_border_width(30) + self.set_position(Gtk.WindowPosition.CENTER) + gpg_key_combo = GpgKeyList() - gpg_keys_list = Gtk.ListStore(str, str) - for key in self._get_gpg_keys(): - gpg_keys_list.append([key['keyid'], "%s %s" % (key['keyid'], key['uids'][0])]) - gpg_key_combo_box = Gtk.ComboBox.new_with_model_and_entry(gpg_keys_list) - gpg_key_combo_box.set_entry_text_column(1) - - self.add(gpg_key_combo_box) + self.add(gpg_key_combo) - - def _get_gpg_keys(self): - gpg = gnupg.GPG() - - return gpg.list_keys() class EzGpg(Gtk.Window): def launch(self): MainWindow().show_all() Gtk.main()
Split out gpg key list into its own class
## Code Before: import gi import gnupg # Requires python3-gnupg gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="EZ GPG") self.connect("delete-event", Gtk.main_quit) self.set_border_width(30) gpg_keys_list = Gtk.ListStore(str, str) for key in self._get_gpg_keys(): gpg_keys_list.append([key['keyid'], "%s %s" % (key['keyid'], key['uids'][0])]) gpg_key_combo_box = Gtk.ComboBox.new_with_model_and_entry(gpg_keys_list) gpg_key_combo_box.set_entry_text_column(1) self.add(gpg_key_combo_box) def _get_gpg_keys(self): gpg = gnupg.GPG() return gpg.list_keys() class EzGpg(Gtk.Window): def launch(self): MainWindow().show_all() Gtk.main() ## Instruction: Split out gpg key list into its own class ## Code After: import gi import gnupg # Requires python3-gnupg gi.require_version('Gtk', '3.0') from gi.repository import Gtk class GpgKeyList(Gtk.ComboBox): def __init__(self): Gtk.ComboBox.__init__(self) gpg_keys_list = Gtk.ListStore(str, str) for key in self._get_gpg_keys(): key_id = key['keyid'] key_name = "%s %s" % (key['keyid'], key['uids'][0]) gpg_keys_list.append([key_id, key_name]) cell = Gtk.CellRendererText() self.pack_start(cell, True) self.add_attribute(cell, 'text', 1) self.set_model(gpg_keys_list) self.set_entry_text_column(1) def _get_gpg_keys(self): gpg = gnupg.GPG() return gpg.list_keys() class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="EZ GPG") self.connect("delete-event", Gtk.main_quit) self.set_border_width(30) self.set_position(Gtk.WindowPosition.CENTER) gpg_key_combo = GpgKeyList() self.add(gpg_key_combo) class EzGpg(Gtk.Window): def launch(self): MainWindow().show_all() Gtk.main()
1dfbe495972a5f4d02ce374131f40d4474f24cc6
website/ember_osf_web/views.py
website/ember_osf_web/views.py
import os import json import requests from flask import send_from_directory, Response, stream_with_context from framework.sessions import session from website.settings import EXTERNAL_EMBER_APPS, PROXY_EMBER_APPS, EXTERNAL_EMBER_SERVER_TIMEOUT ember_osf_web_dir = os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['ember_osf_web']['path'])) routes = [ '/quickfiles/', '/<uid>/quickfiles/' ] def use_ember_app(**kwargs): if PROXY_EMBER_APPS: resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT) resp = Response(stream_with_context(resp.iter_content()), resp.status_code) else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): status = [{'id': stat.id if stat.id else stat.message, 'class': stat.css_class, 'jumbo': stat.jumbotron, 'dismiss': stat.dismissible, 'extra': stat.extra} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp
import os import json import requests from flask import send_from_directory, Response, stream_with_context from framework.sessions import session from website.settings import EXTERNAL_EMBER_APPS, PROXY_EMBER_APPS, EXTERNAL_EMBER_SERVER_TIMEOUT ember_osf_web_dir = os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['ember_osf_web']['path'])) routes = [ '/quickfiles/', '/<uid>/quickfiles/' ] def use_ember_app(**kwargs): if PROXY_EMBER_APPS: resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT) resp = Response(stream_with_context(resp.iter_content()), resp.status_code) else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): status = [{'id': stat[5] if stat[5] else stat[0], 'class': stat[2], 'jumbo': stat[1], 'dismiss': stat[3], 'extra': stat[6]} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp
Revert "Use namedtuple's getattr rather than indexing"
Revert "Use namedtuple's getattr rather than indexing" This reverts commit 5c4f93207c1fbfe9b9a478082d5f039a9e5ba720.
Python
apache-2.0
Johnetordoff/osf.io,adlius/osf.io,aaxelb/osf.io,felliott/osf.io,mfraezz/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,icereval/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,saradbowman/osf.io,mattclark/osf.io,aaxelb/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,sloria/osf.io,felliott/osf.io,felliott/osf.io,brianjgeiger/osf.io,binoculars/osf.io,pattisdr/osf.io,adlius/osf.io,sloria/osf.io,Johnetordoff/osf.io,mattclark/osf.io,mfraezz/osf.io,adlius/osf.io,mfraezz/osf.io,icereval/osf.io,cslzchen/osf.io,aaxelb/osf.io,erinspace/osf.io,aaxelb/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,icereval/osf.io,binoculars/osf.io,baylee-d/osf.io,baylee-d/osf.io,caseyrollins/osf.io,felliott/osf.io,erinspace/osf.io,caseyrollins/osf.io,saradbowman/osf.io,brianjgeiger/osf.io,brianjgeiger/osf.io,adlius/osf.io,baylee-d/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,sloria/osf.io
import os import json import requests from flask import send_from_directory, Response, stream_with_context from framework.sessions import session from website.settings import EXTERNAL_EMBER_APPS, PROXY_EMBER_APPS, EXTERNAL_EMBER_SERVER_TIMEOUT ember_osf_web_dir = os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['ember_osf_web']['path'])) routes = [ '/quickfiles/', '/<uid>/quickfiles/' ] def use_ember_app(**kwargs): if PROXY_EMBER_APPS: resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT) resp = Response(stream_with_context(resp.iter_content()), resp.status_code) else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): - status = [{'id': stat.id if stat.id else stat.message, 'class': stat.css_class, 'jumbo': stat.jumbotron, 'dismiss': stat.dismissible, 'extra': stat.extra} for stat in session.data['status']] + status = [{'id': stat[5] if stat[5] else stat[0], 'class': stat[2], 'jumbo': stat[1], 'dismiss': stat[3], 'extra': stat[6]} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp
Revert "Use namedtuple's getattr rather than indexing"
## Code Before: import os import json import requests from flask import send_from_directory, Response, stream_with_context from framework.sessions import session from website.settings import EXTERNAL_EMBER_APPS, PROXY_EMBER_APPS, EXTERNAL_EMBER_SERVER_TIMEOUT ember_osf_web_dir = os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['ember_osf_web']['path'])) routes = [ '/quickfiles/', '/<uid>/quickfiles/' ] def use_ember_app(**kwargs): if PROXY_EMBER_APPS: resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT) resp = Response(stream_with_context(resp.iter_content()), resp.status_code) else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): status = [{'id': stat.id if stat.id else stat.message, 'class': stat.css_class, 'jumbo': stat.jumbotron, 'dismiss': stat.dismissible, 'extra': stat.extra} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp ## Instruction: Revert "Use namedtuple's getattr rather than indexing" ## Code After: import os import json import requests from flask import send_from_directory, Response, stream_with_context from framework.sessions import session from website.settings import EXTERNAL_EMBER_APPS, PROXY_EMBER_APPS, EXTERNAL_EMBER_SERVER_TIMEOUT ember_osf_web_dir = os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['ember_osf_web']['path'])) routes = [ '/quickfiles/', '/<uid>/quickfiles/' ] def use_ember_app(**kwargs): if PROXY_EMBER_APPS: resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT) resp = Response(stream_with_context(resp.iter_content()), resp.status_code) else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): status = [{'id': stat[5] if stat[5] else stat[0], 'class': stat[2], 'jumbo': stat[1], 'dismiss': stat[3], 'extra': stat[6]} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp
6a8068942d985f0c125749d5f58ad7cb9cd189be
scanpointgenerator/linegenerator_step.py
scanpointgenerator/linegenerator_step.py
from linegenerator import LineGenerator import math as m class StepLineGenerator(LineGenerator): def __init__(self, name, units, start, end, step): num = int(m.floor((end - start)/step)) super(StepLineGenerator, self).__init__(name, units, start, step, num)
from linegenerator import LineGenerator class StepLineGenerator(LineGenerator): def __init__(self, name, units, start, end, step): num = int((end - start)/step) + 1 super(StepLineGenerator, self).__init__(name, units, start, step, num)
Add extra point to include start
Add extra point to include start
Python
apache-2.0
dls-controls/scanpointgenerator
from linegenerator import LineGenerator - import math as m class StepLineGenerator(LineGenerator): def __init__(self, name, units, start, end, step): - num = int(m.floor((end - start)/step)) + num = int((end - start)/step) + 1 super(StepLineGenerator, self).__init__(name, units, start, step, num)
Add extra point to include start
## Code Before: from linegenerator import LineGenerator import math as m class StepLineGenerator(LineGenerator): def __init__(self, name, units, start, end, step): num = int(m.floor((end - start)/step)) super(StepLineGenerator, self).__init__(name, units, start, step, num) ## Instruction: Add extra point to include start ## Code After: from linegenerator import LineGenerator class StepLineGenerator(LineGenerator): def __init__(self, name, units, start, end, step): num = int((end - start)/step) + 1 super(StepLineGenerator, self).__init__(name, units, start, step, num)
acd5a676b08e070c804bdae78abba266b47c67b5
libvcs/__about__.py
libvcs/__about__.py
__title__ = 'libvcs' __package_name__ = 'libvcs' __description__ = 'vcs abstraction layer' __version__ = '0.3.0' __author__ = 'Tony Narlock' __email__ = 'tony@git-pull.com' __license__ = 'MIT' __copyright__ = 'Copyright 2016 Tony Narlock'
__title__ = 'libvcs' __package_name__ = 'libvcs' __description__ = 'vcs abstraction layer' __version__ = '0.3.0' __author__ = 'Tony Narlock' __github__ = 'https://github.com/vcs-python/libvcs' __pypi__ = 'https://pypi.org/project/libvcs/' __email__ = 'tony@git-pull.com' __license__ = 'MIT' __copyright__ = 'Copyright 2016- Tony Narlock'
Add pypi + github to metadata
Add pypi + github to metadata
Python
mit
tony/libvcs
__title__ = 'libvcs' __package_name__ = 'libvcs' __description__ = 'vcs abstraction layer' __version__ = '0.3.0' __author__ = 'Tony Narlock' + __github__ = 'https://github.com/vcs-python/libvcs' + __pypi__ = 'https://pypi.org/project/libvcs/' __email__ = 'tony@git-pull.com' __license__ = 'MIT' - __copyright__ = 'Copyright 2016 Tony Narlock' + __copyright__ = 'Copyright 2016- Tony Narlock'
Add pypi + github to metadata
## Code Before: __title__ = 'libvcs' __package_name__ = 'libvcs' __description__ = 'vcs abstraction layer' __version__ = '0.3.0' __author__ = 'Tony Narlock' __email__ = 'tony@git-pull.com' __license__ = 'MIT' __copyright__ = 'Copyright 2016 Tony Narlock' ## Instruction: Add pypi + github to metadata ## Code After: __title__ = 'libvcs' __package_name__ = 'libvcs' __description__ = 'vcs abstraction layer' __version__ = '0.3.0' __author__ = 'Tony Narlock' __github__ = 'https://github.com/vcs-python/libvcs' __pypi__ = 'https://pypi.org/project/libvcs/' __email__ = 'tony@git-pull.com' __license__ = 'MIT' __copyright__ = 'Copyright 2016- Tony Narlock'
7efcc9987f827eec56677d95bc7ad873208b392f
saw/parser/sentences.py
saw/parser/sentences.py
import base from blocks import Blocks import re class Sentences(base.Base): _type = 'sentences' child_class = Blocks @staticmethod def parse(text): #re.split('\!|\?|\. | \.',text) result = [] prev = 0 # we allow .09 as not end of sentences #for m in re.finditer('[\!\?]+|\.+(?:\s+|$|\?|\!)', text): for m in re.finditer('\.+(?:\s+|$)|(\.*)[\!\?]+(\.+(?:\s+|$))*', text): curr, _next = m.start(), m.end() # if prev position of delimiter < current - between exists text # at least 1 symbol. if prev < curr: node = text[prev:curr].strip() if node != '': result.append(node) result.append(list( text[curr:_next].strip() )) prev = _next if len(text) > prev: result.append(text[prev:].strip()) return result
import base from blocks import Blocks import re class Sentences(base.Base): _type = 'sentences' child_class = Blocks @staticmethod def parse(text): _len = len(text) result = [] prev = 0 # we allow .09 as not end of sentences for m in re.finditer('[\!\?\.]+', text): curr, _next = m.start(), m.end() items = list( text[curr: _next].strip() ) if (_len > _next) and not (text[_next] == ' '): # delete ending '.' if they not before space or end of string while (len(items) > 0) and (items[-1] == '.'): items.pop() _next = _next - 1 if len(items) > 0: # if prev position of delimiter < current - between exists text # at least 1 symbol. if prev < curr: node = text[prev:curr].strip() if node != '': result.append(node) result.append( items ) prev = _next if _len > prev: result.append(text[prev:].strip()) return result
Optimize from 5-6s to 2.9-3.0
Optimize from 5-6s to 2.9-3.0
Python
mit
diNard/Saw
import base from blocks import Blocks import re class Sentences(base.Base): _type = 'sentences' child_class = Blocks @staticmethod def parse(text): - #re.split('\!|\?|\. | \.',text) + _len = len(text) result = [] prev = 0 # we allow .09 as not end of sentences - #for m in re.finditer('[\!\?]+|\.+(?:\s+|$|\?|\!)', text): + for m in re.finditer('[\!\?\.]+', text): - for m in re.finditer('\.+(?:\s+|$)|(\.*)[\!\?]+(\.+(?:\s+|$))*', text): curr, _next = m.start(), m.end() + items = list( text[curr: _next].strip() ) + + if (_len > _next) and not (text[_next] == ' '): + # delete ending '.' if they not before space or end of string + while (len(items) > 0) and (items[-1] == '.'): + items.pop() + _next = _next - 1 + + if len(items) > 0: - # if prev position of delimiter < current - between exists text + # if prev position of delimiter < current - between exists text - # at least 1 symbol. + # at least 1 symbol. - if prev < curr: + if prev < curr: - node = text[prev:curr].strip() + node = text[prev:curr].strip() - if node != '': + if node != '': - result.append(node) + result.append(node) - result.append(list( text[curr:_next].strip() )) + result.append( items ) - prev = _next + prev = _next - if len(text) > prev: + if _len > prev: result.append(text[prev:].strip()) return result
Optimize from 5-6s to 2.9-3.0
## Code Before: import base from blocks import Blocks import re class Sentences(base.Base): _type = 'sentences' child_class = Blocks @staticmethod def parse(text): #re.split('\!|\?|\. | \.',text) result = [] prev = 0 # we allow .09 as not end of sentences #for m in re.finditer('[\!\?]+|\.+(?:\s+|$|\?|\!)', text): for m in re.finditer('\.+(?:\s+|$)|(\.*)[\!\?]+(\.+(?:\s+|$))*', text): curr, _next = m.start(), m.end() # if prev position of delimiter < current - between exists text # at least 1 symbol. if prev < curr: node = text[prev:curr].strip() if node != '': result.append(node) result.append(list( text[curr:_next].strip() )) prev = _next if len(text) > prev: result.append(text[prev:].strip()) return result ## Instruction: Optimize from 5-6s to 2.9-3.0 ## Code After: import base from blocks import Blocks import re class Sentences(base.Base): _type = 'sentences' child_class = Blocks @staticmethod def parse(text): _len = len(text) result = [] prev = 0 # we allow .09 as not end of sentences for m in re.finditer('[\!\?\.]+', text): curr, _next = m.start(), m.end() items = list( text[curr: _next].strip() ) if (_len > _next) and not (text[_next] == ' '): # delete ending '.' if they not before space or end of string while (len(items) > 0) and (items[-1] == '.'): items.pop() _next = _next - 1 if len(items) > 0: # if prev position of delimiter < current - between exists text # at least 1 symbol. if prev < curr: node = text[prev:curr].strip() if node != '': result.append(node) result.append( items ) prev = _next if _len > prev: result.append(text[prev:].strip()) return result
0cab34e5f87b4484e0309aba8860d651afe06fb0
app/__init__.py
app/__init__.py
from flask import Flask, request, redirect from flask.ext.bootstrap import Bootstrap from config import configs from dmutils import apiclient, init_app, flask_featureflags from dmutils.content_loader import ContentLoader bootstrap = Bootstrap() data_api_client = apiclient.DataAPIClient() search_api_client = apiclient.SearchAPIClient() feature_flags = flask_featureflags.FeatureFlag() def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, data_api_client=data_api_client, feature_flags=feature_flags, search_api_client=search_api_client ) questions_builder = ContentLoader( "app/helpers/questions_manifest.yml", "app/content/g6/" ).get_builder() from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) main_blueprint.config = { 'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'], 'QUESTIONS_BUILDER': questions_builder } @application.before_request def remove_trailing_slash(): if request.path != '/' and request.path.endswith('/'): if request.query_string: return redirect( '{}?{}'.format( request.path[:-1], request.query_string.decode('utf-8') ), code=301 ) else: return redirect(request.path[:-1], code=301) return application
from flask import Flask, request, redirect from flask.ext.bootstrap import Bootstrap from config import configs from dmutils import apiclient, init_app, flask_featureflags from dmutils.content_loader import ContentLoader bootstrap = Bootstrap() data_api_client = apiclient.DataAPIClient() search_api_client = apiclient.SearchAPIClient() feature_flags = flask_featureflags.FeatureFlag() questions_loader = ContentLoader( "app/helpers/questions_manifest.yml", "app/content/g6/" ) def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, data_api_client=data_api_client, feature_flags=feature_flags, search_api_client=search_api_client ) from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) main_blueprint.config = { 'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'], } @application.before_request def remove_trailing_slash(): if request.path != '/' and request.path.endswith('/'): if request.query_string: return redirect( '{}?{}'.format( request.path[:-1], request.query_string.decode('utf-8') ), code=301 ) else: return redirect(request.path[:-1], code=301) return application
Move QUESTIONS_BUILDER from blueprint to a global variable
Move QUESTIONS_BUILDER from blueprint to a global variable
Python
mit
mtekel/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend
from flask import Flask, request, redirect from flask.ext.bootstrap import Bootstrap from config import configs from dmutils import apiclient, init_app, flask_featureflags from dmutils.content_loader import ContentLoader bootstrap = Bootstrap() data_api_client = apiclient.DataAPIClient() search_api_client = apiclient.SearchAPIClient() feature_flags = flask_featureflags.FeatureFlag() + + questions_loader = ContentLoader( + "app/helpers/questions_manifest.yml", + "app/content/g6/" + ) def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, data_api_client=data_api_client, feature_flags=feature_flags, search_api_client=search_api_client ) - questions_builder = ContentLoader( - "app/helpers/questions_manifest.yml", - "app/content/g6/" - ).get_builder() - from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) main_blueprint.config = { 'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'], - 'QUESTIONS_BUILDER': questions_builder } @application.before_request def remove_trailing_slash(): if request.path != '/' and request.path.endswith('/'): if request.query_string: return redirect( '{}?{}'.format( request.path[:-1], request.query_string.decode('utf-8') ), code=301 ) else: return redirect(request.path[:-1], code=301) return application
Move QUESTIONS_BUILDER from blueprint to a global variable
## Code Before: from flask import Flask, request, redirect from flask.ext.bootstrap import Bootstrap from config import configs from dmutils import apiclient, init_app, flask_featureflags from dmutils.content_loader import ContentLoader bootstrap = Bootstrap() data_api_client = apiclient.DataAPIClient() search_api_client = apiclient.SearchAPIClient() feature_flags = flask_featureflags.FeatureFlag() def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, data_api_client=data_api_client, feature_flags=feature_flags, search_api_client=search_api_client ) questions_builder = ContentLoader( "app/helpers/questions_manifest.yml", "app/content/g6/" ).get_builder() from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) main_blueprint.config = { 'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'], 'QUESTIONS_BUILDER': questions_builder } @application.before_request def remove_trailing_slash(): if request.path != '/' and request.path.endswith('/'): if request.query_string: return redirect( '{}?{}'.format( request.path[:-1], request.query_string.decode('utf-8') ), code=301 ) else: return redirect(request.path[:-1], code=301) return application ## Instruction: Move QUESTIONS_BUILDER from blueprint to a global variable ## Code After: from flask import Flask, request, redirect from flask.ext.bootstrap import Bootstrap from config import configs from dmutils import apiclient, init_app, flask_featureflags from dmutils.content_loader import ContentLoader bootstrap = Bootstrap() data_api_client = apiclient.DataAPIClient() search_api_client = apiclient.SearchAPIClient() feature_flags = flask_featureflags.FeatureFlag() questions_loader = ContentLoader( "app/helpers/questions_manifest.yml", "app/content/g6/" ) def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], bootstrap=bootstrap, data_api_client=data_api_client, feature_flags=feature_flags, search_api_client=search_api_client ) from .main import main as main_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) main_blueprint.config = { 'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA'], } @application.before_request def remove_trailing_slash(): if request.path != '/' and request.path.endswith('/'): if request.query_string: return redirect( '{}?{}'.format( request.path[:-1], request.query_string.decode('utf-8') ), code=301 ) else: return redirect(request.path[:-1], code=301) return application
e65ed7382c691d8ee19a22659ddb6deaa064e85b
kmip/__init__.py
kmip/__init__.py
import os import re # Dynamically set __version__ version_path = os.path.join(os.path.dirname( os.path.realpath(__file__)), 'version.py') with open(version_path, 'r') as version_file: mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE) __version__ = mo.group(1) __all__ = ['core', 'demos', 'services']
import os import re from kmip.core import enums # Dynamically set __version__ version_path = os.path.join(os.path.dirname( os.path.realpath(__file__)), 'version.py') with open(version_path, 'r') as version_file: mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE) __version__ = mo.group(1) __all__ = [ 'core', 'demos', 'enums', 'services' ]
Update the kmip package to allow importing enums globally
Update the kmip package to allow importing enums globally This change updates the root-level kmip package, allowing users to now import enums directly from the kmip package: from kmip import enums Enumerations are used throughout the codebase and user applications and this will simplify usage and help obfuscate internal package details that may change in the future.
Python
apache-2.0
OpenKMIP/PyKMIP,OpenKMIP/PyKMIP
import os import re + + from kmip.core import enums # Dynamically set __version__ version_path = os.path.join(os.path.dirname( os.path.realpath(__file__)), 'version.py') with open(version_path, 'r') as version_file: mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE) __version__ = mo.group(1) - __all__ = ['core', 'demos', 'services'] + __all__ = [ + 'core', + 'demos', + 'enums', + 'services' + ]
Update the kmip package to allow importing enums globally
## Code Before: import os import re # Dynamically set __version__ version_path = os.path.join(os.path.dirname( os.path.realpath(__file__)), 'version.py') with open(version_path, 'r') as version_file: mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE) __version__ = mo.group(1) __all__ = ['core', 'demos', 'services'] ## Instruction: Update the kmip package to allow importing enums globally ## Code After: import os import re from kmip.core import enums # Dynamically set __version__ version_path = os.path.join(os.path.dirname( os.path.realpath(__file__)), 'version.py') with open(version_path, 'r') as version_file: mo = re.search(r"^.*= '(\d\.\d\.\d)'$", version_file.read(), re.MULTILINE) __version__ = mo.group(1) __all__ = [ 'core', 'demos', 'enums', 'services' ]
3e0fbefa021c4c97024da30963845b201ff35089
dmaws/commands/paasmanifest.py
dmaws/commands/paasmanifest.py
import click import os from ..cli import cli_command from ..utils import load_file, template_string @cli_command('paas-manifest', max_apps=1) @click.option('--template', '-t', default='paas/manifest.j2', type=click.Path(exists=True), help="Manifest Jinja2 template file") @click.option('--out-file', '-o', help="Output file, if empty the template content is printed to the stdout") def paas_manifest(ctx, template, out_file): """Generate a PaaS manifest file from a Jinja2 template""" app = ctx.apps[0] if app not in ctx.variables: raise ValueError('Application configuration not found') templace_content = load_file(template) variables = { 'environment': ctx.environment, 'app': app.replace('_', '-') } variables.update(ctx.variables[app]) manifest_content = template_string(templace_content, variables) if out_file is not None: with open(out_file, 'w') as f: f.write(manifest_content) os.chmod(out_file, 0o600) else: print(manifest_content)
import click import os from ..cli import cli_command from ..utils import load_file, template_string, merge_dicts @cli_command('paas-manifest', max_apps=1) @click.option('--out-file', '-o', help="Output file, if empty the template content is printed to the stdout") def paas_manifest(ctx, out_file): """Generate a PaaS manifest file from a Jinja2 template""" app = ctx.apps[0] if app not in ctx.variables: raise ValueError('Application configuration not found') variables = { 'environment': ctx.environment, 'app': app.replace('_', '-') } template_content = load_file('paas/{}.j2'.format(variables['app'])) variables = merge_dicts(variables, ctx.variables) variables = merge_dicts(variables, ctx.variables[app]) manifest_content = template_string(template_content, variables, templates_path='paas/') if out_file is not None: with open(out_file, 'w') as f: f.write(manifest_content) os.chmod(out_file, 0o600) else: print(manifest_content)
Update paas-manifest command to load per-app manifests
Update paas-manifest command to load per-app manifests Removes template file option in favour of the app-specific manifests. Changes the way variables are set for the manifest template. Once the relevant variable files are loaded and merged the command will update the top-level namespace with the values from the application. This allows us to use the same base manifest template referencing generic top-level variables (eg `subdomain`, `instances`, `path`) that are overridden by application-specific values. Previously this was accomplished by using `stacks.yml` as the middle layer. The template variable change means that we can run into issues if we use clashing variable names accidentally, but at the same time it allows us to set common values for all applications. Eg: ``` instances: 3 api: instances: 5 ``` sets instance counts to 3 for all applications, but since the context will be updated with the `api` values the api manifest will only see `instances: 5` value.
Python
mit
alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws
import click import os from ..cli import cli_command - from ..utils import load_file, template_string + from ..utils import load_file, template_string, merge_dicts @cli_command('paas-manifest', max_apps=1) - @click.option('--template', '-t', default='paas/manifest.j2', - type=click.Path(exists=True), - help="Manifest Jinja2 template file") @click.option('--out-file', '-o', help="Output file, if empty the template content is printed to the stdout") - def paas_manifest(ctx, template, out_file): + def paas_manifest(ctx, out_file): """Generate a PaaS manifest file from a Jinja2 template""" app = ctx.apps[0] if app not in ctx.variables: raise ValueError('Application configuration not found') - templace_content = load_file(template) variables = { 'environment': ctx.environment, 'app': app.replace('_', '-') } - variables.update(ctx.variables[app]) + template_content = load_file('paas/{}.j2'.format(variables['app'])) + + variables = merge_dicts(variables, ctx.variables) + variables = merge_dicts(variables, ctx.variables[app]) + - manifest_content = template_string(templace_content, variables) + manifest_content = template_string(template_content, variables, templates_path='paas/') if out_file is not None: with open(out_file, 'w') as f: f.write(manifest_content) os.chmod(out_file, 0o600) else: print(manifest_content)
Update paas-manifest command to load per-app manifests
## Code Before: import click import os from ..cli import cli_command from ..utils import load_file, template_string @cli_command('paas-manifest', max_apps=1) @click.option('--template', '-t', default='paas/manifest.j2', type=click.Path(exists=True), help="Manifest Jinja2 template file") @click.option('--out-file', '-o', help="Output file, if empty the template content is printed to the stdout") def paas_manifest(ctx, template, out_file): """Generate a PaaS manifest file from a Jinja2 template""" app = ctx.apps[0] if app not in ctx.variables: raise ValueError('Application configuration not found') templace_content = load_file(template) variables = { 'environment': ctx.environment, 'app': app.replace('_', '-') } variables.update(ctx.variables[app]) manifest_content = template_string(templace_content, variables) if out_file is not None: with open(out_file, 'w') as f: f.write(manifest_content) os.chmod(out_file, 0o600) else: print(manifest_content) ## Instruction: Update paas-manifest command to load per-app manifests ## Code After: import click import os from ..cli import cli_command from ..utils import load_file, template_string, merge_dicts @cli_command('paas-manifest', max_apps=1) @click.option('--out-file', '-o', help="Output file, if empty the template content is printed to the stdout") def paas_manifest(ctx, out_file): """Generate a PaaS manifest file from a Jinja2 template""" app = ctx.apps[0] if app not in ctx.variables: raise ValueError('Application configuration not found') variables = { 'environment': ctx.environment, 'app': app.replace('_', '-') } template_content = load_file('paas/{}.j2'.format(variables['app'])) variables = merge_dicts(variables, ctx.variables) variables = merge_dicts(variables, ctx.variables[app]) manifest_content = template_string(template_content, variables, templates_path='paas/') if out_file is not None: with open(out_file, 'w') as f: f.write(manifest_content) os.chmod(out_file, 0o600) else: print(manifest_content)
89a7a834638a1384bd9f1a560902b4d3aab29423
smoked/loader.py
smoked/loader.py
from __future__ import unicode_literals from importlib import import_module from django.conf import settings from django.core.exceptions import ImproperlyConfigured def load_test_module(): """ Import test module and trigger registration of tests. Test module is defined in `SMOKE_TESTS` setting. """ test_module = getattr(settings, 'SMOKE_TESTS') if not test_module: raise ImproperlyConfigured('Missing SMOKE_TESTS in settings.') try: import_module(test_module) except ImportError as e: msg = "Can't import '{0}' module. Exception: {1}" raise ImproperlyConfigured(msg.format(test_module, e))
from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def load_test_module(): """ Import test module and trigger registration of tests. Test module is defined in `SMOKE_TESTS` setting. """ test_module = getattr(settings, 'SMOKE_TESTS') if not test_module: raise ImproperlyConfigured('Missing SMOKE_TESTS in settings.') try: import_module(test_module) except ImportError as e: msg = "Can't import '{0}' module. Exception: {1}" raise ImproperlyConfigured(msg.format(test_module, e))
Fix import of import_module for Py2.6
Fix import of import_module for Py2.6
Python
mit
djentlemen/django-smoked
from __future__ import unicode_literals - from importlib import import_module from django.conf import settings from django.core.exceptions import ImproperlyConfigured + from django.utils.importlib import import_module def load_test_module(): """ Import test module and trigger registration of tests. Test module is defined in `SMOKE_TESTS` setting. """ test_module = getattr(settings, 'SMOKE_TESTS') if not test_module: raise ImproperlyConfigured('Missing SMOKE_TESTS in settings.') try: import_module(test_module) except ImportError as e: msg = "Can't import '{0}' module. Exception: {1}" raise ImproperlyConfigured(msg.format(test_module, e))
Fix import of import_module for Py2.6
## Code Before: from __future__ import unicode_literals from importlib import import_module from django.conf import settings from django.core.exceptions import ImproperlyConfigured def load_test_module(): """ Import test module and trigger registration of tests. Test module is defined in `SMOKE_TESTS` setting. """ test_module = getattr(settings, 'SMOKE_TESTS') if not test_module: raise ImproperlyConfigured('Missing SMOKE_TESTS in settings.') try: import_module(test_module) except ImportError as e: msg = "Can't import '{0}' module. Exception: {1}" raise ImproperlyConfigured(msg.format(test_module, e)) ## Instruction: Fix import of import_module for Py2.6 ## Code After: from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def load_test_module(): """ Import test module and trigger registration of tests. Test module is defined in `SMOKE_TESTS` setting. """ test_module = getattr(settings, 'SMOKE_TESTS') if not test_module: raise ImproperlyConfigured('Missing SMOKE_TESTS in settings.') try: import_module(test_module) except ImportError as e: msg = "Can't import '{0}' module. Exception: {1}" raise ImproperlyConfigured(msg.format(test_module, e))
d2339fa094062c0672aef0ce938572aa3f5aead3
nintendo/sead/random.py
nintendo/sead/random.py
class Random: def __init__(self, seed): multiplier = 0x6C078965 temp = seed self.state = [] for i in range(1, 5): temp ^= temp >> 30 temp = (temp * multiplier + i) & 0xFFFFFFFF self.state.append(temp) def u32(self): temp = self.state[0] temp = (temp ^ (temp << 11)) & 0xFFFFFFFF temp ^= temp >> 8 temp ^= self.state[3] temp ^= self.state[3] >> 19 self.state[0] = self.state[1] self.state[1] = self.state[2] self.state[2] = self.state[3] self.state[3] = temp return temp def uint(self, max): return (self.u32() * max) >> 32
class Random: def __init__(self, *param): if len(param) == 1: self.set_seed(param[0]) elif len(param) == 4: self.set_state(*param) else: raise TypeError("Random.__init__ takes either 1 or 4 arguments") def set_seed(self, seed): multiplier = 0x6C078965 temp = seed self.state = [] for i in range(1, 5): temp ^= temp >> 30 temp = (temp * multiplier + i) & 0xFFFFFFFF self.state.append(temp) def set_state(self, s0, s1, s2, s3): self.state = [s0, s1, s2, s3] def u32(self): temp = self.state[0] temp = (temp ^ (temp << 11)) & 0xFFFFFFFF temp ^= temp >> 8 temp ^= self.state[3] temp ^= self.state[3] >> 19 self.state[0] = self.state[1] self.state[1] = self.state[2] self.state[2] = self.state[3] self.state[3] = temp return temp def uint(self, max): return (self.u32() * max) >> 32
Allow sead.Random to be constructed by internal state
Allow sead.Random to be constructed by internal state
Python
mit
Kinnay/NintendoClients
class Random: - def __init__(self, seed): + def __init__(self, *param): + if len(param) == 1: self.set_seed(param[0]) + elif len(param) == 4: self.set_state(*param) + else: + raise TypeError("Random.__init__ takes either 1 or 4 arguments") + + def set_seed(self, seed): multiplier = 0x6C078965 temp = seed self.state = [] for i in range(1, 5): temp ^= temp >> 30 temp = (temp * multiplier + i) & 0xFFFFFFFF self.state.append(temp) + + def set_state(self, s0, s1, s2, s3): + self.state = [s0, s1, s2, s3] def u32(self): temp = self.state[0] temp = (temp ^ (temp << 11)) & 0xFFFFFFFF temp ^= temp >> 8 temp ^= self.state[3] temp ^= self.state[3] >> 19 self.state[0] = self.state[1] self.state[1] = self.state[2] self.state[2] = self.state[3] self.state[3] = temp return temp def uint(self, max): return (self.u32() * max) >> 32
Allow sead.Random to be constructed by internal state
## Code Before: class Random: def __init__(self, seed): multiplier = 0x6C078965 temp = seed self.state = [] for i in range(1, 5): temp ^= temp >> 30 temp = (temp * multiplier + i) & 0xFFFFFFFF self.state.append(temp) def u32(self): temp = self.state[0] temp = (temp ^ (temp << 11)) & 0xFFFFFFFF temp ^= temp >> 8 temp ^= self.state[3] temp ^= self.state[3] >> 19 self.state[0] = self.state[1] self.state[1] = self.state[2] self.state[2] = self.state[3] self.state[3] = temp return temp def uint(self, max): return (self.u32() * max) >> 32 ## Instruction: Allow sead.Random to be constructed by internal state ## Code After: class Random: def __init__(self, *param): if len(param) == 1: self.set_seed(param[0]) elif len(param) == 4: self.set_state(*param) else: raise TypeError("Random.__init__ takes either 1 or 4 arguments") def set_seed(self, seed): multiplier = 0x6C078965 temp = seed self.state = [] for i in range(1, 5): temp ^= temp >> 30 temp = (temp * multiplier + i) & 0xFFFFFFFF self.state.append(temp) def set_state(self, s0, s1, s2, s3): self.state = [s0, s1, s2, s3] def u32(self): temp = self.state[0] temp = (temp ^ (temp << 11)) & 0xFFFFFFFF temp ^= temp >> 8 temp ^= self.state[3] temp ^= self.state[3] >> 19 self.state[0] = self.state[1] self.state[1] = self.state[2] self.state[2] = self.state[3] self.state[3] = temp return temp def uint(self, max): return (self.u32() * max) >> 32
3e913e4267fd7750516edcbed1aa687e0cbd17fe
edx_repo_tools/oep2/__init__.py
edx_repo_tools/oep2/__init__.py
import click from . import explode_repos_yaml from .report import cli def _cli(): cli(auto_envvar_prefix="OEP2") @click.group() def cli(): """ Tools for implementing and enforcing OEP-2. """ pass cli.add_command(explode_repos_yaml.explode) cli.add_command(explode_repos_yaml.implode) cli.add_command(cli.cli, 'report')
import click from . import explode_repos_yaml from .report.cli import cli as report_cli def _cli(): cli(auto_envvar_prefix="OEP2") @click.group() def cli(): """ Tools for implementing and enforcing OEP-2. """ pass cli.add_command(explode_repos_yaml.explode) cli.add_command(explode_repos_yaml.implode) cli.add_command(report_cli, 'report')
Make oep-2 checker run again
Make oep-2 checker run again
Python
apache-2.0
edx/repo-tools,edx/repo-tools
import click from . import explode_repos_yaml - from .report import cli + from .report.cli import cli as report_cli def _cli(): cli(auto_envvar_prefix="OEP2") @click.group() def cli(): """ Tools for implementing and enforcing OEP-2. """ pass cli.add_command(explode_repos_yaml.explode) cli.add_command(explode_repos_yaml.implode) - cli.add_command(cli.cli, 'report') + cli.add_command(report_cli, 'report')
Make oep-2 checker run again
## Code Before: import click from . import explode_repos_yaml from .report import cli def _cli(): cli(auto_envvar_prefix="OEP2") @click.group() def cli(): """ Tools for implementing and enforcing OEP-2. """ pass cli.add_command(explode_repos_yaml.explode) cli.add_command(explode_repos_yaml.implode) cli.add_command(cli.cli, 'report') ## Instruction: Make oep-2 checker run again ## Code After: import click from . import explode_repos_yaml from .report.cli import cli as report_cli def _cli(): cli(auto_envvar_prefix="OEP2") @click.group() def cli(): """ Tools for implementing and enforcing OEP-2. """ pass cli.add_command(explode_repos_yaml.explode) cli.add_command(explode_repos_yaml.implode) cli.add_command(report_cli, 'report')
d85947ee083b0a5d7156b4e49fd5677ebeea33c7
brew/monitor.py
brew/monitor.py
import time import threading from . import app, mongo, controller from bson.objectid import ObjectId class Monitor(object): def __init__(self, timeout=10): self.thread = None self.exit_event = None self.timeout = timeout def temperature(self, brew_id): if self.thread: raise RuntimeError("Brew still ongoing") def run_in_background(): while True: if self.exit_event.wait(self.timeout): break with app.app_context(): temperature = controller.get_temperature() now = time.time() query = {'_id': ObjectId(brew_id)} op = {'$push': {'temperatures': (now, temperature)}} mongo.db.brews.update(query, op) self.exit_event = threading.Event() self.thread = threading.Thread(target=run_in_background) self.thread.start() def stop(self): self.exit_event.set() self.thread.join()
import time import threading from . import app, mongo, controller from bson.objectid import ObjectId class Monitor(object): def __init__(self, timeout=10): self.thread = None self.exit_event = None self.timeout = timeout def temperature(self, brew_id): if self.thread: raise RuntimeError("Brew still ongoing") def run_in_background(): while True: if self.exit_event.wait(self.timeout): break with app.app_context(): temperature = controller.get_temperature() now = time.time() query = {'_id': ObjectId(brew_id)} op = {'$push': {'temperatures': (now, temperature)}} mongo.db.brews.update(query, op) self.exit_event = threading.Event() self.thread = threading.Thread(target=run_in_background) self.thread.start() def stop(self): self.exit_event.set() self.thread.join() self.thread = None
Fix problem after stopping process
Fix problem after stopping process
Python
mit
brewpeople/brewmeister,brewpeople/brewmeister,brewpeople/brewmeister
import time import threading from . import app, mongo, controller from bson.objectid import ObjectId class Monitor(object): def __init__(self, timeout=10): self.thread = None self.exit_event = None self.timeout = timeout def temperature(self, brew_id): if self.thread: raise RuntimeError("Brew still ongoing") def run_in_background(): while True: if self.exit_event.wait(self.timeout): break with app.app_context(): temperature = controller.get_temperature() now = time.time() query = {'_id': ObjectId(brew_id)} op = {'$push': {'temperatures': (now, temperature)}} mongo.db.brews.update(query, op) self.exit_event = threading.Event() self.thread = threading.Thread(target=run_in_background) self.thread.start() def stop(self): self.exit_event.set() self.thread.join() + self.thread = None
Fix problem after stopping process
## Code Before: import time import threading from . import app, mongo, controller from bson.objectid import ObjectId class Monitor(object): def __init__(self, timeout=10): self.thread = None self.exit_event = None self.timeout = timeout def temperature(self, brew_id): if self.thread: raise RuntimeError("Brew still ongoing") def run_in_background(): while True: if self.exit_event.wait(self.timeout): break with app.app_context(): temperature = controller.get_temperature() now = time.time() query = {'_id': ObjectId(brew_id)} op = {'$push': {'temperatures': (now, temperature)}} mongo.db.brews.update(query, op) self.exit_event = threading.Event() self.thread = threading.Thread(target=run_in_background) self.thread.start() def stop(self): self.exit_event.set() self.thread.join() ## Instruction: Fix problem after stopping process ## Code After: import time import threading from . import app, mongo, controller from bson.objectid import ObjectId class Monitor(object): def __init__(self, timeout=10): self.thread = None self.exit_event = None self.timeout = timeout def temperature(self, brew_id): if self.thread: raise RuntimeError("Brew still ongoing") def run_in_background(): while True: if self.exit_event.wait(self.timeout): break with app.app_context(): temperature = controller.get_temperature() now = time.time() query = {'_id': ObjectId(brew_id)} op = {'$push': {'temperatures': (now, temperature)}} mongo.db.brews.update(query, op) self.exit_event = threading.Event() self.thread = threading.Thread(target=run_in_background) self.thread.start() def stop(self): self.exit_event.set() self.thread.join() self.thread = None
ccafafbd51422979ed93ed197135bf03b7d0be81
opps/images/__init__.py
opps/images/__init__.py
from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Image') settings.INSTALLED_APPS += ('thumbor',)
from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Image')
Remove thumbor use on init image, thumbor not django application
Remove thumbor use on init image, thumbor not django application
Python
mit
YACOWS/opps,opps/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,opps/opps,opps/opps,YACOWS/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,williamroot/opps,williamroot/opps,jeanmask/opps,opps/opps
from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Image') - settings.INSTALLED_APPS += ('thumbor',)
Remove thumbor use on init image, thumbor not django application
## Code Before: from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Image') settings.INSTALLED_APPS += ('thumbor',) ## Instruction: Remove thumbor use on init image, thumbor not django application ## Code After: from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Image')
46de02b77c25c633b254dc81ed35da2443b287a9
lighty/wsgi/__init__.py
lighty/wsgi/__init__.py
import functools from .handler import handler from .urls import load_urls, resolve def WSGIApplication(app_settings): '''Create main application handler ''' class Application(object): settings = app_settings urls = load_urls(settings.urls) resolve_url = functools.partial(resolve, urls) return functools.partial(handler, Application, Application.resolve_url)
import functools import os from ..templates.loaders import FSLoader from .handler import handler from .urls import load_urls, resolve class BaseApplication(object): '''Base application class contains obly settings, urls and resolve_url method ''' def __init__(self, settings): self.settings = settings self.urls = load_urls(settings.urls) self.resolve_url = functools.partial(resolve, self.urls) class ComplexApplication(BaseApplication): '''Application loads also templates and database connection ''' def __init__(self, settings): super(ComplexApplication, self).__init__(settings) self.apps = settings.section('APPS') template_dirs = [] for app in self.apps: module = __import__(app, globals(), locals(), app.split('.')[-1]) template_dir = os.path.join(module.__path__[0], 'templates') if os.path.exists(template_dir): template_dirs.append(template_dir) try: template_dirs += settings.section('TEMPLATE_DIRS') except: pass self.template_loader = FSLoader(template_dirs) self.get_template = self.template_loader.get_template def WSGIApplication(app_settings): '''Create main application handler ''' application = ComplexApplication(app_settings) return functools.partial(handler, application, application.resolve_url)
Add ComplexApplication class for WSGI apps that uses not only urls resolving.
Add ComplexApplication class for WSGI apps that uses not only urls resolving.
Python
bsd-3-clause
GrAndSE/lighty
import functools + import os + + from ..templates.loaders import FSLoader from .handler import handler from .urls import load_urls, resolve + class BaseApplication(object): + '''Base application class contains obly settings, urls and resolve_url + method + ''' + + def __init__(self, settings): + self.settings = settings + self.urls = load_urls(settings.urls) + self.resolve_url = functools.partial(resolve, self.urls) + + + class ComplexApplication(BaseApplication): + '''Application loads also templates and database connection + ''' + + def __init__(self, settings): + super(ComplexApplication, self).__init__(settings) + self.apps = settings.section('APPS') + template_dirs = [] + for app in self.apps: + module = __import__(app, globals(), locals(), app.split('.')[-1]) + template_dir = os.path.join(module.__path__[0], 'templates') + if os.path.exists(template_dir): + template_dirs.append(template_dir) + try: + template_dirs += settings.section('TEMPLATE_DIRS') + except: + pass + self.template_loader = FSLoader(template_dirs) + self.get_template = self.template_loader.get_template + + def WSGIApplication(app_settings): '''Create main application handler ''' + application = ComplexApplication(app_settings) + return functools.partial(handler, application, application.resolve_url) - class Application(object): - settings = app_settings - urls = load_urls(settings.urls) - resolve_url = functools.partial(resolve, urls) - - return functools.partial(handler, Application, Application.resolve_url) -
Add ComplexApplication class for WSGI apps that uses not only urls resolving.
## Code Before: import functools from .handler import handler from .urls import load_urls, resolve def WSGIApplication(app_settings): '''Create main application handler ''' class Application(object): settings = app_settings urls = load_urls(settings.urls) resolve_url = functools.partial(resolve, urls) return functools.partial(handler, Application, Application.resolve_url) ## Instruction: Add ComplexApplication class for WSGI apps that uses not only urls resolving. ## Code After: import functools import os from ..templates.loaders import FSLoader from .handler import handler from .urls import load_urls, resolve class BaseApplication(object): '''Base application class contains obly settings, urls and resolve_url method ''' def __init__(self, settings): self.settings = settings self.urls = load_urls(settings.urls) self.resolve_url = functools.partial(resolve, self.urls) class ComplexApplication(BaseApplication): '''Application loads also templates and database connection ''' def __init__(self, settings): super(ComplexApplication, self).__init__(settings) self.apps = settings.section('APPS') template_dirs = [] for app in self.apps: module = __import__(app, globals(), locals(), app.split('.')[-1]) template_dir = os.path.join(module.__path__[0], 'templates') if os.path.exists(template_dir): template_dirs.append(template_dir) try: template_dirs += settings.section('TEMPLATE_DIRS') except: pass self.template_loader = FSLoader(template_dirs) self.get_template = self.template_loader.get_template def WSGIApplication(app_settings): '''Create main application handler ''' application = ComplexApplication(app_settings) return functools.partial(handler, application, application.resolve_url)
a1b4526f48fbd9e7f48c8bb6bc1a4763cc710448
fabric_bolt/web_hooks/tables.py
fabric_bolt/web_hooks/tables.py
import django_tables2 as tables from fabric_bolt.core.mixins.tables import ActionsColumn, PaginateTable from fabric_bolt.web_hooks import models class HookTable(PaginateTable): """Table used to show the configurations Also provides actions to edit and delete""" actions = ActionsColumn([ {'title': '<i class="glyphicon glyphicon-pencil"></i>', 'url': 'hooks_hook_update', 'args': [tables.A('pk')], 'attrs':{'data-toggle': 'tooltip', 'title': 'Edit Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}}, {'title': '<i class="glyphicon glyphicon-trash"></i>', 'url': 'hooks_hook_delete', 'args': [tables.A('pk')], 'attrs':{'data-toggle': 'tooltip', 'title': 'Delete Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}}, ], delimiter='&#160;&#160;&#160;') class Meta: model = models.Hook attrs = {"class": "table table-striped"} sequence = fields = ( 'url', )
import django_tables2 as tables from fabric_bolt.core.mixins.tables import ActionsColumn, PaginateTable from fabric_bolt.web_hooks import models class HookTable(PaginateTable): """Table used to show the configurations Also provides actions to edit and delete""" actions = ActionsColumn([ {'title': '<i class="glyphicon glyphicon-pencil"></i>', 'url': 'hooks_hook_update', 'args': [tables.A('pk')], 'attrs':{'data-toggle': 'tooltip', 'title': 'Edit Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}}, {'title': '<i class="glyphicon glyphicon-trash"></i>', 'url': 'hooks_hook_delete', 'args': [tables.A('pk')], 'attrs':{'data-toggle': 'tooltip', 'title': 'Delete Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}}, ], delimiter='&#160;&#160;&#160;') class Meta: model = models.Hook attrs = {"class": "table table-striped"} sequence = fields = ( 'project', 'url', )
Add project to hook table so it's a little more clear what it's a global one.
Add project to hook table so it's a little more clear what it's a global one.
Python
mit
worthwhile/fabric-bolt,jproffitt/fabric-bolt,gvangool/fabric-bolt,qdqmedia/fabric-bolt,damoguyan8844/fabric-bolt,qdqmedia/fabric-bolt,npardington/fabric-bolt,fabric-bolt/fabric-bolt,maximon93/fabric-bolt,leominov/fabric-bolt,lethe3000/fabric-bolt,worthwhile/fabric-bolt,maximon93/fabric-bolt,damoguyan8844/fabric-bolt,lethe3000/fabric-bolt,maximon93/fabric-bolt,jproffitt/fabric-bolt,damoguyan8844/fabric-bolt,brajput24/fabric-bolt,gvangool/fabric-bolt,worthwhile/fabric-bolt,paperreduction/fabric-bolt,leominov/fabric-bolt,paperreduction/fabric-bolt,brajput24/fabric-bolt,leominov/fabric-bolt,fabric-bolt/fabric-bolt,npardington/fabric-bolt,lethe3000/fabric-bolt,gvangool/fabric-bolt,npardington/fabric-bolt,jproffitt/fabric-bolt,brajput24/fabric-bolt,fabric-bolt/fabric-bolt,qdqmedia/fabric-bolt,paperreduction/fabric-bolt
import django_tables2 as tables from fabric_bolt.core.mixins.tables import ActionsColumn, PaginateTable from fabric_bolt.web_hooks import models class HookTable(PaginateTable): """Table used to show the configurations Also provides actions to edit and delete""" actions = ActionsColumn([ {'title': '<i class="glyphicon glyphicon-pencil"></i>', 'url': 'hooks_hook_update', 'args': [tables.A('pk')], 'attrs':{'data-toggle': 'tooltip', 'title': 'Edit Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}}, {'title': '<i class="glyphicon glyphicon-trash"></i>', 'url': 'hooks_hook_delete', 'args': [tables.A('pk')], 'attrs':{'data-toggle': 'tooltip', 'title': 'Delete Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}}, ], delimiter='&#160;&#160;&#160;') class Meta: model = models.Hook attrs = {"class": "table table-striped"} sequence = fields = ( + 'project', 'url', )
Add project to hook table so it's a little more clear what it's a global one.
## Code Before: import django_tables2 as tables from fabric_bolt.core.mixins.tables import ActionsColumn, PaginateTable from fabric_bolt.web_hooks import models class HookTable(PaginateTable): """Table used to show the configurations Also provides actions to edit and delete""" actions = ActionsColumn([ {'title': '<i class="glyphicon glyphicon-pencil"></i>', 'url': 'hooks_hook_update', 'args': [tables.A('pk')], 'attrs':{'data-toggle': 'tooltip', 'title': 'Edit Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}}, {'title': '<i class="glyphicon glyphicon-trash"></i>', 'url': 'hooks_hook_delete', 'args': [tables.A('pk')], 'attrs':{'data-toggle': 'tooltip', 'title': 'Delete Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}}, ], delimiter='&#160;&#160;&#160;') class Meta: model = models.Hook attrs = {"class": "table table-striped"} sequence = fields = ( 'url', ) ## Instruction: Add project to hook table so it's a little more clear what it's a global one. ## Code After: import django_tables2 as tables from fabric_bolt.core.mixins.tables import ActionsColumn, PaginateTable from fabric_bolt.web_hooks import models class HookTable(PaginateTable): """Table used to show the configurations Also provides actions to edit and delete""" actions = ActionsColumn([ {'title': '<i class="glyphicon glyphicon-pencil"></i>', 'url': 'hooks_hook_update', 'args': [tables.A('pk')], 'attrs':{'data-toggle': 'tooltip', 'title': 'Edit Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}}, {'title': '<i class="glyphicon glyphicon-trash"></i>', 'url': 'hooks_hook_delete', 'args': [tables.A('pk')], 'attrs':{'data-toggle': 'tooltip', 'title': 'Delete Hook', 'data-delay': '{ "show": 300, "hide": 0 }'}}, ], delimiter='&#160;&#160;&#160;') class Meta: model = models.Hook attrs = {"class": "table table-striped"} sequence = fields = ( 'project', 'url', )
377fa94c2963a9c2522164ff374431dbe836217e
indra/sources/rlimsp/api.py
indra/sources/rlimsp/api.py
__all__ = ['process_pmc'] import logging import requests from .processor import RlimspProcessor logger = logging.getLogger(__name__) RLIMSP_URL = 'https://research.bioinformatics.udel.edu/itextmine/api/data/rlims/pmc' class RLIMSP_Error(Exception): pass def process_pmc(pmcid, with_grounding=True): """Get an output from RLIMS-p for the given pmic id. Parameters ---------- pmcid : str A PMCID, with the prefix PMC, of the paper to be "read". with_grounding : bool The RLIMS-P web service provides two endpoints, one pre-grounded, the other not so much. The grounded endpoint returns far less content, and may perform some grounding that can be handled by the grounding mapper. """ if with_grounding: resp = requests.get(RLIMSP_URL + '.normed/pmcid/%s' % pmcid) else: resp = requests.get(RLIMSP_URL + '/pmcid/%s' % pmcid) if resp.status_code != 200: raise RLIMSP_Error("Bad status code: %d - %s" % (resp.status_code, resp.reason)) rp = RlimspProcessor(resp.json()) return rp
__all__ = ['process_from_webservice'] import logging import requests from .processor import RlimspProcessor logger = logging.getLogger(__name__) RLIMSP_URL = 'https://research.bioinformatics.udel.edu/itextmine/api/data/rlims/' class RLIMSP_Error(Exception): pass def process_from_webservice(id_val, id_type='pmcid', source='pmc', with_grounding=True): """Get an output from RLIMS-p for the given pmic id. Parameters ---------- id_val : str A PMCID, with the prefix PMC, or pmid, with no prefix, of the paper to be "read". id_type : str Either 'pmid' or 'pmcid'. The default is 'pmcid'. source : str Either 'pmc' or 'medline', whether you want pmc fulltext or medline abstracts. with_grounding : bool The RLIMS-P web service provides two endpoints, one pre-grounded, the other not so much. The grounded endpoint returns far less content, and may perform some grounding that can be handled by the grounding mapper. """ if with_grounding: fmt = '%s.normed/%s/%s' else: fmt = '%s/%s/%s' resp = requests.get(RLIMSP_URL + fmt % (source, id_type, id_val)) if resp.status_code != 200: raise RLIMSP_Error("Bad status code: %d - %s" % (resp.status_code, resp.reason)) rp = RlimspProcessor(resp.json()) return rp
Add capability to read pmids and get medline.
Add capability to read pmids and get medline.
Python
bsd-2-clause
sorgerlab/belpy,bgyori/indra,johnbachman/belpy,johnbachman/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,sorgerlab/belpy,pvtodorov/indra,pvtodorov/indra,pvtodorov/indra,johnbachman/indra,johnbachman/belpy,sorgerlab/indra,sorgerlab/indra,sorgerlab/indra,bgyori/indra,bgyori/indra,johnbachman/indra
- __all__ = ['process_pmc'] + __all__ = ['process_from_webservice'] import logging import requests from .processor import RlimspProcessor logger = logging.getLogger(__name__) - RLIMSP_URL = 'https://research.bioinformatics.udel.edu/itextmine/api/data/rlims/pmc' + RLIMSP_URL = 'https://research.bioinformatics.udel.edu/itextmine/api/data/rlims/' class RLIMSP_Error(Exception): pass - def process_pmc(pmcid, with_grounding=True): + def process_from_webservice(id_val, id_type='pmcid', source='pmc', + with_grounding=True): """Get an output from RLIMS-p for the given pmic id. Parameters ---------- - pmcid : str + id_val : str - A PMCID, with the prefix PMC, of the paper to be "read". + A PMCID, with the prefix PMC, or pmid, with no prefix, of the paper to + be "read". + id_type : str + Either 'pmid' or 'pmcid'. The default is 'pmcid'. + source : str + Either 'pmc' or 'medline', whether you want pmc fulltext or medline + abstracts. with_grounding : bool The RLIMS-P web service provides two endpoints, one pre-grounded, the other not so much. The grounded endpoint returns far less content, and may perform some grounding that can be handled by the grounding mapper. """ if with_grounding: - resp = requests.get(RLIMSP_URL + '.normed/pmcid/%s' % pmcid) + fmt = '%s.normed/%s/%s' else: - resp = requests.get(RLIMSP_URL + '/pmcid/%s' % pmcid) + fmt = '%s/%s/%s' + + resp = requests.get(RLIMSP_URL + fmt % (source, id_type, id_val)) if resp.status_code != 200: raise RLIMSP_Error("Bad status code: %d - %s" % (resp.status_code, resp.reason)) rp = RlimspProcessor(resp.json()) return rp
Add capability to read pmids and get medline.
## Code Before: __all__ = ['process_pmc'] import logging import requests from .processor import RlimspProcessor logger = logging.getLogger(__name__) RLIMSP_URL = 'https://research.bioinformatics.udel.edu/itextmine/api/data/rlims/pmc' class RLIMSP_Error(Exception): pass def process_pmc(pmcid, with_grounding=True): """Get an output from RLIMS-p for the given pmic id. Parameters ---------- pmcid : str A PMCID, with the prefix PMC, of the paper to be "read". with_grounding : bool The RLIMS-P web service provides two endpoints, one pre-grounded, the other not so much. The grounded endpoint returns far less content, and may perform some grounding that can be handled by the grounding mapper. """ if with_grounding: resp = requests.get(RLIMSP_URL + '.normed/pmcid/%s' % pmcid) else: resp = requests.get(RLIMSP_URL + '/pmcid/%s' % pmcid) if resp.status_code != 200: raise RLIMSP_Error("Bad status code: %d - %s" % (resp.status_code, resp.reason)) rp = RlimspProcessor(resp.json()) return rp ## Instruction: Add capability to read pmids and get medline. ## Code After: __all__ = ['process_from_webservice'] import logging import requests from .processor import RlimspProcessor logger = logging.getLogger(__name__) RLIMSP_URL = 'https://research.bioinformatics.udel.edu/itextmine/api/data/rlims/' class RLIMSP_Error(Exception): pass def process_from_webservice(id_val, id_type='pmcid', source='pmc', with_grounding=True): """Get an output from RLIMS-p for the given pmic id. Parameters ---------- id_val : str A PMCID, with the prefix PMC, or pmid, with no prefix, of the paper to be "read". id_type : str Either 'pmid' or 'pmcid'. The default is 'pmcid'. source : str Either 'pmc' or 'medline', whether you want pmc fulltext or medline abstracts. with_grounding : bool The RLIMS-P web service provides two endpoints, one pre-grounded, the other not so much. The grounded endpoint returns far less content, and may perform some grounding that can be handled by the grounding mapper. """ if with_grounding: fmt = '%s.normed/%s/%s' else: fmt = '%s/%s/%s' resp = requests.get(RLIMSP_URL + fmt % (source, id_type, id_val)) if resp.status_code != 200: raise RLIMSP_Error("Bad status code: %d - %s" % (resp.status_code, resp.reason)) rp = RlimspProcessor(resp.json()) return rp
c17aed93f3dd5a1a46dfb871268ebda4e56b1bee
lib/excel.py
lib/excel.py
class Excel: @staticmethod def empty_cell(cell): """Tests whether an excel cell is empty or contains only whitespace""" if cell.ctype == 0: return True if str(cell.value).strip() == "": return True return False @staticmethod def cell_value(cell): """Returns the string value of an excel spreadsheet cell""" return str(cell.value).strip()
class Excel: @staticmethod def empty_cell(cell): """Tests whether an excel cell is empty or contains only whitespace""" if cell.ctype == 0: return True if str(cell.value).strip() == "": return True return False @staticmethod def cell_value(cell): """Returns the string value of an excel spreadsheet cell""" if (cell.value).__class__.__name__ == 'unicode': return (cell.value).encode('utf-8').strip() return str(cell.value).strip()
Handle special characters in xls cell values
Handle special characters in xls cell values
Python
mit
davharris/retriever,goelakash/retriever,embaldridge/retriever,henrykironde/deletedret,davharris/retriever,goelakash/retriever,embaldridge/retriever,davharris/retriever,henrykironde/deletedret,embaldridge/retriever
class Excel: @staticmethod def empty_cell(cell): """Tests whether an excel cell is empty or contains only whitespace""" if cell.ctype == 0: return True if str(cell.value).strip() == "": return True return False @staticmethod def cell_value(cell): """Returns the string value of an excel spreadsheet cell""" + if (cell.value).__class__.__name__ == 'unicode': + return (cell.value).encode('utf-8').strip() return str(cell.value).strip()
Handle special characters in xls cell values
## Code Before: class Excel: @staticmethod def empty_cell(cell): """Tests whether an excel cell is empty or contains only whitespace""" if cell.ctype == 0: return True if str(cell.value).strip() == "": return True return False @staticmethod def cell_value(cell): """Returns the string value of an excel spreadsheet cell""" return str(cell.value).strip() ## Instruction: Handle special characters in xls cell values ## Code After: class Excel: @staticmethod def empty_cell(cell): """Tests whether an excel cell is empty or contains only whitespace""" if cell.ctype == 0: return True if str(cell.value).strip() == "": return True return False @staticmethod def cell_value(cell): """Returns the string value of an excel spreadsheet cell""" if (cell.value).__class__.__name__ == 'unicode': return (cell.value).encode('utf-8').strip() return str(cell.value).strip()
b874a5d3f54ef7ba71af18474a96e835d97bb846
chat/views.py
chat/views.py
from datetime import datetime, timedelta import jwt import os from django.shortcuts import render from django.conf import settings from django.views.generic.base import TemplateView key = os.path.join( os.path.dirname(__file__), 'ecc', 'key.pem', ) with open(key, 'r') as fh: ecc_private = fh.read() # Create your views here. class NabuView(TemplateView): template_name = 'chat/nabu.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = { 'sub': 'Kromey', 'iss': self.request.headers['Host'], 'aud': self.request.headers['Host'], 'exp': datetime.utcnow() + timedelta(seconds=30), } token = jwt.encode(data, ecc_private, algorithm='ES256') context['token'] = token.decode('utf-8') return context
from datetime import datetime, timedelta import jwt import os from django.shortcuts import render from django.conf import settings from django.views.generic.base import TemplateView key = os.path.join( os.path.dirname(__file__), 'ecc', 'key.pem', ) with open(key, 'r') as fh: ecc_private = fh.read() # Create your views here. class NabuView(TemplateView): template_name = 'chat/nabu.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = { 'sub': 'Kromey', 'iss': settings.NABU['jwt']['iss'], 'aud': settings.NABU['jwt']['aud'], 'exp': datetime.utcnow() + timedelta(**settings.NABU['jwt']['exp']), } token = jwt.encode(data, ecc_private, algorithm='ES256') context['token'] = token.decode('utf-8') return context
Use Nabu settings in token generation
Use Nabu settings in token generation
Python
mit
Kromey/fbxnano,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters
from datetime import datetime, timedelta import jwt import os from django.shortcuts import render from django.conf import settings from django.views.generic.base import TemplateView key = os.path.join( os.path.dirname(__file__), 'ecc', 'key.pem', ) with open(key, 'r') as fh: ecc_private = fh.read() # Create your views here. class NabuView(TemplateView): template_name = 'chat/nabu.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = { 'sub': 'Kromey', - 'iss': self.request.headers['Host'], - 'aud': self.request.headers['Host'], + 'iss': settings.NABU['jwt']['iss'], + 'aud': settings.NABU['jwt']['aud'], - 'exp': datetime.utcnow() + timedelta(seconds=30), + 'exp': datetime.utcnow() + timedelta(**settings.NABU['jwt']['exp']), } token = jwt.encode(data, ecc_private, algorithm='ES256') context['token'] = token.decode('utf-8') return context
Use Nabu settings in token generation
## Code Before: from datetime import datetime, timedelta import jwt import os from django.shortcuts import render from django.conf import settings from django.views.generic.base import TemplateView key = os.path.join( os.path.dirname(__file__), 'ecc', 'key.pem', ) with open(key, 'r') as fh: ecc_private = fh.read() # Create your views here. class NabuView(TemplateView): template_name = 'chat/nabu.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = { 'sub': 'Kromey', 'iss': self.request.headers['Host'], 'aud': self.request.headers['Host'], 'exp': datetime.utcnow() + timedelta(seconds=30), } token = jwt.encode(data, ecc_private, algorithm='ES256') context['token'] = token.decode('utf-8') return context ## Instruction: Use Nabu settings in token generation ## Code After: from datetime import datetime, timedelta import jwt import os from django.shortcuts import render from django.conf import settings from django.views.generic.base import TemplateView key = os.path.join( os.path.dirname(__file__), 'ecc', 'key.pem', ) with open(key, 'r') as fh: ecc_private = fh.read() # Create your views here. class NabuView(TemplateView): template_name = 'chat/nabu.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = { 'sub': 'Kromey', 'iss': settings.NABU['jwt']['iss'], 'aud': settings.NABU['jwt']['aud'], 'exp': datetime.utcnow() + timedelta(**settings.NABU['jwt']['exp']), } token = jwt.encode(data, ecc_private, algorithm='ES256') context['token'] = token.decode('utf-8') return context
d8702486851c59d8b030a63aefee2b5ca152772e
test_projects/django14/pizzagigi/urls.py
test_projects/django14/pizzagigi/urls.py
from django.conf.urls import patterns, url from django.views.generic import TemplateView from .views import ( PizzaCreateView, PizzaDeleteView, PizzaDetailView, PizzaListView, PizzaUpdateView, ChickenWingsListView ) urlpatterns = patterns('', # NOQA url(r'^$', PizzaListView.as_view(), name='list'), url(r'^create/$', PizzaCreateView.as_view(), name='create'), url(r'^created/$', TemplateView.as_view( template_name='pizzagigi/pizza_created.html'), name='created'), url(r'^detail/(?P<pk>[0-9]*)$', PizzaDetailView.as_view(), name='detail'), url(r'^update/(?P<pk>[0-9]*)$', PizzaUpdateView.as_view(), name='update'), url(r'^updated/$', TemplateView.as_view( template_name='pizzagigi/pizza_updated.html'), name='updated'), url(r'^delete/(?P<pk>[0-9]*)$', PizzaDeleteView.as_view(), name='delete'), url(r'^deleted/$', TemplateView.as_view( template_name='pizzagigi/pizza_deleted.html'), name='deleted'), url(r'^wings/$', ChickenWingsListView.as_view(), name='chickenwings_list'), )
from django.conf.urls import patterns, url from django.views.generic import TemplateView from .views import ( PizzaCreateView, PizzaDeleteView, PizzaDetailView, PizzaListView, PizzaUpdateView ) urlpatterns = patterns('', # NOQA url(r'^$', PizzaListView.as_view(), name='list'), url(r'^create/$', PizzaCreateView.as_view(), name='create'), url(r'^created/$', TemplateView.as_view( template_name='pizzagigi/pizza_created.html'), name='created'), url(r'^detail/(?P<pk>[0-9]*)$', PizzaDetailView.as_view(), name='detail'), url(r'^update/(?P<pk>[0-9]*)$', PizzaUpdateView.as_view(), name='update'), url(r'^updated/$', TemplateView.as_view( template_name='pizzagigi/pizza_updated.html'), name='updated'), url(r'^delete/(?P<pk>[0-9]*)$', PizzaDeleteView.as_view(), name='delete'), url(r'^deleted/$', TemplateView.as_view( template_name='pizzagigi/pizza_deleted.html'), name='deleted'), )
Move chickens to other app
Move chickens to other app
Python
bsd-3-clause
kelvinwong-ca/django-select-multiple-field,kelvinwong-ca/django-select-multiple-field,kelvinwong-ca/django-select-multiple-field
from django.conf.urls import patterns, url from django.views.generic import TemplateView from .views import ( PizzaCreateView, PizzaDeleteView, PizzaDetailView, PizzaListView, - PizzaUpdateView, + PizzaUpdateView - ChickenWingsListView ) urlpatterns = patterns('', # NOQA url(r'^$', PizzaListView.as_view(), name='list'), url(r'^create/$', PizzaCreateView.as_view(), name='create'), url(r'^created/$', TemplateView.as_view( template_name='pizzagigi/pizza_created.html'), name='created'), url(r'^detail/(?P<pk>[0-9]*)$', PizzaDetailView.as_view(), name='detail'), url(r'^update/(?P<pk>[0-9]*)$', PizzaUpdateView.as_view(), name='update'), url(r'^updated/$', TemplateView.as_view( template_name='pizzagigi/pizza_updated.html'), name='updated'), url(r'^delete/(?P<pk>[0-9]*)$', PizzaDeleteView.as_view(), name='delete'), url(r'^deleted/$', TemplateView.as_view( template_name='pizzagigi/pizza_deleted.html'), name='deleted'), - url(r'^wings/$', ChickenWingsListView.as_view(), name='chickenwings_list'), - )
Move chickens to other app
## Code Before: from django.conf.urls import patterns, url from django.views.generic import TemplateView from .views import ( PizzaCreateView, PizzaDeleteView, PizzaDetailView, PizzaListView, PizzaUpdateView, ChickenWingsListView ) urlpatterns = patterns('', # NOQA url(r'^$', PizzaListView.as_view(), name='list'), url(r'^create/$', PizzaCreateView.as_view(), name='create'), url(r'^created/$', TemplateView.as_view( template_name='pizzagigi/pizza_created.html'), name='created'), url(r'^detail/(?P<pk>[0-9]*)$', PizzaDetailView.as_view(), name='detail'), url(r'^update/(?P<pk>[0-9]*)$', PizzaUpdateView.as_view(), name='update'), url(r'^updated/$', TemplateView.as_view( template_name='pizzagigi/pizza_updated.html'), name='updated'), url(r'^delete/(?P<pk>[0-9]*)$', PizzaDeleteView.as_view(), name='delete'), url(r'^deleted/$', TemplateView.as_view( template_name='pizzagigi/pizza_deleted.html'), name='deleted'), url(r'^wings/$', ChickenWingsListView.as_view(), name='chickenwings_list'), ) ## Instruction: Move chickens to other app ## Code After: from django.conf.urls import patterns, url from django.views.generic import TemplateView from .views import ( PizzaCreateView, PizzaDeleteView, PizzaDetailView, PizzaListView, PizzaUpdateView ) urlpatterns = patterns('', # NOQA url(r'^$', PizzaListView.as_view(), name='list'), url(r'^create/$', PizzaCreateView.as_view(), name='create'), url(r'^created/$', TemplateView.as_view( template_name='pizzagigi/pizza_created.html'), name='created'), url(r'^detail/(?P<pk>[0-9]*)$', PizzaDetailView.as_view(), name='detail'), url(r'^update/(?P<pk>[0-9]*)$', PizzaUpdateView.as_view(), name='update'), url(r'^updated/$', TemplateView.as_view( template_name='pizzagigi/pizza_updated.html'), name='updated'), url(r'^delete/(?P<pk>[0-9]*)$', PizzaDeleteView.as_view(), name='delete'), url(r'^deleted/$', TemplateView.as_view( template_name='pizzagigi/pizza_deleted.html'), name='deleted'), )
4bd930b8bc6410a9966327c8e73e0b1849c71157
sympy/conftest.py
sympy/conftest.py
import sys sys._running_pytest = True from sympy.core.cache import clear_cache def pytest_terminal_summary(terminalreporter): if (terminalreporter.stats.get('error', None) or terminalreporter.stats.get('failed', None)): terminalreporter.write_sep(' ', 'DO *NOT* COMMIT!', red=True, bold=True) def pytest_runtest_teardown(): clear_cache()
import sys sys._running_pytest = True from sympy.core.cache import clear_cache def pytest_report_header(config): from sympy.utilities.misc import ARCH s = "architecture: %s\n" % ARCH from sympy.core.cache import USE_CACHE s += "cache: %s\n" % USE_CACHE from sympy.polys.domains import GROUND_TYPES s += "ground types: %s\n" % GROUND_TYPES return s def pytest_terminal_summary(terminalreporter): if (terminalreporter.stats.get('error', None) or terminalreporter.stats.get('failed', None)): terminalreporter.write_sep(' ', 'DO *NOT* COMMIT!', red=True, bold=True) def pytest_runtest_teardown(): clear_cache()
Add more info to pytest header
Add more info to pytest header
Python
bsd-3-clause
moble/sympy,ahhda/sympy,chaffra/sympy,saurabhjn76/sympy,saurabhjn76/sympy,ga7g08/sympy,AkademieOlympia/sympy,sampadsaha5/sympy,hrashk/sympy,jbbskinny/sympy,chaffra/sympy,yukoba/sympy,Designist/sympy,abhiii5459/sympy,atsao72/sympy,pandeyadarsh/sympy,kevalds51/sympy,postvakje/sympy,sahmed95/sympy,beni55/sympy,Vishluck/sympy,asm666/sympy,rahuldan/sympy,garvitr/sympy,AunShiLord/sympy,MechCoder/sympy,shipci/sympy,bukzor/sympy,ga7g08/sympy,chaffra/sympy,ga7g08/sympy,sahilshekhawat/sympy,Gadal/sympy,emon10005/sympy,madan96/sympy,MechCoder/sympy,jaimahajan1997/sympy,MridulS/sympy,kaushik94/sympy,bukzor/sympy,oliverlee/sympy,lidavidm/sympy,Shaswat27/sympy,drufat/sympy,Gadal/sympy,Designist/sympy,cccfran/sympy,hargup/sympy,souravsingh/sympy,atsao72/sympy,diofant/diofant,dqnykamp/sympy,farhaanbukhsh/sympy,hrashk/sympy,abloomston/sympy,Titan-C/sympy,abhiii5459/sympy,farhaanbukhsh/sympy,mafiya69/sympy,lidavidm/sympy,pbrady/sympy,jamesblunt/sympy,iamutkarshtiwari/sympy,yashsharan/sympy,Titan-C/sympy,drufat/sympy,pandeyadarsh/sympy,dqnykamp/sympy,maniteja123/sympy,sunny94/temp,debugger22/sympy,meghana1995/sympy,ahhda/sympy,cswiercz/sympy,meghana1995/sympy,AkademieOlympia/sympy,jbbskinny/sympy,hargup/sympy,toolforger/sympy,kaushik94/sympy,mcdaniel67/sympy,Vishluck/sympy,kaichogami/sympy,wyom/sympy,lindsayad/sympy,Shaswat27/sympy,atsao72/sympy,srjoglekar246/sympy,Davidjohnwilson/sympy,sahilshekhawat/sympy,Davidjohnwilson/sympy,dqnykamp/sympy,sahmed95/sympy,moble/sympy,farhaanbukhsh/sympy,rahuldan/sympy,ChristinaZografou/sympy,skidzo/sympy,MridulS/sympy,kevalds51/sympy,shipci/sympy,jamesblunt/sympy,VaibhavAgarwalVA/sympy,beni55/sympy,hrashk/sympy,ChristinaZografou/sympy,pbrady/sympy,MechCoder/sympy,sampadsaha5/sympy,Designist/sympy,Curious72/sympy,souravsingh/sympy,wyom/sympy,lidavidm/sympy,abhiii5459/sympy,moble/sympy,wyom/sympy,Mitchkoens/sympy,Mitchkoens/sympy,liangjiaxing/sympy,Arafatk/sympy,hargup/sympy,yukoba/sympy,jbbskinny/sympy,postvakje/sympy,garvitr/sympy,grevutiu-gabriel/sympy,MridulS/sympy,mcdaniel67/sympy,Titan-C/sympy,cccfran/sympy,shipci/sympy,amitjamadagni/sympy,Curious72/sympy,cswiercz/sympy,toolforger/sympy,Arafatk/sympy,kmacinnis/sympy,asm666/sympy,iamutkarshtiwari/sympy,atreyv/sympy,kumarkrishna/sympy,atreyv/sympy,debugger22/sympy,wanglongqi/sympy,VaibhavAgarwalVA/sympy,saurabhjn76/sympy,pandeyadarsh/sympy,Gadal/sympy,aktech/sympy,shikil/sympy,amitjamadagni/sympy,VaibhavAgarwalVA/sympy,madan96/sympy,Mitchkoens/sympy,kumarkrishna/sympy,drufat/sympy,skidzo/sympy,maniteja123/sympy,kmacinnis/sympy,wanglongqi/sympy,kmacinnis/sympy,toolforger/sympy,skirpichev/omg,jerli/sympy,liangjiaxing/sympy,cswiercz/sympy,lindsayad/sympy,mafiya69/sympy,beni55/sympy,atreyv/sympy,abloomston/sympy,yukoba/sympy,cccfran/sympy,rahuldan/sympy,postvakje/sympy,shikil/sympy,shikil/sympy,Sumith1896/sympy,lindsayad/sympy,sunny94/temp,yashsharan/sympy,ahhda/sympy,asm666/sympy,AunShiLord/sympy,jamesblunt/sympy,grevutiu-gabriel/sympy,madan96/sympy,jaimahajan1997/sympy,sunny94/temp,liangjiaxing/sympy,jerli/sympy,emon10005/sympy,Vishluck/sympy,yashsharan/sympy,kaichogami/sympy,skidzo/sympy,kevalds51/sympy,mafiya69/sympy,AunShiLord/sympy,vipulroxx/sympy,vipulroxx/sympy,kumarkrishna/sympy,oliverlee/sympy,debugger22/sympy,grevutiu-gabriel/sympy,Davidjohnwilson/sympy,sampadsaha5/sympy,sahilshekhawat/sympy,Shaswat27/sympy,maniteja123/sympy,pbrady/sympy,emon10005/sympy,aktech/sympy,ChristinaZografou/sympy,bukzor/sympy,flacjacket/sympy,Curious72/sympy,mcdaniel67/sympy,oliverlee/sympy,Arafatk/sympy,sahmed95/sympy,souravsingh/sympy,Sumith1896/sympy,garvitr/sympy,abloomston/sympy,meghana1995/sympy,kaushik94/sympy,Sumith1896/sympy,AkademieOlympia/sympy,kaichogami/sympy,aktech/sympy,wanglongqi/sympy,iamutkarshtiwari/sympy,jerli/sympy,vipulroxx/sympy,jaimahajan1997/sympy
import sys sys._running_pytest = True from sympy.core.cache import clear_cache + + def pytest_report_header(config): + from sympy.utilities.misc import ARCH + s = "architecture: %s\n" % ARCH + from sympy.core.cache import USE_CACHE + s += "cache: %s\n" % USE_CACHE + from sympy.polys.domains import GROUND_TYPES + s += "ground types: %s\n" % GROUND_TYPES + return s def pytest_terminal_summary(terminalreporter): if (terminalreporter.stats.get('error', None) or terminalreporter.stats.get('failed', None)): terminalreporter.write_sep(' ', 'DO *NOT* COMMIT!', red=True, bold=True) def pytest_runtest_teardown(): clear_cache()
Add more info to pytest header
## Code Before: import sys sys._running_pytest = True from sympy.core.cache import clear_cache def pytest_terminal_summary(terminalreporter): if (terminalreporter.stats.get('error', None) or terminalreporter.stats.get('failed', None)): terminalreporter.write_sep(' ', 'DO *NOT* COMMIT!', red=True, bold=True) def pytest_runtest_teardown(): clear_cache() ## Instruction: Add more info to pytest header ## Code After: import sys sys._running_pytest = True from sympy.core.cache import clear_cache def pytest_report_header(config): from sympy.utilities.misc import ARCH s = "architecture: %s\n" % ARCH from sympy.core.cache import USE_CACHE s += "cache: %s\n" % USE_CACHE from sympy.polys.domains import GROUND_TYPES s += "ground types: %s\n" % GROUND_TYPES return s def pytest_terminal_summary(terminalreporter): if (terminalreporter.stats.get('error', None) or terminalreporter.stats.get('failed', None)): terminalreporter.write_sep(' ', 'DO *NOT* COMMIT!', red=True, bold=True) def pytest_runtest_teardown(): clear_cache()
f5fb36875b09926effdae46a92497d01fa04e777
src/models/lm.py
src/models/lm.py
from keras.layers import LSTM, Input, Reshape from keras.models import Model from ..layers import LMMask, Projection class LanguageModel(Model): def __init__(self, n_batch, d_W, d_L, trainable=True): """ n_batch :: batch size for model application d_L :: language model state dimension (and output vector size) d_W :: input word embedding size (word features) """ w_n = Input(batch_shape=(n_batch, d_W), name='w_n', dtype='floatX') w_nmask = Input(batch_shape=(n_batch, 1), name='w_nmask', dtype='int8') # Prevent padded samples to affect internal state (and cause NaN loss in worst # case) by masking them by using another input value w_nmasked = LMMask(0.)([Reshape((1, d_W))(w_n), w_nmask]) # Using stateful LSTM for language model - model fitting code resets the # state after each sentence w_np1Ei = LSTM(d_L, trainable=trainable, return_sequences=False, stateful=True, consume_less='gpu')(w_nmasked) w_np1E = Projection(d_W)(w_np1Ei) super(LanguageModel, self).__init__(input=[w_n, w_nmask], output=w_np1E, name='LanguageModel')
from keras.layers import LSTM, Input, Reshape from keras.models import Model from ..layers import LMMask, Projection class LanguageModel(Model): def __init__(self, n_batch, d_W, d_L, trainable=True): """ n_batch :: batch size for model application d_L :: language model state dimension (and output vector size) d_W :: input word embedding size (word features) """ w_n = Input(batch_shape=(n_batch, d_W), name='w_n', dtype='floatX') w_nmask = Input(batch_shape=(n_batch, 1), name='w_nmask', dtype='int8') # Prevent padded samples to affect internal state (and cause NaN loss in worst # case) by masking them by using w_nmask masking values w_nmasked = LMMask(0.)([Reshape((1, d_W))(w_n), w_nmask]) # Using stateful LSTM for language model - model fitting code resets the # state after each sentence w_np1Ei = LSTM(d_L, trainable=trainable, return_sequences=True, stateful=True, consume_less='gpu')(w_nmasked) w_np1Ei = LSTM(d_L, trainable=trainable, return_sequences=False, stateful=True, consume_less='gpu')(w_np1Ei) w_np1E = Projection(d_W)(w_np1Ei) super(LanguageModel, self).__init__(input=[w_n, w_nmask], output=w_np1E, name='LanguageModel')
Use two LSTM LM’s instead of single huge one
Use two LSTM LM’s instead of single huge one
Python
mit
milankinen/c2w2c,milankinen/c2w2c
from keras.layers import LSTM, Input, Reshape from keras.models import Model from ..layers import LMMask, Projection class LanguageModel(Model): def __init__(self, n_batch, d_W, d_L, trainable=True): """ n_batch :: batch size for model application d_L :: language model state dimension (and output vector size) d_W :: input word embedding size (word features) """ w_n = Input(batch_shape=(n_batch, d_W), name='w_n', dtype='floatX') w_nmask = Input(batch_shape=(n_batch, 1), name='w_nmask', dtype='int8') # Prevent padded samples to affect internal state (and cause NaN loss in worst - # case) by masking them by using another input value + # case) by masking them by using w_nmask masking values w_nmasked = LMMask(0.)([Reshape((1, d_W))(w_n), w_nmask]) # Using stateful LSTM for language model - model fitting code resets the # state after each sentence w_np1Ei = LSTM(d_L, trainable=trainable, + return_sequences=True, + stateful=True, + consume_less='gpu')(w_nmasked) + w_np1Ei = LSTM(d_L, + trainable=trainable, return_sequences=False, stateful=True, - consume_less='gpu')(w_nmasked) + consume_less='gpu')(w_np1Ei) w_np1E = Projection(d_W)(w_np1Ei) super(LanguageModel, self).__init__(input=[w_n, w_nmask], output=w_np1E, name='LanguageModel')
Use two LSTM LM’s instead of single huge one
## Code Before: from keras.layers import LSTM, Input, Reshape from keras.models import Model from ..layers import LMMask, Projection class LanguageModel(Model): def __init__(self, n_batch, d_W, d_L, trainable=True): """ n_batch :: batch size for model application d_L :: language model state dimension (and output vector size) d_W :: input word embedding size (word features) """ w_n = Input(batch_shape=(n_batch, d_W), name='w_n', dtype='floatX') w_nmask = Input(batch_shape=(n_batch, 1), name='w_nmask', dtype='int8') # Prevent padded samples to affect internal state (and cause NaN loss in worst # case) by masking them by using another input value w_nmasked = LMMask(0.)([Reshape((1, d_W))(w_n), w_nmask]) # Using stateful LSTM for language model - model fitting code resets the # state after each sentence w_np1Ei = LSTM(d_L, trainable=trainable, return_sequences=False, stateful=True, consume_less='gpu')(w_nmasked) w_np1E = Projection(d_W)(w_np1Ei) super(LanguageModel, self).__init__(input=[w_n, w_nmask], output=w_np1E, name='LanguageModel') ## Instruction: Use two LSTM LM’s instead of single huge one ## Code After: from keras.layers import LSTM, Input, Reshape from keras.models import Model from ..layers import LMMask, Projection class LanguageModel(Model): def __init__(self, n_batch, d_W, d_L, trainable=True): """ n_batch :: batch size for model application d_L :: language model state dimension (and output vector size) d_W :: input word embedding size (word features) """ w_n = Input(batch_shape=(n_batch, d_W), name='w_n', dtype='floatX') w_nmask = Input(batch_shape=(n_batch, 1), name='w_nmask', dtype='int8') # Prevent padded samples to affect internal state (and cause NaN loss in worst # case) by masking them by using w_nmask masking values w_nmasked = LMMask(0.)([Reshape((1, d_W))(w_n), w_nmask]) # Using stateful LSTM for language model - model fitting code resets the # state after each sentence w_np1Ei = LSTM(d_L, trainable=trainable, return_sequences=True, stateful=True, consume_less='gpu')(w_nmasked) w_np1Ei = LSTM(d_L, trainable=trainable, return_sequences=False, stateful=True, consume_less='gpu')(w_np1Ei) w_np1E = Projection(d_W)(w_np1Ei) super(LanguageModel, self).__init__(input=[w_n, w_nmask], output=w_np1E, name='LanguageModel')
f16ce4235e124fa9ea5d335665221514a2fcdcce
examples/cpp/clion.py
examples/cpp/clion.py
"""This is a **proof-of-concept** CLion project generator.""" import functools import json import subprocess subprocess.check_call(['cook', '--results']) with open('results.json') as file: content = json.load(file) with open('CMakeLists.txt', 'w') as file: w = functools.partial(print, file=file) w('cmake_minimum_required(VERSION 2.8.8)') w() w('add_custom_target(COOK COMMAND cook ' 'WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})') w() outputs = {} for primary, result in content.items(): for output in result['outputs']: outputs[output] = primary for primary, result in content.items(): if result.get('type') == 'cpp.object': cpp = [file for file in result['inputs'] if file.endswith('.cpp')] w('add_library({} OBJECT {})'.format(primary, ' '.join(cpp))) defines = ' '.join(name + '=' + str(val) for name, val in result['define'].items()) if defines: w('target_compile_definitions({} PRIVATE {})' .format(primary, defines)) includes = result['include'] if includes: w('target_include_directories({} PRIVATE {})'.format( primary, ' '.join(includes) )) w()
"""This is a **proof-of-concept** CLion project generator.""" import functools import json import subprocess import sys subprocess.check_call(['cook', '--results']) with open('results.json') as file: content = json.load(file) with open('CMakeLists.txt', 'w') as file: w = functools.partial(print, file=file) w('cmake_minimum_required(VERSION 2.8.8)') w() w('add_custom_target(COOK COMMAND ' + sys.executable + ' clion.py COMMAND cook ' 'WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})') w() outputs = {} for primary, result in content.items(): for output in result['outputs']: outputs[output] = primary for primary, result in content.items(): if result.get('type') == 'cpp.object': cpp = [file for file in result['inputs'] if file.endswith('.cpp')] w('add_library({} OBJECT {})'.format(primary, ' '.join(cpp))) defines = ' '.join(name + '=' + str(val) for name, val in result['define'].items()) if defines: w('target_compile_definitions({} PRIVATE {})' .format(primary, defines)) includes = result['include'] if includes: w('target_include_directories({} PRIVATE {})'.format( primary, ' '.join(includes) )) w()
Add automatic regeneration for CLion
Add automatic regeneration for CLion
Python
mit
jachris/cook
"""This is a **proof-of-concept** CLion project generator.""" import functools import json import subprocess + import sys subprocess.check_call(['cook', '--results']) with open('results.json') as file: content = json.load(file) with open('CMakeLists.txt', 'w') as file: w = functools.partial(print, file=file) w('cmake_minimum_required(VERSION 2.8.8)') w() - w('add_custom_target(COOK COMMAND cook ' + w('add_custom_target(COOK COMMAND ' + sys.executable + ' clion.py COMMAND cook ' 'WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})') w() outputs = {} for primary, result in content.items(): for output in result['outputs']: outputs[output] = primary for primary, result in content.items(): if result.get('type') == 'cpp.object': cpp = [file for file in result['inputs'] if file.endswith('.cpp')] w('add_library({} OBJECT {})'.format(primary, ' '.join(cpp))) defines = ' '.join(name + '=' + str(val) for name, val in result['define'].items()) if defines: w('target_compile_definitions({} PRIVATE {})' .format(primary, defines)) includes = result['include'] if includes: w('target_include_directories({} PRIVATE {})'.format( primary, ' '.join(includes) )) w()
Add automatic regeneration for CLion
## Code Before: """This is a **proof-of-concept** CLion project generator.""" import functools import json import subprocess subprocess.check_call(['cook', '--results']) with open('results.json') as file: content = json.load(file) with open('CMakeLists.txt', 'w') as file: w = functools.partial(print, file=file) w('cmake_minimum_required(VERSION 2.8.8)') w() w('add_custom_target(COOK COMMAND cook ' 'WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})') w() outputs = {} for primary, result in content.items(): for output in result['outputs']: outputs[output] = primary for primary, result in content.items(): if result.get('type') == 'cpp.object': cpp = [file for file in result['inputs'] if file.endswith('.cpp')] w('add_library({} OBJECT {})'.format(primary, ' '.join(cpp))) defines = ' '.join(name + '=' + str(val) for name, val in result['define'].items()) if defines: w('target_compile_definitions({} PRIVATE {})' .format(primary, defines)) includes = result['include'] if includes: w('target_include_directories({} PRIVATE {})'.format( primary, ' '.join(includes) )) w() ## Instruction: Add automatic regeneration for CLion ## Code After: """This is a **proof-of-concept** CLion project generator.""" import functools import json import subprocess import sys subprocess.check_call(['cook', '--results']) with open('results.json') as file: content = json.load(file) with open('CMakeLists.txt', 'w') as file: w = functools.partial(print, file=file) w('cmake_minimum_required(VERSION 2.8.8)') w() w('add_custom_target(COOK COMMAND ' + sys.executable + ' clion.py COMMAND cook ' 'WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})') w() outputs = {} for primary, result in content.items(): for output in result['outputs']: outputs[output] = primary for primary, result in content.items(): if result.get('type') == 'cpp.object': cpp = [file for file in result['inputs'] if file.endswith('.cpp')] w('add_library({} OBJECT {})'.format(primary, ' '.join(cpp))) defines = ' '.join(name + '=' + str(val) for name, val in result['define'].items()) if defines: w('target_compile_definitions({} PRIVATE {})' .format(primary, defines)) includes = result['include'] if includes: w('target_include_directories({} PRIVATE {})'.format( primary, ' '.join(includes) )) w()
c0df1342b6625cdc2a205f2ba13ee201e8d0b02a
tests/conftest.py
tests/conftest.py
from __future__ import absolute_import import pytest import os import mock import json import app.mapping with open(os.path.join(os.path.dirname(__file__), 'fixtures/mappings/services.json')) as f: _services_mapping_definition = json.load(f) @pytest.fixture(scope="function") def services_mapping(): """Provide a services mapping fixture, and patch it into the global singleton getter.""" mock_services_mapping_getter_patch = mock.patch('app.mapping.get_services_mapping') mock_services_mapping_getter = mock_services_mapping_getter_patch.start() mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') yield mock_services_mapping_getter.return_value mock_services_mapping_getter_patch.stop()
from __future__ import absolute_import import pytest import os import mock import json import app.mapping with open(os.path.join(os.path.dirname(__file__), 'fixtures/mappings/services.json')) as f: _services_mapping_definition = json.load(f) @pytest.fixture(scope="function") def services_mapping(): """Provide a services mapping fixture, and patch it into the global singleton getter.""" with mock.patch('app.mapping.get_services_mapping') as mock_services_mapping_getter: mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') yield mock_services_mapping_getter.return_value
Use with block to start/stop the patch context manager.
Use with block to start/stop the patch context manager. - this is less code, hopefully is just as clear why we need to 'yield' rather than just 'return'. https://trello.com/c/OpWI068M/380-after-g9-go-live-removal-of-old-filters-from-search-api-mapping
Python
mit
alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api
from __future__ import absolute_import import pytest import os import mock import json import app.mapping with open(os.path.join(os.path.dirname(__file__), 'fixtures/mappings/services.json')) as f: _services_mapping_definition = json.load(f) @pytest.fixture(scope="function") def services_mapping(): """Provide a services mapping fixture, and patch it into the global singleton getter.""" + with mock.patch('app.mapping.get_services_mapping') as mock_services_mapping_getter: - mock_services_mapping_getter_patch = mock.patch('app.mapping.get_services_mapping') - mock_services_mapping_getter = mock_services_mapping_getter_patch.start() - mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') + mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') + yield mock_services_mapping_getter.return_value - yield mock_services_mapping_getter.return_value - - mock_services_mapping_getter_patch.stop() -
Use with block to start/stop the patch context manager.
## Code Before: from __future__ import absolute_import import pytest import os import mock import json import app.mapping with open(os.path.join(os.path.dirname(__file__), 'fixtures/mappings/services.json')) as f: _services_mapping_definition = json.load(f) @pytest.fixture(scope="function") def services_mapping(): """Provide a services mapping fixture, and patch it into the global singleton getter.""" mock_services_mapping_getter_patch = mock.patch('app.mapping.get_services_mapping') mock_services_mapping_getter = mock_services_mapping_getter_patch.start() mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') yield mock_services_mapping_getter.return_value mock_services_mapping_getter_patch.stop() ## Instruction: Use with block to start/stop the patch context manager. ## Code After: from __future__ import absolute_import import pytest import os import mock import json import app.mapping with open(os.path.join(os.path.dirname(__file__), 'fixtures/mappings/services.json')) as f: _services_mapping_definition = json.load(f) @pytest.fixture(scope="function") def services_mapping(): """Provide a services mapping fixture, and patch it into the global singleton getter.""" with mock.patch('app.mapping.get_services_mapping') as mock_services_mapping_getter: mock_services_mapping_getter.return_value = app.mapping.Mapping(_services_mapping_definition, 'services') yield mock_services_mapping_getter.return_value
d613ca02bef0572d7581c843eb5466443410decf
test_settings.py
test_settings.py
import os from django.urls import ( include, path, ) BASE_DIR = os.path.dirname(__file__) STATIC_URL = "/static/" INSTALLED_APPS = ( 'gcloudc', 'djangae', 'djangae.commands', # Takes care of emulator setup 'djangae.tasks', ) DATABASES = { 'default': { 'ENGINE': 'gcloudc.db.backends.datastore', 'INDEXES_FILE': os.path.join(os.path.abspath(os.path.dirname(__file__)), "djangaeidx.yaml"), "PROJECT": "test", "NAMESPACE": "ns1", # Use a non-default namespace to catch edge cases where we forget } } SECRET_KEY = "secret_key_for_testing" USE_TZ = True CSRF_USE_SESSIONS = True CLOUD_TASKS_LOCATION = "[LOCATION]" # Define two required task queues CLOUD_TASKS_QUEUES = [ { "name": "default" }, { "name": "another" } ] # Point the URL conf at this file ROOT_URLCONF = __name__ urlpatterns = [ path('tasks/', include('djangae.tasks.urls')), ]
import os from django.urls import ( include, path, ) BASE_DIR = os.path.dirname(__file__) STATIC_URL = "/static/" # Default Django middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'djangae.tasks.middleware.task_environment_middleware', ] INSTALLED_APPS = ( 'django.contrib.sessions', 'gcloudc', 'djangae', 'djangae.commands', # Takes care of emulator setup 'djangae.tasks', ) DATABASES = { 'default': { 'ENGINE': 'gcloudc.db.backends.datastore', 'INDEXES_FILE': os.path.join(os.path.abspath(os.path.dirname(__file__)), "djangaeidx.yaml"), "PROJECT": "test", "NAMESPACE": "ns1", # Use a non-default namespace to catch edge cases where we forget } } SECRET_KEY = "secret_key_for_testing" USE_TZ = True CSRF_USE_SESSIONS = True CLOUD_TASKS_LOCATION = "[LOCATION]" # Define two required task queues CLOUD_TASKS_QUEUES = [ { "name": "default" }, { "name": "another" } ] # Point the URL conf at this file ROOT_URLCONF = __name__ urlpatterns = [ path('tasks/', include('djangae.tasks.urls')), ]
Set default Django middleware in test settings
Set default Django middleware in test settings
Python
bsd-3-clause
potatolondon/djangae,potatolondon/djangae
import os from django.urls import ( include, path, ) BASE_DIR = os.path.dirname(__file__) STATIC_URL = "/static/" + # Default Django middleware + MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'djangae.tasks.middleware.task_environment_middleware', + ] + INSTALLED_APPS = ( + 'django.contrib.sessions', 'gcloudc', 'djangae', 'djangae.commands', # Takes care of emulator setup 'djangae.tasks', ) DATABASES = { 'default': { 'ENGINE': 'gcloudc.db.backends.datastore', 'INDEXES_FILE': os.path.join(os.path.abspath(os.path.dirname(__file__)), "djangaeidx.yaml"), "PROJECT": "test", "NAMESPACE": "ns1", # Use a non-default namespace to catch edge cases where we forget } } SECRET_KEY = "secret_key_for_testing" USE_TZ = True CSRF_USE_SESSIONS = True CLOUD_TASKS_LOCATION = "[LOCATION]" # Define two required task queues CLOUD_TASKS_QUEUES = [ { "name": "default" }, { "name": "another" } ] # Point the URL conf at this file ROOT_URLCONF = __name__ urlpatterns = [ path('tasks/', include('djangae.tasks.urls')), ]
Set default Django middleware in test settings
## Code Before: import os from django.urls import ( include, path, ) BASE_DIR = os.path.dirname(__file__) STATIC_URL = "/static/" INSTALLED_APPS = ( 'gcloudc', 'djangae', 'djangae.commands', # Takes care of emulator setup 'djangae.tasks', ) DATABASES = { 'default': { 'ENGINE': 'gcloudc.db.backends.datastore', 'INDEXES_FILE': os.path.join(os.path.abspath(os.path.dirname(__file__)), "djangaeidx.yaml"), "PROJECT": "test", "NAMESPACE": "ns1", # Use a non-default namespace to catch edge cases where we forget } } SECRET_KEY = "secret_key_for_testing" USE_TZ = True CSRF_USE_SESSIONS = True CLOUD_TASKS_LOCATION = "[LOCATION]" # Define two required task queues CLOUD_TASKS_QUEUES = [ { "name": "default" }, { "name": "another" } ] # Point the URL conf at this file ROOT_URLCONF = __name__ urlpatterns = [ path('tasks/', include('djangae.tasks.urls')), ] ## Instruction: Set default Django middleware in test settings ## Code After: import os from django.urls import ( include, path, ) BASE_DIR = os.path.dirname(__file__) STATIC_URL = "/static/" # Default Django middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'djangae.tasks.middleware.task_environment_middleware', ] INSTALLED_APPS = ( 'django.contrib.sessions', 'gcloudc', 'djangae', 'djangae.commands', # Takes care of emulator setup 'djangae.tasks', ) DATABASES = { 'default': { 'ENGINE': 'gcloudc.db.backends.datastore', 'INDEXES_FILE': os.path.join(os.path.abspath(os.path.dirname(__file__)), "djangaeidx.yaml"), "PROJECT": "test", "NAMESPACE": "ns1", # Use a non-default namespace to catch edge cases where we forget } } SECRET_KEY = "secret_key_for_testing" USE_TZ = True CSRF_USE_SESSIONS = True CLOUD_TASKS_LOCATION = "[LOCATION]" # Define two required task queues CLOUD_TASKS_QUEUES = [ { "name": "default" }, { "name": "another" } ] # Point the URL conf at this file ROOT_URLCONF = __name__ urlpatterns = [ path('tasks/', include('djangae.tasks.urls')), ]
2bef67ad0a4fb0db4bdf11d24b3c63e37558e7b9
poker/_common.py
poker/_common.py
import random from enum import Enum from enum34_custom import _MultiValueMeta, OrderableMixin, CaseInsensitiveMultiValueEnum from types import DynamicClassAttribute class _MultiMeta(_MultiValueMeta): def make_random(cls): return random.choice(list(cls)) class _MultiValueEnum(OrderableMixin, Enum, metaclass=_MultiMeta): def __str__(self): return str(self.value) def __repr__(self): apostrophe = "'" if isinstance(self.value, str) else '' return "{0}({1}{2}{1})".format(self.__class__.__qualname__, apostrophe, self) @DynamicClassAttribute def value(self): """The value of the Enum member.""" return self._value_[0] class _CaseInsensitiveMultiValueEnum(CaseInsensitiveMultiValueEnum): def __str__(self): return str(self.value[0]) class _ReprMixin: def __repr__(self): return "{}('{}')".format(self.__class__.__qualname__, self) def _make_float(string): return float(string.strip().replace(',', '')) def _make_int(string): return int(string.strip().replace(',', ''))
import random from enum import Enum from enum34_custom import ( _MultiValueMeta, OrderableMixin, CaseInsensitiveMultiValueEnum, MultiValueEnum ) from types import DynamicClassAttribute class _RandomMultiValueMeta(_MultiValueMeta): def make_random(cls): return random.choice(list(cls)) class _MultiValueEnum(OrderableMixin, MultiValueEnum, metaclass=_RandomMultiValueMeta): def __str__(self): return str(self.value) def __repr__(self): apostrophe = "'" if isinstance(self.value, str) else '' return "{0}({1}{2}{1})".format(self.__class__.__qualname__, apostrophe, self) @DynamicClassAttribute def value(self): """The value of the Enum member.""" return self._value_[0] class _CaseInsensitiveMultiValueEnum(CaseInsensitiveMultiValueEnum): def __str__(self): return str(self.value[0]) class _ReprMixin: def __repr__(self): return "{}('{}')".format(self.__class__.__qualname__, self) def _make_float(string): return float(string.strip().replace(',', '')) def _make_int(string): return int(string.strip().replace(',', ''))
Clarify what _MultiVAlueEnum does and where it comes from.
Clarify what _MultiVAlueEnum does and where it comes from.
Python
mit
pokerregion/poker,Seanmcn/poker,marchon/poker
import random from enum import Enum - from enum34_custom import _MultiValueMeta, OrderableMixin, CaseInsensitiveMultiValueEnum + from enum34_custom import ( + _MultiValueMeta, OrderableMixin, CaseInsensitiveMultiValueEnum, MultiValueEnum + ) from types import DynamicClassAttribute - class _MultiMeta(_MultiValueMeta): + class _RandomMultiValueMeta(_MultiValueMeta): def make_random(cls): return random.choice(list(cls)) - class _MultiValueEnum(OrderableMixin, Enum, metaclass=_MultiMeta): + class _MultiValueEnum(OrderableMixin, MultiValueEnum, metaclass=_RandomMultiValueMeta): def __str__(self): return str(self.value) def __repr__(self): apostrophe = "'" if isinstance(self.value, str) else '' return "{0}({1}{2}{1})".format(self.__class__.__qualname__, apostrophe, self) @DynamicClassAttribute def value(self): """The value of the Enum member.""" return self._value_[0] class _CaseInsensitiveMultiValueEnum(CaseInsensitiveMultiValueEnum): def __str__(self): return str(self.value[0]) class _ReprMixin: def __repr__(self): return "{}('{}')".format(self.__class__.__qualname__, self) def _make_float(string): return float(string.strip().replace(',', '')) def _make_int(string): return int(string.strip().replace(',', ''))
Clarify what _MultiVAlueEnum does and where it comes from.
## Code Before: import random from enum import Enum from enum34_custom import _MultiValueMeta, OrderableMixin, CaseInsensitiveMultiValueEnum from types import DynamicClassAttribute class _MultiMeta(_MultiValueMeta): def make_random(cls): return random.choice(list(cls)) class _MultiValueEnum(OrderableMixin, Enum, metaclass=_MultiMeta): def __str__(self): return str(self.value) def __repr__(self): apostrophe = "'" if isinstance(self.value, str) else '' return "{0}({1}{2}{1})".format(self.__class__.__qualname__, apostrophe, self) @DynamicClassAttribute def value(self): """The value of the Enum member.""" return self._value_[0] class _CaseInsensitiveMultiValueEnum(CaseInsensitiveMultiValueEnum): def __str__(self): return str(self.value[0]) class _ReprMixin: def __repr__(self): return "{}('{}')".format(self.__class__.__qualname__, self) def _make_float(string): return float(string.strip().replace(',', '')) def _make_int(string): return int(string.strip().replace(',', '')) ## Instruction: Clarify what _MultiVAlueEnum does and where it comes from. ## Code After: import random from enum import Enum from enum34_custom import ( _MultiValueMeta, OrderableMixin, CaseInsensitiveMultiValueEnum, MultiValueEnum ) from types import DynamicClassAttribute class _RandomMultiValueMeta(_MultiValueMeta): def make_random(cls): return random.choice(list(cls)) class _MultiValueEnum(OrderableMixin, MultiValueEnum, metaclass=_RandomMultiValueMeta): def __str__(self): return str(self.value) def __repr__(self): apostrophe = "'" if isinstance(self.value, str) else '' return "{0}({1}{2}{1})".format(self.__class__.__qualname__, apostrophe, self) @DynamicClassAttribute def value(self): """The value of the Enum member.""" return self._value_[0] class _CaseInsensitiveMultiValueEnum(CaseInsensitiveMultiValueEnum): def __str__(self): return str(self.value[0]) class _ReprMixin: def __repr__(self): return "{}('{}')".format(self.__class__.__qualname__, self) def _make_float(string): return float(string.strip().replace(',', '')) def _make_int(string): return int(string.strip().replace(',', ''))
edbbf93222fc4061a18f81718a6a7233c6b840ec
tests/test_callbacks.py
tests/test_callbacks.py
import pytest from aiotg import TgBot from aiotg import MESSAGE_TYPES API_TOKEN = "test_token" def text_msg(text): return { "message_id": 0, "from": {}, "chat": { "id": 0, "type": "private" }, "text": text } def test_command(): bot = TgBot(API_TOKEN) called_with = None @bot.command(r"/echo (.+)") def echo(chat, match): nonlocal called_with called_with = match.group(1) bot._process_message(text_msg("/echo foo")) assert called_with == "foo" def test_default(): bot = TgBot(API_TOKEN) called_with = None @bot.default def default(chat, message): nonlocal called_with called_with = message["text"] bot._process_message(text_msg("foo bar")) assert called_with == "foo bar"
import pytest import random from aiotg import TgBot from aiotg import MESSAGE_TYPES API_TOKEN = "test_token" bot = TgBot(API_TOKEN) def custom_msg(msg): template = { "message_id": 0, "from": {}, "chat": { "id": 0, "type": "private" } } template.update(msg) return template def text_msg(text): return custom_msg({ "text": text }) def test_command(): called_with = None @bot.command(r"/echo (.+)") def echo(chat, match): nonlocal called_with called_with = match.group(1) bot._process_message(text_msg("/echo foo")) assert called_with == "foo" def test_default(): called_with = None @bot.default def default(chat, message): nonlocal called_with called_with = message["text"] bot._process_message(text_msg("foo bar")) assert called_with == "foo bar" @pytest.mark.parametrize("mt", MESSAGE_TYPES) def test_handle(mt): called_with = None @bot.handle(mt) def handle(chat, media): nonlocal called_with called_with = media value = random.random() bot._process_message(custom_msg({ mt: value })) assert called_with == value
Add test for media handlers
Add test for media handlers
Python
mit
SijmenSchoon/aiotg,szastupov/aiotg,derfenix/aiotg
import pytest + import random + from aiotg import TgBot from aiotg import MESSAGE_TYPES API_TOKEN = "test_token" + bot = TgBot(API_TOKEN) + + def custom_msg(msg): + template = { + "message_id": 0, + "from": {}, + "chat": { "id": 0, "type": "private" } + } + template.update(msg) + return template + def text_msg(text): + return custom_msg({ "text": text }) + - return { - "message_id": 0, - "from": {}, - "chat": { "id": 0, "type": "private" }, - "text": text - } def test_command(): - bot = TgBot(API_TOKEN) called_with = None @bot.command(r"/echo (.+)") def echo(chat, match): nonlocal called_with called_with = match.group(1) bot._process_message(text_msg("/echo foo")) - assert called_with == "foo" + def test_default(): - bot = TgBot(API_TOKEN) called_with = None @bot.default def default(chat, message): nonlocal called_with called_with = message["text"] bot._process_message(text_msg("foo bar")) - assert called_with == "foo bar" + + @pytest.mark.parametrize("mt", MESSAGE_TYPES) + def test_handle(mt): + called_with = None + + @bot.handle(mt) + def handle(chat, media): + nonlocal called_with + called_with = media + + value = random.random() + bot._process_message(custom_msg({ mt: value })) + assert called_with == value +
Add test for media handlers
## Code Before: import pytest from aiotg import TgBot from aiotg import MESSAGE_TYPES API_TOKEN = "test_token" def text_msg(text): return { "message_id": 0, "from": {}, "chat": { "id": 0, "type": "private" }, "text": text } def test_command(): bot = TgBot(API_TOKEN) called_with = None @bot.command(r"/echo (.+)") def echo(chat, match): nonlocal called_with called_with = match.group(1) bot._process_message(text_msg("/echo foo")) assert called_with == "foo" def test_default(): bot = TgBot(API_TOKEN) called_with = None @bot.default def default(chat, message): nonlocal called_with called_with = message["text"] bot._process_message(text_msg("foo bar")) assert called_with == "foo bar" ## Instruction: Add test for media handlers ## Code After: import pytest import random from aiotg import TgBot from aiotg import MESSAGE_TYPES API_TOKEN = "test_token" bot = TgBot(API_TOKEN) def custom_msg(msg): template = { "message_id": 0, "from": {}, "chat": { "id": 0, "type": "private" } } template.update(msg) return template def text_msg(text): return custom_msg({ "text": text }) def test_command(): called_with = None @bot.command(r"/echo (.+)") def echo(chat, match): nonlocal called_with called_with = match.group(1) bot._process_message(text_msg("/echo foo")) assert called_with == "foo" def test_default(): called_with = None @bot.default def default(chat, message): nonlocal called_with called_with = message["text"] bot._process_message(text_msg("foo bar")) assert called_with == "foo bar" @pytest.mark.parametrize("mt", MESSAGE_TYPES) def test_handle(mt): called_with = None @bot.handle(mt) def handle(chat, media): nonlocal called_with called_with = media value = random.random() bot._process_message(custom_msg({ mt: value })) assert called_with == value
29f6a260e49a6955dd12d354400d9ee6cfd6ddc7
tests/qtcore/qstatemachine_test.py
tests/qtcore/qstatemachine_test.py
import unittest from PySide.QtCore import QObject, QState, QFinalState, SIGNAL, QCoreApplication, QTimer, QStateMachine, QSignalTransition, QVariant, QParallelAnimationGroup, QPropertyAnimation class QStateMachineTest(unittest.TestCase): def cb(self, *args): self.assertEqual(self.machine.defaultAnimations(), [self.anim]) def testBasic(self): app = QCoreApplication([]) self.machine = QStateMachine() s1 = QState() s2 = QState() s3 = QFinalState() QObject.connect(self.machine, SIGNAL("started()"), self.cb) self.anim = QParallelAnimationGroup() self.machine.addState(s1) self.machine.addState(s2) self.machine.addState(s3) self.machine.setInitialState(s1) self.machine.addDefaultAnimation(self.anim) self.machine.start() QTimer.singleShot(100, app.quit) app.exec_() if __name__ == '__main__': unittest.main()
import unittest from PySide.QtCore import QObject, QState, QFinalState, SIGNAL, QCoreApplication, QTimer, QStateMachine, QSignalTransition, QVariant, QParallelAnimationGroup, QPropertyAnimation from helper import UsesQCoreApplication class QStateMachineTest(UsesQCoreApplication): def cb(self, *args): self.assertEqual(self.machine.defaultAnimations(), [self.anim]) def testBasic(self): self.machine = QStateMachine() s1 = QState() s2 = QState() s3 = QFinalState() QObject.connect(self.machine, SIGNAL("started()"), self.cb) self.anim = QParallelAnimationGroup() self.machine.addState(s1) self.machine.addState(s2) self.machine.addState(s3) self.machine.setInitialState(s1) self.machine.addDefaultAnimation(self.anim) self.machine.start() QTimer.singleShot(100, self.app.quit) self.app.exec_() if __name__ == '__main__': unittest.main()
Add UsesQCoreApplication in state machine test
Add UsesQCoreApplication in state machine test
Python
lgpl-2.1
M4rtinK/pyside-bb10,enthought/pyside,M4rtinK/pyside-android,PySide/PySide,IronManMark20/pyside2,PySide/PySide,M4rtinK/pyside-bb10,RobinD42/pyside,BadSingleton/pyside2,PySide/PySide,qtproject/pyside-pyside,enthought/pyside,pankajp/pyside,pankajp/pyside,M4rtinK/pyside-android,PySide/PySide,BadSingleton/pyside2,gbaty/pyside2,qtproject/pyside-pyside,enthought/pyside,enthought/pyside,RobinD42/pyside,pankajp/pyside,pankajp/pyside,enthought/pyside,M4rtinK/pyside-android,M4rtinK/pyside-bb10,enthought/pyside,gbaty/pyside2,qtproject/pyside-pyside,PySide/PySide,M4rtinK/pyside-bb10,M4rtinK/pyside-bb10,M4rtinK/pyside-android,qtproject/pyside-pyside,gbaty/pyside2,RobinD42/pyside,BadSingleton/pyside2,RobinD42/pyside,enthought/pyside,RobinD42/pyside,gbaty/pyside2,IronManMark20/pyside2,M4rtinK/pyside-bb10,IronManMark20/pyside2,RobinD42/pyside,IronManMark20/pyside2,BadSingleton/pyside2,pankajp/pyside,M4rtinK/pyside-android,BadSingleton/pyside2,IronManMark20/pyside2,M4rtinK/pyside-android,gbaty/pyside2,RobinD42/pyside,qtproject/pyside-pyside
import unittest from PySide.QtCore import QObject, QState, QFinalState, SIGNAL, QCoreApplication, QTimer, QStateMachine, QSignalTransition, QVariant, QParallelAnimationGroup, QPropertyAnimation - class QStateMachineTest(unittest.TestCase): + from helper import UsesQCoreApplication + + class QStateMachineTest(UsesQCoreApplication): def cb(self, *args): self.assertEqual(self.machine.defaultAnimations(), [self.anim]) def testBasic(self): - app = QCoreApplication([]) - self.machine = QStateMachine() s1 = QState() s2 = QState() s3 = QFinalState() QObject.connect(self.machine, SIGNAL("started()"), self.cb) self.anim = QParallelAnimationGroup() self.machine.addState(s1) self.machine.addState(s2) self.machine.addState(s3) self.machine.setInitialState(s1) self.machine.addDefaultAnimation(self.anim) self.machine.start() - QTimer.singleShot(100, app.quit) + QTimer.singleShot(100, self.app.quit) - app.exec_() + self.app.exec_() if __name__ == '__main__': unittest.main()
Add UsesQCoreApplication in state machine test
## Code Before: import unittest from PySide.QtCore import QObject, QState, QFinalState, SIGNAL, QCoreApplication, QTimer, QStateMachine, QSignalTransition, QVariant, QParallelAnimationGroup, QPropertyAnimation class QStateMachineTest(unittest.TestCase): def cb(self, *args): self.assertEqual(self.machine.defaultAnimations(), [self.anim]) def testBasic(self): app = QCoreApplication([]) self.machine = QStateMachine() s1 = QState() s2 = QState() s3 = QFinalState() QObject.connect(self.machine, SIGNAL("started()"), self.cb) self.anim = QParallelAnimationGroup() self.machine.addState(s1) self.machine.addState(s2) self.machine.addState(s3) self.machine.setInitialState(s1) self.machine.addDefaultAnimation(self.anim) self.machine.start() QTimer.singleShot(100, app.quit) app.exec_() if __name__ == '__main__': unittest.main() ## Instruction: Add UsesQCoreApplication in state machine test ## Code After: import unittest from PySide.QtCore import QObject, QState, QFinalState, SIGNAL, QCoreApplication, QTimer, QStateMachine, QSignalTransition, QVariant, QParallelAnimationGroup, QPropertyAnimation from helper import UsesQCoreApplication class QStateMachineTest(UsesQCoreApplication): def cb(self, *args): self.assertEqual(self.machine.defaultAnimations(), [self.anim]) def testBasic(self): self.machine = QStateMachine() s1 = QState() s2 = QState() s3 = QFinalState() QObject.connect(self.machine, SIGNAL("started()"), self.cb) self.anim = QParallelAnimationGroup() self.machine.addState(s1) self.machine.addState(s2) self.machine.addState(s3) self.machine.setInitialState(s1) self.machine.addDefaultAnimation(self.anim) self.machine.start() QTimer.singleShot(100, self.app.quit) self.app.exec_() if __name__ == '__main__': unittest.main()
5eefa21699f2dc7b75a919b5899a25ec7ef5c5b7
tests/unit/test_adapter_session.py
tests/unit/test_adapter_session.py
import pytest from wagtail_personalisation import adapters from tests.factories.segment import SegmentFactory @pytest.mark.django_db def test_get_segments(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) assert len(request.session['segments']) == 2 segments = adapter.get_segments() assert segments == [segment_1, segment_2] @pytest.mark.django_db def test_get_segment_by_id(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) segment_x = adapter.get_segment_by_id(segment_2.pk) assert segment_x == segment_2
import pytest from wagtail_personalisation import adapters from tests.factories.segment import SegmentFactory @pytest.mark.django_db def test_get_segments(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) assert len(request.session['segments']) == 2 segments = adapter.get_segments() assert segments == [segment_1, segment_2] @pytest.mark.django_db def test_get_segment_by_id(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) segment_x = adapter.get_segment_by_id(segment_2.pk) assert segment_x == segment_2 @pytest.mark.django_db def test_refresh_removes_disabled(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) adapter = adapters.SessionSegmentsAdapter(request) segment_1.status = segment_1.STATUS_DISABLED segment_1.save() adapter.refresh() assert adapter.get_segments() == [segment_2]
Add test for sessionadapter.refresh when segment is disable
Add test for sessionadapter.refresh when segment is disable
Python
mit
LabD/wagtail-personalisation,LabD/wagtail-personalisation,LabD/wagtail-personalisation
import pytest from wagtail_personalisation import adapters from tests.factories.segment import SegmentFactory @pytest.mark.django_db def test_get_segments(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) assert len(request.session['segments']) == 2 segments = adapter.get_segments() assert segments == [segment_1, segment_2] @pytest.mark.django_db def test_get_segment_by_id(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) segment_x = adapter.get_segment_by_id(segment_2.pk) assert segment_x == segment_2 + + @pytest.mark.django_db + def test_refresh_removes_disabled(rf, monkeypatch): + request = rf.get('/') + + adapter = adapters.SessionSegmentsAdapter(request) + + segment_1 = SegmentFactory(name='segment-1', persistent=True) + segment_2 = SegmentFactory(name='segment-2', persistent=True) + + adapter.set_segments([segment_1, segment_2]) + + adapter = adapters.SessionSegmentsAdapter(request) + segment_1.status = segment_1.STATUS_DISABLED + segment_1.save() + adapter.refresh() + + assert adapter.get_segments() == [segment_2] +
Add test for sessionadapter.refresh when segment is disable
## Code Before: import pytest from wagtail_personalisation import adapters from tests.factories.segment import SegmentFactory @pytest.mark.django_db def test_get_segments(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) assert len(request.session['segments']) == 2 segments = adapter.get_segments() assert segments == [segment_1, segment_2] @pytest.mark.django_db def test_get_segment_by_id(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) segment_x = adapter.get_segment_by_id(segment_2.pk) assert segment_x == segment_2 ## Instruction: Add test for sessionadapter.refresh when segment is disable ## Code After: import pytest from wagtail_personalisation import adapters from tests.factories.segment import SegmentFactory @pytest.mark.django_db def test_get_segments(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) assert len(request.session['segments']) == 2 segments = adapter.get_segments() assert segments == [segment_1, segment_2] @pytest.mark.django_db def test_get_segment_by_id(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) segment_x = adapter.get_segment_by_id(segment_2.pk) assert segment_x == segment_2 @pytest.mark.django_db def test_refresh_removes_disabled(rf, monkeypatch): request = rf.get('/') adapter = adapters.SessionSegmentsAdapter(request) segment_1 = SegmentFactory(name='segment-1', persistent=True) segment_2 = SegmentFactory(name='segment-2', persistent=True) adapter.set_segments([segment_1, segment_2]) adapter = adapters.SessionSegmentsAdapter(request) segment_1.status = segment_1.STATUS_DISABLED segment_1.save() adapter.refresh() assert adapter.get_segments() == [segment_2]
5fb365333711f7e999f71d53061ae14c386e575c
src/waldur_core/core/api_groups_mapping.py
src/waldur_core/core/api_groups_mapping.py
API_GROUPS = { 'authentication': ['/api-auth/', '/api/auth-valimo/',], 'user': ['/api/users/', '/api/user-invitations/', '/api/user-counters/',], 'organization': [ '/api/customers/', '/api/customer-permissions-log/', '/api/customer-permissions-reviews/', '/api/customer-permissions/', ], 'marketplace': [ '/api/marketplace-bookings/', '/api/marketplace-cart-items/', '/api/marketplace-categories/', '/api/marketplace-category-component-usages/', '/api/marketplace-checklists-categories/', '/api/marketplace-checklists/', '/api/marketplace-component-usages/', '/api/marketplace-offering-files/', '/api/marketplace-offerings/', '/api/marketplace-order-items/', '/api/marketplace-orders/', '/api/marketplace-plans/', '/api/marketplace-plugins/', '/api/marketplace-public-api/', '/api/marketplace-resource-offerings/', '/api/marketplace-resources/', '/api/marketplace-screenshots/', '/api/marketplace-service-providers/', ], 'reporting': [ '/api/support-feedback-average-report/', '/api/support-feedback-report/', ], }
API_GROUPS = { 'authentication': ['/api-auth/', '/api/auth-valimo/',], 'user': ['/api/users/', '/api/user-invitations/', '/api/user-counters/',], 'organization': [ '/api/customers/', '/api/customer-permissions-log/', '/api/customer-permissions-reviews/', '/api/customer-permissions/', ], 'marketplace': [ '/api/marketplace-bookings/', '/api/marketplace-cart-items/', '/api/marketplace-categories/', '/api/marketplace-category-component-usages/', '/api/marketplace-checklists-categories/', '/api/marketplace-checklists/', '/api/marketplace-component-usages/', '/api/marketplace-offering-files/', '/api/marketplace-offerings/', '/api/marketplace-order-items/', '/api/marketplace-orders/', '/api/marketplace-plans/', '/api/marketplace-plugins/', '/api/marketplace-public-api/', '/api/marketplace-resource-offerings/', '/api/marketplace-resources/', '/api/marketplace-screenshots/', '/api/marketplace-service-providers/', ], 'reporting': [ '/api/support-feedback-average-report/', '/api/support-feedback-report/', ], 'accounting': ['/api/invoices/', '/api/invoice-items/',], }
Add accounting group to apidocs
Add accounting group to apidocs
Python
mit
opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind
API_GROUPS = { 'authentication': ['/api-auth/', '/api/auth-valimo/',], 'user': ['/api/users/', '/api/user-invitations/', '/api/user-counters/',], 'organization': [ '/api/customers/', '/api/customer-permissions-log/', '/api/customer-permissions-reviews/', '/api/customer-permissions/', ], 'marketplace': [ '/api/marketplace-bookings/', '/api/marketplace-cart-items/', '/api/marketplace-categories/', '/api/marketplace-category-component-usages/', '/api/marketplace-checklists-categories/', '/api/marketplace-checklists/', '/api/marketplace-component-usages/', '/api/marketplace-offering-files/', '/api/marketplace-offerings/', '/api/marketplace-order-items/', '/api/marketplace-orders/', '/api/marketplace-plans/', '/api/marketplace-plugins/', '/api/marketplace-public-api/', '/api/marketplace-resource-offerings/', '/api/marketplace-resources/', '/api/marketplace-screenshots/', '/api/marketplace-service-providers/', ], 'reporting': [ '/api/support-feedback-average-report/', '/api/support-feedback-report/', ], + 'accounting': ['/api/invoices/', '/api/invoice-items/',], }
Add accounting group to apidocs
## Code Before: API_GROUPS = { 'authentication': ['/api-auth/', '/api/auth-valimo/',], 'user': ['/api/users/', '/api/user-invitations/', '/api/user-counters/',], 'organization': [ '/api/customers/', '/api/customer-permissions-log/', '/api/customer-permissions-reviews/', '/api/customer-permissions/', ], 'marketplace': [ '/api/marketplace-bookings/', '/api/marketplace-cart-items/', '/api/marketplace-categories/', '/api/marketplace-category-component-usages/', '/api/marketplace-checklists-categories/', '/api/marketplace-checklists/', '/api/marketplace-component-usages/', '/api/marketplace-offering-files/', '/api/marketplace-offerings/', '/api/marketplace-order-items/', '/api/marketplace-orders/', '/api/marketplace-plans/', '/api/marketplace-plugins/', '/api/marketplace-public-api/', '/api/marketplace-resource-offerings/', '/api/marketplace-resources/', '/api/marketplace-screenshots/', '/api/marketplace-service-providers/', ], 'reporting': [ '/api/support-feedback-average-report/', '/api/support-feedback-report/', ], } ## Instruction: Add accounting group to apidocs ## Code After: API_GROUPS = { 'authentication': ['/api-auth/', '/api/auth-valimo/',], 'user': ['/api/users/', '/api/user-invitations/', '/api/user-counters/',], 'organization': [ '/api/customers/', '/api/customer-permissions-log/', '/api/customer-permissions-reviews/', '/api/customer-permissions/', ], 'marketplace': [ '/api/marketplace-bookings/', '/api/marketplace-cart-items/', '/api/marketplace-categories/', '/api/marketplace-category-component-usages/', '/api/marketplace-checklists-categories/', '/api/marketplace-checklists/', '/api/marketplace-component-usages/', '/api/marketplace-offering-files/', '/api/marketplace-offerings/', '/api/marketplace-order-items/', '/api/marketplace-orders/', '/api/marketplace-plans/', '/api/marketplace-plugins/', '/api/marketplace-public-api/', '/api/marketplace-resource-offerings/', '/api/marketplace-resources/', '/api/marketplace-screenshots/', '/api/marketplace-service-providers/', ], 'reporting': [ '/api/support-feedback-average-report/', '/api/support-feedback-report/', ], 'accounting': ['/api/invoices/', '/api/invoice-items/',], }
a5cd2110283ba699f36548c42b83aa86e6b50aab
configuration.py
configuration.py
from trytond.model import fields, ModelSingleton, ModelSQL, ModelView __all__ = ['EndiciaConfiguration'] class EndiciaConfiguration(ModelSingleton, ModelSQL, ModelView): """ Configuration settings for Endicia. """ __name__ = 'endicia.configuration' account_id = fields.Integer('Account Id') requester_id = fields.Char('Requester Id') passphrase = fields.Char('Passphrase') is_test = fields.Boolean('Is Test') @classmethod def __setup__(cls): super(EndiciaConfiguration, cls).__setup__() cls._error_messages.update({ 'endicia_credentials_required': 'Endicia settings on endicia configuration are incomplete.', }) def get_endicia_credentials(self): """Validate if endicia credentials are complete. """ if not all([ self.account_id, self.requester_id, self.passphrase ]): self.raise_user_error('endicia_credentials_required') return self
from trytond import backend from trytond.model import fields, ModelSingleton, ModelSQL, ModelView from trytond.transaction import Transaction __all__ = ['EndiciaConfiguration'] class EndiciaConfiguration(ModelSingleton, ModelSQL, ModelView): """ Configuration settings for Endicia. """ __name__ = 'endicia.configuration' account_id = fields.Char('Account Id') requester_id = fields.Char('Requester Id') passphrase = fields.Char('Passphrase') is_test = fields.Boolean('Is Test') @classmethod def __setup__(cls): super(EndiciaConfiguration, cls).__setup__() cls._error_messages.update({ 'endicia_credentials_required': 'Endicia settings on endicia configuration are incomplete.', }) @classmethod def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().cursor # Migration from 3.4.0.6 : Migrate account_id field to string if backend.name() == 'postgresql': cursor.execute( 'SELECT pg_typeof("account_id") ' 'FROM endicia_configuration ' 'LIMIT 1', ) # Check if account_id is integer field is_integer = cursor.fetchone()[0] == 'integer' if is_integer: # Migrate integer field to string table = TableHandler(cursor, cls, module_name) table.alter_type('account_id', 'varchar') super(EndiciaConfiguration, cls).__register__(module_name) def get_endicia_credentials(self): """Validate if endicia credentials are complete. """ if not all([ self.account_id, self.requester_id, self.passphrase ]): self.raise_user_error('endicia_credentials_required') return self
Migrate account_id from integer field to char field
Migrate account_id from integer field to char field
Python
bsd-3-clause
priyankarani/trytond-shipping-endicia,fulfilio/trytond-shipping-endicia,prakashpp/trytond-shipping-endicia
+ from trytond import backend from trytond.model import fields, ModelSingleton, ModelSQL, ModelView + from trytond.transaction import Transaction __all__ = ['EndiciaConfiguration'] class EndiciaConfiguration(ModelSingleton, ModelSQL, ModelView): """ Configuration settings for Endicia. """ __name__ = 'endicia.configuration' - account_id = fields.Integer('Account Id') + account_id = fields.Char('Account Id') requester_id = fields.Char('Requester Id') passphrase = fields.Char('Passphrase') is_test = fields.Boolean('Is Test') @classmethod def __setup__(cls): super(EndiciaConfiguration, cls).__setup__() cls._error_messages.update({ 'endicia_credentials_required': 'Endicia settings on endicia configuration are incomplete.', }) + + @classmethod + def __register__(cls, module_name): + TableHandler = backend.get('TableHandler') + cursor = Transaction().cursor + + # Migration from 3.4.0.6 : Migrate account_id field to string + if backend.name() == 'postgresql': + cursor.execute( + 'SELECT pg_typeof("account_id") ' + 'FROM endicia_configuration ' + 'LIMIT 1', + ) + + # Check if account_id is integer field + is_integer = cursor.fetchone()[0] == 'integer' + + if is_integer: + # Migrate integer field to string + table = TableHandler(cursor, cls, module_name) + table.alter_type('account_id', 'varchar') + + super(EndiciaConfiguration, cls).__register__(module_name) def get_endicia_credentials(self): """Validate if endicia credentials are complete. """ if not all([ self.account_id, self.requester_id, self.passphrase ]): self.raise_user_error('endicia_credentials_required') return self
Migrate account_id from integer field to char field
## Code Before: from trytond.model import fields, ModelSingleton, ModelSQL, ModelView __all__ = ['EndiciaConfiguration'] class EndiciaConfiguration(ModelSingleton, ModelSQL, ModelView): """ Configuration settings for Endicia. """ __name__ = 'endicia.configuration' account_id = fields.Integer('Account Id') requester_id = fields.Char('Requester Id') passphrase = fields.Char('Passphrase') is_test = fields.Boolean('Is Test') @classmethod def __setup__(cls): super(EndiciaConfiguration, cls).__setup__() cls._error_messages.update({ 'endicia_credentials_required': 'Endicia settings on endicia configuration are incomplete.', }) def get_endicia_credentials(self): """Validate if endicia credentials are complete. """ if not all([ self.account_id, self.requester_id, self.passphrase ]): self.raise_user_error('endicia_credentials_required') return self ## Instruction: Migrate account_id from integer field to char field ## Code After: from trytond import backend from trytond.model import fields, ModelSingleton, ModelSQL, ModelView from trytond.transaction import Transaction __all__ = ['EndiciaConfiguration'] class EndiciaConfiguration(ModelSingleton, ModelSQL, ModelView): """ Configuration settings for Endicia. """ __name__ = 'endicia.configuration' account_id = fields.Char('Account Id') requester_id = fields.Char('Requester Id') passphrase = fields.Char('Passphrase') is_test = fields.Boolean('Is Test') @classmethod def __setup__(cls): super(EndiciaConfiguration, cls).__setup__() cls._error_messages.update({ 'endicia_credentials_required': 'Endicia settings on endicia configuration are incomplete.', }) @classmethod def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().cursor # Migration from 3.4.0.6 : Migrate account_id field to string if backend.name() == 'postgresql': cursor.execute( 'SELECT pg_typeof("account_id") ' 'FROM endicia_configuration ' 'LIMIT 1', ) # Check if account_id is integer field is_integer = cursor.fetchone()[0] == 'integer' if is_integer: # Migrate integer field to string table = TableHandler(cursor, cls, module_name) table.alter_type('account_id', 'varchar') super(EndiciaConfiguration, cls).__register__(module_name) def get_endicia_credentials(self): """Validate if endicia credentials are complete. """ if not all([ self.account_id, self.requester_id, self.passphrase ]): self.raise_user_error('endicia_credentials_required') return self
819f36493e1e0112c3bbe4f92f87f1771cc4af3f
moa/base.py
moa/base.py
''' * when dispatching events, returning True stops it. ''' from weakref import ref from kivy.event import EventDispatcher from kivy.properties import StringProperty, OptionProperty, ObjectProperty import logging class MoaException(Exception): pass class MoaBase(EventDispatcher): named_moas = {} ''' A weakref.ref to the named moa instances. Read only. ''' _last_name = '' def __init__(self, **kwargs): super(MoaBase, self).__init__(**kwargs) def verfiy_name(instance, value): named_moas = MoaBase.named_moas old_name = self._last_name if value == old_name: return if old_name: del named_moas[old_name] if value: if value in named_moas and named_moas[value]() is not None: raise ValueError('Moa instance with name {} already ' 'exists: {}'.format(value, named_moas[value]())) else: named_moas[value] = ref(self) self._last_name = value self.bind(name=verfiy_name) verfiy_name(self, self.name) name = StringProperty('') ''' Unique name across all Moa objects ''' logger = ObjectProperty(logging.getLogger('moa'), baseclass=logging.Logger) source = StringProperty('') ''' E.g. a filename to load that interpreted by the subclass. '''
''' * when dispatching events, returning True stops it. ''' __all__ = ('MoaBase', ) from weakref import ref from kivy.event import EventDispatcher from kivy.properties import StringProperty, OptionProperty, ObjectProperty import logging class MoaBase(EventDispatcher): named_moas = {} ''' A weakref.ref to the named moa instances. Read only. ''' _last_name = '' def __init__(self, **kwargs): super(MoaBase, self).__init__(**kwargs) def verfiy_name(instance, value): named_moas = MoaBase.named_moas old_name = self._last_name if value == old_name: return if old_name: del named_moas[old_name] if value: if value in named_moas and named_moas[value]() is not None: raise ValueError('Moa instance with name {} already ' 'exists: {}'.format(value, named_moas[value]())) else: named_moas[value] = ref(self) self._last_name = value self.bind(name=verfiy_name) verfiy_name(self, self.name) name = StringProperty('') ''' Unique name across all Moa objects ''' logger = ObjectProperty(logging.getLogger('moa'), baseclass=logging.Logger) source = StringProperty('') ''' E.g. a filename to load that interpreted by the subclass. '''
Remove unused moa exception class.
Remove unused moa exception class.
Python
mit
matham/moa
''' * when dispatching events, returning True stops it. ''' + + __all__ = ('MoaBase', ) from weakref import ref from kivy.event import EventDispatcher from kivy.properties import StringProperty, OptionProperty, ObjectProperty import logging - - - class MoaException(Exception): - pass class MoaBase(EventDispatcher): named_moas = {} ''' A weakref.ref to the named moa instances. Read only. ''' _last_name = '' def __init__(self, **kwargs): super(MoaBase, self).__init__(**kwargs) def verfiy_name(instance, value): named_moas = MoaBase.named_moas old_name = self._last_name if value == old_name: return if old_name: del named_moas[old_name] if value: if value in named_moas and named_moas[value]() is not None: raise ValueError('Moa instance with name {} already ' 'exists: {}'.format(value, named_moas[value]())) else: named_moas[value] = ref(self) self._last_name = value self.bind(name=verfiy_name) verfiy_name(self, self.name) name = StringProperty('') ''' Unique name across all Moa objects ''' logger = ObjectProperty(logging.getLogger('moa'), baseclass=logging.Logger) source = StringProperty('') ''' E.g. a filename to load that interpreted by the subclass. '''
Remove unused moa exception class.
## Code Before: ''' * when dispatching events, returning True stops it. ''' from weakref import ref from kivy.event import EventDispatcher from kivy.properties import StringProperty, OptionProperty, ObjectProperty import logging class MoaException(Exception): pass class MoaBase(EventDispatcher): named_moas = {} ''' A weakref.ref to the named moa instances. Read only. ''' _last_name = '' def __init__(self, **kwargs): super(MoaBase, self).__init__(**kwargs) def verfiy_name(instance, value): named_moas = MoaBase.named_moas old_name = self._last_name if value == old_name: return if old_name: del named_moas[old_name] if value: if value in named_moas and named_moas[value]() is not None: raise ValueError('Moa instance with name {} already ' 'exists: {}'.format(value, named_moas[value]())) else: named_moas[value] = ref(self) self._last_name = value self.bind(name=verfiy_name) verfiy_name(self, self.name) name = StringProperty('') ''' Unique name across all Moa objects ''' logger = ObjectProperty(logging.getLogger('moa'), baseclass=logging.Logger) source = StringProperty('') ''' E.g. a filename to load that interpreted by the subclass. ''' ## Instruction: Remove unused moa exception class. ## Code After: ''' * when dispatching events, returning True stops it. ''' __all__ = ('MoaBase', ) from weakref import ref from kivy.event import EventDispatcher from kivy.properties import StringProperty, OptionProperty, ObjectProperty import logging class MoaBase(EventDispatcher): named_moas = {} ''' A weakref.ref to the named moa instances. Read only. ''' _last_name = '' def __init__(self, **kwargs): super(MoaBase, self).__init__(**kwargs) def verfiy_name(instance, value): named_moas = MoaBase.named_moas old_name = self._last_name if value == old_name: return if old_name: del named_moas[old_name] if value: if value in named_moas and named_moas[value]() is not None: raise ValueError('Moa instance with name {} already ' 'exists: {}'.format(value, named_moas[value]())) else: named_moas[value] = ref(self) self._last_name = value self.bind(name=verfiy_name) verfiy_name(self, self.name) name = StringProperty('') ''' Unique name across all Moa objects ''' logger = ObjectProperty(logging.getLogger('moa'), baseclass=logging.Logger) source = StringProperty('') ''' E.g. a filename to load that interpreted by the subclass. '''
5fb609b13cf65ef3c29502b9b406b73f03873ab0
pathfinder/tests/BugTracker/Tests/stream-document.SF-2804823.XQUERY.py
pathfinder/tests/BugTracker/Tests/stream-document.SF-2804823.XQUERY.py
import os, sys try: import sybprocess except ImportError: # user private copy for old Python versions import MonetDBtesting.subprocess26 as subprocess def client(cmd, input = None): clt = subprocess.Popen(cmd, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True) out, err = clt.communicate(input) sys.stdout.write(out) sys.stderr.write(err) def main(): xq_client = os.getenv('XQUERY_CLIENT') client('%s --input=my-document --collection=my-collection' % xq_client, '<document>test document</document>') client('%s -s "pf:documents()"' % xq_client) client('%s -s "pf:del-doc(\'my-document\')"' % xq_client) main()
import os, sys try: import sybprocess except ImportError: # user private copy for old Python versions import MonetDBtesting.subprocess26 as subprocess def client(cmd, input = None): clt = subprocess.Popen(cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True) out, err = clt.communicate(input) sys.stdout.write(out) sys.stderr.write(err) def main(): xq_client = os.getenv('XQUERY_CLIENT').split() client(xq_client + ['--input=my-document', '--collection=my-collection'], '<document>test document</document>') client(xq_client + ['-s', 'for $doc in pf:documents() where $doc/@url = "my-document" return $doc']) client(xq_client + ['-s', 'pf:del-doc("my-document")']) main()
Make test independent of whatever else is in the database. Also, use a different way of calling subprocess.Popen so that we can use quotes and dollars without having to do difficult cross-architectural escaping.
Make test independent of whatever else is in the database. Also, use a different way of calling subprocess.Popen so that we can use quotes and dollars without having to do difficult cross-architectural escaping.
Python
mpl-2.0
zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb
import os, sys try: import sybprocess except ImportError: # user private copy for old Python versions import MonetDBtesting.subprocess26 as subprocess def client(cmd, input = None): clt = subprocess.Popen(cmd, - shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True) out, err = clt.communicate(input) sys.stdout.write(out) sys.stderr.write(err) def main(): - xq_client = os.getenv('XQUERY_CLIENT') + xq_client = os.getenv('XQUERY_CLIENT').split() - client('%s --input=my-document --collection=my-collection' % xq_client, + client(xq_client + ['--input=my-document', '--collection=my-collection'], '<document>test document</document>') - client('%s -s "pf:documents()"' % xq_client) - client('%s -s "pf:del-doc(\'my-document\')"' % xq_client) + client(xq_client + ['-s', 'for $doc in pf:documents() where $doc/@url = "my-document" return $doc']) + client(xq_client + ['-s', 'pf:del-doc("my-document")']) main()
Make test independent of whatever else is in the database. Also, use a different way of calling subprocess.Popen so that we can use quotes and dollars without having to do difficult cross-architectural escaping.
## Code Before: import os, sys try: import sybprocess except ImportError: # user private copy for old Python versions import MonetDBtesting.subprocess26 as subprocess def client(cmd, input = None): clt = subprocess.Popen(cmd, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True) out, err = clt.communicate(input) sys.stdout.write(out) sys.stderr.write(err) def main(): xq_client = os.getenv('XQUERY_CLIENT') client('%s --input=my-document --collection=my-collection' % xq_client, '<document>test document</document>') client('%s -s "pf:documents()"' % xq_client) client('%s -s "pf:del-doc(\'my-document\')"' % xq_client) main() ## Instruction: Make test independent of whatever else is in the database. Also, use a different way of calling subprocess.Popen so that we can use quotes and dollars without having to do difficult cross-architectural escaping. ## Code After: import os, sys try: import sybprocess except ImportError: # user private copy for old Python versions import MonetDBtesting.subprocess26 as subprocess def client(cmd, input = None): clt = subprocess.Popen(cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True) out, err = clt.communicate(input) sys.stdout.write(out) sys.stderr.write(err) def main(): xq_client = os.getenv('XQUERY_CLIENT').split() client(xq_client + ['--input=my-document', '--collection=my-collection'], '<document>test document</document>') client(xq_client + ['-s', 'for $doc in pf:documents() where $doc/@url = "my-document" return $doc']) client(xq_client + ['-s', 'pf:del-doc("my-document")']) main()
65ecd11b4d4689108eabd464377afdb20ff95240
rest_framework_simplejwt/utils.py
rest_framework_simplejwt/utils.py
from __future__ import unicode_literals from calendar import timegm from datetime import datetime from django.conf import settings from django.utils import six from django.utils.functional import lazy from django.utils.timezone import is_aware, make_aware, utc def make_utc(dt): if settings.USE_TZ and not is_aware(dt): return make_aware(dt, timezone=utc) return dt def aware_utcnow(): return make_utc(datetime.utcnow()) def datetime_to_epoch(dt): return timegm(dt.utctimetuple()) def datetime_from_epoch(ts): return make_utc(datetime.utcfromtimestamp(ts)) def format_lazy(s, *args, **kwargs): return s.format(*args, **kwargs) format_lazy = lazy(format_lazy, six.text_type)
from __future__ import unicode_literals from calendar import timegm from datetime import datetime from django.conf import settings from django.utils import six from django.utils.functional import lazy from django.utils.timezone import is_naive, make_aware, utc def make_utc(dt): if settings.USE_TZ and is_naive(dt): return make_aware(dt, timezone=utc) return dt def aware_utcnow(): return make_utc(datetime.utcnow()) def datetime_to_epoch(dt): return timegm(dt.utctimetuple()) def datetime_from_epoch(ts): return make_utc(datetime.utcfromtimestamp(ts)) def format_lazy(s, *args, **kwargs): return s.format(*args, **kwargs) format_lazy = lazy(format_lazy, six.text_type)
Use is_naive here for clarity
Use is_naive here for clarity
Python
mit
davesque/django-rest-framework-simplejwt,davesque/django-rest-framework-simplejwt
from __future__ import unicode_literals from calendar import timegm from datetime import datetime from django.conf import settings from django.utils import six from django.utils.functional import lazy - from django.utils.timezone import is_aware, make_aware, utc + from django.utils.timezone import is_naive, make_aware, utc def make_utc(dt): - if settings.USE_TZ and not is_aware(dt): + if settings.USE_TZ and is_naive(dt): return make_aware(dt, timezone=utc) return dt def aware_utcnow(): return make_utc(datetime.utcnow()) def datetime_to_epoch(dt): return timegm(dt.utctimetuple()) def datetime_from_epoch(ts): return make_utc(datetime.utcfromtimestamp(ts)) def format_lazy(s, *args, **kwargs): return s.format(*args, **kwargs) format_lazy = lazy(format_lazy, six.text_type)
Use is_naive here for clarity
## Code Before: from __future__ import unicode_literals from calendar import timegm from datetime import datetime from django.conf import settings from django.utils import six from django.utils.functional import lazy from django.utils.timezone import is_aware, make_aware, utc def make_utc(dt): if settings.USE_TZ and not is_aware(dt): return make_aware(dt, timezone=utc) return dt def aware_utcnow(): return make_utc(datetime.utcnow()) def datetime_to_epoch(dt): return timegm(dt.utctimetuple()) def datetime_from_epoch(ts): return make_utc(datetime.utcfromtimestamp(ts)) def format_lazy(s, *args, **kwargs): return s.format(*args, **kwargs) format_lazy = lazy(format_lazy, six.text_type) ## Instruction: Use is_naive here for clarity ## Code After: from __future__ import unicode_literals from calendar import timegm from datetime import datetime from django.conf import settings from django.utils import six from django.utils.functional import lazy from django.utils.timezone import is_naive, make_aware, utc def make_utc(dt): if settings.USE_TZ and is_naive(dt): return make_aware(dt, timezone=utc) return dt def aware_utcnow(): return make_utc(datetime.utcnow()) def datetime_to_epoch(dt): return timegm(dt.utctimetuple()) def datetime_from_epoch(ts): return make_utc(datetime.utcfromtimestamp(ts)) def format_lazy(s, *args, **kwargs): return s.format(*args, **kwargs) format_lazy = lazy(format_lazy, six.text_type)
eb33d70bfda4857fbd76616cf3bf7fb7d7feec71
spoj/00005/palin.py
spoj/00005/palin.py
def next_palindrome(k): palin = list(k) n = len(k) mid = n // 2 # case 1: forward right just_copy = False for i in range(mid, n): mirrored = n - 1 - i if k[i] < k[mirrored]: just_copy = True if just_copy: palin[i] = palin[mirrored] # case 2: backward left if not just_copy: i = (n - 1) // 2 while i >= 0 and k[i] == '9': i -= 1 if i >= 0: palin[i] = str(int(k[i]) + 1) for j in range(i + 1, mid): palin[j] = '0' for j in range(mid, n): mirrored = n - 1 - j palin[j] = palin[mirrored] else: # case 3: "99...9" -> "100..01" palin = ['0'] * (n + 1) palin[0] = palin[-1] = '1' return ''.join(palin) if __name__ == '__main__': t = int(input()) for _ in range(t): k = input() print(next_palindrome(k))
def next_palindrome(k): palin = list(k) n = len(k) mid = n // 2 # case 1: forward right just_copy = False for i in range(mid, n): mirrored = n - 1 - i if k[i] < k[mirrored]: just_copy = True if just_copy: palin[i] = palin[mirrored] # case 2: backward left if not just_copy: i = (n - 1) // 2 while i >= 0 and k[i] == '9': i -= 1 if i >= 0: palin[i] = str(int(k[i]) + 1) for j in range(i + 1, (n + 1) // 2): palin[j] = '0' for j in range((n + 1) // 2, n): mirrored = n - 1 - j palin[j] = palin[mirrored] else: # case 3: "99...9" -> "100..01" palin = ['0'] * (n + 1) palin[0] = palin[-1] = '1' return ''.join(palin) if __name__ == '__main__': t = int(input()) for _ in range(t): k = input() print(next_palindrome(k))
Fix bug in ranges (to middle)
Fix bug in ranges (to middle) - in SPOJ palin Signed-off-by: Karel Ha <70f8965fdfb04f1fc0e708a55d9e822c449f57d3@gmail.com>
Python
mit
mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming
def next_palindrome(k): palin = list(k) n = len(k) mid = n // 2 # case 1: forward right just_copy = False for i in range(mid, n): mirrored = n - 1 - i if k[i] < k[mirrored]: just_copy = True if just_copy: palin[i] = palin[mirrored] # case 2: backward left if not just_copy: i = (n - 1) // 2 while i >= 0 and k[i] == '9': i -= 1 if i >= 0: palin[i] = str(int(k[i]) + 1) - for j in range(i + 1, mid): + for j in range(i + 1, (n + 1) // 2): palin[j] = '0' - for j in range(mid, n): + for j in range((n + 1) // 2, n): mirrored = n - 1 - j palin[j] = palin[mirrored] else: # case 3: "99...9" -> "100..01" palin = ['0'] * (n + 1) palin[0] = palin[-1] = '1' return ''.join(palin) if __name__ == '__main__': t = int(input()) for _ in range(t): k = input() print(next_palindrome(k))
Fix bug in ranges (to middle)
## Code Before: def next_palindrome(k): palin = list(k) n = len(k) mid = n // 2 # case 1: forward right just_copy = False for i in range(mid, n): mirrored = n - 1 - i if k[i] < k[mirrored]: just_copy = True if just_copy: palin[i] = palin[mirrored] # case 2: backward left if not just_copy: i = (n - 1) // 2 while i >= 0 and k[i] == '9': i -= 1 if i >= 0: palin[i] = str(int(k[i]) + 1) for j in range(i + 1, mid): palin[j] = '0' for j in range(mid, n): mirrored = n - 1 - j palin[j] = palin[mirrored] else: # case 3: "99...9" -> "100..01" palin = ['0'] * (n + 1) palin[0] = palin[-1] = '1' return ''.join(palin) if __name__ == '__main__': t = int(input()) for _ in range(t): k = input() print(next_palindrome(k)) ## Instruction: Fix bug in ranges (to middle) ## Code After: def next_palindrome(k): palin = list(k) n = len(k) mid = n // 2 # case 1: forward right just_copy = False for i in range(mid, n): mirrored = n - 1 - i if k[i] < k[mirrored]: just_copy = True if just_copy: palin[i] = palin[mirrored] # case 2: backward left if not just_copy: i = (n - 1) // 2 while i >= 0 and k[i] == '9': i -= 1 if i >= 0: palin[i] = str(int(k[i]) + 1) for j in range(i + 1, (n + 1) // 2): palin[j] = '0' for j in range((n + 1) // 2, n): mirrored = n - 1 - j palin[j] = palin[mirrored] else: # case 3: "99...9" -> "100..01" palin = ['0'] * (n + 1) palin[0] = palin[-1] = '1' return ''.join(palin) if __name__ == '__main__': t = int(input()) for _ in range(t): k = input() print(next_palindrome(k))
e43596395507c4606909087c0e77e84c1a232811
damn/__init__.py
damn/__init__.py
__version__ = '0.0.0'
__author__ = 'Romain Clement' __copyright__ = 'Copyright 2014, Romain Clement' __credits__ = [] __license__ = 'MIT' __version__ = "0.0.0" __maintainer__ = 'Romain Clement' __email__ = 'contact@romainclement.com' __status__ = 'Development'
Add meta information for damn package
[DEV] Add meta information for damn package
Python
mit
rclement/yodel,rclement/yodel
+ __author__ = 'Romain Clement' + __copyright__ = 'Copyright 2014, Romain Clement' + __credits__ = [] + __license__ = 'MIT' - __version__ = '0.0.0' + __version__ = "0.0.0" + __maintainer__ = 'Romain Clement' + __email__ = 'contact@romainclement.com' + __status__ = 'Development'
Add meta information for damn package
## Code Before: __version__ = '0.0.0' ## Instruction: Add meta information for damn package ## Code After: __author__ = 'Romain Clement' __copyright__ = 'Copyright 2014, Romain Clement' __credits__ = [] __license__ = 'MIT' __version__ = "0.0.0" __maintainer__ = 'Romain Clement' __email__ = 'contact@romainclement.com' __status__ = 'Development'
49e95022577eb40bcf9e1d1c9f95be7269fd0e3b
scripts/update_acq_stats.py
scripts/update_acq_stats.py
from mica.stats import update_acq_stats update_acq_stats.main() import os table_file = mica.stats.acq_stats.table_file file_stat = os.stat(table_file) if file_stat.st_size > 50e6: print(""" Warning: {tfile} is larger than 50MB and may need Warning: to be manually repacked (i.e.): Warning: Warning: ptrepack --chunkshape=auto --propindexes --keep-source-filters {tfile} compressed.h5 Warning: cp compressed.h5 {tfile} """.format(tfile=table_file))
import os from mica.stats import update_acq_stats import mica.stats.acq_stats update_acq_stats.main() table_file = mica.stats.acq_stats.TABLE_FILE file_stat = os.stat(table_file) if file_stat.st_size > 50e6: print(""" Warning: {tfile} is larger than 50MB and may need Warning: to be manually repacked (i.e.): Warning: Warning: ptrepack --chunkshape=auto --propindexes --keep-source-filters {tfile} compressed.h5 Warning: cp compressed.h5 {tfile} """.format(tfile=table_file))
Fix reference to acq table file in script
Fix reference to acq table file in script
Python
bsd-3-clause
sot/mica,sot/mica
- + import os from mica.stats import update_acq_stats + import mica.stats.acq_stats update_acq_stats.main() - import os + - table_file = mica.stats.acq_stats.table_file + table_file = mica.stats.acq_stats.TABLE_FILE file_stat = os.stat(table_file) if file_stat.st_size > 50e6: print(""" Warning: {tfile} is larger than 50MB and may need Warning: to be manually repacked (i.e.): Warning: Warning: ptrepack --chunkshape=auto --propindexes --keep-source-filters {tfile} compressed.h5 Warning: cp compressed.h5 {tfile} """.format(tfile=table_file))
Fix reference to acq table file in script
## Code Before: from mica.stats import update_acq_stats update_acq_stats.main() import os table_file = mica.stats.acq_stats.table_file file_stat = os.stat(table_file) if file_stat.st_size > 50e6: print(""" Warning: {tfile} is larger than 50MB and may need Warning: to be manually repacked (i.e.): Warning: Warning: ptrepack --chunkshape=auto --propindexes --keep-source-filters {tfile} compressed.h5 Warning: cp compressed.h5 {tfile} """.format(tfile=table_file)) ## Instruction: Fix reference to acq table file in script ## Code After: import os from mica.stats import update_acq_stats import mica.stats.acq_stats update_acq_stats.main() table_file = mica.stats.acq_stats.TABLE_FILE file_stat = os.stat(table_file) if file_stat.st_size > 50e6: print(""" Warning: {tfile} is larger than 50MB and may need Warning: to be manually repacked (i.e.): Warning: Warning: ptrepack --chunkshape=auto --propindexes --keep-source-filters {tfile} compressed.h5 Warning: cp compressed.h5 {tfile} """.format(tfile=table_file))
8a6144fc3918856cb2259f65f9ee5cc9cfaf1fdc
locustfile.py
locustfile.py
from locust import HttpLocust, TaskSet, task class UserBehavior(TaskSet): tasks = [] def on_start(self): pass @task def index(self): self.client.get("/") @task def move_map(self): self.client.get("") @task def select_scene(self): # Get url self.client.get() @task def render_preview(self): self.client.get() @task def render_full(self): self.client.get() class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait = 1000 max_wait = 5000
from locust import HttpLocust, TaskSet, task from bs4 import BeautifulSoup from requests import Session import random class UserBehavior(TaskSet): def on_start(self): pass @task def index(self): self.client.get("/") @task def move_map(self): lat = random.uniform(-1, 1) lon = random.uniform(-1, 1) response = self.client.post( url="/ajax", data={'lat': lat, 'lng': lng,} ) self.client.get("") @task def select_scene(self): # Get url soup = BeautifulSoup(self.client.get("")) self.client.get() @task def render_preview(self): self.client.get() @task def render_full(self): self.client.get() class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait = 1000 max_wait = 5000
Add random functionality to map move.
Add random functionality to map move.
Python
mit
recombinators/snapsat,recombinators/snapsat,recombinators/snapsat
from locust import HttpLocust, TaskSet, task + from bs4 import BeautifulSoup + from requests import Session + import random class UserBehavior(TaskSet): - tasks = [] - def on_start(self): pass @task def index(self): self.client.get("/") @task def move_map(self): + lat = random.uniform(-1, 1) + lon = random.uniform(-1, 1) + response = self.client.post( + url="/ajax", + data={'lat': lat, 'lng': lng,} + ) + self.client.get("") - @task + @task - def select_scene(self): + def select_scene(self): - # Get url + # Get url + soup = BeautifulSoup(self.client.get("")) - self.client.get() - - @task - def render_preview(self): self.client.get() - @task + @task + def render_preview(self): + self.client.get() + + @task - def render_full(self): + def render_full(self): - self.client.get() + self.client.get() class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait = 1000 max_wait = 5000
Add random functionality to map move.
## Code Before: from locust import HttpLocust, TaskSet, task class UserBehavior(TaskSet): tasks = [] def on_start(self): pass @task def index(self): self.client.get("/") @task def move_map(self): self.client.get("") @task def select_scene(self): # Get url self.client.get() @task def render_preview(self): self.client.get() @task def render_full(self): self.client.get() class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait = 1000 max_wait = 5000 ## Instruction: Add random functionality to map move. ## Code After: from locust import HttpLocust, TaskSet, task from bs4 import BeautifulSoup from requests import Session import random class UserBehavior(TaskSet): def on_start(self): pass @task def index(self): self.client.get("/") @task def move_map(self): lat = random.uniform(-1, 1) lon = random.uniform(-1, 1) response = self.client.post( url="/ajax", data={'lat': lat, 'lng': lng,} ) self.client.get("") @task def select_scene(self): # Get url soup = BeautifulSoup(self.client.get("")) self.client.get() @task def render_preview(self): self.client.get() @task def render_full(self): self.client.get() class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait = 1000 max_wait = 5000
3b41e2166adde50f36f8f7ea389c80b76b83acaf
test/test_wavedrom.py
test/test_wavedrom.py
import subprocess from utils import * @all_files_in_dir('wavedrom_0') def test_wavedrom_0(datafiles): with datafiles.as_cwd(): subprocess.check_call(['python3', 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') def test_wavedrom_1(datafiles): with datafiles.as_cwd(): for s in get_simulators(): subprocess.check_call(['runSVUnit', '-s', s, '-w']) expect_testrunner_pass('run.log')
import subprocess from utils import * @all_files_in_dir('wavedrom_0') def test_wavedrom_0(datafiles): with datafiles.as_cwd(): subprocess.check_call(['python3', 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') @all_available_simulators() def test_wavedrom_1(datafiles, simulator): with datafiles.as_cwd(): subprocess.check_call(['runSVUnit', '-s', simulator, '-w']) expect_testrunner_pass('run.log')
Update wavedrom tests to get simulators via fixture
Update wavedrom tests to get simulators via fixture
Python
apache-2.0
nosnhojn/svunit-code,svunit/svunit,nosnhojn/svunit-code,svunit/svunit,svunit/svunit,nosnhojn/svunit-code
import subprocess from utils import * @all_files_in_dir('wavedrom_0') def test_wavedrom_0(datafiles): with datafiles.as_cwd(): subprocess.check_call(['python3', 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') + @all_available_simulators() - def test_wavedrom_1(datafiles): + def test_wavedrom_1(datafiles, simulator): with datafiles.as_cwd(): - for s in get_simulators(): - subprocess.check_call(['runSVUnit', '-s', s, '-w']) + subprocess.check_call(['runSVUnit', '-s', simulator, '-w']) - expect_testrunner_pass('run.log') + expect_testrunner_pass('run.log')
Update wavedrom tests to get simulators via fixture
## Code Before: import subprocess from utils import * @all_files_in_dir('wavedrom_0') def test_wavedrom_0(datafiles): with datafiles.as_cwd(): subprocess.check_call(['python3', 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') def test_wavedrom_1(datafiles): with datafiles.as_cwd(): for s in get_simulators(): subprocess.check_call(['runSVUnit', '-s', s, '-w']) expect_testrunner_pass('run.log') ## Instruction: Update wavedrom tests to get simulators via fixture ## Code After: import subprocess from utils import * @all_files_in_dir('wavedrom_0') def test_wavedrom_0(datafiles): with datafiles.as_cwd(): subprocess.check_call(['python3', 'wavedrom-test.py']) @all_files_in_dir('wavedrom_1') @all_available_simulators() def test_wavedrom_1(datafiles, simulator): with datafiles.as_cwd(): subprocess.check_call(['runSVUnit', '-s', simulator, '-w']) expect_testrunner_pass('run.log')
362c8dacda35bac24aa83e4fcaa2f6bac37150fd
tests/test_mw_util.py
tests/test_mw_util.py
"""Unit tests for cat2cohort.""" import unittest from mw_util import str2cat class TestMWutil(unittest.TestCase): """Test methods from mw_util.""" pass
"""Unit tests for cat2cohort.""" import unittest from mw_util import str2cat class TestMWutil(unittest.TestCase): """Test methods from mw_util.""" def test_str2cat(self): """Test str2cat.""" values = [ ('A', 'Category:A'), ('Category:B', 'Category:B'), ] for value, expected in values: self.assertEqual(str2cat(value), expected)
Add unit test for str2cat method.
Add unit test for str2cat method.
Python
mit
Commonists/wm_metrics,danmichaelo/wm_metrics,Commonists/wm_metrics,Commonists/wm_metrics,danmichaelo/wm_metrics,danmichaelo/wm_metrics,danmichaelo/wm_metrics,Commonists/wm_metrics
"""Unit tests for cat2cohort.""" import unittest from mw_util import str2cat class TestMWutil(unittest.TestCase): """Test methods from mw_util.""" - pass + def test_str2cat(self): + """Test str2cat.""" + values = [ + ('A', 'Category:A'), + ('Category:B', 'Category:B'), + ] + for value, expected in values: + self.assertEqual(str2cat(value), expected)
Add unit test for str2cat method.
## Code Before: """Unit tests for cat2cohort.""" import unittest from mw_util import str2cat class TestMWutil(unittest.TestCase): """Test methods from mw_util.""" pass ## Instruction: Add unit test for str2cat method. ## Code After: """Unit tests for cat2cohort.""" import unittest from mw_util import str2cat class TestMWutil(unittest.TestCase): """Test methods from mw_util.""" def test_str2cat(self): """Test str2cat.""" values = [ ('A', 'Category:A'), ('Category:B', 'Category:B'), ] for value, expected in values: self.assertEqual(str2cat(value), expected)
ebf52caf6ee09ef1f15cb88815a1fb8008899c79
tests/test_reactjs.py
tests/test_reactjs.py
import dukpy class TestReactJS(object): def test_hello_world(self): jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;') jsi = dukpy.JSInterpreter() result = jsi.evaljs([ ''' var React = require('react/react'), ReactDOM = require('react/react-dom-server'); ''', jsx, 'ReactDOM.renderToStaticMarkup(react_hello, null);' ]) assert result == '<h1>Hello, world!</h1>'
import dukpy class TestReactJS(object): def test_hello_world(self): jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;') jsi = dukpy.JSInterpreter() result = jsi.evaljs([ ''' var React = require('react/react'), ReactDOM = require('react/react-dom-server'); ''', jsx, 'ReactDOM.renderToStaticMarkup(react_hello, null);' ]) assert result == '<h1>Hello, world!</h1>', res def test_jsx_mixed(self): code = ''' var React = require('react/react'), ReactDOM = require('react/react-dom-server'); ReactDOM.renderToStaticMarkup(<h1>Hello, world!</h1>, null); ''' jsx = dukpy.jsx_compile(code) res = dukpy.evaljs(jsx) assert res == '<h1>Hello, world!</h1>', res def test_react_binding(self): code = ''' var React = require('react/react'), ReactDOM = require('react/react-dom-server'); var HelloWorld = React.createClass({ render: function() { return ( <div className="helloworld"> Hello {this.props.data.name} </div> ); } }); ReactDOM.renderToStaticMarkup(<HelloWorld data={dukpy.data}/>, null); ''' jsx = dukpy.jsx_compile(code) res = dukpy.evaljs(jsx, data={'id': 1, 'name': "Alessandro"}) assert res == '<div class="helloworld">Hello Alessandro</div>', res
Add tests for a React Component
Add tests for a React Component
Python
mit
amol-/dukpy,amol-/dukpy,amol-/dukpy
import dukpy class TestReactJS(object): def test_hello_world(self): jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;') jsi = dukpy.JSInterpreter() result = jsi.evaljs([ ''' var React = require('react/react'), ReactDOM = require('react/react-dom-server'); ''', jsx, 'ReactDOM.renderToStaticMarkup(react_hello, null);' ]) - assert result == '<h1>Hello, world!</h1>' + assert result == '<h1>Hello, world!</h1>', res + def test_jsx_mixed(self): + code = ''' + var React = require('react/react'), + ReactDOM = require('react/react-dom-server'); + ReactDOM.renderToStaticMarkup(<h1>Hello, world!</h1>, null); + ''' + jsx = dukpy.jsx_compile(code) + res = dukpy.evaljs(jsx) + assert res == '<h1>Hello, world!</h1>', res + + def test_react_binding(self): + code = ''' + var React = require('react/react'), + ReactDOM = require('react/react-dom-server'); + + var HelloWorld = React.createClass({ + render: function() { + return ( + <div className="helloworld"> + Hello {this.props.data.name} + </div> + ); + } + }); + + ReactDOM.renderToStaticMarkup(<HelloWorld data={dukpy.data}/>, null); + ''' + jsx = dukpy.jsx_compile(code) + res = dukpy.evaljs(jsx, data={'id': 1, 'name': "Alessandro"}) + assert res == '<div class="helloworld">Hello Alessandro</div>', res
Add tests for a React Component
## Code Before: import dukpy class TestReactJS(object): def test_hello_world(self): jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;') jsi = dukpy.JSInterpreter() result = jsi.evaljs([ ''' var React = require('react/react'), ReactDOM = require('react/react-dom-server'); ''', jsx, 'ReactDOM.renderToStaticMarkup(react_hello, null);' ]) assert result == '<h1>Hello, world!</h1>' ## Instruction: Add tests for a React Component ## Code After: import dukpy class TestReactJS(object): def test_hello_world(self): jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;') jsi = dukpy.JSInterpreter() result = jsi.evaljs([ ''' var React = require('react/react'), ReactDOM = require('react/react-dom-server'); ''', jsx, 'ReactDOM.renderToStaticMarkup(react_hello, null);' ]) assert result == '<h1>Hello, world!</h1>', res def test_jsx_mixed(self): code = ''' var React = require('react/react'), ReactDOM = require('react/react-dom-server'); ReactDOM.renderToStaticMarkup(<h1>Hello, world!</h1>, null); ''' jsx = dukpy.jsx_compile(code) res = dukpy.evaljs(jsx) assert res == '<h1>Hello, world!</h1>', res def test_react_binding(self): code = ''' var React = require('react/react'), ReactDOM = require('react/react-dom-server'); var HelloWorld = React.createClass({ render: function() { return ( <div className="helloworld"> Hello {this.props.data.name} </div> ); } }); ReactDOM.renderToStaticMarkup(<HelloWorld data={dukpy.data}/>, null); ''' jsx = dukpy.jsx_compile(code) res = dukpy.evaljs(jsx, data={'id': 1, 'name': "Alessandro"}) assert res == '<div class="helloworld">Hello Alessandro</div>', res
2a32fc912a5839f627a216918e4671e6547ee53b
tests/utils/driver.py
tests/utils/driver.py
import os from importlib import import_module from .testdriver import TestDriver class Driver(TestDriver): drivers = {} def __new__(cls, type, *args, **kwargs): if type not in cls.drivers: try: mod = import_module('onitu.drivers.{}.tests.driver'. format(type)) except ImportError: raise KeyError("No such driver {}".format(repr(type))) cls.drivers[type] = mod.Driver return cls.drivers[type](*args, **kwargs) class LocalStorageDriver(TestDriver): def __new__(cls, *args, **kwargs): return Driver('local_storage', *args, **kwargs) class TargetDriver(Driver): def __new__(cls, *args, **kwargs): type = os.environ.get('ONITU_TEST_DRIVER', 'local_storage') return Driver(type, *args, **kwargs)
import os import pkg_resources from .testdriver import TestDriver class Driver(TestDriver): drivers = {} def __new__(cls, name, *args, **kwargs): entry_points = pkg_resources.iter_entry_points('onitu.tests') tests_modules = {e.name: e for e in entry_points} if name not in tests_modules: raise ImportError( "Cannot import tests for driver {}".format(name) ) try: tests = tests_modules[name].load() except ImportError as e: raise ImportError( "Error importing tests for driver {}: {}".format(name, e) ) try: driver = tests.Driver except ImportError: raise ImportError( "Tests for driver {} don't expose a" "Driver class".format(name) ) cls.drivers[name] = driver return driver(*args, **kwargs) class LocalStorageDriver(TestDriver): def __new__(cls, *args, **kwargs): return Driver('local_storage', *args, **kwargs) class TargetDriver(Driver): def __new__(cls, *args, **kwargs): type = os.environ.get('ONITU_TEST_DRIVER', 'local_storage') return Driver(type, *args, **kwargs)
Load tests helpers using entry_points
Load tests helpers using entry_points
Python
mit
onitu/onitu,onitu/onitu,onitu/onitu
import os - from importlib import import_module + import pkg_resources from .testdriver import TestDriver class Driver(TestDriver): drivers = {} - def __new__(cls, type, *args, **kwargs): + def __new__(cls, name, *args, **kwargs): - if type not in cls.drivers: + entry_points = pkg_resources.iter_entry_points('onitu.tests') + tests_modules = {e.name: e for e in entry_points} + + if name not in tests_modules: + raise ImportError( + "Cannot import tests for driver {}".format(name) + ) + - try: + try: - mod = import_module('onitu.drivers.{}.tests.driver'. - format(type)) + tests = tests_modules[name].load() + except ImportError as e: + raise ImportError( + "Error importing tests for driver {}: {}".format(name, e) + ) + + try: + driver = tests.Driver - except ImportError: + except ImportError: - raise KeyError("No such driver {}".format(repr(type))) + raise ImportError( + "Tests for driver {} don't expose a" + "Driver class".format(name) + ) + - cls.drivers[type] = mod.Driver + cls.drivers[name] = driver - return cls.drivers[type](*args, **kwargs) + return driver(*args, **kwargs) class LocalStorageDriver(TestDriver): def __new__(cls, *args, **kwargs): return Driver('local_storage', *args, **kwargs) class TargetDriver(Driver): def __new__(cls, *args, **kwargs): type = os.environ.get('ONITU_TEST_DRIVER', 'local_storage') return Driver(type, *args, **kwargs)
Load tests helpers using entry_points
## Code Before: import os from importlib import import_module from .testdriver import TestDriver class Driver(TestDriver): drivers = {} def __new__(cls, type, *args, **kwargs): if type not in cls.drivers: try: mod = import_module('onitu.drivers.{}.tests.driver'. format(type)) except ImportError: raise KeyError("No such driver {}".format(repr(type))) cls.drivers[type] = mod.Driver return cls.drivers[type](*args, **kwargs) class LocalStorageDriver(TestDriver): def __new__(cls, *args, **kwargs): return Driver('local_storage', *args, **kwargs) class TargetDriver(Driver): def __new__(cls, *args, **kwargs): type = os.environ.get('ONITU_TEST_DRIVER', 'local_storage') return Driver(type, *args, **kwargs) ## Instruction: Load tests helpers using entry_points ## Code After: import os import pkg_resources from .testdriver import TestDriver class Driver(TestDriver): drivers = {} def __new__(cls, name, *args, **kwargs): entry_points = pkg_resources.iter_entry_points('onitu.tests') tests_modules = {e.name: e for e in entry_points} if name not in tests_modules: raise ImportError( "Cannot import tests for driver {}".format(name) ) try: tests = tests_modules[name].load() except ImportError as e: raise ImportError( "Error importing tests for driver {}: {}".format(name, e) ) try: driver = tests.Driver except ImportError: raise ImportError( "Tests for driver {} don't expose a" "Driver class".format(name) ) cls.drivers[name] = driver return driver(*args, **kwargs) class LocalStorageDriver(TestDriver): def __new__(cls, *args, **kwargs): return Driver('local_storage', *args, **kwargs) class TargetDriver(Driver): def __new__(cls, *args, **kwargs): type = os.environ.get('ONITU_TEST_DRIVER', 'local_storage') return Driver(type, *args, **kwargs)
86f6191867141d7a7a165b227255d7b4406eb4f4
accounts/utils.py
accounts/utils.py
from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except ObjectDoesNotExist: city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except (ObjectDoesNotExist, AttributeError): city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
Fix crash on non-logged in users.
Fix crash on non-logged in users.
Python
agpl-3.0
osamak/student-portal,osamak/student-portal,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,enjaz/enjaz
from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city - except ObjectDoesNotExist: + except (ObjectDoesNotExist, AttributeError): city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
Fix crash on non-logged in users.
## Code Before: from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except ObjectDoesNotExist: city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender ## Instruction: Fix crash on non-logged in users. ## Code After: from django.core.exceptions import ObjectDoesNotExist def get_user_city(user): """Return the user's city. If unavailable, return an empty string.""" # If the profile is absent (i.e. superuser), return None. try: city = user.common_profile.city except (ObjectDoesNotExist, AttributeError): city = '' return city def get_user_gender(user): """Return the user's city. If unavailable, return an empty string.""" # If either the profile (i.e. superuser) or the college # (i.e. non-student) are absent, return an empty string. try: gender = user.common_profile.college.gender except (ObjectDoesNotExist, AttributeError): gender = '' return gender
6795e112e4f7037449850a361ab6b2f85fc2a66e
service/settings/staging.py
service/settings/staging.py
from service.settings.production import * ALLOWED_HOSTS = [ 'fantastic-doodle--staging.herokuapp.com', ]
from service.settings.production import * ALLOWED_HOSTS = [ 'fantastic-doodle--staging.herokuapp.com', '.herokuapp.com', ]
Add .herokuapp.com to ALLOWED_HOSTS to support review apps
Add .herokuapp.com to ALLOWED_HOSTS to support review apps
Python
unlicense
Mystopia/fantastic-doodle
from service.settings.production import * ALLOWED_HOSTS = [ 'fantastic-doodle--staging.herokuapp.com', + '.herokuapp.com', ]
Add .herokuapp.com to ALLOWED_HOSTS to support review apps
## Code Before: from service.settings.production import * ALLOWED_HOSTS = [ 'fantastic-doodle--staging.herokuapp.com', ] ## Instruction: Add .herokuapp.com to ALLOWED_HOSTS to support review apps ## Code After: from service.settings.production import * ALLOWED_HOSTS = [ 'fantastic-doodle--staging.herokuapp.com', '.herokuapp.com', ]
3800c095f58e9bc2ca8c580537ea576049bbfe2d
sell/urls.py
sell/urls.py
from django.conf.urls import url from sell import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^personal/$', views.personal_data), url(r'^books/$', views.books), url(r'^summary/$', views.summary), ]
from django.conf.urls import url from sell import views urlpatterns = [ url(r'^$', views.index), url(r'^personal/$', views.personal_data), url(r'^books/$', views.books), url(r'^summary/$', views.summary), ]
Remove unnecessary URL name in Sell app
Remove unnecessary URL name in Sell app
Python
agpl-3.0
m4tx/egielda,m4tx/egielda,m4tx/egielda
from django.conf.urls import url from sell import views urlpatterns = [ - url(r'^$', views.index, name='index'), + url(r'^$', views.index), url(r'^personal/$', views.personal_data), url(r'^books/$', views.books), url(r'^summary/$', views.summary), ]
Remove unnecessary URL name in Sell app
## Code Before: from django.conf.urls import url from sell import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^personal/$', views.personal_data), url(r'^books/$', views.books), url(r'^summary/$', views.summary), ] ## Instruction: Remove unnecessary URL name in Sell app ## Code After: from django.conf.urls import url from sell import views urlpatterns = [ url(r'^$', views.index), url(r'^personal/$', views.personal_data), url(r'^books/$', views.books), url(r'^summary/$', views.summary), ]
82ae5e5cf3da57af771aa688ec7d951879423578
big_o/test/test_complexities.py
big_o/test/test_complexities.py
import unittest import numpy as np from numpy.testing import assert_array_almost_equal from big_o import complexities class TestComplexities(unittest.TestCase): def test_compute(self): x = np.linspace(10, 100, 100) y = 3.0 * x + 2.0 linear = complexities.Linear() linear.fit(x, y) assert_array_almost_equal(linear.compute(x), y, 10) def test_not_fitted(self): linear = complexities.Linear() self.assertRaises(complexities.NotFittedError, linear.compute, 100) def test_str_includes_units(self): x = np.linspace(10, 100, 100) y = 3.0 * x + 2.0 linear = complexities.Linear() linear.fit(x, y) linear_str = str(linear) assert '(sec)' in linear_str
import unittest import numpy as np from numpy.testing import assert_array_almost_equal from big_o import complexities class TestComplexities(unittest.TestCase): def test_compute(self): desired = [ (lambda x: 2.+x*0., complexities.Constant), (lambda x: 5.*x+3., complexities.Linear), (lambda x: 8.1*x**2.+0.9, complexities.Quadratic), (lambda x: 1.0*x**3+11.0, complexities.Cubic), (lambda x: 5.2*x**2.5, complexities.Polynomial), (lambda x: 8.5*np.log(x)+99.0, complexities.Logarithmic), (lambda x: 1.7*x*np.log(x)+2.74, complexities.Linearithmic), (lambda x: 3.14**x, complexities.Exponential) ] x = np.linspace(10, 100, 100) for f, class_ in desired: y = f(x) complexity = class_() complexity.fit(x, y) assert_array_almost_equal(complexity.compute(x), y, 10, "compute() failed to match expected values for class %r" % class_) def test_not_fitted(self): linear = complexities.Linear() self.assertRaises(complexities.NotFittedError, linear.compute, 100) def test_str_includes_units(self): x = np.linspace(10, 100, 100) y = 3.0 * x + 2.0 linear = complexities.Linear() linear.fit(x, y) linear_str = str(linear) assert '(sec)' in linear_str
Add compute test cases for all complexity classes
Add compute test cases for all complexity classes
Python
bsd-3-clause
pberkes/big_O
import unittest import numpy as np from numpy.testing import assert_array_almost_equal from big_o import complexities class TestComplexities(unittest.TestCase): def test_compute(self): + desired = [ + (lambda x: 2.+x*0., complexities.Constant), + (lambda x: 5.*x+3., complexities.Linear), + (lambda x: 8.1*x**2.+0.9, complexities.Quadratic), + (lambda x: 1.0*x**3+11.0, complexities.Cubic), + (lambda x: 5.2*x**2.5, complexities.Polynomial), + (lambda x: 8.5*np.log(x)+99.0, complexities.Logarithmic), + (lambda x: 1.7*x*np.log(x)+2.74, complexities.Linearithmic), + (lambda x: 3.14**x, complexities.Exponential) + ] + x = np.linspace(10, 100, 100) - y = 3.0 * x + 2.0 - linear = complexities.Linear() - linear.fit(x, y) - assert_array_almost_equal(linear.compute(x), y, 10) + for f, class_ in desired: + y = f(x) + complexity = class_() + complexity.fit(x, y) + assert_array_almost_equal(complexity.compute(x), y, 10, "compute() failed to match expected values for class %r" % class_) def test_not_fitted(self): linear = complexities.Linear() self.assertRaises(complexities.NotFittedError, linear.compute, 100) def test_str_includes_units(self): x = np.linspace(10, 100, 100) y = 3.0 * x + 2.0 linear = complexities.Linear() linear.fit(x, y) linear_str = str(linear) assert '(sec)' in linear_str
Add compute test cases for all complexity classes
## Code Before: import unittest import numpy as np from numpy.testing import assert_array_almost_equal from big_o import complexities class TestComplexities(unittest.TestCase): def test_compute(self): x = np.linspace(10, 100, 100) y = 3.0 * x + 2.0 linear = complexities.Linear() linear.fit(x, y) assert_array_almost_equal(linear.compute(x), y, 10) def test_not_fitted(self): linear = complexities.Linear() self.assertRaises(complexities.NotFittedError, linear.compute, 100) def test_str_includes_units(self): x = np.linspace(10, 100, 100) y = 3.0 * x + 2.0 linear = complexities.Linear() linear.fit(x, y) linear_str = str(linear) assert '(sec)' in linear_str ## Instruction: Add compute test cases for all complexity classes ## Code After: import unittest import numpy as np from numpy.testing import assert_array_almost_equal from big_o import complexities class TestComplexities(unittest.TestCase): def test_compute(self): desired = [ (lambda x: 2.+x*0., complexities.Constant), (lambda x: 5.*x+3., complexities.Linear), (lambda x: 8.1*x**2.+0.9, complexities.Quadratic), (lambda x: 1.0*x**3+11.0, complexities.Cubic), (lambda x: 5.2*x**2.5, complexities.Polynomial), (lambda x: 8.5*np.log(x)+99.0, complexities.Logarithmic), (lambda x: 1.7*x*np.log(x)+2.74, complexities.Linearithmic), (lambda x: 3.14**x, complexities.Exponential) ] x = np.linspace(10, 100, 100) for f, class_ in desired: y = f(x) complexity = class_() complexity.fit(x, y) assert_array_almost_equal(complexity.compute(x), y, 10, "compute() failed to match expected values for class %r" % class_) def test_not_fitted(self): linear = complexities.Linear() self.assertRaises(complexities.NotFittedError, linear.compute, 100) def test_str_includes_units(self): x = np.linspace(10, 100, 100) y = 3.0 * x + 2.0 linear = complexities.Linear() linear.fit(x, y) linear_str = str(linear) assert '(sec)' in linear_str
219c474860ca7674070ef19fa95f0282b7c92399
mpages/admin.py
mpages/admin.py
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "parent": kwargs["queryset"] = Page.objects.order_by("title") return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
Order parents in Admin select field
Order parents in Admin select field
Python
bsd-3-clause
ahernp/DMCM,ahernp/DMCM,ahernp/DMCM
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) + def formfield_for_foreignkey(self, db_field, request, **kwargs): + if db_field.name == "parent": + kwargs["queryset"] = Page.objects.order_by("title") + return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) + admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
Order parents in Admin select field
## Code Before: from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag) ## Instruction: Order parents in Admin select field ## Code After: from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "parent": kwargs["queryset"] = Page.objects.order_by("title") return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
f76783ddb616c74e22feb003cb12952375cad658
corehq/apps/hqwebapp/encoders.py
corehq/apps/hqwebapp/encoders.py
import json import datetime from django.utils.encoding import force_unicode from django.utils.functional import Promise class LazyEncoder(json.JSONEncoder): """Taken from https://github.com/tomchristie/django-rest-framework/issues/87 This makes sure that ugettext_lazy refrences in a dict are properly evaluated """ def default(self, obj): if isinstance(obj, Promise): return force_unicode(obj) return super(LazyEncoder, self).default(obj)
import json import datetime from decimal import Decimal from django.utils.encoding import force_unicode from django.utils.functional import Promise class DecimalEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return str(obj) return super(DecimalEncoder, self).default(obj) class LazyEncoder(DecimalEncoder): """Taken from https://github.com/tomchristie/django-rest-framework/issues/87 This makes sure that ugettext_lazy refrences in a dict are properly evaluated """ def default(self, obj): if isinstance(obj, Promise): return force_unicode(obj) return super(LazyEncoder, self).default(obj)
Fix for json encoding Decimal values
Fix for json encoding Decimal values
Python
bsd-3-clause
SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,SEL-Columbia/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
import json import datetime + from decimal import Decimal from django.utils.encoding import force_unicode from django.utils.functional import Promise - class LazyEncoder(json.JSONEncoder): + class DecimalEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, Decimal): + return str(obj) + return super(DecimalEncoder, self).default(obj) + + + class LazyEncoder(DecimalEncoder): """Taken from https://github.com/tomchristie/django-rest-framework/issues/87 This makes sure that ugettext_lazy refrences in a dict are properly evaluated """ def default(self, obj): if isinstance(obj, Promise): return force_unicode(obj) return super(LazyEncoder, self).default(obj)
Fix for json encoding Decimal values
## Code Before: import json import datetime from django.utils.encoding import force_unicode from django.utils.functional import Promise class LazyEncoder(json.JSONEncoder): """Taken from https://github.com/tomchristie/django-rest-framework/issues/87 This makes sure that ugettext_lazy refrences in a dict are properly evaluated """ def default(self, obj): if isinstance(obj, Promise): return force_unicode(obj) return super(LazyEncoder, self).default(obj) ## Instruction: Fix for json encoding Decimal values ## Code After: import json import datetime from decimal import Decimal from django.utils.encoding import force_unicode from django.utils.functional import Promise class DecimalEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return str(obj) return super(DecimalEncoder, self).default(obj) class LazyEncoder(DecimalEncoder): """Taken from https://github.com/tomchristie/django-rest-framework/issues/87 This makes sure that ugettext_lazy refrences in a dict are properly evaluated """ def default(self, obj): if isinstance(obj, Promise): return force_unicode(obj) return super(LazyEncoder, self).default(obj)
991973e554758e7a9881453d7668925902e610b9
tests.py
tests.py
import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode("master") self.assertEquals(gm.encode(gm.decode(once)), once) if __name__ == '__main__': unittest.main(verbosity=2)
import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode("master") self.assertEquals(gm.encode(gm.decode(once)), once) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(GitMnemonicTests) results = unittest.TextTestRunner(verbosity=2).run(suite) if not results.wasSuccessful(): import sys sys.exit(1)
Make unittest test runner work in older pythons
Make unittest test runner work in older pythons
Python
mit
glenjamin/git-mnemonic
import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode("master") self.assertEquals(gm.encode(gm.decode(once)), once) if __name__ == '__main__': - unittest.main(verbosity=2) + suite = unittest.TestLoader().loadTestsFromTestCase(GitMnemonicTests) + results = unittest.TextTestRunner(verbosity=2).run(suite) + if not results.wasSuccessful(): + import sys + sys.exit(1)
Make unittest test runner work in older pythons
## Code Before: import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode("master") self.assertEquals(gm.encode(gm.decode(once)), once) if __name__ == '__main__': unittest.main(verbosity=2) ## Instruction: Make unittest test runner work in older pythons ## Code After: import unittest import git_mnemonic as gm class GitMnemonicTests(unittest.TestCase): def test_encode(self): self.assertTrue(gm.encode("master")) def test_decode(self): self.assertTrue(gm.decode("bis alo ama aha")) def test_invertible(self): once = gm.encode("master") self.assertEquals(gm.encode(gm.decode(once)), once) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(GitMnemonicTests) results = unittest.TextTestRunner(verbosity=2).run(suite) if not results.wasSuccessful(): import sys sys.exit(1)
cb08d25f49b8b4c5177c8afdd9a69330992ee854
tests/replay/test_replay.py
tests/replay/test_replay.py
import pytest from cookiecutter import replay, main, exceptions def test_get_replay_file_name(): """Make sure that replay.get_file_name generates a valid json file path.""" assert replay.get_file_name('foo', 'bar') == 'foo/bar.json' @pytest.fixture(params=[ {'no_input': True}, {'extra_context': {}}, {'no_input': True, 'extra_context': {}}, ]) def invalid_kwargs(request): return request.param def test_raise_on_invalid_mode(invalid_kwargs): with pytest.raises(exceptions.InvalidModeException): main.cookiecutter('foo', replay=True, **invalid_kwargs)
import pytest from cookiecutter import replay, main, exceptions def test_get_replay_file_name(): """Make sure that replay.get_file_name generates a valid json file path.""" assert replay.get_file_name('foo', 'bar') == 'foo/bar.json' @pytest.fixture(params=[ {'no_input': True}, {'extra_context': {}}, {'no_input': True, 'extra_context': {}}, ]) def invalid_kwargs(request): return request.param def test_raise_on_invalid_mode(invalid_kwargs): with pytest.raises(exceptions.InvalidModeException): main.cookiecutter('foo', replay=True, **invalid_kwargs) def test_main_does_not_invoke_dump_but_load(mocker): mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config') mock_gen_context = mocker.patch('cookiecutter.main.generate_context') mock_gen_files = mocker.patch('cookiecutter.main.generate_files') mock_replay_dump = mocker.patch('cookiecutter.main.dump') mock_replay_load = mocker.patch('cookiecutter.main.load') main.cookiecutter('foobar', replay=True) assert not mock_prompt.called assert not mock_gen_context.called assert not mock_replay_dump.called assert mock_replay_load.called assert mock_gen_files.called def test_main_does_not_invoke_load_but_dump(mocker): mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config') mock_gen_context = mocker.patch('cookiecutter.main.generate_context') mock_gen_files = mocker.patch('cookiecutter.main.generate_files') mock_replay_dump = mocker.patch('cookiecutter.main.dump') mock_replay_load = mocker.patch('cookiecutter.main.load') main.cookiecutter('foobar', replay=False) assert mock_prompt.called assert mock_gen_context.called assert mock_replay_dump.called assert not mock_replay_load.called assert mock_gen_files.called
Add tests for a correct behaviour in cookiecutter.main for replay
Add tests for a correct behaviour in cookiecutter.main for replay
Python
bsd-3-clause
christabor/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,cguardia/cookiecutter,pjbull/cookiecutter,dajose/cookiecutter,michaeljoseph/cookiecutter,moi65/cookiecutter,terryjbates/cookiecutter,takeflight/cookiecutter,terryjbates/cookiecutter,luzfcb/cookiecutter,agconti/cookiecutter,cguardia/cookiecutter,christabor/cookiecutter,audreyr/cookiecutter,stevepiercy/cookiecutter,willingc/cookiecutter,venumech/cookiecutter,stevepiercy/cookiecutter,takeflight/cookiecutter,pjbull/cookiecutter,benthomasson/cookiecutter,agconti/cookiecutter,benthomasson/cookiecutter,Springerle/cookiecutter,ramiroluz/cookiecutter,audreyr/cookiecutter,moi65/cookiecutter,dajose/cookiecutter,hackebrot/cookiecutter,michaeljoseph/cookiecutter,Springerle/cookiecutter,ramiroluz/cookiecutter,venumech/cookiecutter,willingc/cookiecutter
import pytest from cookiecutter import replay, main, exceptions def test_get_replay_file_name(): """Make sure that replay.get_file_name generates a valid json file path.""" assert replay.get_file_name('foo', 'bar') == 'foo/bar.json' @pytest.fixture(params=[ {'no_input': True}, {'extra_context': {}}, {'no_input': True, 'extra_context': {}}, ]) def invalid_kwargs(request): return request.param def test_raise_on_invalid_mode(invalid_kwargs): with pytest.raises(exceptions.InvalidModeException): main.cookiecutter('foo', replay=True, **invalid_kwargs) + + def test_main_does_not_invoke_dump_but_load(mocker): + mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config') + mock_gen_context = mocker.patch('cookiecutter.main.generate_context') + mock_gen_files = mocker.patch('cookiecutter.main.generate_files') + mock_replay_dump = mocker.patch('cookiecutter.main.dump') + mock_replay_load = mocker.patch('cookiecutter.main.load') + + main.cookiecutter('foobar', replay=True) + + assert not mock_prompt.called + assert not mock_gen_context.called + assert not mock_replay_dump.called + assert mock_replay_load.called + assert mock_gen_files.called + + + def test_main_does_not_invoke_load_but_dump(mocker): + mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config') + mock_gen_context = mocker.patch('cookiecutter.main.generate_context') + mock_gen_files = mocker.patch('cookiecutter.main.generate_files') + mock_replay_dump = mocker.patch('cookiecutter.main.dump') + mock_replay_load = mocker.patch('cookiecutter.main.load') + + main.cookiecutter('foobar', replay=False) + + assert mock_prompt.called + assert mock_gen_context.called + assert mock_replay_dump.called + assert not mock_replay_load.called + assert mock_gen_files.called +
Add tests for a correct behaviour in cookiecutter.main for replay
## Code Before: import pytest from cookiecutter import replay, main, exceptions def test_get_replay_file_name(): """Make sure that replay.get_file_name generates a valid json file path.""" assert replay.get_file_name('foo', 'bar') == 'foo/bar.json' @pytest.fixture(params=[ {'no_input': True}, {'extra_context': {}}, {'no_input': True, 'extra_context': {}}, ]) def invalid_kwargs(request): return request.param def test_raise_on_invalid_mode(invalid_kwargs): with pytest.raises(exceptions.InvalidModeException): main.cookiecutter('foo', replay=True, **invalid_kwargs) ## Instruction: Add tests for a correct behaviour in cookiecutter.main for replay ## Code After: import pytest from cookiecutter import replay, main, exceptions def test_get_replay_file_name(): """Make sure that replay.get_file_name generates a valid json file path.""" assert replay.get_file_name('foo', 'bar') == 'foo/bar.json' @pytest.fixture(params=[ {'no_input': True}, {'extra_context': {}}, {'no_input': True, 'extra_context': {}}, ]) def invalid_kwargs(request): return request.param def test_raise_on_invalid_mode(invalid_kwargs): with pytest.raises(exceptions.InvalidModeException): main.cookiecutter('foo', replay=True, **invalid_kwargs) def test_main_does_not_invoke_dump_but_load(mocker): mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config') mock_gen_context = mocker.patch('cookiecutter.main.generate_context') mock_gen_files = mocker.patch('cookiecutter.main.generate_files') mock_replay_dump = mocker.patch('cookiecutter.main.dump') mock_replay_load = mocker.patch('cookiecutter.main.load') main.cookiecutter('foobar', replay=True) assert not mock_prompt.called assert not mock_gen_context.called assert not mock_replay_dump.called assert mock_replay_load.called assert mock_gen_files.called def test_main_does_not_invoke_load_but_dump(mocker): mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config') mock_gen_context = mocker.patch('cookiecutter.main.generate_context') mock_gen_files = mocker.patch('cookiecutter.main.generate_files') mock_replay_dump = mocker.patch('cookiecutter.main.dump') mock_replay_load = mocker.patch('cookiecutter.main.load') main.cookiecutter('foobar', replay=False) assert mock_prompt.called assert mock_gen_context.called assert mock_replay_dump.called assert not mock_replay_load.called assert mock_gen_files.called
f3b9cc6392e4c271ae11417357ecdc196f1c3ae7
python_scripts/extractor_python_readability_server.py
python_scripts/extractor_python_readability_server.py
import sys import os import glob #sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py")) sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/")) sys.path.append(os.path.dirname(__file__) ) from thrift.transport import TSocket from thrift.server import TServer #import thrift_solr import ExtractorService import sys import readability import readability def extract_with_python_readability( raw_content ): doc = readability.Document( raw_content ) return [ u'' + doc.short_title(), u'' + doc.summary() ] class ExtractorHandler: def extract_html( self, raw_html ): #print raw_html #raw_html = raw_html.encode( 'utf-8' ) ret = extract_with_python_readability( raw_html ) #print ret[1] return ret handler = ExtractorHandler() processor = ExtractorService.Processor(handler) listening_socket = TSocket.TServerSocket(port=9090) server = TServer.TThreadPoolServer(processor, listening_socket) print ("[Server] Started") server.serve()
import sys import os import glob #sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py")) sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/")) sys.path.append(os.path.dirname(__file__) ) from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer from thrift.protocol.TBinaryProtocol import TBinaryProtocolAccelerated #import thrift_solr import ExtractorService import sys import readability import readability def extract_with_python_readability( raw_content ): doc = readability.Document( raw_content ) return [ u'' + doc.short_title(), u'' + doc.summary() ] class ExtractorHandler: def extract_html( self, raw_html ): #print raw_html #raw_html = raw_html.encode( 'utf-8' ) ret = extract_with_python_readability( raw_html ) #print ret[1] return ret handler = ExtractorHandler() processor = ExtractorService.Processor(handler) listening_socket = TSocket.TServerSocket(port=9090) tfactory = TTransport.TBufferedTransportFactory() #pfactory = TBinaryProtocol.TBinaryProtocolFactory() pfactory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory() server = TServer.TThreadPoolServer(processor, listening_socket, tfactory, pfactory) print ("[Server] Started") server.serve()
Use the TBinaryProtocolAccelerated protocol instead of TBinaryProtocol to improve performance.
Use the TBinaryProtocolAccelerated protocol instead of TBinaryProtocol to improve performance.
Python
agpl-3.0
AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud
import sys import os import glob #sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py")) sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/")) sys.path.append(os.path.dirname(__file__) ) from thrift.transport import TSocket + from thrift.transport import TTransport + from thrift.protocol import TBinaryProtocol from thrift.server import TServer + from thrift.protocol.TBinaryProtocol import TBinaryProtocolAccelerated + #import thrift_solr import ExtractorService import sys import readability import readability def extract_with_python_readability( raw_content ): doc = readability.Document( raw_content ) return [ u'' + doc.short_title(), u'' + doc.summary() ] class ExtractorHandler: def extract_html( self, raw_html ): #print raw_html #raw_html = raw_html.encode( 'utf-8' ) ret = extract_with_python_readability( raw_html ) #print ret[1] return ret handler = ExtractorHandler() processor = ExtractorService.Processor(handler) listening_socket = TSocket.TServerSocket(port=9090) + tfactory = TTransport.TBufferedTransportFactory() + #pfactory = TBinaryProtocol.TBinaryProtocolFactory() + pfactory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory() + - server = TServer.TThreadPoolServer(processor, listening_socket) + server = TServer.TThreadPoolServer(processor, listening_socket, tfactory, pfactory) print ("[Server] Started") server.serve()
Use the TBinaryProtocolAccelerated protocol instead of TBinaryProtocol to improve performance.
## Code Before: import sys import os import glob #sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py")) sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/")) sys.path.append(os.path.dirname(__file__) ) from thrift.transport import TSocket from thrift.server import TServer #import thrift_solr import ExtractorService import sys import readability import readability def extract_with_python_readability( raw_content ): doc = readability.Document( raw_content ) return [ u'' + doc.short_title(), u'' + doc.summary() ] class ExtractorHandler: def extract_html( self, raw_html ): #print raw_html #raw_html = raw_html.encode( 'utf-8' ) ret = extract_with_python_readability( raw_html ) #print ret[1] return ret handler = ExtractorHandler() processor = ExtractorService.Processor(handler) listening_socket = TSocket.TServerSocket(port=9090) server = TServer.TThreadPoolServer(processor, listening_socket) print ("[Server] Started") server.serve() ## Instruction: Use the TBinaryProtocolAccelerated protocol instead of TBinaryProtocol to improve performance. ## Code After: import sys import os import glob #sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py")) sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/")) sys.path.append(os.path.dirname(__file__) ) from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer from thrift.protocol.TBinaryProtocol import TBinaryProtocolAccelerated #import thrift_solr import ExtractorService import sys import readability import readability def extract_with_python_readability( raw_content ): doc = readability.Document( raw_content ) return [ u'' + doc.short_title(), u'' + doc.summary() ] class ExtractorHandler: def extract_html( self, raw_html ): #print raw_html #raw_html = raw_html.encode( 'utf-8' ) ret = extract_with_python_readability( raw_html ) #print ret[1] return ret handler = ExtractorHandler() processor = ExtractorService.Processor(handler) listening_socket = TSocket.TServerSocket(port=9090) tfactory = TTransport.TBufferedTransportFactory() #pfactory = TBinaryProtocol.TBinaryProtocolFactory() pfactory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory() server = TServer.TThreadPoolServer(processor, listening_socket, tfactory, pfactory) print ("[Server] Started") server.serve()
b352c3e1f5e8812d29f2e8a1bca807bea5da8cc4
test/test_hx_launcher.py
test/test_hx_launcher.py
import pytest_twisted from hendrix.ux import main from hendrix.options import HendrixOptionParser def test_no_arguments_gives_help_text(mocker): class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write(cls, whatever): HendrixOptionParser.print_help(MockFile) assert MockFile.things_written == whatever mocker.patch('sys.stdout', new=MockStdOut) main([])
from hendrix.options import HendrixOptionParser from hendrix.ux import main def test_no_arguments_gives_help_text(mocker): class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write(cls, whatever): HendrixOptionParser.print_help(MockFile) assert MockFile.things_written == whatever mocker.patch('sys.stdout', new=MockStdOut) main([])
Test for the hx launcher.
Test for the hx launcher.
Python
mit
hangarunderground/hendrix,hendrix/hendrix,hangarunderground/hendrix,hendrix/hendrix,jMyles/hendrix,hendrix/hendrix,jMyles/hendrix,hangarunderground/hendrix,hangarunderground/hendrix,jMyles/hendrix
+ from hendrix.options import HendrixOptionParser - import pytest_twisted - from hendrix.ux import main - from hendrix.options import HendrixOptionParser def test_no_arguments_gives_help_text(mocker): - class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write(cls, whatever): HendrixOptionParser.print_help(MockFile) assert MockFile.things_written == whatever mocker.patch('sys.stdout', new=MockStdOut) main([])
Test for the hx launcher.
## Code Before: import pytest_twisted from hendrix.ux import main from hendrix.options import HendrixOptionParser def test_no_arguments_gives_help_text(mocker): class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write(cls, whatever): HendrixOptionParser.print_help(MockFile) assert MockFile.things_written == whatever mocker.patch('sys.stdout', new=MockStdOut) main([]) ## Instruction: Test for the hx launcher. ## Code After: from hendrix.options import HendrixOptionParser from hendrix.ux import main def test_no_arguments_gives_help_text(mocker): class MockFile(object): @classmethod def write(cls, whatever): cls.things_written = whatever class MockStdOut(object): @classmethod def write(cls, whatever): HendrixOptionParser.print_help(MockFile) assert MockFile.things_written == whatever mocker.patch('sys.stdout', new=MockStdOut) main([])
ad21c9255f6246944cd032ad50082c0aca46fcb3
neurokernel/tools/mpi.py
neurokernel/tools/mpi.py
from mpi4py import MPI import twiggy class MPIOutput(twiggy.outputs.Output): """ Output messages to a file via MPI I/O. """ def __init__(self, name, format, comm, mode=MPI.MODE_CREATE | MPI.MODE_WRONLY, close_atexit=True): self.filename = name self._format = format if format is not None else self._noop_format self.comm = comm self.mode = mode super(MPIOutput, self).__init__(format, close_atexit) def _open(self): self.file = MPI.File.Open(self.comm, self.filename, self.mode) def _close(self): self.file.Close() def _write(self, x): self.file.Iwrite_shared(x)
from mpi4py import MPI import twiggy class MPIOutput(twiggy.outputs.Output): """ Output messages to a file via MPI I/O. """ def __init__(self, name, format, comm, mode=MPI.MODE_CREATE | MPI.MODE_WRONLY, close_atexit=True): self.filename = name self._format = format if format is not None else self._noop_format self.comm = comm self.mode = mode super(MPIOutput, self).__init__(format, close_atexit) def _open(self): self.file = MPI.File.Open(self.comm, self.filename, self.mode) def _close(self): self.file.Close() def _write(self, x): self.file.Iwrite_shared(x) # This seems to be necessary to prevent some log lines from being lost: self.file.Sync()
Call MPIOutput.file.Sync() in MPIOutput.file._write() to prevent log lines from intermittently being lost.
Call MPIOutput.file.Sync() in MPIOutput.file._write() to prevent log lines from intermittently being lost.
Python
bsd-3-clause
cerrno/neurokernel
from mpi4py import MPI import twiggy class MPIOutput(twiggy.outputs.Output): """ Output messages to a file via MPI I/O. """ def __init__(self, name, format, comm, mode=MPI.MODE_CREATE | MPI.MODE_WRONLY, close_atexit=True): self.filename = name self._format = format if format is not None else self._noop_format self.comm = comm self.mode = mode super(MPIOutput, self).__init__(format, close_atexit) def _open(self): self.file = MPI.File.Open(self.comm, self.filename, self.mode) def _close(self): self.file.Close() def _write(self, x): self.file.Iwrite_shared(x) + # This seems to be necessary to prevent some log lines from being lost: + self.file.Sync()
Call MPIOutput.file.Sync() in MPIOutput.file._write() to prevent log lines from intermittently being lost.
## Code Before: from mpi4py import MPI import twiggy class MPIOutput(twiggy.outputs.Output): """ Output messages to a file via MPI I/O. """ def __init__(self, name, format, comm, mode=MPI.MODE_CREATE | MPI.MODE_WRONLY, close_atexit=True): self.filename = name self._format = format if format is not None else self._noop_format self.comm = comm self.mode = mode super(MPIOutput, self).__init__(format, close_atexit) def _open(self): self.file = MPI.File.Open(self.comm, self.filename, self.mode) def _close(self): self.file.Close() def _write(self, x): self.file.Iwrite_shared(x) ## Instruction: Call MPIOutput.file.Sync() in MPIOutput.file._write() to prevent log lines from intermittently being lost. ## Code After: from mpi4py import MPI import twiggy class MPIOutput(twiggy.outputs.Output): """ Output messages to a file via MPI I/O. """ def __init__(self, name, format, comm, mode=MPI.MODE_CREATE | MPI.MODE_WRONLY, close_atexit=True): self.filename = name self._format = format if format is not None else self._noop_format self.comm = comm self.mode = mode super(MPIOutput, self).__init__(format, close_atexit) def _open(self): self.file = MPI.File.Open(self.comm, self.filename, self.mode) def _close(self): self.file.Close() def _write(self, x): self.file.Iwrite_shared(x) # This seems to be necessary to prevent some log lines from being lost: self.file.Sync()
4485b65722645d6c9617b5ff4aea6d62ee8a9adf
bumblebee_status/modules/contrib/optman.py
bumblebee_status/modules/contrib/optman.py
import subprocess import core.module import core.widget class Module(core.module.Module): def __init__(self, config, theme): super().__init__(config, theme, core.widget.Widget(self.output)) self.__gpumode = "" def output(self, _): return "GPU: {}".format(self.__gpumode) def update(self): cmd = ["optimus-manager", "--print-mode"] output = ( subprocess.Popen(cmd, stdout=subprocess.PIPE) .communicate()[0] .decode("utf-8") .lower() ) if "intel" in output: self.__gpumode = "Intel" elif "nvidia" in output: self.__gpumode = "Nvidia" elif "amd" in output: self.__gpumode = "AMD"
import core.module import core.widget import util.cli class Module(core.module.Module): def __init__(self, config, theme): super().__init__(config, theme, core.widget.Widget(self.output)) self.__gpumode = "" def output(self, _): return "GPU: {}".format(self.__gpumode) def update(self): cmd = "optimus-manager --print-mode" output = util.cli.execute(cmd).strip() if "intel" in output: self.__gpumode = "Intel" elif "nvidia" in output: self.__gpumode = "Nvidia" elif "amd" in output: self.__gpumode = "AMD"
Use the existing util.cli module
Use the existing util.cli module
Python
mit
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
- - import subprocess import core.module import core.widget + import util.cli class Module(core.module.Module): def __init__(self, config, theme): super().__init__(config, theme, core.widget.Widget(self.output)) self.__gpumode = "" def output(self, _): return "GPU: {}".format(self.__gpumode) def update(self): - cmd = ["optimus-manager", "--print-mode"] + cmd = "optimus-manager --print-mode" + output = util.cli.execute(cmd).strip() - output = ( - subprocess.Popen(cmd, stdout=subprocess.PIPE) - .communicate()[0] - .decode("utf-8") - .lower() - ) if "intel" in output: self.__gpumode = "Intel" elif "nvidia" in output: self.__gpumode = "Nvidia" elif "amd" in output: self.__gpumode = "AMD"
Use the existing util.cli module
## Code Before: import subprocess import core.module import core.widget class Module(core.module.Module): def __init__(self, config, theme): super().__init__(config, theme, core.widget.Widget(self.output)) self.__gpumode = "" def output(self, _): return "GPU: {}".format(self.__gpumode) def update(self): cmd = ["optimus-manager", "--print-mode"] output = ( subprocess.Popen(cmd, stdout=subprocess.PIPE) .communicate()[0] .decode("utf-8") .lower() ) if "intel" in output: self.__gpumode = "Intel" elif "nvidia" in output: self.__gpumode = "Nvidia" elif "amd" in output: self.__gpumode = "AMD" ## Instruction: Use the existing util.cli module ## Code After: import core.module import core.widget import util.cli class Module(core.module.Module): def __init__(self, config, theme): super().__init__(config, theme, core.widget.Widget(self.output)) self.__gpumode = "" def output(self, _): return "GPU: {}".format(self.__gpumode) def update(self): cmd = "optimus-manager --print-mode" output = util.cli.execute(cmd).strip() if "intel" in output: self.__gpumode = "Intel" elif "nvidia" in output: self.__gpumode = "Nvidia" elif "amd" in output: self.__gpumode = "AMD"
3307bfb7075a527dc7805da2ff735f461f5fc02f
employees/models.py
employees/models.py
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Role(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name @python_2_unicode_compatible class Category(models.Model): name = models.CharField(max_length=100) weight = models.PositiveSmallIntegerField(default=1) def __str__(self): return self.name class Meta: verbose_name_plural = "categories" ordering = ['weight'] class Employee(AbstractUser): role = models.ForeignKey(Role, null=True, blank=True) skype_id = models.CharField(max_length=200, null=True, blank=True) last_month_score = models.PositiveIntegerField(default=0) current_month_score = models.PositiveIntegerField(default=0) level = models.PositiveIntegerField(default=0) total_score = models.PositiveIntegerField(default=0) avatar = models.ImageField(upload_to='avatar', null=True, blank=True) categories = models.ManyToManyField(Category)
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Role(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name @python_2_unicode_compatible class Category(models.Model): name = models.CharField(max_length=100) weight = models.PositiveSmallIntegerField(default=1) def __str__(self): return self.name class Meta: verbose_name_plural = "categories" ordering = ['weight'] class Employee(AbstractUser): role = models.ForeignKey(Role, null=True, blank=True) skype_id = models.CharField(max_length=200, null=True, blank=True) last_month_score = models.PositiveIntegerField(default=0) current_month_score = models.PositiveIntegerField(default=0) level = models.PositiveIntegerField(default=0) total_score = models.PositiveIntegerField(default=0) avatar = models.ImageField(upload_to='avatar', null=True, blank=True) categories = models.ManyToManyField(Category, blank=True)
Change categories field to non required.
Change categories field to non required.
Python
mit
neosergio/allstars
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Role(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name @python_2_unicode_compatible class Category(models.Model): name = models.CharField(max_length=100) weight = models.PositiveSmallIntegerField(default=1) def __str__(self): return self.name class Meta: verbose_name_plural = "categories" ordering = ['weight'] class Employee(AbstractUser): role = models.ForeignKey(Role, null=True, blank=True) skype_id = models.CharField(max_length=200, null=True, blank=True) last_month_score = models.PositiveIntegerField(default=0) current_month_score = models.PositiveIntegerField(default=0) level = models.PositiveIntegerField(default=0) total_score = models.PositiveIntegerField(default=0) avatar = models.ImageField(upload_to='avatar', null=True, blank=True) - categories = models.ManyToManyField(Category) + categories = models.ManyToManyField(Category, blank=True)
Change categories field to non required.
## Code Before: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Role(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name @python_2_unicode_compatible class Category(models.Model): name = models.CharField(max_length=100) weight = models.PositiveSmallIntegerField(default=1) def __str__(self): return self.name class Meta: verbose_name_plural = "categories" ordering = ['weight'] class Employee(AbstractUser): role = models.ForeignKey(Role, null=True, blank=True) skype_id = models.CharField(max_length=200, null=True, blank=True) last_month_score = models.PositiveIntegerField(default=0) current_month_score = models.PositiveIntegerField(default=0) level = models.PositiveIntegerField(default=0) total_score = models.PositiveIntegerField(default=0) avatar = models.ImageField(upload_to='avatar', null=True, blank=True) categories = models.ManyToManyField(Category) ## Instruction: Change categories field to non required. ## Code After: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Role(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name @python_2_unicode_compatible class Category(models.Model): name = models.CharField(max_length=100) weight = models.PositiveSmallIntegerField(default=1) def __str__(self): return self.name class Meta: verbose_name_plural = "categories" ordering = ['weight'] class Employee(AbstractUser): role = models.ForeignKey(Role, null=True, blank=True) skype_id = models.CharField(max_length=200, null=True, blank=True) last_month_score = models.PositiveIntegerField(default=0) current_month_score = models.PositiveIntegerField(default=0) level = models.PositiveIntegerField(default=0) total_score = models.PositiveIntegerField(default=0) avatar = models.ImageField(upload_to='avatar', null=True, blank=True) categories = models.ManyToManyField(Category, blank=True)
b4247769fcaa67d09e0f38d1283cf4f28ddc350e
cookiecutter/extensions.py
cookiecutter/extensions.py
"""Jinja2 extensions.""" import json from jinja2.ext import Extension class JsonifyExtension(Extension): """Jinja2 extension to convert a python object to json.""" def __init__(self, environment): """Initilize extension with given environment.""" super(JsonifyExtension, self).__init__(environment) def jsonify(obj): return json.dumps(obj, sort_keys=True, indent=4) environment.filters['jsonify'] = jsonify
"""Jinja2 extensions.""" import json from jinja2.ext import Extension class JsonifyExtension(Extension): """Jinja2 extension to convert a Python object to JSON.""" def __init__(self, environment): """Initialize the extension with the given environment.""" super(JsonifyExtension, self).__init__(environment) def jsonify(obj): return json.dumps(obj, sort_keys=True, indent=4) environment.filters['jsonify'] = jsonify
Fix typo and improve grammar in doc string
Fix typo and improve grammar in doc string
Python
bsd-3-clause
michaeljoseph/cookiecutter,dajose/cookiecutter,audreyr/cookiecutter,hackebrot/cookiecutter,audreyr/cookiecutter,hackebrot/cookiecutter,luzfcb/cookiecutter,pjbull/cookiecutter,dajose/cookiecutter,pjbull/cookiecutter,luzfcb/cookiecutter,michaeljoseph/cookiecutter
"""Jinja2 extensions.""" import json from jinja2.ext import Extension class JsonifyExtension(Extension): - """Jinja2 extension to convert a python object to json.""" + """Jinja2 extension to convert a Python object to JSON.""" def __init__(self, environment): - """Initilize extension with given environment.""" + """Initialize the extension with the given environment.""" super(JsonifyExtension, self).__init__(environment) def jsonify(obj): return json.dumps(obj, sort_keys=True, indent=4) environment.filters['jsonify'] = jsonify
Fix typo and improve grammar in doc string
## Code Before: """Jinja2 extensions.""" import json from jinja2.ext import Extension class JsonifyExtension(Extension): """Jinja2 extension to convert a python object to json.""" def __init__(self, environment): """Initilize extension with given environment.""" super(JsonifyExtension, self).__init__(environment) def jsonify(obj): return json.dumps(obj, sort_keys=True, indent=4) environment.filters['jsonify'] = jsonify ## Instruction: Fix typo and improve grammar in doc string ## Code After: """Jinja2 extensions.""" import json from jinja2.ext import Extension class JsonifyExtension(Extension): """Jinja2 extension to convert a Python object to JSON.""" def __init__(self, environment): """Initialize the extension with the given environment.""" super(JsonifyExtension, self).__init__(environment) def jsonify(obj): return json.dumps(obj, sort_keys=True, indent=4) environment.filters['jsonify'] = jsonify
42ec5ed6d56fcc59c99d175e1c9280d00cd3bef1
tests/test_published_results.py
tests/test_published_results.py
""" To test if the new code produces the same precision values on the published results.""" from __future__ import division, print_function import pytest import numpy as np import eniric.Qcalculator as Q import eniric.IOmodule as IO from bin.prec_1 import calc_prec1 # For python2.X compatibility file_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError) path = "data/Published_Results/resampled/" @pytest.mark.xfail(raises=file_error_to_catch) # Data file may not exist def test_presicion_1(): """ New precision 1 test that works.""" published_results = {1: 3.8, 5: 9.1, 10: 20.7} path = "data/resampled/" for vsini in [1, 5, 10]: # name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini) __, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path) assert np.round(p1, 1).value == published_results[vsini]
""" To test if the new code produces the same precision values on the published results.""" from __future__ import division, print_function import pytest import numpy as np import eniric.Qcalculator as Q import eniric.IOmodule as IO from bin.prec_1 import calc_prec1 # For python2.X compatibility file_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError) path = "data/Published_Results/resampled/" @pytest.mark.xfail(raises=file_error_to_catch) # Data file may not exist def test_presicion_1(): """ New precision 1 test that works.""" published_results = {1: 3.8, 5: 9.1, 10: 20.7} path = "data/resampled/" for vsini in [1, 5, 10]: # name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini) __, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path) # assert np.round(p1, 1).value == published_results[vsini] assert np.round(100 * p1, 1).value == published_results[vsini] # With incorect normalization
Add known offset for known bad calibration.
Add known offset for known bad calibration. Former-commit-id: afa3d6a66e32bbcc2b20f00f7e63fba5cb45882e [formerly 0470ca22b8a24205d2eb1c66caee912c990da0b3] [formerly c23210f4056c27e61708da2f2440bce3eda151a8 [formerly 5c0a6b9c0fefd2b88b9382d4a6ed98d9eac626df]] Former-commit-id: 8bfdaa1f7940b26aee05f20e801616f4a8d1d55d [formerly 1c85db5b2b87b73dfb28a1db171ff79a69e3a24a] Former-commit-id: d02a26b263c5c59776a35fc130e5c96b7ac30f5d
Python
mit
jason-neal/eniric,jason-neal/eniric
""" To test if the new code produces the same precision values on the published results.""" from __future__ import division, print_function import pytest import numpy as np import eniric.Qcalculator as Q import eniric.IOmodule as IO from bin.prec_1 import calc_prec1 # For python2.X compatibility file_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError) path = "data/Published_Results/resampled/" @pytest.mark.xfail(raises=file_error_to_catch) # Data file may not exist def test_presicion_1(): """ New precision 1 test that works.""" published_results = {1: 3.8, 5: 9.1, 10: 20.7} path = "data/resampled/" for vsini in [1, 5, 10]: # name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini) __, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path) - assert np.round(p1, 1).value == published_results[vsini] + # assert np.round(p1, 1).value == published_results[vsini] + assert np.round(100 * p1, 1).value == published_results[vsini] # With incorect normalization
Add known offset for known bad calibration.
## Code Before: """ To test if the new code produces the same precision values on the published results.""" from __future__ import division, print_function import pytest import numpy as np import eniric.Qcalculator as Q import eniric.IOmodule as IO from bin.prec_1 import calc_prec1 # For python2.X compatibility file_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError) path = "data/Published_Results/resampled/" @pytest.mark.xfail(raises=file_error_to_catch) # Data file may not exist def test_presicion_1(): """ New precision 1 test that works.""" published_results = {1: 3.8, 5: 9.1, 10: 20.7} path = "data/resampled/" for vsini in [1, 5, 10]: # name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini) __, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path) assert np.round(p1, 1).value == published_results[vsini] ## Instruction: Add known offset for known bad calibration. ## Code After: """ To test if the new code produces the same precision values on the published results.""" from __future__ import division, print_function import pytest import numpy as np import eniric.Qcalculator as Q import eniric.IOmodule as IO from bin.prec_1 import calc_prec1 # For python2.X compatibility file_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError) path = "data/Published_Results/resampled/" @pytest.mark.xfail(raises=file_error_to_catch) # Data file may not exist def test_presicion_1(): """ New precision 1 test that works.""" published_results = {1: 3.8, 5: 9.1, 10: 20.7} path = "data/resampled/" for vsini in [1, 5, 10]: # name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini) __, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path) # assert np.round(p1, 1).value == published_results[vsini] assert np.round(100 * p1, 1).value == published_results[vsini] # With incorect normalization
f3df3b2b8e1167e953457a85f2297d28b6a39729
examples/Micro.Blog/microblog.py
examples/Micro.Blog/microblog.py
from getpass import getpass from bessie import BaseClient import config class MicroBlogApi(BaseClient): endpoints = config.available_endpoints separator = '/' base_url='https://micro.blog' def __init__(self, path='', token=''): self.token = token super(self.__class__, self).__init__(path, token=token) # override method from BaseClient to inject Authorization header def _prepare_request(self): super(self.__class__, self)._prepare_request() self.request.headers['Authorization'] = 'Token {}'.format(self.token) if __name__ == '__main__': token = getpass('Token... ') mba = MicroBlogApi(token=token) # GET - https://micro.blog/posts/all posts = mba.posts.all.get() print(posts.status_code, posts.reason) print(posts.json())
from getpass import getpass from bessie import BaseClient import config class MicroBlogApi(BaseClient): endpoints = config.available_endpoints separator = '/' base_url='https://micro.blog' def __init__(self, path='', path_params=None, token=''): self.token = token super(self.__class__, self).__init__(path, path_params, token=token) # override method from BaseClient to inject Authorization header def _prepare_request(self): super(self.__class__, self)._prepare_request() self.request.headers['Authorization'] = 'Token {}'.format(self.token) if __name__ == '__main__': token = getpass('Token... ') mba = MicroBlogApi(token=token) # GET - https://micro.blog/posts/all posts = mba.posts.all.get() print(posts.status_code, posts.reason) print(posts.json())
Include path_params in override constructor
Include path_params in override constructor
Python
mit
andymitchhank/bessie
from getpass import getpass from bessie import BaseClient import config class MicroBlogApi(BaseClient): endpoints = config.available_endpoints separator = '/' base_url='https://micro.blog' - def __init__(self, path='', token=''): + def __init__(self, path='', path_params=None, token=''): self.token = token - super(self.__class__, self).__init__(path, token=token) + super(self.__class__, self).__init__(path, path_params, token=token) # override method from BaseClient to inject Authorization header def _prepare_request(self): super(self.__class__, self)._prepare_request() self.request.headers['Authorization'] = 'Token {}'.format(self.token) if __name__ == '__main__': token = getpass('Token... ') mba = MicroBlogApi(token=token) # GET - https://micro.blog/posts/all posts = mba.posts.all.get() print(posts.status_code, posts.reason) print(posts.json())
Include path_params in override constructor
## Code Before: from getpass import getpass from bessie import BaseClient import config class MicroBlogApi(BaseClient): endpoints = config.available_endpoints separator = '/' base_url='https://micro.blog' def __init__(self, path='', token=''): self.token = token super(self.__class__, self).__init__(path, token=token) # override method from BaseClient to inject Authorization header def _prepare_request(self): super(self.__class__, self)._prepare_request() self.request.headers['Authorization'] = 'Token {}'.format(self.token) if __name__ == '__main__': token = getpass('Token... ') mba = MicroBlogApi(token=token) # GET - https://micro.blog/posts/all posts = mba.posts.all.get() print(posts.status_code, posts.reason) print(posts.json()) ## Instruction: Include path_params in override constructor ## Code After: from getpass import getpass from bessie import BaseClient import config class MicroBlogApi(BaseClient): endpoints = config.available_endpoints separator = '/' base_url='https://micro.blog' def __init__(self, path='', path_params=None, token=''): self.token = token super(self.__class__, self).__init__(path, path_params, token=token) # override method from BaseClient to inject Authorization header def _prepare_request(self): super(self.__class__, self)._prepare_request() self.request.headers['Authorization'] = 'Token {}'.format(self.token) if __name__ == '__main__': token = getpass('Token... ') mba = MicroBlogApi(token=token) # GET - https://micro.blog/posts/all posts = mba.posts.all.get() print(posts.status_code, posts.reason) print(posts.json())
c9980756dcee82cc570208e73ec1a2112aea0155
tvtk/tests/test_scene.py
tvtk/tests/test_scene.py
# Authors: Deepak Surti, Ioannis Tziakos # Copyright (c) 2015, Enthought, Inc. # License: BSD Style. import unittest import weakref import gc from traits.etsconfig.api import ETSConfig from tvtk.pyface.scene import Scene from tvtk.tests.common import restore_gc_state class TestScene(unittest.TestCase): @unittest.skipIf( ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)') def test_scene_garbage_collected(self): # given scene_collected = [] scene_weakref = None def scene_collected_callback(weakref): scene_collected.append(True) def do(): scene = Scene() reference = weakref.ref(scene, scene_collected_callback) scene.close() return reference # when with restore_gc_state(): gc.disable() scene_weakref = do() # The Scene should have been collected. self.assertTrue(scene_collected[0]) if __name__ == "__main__": unittest.main()
# Authors: Deepak Surti, Ioannis Tziakos # Copyright (c) 2015, Enthought, Inc. # License: BSD Style. import unittest import weakref import gc from traits.etsconfig.api import ETSConfig from tvtk.pyface.scene import Scene from tvtk.tests.common import restore_gc_state class TestScene(unittest.TestCase): @unittest.skipIf( ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)') def test_scene_garbage_collected(self): # given scene_collected = [] scene_weakref = None def scene_collected_callback(weakref): scene_collected.append(True) def do(): scene = Scene() reference = weakref.ref(scene, scene_collected_callback) scene.close() return reference # when with restore_gc_state(): gc.disable() scene_weakref = do() # The Scene should have been collected. self.assertTrue(scene_collected[0]) self.assertIsNone(scene_weakref()) if __name__ == "__main__": unittest.main()
Add weakref assertion in test case
Add weakref assertion in test case
Python
bsd-3-clause
alexandreleroux/mayavi,dmsurti/mayavi,dmsurti/mayavi,alexandreleroux/mayavi,liulion/mayavi,liulion/mayavi
# Authors: Deepak Surti, Ioannis Tziakos # Copyright (c) 2015, Enthought, Inc. # License: BSD Style. import unittest import weakref import gc from traits.etsconfig.api import ETSConfig from tvtk.pyface.scene import Scene from tvtk.tests.common import restore_gc_state class TestScene(unittest.TestCase): @unittest.skipIf( ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)') def test_scene_garbage_collected(self): # given scene_collected = [] scene_weakref = None def scene_collected_callback(weakref): scene_collected.append(True) def do(): scene = Scene() reference = weakref.ref(scene, scene_collected_callback) scene.close() return reference # when with restore_gc_state(): gc.disable() scene_weakref = do() # The Scene should have been collected. self.assertTrue(scene_collected[0]) + self.assertIsNone(scene_weakref()) if __name__ == "__main__": unittest.main()
Add weakref assertion in test case
## Code Before: # Authors: Deepak Surti, Ioannis Tziakos # Copyright (c) 2015, Enthought, Inc. # License: BSD Style. import unittest import weakref import gc from traits.etsconfig.api import ETSConfig from tvtk.pyface.scene import Scene from tvtk.tests.common import restore_gc_state class TestScene(unittest.TestCase): @unittest.skipIf( ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)') def test_scene_garbage_collected(self): # given scene_collected = [] scene_weakref = None def scene_collected_callback(weakref): scene_collected.append(True) def do(): scene = Scene() reference = weakref.ref(scene, scene_collected_callback) scene.close() return reference # when with restore_gc_state(): gc.disable() scene_weakref = do() # The Scene should have been collected. self.assertTrue(scene_collected[0]) if __name__ == "__main__": unittest.main() ## Instruction: Add weakref assertion in test case ## Code After: # Authors: Deepak Surti, Ioannis Tziakos # Copyright (c) 2015, Enthought, Inc. # License: BSD Style. import unittest import weakref import gc from traits.etsconfig.api import ETSConfig from tvtk.pyface.scene import Scene from tvtk.tests.common import restore_gc_state class TestScene(unittest.TestCase): @unittest.skipIf( ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)') def test_scene_garbage_collected(self): # given scene_collected = [] scene_weakref = None def scene_collected_callback(weakref): scene_collected.append(True) def do(): scene = Scene() reference = weakref.ref(scene, scene_collected_callback) scene.close() return reference # when with restore_gc_state(): gc.disable() scene_weakref = do() # The Scene should have been collected. self.assertTrue(scene_collected[0]) self.assertIsNone(scene_weakref()) if __name__ == "__main__": unittest.main()
74b2883c3371304e8f5ea95b0454fb006d85ba3d
mapentity/urls.py
mapentity/urls.py
from django.conf import settings from django.conf.urls import patterns, url from . import app_settings from .views import (map_screenshot, convert, history_delete, serve_secure_media, JSSettings) _MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')[1:] urlpatterns = patterns( '', url(r'^%s(?P<path>.*?)$' % _MEDIA_URL, serve_secure_media), url(r'^map_screenshot/$', map_screenshot, name='map_screenshot'), url(r'^convert/$', convert, name='convert'), url(r'^history/delete/$', history_delete, name='history_delete'), # See default value in app_settings.JS_SETTINGS. # Will be overriden, most probably. url(r'^api/settings.json$', JSSettings.as_view(), name='js_settings'), )
from django.conf import settings from django.conf.urls import patterns, url from . import app_settings from .views import (map_screenshot, convert, history_delete, serve_secure_media, JSSettings) _MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '') if _MEDIA_URL.startswith('/'): _MEDIA_URL = _MEDIA_URL[1:] if _MEDIA_URL.endswith('/'): _MEDIA_URL = _MEDIA_URL[:-1] urlpatterns = patterns( '', url(r'^%s(?P<path>.*?)$' % _MEDIA_URL, serve_secure_media), url(r'^map_screenshot/$', map_screenshot, name='map_screenshot'), url(r'^convert/$', convert, name='convert'), url(r'^history/delete/$', history_delete, name='history_delete'), # See default value in app_settings.JS_SETTINGS. # Will be overriden, most probably. url(r'^api/settings.json$', JSSettings.as_view(), name='js_settings'), )
Remove leading and trailing slash of MEDIA_URL
Remove leading and trailing slash of MEDIA_URL Conflicts: mapentity/static/mapentity/Leaflet.label
Python
bsd-3-clause
Anaethelion/django-mapentity,Anaethelion/django-mapentity,makinacorpus/django-mapentity,makinacorpus/django-mapentity,Anaethelion/django-mapentity,makinacorpus/django-mapentity
from django.conf import settings from django.conf.urls import patterns, url from . import app_settings from .views import (map_screenshot, convert, history_delete, serve_secure_media, JSSettings) - _MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')[1:] + _MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '') + if _MEDIA_URL.startswith('/'): + _MEDIA_URL = _MEDIA_URL[1:] + if _MEDIA_URL.endswith('/'): + _MEDIA_URL = _MEDIA_URL[:-1] urlpatterns = patterns( '', url(r'^%s(?P<path>.*?)$' % _MEDIA_URL, serve_secure_media), url(r'^map_screenshot/$', map_screenshot, name='map_screenshot'), url(r'^convert/$', convert, name='convert'), url(r'^history/delete/$', history_delete, name='history_delete'), # See default value in app_settings.JS_SETTINGS. # Will be overriden, most probably. url(r'^api/settings.json$', JSSettings.as_view(), name='js_settings'), )
Remove leading and trailing slash of MEDIA_URL
## Code Before: from django.conf import settings from django.conf.urls import patterns, url from . import app_settings from .views import (map_screenshot, convert, history_delete, serve_secure_media, JSSettings) _MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')[1:] urlpatterns = patterns( '', url(r'^%s(?P<path>.*?)$' % _MEDIA_URL, serve_secure_media), url(r'^map_screenshot/$', map_screenshot, name='map_screenshot'), url(r'^convert/$', convert, name='convert'), url(r'^history/delete/$', history_delete, name='history_delete'), # See default value in app_settings.JS_SETTINGS. # Will be overriden, most probably. url(r'^api/settings.json$', JSSettings.as_view(), name='js_settings'), ) ## Instruction: Remove leading and trailing slash of MEDIA_URL ## Code After: from django.conf import settings from django.conf.urls import patterns, url from . import app_settings from .views import (map_screenshot, convert, history_delete, serve_secure_media, JSSettings) _MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '') if _MEDIA_URL.startswith('/'): _MEDIA_URL = _MEDIA_URL[1:] if _MEDIA_URL.endswith('/'): _MEDIA_URL = _MEDIA_URL[:-1] urlpatterns = patterns( '', url(r'^%s(?P<path>.*?)$' % _MEDIA_URL, serve_secure_media), url(r'^map_screenshot/$', map_screenshot, name='map_screenshot'), url(r'^convert/$', convert, name='convert'), url(r'^history/delete/$', history_delete, name='history_delete'), # See default value in app_settings.JS_SETTINGS. # Will be overriden, most probably. url(r'^api/settings.json$', JSSettings.as_view(), name='js_settings'), )
7dd17cc10f7e0857ab3017177d6c4abeb115ff07
south/models.py
south/models.py
from django.db import models from south.db import DEFAULT_DB_ALIAS class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) @classmethod def for_migration(cls, migration, database): try: # Switch on multi-db-ness if database != DEFAULT_DB_ALIAS: # Django 1.2 objects = cls.objects.using(database) else: # Django <= 1.1 objects = cls.objects return objects.get( app_name=migration.app_label(), migration=migration.name(), ) except cls.DoesNotExist: return cls( app_name=migration.app_label(), migration=migration.name(), ) def get_migrations(self): from south.migration.base import Migrations return Migrations(self.app_name) def get_migration(self): return self.get_migrations().migration(self.migration) def __str__(self): return "<%s: %s>" % (self.app_name, self.migration)
from django.db import models from south.db import DEFAULT_DB_ALIAS # If we detect Django 1.7 or higher, then exit # Placed here so it's guaranteed to be imported on Django start import django if django.VERSION[0] > 1 or (django.VERSION[0] == 1 and django.VERSION[1] > 6): raise RuntimeError("South does not support Django 1.7 or higher. Please use native Django migrations.") class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) @classmethod def for_migration(cls, migration, database): try: # Switch on multi-db-ness if database != DEFAULT_DB_ALIAS: # Django 1.2 objects = cls.objects.using(database) else: # Django <= 1.1 objects = cls.objects return objects.get( app_name=migration.app_label(), migration=migration.name(), ) except cls.DoesNotExist: return cls( app_name=migration.app_label(), migration=migration.name(), ) def get_migrations(self): from south.migration.base import Migrations return Migrations(self.app_name) def get_migration(self): return self.get_migrations().migration(self.migration) def __str__(self): return "<%s: %s>" % (self.app_name, self.migration)
Add explicit version check for Django 1.7 or above
Add explicit version check for Django 1.7 or above
Python
apache-2.0
smartfile/django-south,smartfile/django-south
from django.db import models from south.db import DEFAULT_DB_ALIAS + + # If we detect Django 1.7 or higher, then exit + # Placed here so it's guaranteed to be imported on Django start + import django + if django.VERSION[0] > 1 or (django.VERSION[0] == 1 and django.VERSION[1] > 6): + raise RuntimeError("South does not support Django 1.7 or higher. Please use native Django migrations.") class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) @classmethod def for_migration(cls, migration, database): try: # Switch on multi-db-ness if database != DEFAULT_DB_ALIAS: # Django 1.2 objects = cls.objects.using(database) else: # Django <= 1.1 objects = cls.objects return objects.get( app_name=migration.app_label(), migration=migration.name(), ) except cls.DoesNotExist: return cls( app_name=migration.app_label(), migration=migration.name(), ) def get_migrations(self): from south.migration.base import Migrations return Migrations(self.app_name) def get_migration(self): return self.get_migrations().migration(self.migration) def __str__(self): return "<%s: %s>" % (self.app_name, self.migration)
Add explicit version check for Django 1.7 or above
## Code Before: from django.db import models from south.db import DEFAULT_DB_ALIAS class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) @classmethod def for_migration(cls, migration, database): try: # Switch on multi-db-ness if database != DEFAULT_DB_ALIAS: # Django 1.2 objects = cls.objects.using(database) else: # Django <= 1.1 objects = cls.objects return objects.get( app_name=migration.app_label(), migration=migration.name(), ) except cls.DoesNotExist: return cls( app_name=migration.app_label(), migration=migration.name(), ) def get_migrations(self): from south.migration.base import Migrations return Migrations(self.app_name) def get_migration(self): return self.get_migrations().migration(self.migration) def __str__(self): return "<%s: %s>" % (self.app_name, self.migration) ## Instruction: Add explicit version check for Django 1.7 or above ## Code After: from django.db import models from south.db import DEFAULT_DB_ALIAS # If we detect Django 1.7 or higher, then exit # Placed here so it's guaranteed to be imported on Django start import django if django.VERSION[0] > 1 or (django.VERSION[0] == 1 and django.VERSION[1] > 6): raise RuntimeError("South does not support Django 1.7 or higher. Please use native Django migrations.") class MigrationHistory(models.Model): app_name = models.CharField(max_length=255) migration = models.CharField(max_length=255) applied = models.DateTimeField(blank=True) @classmethod def for_migration(cls, migration, database): try: # Switch on multi-db-ness if database != DEFAULT_DB_ALIAS: # Django 1.2 objects = cls.objects.using(database) else: # Django <= 1.1 objects = cls.objects return objects.get( app_name=migration.app_label(), migration=migration.name(), ) except cls.DoesNotExist: return cls( app_name=migration.app_label(), migration=migration.name(), ) def get_migrations(self): from south.migration.base import Migrations return Migrations(self.app_name) def get_migration(self): return self.get_migrations().migration(self.migration) def __str__(self): return "<%s: %s>" % (self.app_name, self.migration)
fe85f1f135d2a7831afee6c8ab0bad394beb8aba
src/ais.py
src/ais.py
class MonsterAI(object): def __init__(self, level): self.owner = None self.level = level def take_turn(self): self.owner.log.log_begin_turn(self.owner.oid) self._take_turn() def _take_turn(self): raise NotImplementedError('Subclass this before usage please.') class TestMonster(MonsterAI): def _take_turn(self): enemies = self.level.get_objects_outside_faction(self.owner.faction) if len(enemies) > 0: distances = {self.owner.distance_to(e): e for e in enemies} closest_distance = min(distances) closest_enemy = distances[closest_distance] if closest_distance <= 1.5: self.owner.fighter.attack(closest_enemy) else: self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level)
from src.constants import * class MonsterAI(object): def __init__(self, level): self.owner = None self.level = level def take_turn(self): self.owner.log.log_begin_turn(self.owner.oid) self._take_turn() def _take_turn(self): raise NotImplementedError('Subclass this before usage please.') class TestMonster(MonsterAI): def _take_turn(self): enemies = self.level.get_objects_outside_faction(self.owner.faction) if len(enemies) > 0: # Identify the closest enemy distances = {self.owner.distance_to(e): e for e in enemies} closest_distance = min(distances) closest_enemy = distances[closest_distance] # Inspect inventory for usable items if self.owner.inventory is not None: usable = self.owner.inventory.get_usable_items() throwing_items = [i for i in usable if i.item.can_use(self.owner, closest_enemy, self.level)] else: throwing_items = [] # Attack if adjacent if closest_distance <= 1.5: self.owner.fighter.attack(closest_enemy) # Throw if you have a throwing item if len(throwing_items) > 0: throwing_items[0].item.use(self.owner, closest_enemy, self.level) else: self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level)
Add throwing item usage to test AI
Add throwing item usage to test AI Unforutnately the item isn't evicted from the inventory on usage, so the guy with the throwing item can kill everybody, but it's working - he does throw it!
Python
mit
MoyTW/RL_Arena_Experiment
+ from src.constants import * + + class MonsterAI(object): def __init__(self, level): self.owner = None self.level = level def take_turn(self): self.owner.log.log_begin_turn(self.owner.oid) self._take_turn() def _take_turn(self): raise NotImplementedError('Subclass this before usage please.') class TestMonster(MonsterAI): def _take_turn(self): + enemies = self.level.get_objects_outside_faction(self.owner.faction) + if len(enemies) > 0: + # Identify the closest enemy distances = {self.owner.distance_to(e): e for e in enemies} closest_distance = min(distances) closest_enemy = distances[closest_distance] + + # Inspect inventory for usable items + if self.owner.inventory is not None: + usable = self.owner.inventory.get_usable_items() + throwing_items = [i for i in usable if i.item.can_use(self.owner, closest_enemy, self.level)] + else: + throwing_items = [] + + # Attack if adjacent if closest_distance <= 1.5: self.owner.fighter.attack(closest_enemy) + # Throw if you have a throwing item + if len(throwing_items) > 0: + throwing_items[0].item.use(self.owner, closest_enemy, self.level) else: self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level)
Add throwing item usage to test AI
## Code Before: class MonsterAI(object): def __init__(self, level): self.owner = None self.level = level def take_turn(self): self.owner.log.log_begin_turn(self.owner.oid) self._take_turn() def _take_turn(self): raise NotImplementedError('Subclass this before usage please.') class TestMonster(MonsterAI): def _take_turn(self): enemies = self.level.get_objects_outside_faction(self.owner.faction) if len(enemies) > 0: distances = {self.owner.distance_to(e): e for e in enemies} closest_distance = min(distances) closest_enemy = distances[closest_distance] if closest_distance <= 1.5: self.owner.fighter.attack(closest_enemy) else: self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level) ## Instruction: Add throwing item usage to test AI ## Code After: from src.constants import * class MonsterAI(object): def __init__(self, level): self.owner = None self.level = level def take_turn(self): self.owner.log.log_begin_turn(self.owner.oid) self._take_turn() def _take_turn(self): raise NotImplementedError('Subclass this before usage please.') class TestMonster(MonsterAI): def _take_turn(self): enemies = self.level.get_objects_outside_faction(self.owner.faction) if len(enemies) > 0: # Identify the closest enemy distances = {self.owner.distance_to(e): e for e in enemies} closest_distance = min(distances) closest_enemy = distances[closest_distance] # Inspect inventory for usable items if self.owner.inventory is not None: usable = self.owner.inventory.get_usable_items() throwing_items = [i for i in usable if i.item.can_use(self.owner, closest_enemy, self.level)] else: throwing_items = [] # Attack if adjacent if closest_distance <= 1.5: self.owner.fighter.attack(closest_enemy) # Throw if you have a throwing item if len(throwing_items) > 0: throwing_items[0].item.use(self.owner, closest_enemy, self.level) else: self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level)
fe78335e4f469e22f9a1de7a1e5ddd52021a7f0f
linesep.py
linesep.py
STARTER = -1 SEPARATOR = 0 TERMINATOR = 1 def readlines(fp, sep, mode=TERMINATOR, retain=True, size=512): if mode < 0: return _readlines_start(fp, sep, retain, size) elif mode == 0: return _readlines_sep(fp, sep, size) else: return _readlines_term(fp, sep, retain, size) def _readlines_start(fp, sep, retain=True, size=512): # Omits empty leading entry entries = _readlines_sep(fp, sep, size=size) e = next(entries) if e: yield e for e in entries: if retain: e = sep + e yield e def _readlines_sep(fp, sep, size=512): buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: yield l yield buff def _readlines_term(fp, sep, retain=True, size=512): # Omits empty trailing entry buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: if retain: l += sep yield l if buff: yield buff
def read_begun(fp, sep, retain=True, size=512): # Omits empty leading entry entries = read_separated(fp, sep, size=size) e = next(entries) if e: yield e for e in entries: if retain: e = sep + e yield e def read_separated(fp, sep, size=512): buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: yield l yield buff def read_terminated(fp, sep, retain=True, size=512): # Omits empty trailing entry buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: if retain: l += sep yield l if buff: yield buff
Use three public functions instead of one
Use three public functions instead of one
Python
mit
jwodder/linesep
- STARTER = -1 - SEPARATOR = 0 - TERMINATOR = 1 - - def readlines(fp, sep, mode=TERMINATOR, retain=True, size=512): - if mode < 0: - return _readlines_start(fp, sep, retain, size) - elif mode == 0: - return _readlines_sep(fp, sep, size) - else: - return _readlines_term(fp, sep, retain, size) - - def _readlines_start(fp, sep, retain=True, size=512): + def read_begun(fp, sep, retain=True, size=512): # Omits empty leading entry - entries = _readlines_sep(fp, sep, size=size) + entries = read_separated(fp, sep, size=size) e = next(entries) if e: yield e for e in entries: if retain: e = sep + e yield e - def _readlines_sep(fp, sep, size=512): + def read_separated(fp, sep, size=512): buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: yield l yield buff - def _readlines_term(fp, sep, retain=True, size=512): + def read_terminated(fp, sep, retain=True, size=512): # Omits empty trailing entry buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: if retain: l += sep yield l if buff: yield buff
Use three public functions instead of one
## Code Before: STARTER = -1 SEPARATOR = 0 TERMINATOR = 1 def readlines(fp, sep, mode=TERMINATOR, retain=True, size=512): if mode < 0: return _readlines_start(fp, sep, retain, size) elif mode == 0: return _readlines_sep(fp, sep, size) else: return _readlines_term(fp, sep, retain, size) def _readlines_start(fp, sep, retain=True, size=512): # Omits empty leading entry entries = _readlines_sep(fp, sep, size=size) e = next(entries) if e: yield e for e in entries: if retain: e = sep + e yield e def _readlines_sep(fp, sep, size=512): buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: yield l yield buff def _readlines_term(fp, sep, retain=True, size=512): # Omits empty trailing entry buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: if retain: l += sep yield l if buff: yield buff ## Instruction: Use three public functions instead of one ## Code After: def read_begun(fp, sep, retain=True, size=512): # Omits empty leading entry entries = read_separated(fp, sep, size=size) e = next(entries) if e: yield e for e in entries: if retain: e = sep + e yield e def read_separated(fp, sep, size=512): buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: yield l yield buff def read_terminated(fp, sep, retain=True, size=512): # Omits empty trailing entry buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: if retain: l += sep yield l if buff: yield buff
e9ae6b7f92ee0a4585adc11e695cc15cbe425e23
morepath/app.py
morepath/app.py
from .interfaces import IRoot, IApp from .publish import publish from .request import Request from .traject import Traject from comparch import ClassRegistry, Lookup, ChainClassLookup known_apps = {} class App(IApp, ClassRegistry): def __init__(self, name='', parent=None): super(App, self).__init__() self.name = name self.root_model = None self.root_obj = None self.child_apps = {} self.parent = parent self.traject = Traject() if self.parent is not None: parent.add_child(self) def add_child(self, app): self.child_apps[app.name] = app self.traject.register(app.name, lambda: app, conflicting=True) def class_lookup(self): if self.parent is None: return ChainClassLookup(self, global_app) return ChainClassLookup(self, self.parent.class_lookup()) def __call__(self, environ, start_response): # XXX do caching lookup where? lookup = Lookup(self.class_lookup()) request = Request(environ) request.lookup = lookup response = publish(request, self, lookup) return response(environ, start_response) global_app = App() # XXX this shouldn't be here but be the root of the global app class Root(IRoot): pass root = Root()
from .interfaces import IRoot, IApp from .publish import publish from .request import Request from .traject import Traject from comparch import ClassRegistry, Lookup, ChainClassLookup known_apps = {} class App(IApp, ClassRegistry): def __init__(self, name='', parent=None): super(App, self).__init__() self.name = name self.root_model = None self.root_obj = None self.child_apps = {} self.parent = parent self.traject = Traject() if self.parent is not None: parent.add_child(self) def add_child(self, app): self.child_apps[app.name] = app self.traject.register(app.name, lambda: app, conflicting=True) def class_lookup(self): if self.parent is None: return ChainClassLookup(self, global_app) return ChainClassLookup(self, self.parent.class_lookup()) def __call__(self, environ, start_response): # XXX do caching lookup where? lookup = Lookup(self.class_lookup()) request = Request(environ) request.lookup = lookup response = publish(request, self, lookup) return response(environ, start_response) global_app = App()
Remove root that wasn't used.
Remove root that wasn't used.
Python
bsd-3-clause
faassen/morepath,morepath/morepath,taschini/morepath
from .interfaces import IRoot, IApp from .publish import publish from .request import Request from .traject import Traject from comparch import ClassRegistry, Lookup, ChainClassLookup known_apps = {} class App(IApp, ClassRegistry): def __init__(self, name='', parent=None): super(App, self).__init__() self.name = name self.root_model = None self.root_obj = None self.child_apps = {} self.parent = parent self.traject = Traject() if self.parent is not None: parent.add_child(self) def add_child(self, app): self.child_apps[app.name] = app self.traject.register(app.name, lambda: app, conflicting=True) def class_lookup(self): if self.parent is None: return ChainClassLookup(self, global_app) return ChainClassLookup(self, self.parent.class_lookup()) def __call__(self, environ, start_response): # XXX do caching lookup where? lookup = Lookup(self.class_lookup()) request = Request(environ) request.lookup = lookup response = publish(request, self, lookup) return response(environ, start_response) global_app = App() - # XXX this shouldn't be here but be the root of the global app - class Root(IRoot): - pass - root = Root() -
Remove root that wasn't used.
## Code Before: from .interfaces import IRoot, IApp from .publish import publish from .request import Request from .traject import Traject from comparch import ClassRegistry, Lookup, ChainClassLookup known_apps = {} class App(IApp, ClassRegistry): def __init__(self, name='', parent=None): super(App, self).__init__() self.name = name self.root_model = None self.root_obj = None self.child_apps = {} self.parent = parent self.traject = Traject() if self.parent is not None: parent.add_child(self) def add_child(self, app): self.child_apps[app.name] = app self.traject.register(app.name, lambda: app, conflicting=True) def class_lookup(self): if self.parent is None: return ChainClassLookup(self, global_app) return ChainClassLookup(self, self.parent.class_lookup()) def __call__(self, environ, start_response): # XXX do caching lookup where? lookup = Lookup(self.class_lookup()) request = Request(environ) request.lookup = lookup response = publish(request, self, lookup) return response(environ, start_response) global_app = App() # XXX this shouldn't be here but be the root of the global app class Root(IRoot): pass root = Root() ## Instruction: Remove root that wasn't used. ## Code After: from .interfaces import IRoot, IApp from .publish import publish from .request import Request from .traject import Traject from comparch import ClassRegistry, Lookup, ChainClassLookup known_apps = {} class App(IApp, ClassRegistry): def __init__(self, name='', parent=None): super(App, self).__init__() self.name = name self.root_model = None self.root_obj = None self.child_apps = {} self.parent = parent self.traject = Traject() if self.parent is not None: parent.add_child(self) def add_child(self, app): self.child_apps[app.name] = app self.traject.register(app.name, lambda: app, conflicting=True) def class_lookup(self): if self.parent is None: return ChainClassLookup(self, global_app) return ChainClassLookup(self, self.parent.class_lookup()) def __call__(self, environ, start_response): # XXX do caching lookup where? lookup = Lookup(self.class_lookup()) request = Request(environ) request.lookup = lookup response = publish(request, self, lookup) return response(environ, start_response) global_app = App()
a7938ed9ec814fa9cf53272ceb65e84d11d50dc1
moto/s3/urls.py
moto/s3/urls.py
from __future__ import unicode_literals from moto.compat import OrderedDict from .responses import S3ResponseInstance url_bases = [ "https?://s3(.*).amazonaws.com", "https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com" ] url_paths = OrderedDict([ # subdomain bucket ('{0}/$', S3ResponseInstance.bucket_response), # subdomain key of path-based bucket ('{0}/(?P<key_or_bucket_name>.+)', S3ResponseInstance.ambiguous_response), # path-based bucket + key ('{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)', S3ResponseInstance.key_response), ])
from __future__ import unicode_literals from .responses import S3ResponseInstance url_bases = [ "https?://s3(.*).amazonaws.com", "https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com" ] url_paths = { # subdomain bucket '{0}/$': S3ResponseInstance.bucket_response, # subdomain key of path-based bucket '{0}/(?P<key_or_bucket_name>[^/]+)/?$': S3ResponseInstance.ambiguous_response, # path-based bucket + key '{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)': S3ResponseInstance.key_response, }
Fix s3 url regex to ensure path-based bucket and key does not catch.
Fix s3 url regex to ensure path-based bucket and key does not catch.
Python
apache-2.0
william-richard/moto,kefo/moto,botify-labs/moto,2rs2ts/moto,dbfr3qs/moto,im-auld/moto,william-richard/moto,william-richard/moto,Affirm/moto,kefo/moto,botify-labs/moto,Brett55/moto,ZuluPro/moto,ZuluPro/moto,okomestudio/moto,spulec/moto,whummer/moto,william-richard/moto,kefo/moto,kefo/moto,ZuluPro/moto,dbfr3qs/moto,heddle317/moto,Brett55/moto,whummer/moto,mrucci/moto,gjtempleton/moto,rocky4570/moto,spulec/moto,whummer/moto,tootedom/moto,Brett55/moto,heddle317/moto,gjtempleton/moto,IlyaSukhanov/moto,botify-labs/moto,2rs2ts/moto,spulec/moto,william-richard/moto,okomestudio/moto,ZuluPro/moto,okomestudio/moto,whummer/moto,gjtempleton/moto,Affirm/moto,rocky4570/moto,silveregg/moto,2rs2ts/moto,spulec/moto,botify-labs/moto,okomestudio/moto,dbfr3qs/moto,heddle317/moto,whummer/moto,rocky4570/moto,Affirm/moto,dbfr3qs/moto,Brett55/moto,Brett55/moto,dbfr3qs/moto,spulec/moto,2rs2ts/moto,gjtempleton/moto,botify-labs/moto,botify-labs/moto,spulec/moto,whummer/moto,kefo/moto,Brett55/moto,Affirm/moto,braintreeps/moto,ZuluPro/moto,heddle317/moto,gjtempleton/moto,Affirm/moto,rocky4570/moto,okomestudio/moto,rocky4570/moto,Affirm/moto,heddle317/moto,2rs2ts/moto,dbfr3qs/moto,rocky4570/moto,ZuluPro/moto,william-richard/moto,riccardomc/moto,okomestudio/moto
from __future__ import unicode_literals - from moto.compat import OrderedDict from .responses import S3ResponseInstance url_bases = [ "https?://s3(.*).amazonaws.com", "https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com" ] - url_paths = OrderedDict([ + url_paths = { # subdomain bucket - ('{0}/$', S3ResponseInstance.bucket_response), + '{0}/$': S3ResponseInstance.bucket_response, # subdomain key of path-based bucket - ('{0}/(?P<key_or_bucket_name>.+)', S3ResponseInstance.ambiguous_response), + '{0}/(?P<key_or_bucket_name>[^/]+)/?$': S3ResponseInstance.ambiguous_response, # path-based bucket + key - ('{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)', S3ResponseInstance.key_response), + '{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)': S3ResponseInstance.key_response, - ]) + }
Fix s3 url regex to ensure path-based bucket and key does not catch.
## Code Before: from __future__ import unicode_literals from moto.compat import OrderedDict from .responses import S3ResponseInstance url_bases = [ "https?://s3(.*).amazonaws.com", "https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com" ] url_paths = OrderedDict([ # subdomain bucket ('{0}/$', S3ResponseInstance.bucket_response), # subdomain key of path-based bucket ('{0}/(?P<key_or_bucket_name>.+)', S3ResponseInstance.ambiguous_response), # path-based bucket + key ('{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)', S3ResponseInstance.key_response), ]) ## Instruction: Fix s3 url regex to ensure path-based bucket and key does not catch. ## Code After: from __future__ import unicode_literals from .responses import S3ResponseInstance url_bases = [ "https?://s3(.*).amazonaws.com", "https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com" ] url_paths = { # subdomain bucket '{0}/$': S3ResponseInstance.bucket_response, # subdomain key of path-based bucket '{0}/(?P<key_or_bucket_name>[^/]+)/?$': S3ResponseInstance.ambiguous_response, # path-based bucket + key '{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)': S3ResponseInstance.key_response, }
39ce4e74a6b7115a35260fa2722ace1792cb1780
python/count_triplets.py
python/count_triplets.py
import math import os import random import re import sys from collections import Counter def countTriplets(arr, r): potential_triplets_with_middle = Counter() potential_triplets_with_end = Counter() total_triplets = 0 for num in arr: # num completed potential_triplets_with_end[num] triplets if potential_triplets_with_end[num]: total_triplets += potential_triplets_with_end[num] # num can be the middle number in potential_triplets_with_middle[num] triplets if potential_triplets_with_middle[num]: potential_triplets_with_end[num * r] += potential_triplets_with_middle[num] # num can be the begining of a triplet potential_triplets_with_middle[num * r] += 1 print("num", num, " middle", potential_triplets_with_middle, " end", potential_triplets_with_end, " total", total_triplets) return total_triplets if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close()
import math import os import random import re import sys from collections import Counter def countTriplets(arr, r): potential_triplets_with_middle = Counter() potential_triplets_with_end = Counter() total_triplets = 0 for num in arr: # num completed potential_triplets_with_end[num] triplets if potential_triplets_with_end[num]: total_triplets += potential_triplets_with_end[num] # num can be the middle number in # potential_triplets_with_middle[num] triplets if potential_triplets_with_middle[num]: potential_triplets_with_end[num * r] += \ potential_triplets_with_middle[num] # num can be the begining of a triplet potential_triplets_with_middle[num * r] += 1 return total_triplets if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close()
Remove debug output and pycodestyle
Remove debug output and pycodestyle
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
import math import os import random import re import sys from collections import Counter + def countTriplets(arr, r): potential_triplets_with_middle = Counter() potential_triplets_with_end = Counter() total_triplets = 0 for num in arr: # num completed potential_triplets_with_end[num] triplets if potential_triplets_with_end[num]: total_triplets += potential_triplets_with_end[num] + # num can be the middle number in - # num can be the middle number in potential_triplets_with_middle[num] triplets + # potential_triplets_with_middle[num] triplets if potential_triplets_with_middle[num]: - potential_triplets_with_end[num * r] += potential_triplets_with_middle[num] + potential_triplets_with_end[num * r] += \ + potential_triplets_with_middle[num] # num can be the begining of a triplet potential_triplets_with_middle[num * r] += 1 - print("num", num, " middle", potential_triplets_with_middle, " end", potential_triplets_with_end, " total", total_triplets) return total_triplets if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close()
Remove debug output and pycodestyle
## Code Before: import math import os import random import re import sys from collections import Counter def countTriplets(arr, r): potential_triplets_with_middle = Counter() potential_triplets_with_end = Counter() total_triplets = 0 for num in arr: # num completed potential_triplets_with_end[num] triplets if potential_triplets_with_end[num]: total_triplets += potential_triplets_with_end[num] # num can be the middle number in potential_triplets_with_middle[num] triplets if potential_triplets_with_middle[num]: potential_triplets_with_end[num * r] += potential_triplets_with_middle[num] # num can be the begining of a triplet potential_triplets_with_middle[num * r] += 1 print("num", num, " middle", potential_triplets_with_middle, " end", potential_triplets_with_end, " total", total_triplets) return total_triplets if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close() ## Instruction: Remove debug output and pycodestyle ## Code After: import math import os import random import re import sys from collections import Counter def countTriplets(arr, r): potential_triplets_with_middle = Counter() potential_triplets_with_end = Counter() total_triplets = 0 for num in arr: # num completed potential_triplets_with_end[num] triplets if potential_triplets_with_end[num]: total_triplets += potential_triplets_with_end[num] # num can be the middle number in # potential_triplets_with_middle[num] triplets if potential_triplets_with_middle[num]: potential_triplets_with_end[num * r] += \ potential_triplets_with_middle[num] # num can be the begining of a triplet potential_triplets_with_middle[num * r] += 1 return total_triplets if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close()
5dd78f614e5882bc2a3fcae24117a26ee34371ac
register-result.py
register-result.py
import json import socket import sys if len(sys.argv) < 4: print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>") sys.exit(128) check_client = sys.argv[1] check_name = sys.argv[2] check_output = sys.argv[3] check_status = int(sys.argv[4]) check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000 # Our result dict result = dict() result['source'] = check_client result['name'] = check_name result['output'] = check_output result['status'] = check_status result['ttl'] = check_ttl # TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 3030) sock.connect(server_address) print (json.dumps(result)) socket.sendall(json.dumps(result))
import json import socket import sys if len(sys.argv) < 4: print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>") sys.exit(128) check_client = sys.argv[1] check_name = sys.argv[2] check_output = sys.argv[3] check_status = int(sys.argv[4]) check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000 # Our result dict result = dict() result['source'] = check_client result['name'] = check_name result['output'] = check_output result['status'] = check_status result['ttl'] = check_ttl # TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 3030) sock.connect(server_address) sock.sendall(json.dumps(result)) print (json.dumps(result))
Fix mistake with socket constructor
Fix mistake with socket constructor
Python
mit
panubo/docker-monitor,panubo/docker-monitor,panubo/docker-monitor
import json import socket import sys if len(sys.argv) < 4: print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>") sys.exit(128) check_client = sys.argv[1] check_name = sys.argv[2] check_output = sys.argv[3] check_status = int(sys.argv[4]) check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000 # Our result dict result = dict() result['source'] = check_client result['name'] = check_name result['output'] = check_output result['status'] = check_status result['ttl'] = check_ttl # TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 3030) sock.connect(server_address) + sock.sendall(json.dumps(result)) print (json.dumps(result)) - socket.sendall(json.dumps(result))
Fix mistake with socket constructor
## Code Before: import json import socket import sys if len(sys.argv) < 4: print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>") sys.exit(128) check_client = sys.argv[1] check_name = sys.argv[2] check_output = sys.argv[3] check_status = int(sys.argv[4]) check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000 # Our result dict result = dict() result['source'] = check_client result['name'] = check_name result['output'] = check_output result['status'] = check_status result['ttl'] = check_ttl # TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 3030) sock.connect(server_address) print (json.dumps(result)) socket.sendall(json.dumps(result)) ## Instruction: Fix mistake with socket constructor ## Code After: import json import socket import sys if len(sys.argv) < 4: print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>") sys.exit(128) check_client = sys.argv[1] check_name = sys.argv[2] check_output = sys.argv[3] check_status = int(sys.argv[4]) check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000 # Our result dict result = dict() result['source'] = check_client result['name'] = check_name result['output'] = check_output result['status'] = check_status result['ttl'] = check_ttl # TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 3030) sock.connect(server_address) sock.sendall(json.dumps(result)) print (json.dumps(result))
5e57dce84ffe7be7e699af1e2be953d5a65d8435
tests/test_module.py
tests/test_module.py
import sys import dill import test_mixins as module module.a = 1234 pik_mod = dill.dumps(module) module.a = 0 # remove module del sys.modules[module.__name__] del module module = dill.loads(pik_mod) assert module.a == 1234 assert module.double_add(1, 2, 3) == 2 * module.fx
import sys import dill import test_mixins as module cached = (module.__cached__ if hasattr(module, "__cached__") else module.__file__ + "c") module.a = 1234 pik_mod = dill.dumps(module) module.a = 0 # remove module del sys.modules[module.__name__] del module module = dill.loads(pik_mod) assert hasattr(module, "a") and module.a == 1234 assert module.double_add(1, 2, 3) == 2 * module.fx # clean up import os os.remove(cached) if os.path.exists("__pycache__") and not os.listdir("__pycache__"): os.removedirs("__pycache__")
Add code to clean up
Add code to clean up
Python
bsd-3-clause
wxiang7/dill,mindw/dill
import sys import dill import test_mixins as module + + cached = (module.__cached__ if hasattr(module, "__cached__") + else module.__file__ + "c") module.a = 1234 pik_mod = dill.dumps(module) module.a = 0 # remove module del sys.modules[module.__name__] del module module = dill.loads(pik_mod) - assert module.a == 1234 + assert hasattr(module, "a") and module.a == 1234 assert module.double_add(1, 2, 3) == 2 * module.fx + # clean up + import os + os.remove(cached) + if os.path.exists("__pycache__") and not os.listdir("__pycache__"): + os.removedirs("__pycache__") +
Add code to clean up
## Code Before: import sys import dill import test_mixins as module module.a = 1234 pik_mod = dill.dumps(module) module.a = 0 # remove module del sys.modules[module.__name__] del module module = dill.loads(pik_mod) assert module.a == 1234 assert module.double_add(1, 2, 3) == 2 * module.fx ## Instruction: Add code to clean up ## Code After: import sys import dill import test_mixins as module cached = (module.__cached__ if hasattr(module, "__cached__") else module.__file__ + "c") module.a = 1234 pik_mod = dill.dumps(module) module.a = 0 # remove module del sys.modules[module.__name__] del module module = dill.loads(pik_mod) assert hasattr(module, "a") and module.a == 1234 assert module.double_add(1, 2, 3) == 2 * module.fx # clean up import os os.remove(cached) if os.path.exists("__pycache__") and not os.listdir("__pycache__"): os.removedirs("__pycache__")
782c1b8379d38f99de413398919aa797af0df645
plot_s_curve.py
plot_s_curve.py
import matplotlib.pyplot as plt from numpy import array, log import sys x = [] y = [] infile = open(sys.argv[1]) for line in infile: data = line.replace('\n','').split() print(data) try : x.append(float(data[0])) y.append(float(data[1])) except ValueError: pass #x = array(x) #y = array(y) figManager = plt.get_current_fig_manager() figManager.window.showMaximized() #plt.plot(log(x),log(y)) plt.plot(x,y,"o") plt.ylabel('$\log T$') plt.xlabel('$\log \Sigma$') plt.grid() plt.show()
import matplotlib.pyplot as plt from numpy import array, log import sys import os import matplotlib.animation as animation fig = plt.figure() inpath = sys.argv[1] if os.path.isfile(inpath): print('Visiting {}'.format(inpath)) filenames = [inpath] else: _filenames = os.listdir(inpath) _filenames.sort() filesnames = [inpath + '/' + fname for fname in _filesnames if '_tot.dat' in fname] print('Visiting all files of {}'.format(inpath)) axline, = plt.plot(0, 0, 'o') def draw_once(filename): x = [] y = [] if not 'tot.dat' in filename: return ([0], [0]) else: print('Visiting {}'.format(filename)) outfile = filename.replace('.dat', '.png') for line in open(filename): data = line.replace('\n', '').split() try : print (data) xData = float(data[0]) yData = float(data[1]) x.append(xData) y.append(yData) except ValueError: pass axline.set_xdata(x) axline.set_ydata(y) return axline, def init(): print('Initialisation') plt.ylabel('$\log T$') plt.xlabel('$\log \Sigma$') plt.xlim(1.8, 4) plt.ylim(6, 8) plt.grid() if len(filenames) > 1: ani = animation.FuncAnimation(fig, draw_once, filenames, init_func=init, interval=10) else: init() draw_once(filenames[0]) plt.show() # x, y = draw_once(filenames[2]) # plt.plot(x, y, 'o')
Use animation if dirname is provided
Use animation if dirname is provided
Python
mit
M2-AAIS/BAD
import matplotlib.pyplot as plt from numpy import array, log import sys + import os - x = [] + import matplotlib.animation as animation - y = [] + fig = plt.figure() - infile = open(sys.argv[1]) + inpath = sys.argv[1] - for line in infile: - data = line.replace('\n','').split() - print(data) - try : - x.append(float(data[0])) - y.append(float(data[1])) - except ValueError: - pass + if os.path.isfile(inpath): + print('Visiting {}'.format(inpath)) + filenames = [inpath] + else: + _filenames = os.listdir(inpath) + _filenames.sort() + filesnames = [inpath + '/' + fname for fname in _filesnames if '_tot.dat' in fname] + + print('Visiting all files of {}'.format(inpath)) + axline, = plt.plot(0, 0, 'o') - #x = array(x) - #y = array(y) - figManager = plt.get_current_fig_manager() - figManager.window.showMaximized() - #plt.plot(log(x),log(y)) - plt.plot(x,y,"o") + def draw_once(filename): + x = [] + y = [] + if not 'tot.dat' in filename: + return ([0], [0]) + else: + print('Visiting {}'.format(filename)) + outfile = filename.replace('.dat', '.png') + + for line in open(filename): + data = line.replace('\n', '').split() + try : + print (data) + xData = float(data[0]) + yData = float(data[1]) + x.append(xData) + y.append(yData) + except ValueError: + pass + axline.set_xdata(x) + axline.set_ydata(y) - plt.ylabel('$\log T$') - plt.xlabel('$\log \Sigma$') - plt.grid() - plt.show() + return axline, + + def init(): + print('Initialisation') + plt.ylabel('$\log T$') + plt.xlabel('$\log \Sigma$') + plt.xlim(1.8, 4) + plt.ylim(6, 8) + plt.grid() + + if len(filenames) > 1: + ani = animation.FuncAnimation(fig, draw_once, filenames, init_func=init, interval=10) + else: + init() + draw_once(filenames[0]) + plt.show() + # x, y = draw_once(filenames[2]) + # plt.plot(x, y, 'o') + +
Use animation if dirname is provided
## Code Before: import matplotlib.pyplot as plt from numpy import array, log import sys x = [] y = [] infile = open(sys.argv[1]) for line in infile: data = line.replace('\n','').split() print(data) try : x.append(float(data[0])) y.append(float(data[1])) except ValueError: pass #x = array(x) #y = array(y) figManager = plt.get_current_fig_manager() figManager.window.showMaximized() #plt.plot(log(x),log(y)) plt.plot(x,y,"o") plt.ylabel('$\log T$') plt.xlabel('$\log \Sigma$') plt.grid() plt.show() ## Instruction: Use animation if dirname is provided ## Code After: import matplotlib.pyplot as plt from numpy import array, log import sys import os import matplotlib.animation as animation fig = plt.figure() inpath = sys.argv[1] if os.path.isfile(inpath): print('Visiting {}'.format(inpath)) filenames = [inpath] else: _filenames = os.listdir(inpath) _filenames.sort() filesnames = [inpath + '/' + fname for fname in _filesnames if '_tot.dat' in fname] print('Visiting all files of {}'.format(inpath)) axline, = plt.plot(0, 0, 'o') def draw_once(filename): x = [] y = [] if not 'tot.dat' in filename: return ([0], [0]) else: print('Visiting {}'.format(filename)) outfile = filename.replace('.dat', '.png') for line in open(filename): data = line.replace('\n', '').split() try : print (data) xData = float(data[0]) yData = float(data[1]) x.append(xData) y.append(yData) except ValueError: pass axline.set_xdata(x) axline.set_ydata(y) return axline, def init(): print('Initialisation') plt.ylabel('$\log T$') plt.xlabel('$\log \Sigma$') plt.xlim(1.8, 4) plt.ylim(6, 8) plt.grid() if len(filenames) > 1: ani = animation.FuncAnimation(fig, draw_once, filenames, init_func=init, interval=10) else: init() draw_once(filenames[0]) plt.show() # x, y = draw_once(filenames[2]) # plt.plot(x, y, 'o')
3053219149f7dac7ab073fc24488116b1b280b77
money_rounding.py
money_rounding.py
def get_price_without_vat(price_to_show, vat_percent): raise NotImplementedError() def get_price_without_vat_from_other_valuta(conversion_rate, origin_price, origin_vat, other_vat): raise NotImplementedError()
def show_pretty_price(value): raise NotImplementedError()
Use function described in readme
Use function described in readme
Python
mit
coolshop-com/coolshop-application-assignment
- def get_price_without_vat(price_to_show, vat_percent): + def show_pretty_price(value): raise NotImplementedError() - - def get_price_without_vat_from_other_valuta(conversion_rate, origin_price, - origin_vat, other_vat): - raise NotImplementedError() -
Use function described in readme
## Code Before: def get_price_without_vat(price_to_show, vat_percent): raise NotImplementedError() def get_price_without_vat_from_other_valuta(conversion_rate, origin_price, origin_vat, other_vat): raise NotImplementedError() ## Instruction: Use function described in readme ## Code After: def show_pretty_price(value): raise NotImplementedError()
ea7200bc9774f69562b37f177ad18ca606998dfa
perfrunner/utils/debug.py
perfrunner/utils/debug.py
import glob import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', help='path to the cluster specification file', metavar='cluster.spec') options, args = parser.parse_args() if not options.cluster_spec_fname: parser.error('Please specify a cluster specification') return options, args def main(): options, args = get_options() cluster_spec = ClusterSpec() cluster_spec.parse(options.cluster_spec_fname, args) remote = RemoteHelper(cluster_spec, test_config=None, verbose=False) remote.collect_info() for hostname in cluster_spec.yield_hostnames(): for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) if __name__ == '__main__': main()
import glob import os.path import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', help='path to the cluster specification file', metavar='cluster.spec') options, args = parser.parse_args() if not options.cluster_spec_fname: parser.error('Please specify a cluster specification') return options, args def main(): options, args = get_options() cluster_spec = ClusterSpec() cluster_spec.parse(options.cluster_spec_fname, args) remote = RemoteHelper(cluster_spec, test_config=None, verbose=False) remote.collect_info() for hostname in cluster_spec.yield_hostnames(): for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) if cluster_spec.backup is not None: logs = os.path.join(cluster_spec.backup, 'logs') if os.path.exists(logs): shutil.make_archive('tools', 'zip', logs) if __name__ == '__main__': main()
Archive logs from the tools
Archive logs from the tools Change-Id: I184473d20cc2763fbc97c993bfcab36b80d1c864 Reviewed-on: http://review.couchbase.org/76571 Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com> Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
Python
apache-2.0
couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner
import glob + import os.path import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', help='path to the cluster specification file', metavar='cluster.spec') options, args = parser.parse_args() if not options.cluster_spec_fname: parser.error('Please specify a cluster specification') return options, args def main(): options, args = get_options() cluster_spec = ClusterSpec() cluster_spec.parse(options.cluster_spec_fname, args) remote = RemoteHelper(cluster_spec, test_config=None, verbose=False) remote.collect_info() for hostname in cluster_spec.yield_hostnames(): for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) + if cluster_spec.backup is not None: + logs = os.path.join(cluster_spec.backup, 'logs') + if os.path.exists(logs): + shutil.make_archive('tools', 'zip', logs) + if __name__ == '__main__': main()
Archive logs from the tools
## Code Before: import glob import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', help='path to the cluster specification file', metavar='cluster.spec') options, args = parser.parse_args() if not options.cluster_spec_fname: parser.error('Please specify a cluster specification') return options, args def main(): options, args = get_options() cluster_spec = ClusterSpec() cluster_spec.parse(options.cluster_spec_fname, args) remote = RemoteHelper(cluster_spec, test_config=None, verbose=False) remote.collect_info() for hostname in cluster_spec.yield_hostnames(): for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) if __name__ == '__main__': main() ## Instruction: Archive logs from the tools ## Code After: import glob import os.path import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', help='path to the cluster specification file', metavar='cluster.spec') options, args = parser.parse_args() if not options.cluster_spec_fname: parser.error('Please specify a cluster specification') return options, args def main(): options, args = get_options() cluster_spec = ClusterSpec() cluster_spec.parse(options.cluster_spec_fname, args) remote = RemoteHelper(cluster_spec, test_config=None, verbose=False) remote.collect_info() for hostname in cluster_spec.yield_hostnames(): for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) if cluster_spec.backup is not None: logs = os.path.join(cluster_spec.backup, 'logs') if os.path.exists(logs): shutil.make_archive('tools', 'zip', logs) if __name__ == '__main__': main()
22e82e3fb6949efe862216feafaedb2da9b19c62
filehandler.py
filehandler.py
import csv import sys import urllib from scheduleitem import ScheduleItem from team import Team def read(uri): """Open a File or a Web URL""" if uri.startswith('http://') or uri.startswith('https://'): return open_url(uri) else: return open_file(uri) def open_url(url): """Return the games file data as an array""" try: with urllib.request.urlopen(url) as response: return response.read() except urllib.HTTPError as e: msg = "Could Not Open URL {}.\nThe Code is: {} " print(msg.format(url, e.code)) sys.exit(1) except urllib.URLError as e: msg = "Could Not Open URL {}.\nThe Reason is: {} " print(msg.format(url.url, e.reason)) sys.exit(1) def open_file(uri): """Return the games file data as an array""" try: with open(uri, 'r') as f: return f.read() except IOError: msg = "Could not open file: `{}`" print(msg.format(uri)) sys.exit(1) def load_schedules(games_file): with open(games_file, 'r') as f: return [ScheduleItem.from_str(line) for line in f.readlines()] def load_teams_data(data_file): with open(data_file, 'r') as csv_file: reader = csv.reader(csv_file) # Skip the header row next(reader) return [Team(row[0], row[2], row[3]) for row in reader]
import csv import sys import urllib.error import urllib.request from scheduleitem import ScheduleItem from team import Team def read(uri): """Open a File or a Web URL""" if uri.startswith('http://') or uri.startswith('https://'): return open_url(uri) else: return open_local_file(uri) def open_url(url): """Return the game file data.""" with urllib.request.urlopen(url) as response: if response.status != 200: msg = 'Status {}. Could Not Open URL {}. Reason: {}' raise urllib.error.HTTPError( msg.format(response.status, url, response.msg) ) encoding = sys.getdefaultencoding() return [line.decode(encoding) for line in response.readlines()] def open_local_file(uri): """Return the games file data as an array""" with open(uri, 'r') as f: return f.readlines() def load_schedules(uri): data = read(uri) return [ScheduleItem.from_str(line) for line in data] def load_teams_data(data_file): with open(data_file, 'r') as csv_file: reader = csv.reader(csv_file) next(reader) # Skip the header row return [Team(row[0], row[2], row[3]) for row in reader]
Update file handlers to use Python3 urllib
Update file handlers to use Python3 urllib
Python
mit
brianjbuck/robie
import csv import sys - import urllib + import urllib.error + import urllib.request + from scheduleitem import ScheduleItem from team import Team def read(uri): """Open a File or a Web URL""" if uri.startswith('http://') or uri.startswith('https://'): return open_url(uri) else: - return open_file(uri) + return open_local_file(uri) def open_url(url): - """Return the games file data as an array""" + """Return the game file data.""" - try: - with urllib.request.urlopen(url) as response: + with urllib.request.urlopen(url) as response: + if response.status != 200: - return response.read() - except urllib.HTTPError as e: - msg = "Could Not Open URL {}.\nThe Code is: {} " - print(msg.format(url, e.code)) - sys.exit(1) - except urllib.URLError as e: - msg = "Could Not Open URL {}.\nThe Reason is: {} " + msg = 'Status {}. Could Not Open URL {}. Reason: {}' - print(msg.format(url.url, e.reason)) - sys.exit(1) + raise urllib.error.HTTPError( + msg.format(response.status, url, response.msg) + ) + encoding = sys.getdefaultencoding() + return [line.decode(encoding) for line in response.readlines()] - def open_file(uri): + def open_local_file(uri): """Return the games file data as an array""" - try: - with open(uri, 'r') as f: + with open(uri, 'r') as f: - return f.read() + return f.readlines() - except IOError: - msg = "Could not open file: `{}`" - print(msg.format(uri)) - sys.exit(1) - def load_schedules(games_file): + def load_schedules(uri): - with open(games_file, 'r') as f: + data = read(uri) - return [ScheduleItem.from_str(line) for line in f.readlines()] + return [ScheduleItem.from_str(line) for line in data] def load_teams_data(data_file): with open(data_file, 'r') as csv_file: reader = csv.reader(csv_file) - # Skip the header row + next(reader) # Skip the header row - next(reader) return [Team(row[0], row[2], row[3]) for row in reader]
Update file handlers to use Python3 urllib
## Code Before: import csv import sys import urllib from scheduleitem import ScheduleItem from team import Team def read(uri): """Open a File or a Web URL""" if uri.startswith('http://') or uri.startswith('https://'): return open_url(uri) else: return open_file(uri) def open_url(url): """Return the games file data as an array""" try: with urllib.request.urlopen(url) as response: return response.read() except urllib.HTTPError as e: msg = "Could Not Open URL {}.\nThe Code is: {} " print(msg.format(url, e.code)) sys.exit(1) except urllib.URLError as e: msg = "Could Not Open URL {}.\nThe Reason is: {} " print(msg.format(url.url, e.reason)) sys.exit(1) def open_file(uri): """Return the games file data as an array""" try: with open(uri, 'r') as f: return f.read() except IOError: msg = "Could not open file: `{}`" print(msg.format(uri)) sys.exit(1) def load_schedules(games_file): with open(games_file, 'r') as f: return [ScheduleItem.from_str(line) for line in f.readlines()] def load_teams_data(data_file): with open(data_file, 'r') as csv_file: reader = csv.reader(csv_file) # Skip the header row next(reader) return [Team(row[0], row[2], row[3]) for row in reader] ## Instruction: Update file handlers to use Python3 urllib ## Code After: import csv import sys import urllib.error import urllib.request from scheduleitem import ScheduleItem from team import Team def read(uri): """Open a File or a Web URL""" if uri.startswith('http://') or uri.startswith('https://'): return open_url(uri) else: return open_local_file(uri) def open_url(url): """Return the game file data.""" with urllib.request.urlopen(url) as response: if response.status != 200: msg = 'Status {}. Could Not Open URL {}. Reason: {}' raise urllib.error.HTTPError( msg.format(response.status, url, response.msg) ) encoding = sys.getdefaultencoding() return [line.decode(encoding) for line in response.readlines()] def open_local_file(uri): """Return the games file data as an array""" with open(uri, 'r') as f: return f.readlines() def load_schedules(uri): data = read(uri) return [ScheduleItem.from_str(line) for line in data] def load_teams_data(data_file): with open(data_file, 'r') as csv_file: reader = csv.reader(csv_file) next(reader) # Skip the header row return [Team(row[0], row[2], row[3]) for row in reader]
7b4b2fcbcb9a95c07f09b71305afa0c5ce95fe99
tenant_schemas/routers.py
tenant_schemas/routers.py
from django.conf import settings class TenantSyncRouter(object): """ A router to control which applications will be synced, depending if we are syncing the shared apps or the tenant apps. """ def allow_syncdb(self, db, model): # the imports below need to be done here else django <1.5 goes crazy # https://code.djangoproject.com/ticket/20704 from django.db import connection from tenant_schemas.utils import get_public_schema_name, app_labels if connection.schema_name == get_public_schema_name(): if model._meta.app_label not in app_labels(settings.SHARED_APPS): return False else: if model._meta.app_label not in app_labels(settings.TENANT_APPS): return False return None
from django.conf import settings class TenantSyncRouter(object): """ A router to control which applications will be synced, depending if we are syncing the shared apps or the tenant apps. """ def allow_migrate(self, db, model): # the imports below need to be done here else django <1.5 goes crazy # https://code.djangoproject.com/ticket/20704 from django.db import connection from tenant_schemas.utils import get_public_schema_name, app_labels if connection.schema_name == get_public_schema_name(): if model._meta.app_label not in app_labels(settings.SHARED_APPS): return False else: if model._meta.app_label not in app_labels(settings.TENANT_APPS): return False return None def allow_syncdb(self, db, model): # allow_syncdb was changed to allow_migrate in django 1.7 return self.allow_migrate(db, model)
Add database router allow_migrate() for Django 1.7
Add database router allow_migrate() for Django 1.7
Python
mit
goodtune/django-tenant-schemas,Mobytes/django-tenant-schemas,kajarenc/django-tenant-schemas,honur/django-tenant-schemas,mcanaves/django-tenant-schemas,ArtProcessors/django-tenant-schemas,goodtune/django-tenant-schemas,ArtProcessors/django-tenant-schemas,bernardopires/django-tenant-schemas,bernardopires/django-tenant-schemas,pombredanne/django-tenant-schemas
from django.conf import settings class TenantSyncRouter(object): """ A router to control which applications will be synced, depending if we are syncing the shared apps or the tenant apps. """ - def allow_syncdb(self, db, model): + def allow_migrate(self, db, model): # the imports below need to be done here else django <1.5 goes crazy # https://code.djangoproject.com/ticket/20704 from django.db import connection from tenant_schemas.utils import get_public_schema_name, app_labels if connection.schema_name == get_public_schema_name(): if model._meta.app_label not in app_labels(settings.SHARED_APPS): return False else: if model._meta.app_label not in app_labels(settings.TENANT_APPS): return False return None + def allow_syncdb(self, db, model): + # allow_syncdb was changed to allow_migrate in django 1.7 + return self.allow_migrate(db, model) +
Add database router allow_migrate() for Django 1.7
## Code Before: from django.conf import settings class TenantSyncRouter(object): """ A router to control which applications will be synced, depending if we are syncing the shared apps or the tenant apps. """ def allow_syncdb(self, db, model): # the imports below need to be done here else django <1.5 goes crazy # https://code.djangoproject.com/ticket/20704 from django.db import connection from tenant_schemas.utils import get_public_schema_name, app_labels if connection.schema_name == get_public_schema_name(): if model._meta.app_label not in app_labels(settings.SHARED_APPS): return False else: if model._meta.app_label not in app_labels(settings.TENANT_APPS): return False return None ## Instruction: Add database router allow_migrate() for Django 1.7 ## Code After: from django.conf import settings class TenantSyncRouter(object): """ A router to control which applications will be synced, depending if we are syncing the shared apps or the tenant apps. """ def allow_migrate(self, db, model): # the imports below need to be done here else django <1.5 goes crazy # https://code.djangoproject.com/ticket/20704 from django.db import connection from tenant_schemas.utils import get_public_schema_name, app_labels if connection.schema_name == get_public_schema_name(): if model._meta.app_label not in app_labels(settings.SHARED_APPS): return False else: if model._meta.app_label not in app_labels(settings.TENANT_APPS): return False return None def allow_syncdb(self, db, model): # allow_syncdb was changed to allow_migrate in django 1.7 return self.allow_migrate(db, model)
c8a0f4f439c2123c9b7f9b081f91d75b1f9a8a13
dmoj/checkers/linecount.py
dmoj/checkers/linecount.py
from re import split as resplit from typing import Callable, Union from dmoj.result import CheckerResult from dmoj.utils.unicode import utf8bytes verdict = u"\u2717\u2713" def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True, match: Callable[[bytes, bytes], bool] = lambda p, j: p.strip() == j.strip(), **kwargs) -> Union[CheckerResult, bool]: process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output)))) judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output)))) if len(process_lines) > len(judge_lines): return False if not judge_lines: return True if isinstance(match, str): match = eval(match) cases = [verdict[0]] * len(judge_lines) count = 0 for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)): if match(process_line, judge_line): cases[i] = verdict[1] count += 1 return CheckerResult(count == len(judge_lines), point_value * (1.0 * count / len(judge_lines)), ''.join(cases) if feedback else "") check.run_on_error = True # type: ignore
from re import split as resplit from typing import Callable, Union from dmoj.result import CheckerResult from dmoj.utils.unicode import utf8bytes verdict = u"\u2717\u2713" def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True, **kwargs) -> Union[CheckerResult, bool]: process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output)))) judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output)))) if len(process_lines) > len(judge_lines): return False if not judge_lines: return True cases = [verdict[0]] * len(judge_lines) count = 0 for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)): if process_line.strip() == judge_line.strip(): cases[i] = verdict[1] count += 1 return CheckerResult(count == len(judge_lines), point_value * (1.0 * count / len(judge_lines)), ''.join(cases) if feedback else "") check.run_on_error = True # type: ignore
Remove the match param to fix RCE.
Remove the match param to fix RCE.
Python
agpl-3.0
DMOJ/judge,DMOJ/judge,DMOJ/judge
from re import split as resplit from typing import Callable, Union from dmoj.result import CheckerResult from dmoj.utils.unicode import utf8bytes verdict = u"\u2717\u2713" def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True, - match: Callable[[bytes, bytes], bool] = lambda p, j: p.strip() == j.strip(), **kwargs) -> Union[CheckerResult, bool]: process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output)))) judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output)))) if len(process_lines) > len(judge_lines): return False if not judge_lines: return True - if isinstance(match, str): - match = eval(match) - cases = [verdict[0]] * len(judge_lines) count = 0 for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)): - if match(process_line, judge_line): + if process_line.strip() == judge_line.strip(): cases[i] = verdict[1] count += 1 return CheckerResult(count == len(judge_lines), point_value * (1.0 * count / len(judge_lines)), ''.join(cases) if feedback else "") check.run_on_error = True # type: ignore
Remove the match param to fix RCE.
## Code Before: from re import split as resplit from typing import Callable, Union from dmoj.result import CheckerResult from dmoj.utils.unicode import utf8bytes verdict = u"\u2717\u2713" def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True, match: Callable[[bytes, bytes], bool] = lambda p, j: p.strip() == j.strip(), **kwargs) -> Union[CheckerResult, bool]: process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output)))) judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output)))) if len(process_lines) > len(judge_lines): return False if not judge_lines: return True if isinstance(match, str): match = eval(match) cases = [verdict[0]] * len(judge_lines) count = 0 for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)): if match(process_line, judge_line): cases[i] = verdict[1] count += 1 return CheckerResult(count == len(judge_lines), point_value * (1.0 * count / len(judge_lines)), ''.join(cases) if feedback else "") check.run_on_error = True # type: ignore ## Instruction: Remove the match param to fix RCE. ## Code After: from re import split as resplit from typing import Callable, Union from dmoj.result import CheckerResult from dmoj.utils.unicode import utf8bytes verdict = u"\u2717\u2713" def check(process_output: bytes, judge_output: bytes, point_value: float, feedback: bool = True, **kwargs) -> Union[CheckerResult, bool]: process_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(process_output)))) judge_lines = list(filter(None, resplit(b'[\r\n]', utf8bytes(judge_output)))) if len(process_lines) > len(judge_lines): return False if not judge_lines: return True cases = [verdict[0]] * len(judge_lines) count = 0 for i, (process_line, judge_line) in enumerate(zip(process_lines, judge_lines)): if process_line.strip() == judge_line.strip(): cases[i] = verdict[1] count += 1 return CheckerResult(count == len(judge_lines), point_value * (1.0 * count / len(judge_lines)), ''.join(cases) if feedback else "") check.run_on_error = True # type: ignore
973641c7d68f4b1505541a06ec46901b412ab56b
tests/test_constraints.py
tests/test_constraints.py
import unittest import numpy as np from constraints import (generate_constraints_function, generate_constraint_gradients_function, ) from robot_arm import RobotArm class TestConstraintFunctions(unittest.TestCase): def setUp(self): self.lengths = (3, 2, 2,) self.destinations = ( (5, 4, 6, 4, 5), (0, 2, 0.5, -2, -1), ) self.theta = (np.pi, np.pi / 2, 0,) self.thetas = np.ones((3 * 5,)) self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta) self.constraints_func = generate_constraints_function(self.robot_arm) self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm) def test_constraints_func_return_type(self): constraints = self.constraints_func(self.thetas) self.assertEqual(constraints.shape, (2 * 5,)) def test_constraint_gradients_func_return_type(self): constraint_gradients = self.constraint_gradients_func(self.thetas) self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5)) # print(np.array2string(constraint_gradients, max_line_width=np.inf))
import unittest import numpy as np from constraints import (generate_constraints_function, generate_constraint_gradients_function, ) from robot_arm import RobotArm class TestConstraintFunctions(unittest.TestCase): def setUp(self): self.lengths = (3, 2, 2,) self.destinations = ( (5, 4, 6, 4, 5), (0, 2, 0.5, -2, -1), ) self.theta = (np.pi, np.pi / 2, 0,) self.thetas = np.ones((3 * 5,)) self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta) self.constraints_func = generate_constraints_function(self.robot_arm) self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm) def test_constraints_func_return_type(self): constraints = self.constraints_func(self.thetas) self.assertEqual(constraints.shape, (2 * 5,)) def test_constraint_gradients_func_return_type(self): constraint_gradients = self.constraint_gradients_func(self.thetas) self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5)) # print(np.array2string(constraint_gradients, max_line_width=np.inf)) def test_licq(self): constraint_gradients = self.constraint_gradients_func(self.thetas) rank = np.linalg.matrix_rank(constraint_gradients) self.assertEqual(rank, 2 * 5)
Test LICQ condition of constraint gradient
Test LICQ condition of constraint gradient
Python
mit
JakobGM/robotarm-optimization
import unittest import numpy as np from constraints import (generate_constraints_function, generate_constraint_gradients_function, ) from robot_arm import RobotArm class TestConstraintFunctions(unittest.TestCase): def setUp(self): self.lengths = (3, 2, 2,) self.destinations = ( (5, 4, 6, 4, 5), (0, 2, 0.5, -2, -1), ) self.theta = (np.pi, np.pi / 2, 0,) self.thetas = np.ones((3 * 5,)) self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta) self.constraints_func = generate_constraints_function(self.robot_arm) self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm) def test_constraints_func_return_type(self): constraints = self.constraints_func(self.thetas) self.assertEqual(constraints.shape, (2 * 5,)) def test_constraint_gradients_func_return_type(self): constraint_gradients = self.constraint_gradients_func(self.thetas) self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5)) # print(np.array2string(constraint_gradients, max_line_width=np.inf)) + def test_licq(self): + constraint_gradients = self.constraint_gradients_func(self.thetas) + rank = np.linalg.matrix_rank(constraint_gradients) + self.assertEqual(rank, 2 * 5) +
Test LICQ condition of constraint gradient
## Code Before: import unittest import numpy as np from constraints import (generate_constraints_function, generate_constraint_gradients_function, ) from robot_arm import RobotArm class TestConstraintFunctions(unittest.TestCase): def setUp(self): self.lengths = (3, 2, 2,) self.destinations = ( (5, 4, 6, 4, 5), (0, 2, 0.5, -2, -1), ) self.theta = (np.pi, np.pi / 2, 0,) self.thetas = np.ones((3 * 5,)) self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta) self.constraints_func = generate_constraints_function(self.robot_arm) self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm) def test_constraints_func_return_type(self): constraints = self.constraints_func(self.thetas) self.assertEqual(constraints.shape, (2 * 5,)) def test_constraint_gradients_func_return_type(self): constraint_gradients = self.constraint_gradients_func(self.thetas) self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5)) # print(np.array2string(constraint_gradients, max_line_width=np.inf)) ## Instruction: Test LICQ condition of constraint gradient ## Code After: import unittest import numpy as np from constraints import (generate_constraints_function, generate_constraint_gradients_function, ) from robot_arm import RobotArm class TestConstraintFunctions(unittest.TestCase): def setUp(self): self.lengths = (3, 2, 2,) self.destinations = ( (5, 4, 6, 4, 5), (0, 2, 0.5, -2, -1), ) self.theta = (np.pi, np.pi / 2, 0,) self.thetas = np.ones((3 * 5,)) self.robot_arm = RobotArm(self.lengths, self.destinations, self.theta) self.constraints_func = generate_constraints_function(self.robot_arm) self.constraint_gradients_func = generate_constraint_gradients_function(self.robot_arm) def test_constraints_func_return_type(self): constraints = self.constraints_func(self.thetas) self.assertEqual(constraints.shape, (2 * 5,)) def test_constraint_gradients_func_return_type(self): constraint_gradients = self.constraint_gradients_func(self.thetas) self.assertEqual(constraint_gradients.shape, (3 * 5, 2 * 5)) # print(np.array2string(constraint_gradients, max_line_width=np.inf)) def test_licq(self): constraint_gradients = self.constraint_gradients_func(self.thetas) rank = np.linalg.matrix_rank(constraint_gradients) self.assertEqual(rank, 2 * 5)
91ef89371f7ba99346ba982a3fdb7fc2105a9840
superdesk/users/__init__.py
superdesk/users/__init__.py
from .users import RolesResource, UsersResource from .services import DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
from .users import RolesResource, UsersResource from .services import UsersService, DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
Make UsersResource reusable for LDAP
Make UsersResource reusable for LDAP
Python
agpl-3.0
ioanpocol/superdesk-core,plamut/superdesk-core,akintolga/superdesk-core,ancafarcas/superdesk-core,ancafarcas/superdesk-core,nistormihai/superdesk-core,superdesk/superdesk-core,sivakuna-aap/superdesk-core,superdesk/superdesk-core,mdhaman/superdesk-core,petrjasek/superdesk-core,mdhaman/superdesk-core,mugurrus/superdesk-core,mugurrus/superdesk-core,mdhaman/superdesk-core,superdesk/superdesk-core,ioanpocol/superdesk-core,sivakuna-aap/superdesk-core,marwoodandrew/superdesk-core,plamut/superdesk-core,superdesk/superdesk-core,petrjasek/superdesk-core,ioanpocol/superdesk-core,marwoodandrew/superdesk-core,hlmnrmr/superdesk-core,akintolga/superdesk-core,nistormihai/superdesk-core,hlmnrmr/superdesk-core,mugurrus/superdesk-core,petrjasek/superdesk-core,petrjasek/superdesk-core
from .users import RolesResource, UsersResource - from .services import DBUsersService, RolesService, is_admin # noqa + from .services import UsersService, DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
Make UsersResource reusable for LDAP
## Code Before: from .users import RolesResource, UsersResource from .services import DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH']) ## Instruction: Make UsersResource reusable for LDAP ## Code After: from .users import RolesResource, UsersResource from .services import UsersService, DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
49a275a268fba520252ee864c39934699c053d13
csunplugged/resources/views/barcode_checksum_poster.py
csunplugged/resources/views/barcode_checksum_poster.py
"""Module for generating Barcode Checksum Poster resource.""" from PIL import Image from utils.retrieve_query_parameter import retrieve_query_parameter def resource_image(request, resource): """Create a image for Barcode Checksum Poster resource. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: A list of Pillow image objects. """ # Retrieve parameters parameter_options = valid_options() barcode_length = retrieve_query_parameter(request, "barcode_length", parameter_options["barcode_length"]) image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png" image = Image.open(image_path.format(barcode_length)) return image def subtitle(request, resource): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: Text for subtitle (str). """ barcode_length = retrieve_query_parameter(request, "barcode_length") paper_size = retrieve_query_parameter(request, "paper_size") return "{} digits - {}".format(barcode_length, paper_size) def valid_options(): """Provide dictionary of all valid parameters. This excludes the header text parameter. Returns: All valid options (dict). """ return { "barcode_length": ["12", "13"], "paper_size": ["a4", "letter"], }
"""Module for generating Barcode Checksum Poster resource.""" from PIL import Image from utils.retrieve_query_parameter import retrieve_query_parameter def resource(request, resource): """Create a image for Barcode Checksum Poster resource. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: A dictionary for the resource page. """ # Retrieve parameters parameter_options = valid_options() barcode_length = retrieve_query_parameter(request, "barcode_length", parameter_options["barcode_length"]) image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png" image = Image.open(image_path.format(barcode_length)) return {"type": "image", "data": image} def subtitle(request, resource): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: Text for subtitle (str). """ barcode_length = retrieve_query_parameter(request, "barcode_length") paper_size = retrieve_query_parameter(request, "paper_size") return "{} digits - {}".format(barcode_length, paper_size) def valid_options(): """Provide dictionary of all valid parameters. This excludes the header text parameter. Returns: All valid options (dict). """ return { "barcode_length": ["12", "13"], "paper_size": ["a4", "letter"], }
Update barcode resource to new resource specification
Update barcode resource to new resource specification
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
"""Module for generating Barcode Checksum Poster resource.""" from PIL import Image from utils.retrieve_query_parameter import retrieve_query_parameter - def resource_image(request, resource): + def resource(request, resource): """Create a image for Barcode Checksum Poster resource. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: - A list of Pillow image objects. + A dictionary for the resource page. """ # Retrieve parameters parameter_options = valid_options() barcode_length = retrieve_query_parameter(request, "barcode_length", parameter_options["barcode_length"]) image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png" image = Image.open(image_path.format(barcode_length)) - return image + return {"type": "image", "data": image} def subtitle(request, resource): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: Text for subtitle (str). """ barcode_length = retrieve_query_parameter(request, "barcode_length") paper_size = retrieve_query_parameter(request, "paper_size") return "{} digits - {}".format(barcode_length, paper_size) def valid_options(): """Provide dictionary of all valid parameters. This excludes the header text parameter. Returns: All valid options (dict). """ return { "barcode_length": ["12", "13"], "paper_size": ["a4", "letter"], }
Update barcode resource to new resource specification
## Code Before: """Module for generating Barcode Checksum Poster resource.""" from PIL import Image from utils.retrieve_query_parameter import retrieve_query_parameter def resource_image(request, resource): """Create a image for Barcode Checksum Poster resource. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: A list of Pillow image objects. """ # Retrieve parameters parameter_options = valid_options() barcode_length = retrieve_query_parameter(request, "barcode_length", parameter_options["barcode_length"]) image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png" image = Image.open(image_path.format(barcode_length)) return image def subtitle(request, resource): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: Text for subtitle (str). """ barcode_length = retrieve_query_parameter(request, "barcode_length") paper_size = retrieve_query_parameter(request, "paper_size") return "{} digits - {}".format(barcode_length, paper_size) def valid_options(): """Provide dictionary of all valid parameters. This excludes the header text parameter. Returns: All valid options (dict). """ return { "barcode_length": ["12", "13"], "paper_size": ["a4", "letter"], } ## Instruction: Update barcode resource to new resource specification ## Code After: """Module for generating Barcode Checksum Poster resource.""" from PIL import Image from utils.retrieve_query_parameter import retrieve_query_parameter def resource(request, resource): """Create a image for Barcode Checksum Poster resource. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: A dictionary for the resource page. """ # Retrieve parameters parameter_options = valid_options() barcode_length = retrieve_query_parameter(request, "barcode_length", parameter_options["barcode_length"]) image_path = "static/img/resources/barcode-checksum-poster/{}-digits.png" image = Image.open(image_path.format(barcode_length)) return {"type": "image", "data": image} def subtitle(request, resource): """Return the subtitle string of the resource. Used after the resource name in the filename, and also on the resource image. Args: request: HTTP request object (QueryDict). resource: Object of resource data (Resource). Returns: Text for subtitle (str). """ barcode_length = retrieve_query_parameter(request, "barcode_length") paper_size = retrieve_query_parameter(request, "paper_size") return "{} digits - {}".format(barcode_length, paper_size) def valid_options(): """Provide dictionary of all valid parameters. This excludes the header text parameter. Returns: All valid options (dict). """ return { "barcode_length": ["12", "13"], "paper_size": ["a4", "letter"], }
12f3bb8c82b97496c79948d323f7076b6618293a
saleor/graphql/scalars.py
saleor/graphql/scalars.py
from graphene.types import Scalar from graphql.language import ast class AttributesFilterScalar(Scalar): @staticmethod def coerce_filter(value): if isinstance(value, tuple) and len(value) == 2: return ":".join(value) serialize = coerce_filter parse_value = coerce_filter @staticmethod def parse_literal(node): if isinstance(node, ast.StringValue): splitted = node.value.split(":") if len(splitted) == 2: return tuple(splitted)
from graphene.types import Scalar from graphql.language import ast class AttributesFilterScalar(Scalar): @staticmethod def parse_literal(node): if isinstance(node, ast.StringValue): splitted = node.value.split(":") if len(splitted) == 2: return tuple(splitted) @staticmethod def parse_value(value): if isinstance(value, basestring): splitted = value.split(":") if len(splitted) == 2: return tuple(splitted) @staticmethod def serialize(value): if isinstance(value, tuple) and len(value) == 2: return ":".join(value)
Fix parsing attributes filter values in GraphQL API
Fix parsing attributes filter values in GraphQL API
Python
bsd-3-clause
KenMutemi/saleor,KenMutemi/saleor,jreigel/saleor,itbabu/saleor,maferelo/saleor,maferelo/saleor,jreigel/saleor,jreigel/saleor,HyperManTT/ECommerceSaleor,mociepka/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,car3oon/saleor,itbabu/saleor,UITools/saleor,HyperManTT/ECommerceSaleor,car3oon/saleor,car3oon/saleor,UITools/saleor,HyperManTT/ECommerceSaleor,tfroehlich82/saleor,itbabu/saleor,tfroehlich82/saleor,tfroehlich82/saleor,KenMutemi/saleor,mociepka/saleor,UITools/saleor,mociepka/saleor
from graphene.types import Scalar from graphql.language import ast class AttributesFilterScalar(Scalar): - - @staticmethod - def coerce_filter(value): - if isinstance(value, tuple) and len(value) == 2: - return ":".join(value) - - serialize = coerce_filter - parse_value = coerce_filter @staticmethod def parse_literal(node): if isinstance(node, ast.StringValue): splitted = node.value.split(":") if len(splitted) == 2: return tuple(splitted) + @staticmethod + def parse_value(value): + if isinstance(value, basestring): + splitted = value.split(":") + if len(splitted) == 2: + return tuple(splitted) + + @staticmethod + def serialize(value): + if isinstance(value, tuple) and len(value) == 2: + return ":".join(value) +
Fix parsing attributes filter values in GraphQL API
## Code Before: from graphene.types import Scalar from graphql.language import ast class AttributesFilterScalar(Scalar): @staticmethod def coerce_filter(value): if isinstance(value, tuple) and len(value) == 2: return ":".join(value) serialize = coerce_filter parse_value = coerce_filter @staticmethod def parse_literal(node): if isinstance(node, ast.StringValue): splitted = node.value.split(":") if len(splitted) == 2: return tuple(splitted) ## Instruction: Fix parsing attributes filter values in GraphQL API ## Code After: from graphene.types import Scalar from graphql.language import ast class AttributesFilterScalar(Scalar): @staticmethod def parse_literal(node): if isinstance(node, ast.StringValue): splitted = node.value.split(":") if len(splitted) == 2: return tuple(splitted) @staticmethod def parse_value(value): if isinstance(value, basestring): splitted = value.split(":") if len(splitted) == 2: return tuple(splitted) @staticmethod def serialize(value): if isinstance(value, tuple) and len(value) == 2: return ":".join(value)
5b8ff4276fbe92d5ccd5fa63fecccc5ff7d571a9
quokka/core/tests/test_models.py
quokka/core/tests/test_models.py
from . import BaseTestCase from ..models import Channel class TestCoreModels(BaseTestCase): def setUp(self): # Create method was not returning the created object with # the create() method self.channel, new = Channel.objects.get_or_create( title=u'Monkey Island', description=u'The coolest pirate history ever', ) def tearDown(self): self.channel.delete() def test_channel_fields(self): self.assertEqual(self.channel.title, u'Monkey Island') self.assertEqual(self.channel.slug, u'monkey-island') self.assertEqual(self.channel.description, u'The coolest pirate history ever')
from . import BaseTestCase from ..models import Channel class TestChannel(BaseTestCase): def setUp(self): # Create method was not returning the created object with # the create() method self.parent, new = Channel.objects.get_or_create( title=u'Father', ) self.channel, new = Channel.objects.get_or_create( title=u'Monkey Island', description=u'The coolest pirate history ever', parent=self.parent, tags=['tag1', 'tag2'], ) def tearDown(self): self.channel.delete() def test_channel_fields(self): self.assertEqual(self.channel.title, u'Monkey Island') self.assertEqual(self.channel.slug, u'monkey-island') self.assertEqual(self.channel.long_slug, u'father/monkey-island') self.assertEqual(self.channel.mpath, u',father,monkey-island,') self.assertEqual(self.channel.description, u'The coolest pirate history ever') self.assertEqual(self.channel.tags, ['tag1', 'tag2']) self.assertEqual(self.channel.parent, self.parent) self.assertEqual(unicode(self.channel), u'father/monkey-island') def test_get_ancestors(self): self.assertEqual(list(self.channel.get_ancestors()), [self.channel, self.parent]) def test_get_ancestors_slug(self): self.assertEqual(self.channel.get_ancestors_slugs(), [u'father/monkey-island', u'father']) def test_get_children(self): self.assertEqual(list(self.parent.get_children()), [self.channel]) def test_get_descendants(self): self.assertEqual(list(self.parent.get_descendants()), [self.parent, self.channel]) def test_absolute_urls(self): self.assertEqual(self.channel.get_absolute_url(), '/father/monkey-island/') self.assertEqual(self.parent.get_absolute_url(), '/father/') def test_get_canonical_url(self): self.assertEqual(self.channel.get_canonical_url(), '/father/monkey-island/') self.assertEqual(self.parent.get_canonical_url(), '/father/')
Add more core tests / Rename test
Add more core tests / Rename test
Python
mit
romulocollopy/quokka,felipevolpone/quokka,lnick/quokka,ChengChiongWah/quokka,felipevolpone/quokka,wushuyi/quokka,wushuyi/quokka,cbeloni/quokka,felipevolpone/quokka,CoolCloud/quokka,ChengChiongWah/quokka,lnick/quokka,romulocollopy/quokka,Ckai1991/quokka,cbeloni/quokka,CoolCloud/quokka,alexandre/quokka,felipevolpone/quokka,fdumpling/quokka,fdumpling/quokka,romulocollopy/quokka,CoolCloud/quokka,maurobaraldi/quokka,maurobaraldi/quokka,romulocollopy/quokka,Ckai1991/quokka,fdumpling/quokka,cbeloni/quokka,ChengChiongWah/quokka,lnick/quokka,ChengChiongWah/quokka,Ckai1991/quokka,wushuyi/quokka,lnick/quokka,fdumpling/quokka,CoolCloud/quokka,alexandre/quokka,Ckai1991/quokka,maurobaraldi/quokka,maurobaraldi/quokka,wushuyi/quokka,cbeloni/quokka
from . import BaseTestCase from ..models import Channel - class TestCoreModels(BaseTestCase): + class TestChannel(BaseTestCase): def setUp(self): # Create method was not returning the created object with # the create() method + self.parent, new = Channel.objects.get_or_create( + title=u'Father', + ) self.channel, new = Channel.objects.get_or_create( title=u'Monkey Island', description=u'The coolest pirate history ever', + parent=self.parent, + tags=['tag1', 'tag2'], ) def tearDown(self): self.channel.delete() def test_channel_fields(self): self.assertEqual(self.channel.title, u'Monkey Island') self.assertEqual(self.channel.slug, u'monkey-island') + self.assertEqual(self.channel.long_slug, u'father/monkey-island') + self.assertEqual(self.channel.mpath, u',father,monkey-island,') self.assertEqual(self.channel.description, u'The coolest pirate history ever') + self.assertEqual(self.channel.tags, ['tag1', 'tag2']) + self.assertEqual(self.channel.parent, self.parent) + self.assertEqual(unicode(self.channel), u'father/monkey-island') + def test_get_ancestors(self): + self.assertEqual(list(self.channel.get_ancestors()), [self.channel, + self.parent]) + + def test_get_ancestors_slug(self): + self.assertEqual(self.channel.get_ancestors_slugs(), + [u'father/monkey-island', u'father']) + + def test_get_children(self): + self.assertEqual(list(self.parent.get_children()), [self.channel]) + + def test_get_descendants(self): + self.assertEqual(list(self.parent.get_descendants()), + [self.parent, self.channel]) + + def test_absolute_urls(self): + self.assertEqual(self.channel.get_absolute_url(), + '/father/monkey-island/') + self.assertEqual(self.parent.get_absolute_url(), + '/father/') + + def test_get_canonical_url(self): + self.assertEqual(self.channel.get_canonical_url(), + '/father/monkey-island/') + self.assertEqual(self.parent.get_canonical_url(), + '/father/') +
Add more core tests / Rename test
## Code Before: from . import BaseTestCase from ..models import Channel class TestCoreModels(BaseTestCase): def setUp(self): # Create method was not returning the created object with # the create() method self.channel, new = Channel.objects.get_or_create( title=u'Monkey Island', description=u'The coolest pirate history ever', ) def tearDown(self): self.channel.delete() def test_channel_fields(self): self.assertEqual(self.channel.title, u'Monkey Island') self.assertEqual(self.channel.slug, u'monkey-island') self.assertEqual(self.channel.description, u'The coolest pirate history ever') ## Instruction: Add more core tests / Rename test ## Code After: from . import BaseTestCase from ..models import Channel class TestChannel(BaseTestCase): def setUp(self): # Create method was not returning the created object with # the create() method self.parent, new = Channel.objects.get_or_create( title=u'Father', ) self.channel, new = Channel.objects.get_or_create( title=u'Monkey Island', description=u'The coolest pirate history ever', parent=self.parent, tags=['tag1', 'tag2'], ) def tearDown(self): self.channel.delete() def test_channel_fields(self): self.assertEqual(self.channel.title, u'Monkey Island') self.assertEqual(self.channel.slug, u'monkey-island') self.assertEqual(self.channel.long_slug, u'father/monkey-island') self.assertEqual(self.channel.mpath, u',father,monkey-island,') self.assertEqual(self.channel.description, u'The coolest pirate history ever') self.assertEqual(self.channel.tags, ['tag1', 'tag2']) self.assertEqual(self.channel.parent, self.parent) self.assertEqual(unicode(self.channel), u'father/monkey-island') def test_get_ancestors(self): self.assertEqual(list(self.channel.get_ancestors()), [self.channel, self.parent]) def test_get_ancestors_slug(self): self.assertEqual(self.channel.get_ancestors_slugs(), [u'father/monkey-island', u'father']) def test_get_children(self): self.assertEqual(list(self.parent.get_children()), [self.channel]) def test_get_descendants(self): self.assertEqual(list(self.parent.get_descendants()), [self.parent, self.channel]) def test_absolute_urls(self): self.assertEqual(self.channel.get_absolute_url(), '/father/monkey-island/') self.assertEqual(self.parent.get_absolute_url(), '/father/') def test_get_canonical_url(self): self.assertEqual(self.channel.get_canonical_url(), '/father/monkey-island/') self.assertEqual(self.parent.get_canonical_url(), '/father/')
3037562643bc1ddaf081a6fa9c757aed4101bb53
robots/urls.py
robots/urls.py
try: from django.conf.urls import patterns, url except ImportError: from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'robots.views', url(r'^$', 'rules_list', name='robots_rule_list'), )
from django.conf.urls import url from robots.views import rules_list urlpatterns = [ url(r'^$', rules_list, name='robots_rule_list'), ]
Fix warnings about URLconf in Django 1.9
Fix warnings about URLconf in Django 1.9 * django.conf.urls.patterns will be removed in Django 1.10 * Passing a dotted path and not a view function will be deprecated in Django 1.10
Python
bsd-3-clause
jezdez/django-robots,jezdez/django-robots,jscott1971/django-robots,jscott1971/django-robots,jazzband/django-robots,jazzband/django-robots
- try: - from django.conf.urls import patterns, url + from django.conf.urls import url - except ImportError: - from django.conf.urls.defaults import patterns, url + from robots.views import rules_list - urlpatterns = patterns( - 'robots.views', - url(r'^$', 'rules_list', name='robots_rule_list'), - ) + + urlpatterns = [ + url(r'^$', rules_list, name='robots_rule_list'), + ] +
Fix warnings about URLconf in Django 1.9
## Code Before: try: from django.conf.urls import patterns, url except ImportError: from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'robots.views', url(r'^$', 'rules_list', name='robots_rule_list'), ) ## Instruction: Fix warnings about URLconf in Django 1.9 ## Code After: from django.conf.urls import url from robots.views import rules_list urlpatterns = [ url(r'^$', rules_list, name='robots_rule_list'), ]
aba5ae9736b064fd1e3541de3ef36371d92fc875
RandoAmisSecours/admin.py
RandoAmisSecours/admin.py
from django.contrib import admin from models import * admin.site.register(FriendRequest) admin.site.register(Outing) admin.site.register(Profile)
from django.contrib import admin from RandoAmisSecours.models import * admin.site.register(FriendRequest) admin.site.register(Outing) admin.site.register(Profile)
Fix import when using python3.3
Fix import when using python3.3
Python
agpl-3.0
ivoire/RandoAmisSecours,ivoire/RandoAmisSecours
from django.contrib import admin - from models import * + from RandoAmisSecours.models import * admin.site.register(FriendRequest) admin.site.register(Outing) admin.site.register(Profile)
Fix import when using python3.3
## Code Before: from django.contrib import admin from models import * admin.site.register(FriendRequest) admin.site.register(Outing) admin.site.register(Profile) ## Instruction: Fix import when using python3.3 ## Code After: from django.contrib import admin from RandoAmisSecours.models import * admin.site.register(FriendRequest) admin.site.register(Outing) admin.site.register(Profile)
b9e1b34348444c4c51c8fd30ff7882552e21939b
temba/msgs/migrations/0094_auto_20170501_1641.py
temba/msgs/migrations/0094_auto_20170501_1641.py
from __future__ import unicode_literals from django.db import migrations, models import temba.utils.models class Migration(migrations.Migration): dependencies = [ ('msgs', '0093_populate_translatables'), ] operations = [ migrations.RemoveField( model_name='broadcast', name='language_dict', ), migrations.RemoveField( model_name='broadcast', name='media_dict', ), migrations.RemoveField( model_name='broadcast', name='text', ), migrations.AlterField( model_name='broadcast', name='base_language', field=models.CharField(help_text='The language used to send this to contacts without a language', max_length=4), ), migrations.AlterField( model_name='broadcast', name='translations', field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text', max_length=640, verbose_name='Translations'), ), migrations.RenameField( model_name='broadcast', old_name='translations', new_name='text', ), ]
from __future__ import unicode_literals from django.db import migrations, models import temba.utils.models class Migration(migrations.Migration): dependencies = [ ('msgs', '0093_populate_translatables'), ] operations = [ migrations.AlterField( model_name='broadcast', name='base_language', field=models.CharField(help_text='The language used to send this to contacts without a language', max_length=4), ), migrations.AlterField( model_name='broadcast', name='translations', field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text', max_length=640, verbose_name='Translations'), ), migrations.RemoveField( model_name='broadcast', name='language_dict', ), migrations.RemoveField( model_name='broadcast', name='media_dict', ), migrations.RemoveField( model_name='broadcast', name='text', ), migrations.RenameField( model_name='broadcast', old_name='translations', new_name='text', ), ]
Change order of operations within migration so breaking schema changes come last
Change order of operations within migration so breaking schema changes come last
Python
agpl-3.0
pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro
from __future__ import unicode_literals from django.db import migrations, models import temba.utils.models class Migration(migrations.Migration): dependencies = [ ('msgs', '0093_populate_translatables'), ] operations = [ + migrations.AlterField( + model_name='broadcast', + name='base_language', + field=models.CharField(help_text='The language used to send this to contacts without a language', + max_length=4), + ), + migrations.AlterField( + model_name='broadcast', + name='translations', + field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text', + max_length=640, verbose_name='Translations'), + ), migrations.RemoveField( model_name='broadcast', name='language_dict', ), migrations.RemoveField( model_name='broadcast', name='media_dict', ), migrations.RemoveField( model_name='broadcast', name='text', ), - migrations.AlterField( - model_name='broadcast', - name='base_language', - field=models.CharField(help_text='The language used to send this to contacts without a language', - max_length=4), - ), - migrations.AlterField( - model_name='broadcast', - name='translations', - field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text', - max_length=640, verbose_name='Translations'), - ), migrations.RenameField( model_name='broadcast', old_name='translations', new_name='text', ), ]
Change order of operations within migration so breaking schema changes come last
## Code Before: from __future__ import unicode_literals from django.db import migrations, models import temba.utils.models class Migration(migrations.Migration): dependencies = [ ('msgs', '0093_populate_translatables'), ] operations = [ migrations.RemoveField( model_name='broadcast', name='language_dict', ), migrations.RemoveField( model_name='broadcast', name='media_dict', ), migrations.RemoveField( model_name='broadcast', name='text', ), migrations.AlterField( model_name='broadcast', name='base_language', field=models.CharField(help_text='The language used to send this to contacts without a language', max_length=4), ), migrations.AlterField( model_name='broadcast', name='translations', field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text', max_length=640, verbose_name='Translations'), ), migrations.RenameField( model_name='broadcast', old_name='translations', new_name='text', ), ] ## Instruction: Change order of operations within migration so breaking schema changes come last ## Code After: from __future__ import unicode_literals from django.db import migrations, models import temba.utils.models class Migration(migrations.Migration): dependencies = [ ('msgs', '0093_populate_translatables'), ] operations = [ migrations.AlterField( model_name='broadcast', name='base_language', field=models.CharField(help_text='The language used to send this to contacts without a language', max_length=4), ), migrations.AlterField( model_name='broadcast', name='translations', field=temba.utils.models.TranslatableField(help_text='The localized versions of the message text', max_length=640, verbose_name='Translations'), ), migrations.RemoveField( model_name='broadcast', name='language_dict', ), migrations.RemoveField( model_name='broadcast', name='media_dict', ), migrations.RemoveField( model_name='broadcast', name='text', ), migrations.RenameField( model_name='broadcast', old_name='translations', new_name='text', ), ]
3c9da01bee3d157e344f3ad317b777b3977b2e4d
account_invoice_start_end_dates/models/account_move.py
account_invoice_start_end_dates/models/account_move.py
from odoo import _, models from odoo.exceptions import UserError class AccountMove(models.Model): _inherit = "account.move" def action_post(self): for move in self: for line in move.line_ids: if line.product_id and line.product_id.must_have_dates: if not line.start_date or not line.end_date: raise UserError( _( "Missing Start Date and End Date for invoice " "line with Product '%s' which has the " "property 'Must Have Start and End Dates'." ) % (line.product_id.display_name) ) return super(AccountMove, self).action_post()
from odoo import _, models from odoo.exceptions import UserError class AccountMove(models.Model): _inherit = "account.move" def action_post(self): for move in self: for line in move.line_ids: if line.product_id and line.product_id.must_have_dates: if not line.start_date or not line.end_date: raise UserError( _( "Missing Start Date and End Date for invoice " "line with Product '%s' which has the " "property 'Must Have Start and End Dates'." ) % (line.product_id.display_name) ) return super().action_post()
Use super() instead of super(classname, self)
Use super() instead of super(classname, self)
Python
agpl-3.0
OCA/account-closing,OCA/account-closing
from odoo import _, models from odoo.exceptions import UserError class AccountMove(models.Model): _inherit = "account.move" def action_post(self): for move in self: for line in move.line_ids: if line.product_id and line.product_id.must_have_dates: if not line.start_date or not line.end_date: raise UserError( _( "Missing Start Date and End Date for invoice " "line with Product '%s' which has the " "property 'Must Have Start and End Dates'." ) % (line.product_id.display_name) ) - return super(AccountMove, self).action_post() + return super().action_post()
Use super() instead of super(classname, self)
## Code Before: from odoo import _, models from odoo.exceptions import UserError class AccountMove(models.Model): _inherit = "account.move" def action_post(self): for move in self: for line in move.line_ids: if line.product_id and line.product_id.must_have_dates: if not line.start_date or not line.end_date: raise UserError( _( "Missing Start Date and End Date for invoice " "line with Product '%s' which has the " "property 'Must Have Start and End Dates'." ) % (line.product_id.display_name) ) return super(AccountMove, self).action_post() ## Instruction: Use super() instead of super(classname, self) ## Code After: from odoo import _, models from odoo.exceptions import UserError class AccountMove(models.Model): _inherit = "account.move" def action_post(self): for move in self: for line in move.line_ids: if line.product_id and line.product_id.must_have_dates: if not line.start_date or not line.end_date: raise UserError( _( "Missing Start Date and End Date for invoice " "line with Product '%s' which has the " "property 'Must Have Start and End Dates'." ) % (line.product_id.display_name) ) return super().action_post()
b0254fd4090c0d17f60a87f3fe5fe28c0382310e
scripts/v0to1.py
scripts/v0to1.py
import sys import h5py infiles = sys.argv[1:] for infile in infiles: with h5py.File(infile, 'a') as h5: print(infile) if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1: if 'matrix' in h5 and not 'pixels' in h5: print('renaming matrix --> pixels') h5['pixels'] = h5['matrix'] if 'scaffolds' in h5 and not 'chroms' in h5: print('renaming scaffolds --> chroms') h5['chroms'] = h5['scaffolds'] h5.attrs['format-version'] = 1
import sys import h5py infiles = sys.argv[1:] for infile in infiles: with h5py.File(infile, 'a') as h5: print(infile) if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1: if 'matrix' in h5 and not 'pixels' in h5: print('renaming matrix --> pixels') h5['pixels'] = h5['matrix'] del h5['matrix'] if 'scaffolds' in h5 and not 'chroms' in h5: print('renaming scaffolds --> chroms') h5['chroms'] = h5['scaffolds'] del h5['scaffolds'] h5.attrs['format-version'] = 1
Drop old names from v0
Drop old names from v0
Python
bsd-3-clause
mirnylab/cooler
import sys import h5py infiles = sys.argv[1:] for infile in infiles: with h5py.File(infile, 'a') as h5: print(infile) if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1: if 'matrix' in h5 and not 'pixels' in h5: print('renaming matrix --> pixels') h5['pixels'] = h5['matrix'] + del h5['matrix'] if 'scaffolds' in h5 and not 'chroms' in h5: print('renaming scaffolds --> chroms') h5['chroms'] = h5['scaffolds'] + del h5['scaffolds'] h5.attrs['format-version'] = 1
Drop old names from v0
## Code Before: import sys import h5py infiles = sys.argv[1:] for infile in infiles: with h5py.File(infile, 'a') as h5: print(infile) if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1: if 'matrix' in h5 and not 'pixels' in h5: print('renaming matrix --> pixels') h5['pixels'] = h5['matrix'] if 'scaffolds' in h5 and not 'chroms' in h5: print('renaming scaffolds --> chroms') h5['chroms'] = h5['scaffolds'] h5.attrs['format-version'] = 1 ## Instruction: Drop old names from v0 ## Code After: import sys import h5py infiles = sys.argv[1:] for infile in infiles: with h5py.File(infile, 'a') as h5: print(infile) if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1: if 'matrix' in h5 and not 'pixels' in h5: print('renaming matrix --> pixels') h5['pixels'] = h5['matrix'] del h5['matrix'] if 'scaffolds' in h5 and not 'chroms' in h5: print('renaming scaffolds --> chroms') h5['chroms'] = h5['scaffolds'] del h5['scaffolds'] h5.attrs['format-version'] = 1
43350965e171e6a3bfd89af3dd192ab5c9281b3a
vumi/blinkenlights/tests/test_message20110818.py
vumi/blinkenlights/tests/test_message20110818.py
from twisted.trial.unittest import TestCase import vumi.blinkenlights.message20110818 as message import time class TestMessage(TestCase): def test_to_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msg = message.MetricMessage() msg.append(datapoint) self.assertEqual(msg.to_dict(), { 'datapoints': [datapoint], }) def test_from_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msgdict = {"datapoints": [datapoint]} msg = message.MetricMessage.from_dict(msgdict) self.assertEqual(msg._datapoints, [datapoint])
from twisted.trial.unittest import TestCase import vumi.blinkenlights.message20110818 as message import time class TestMessage(TestCase): def test_to_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msg = message.MetricMessage() msg.append(datapoint) self.assertEqual(msg.to_dict(), { 'datapoints': [datapoint], }) def test_from_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msgdict = {"datapoints": [datapoint]} msg = message.MetricMessage.from_dict(msgdict) self.assertEqual(msg._datapoints, [datapoint]) def test_extend(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msg = message.MetricMessage() msg.extend([datapoint, datapoint, datapoint]) self.assertEqual(msg._datapoints, [ datapoint, datapoint, datapoint])
Add test for extend method.
Add test for extend method.
Python
bsd-3-clause
TouK/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,TouK/vumi,harrissoerja/vumi,harrissoerja/vumi
from twisted.trial.unittest import TestCase import vumi.blinkenlights.message20110818 as message import time class TestMessage(TestCase): def test_to_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msg = message.MetricMessage() msg.append(datapoint) self.assertEqual(msg.to_dict(), { 'datapoints': [datapoint], }) def test_from_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msgdict = {"datapoints": [datapoint]} msg = message.MetricMessage.from_dict(msgdict) self.assertEqual(msg._datapoints, [datapoint]) + def test_extend(self): + now = time.time() + datapoint = ("vumi.w1.a_metric", now, 1.5) + msg = message.MetricMessage() + msg.extend([datapoint, datapoint, datapoint]) + self.assertEqual(msg._datapoints, [ + datapoint, datapoint, datapoint]) +
Add test for extend method.
## Code Before: from twisted.trial.unittest import TestCase import vumi.blinkenlights.message20110818 as message import time class TestMessage(TestCase): def test_to_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msg = message.MetricMessage() msg.append(datapoint) self.assertEqual(msg.to_dict(), { 'datapoints': [datapoint], }) def test_from_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msgdict = {"datapoints": [datapoint]} msg = message.MetricMessage.from_dict(msgdict) self.assertEqual(msg._datapoints, [datapoint]) ## Instruction: Add test for extend method. ## Code After: from twisted.trial.unittest import TestCase import vumi.blinkenlights.message20110818 as message import time class TestMessage(TestCase): def test_to_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msg = message.MetricMessage() msg.append(datapoint) self.assertEqual(msg.to_dict(), { 'datapoints': [datapoint], }) def test_from_dict(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msgdict = {"datapoints": [datapoint]} msg = message.MetricMessage.from_dict(msgdict) self.assertEqual(msg._datapoints, [datapoint]) def test_extend(self): now = time.time() datapoint = ("vumi.w1.a_metric", now, 1.5) msg = message.MetricMessage() msg.extend([datapoint, datapoint, datapoint]) self.assertEqual(msg._datapoints, [ datapoint, datapoint, datapoint])
34960807eac1818a8167ff015e941c42be8827da
checkenv.py
checkenv.py
from colorama import Fore from pkgutil import iter_modules def check_import(packagename): """ Checks that a package is present. Returns true if it is available, and false if not available. """ if packagename in (name for _, name, _ in iter_modules()): return True else: return False packages = ['missingno', 'pytest', 'pytest_cov', 'tinydb', 'yaml', 'pandas_summary', 'environment_kernels', 'hypothesis'] try: for pkg in packages: assert check_import(pkg) print(Fore.GREEN + 'All packages found; environment checks passed.') except AssertionError: print(Fore.RED + f"{pkg} cannot be found. Please pip or conda install.")
from colorama import Fore, Style from pkgutil import iter_modules def check_import(packagename): """ Checks that a package is present. Returns true if it is available, and false if not available. """ if packagename in (name for _, name, _ in iter_modules()): return True else: return False packages = ['missingno', 'pytest', 'pytest_cov', 'tinydb', 'yaml', 'pandas_summary', 'environment_kernels', 'hypothesis'] try: for pkg in packages: assert check_import(pkg) print(Fore.GREEN + 'All packages found; environment checks passed.') except AssertionError: print(Fore.RED + f"{pkg} cannot be found. Please pip or conda install.") Style.RESET_ALL
Reset colors at the end
Reset colors at the end
Python
mit
ericmjl/data-testing-tutorial,ericmjl/data-testing-tutorial
- from colorama import Fore + from colorama import Fore, Style from pkgutil import iter_modules def check_import(packagename): """ Checks that a package is present. Returns true if it is available, and false if not available. """ if packagename in (name for _, name, _ in iter_modules()): return True else: return False packages = ['missingno', 'pytest', 'pytest_cov', 'tinydb', 'yaml', 'pandas_summary', 'environment_kernels', 'hypothesis'] try: for pkg in packages: assert check_import(pkg) print(Fore.GREEN + 'All packages found; environment checks passed.') except AssertionError: print(Fore.RED + f"{pkg} cannot be found. Please pip or conda install.") + Style.RESET_ALL +
Reset colors at the end
## Code Before: from colorama import Fore from pkgutil import iter_modules def check_import(packagename): """ Checks that a package is present. Returns true if it is available, and false if not available. """ if packagename in (name for _, name, _ in iter_modules()): return True else: return False packages = ['missingno', 'pytest', 'pytest_cov', 'tinydb', 'yaml', 'pandas_summary', 'environment_kernels', 'hypothesis'] try: for pkg in packages: assert check_import(pkg) print(Fore.GREEN + 'All packages found; environment checks passed.') except AssertionError: print(Fore.RED + f"{pkg} cannot be found. Please pip or conda install.") ## Instruction: Reset colors at the end ## Code After: from colorama import Fore, Style from pkgutil import iter_modules def check_import(packagename): """ Checks that a package is present. Returns true if it is available, and false if not available. """ if packagename in (name for _, name, _ in iter_modules()): return True else: return False packages = ['missingno', 'pytest', 'pytest_cov', 'tinydb', 'yaml', 'pandas_summary', 'environment_kernels', 'hypothesis'] try: for pkg in packages: assert check_import(pkg) print(Fore.GREEN + 'All packages found; environment checks passed.') except AssertionError: print(Fore.RED + f"{pkg} cannot be found. Please pip or conda install.") Style.RESET_ALL
dfa752590c944fc07253c01c3d99b640a46dae1d
jinja2_time/jinja2_time.py
jinja2_time/jinja2_time.py
import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.extend( datetime_format='%Y-%m-%d', ) def _now(self, timezone, datetime_format): datetime_format = datetime_format or self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): lineno = next(parser.stream).lineno args = [parser.parse_expression()] if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) call = self.call_method('_now', args, lineno=lineno) return nodes.Output([call], lineno=lineno)
import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.extend(datetime_format='%Y-%m-%d') def _datetime(self, timezone, operator, offset, datetime_format): d = arrow.now(timezone) # Parse replace kwargs from offset and include operator replace_params = {} for param in offset.split(','): interval, value = param.split('=') replace_params[interval] = float(operator + value) d = d.replace(**replace_params) if datetime_format is None: datetime_format = self.environment.datetime_format return d.strftime(datetime_format) def _now(self, timezone, datetime_format): if datetime_format is None: datetime_format = self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): lineno = next(parser.stream).lineno node = parser.parse_expression() if parser.stream.skip_if('comma'): datetime_format = parser.parse_expression() else: datetime_format = nodes.Const(None) if isinstance(node, nodes.Add): call_method = self.call_method( '_datetime', [node.left, nodes.Const('+'), node.right, datetime_format], lineno=lineno, ) elif isinstance(node, nodes.Sub): call_method = self.call_method( '_datetime', [node.left, nodes.Const('-'), node.right, datetime_format], lineno=lineno, ) else: call_method = self.call_method( '_now', [node, datetime_format], lineno=lineno, ) return nodes.Output([call_method], lineno=lineno)
Implement parser method for optional offset
Implement parser method for optional offset
Python
mit
hackebrot/jinja2-time
import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment - environment.extend( - datetime_format='%Y-%m-%d', - ) + environment.extend(datetime_format='%Y-%m-%d') + + def _datetime(self, timezone, operator, offset, datetime_format): + d = arrow.now(timezone) + + # Parse replace kwargs from offset and include operator + replace_params = {} + for param in offset.split(','): + interval, value = param.split('=') + replace_params[interval] = float(operator + value) + d = d.replace(**replace_params) + + if datetime_format is None: + datetime_format = self.environment.datetime_format + return d.strftime(datetime_format) def _now(self, timezone, datetime_format): + if datetime_format is None: - datetime_format = datetime_format or self.environment.datetime_format + datetime_format = self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): lineno = next(parser.stream).lineno - args = [parser.parse_expression()] + node = parser.parse_expression() if parser.stream.skip_if('comma'): - args.append(parser.parse_expression()) + datetime_format = parser.parse_expression() else: - args.append(nodes.Const(None)) + datetime_format = nodes.Const(None) - call = self.call_method('_now', args, lineno=lineno) + if isinstance(node, nodes.Add): + call_method = self.call_method( + '_datetime', + [node.left, nodes.Const('+'), node.right, datetime_format], + lineno=lineno, + ) + elif isinstance(node, nodes.Sub): + call_method = self.call_method( + '_datetime', + [node.left, nodes.Const('-'), node.right, datetime_format], + lineno=lineno, + ) + else: + call_method = self.call_method( + '_now', + [node, datetime_format], + lineno=lineno, + ) + return nodes.Output([call_method], lineno=lineno) - return nodes.Output([call], lineno=lineno) -
Implement parser method for optional offset
## Code Before: import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.extend( datetime_format='%Y-%m-%d', ) def _now(self, timezone, datetime_format): datetime_format = datetime_format or self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): lineno = next(parser.stream).lineno args = [parser.parse_expression()] if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) call = self.call_method('_now', args, lineno=lineno) return nodes.Output([call], lineno=lineno) ## Instruction: Implement parser method for optional offset ## Code After: import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.extend(datetime_format='%Y-%m-%d') def _datetime(self, timezone, operator, offset, datetime_format): d = arrow.now(timezone) # Parse replace kwargs from offset and include operator replace_params = {} for param in offset.split(','): interval, value = param.split('=') replace_params[interval] = float(operator + value) d = d.replace(**replace_params) if datetime_format is None: datetime_format = self.environment.datetime_format return d.strftime(datetime_format) def _now(self, timezone, datetime_format): if datetime_format is None: datetime_format = self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): lineno = next(parser.stream).lineno node = parser.parse_expression() if parser.stream.skip_if('comma'): datetime_format = parser.parse_expression() else: datetime_format = nodes.Const(None) if isinstance(node, nodes.Add): call_method = self.call_method( '_datetime', [node.left, nodes.Const('+'), node.right, datetime_format], lineno=lineno, ) elif isinstance(node, nodes.Sub): call_method = self.call_method( '_datetime', [node.left, nodes.Const('-'), node.right, datetime_format], lineno=lineno, ) else: call_method = self.call_method( '_now', [node, datetime_format], lineno=lineno, ) return nodes.Output([call_method], lineno=lineno)
d68f28581cd3c3f57f7c41adbd65676887a51136
opps/channels/tests/test_forms.py
opps/channels/tests/test_forms.py
from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create(username=u'test', password='test') self.site = Site.objects.filter(name=u'example.com').get() self.parent = Channel.objects.create(name=u'Home', slug=u'home', description=u'home page', site=self.site, user=self.user) def test_init(self): """ Test successful init without data """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(isinstance(form.instance, Channel)) self.assertEqual(form.instance.pk, self.parent.pk)
from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create(username=u'test', password='test') self.site = Site.objects.filter(name=u'example.com').get() self.parent = Channel.objects.create(name=u'Home', slug=u'home', description=u'home page', site=self.site, user=self.user) def test_init(self): """ Test successful init without data """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(isinstance(form.instance, Channel)) self.assertEqual(form.instance.pk, self.parent.pk) self.assertEqual(int(form.fields['slug'].widget.attrs['maxlength']), 150) def test_readonly_slug(self): """ Check readonly field slug """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(form.fields['slug'].widget.attrs['readonly']) form_2 = ChannelAdminForm() self.assertNotIn('readonly', form_2.fields['slug'].widget.attrs)
Add test check readonly field slug of channel
Add test check readonly field slug of channel
Python
mit
jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,jeanmask/opps,opps/opps
from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create(username=u'test', password='test') self.site = Site.objects.filter(name=u'example.com').get() self.parent = Channel.objects.create(name=u'Home', slug=u'home', description=u'home page', site=self.site, user=self.user) def test_init(self): """ Test successful init without data """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(isinstance(form.instance, Channel)) self.assertEqual(form.instance.pk, self.parent.pk) + self.assertEqual(int(form.fields['slug'].widget.attrs['maxlength']), 150) + def test_readonly_slug(self): + """ + Check readonly field slug + """ + form = ChannelAdminForm(instance=self.parent) + self.assertTrue(form.fields['slug'].widget.attrs['readonly']) + form_2 = ChannelAdminForm() + self.assertNotIn('readonly', form_2.fields['slug'].widget.attrs) +
Add test check readonly field slug of channel
## Code Before: from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create(username=u'test', password='test') self.site = Site.objects.filter(name=u'example.com').get() self.parent = Channel.objects.create(name=u'Home', slug=u'home', description=u'home page', site=self.site, user=self.user) def test_init(self): """ Test successful init without data """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(isinstance(form.instance, Channel)) self.assertEqual(form.instance.pk, self.parent.pk) ## Instruction: Add test check readonly field slug of channel ## Code After: from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create(username=u'test', password='test') self.site = Site.objects.filter(name=u'example.com').get() self.parent = Channel.objects.create(name=u'Home', slug=u'home', description=u'home page', site=self.site, user=self.user) def test_init(self): """ Test successful init without data """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(isinstance(form.instance, Channel)) self.assertEqual(form.instance.pk, self.parent.pk) self.assertEqual(int(form.fields['slug'].widget.attrs['maxlength']), 150) def test_readonly_slug(self): """ Check readonly field slug """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(form.fields['slug'].widget.attrs['readonly']) form_2 = ChannelAdminForm() self.assertNotIn('readonly', form_2.fields['slug'].widget.attrs)
b97115679929dfe4f69618f756850617f265048f
service/pixelated/config/site.py
service/pixelated/config/site.py
from twisted.web.server import Site, Request class AddCSPHeaderRequest(Request): CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'" def process(self): self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES) self.setHeader('X-Frame-Options', 'SAMEORIGIN') self.setHeader('X-XSS-Protection', '1; mode=block') self.setHeader('X-Content-Type-Options', 'nosniff') if self.isSecure(): self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains') Request.process(self) class PixelatedSite(Site): requestFactory = AddCSPHeaderRequest @classmethod def enable_csp_requests(cls): cls.requestFactory = AddCSPHeaderRequest @classmethod def disable_csp_requests(cls): cls.requestFactory = Site.requestFactory
from twisted.web.server import Site, Request class AddSecurityHeadersRequest(Request): CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'" def process(self): self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES) self.setHeader('X-Frame-Options', 'SAMEORIGIN') self.setHeader('X-XSS-Protection', '1; mode=block') self.setHeader('X-Content-Type-Options', 'nosniff') if self.isSecure(): self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains') Request.process(self) class PixelatedSite(Site): requestFactory = AddSecurityHeadersRequest @classmethod def enable_csp_requests(cls): cls.requestFactory = AddSecurityHeadersRequest @classmethod def disable_csp_requests(cls): cls.requestFactory = Site.requestFactory
Rename class to match intent
Rename class to match intent
Python
agpl-3.0
pixelated-project/pixelated-user-agent,pixelated/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated/pixelated-user-agent,pixelated-project/pixelated-user-agent,pixelated/pixelated-user-agent,pixelated/pixelated-user-agent,pixelated/pixelated-user-agent
from twisted.web.server import Site, Request - class AddCSPHeaderRequest(Request): + class AddSecurityHeadersRequest(Request): CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'" def process(self): self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES) self.setHeader('X-Frame-Options', 'SAMEORIGIN') self.setHeader('X-XSS-Protection', '1; mode=block') self.setHeader('X-Content-Type-Options', 'nosniff') if self.isSecure(): self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains') Request.process(self) class PixelatedSite(Site): - requestFactory = AddCSPHeaderRequest + requestFactory = AddSecurityHeadersRequest @classmethod def enable_csp_requests(cls): - cls.requestFactory = AddCSPHeaderRequest + cls.requestFactory = AddSecurityHeadersRequest @classmethod def disable_csp_requests(cls): cls.requestFactory = Site.requestFactory
Rename class to match intent
## Code Before: from twisted.web.server import Site, Request class AddCSPHeaderRequest(Request): CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'" def process(self): self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES) self.setHeader('X-Frame-Options', 'SAMEORIGIN') self.setHeader('X-XSS-Protection', '1; mode=block') self.setHeader('X-Content-Type-Options', 'nosniff') if self.isSecure(): self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains') Request.process(self) class PixelatedSite(Site): requestFactory = AddCSPHeaderRequest @classmethod def enable_csp_requests(cls): cls.requestFactory = AddCSPHeaderRequest @classmethod def disable_csp_requests(cls): cls.requestFactory = Site.requestFactory ## Instruction: Rename class to match intent ## Code After: from twisted.web.server import Site, Request class AddSecurityHeadersRequest(Request): CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'" def process(self): self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES) self.setHeader('X-Frame-Options', 'SAMEORIGIN') self.setHeader('X-XSS-Protection', '1; mode=block') self.setHeader('X-Content-Type-Options', 'nosniff') if self.isSecure(): self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains') Request.process(self) class PixelatedSite(Site): requestFactory = AddSecurityHeadersRequest @classmethod def enable_csp_requests(cls): cls.requestFactory = AddSecurityHeadersRequest @classmethod def disable_csp_requests(cls): cls.requestFactory = Site.requestFactory
4b245b9a859552adb9c19fafc4bdfab5780782f2
d1_common_python/src/d1_common/__init__.py
d1_common_python/src/d1_common/__init__.py
__version__ = "2.1.0" __all__ = [ 'const', 'exceptions', 'upload', 'xmlrunner', 'types.exceptions', 'types.dataoneTypes', 'types.dataoneErrors', 'ext.mimeparser', ]
__version__ = "2.1.0" # Set default logging handler to avoid "No handler found" warnings. import logging try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())
Add logging NullHandler to prevent "no handler found" errors
Add logging NullHandler to prevent "no handler found" errors This fixes the issue where "no handler found" errors would be printed by the library if library clients did not set up logging.
Python
apache-2.0
DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python
__version__ = "2.1.0" + # Set default logging handler to avoid "No handler found" warnings. + import logging - __all__ = [ - 'const', - 'exceptions', - 'upload', - 'xmlrunner', - 'types.exceptions', - 'types.dataoneTypes', - 'types.dataoneErrors', - 'ext.mimeparser', - ] + try: + from logging import NullHandler + except ImportError: + class NullHandler(logging.Handler): + def emit(self, record): + pass + + logging.getLogger(__name__).addHandler(NullHandler()) +
Add logging NullHandler to prevent "no handler found" errors
## Code Before: __version__ = "2.1.0" __all__ = [ 'const', 'exceptions', 'upload', 'xmlrunner', 'types.exceptions', 'types.dataoneTypes', 'types.dataoneErrors', 'ext.mimeparser', ] ## Instruction: Add logging NullHandler to prevent "no handler found" errors ## Code After: __version__ = "2.1.0" # Set default logging handler to avoid "No handler found" warnings. import logging try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())
af8a96e08029e2dc746cfa1ecbd7a6d02be1c374
InvenTree/company/forms.py
InvenTree/company/forms.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from InvenTree.forms import HelperForm from .models import Company from .models import SupplierPart from .models import SupplierPriceBreak class EditCompanyForm(HelperForm): """ Form for editing a Company object """ class Meta: model = Company fields = [ 'name', 'description', 'website', 'address', 'phone', 'email', 'contact', 'is_customer', 'is_supplier', 'notes' ] class CompanyImageForm(HelperForm): """ Form for uploading a Company image """ class Meta: model = Company fields = [ 'image' ] class EditSupplierPartForm(HelperForm): """ Form for editing a SupplierPart object """ class Meta: model = SupplierPart fields = [ 'part', 'supplier', 'SKU', 'description', 'manufacturer', 'MPN', 'URL', 'note', 'base_cost', 'multiple', 'packaging', 'lead_time' ] class EditPriceBreakForm(HelperForm): """ Form for creating / editing a supplier price break """ class Meta: model = SupplierPriceBreak fields = [ 'part', 'quantity', 'cost' ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from InvenTree.forms import HelperForm from .models import Company from .models import SupplierPart from .models import SupplierPriceBreak class EditCompanyForm(HelperForm): """ Form for editing a Company object """ class Meta: model = Company fields = [ 'name', 'description', 'website', 'address', 'phone', 'email', 'contact', 'is_customer', 'is_supplier', 'notes' ] class CompanyImageForm(HelperForm): """ Form for uploading a Company image """ class Meta: model = Company fields = [ 'image' ] class EditSupplierPartForm(HelperForm): """ Form for editing a SupplierPart object """ class Meta: model = SupplierPart fields = [ 'part', 'supplier', 'SKU', 'description', 'manufacturer', 'MPN', 'URL', 'note', 'base_cost', 'multiple', 'packaging', 'lead_time' ] class EditPriceBreakForm(HelperForm): """ Form for creating / editing a supplier price break """ class Meta: model = SupplierPriceBreak fields = [ 'part', 'quantity', 'cost', 'currency', ]
Add option to edit currency
Add option to edit currency
Python
mit
SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree
# -*- coding: utf-8 -*- from __future__ import unicode_literals from InvenTree.forms import HelperForm from .models import Company from .models import SupplierPart from .models import SupplierPriceBreak class EditCompanyForm(HelperForm): """ Form for editing a Company object """ class Meta: model = Company fields = [ 'name', 'description', 'website', 'address', 'phone', 'email', 'contact', 'is_customer', 'is_supplier', 'notes' ] class CompanyImageForm(HelperForm): """ Form for uploading a Company image """ class Meta: model = Company fields = [ 'image' ] class EditSupplierPartForm(HelperForm): """ Form for editing a SupplierPart object """ class Meta: model = SupplierPart fields = [ 'part', 'supplier', 'SKU', 'description', 'manufacturer', 'MPN', 'URL', 'note', 'base_cost', 'multiple', 'packaging', 'lead_time' ] class EditPriceBreakForm(HelperForm): """ Form for creating / editing a supplier price break """ class Meta: model = SupplierPriceBreak fields = [ 'part', 'quantity', - 'cost' + 'cost', + 'currency', ]
Add option to edit currency
## Code Before: # -*- coding: utf-8 -*- from __future__ import unicode_literals from InvenTree.forms import HelperForm from .models import Company from .models import SupplierPart from .models import SupplierPriceBreak class EditCompanyForm(HelperForm): """ Form for editing a Company object """ class Meta: model = Company fields = [ 'name', 'description', 'website', 'address', 'phone', 'email', 'contact', 'is_customer', 'is_supplier', 'notes' ] class CompanyImageForm(HelperForm): """ Form for uploading a Company image """ class Meta: model = Company fields = [ 'image' ] class EditSupplierPartForm(HelperForm): """ Form for editing a SupplierPart object """ class Meta: model = SupplierPart fields = [ 'part', 'supplier', 'SKU', 'description', 'manufacturer', 'MPN', 'URL', 'note', 'base_cost', 'multiple', 'packaging', 'lead_time' ] class EditPriceBreakForm(HelperForm): """ Form for creating / editing a supplier price break """ class Meta: model = SupplierPriceBreak fields = [ 'part', 'quantity', 'cost' ] ## Instruction: Add option to edit currency ## Code After: # -*- coding: utf-8 -*- from __future__ import unicode_literals from InvenTree.forms import HelperForm from .models import Company from .models import SupplierPart from .models import SupplierPriceBreak class EditCompanyForm(HelperForm): """ Form for editing a Company object """ class Meta: model = Company fields = [ 'name', 'description', 'website', 'address', 'phone', 'email', 'contact', 'is_customer', 'is_supplier', 'notes' ] class CompanyImageForm(HelperForm): """ Form for uploading a Company image """ class Meta: model = Company fields = [ 'image' ] class EditSupplierPartForm(HelperForm): """ Form for editing a SupplierPart object """ class Meta: model = SupplierPart fields = [ 'part', 'supplier', 'SKU', 'description', 'manufacturer', 'MPN', 'URL', 'note', 'base_cost', 'multiple', 'packaging', 'lead_time' ] class EditPriceBreakForm(HelperForm): """ Form for creating / editing a supplier price break """ class Meta: model = SupplierPriceBreak fields = [ 'part', 'quantity', 'cost', 'currency', ]
824c46b7d3953e1933a72def4edf058a577487ea
byceps/services/attendance/transfer/models.py
byceps/services/attendance/transfer/models.py
from attr import attrib, attrs from ....services.seating.models.seat import Seat from ....services.user.models.user import User @attrs(slots=True) # Not yet frozen b/c models are not immutable. class Attendee: user = attrib(type=User) seat = attrib(type=Seat) checked_in = attrib(type=bool)
from dataclasses import dataclass from ....services.seating.models.seat import Seat from ....services.user.models.user import User @dataclass # Not yet frozen b/c models are not immutable. class Attendee: user: User seat: Seat checked_in: bool
Use `dataclass` instead of `attr` for attendance model
Use `dataclass` instead of `attr` for attendance model
Python
bsd-3-clause
m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps
- from attr import attrib, attrs + from dataclasses import dataclass from ....services.seating.models.seat import Seat from ....services.user.models.user import User - @attrs(slots=True) # Not yet frozen b/c models are not immutable. + @dataclass # Not yet frozen b/c models are not immutable. class Attendee: - user = attrib(type=User) - seat = attrib(type=Seat) - checked_in = attrib(type=bool) + user: User + seat: Seat + checked_in: bool
Use `dataclass` instead of `attr` for attendance model
## Code Before: from attr import attrib, attrs from ....services.seating.models.seat import Seat from ....services.user.models.user import User @attrs(slots=True) # Not yet frozen b/c models are not immutable. class Attendee: user = attrib(type=User) seat = attrib(type=Seat) checked_in = attrib(type=bool) ## Instruction: Use `dataclass` instead of `attr` for attendance model ## Code After: from dataclasses import dataclass from ....services.seating.models.seat import Seat from ....services.user.models.user import User @dataclass # Not yet frozen b/c models are not immutable. class Attendee: user: User seat: Seat checked_in: bool
7d52ee6030b2e59a6b6cb6dce78686e8d551281b
examples/horizontal_boxplot.py
examples/horizontal_boxplot.py
import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks") # Initialize the figure f, ax = plt.subplots(figsize=(7, 6)) ax.set_xscale("log") # Load the example planets dataset planets = sns.load_dataset("planets") # Plot the orbital period with horizontal boxes sns.boxplot(x="distance", y="method", data=planets, whis=np.inf, palette="vlag") # Add in points to show each observation sns.swarmplot(x="distance", y="method", data=planets, size=2, color=".3", linewidth=0) # Make the quantitative axis logarithmic ax.xaxis.grid(True) ax.set(ylabel="") sns.despine(trim=True, left=True)
import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks") # Initialize the figure with a logarithmic x axis f, ax = plt.subplots(figsize=(7, 6)) ax.set_xscale("log") # Load the example planets dataset planets = sns.load_dataset("planets") # Plot the orbital period with horizontal boxes sns.boxplot(x="distance", y="method", data=planets, whis=np.inf, palette="vlag") # Add in points to show each observation sns.swarmplot(x="distance", y="method", data=planets, size=2, color=".3", linewidth=0) # Tweak the visual presentation ax.xaxis.grid(True) ax.set(ylabel="") sns.despine(trim=True, left=True)
Fix comments in horizontal boxplot example
Fix comments in horizontal boxplot example
Python
bsd-3-clause
mwaskom/seaborn,phobson/seaborn,arokem/seaborn,lukauskas/seaborn,anntzer/seaborn,arokem/seaborn,sauliusl/seaborn,mwaskom/seaborn,phobson/seaborn,petebachant/seaborn,anntzer/seaborn,lukauskas/seaborn
import numpy as np import seaborn as sns import matplotlib.pyplot as plt + sns.set(style="ticks") - # Initialize the figure + # Initialize the figure with a logarithmic x axis f, ax = plt.subplots(figsize=(7, 6)) ax.set_xscale("log") # Load the example planets dataset planets = sns.load_dataset("planets") # Plot the orbital period with horizontal boxes sns.boxplot(x="distance", y="method", data=planets, whis=np.inf, palette="vlag") # Add in points to show each observation sns.swarmplot(x="distance", y="method", data=planets, size=2, color=".3", linewidth=0) + # Tweak the visual presentation - - # Make the quantitative axis logarithmic ax.xaxis.grid(True) ax.set(ylabel="") sns.despine(trim=True, left=True)
Fix comments in horizontal boxplot example
## Code Before: import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks") # Initialize the figure f, ax = plt.subplots(figsize=(7, 6)) ax.set_xscale("log") # Load the example planets dataset planets = sns.load_dataset("planets") # Plot the orbital period with horizontal boxes sns.boxplot(x="distance", y="method", data=planets, whis=np.inf, palette="vlag") # Add in points to show each observation sns.swarmplot(x="distance", y="method", data=planets, size=2, color=".3", linewidth=0) # Make the quantitative axis logarithmic ax.xaxis.grid(True) ax.set(ylabel="") sns.despine(trim=True, left=True) ## Instruction: Fix comments in horizontal boxplot example ## Code After: import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks") # Initialize the figure with a logarithmic x axis f, ax = plt.subplots(figsize=(7, 6)) ax.set_xscale("log") # Load the example planets dataset planets = sns.load_dataset("planets") # Plot the orbital period with horizontal boxes sns.boxplot(x="distance", y="method", data=planets, whis=np.inf, palette="vlag") # Add in points to show each observation sns.swarmplot(x="distance", y="method", data=planets, size=2, color=".3", linewidth=0) # Tweak the visual presentation ax.xaxis.grid(True) ax.set(ylabel="") sns.despine(trim=True, left=True)
ca4be3892ec0c1b5bc337a9fae10503b5f7f765a
bika/lims/browser/validation.py
bika/lims/browser/validation.py
from Products.Archetypes.browser.validation import InlineValidationView as _IVV from Acquisition import aq_inner from Products.CMFCore.utils import getToolByName import json SKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference') class InlineValidationView(_IVV): def __call__(self, uid, fname, value): '''Validate a given field. Return any error messages. ''' res = {'errmsg': ''} if value not in self.request: return json.dumps(res) rc = getToolByName(aq_inner(self.context), 'reference_catalog') instance = rc.lookupObject(uid) # make sure this works for portal_factory items if instance is None: instance = self.context field = instance.getField(fname) if field and field.type not in SKIP_VALIDATION_FIELDTYPES: return super(InlineValidationView, self).__call__(uid, fname, value) self.request.response.setHeader('Content-Type', 'application/json') return json.dumps(res)
from Products.Archetypes.browser.validation import InlineValidationView as _IVV from Acquisition import aq_inner from Products.CMFCore.utils import getToolByName import json SKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference') class InlineValidationView(_IVV): def __call__(self, uid, fname, value): '''Validate a given field. Return any error messages. ''' res = {'errmsg': ''} rc = getToolByName(aq_inner(self.context), 'reference_catalog') instance = rc.lookupObject(uid) # make sure this works for portal_factory items if instance is None: instance = self.context field = instance.getField(fname) if field and field.type not in SKIP_VALIDATION_FIELDTYPES: return super(InlineValidationView, self).__call__(uid, fname, value) self.request.response.setHeader('Content-Type', 'application/json') return json.dumps(res)
Revert "Inline Validation fails silently if request is malformed"
Revert "Inline Validation fails silently if request is malformed" This reverts commit 723e4eb603568d3a60190d8d292cc335a74b79d5.
Python
agpl-3.0
labsanmartin/Bika-LIMS,veroc/Bika-LIMS,veroc/Bika-LIMS,rockfruit/bika.lims,veroc/Bika-LIMS,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,rockfruit/bika.lims,labsanmartin/Bika-LIMS
from Products.Archetypes.browser.validation import InlineValidationView as _IVV from Acquisition import aq_inner from Products.CMFCore.utils import getToolByName import json SKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference') class InlineValidationView(_IVV): def __call__(self, uid, fname, value): '''Validate a given field. Return any error messages. ''' res = {'errmsg': ''} - if value not in self.request: - return json.dumps(res) - rc = getToolByName(aq_inner(self.context), 'reference_catalog') instance = rc.lookupObject(uid) # make sure this works for portal_factory items if instance is None: instance = self.context field = instance.getField(fname) if field and field.type not in SKIP_VALIDATION_FIELDTYPES: return super(InlineValidationView, self).__call__(uid, fname, value) self.request.response.setHeader('Content-Type', 'application/json') return json.dumps(res)
Revert "Inline Validation fails silently if request is malformed"
## Code Before: from Products.Archetypes.browser.validation import InlineValidationView as _IVV from Acquisition import aq_inner from Products.CMFCore.utils import getToolByName import json SKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference') class InlineValidationView(_IVV): def __call__(self, uid, fname, value): '''Validate a given field. Return any error messages. ''' res = {'errmsg': ''} if value not in self.request: return json.dumps(res) rc = getToolByName(aq_inner(self.context), 'reference_catalog') instance = rc.lookupObject(uid) # make sure this works for portal_factory items if instance is None: instance = self.context field = instance.getField(fname) if field and field.type not in SKIP_VALIDATION_FIELDTYPES: return super(InlineValidationView, self).__call__(uid, fname, value) self.request.response.setHeader('Content-Type', 'application/json') return json.dumps(res) ## Instruction: Revert "Inline Validation fails silently if request is malformed" ## Code After: from Products.Archetypes.browser.validation import InlineValidationView as _IVV from Acquisition import aq_inner from Products.CMFCore.utils import getToolByName import json SKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference') class InlineValidationView(_IVV): def __call__(self, uid, fname, value): '''Validate a given field. Return any error messages. ''' res = {'errmsg': ''} rc = getToolByName(aq_inner(self.context), 'reference_catalog') instance = rc.lookupObject(uid) # make sure this works for portal_factory items if instance is None: instance = self.context field = instance.getField(fname) if field and field.type not in SKIP_VALIDATION_FIELDTYPES: return super(InlineValidationView, self).__call__(uid, fname, value) self.request.response.setHeader('Content-Type', 'application/json') return json.dumps(res)
6949339cda8c60b74341f854d9a00aa8abbfe4d5
test/level_sets_measure_test.py
test/level_sets_measure_test.py
__author__ = 'intsco' import cPickle from engine.pyIMS.image_measures.level_sets_measure import measure_of_chaos_dict from unittest import TestCase import unittest from os.path import join, realpath, dirname class MeasureOfChaosDictTest(TestCase): def setUp(self): self.rows, self.cols = 65, 65 self.input_fn = join(dirname(realpath(__file__)), 'data/measure_of_chaos_dict_test_input.pkl') with open(self.input_fn) as f: self.input_data = cPickle.load(f) def testMOCBoundaries(self): for img_d in self.input_data: if len(img_d) > 0: assert 0 <= measure_of_chaos_dict(img_d, self.rows, self.cols) <= 1 def testEmptyInput(self): # print measure_of_chaos_dict({}, self.cols, self.cols) self.assertRaises(Exception, measure_of_chaos_dict, {}, self.cols, self.cols) self.assertRaises(Exception, measure_of_chaos_dict, None, self.cols, self.cols) self.assertRaises(Exception, measure_of_chaos_dict, (), self.cols, self.cols) self.assertRaises(Exception, measure_of_chaos_dict, [], self.cols, self.cols) def testMaxInputDictKeyVal(self): max_key_val = self.rows * self.cols - 1 self.assertRaises(Exception, measure_of_chaos_dict, {max_key_val + 10: 1}, self.rows, self.cols) if __name__ == '__main__': unittest.main()
import unittest import numpy as np from ..image_measures.level_sets_measure import measure_of_chaos, _nan_to_zero class MeasureOfChaosTest(unittest.TestCase): def test__nan_to_zero_with_ge_zero(self): ids = ( np.zeros(1), np.ones(range(1, 10)), np.arange(1024 * 1024) ) for id_ in ids: before = id_.copy() _nan_to_zero(id_) np.testing.assert_array_equal(before, id_) def test__nan_to_zero_with_negatives(self): negs = ( np.array([-1]), -np.arange(1, 1024 * 1024 + 1).reshape((1024, 1024)), np.linspace(0, -20, 201) ) for neg in negs: sh = neg.shape _nan_to_zero(neg) np.testing.assert_array_equal(neg, np.zeros(sh)) if __name__ == '__main__': unittest.main()
Implement first tests for _nan_to_zero
Implement first tests for _nan_to_zero - Remove outdated dict test class - write some test methods
Python
apache-2.0
andy-d-palmer/pyIMS,alexandrovteam/pyImagingMSpec
- __author__ = 'intsco' + import unittest - import cPickle + import numpy as np + - from engine.pyIMS.image_measures.level_sets_measure import measure_of_chaos_dict + from ..image_measures.level_sets_measure import measure_of_chaos, _nan_to_zero - from unittest import TestCase - import unittest - from os.path import join, realpath, dirname - class MeasureOfChaosDictTest(TestCase): + class MeasureOfChaosTest(unittest.TestCase): + def test__nan_to_zero_with_ge_zero(self): + ids = ( + np.zeros(1), + np.ones(range(1, 10)), + np.arange(1024 * 1024) + ) + for id_ in ids: + before = id_.copy() + _nan_to_zero(id_) + np.testing.assert_array_equal(before, id_) + def test__nan_to_zero_with_negatives(self): + negs = ( + np.array([-1]), + -np.arange(1, 1024 * 1024 + 1).reshape((1024, 1024)), + np.linspace(0, -20, 201) + ) + for neg in negs: + sh = neg.shape + _nan_to_zero(neg) + np.testing.assert_array_equal(neg, np.zeros(sh)) - def setUp(self): - self.rows, self.cols = 65, 65 - self.input_fn = join(dirname(realpath(__file__)), 'data/measure_of_chaos_dict_test_input.pkl') - with open(self.input_fn) as f: - self.input_data = cPickle.load(f) - - def testMOCBoundaries(self): - for img_d in self.input_data: - if len(img_d) > 0: - assert 0 <= measure_of_chaos_dict(img_d, self.rows, self.cols) <= 1 - - def testEmptyInput(self): - # print measure_of_chaos_dict({}, self.cols, self.cols) - self.assertRaises(Exception, measure_of_chaos_dict, {}, self.cols, self.cols) - self.assertRaises(Exception, measure_of_chaos_dict, None, self.cols, self.cols) - self.assertRaises(Exception, measure_of_chaos_dict, (), self.cols, self.cols) - self.assertRaises(Exception, measure_of_chaos_dict, [], self.cols, self.cols) - - def testMaxInputDictKeyVal(self): - max_key_val = self.rows * self.cols - 1 - self.assertRaises(Exception, measure_of_chaos_dict, {max_key_val + 10: 1}, self.rows, self.cols) - if __name__ == '__main__': unittest.main()
Implement first tests for _nan_to_zero
## Code Before: __author__ = 'intsco' import cPickle from engine.pyIMS.image_measures.level_sets_measure import measure_of_chaos_dict from unittest import TestCase import unittest from os.path import join, realpath, dirname class MeasureOfChaosDictTest(TestCase): def setUp(self): self.rows, self.cols = 65, 65 self.input_fn = join(dirname(realpath(__file__)), 'data/measure_of_chaos_dict_test_input.pkl') with open(self.input_fn) as f: self.input_data = cPickle.load(f) def testMOCBoundaries(self): for img_d in self.input_data: if len(img_d) > 0: assert 0 <= measure_of_chaos_dict(img_d, self.rows, self.cols) <= 1 def testEmptyInput(self): # print measure_of_chaos_dict({}, self.cols, self.cols) self.assertRaises(Exception, measure_of_chaos_dict, {}, self.cols, self.cols) self.assertRaises(Exception, measure_of_chaos_dict, None, self.cols, self.cols) self.assertRaises(Exception, measure_of_chaos_dict, (), self.cols, self.cols) self.assertRaises(Exception, measure_of_chaos_dict, [], self.cols, self.cols) def testMaxInputDictKeyVal(self): max_key_val = self.rows * self.cols - 1 self.assertRaises(Exception, measure_of_chaos_dict, {max_key_val + 10: 1}, self.rows, self.cols) if __name__ == '__main__': unittest.main() ## Instruction: Implement first tests for _nan_to_zero ## Code After: import unittest import numpy as np from ..image_measures.level_sets_measure import measure_of_chaos, _nan_to_zero class MeasureOfChaosTest(unittest.TestCase): def test__nan_to_zero_with_ge_zero(self): ids = ( np.zeros(1), np.ones(range(1, 10)), np.arange(1024 * 1024) ) for id_ in ids: before = id_.copy() _nan_to_zero(id_) np.testing.assert_array_equal(before, id_) def test__nan_to_zero_with_negatives(self): negs = ( np.array([-1]), -np.arange(1, 1024 * 1024 + 1).reshape((1024, 1024)), np.linspace(0, -20, 201) ) for neg in negs: sh = neg.shape _nan_to_zero(neg) np.testing.assert_array_equal(neg, np.zeros(sh)) if __name__ == '__main__': unittest.main()
132b148ca8701ee867b7a08432a3595a213ce470
cedexis/radar/tests/test_cli.py
cedexis/radar/tests/test_cli.py
import unittest import types import cedexis.radar.cli class TestCommandLineInterface(unittest.TestCase): def test_main(self): self.assertTrue(isinstance(cedexis.radar.cli.main, types.FunctionType))
import unittest from unittest.mock import patch, MagicMock, call import types from pprint import pprint import cedexis.radar.cli class TestCommandLineInterface(unittest.TestCase): def test_main(self): self.assertTrue(isinstance(cedexis.radar.cli.main, types.FunctionType)) @patch('logging.getLogger') @patch('argparse.ArgumentParser') @patch('cedexis.radar.run_session') @patch('time.sleep') def test_config_file_with_cli_params(self, mock_sleep, mock_run_session, mock_ArgumentParser, mock_getLogger): args = make_default_args() args.continuous = True args.max_runs = 3 args.repeat_delay = 60 mock_parser = MagicMock() mock_parser.parse_args.return_value = args mock_ArgumentParser.return_value = mock_parser cedexis.radar.cli.main() # Assert # print(mock_run_session.call_args) self.assertEqual( mock_run_session.call_args_list, [ call(1, 12345, 'sandbox', False, None, None, False, None), call(1, 12345, 'sandbox', False, None, None, False, None), call(1, 12345, 'sandbox', False, None, None, False, None) ]) # print(mock_sleep.call_args) self.assertEqual(mock_sleep.call_args_list, [call(60),call(60)]) def make_default_args(): args = lambda: None args.zone_id = 1 args.customer_id = 12345 args.api_key = 'sandbox' args.secure = False args.config_file = 'some config file path' args.tracer = None args.provider_id = None args.report_server = None args.max_runs = None args.repeat_delay = None return args
Add unit test for overrides
Add unit test for overrides
Python
mit
cedexis/cedexis.radar
import unittest + from unittest.mock import patch, MagicMock, call import types + from pprint import pprint import cedexis.radar.cli class TestCommandLineInterface(unittest.TestCase): def test_main(self): self.assertTrue(isinstance(cedexis.radar.cli.main, types.FunctionType)) + @patch('logging.getLogger') + @patch('argparse.ArgumentParser') + @patch('cedexis.radar.run_session') + @patch('time.sleep') + def test_config_file_with_cli_params(self, mock_sleep, mock_run_session, + mock_ArgumentParser, mock_getLogger): + args = make_default_args() + args.continuous = True + args.max_runs = 3 + args.repeat_delay = 60 + mock_parser = MagicMock() + mock_parser.parse_args.return_value = args + mock_ArgumentParser.return_value = mock_parser + cedexis.radar.cli.main() + + # Assert + # print(mock_run_session.call_args) + self.assertEqual( + mock_run_session.call_args_list, + [ + call(1, 12345, 'sandbox', False, None, None, False, None), + call(1, 12345, 'sandbox', False, None, None, False, None), + call(1, 12345, 'sandbox', False, None, None, False, None) + ]) + # print(mock_sleep.call_args) + self.assertEqual(mock_sleep.call_args_list, [call(60),call(60)]) + + def make_default_args(): + args = lambda: None + args.zone_id = 1 + args.customer_id = 12345 + args.api_key = 'sandbox' + args.secure = False + args.config_file = 'some config file path' + args.tracer = None + args.provider_id = None + args.report_server = None + args.max_runs = None + args.repeat_delay = None + return args +
Add unit test for overrides
## Code Before: import unittest import types import cedexis.radar.cli class TestCommandLineInterface(unittest.TestCase): def test_main(self): self.assertTrue(isinstance(cedexis.radar.cli.main, types.FunctionType)) ## Instruction: Add unit test for overrides ## Code After: import unittest from unittest.mock import patch, MagicMock, call import types from pprint import pprint import cedexis.radar.cli class TestCommandLineInterface(unittest.TestCase): def test_main(self): self.assertTrue(isinstance(cedexis.radar.cli.main, types.FunctionType)) @patch('logging.getLogger') @patch('argparse.ArgumentParser') @patch('cedexis.radar.run_session') @patch('time.sleep') def test_config_file_with_cli_params(self, mock_sleep, mock_run_session, mock_ArgumentParser, mock_getLogger): args = make_default_args() args.continuous = True args.max_runs = 3 args.repeat_delay = 60 mock_parser = MagicMock() mock_parser.parse_args.return_value = args mock_ArgumentParser.return_value = mock_parser cedexis.radar.cli.main() # Assert # print(mock_run_session.call_args) self.assertEqual( mock_run_session.call_args_list, [ call(1, 12345, 'sandbox', False, None, None, False, None), call(1, 12345, 'sandbox', False, None, None, False, None), call(1, 12345, 'sandbox', False, None, None, False, None) ]) # print(mock_sleep.call_args) self.assertEqual(mock_sleep.call_args_list, [call(60),call(60)]) def make_default_args(): args = lambda: None args.zone_id = 1 args.customer_id = 12345 args.api_key = 'sandbox' args.secure = False args.config_file = 'some config file path' args.tracer = None args.provider_id = None args.report_server = None args.max_runs = None args.repeat_delay = None return args
70f167d3d5a7540fb3521b82ec70bf7c6db09a99
tests/test_contrib.py
tests/test_contrib.py
from __future__ import print_function import cooler.contrib.higlass as cch import h5py import os.path as op testdir = op.realpath(op.dirname(__file__)) def test_data_retrieval(): data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool') f = h5py.File(data_file, 'r') data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999) assert(data['genome_start1'].iloc[0] == 0.) assert(data['genome_start2'].iloc[0] == 0.) data = cch.get_data(f, 4, 0, 256000000, 0, 256000000) assert(data['genome_start1'].iloc[-1] > 255000000) assert(data['genome_start1'].iloc[-1] < 256000000) #print("ge1", data['genome_end1'])
from __future__ import print_function import cooler.contrib.higlass as cch import cooler.contrib.recursive_agg_onefile as ra import h5py import os.path as op testdir = op.realpath(op.dirname(__file__)) def test_data_retrieval(): data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool') f = h5py.File(data_file, 'r') data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999) assert(data['genome_start1'].iloc[0] == 0.) assert(data['genome_start2'].iloc[0] == 0.) data = cch.get_data(f, 4, 0, 256000000, 0, 256000000) assert(data['genome_start1'].iloc[-1] > 255000000) assert(data['genome_start1'].iloc[-1] < 256000000) #print("ge1", data['genome_end1']) def test_recursive_agg(): infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool') outfile = '/tmp/bla.cool' chunksize = int(10e6) n_zooms = 2 n_cpus = 8 ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus) ra.balance(outfile, n_zooms, chunksize, n_cpus)
Add test for recursive agg
Add test for recursive agg
Python
bsd-3-clause
mirnylab/cooler
from __future__ import print_function import cooler.contrib.higlass as cch + import cooler.contrib.recursive_agg_onefile as ra import h5py import os.path as op testdir = op.realpath(op.dirname(__file__)) def test_data_retrieval(): data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool') f = h5py.File(data_file, 'r') data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999) assert(data['genome_start1'].iloc[0] == 0.) assert(data['genome_start2'].iloc[0] == 0.) data = cch.get_data(f, 4, 0, 256000000, 0, 256000000) assert(data['genome_start1'].iloc[-1] > 255000000) assert(data['genome_start1'].iloc[-1] < 256000000) #print("ge1", data['genome_end1']) + + def test_recursive_agg(): + infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool') + outfile = '/tmp/bla.cool' + chunksize = int(10e6) + n_zooms = 2 + n_cpus = 8 + ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus) + ra.balance(outfile, n_zooms, chunksize, n_cpus)
Add test for recursive agg
## Code Before: from __future__ import print_function import cooler.contrib.higlass as cch import h5py import os.path as op testdir = op.realpath(op.dirname(__file__)) def test_data_retrieval(): data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool') f = h5py.File(data_file, 'r') data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999) assert(data['genome_start1'].iloc[0] == 0.) assert(data['genome_start2'].iloc[0] == 0.) data = cch.get_data(f, 4, 0, 256000000, 0, 256000000) assert(data['genome_start1'].iloc[-1] > 255000000) assert(data['genome_start1'].iloc[-1] < 256000000) #print("ge1", data['genome_end1']) ## Instruction: Add test for recursive agg ## Code After: from __future__ import print_function import cooler.contrib.higlass as cch import cooler.contrib.recursive_agg_onefile as ra import h5py import os.path as op testdir = op.realpath(op.dirname(__file__)) def test_data_retrieval(): data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool') f = h5py.File(data_file, 'r') data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999) assert(data['genome_start1'].iloc[0] == 0.) assert(data['genome_start2'].iloc[0] == 0.) data = cch.get_data(f, 4, 0, 256000000, 0, 256000000) assert(data['genome_start1'].iloc[-1] > 255000000) assert(data['genome_start1'].iloc[-1] < 256000000) #print("ge1", data['genome_end1']) def test_recursive_agg(): infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool') outfile = '/tmp/bla.cool' chunksize = int(10e6) n_zooms = 2 n_cpus = 8 ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus) ra.balance(outfile, n_zooms, chunksize, n_cpus)
166e0980fc20b507763395297e8a67c7dcb3a3da
examples/neural_network_inference/onnx_converter/small_example.py
examples/neural_network_inference/onnx_converter/small_example.py
import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): y = F.relu(self.fc1(x)) y = F.softmax(self.fc2(y)) return y # Step 0 - (b) Create model or Load from dist model = small_model() dummy_input = torch.randn(768) # Step 1 - PyTorch to ONNX model torch.onnx.export(model, dummy_input, './small_model.onnx') # Step 2 - ONNX to CoreML model mlmodel = convert(model='./small_model.onnx', target_ios='13') # Save converted CoreML model mlmodel.save('small_model.mlmodel')
import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): y = F.relu(self.fc1(x)) y = F.softmax(self.fc2(y)) return y # Step 0 - (b) Create model or Load from dist model = small_model() dummy_input = torch.randn(768) # Step 1 - PyTorch to ONNX model torch.onnx.export(model, dummy_input, './small_model.onnx') # Step 2 - ONNX to CoreML model mlmodel = convert(model='./small_model.onnx', minimum_ios_deployment_target='13') # Save converted CoreML model mlmodel.save('small_model.mlmodel')
Update the example with latest interface
Update the example with latest interface Update the example with the latest interface of the function "convert"
Python
bsd-3-clause
apple/coremltools,apple/coremltools,apple/coremltools,apple/coremltools
import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): y = F.relu(self.fc1(x)) y = F.softmax(self.fc2(y)) return y # Step 0 - (b) Create model or Load from dist model = small_model() dummy_input = torch.randn(768) # Step 1 - PyTorch to ONNX model torch.onnx.export(model, dummy_input, './small_model.onnx') # Step 2 - ONNX to CoreML model - mlmodel = convert(model='./small_model.onnx', target_ios='13') + mlmodel = convert(model='./small_model.onnx', minimum_ios_deployment_target='13') # Save converted CoreML model mlmodel.save('small_model.mlmodel')
Update the example with latest interface
## Code Before: import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): y = F.relu(self.fc1(x)) y = F.softmax(self.fc2(y)) return y # Step 0 - (b) Create model or Load from dist model = small_model() dummy_input = torch.randn(768) # Step 1 - PyTorch to ONNX model torch.onnx.export(model, dummy_input, './small_model.onnx') # Step 2 - ONNX to CoreML model mlmodel = convert(model='./small_model.onnx', target_ios='13') # Save converted CoreML model mlmodel.save('small_model.mlmodel') ## Instruction: Update the example with latest interface ## Code After: import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): y = F.relu(self.fc1(x)) y = F.softmax(self.fc2(y)) return y # Step 0 - (b) Create model or Load from dist model = small_model() dummy_input = torch.randn(768) # Step 1 - PyTorch to ONNX model torch.onnx.export(model, dummy_input, './small_model.onnx') # Step 2 - ONNX to CoreML model mlmodel = convert(model='./small_model.onnx', minimum_ios_deployment_target='13') # Save converted CoreML model mlmodel.save('small_model.mlmodel')
967ea6b083437cbe6c87b173567981e1ae41fefc
project/wsgi/tomodev.py
project/wsgi/tomodev.py
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.tomodev") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
import os import site os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.tomodev") base_path = os.path.abspath("../..") site.addsitedir(base_path) site.addsitedir(os.path.join(base_path, 'virtualenv/lib/python2.6/site-packages')) # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Set Python path inside WSGI application
Set Python path inside WSGI application
Python
agpl-3.0
ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo
import os + import site os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.tomodev") + + base_path = os.path.abspath("../..") + site.addsitedir(base_path) + site.addsitedir(os.path.join(base_path, 'virtualenv/lib/python2.6/site-packages')) # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Set Python path inside WSGI application
## Code Before: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.tomodev") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application) ## Instruction: Set Python path inside WSGI application ## Code After: import os import site os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.tomodev") base_path = os.path.abspath("../..") site.addsitedir(base_path) site.addsitedir(os.path.join(base_path, 'virtualenv/lib/python2.6/site-packages')) # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)