commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
65c6c0b5ac47caac71c6c1284d84c1004d348c01
partner_relations/model/__init__.py
partner_relations/model/__init__.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2013 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## PADDING = 10 def get_partner_type(partner): """Get partner type for relation. :param partner: a res.partner either a company or not :return: 'c' for company or 'p' for person :rtype: str """ return 'c' if partner.is_company else 'p' from . import res_partner from . import res_partner_relation from . import res_partner_relation_type from . import res_partner_relation_all from . import res_partner_relation_type_selection
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2013 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import res_partner from . import res_partner_relation from . import res_partner_relation_type from . import res_partner_relation_all from . import res_partner_relation_type_selection PADDING = 10 def get_partner_type(partner): """Get partner type for relation. :param partner: a res.partner either a company or not :return: 'c' for company or 'p' for person :rtype: str """ return 'c' if partner.is_company else 'p'
Fix imports at top of file.
Fix imports at top of file.
Python
agpl-3.0
Therp/partner-contact,acsone/partner-contact,open-synergy/partner-contact,diagramsoftware/partner-contact
--- +++ @@ -19,6 +19,12 @@ # ############################################################################## +from . import res_partner +from . import res_partner_relation +from . import res_partner_relation_type +from . import res_partner_relation_all +from . import res_partner_relation_type_selection + PADDING = 10 @@ -30,10 +36,3 @@ :rtype: str """ return 'c' if partner.is_company else 'p' - - -from . import res_partner -from . import res_partner_relation -from . import res_partner_relation_type -from . import res_partner_relation_all -from . import res_partner_relation_type_selection
a056ddc885d7eb333ab323f7552bfffd35635a8a
plugins/ChangeLogPlugin/__init__.py
plugins/ChangeLogPlugin/__init__.py
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import ChangeLog from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "plugin": { "name": catalog.i18nc("@label", "Changelog"), "author": "Ultimaker", "version": "1.0", "description": catalog.i18nc("@info:whatsthis", "Shows changes since latest checked version"), "api": 2 } } def register(app): return {"extension": ChangeLog.ChangeLog()}
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import ChangeLog from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "plugin": { "name": catalog.i18nc("@label", "Changelog"), "author": "Ultimaker", "version": "1.0", "description": catalog.i18nc("@info:whatsthis", "Shows changes since latest checked version."), "api": 2 } } def register(app): return {"extension": ChangeLog.ChangeLog()}
Add period at end of plug-in description
Add period at end of plug-in description For consistency. All other plug-ins have this (no really, now). Contributes to issue CURA-1190.
Python
agpl-3.0
ynotstartups/Wanhao,senttech/Cura,fieldOfView/Cura,ynotstartups/Wanhao,hmflash/Cura,totalretribution/Cura,fieldOfView/Cura,Curahelper/Cura,senttech/Cura,totalretribution/Cura,Curahelper/Cura,hmflash/Cura
--- +++ @@ -12,7 +12,7 @@ "name": catalog.i18nc("@label", "Changelog"), "author": "Ultimaker", "version": "1.0", - "description": catalog.i18nc("@info:whatsthis", "Shows changes since latest checked version"), + "description": catalog.i18nc("@info:whatsthis", "Shows changes since latest checked version."), "api": 2 } }
92febbffb91943f13cfac8c00e55103b20645b70
plex/objects/library/container.py
plex/objects/library/container.py
from plex.objects.core.base import Property from plex.objects.container import Container from plex.objects.library.section import Section class MediaContainer(Container): section = Property(resolver=lambda: MediaContainer.construct_section) title1 = Property title2 = Property identifier = Property art = Property thumb = Property view_group = Property('viewGroup') view_mode = Property('viewMode', int) media_tag_prefix = Property('mediaTagPrefix') media_tag_version = Property('mediaTagVersion') no_cache = Property('nocache', bool) allow_sync = Property('allowSync', bool) mixed_parents = Property('mixedParents', bool) @staticmethod def construct_section(client, node): attribute_map = { 'key': 'librarySectionID', 'uuid': 'librarySectionUUID', 'title': 'librarySectionTitle' } return Section.construct(client, node, attribute_map, child=True)
from plex.objects.core.base import Property from plex.objects.container import Container from plex.objects.library.section import Section class MediaContainer(Container): section = Property(resolver=lambda: MediaContainer.construct_section) title1 = Property title2 = Property identifier = Property art = Property thumb = Property view_group = Property('viewGroup') view_mode = Property('viewMode', int) media_tag_prefix = Property('mediaTagPrefix') media_tag_version = Property('mediaTagVersion') no_cache = Property('nocache', bool) allow_sync = Property('allowSync', bool) mixed_parents = Property('mixedParents', bool) @staticmethod def construct_section(client, node): attribute_map = { 'key': 'librarySectionID', 'uuid': 'librarySectionUUID', 'title': 'librarySectionTitle' } return Section.construct(client, node, attribute_map, child=True) def __iter__(self): for item in super(MediaContainer, self).__iter__(): item.section = self.section yield item
Update [MediaContainer] children with the correct `section` object
Update [MediaContainer] children with the correct `section` object
Python
mit
fuzeman/plex.py
--- +++ @@ -33,3 +33,9 @@ } return Section.construct(client, node, attribute_map, child=True) + + def __iter__(self): + for item in super(MediaContainer, self).__iter__(): + item.section = self.section + + yield item
35293cecc99a629b3a185e69cf9ed3a339d9d1cf
automat/_introspection.py
automat/_introspection.py
""" Python introspection helpers. """ from types import CodeType as code, FunctionType as function def copycode(template, changes): if hasattr(code, "replace"): return template.replace(**{"co_" + k : v for k, v in changes.items()}) else: names = [ "argcount", "nlocals", "stacksize", "flags", "code", "consts", "names", "varnames", "filename", "name", "firstlineno", "lnotab", "freevars", "cellvars" ] if hasattr(code, "co_kwonlyargcount"): names.insert(1, "kwonlyargcount") if hasattr(code, "co_posonlyargcount"): # PEP 570 added "positional only arguments" names.insert(1, "posonlyargcount") values = [ changes.get(name, getattr(template, "co_" + name)) for name in names ] return code(*values) def copyfunction(template, funcchanges, codechanges): names = [ "globals", "name", "defaults", "closure", ] values = [ funcchanges.get(name, getattr(template, "__" + name + "__")) for name in names ] return function(copycode(template.__code__, codechanges), *values) def preserveName(f): """ Preserve the name of the given function on the decorated function. """ def decorator(decorated): return copyfunction(decorated, dict(name=f.__name__), dict(name=f.__name__)) return decorator
""" Python introspection helpers. """ from types import CodeType as code, FunctionType as function def copycode(template, changes): if hasattr(code, "replace"): return template.replace(**{"co_" + k : v for k, v in changes.items()}) names = [ "argcount", "nlocals", "stacksize", "flags", "code", "consts", "names", "varnames", "filename", "name", "firstlineno", "lnotab", "freevars", "cellvars" ] if hasattr(code, "co_kwonlyargcount"): names.insert(1, "kwonlyargcount") if hasattr(code, "co_posonlyargcount"): # PEP 570 added "positional only arguments" names.insert(1, "posonlyargcount") values = [ changes.get(name, getattr(template, "co_" + name)) for name in names ] return code(*values) def copyfunction(template, funcchanges, codechanges): names = [ "globals", "name", "defaults", "closure", ] values = [ funcchanges.get(name, getattr(template, "__" + name + "__")) for name in names ] return function(copycode(template.__code__, codechanges), *values) def preserveName(f): """ Preserve the name of the given function on the decorated function. """ def decorator(decorated): return copyfunction(decorated, dict(name=f.__name__), dict(name=f.__name__)) return decorator
Remove indentation level for easier review
Remove indentation level for easier review
Python
mit
glyph/automat
--- +++ @@ -8,22 +8,21 @@ def copycode(template, changes): if hasattr(code, "replace"): return template.replace(**{"co_" + k : v for k, v in changes.items()}) - else: - names = [ - "argcount", "nlocals", "stacksize", "flags", "code", "consts", - "names", "varnames", "filename", "name", "firstlineno", "lnotab", - "freevars", "cellvars" - ] - if hasattr(code, "co_kwonlyargcount"): - names.insert(1, "kwonlyargcount") - if hasattr(code, "co_posonlyargcount"): - # PEP 570 added "positional only arguments" - names.insert(1, "posonlyargcount") - values = [ - changes.get(name, getattr(template, "co_" + name)) - for name in names - ] - return code(*values) + names = [ + "argcount", "nlocals", "stacksize", "flags", "code", "consts", + "names", "varnames", "filename", "name", "firstlineno", "lnotab", + "freevars", "cellvars" + ] + if hasattr(code, "co_kwonlyargcount"): + names.insert(1, "kwonlyargcount") + if hasattr(code, "co_posonlyargcount"): + # PEP 570 added "positional only arguments" + names.insert(1, "posonlyargcount") + values = [ + changes.get(name, getattr(template, "co_" + name)) + for name in names + ] + return code(*values) def copyfunction(template, funcchanges, codechanges):
2c6ccdacc2c4e54cf0a12618d60c963d9c67ef62
djangocms_page_sitemap/settings.py
djangocms_page_sitemap/settings.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from cms.sitemaps import CMSSitemap from cms.utils import get_cms_setting from django.conf import settings from django.utils.translation import ugettext_lazy as _ PAGE_SITEMAP_CHANGEFREQ_DEFAULT_LIST = { 'always': _('always'), 'hourly': _('hourly'), 'daily': _('daily'), 'weekly': _('weekly'), 'monthly': _('monthly'), 'yearly': _('yearly'), 'never': _('never'), } PAGE_SITEMAP_CHANGEFREQ_LIST = getattr( settings, 'PAGE_SITEMAP_CHANGEFREQ_LIST', PAGE_SITEMAP_CHANGEFREQ_DEFAULT_LIST ) PAGE_SITEMAP_DEFAULT_CHANGEFREQ = getattr( settings, 'PAGE_SITEMAP_DEFAULT_CHANGEFREQ', CMSSitemap.changefreq ) PAGE_SITEMAP_CACHE_DURATION = get_cms_setting('CACHE_DURATIONS')['menus']
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from cms.sitemaps import CMSSitemap from cms.utils.conf import get_cms_setting from django.conf import settings from django.utils.translation import ugettext_lazy as _ PAGE_SITEMAP_CHANGEFREQ_DEFAULT_LIST = { 'always': _('always'), 'hourly': _('hourly'), 'daily': _('daily'), 'weekly': _('weekly'), 'monthly': _('monthly'), 'yearly': _('yearly'), 'never': _('never'), } PAGE_SITEMAP_CHANGEFREQ_LIST = getattr( settings, 'PAGE_SITEMAP_CHANGEFREQ_LIST', PAGE_SITEMAP_CHANGEFREQ_DEFAULT_LIST ) PAGE_SITEMAP_DEFAULT_CHANGEFREQ = getattr( settings, 'PAGE_SITEMAP_DEFAULT_CHANGEFREQ', CMSSitemap.changefreq ) PAGE_SITEMAP_CACHE_DURATION = get_cms_setting('CACHE_DURATIONS')['menus']
Fix for DjangoCMS 3.5: get_cms_setting
Fix for DjangoCMS 3.5: get_cms_setting ImportError: cannot import name get_cms_setting
Python
bsd-3-clause
nephila/djangocms-page-sitemap
--- +++ @@ -2,7 +2,7 @@ from __future__ import absolute_import, print_function, unicode_literals from cms.sitemaps import CMSSitemap -from cms.utils import get_cms_setting +from cms.utils.conf import get_cms_setting from django.conf import settings from django.utils.translation import ugettext_lazy as _
06cb55639d2bc504d0ec1b9fb073c40e00751328
doc/sample_code/demo_plot_state.py
doc/sample_code/demo_plot_state.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pyogi.board import Board from pyogi.plot import plot_board if __name__ == '__main__': board = Board() board.set_initial_state() board.players = ['先手', '後手'] board.move('+7776FU') board.move('-3334FU') board.move('+2868HI') board.move('-2288UM') board.move('+7988GI') # Plot by materials plot_board(board, savepath='example_pic.png', mode='pic') # Plot using matplotlib board.plot_state_mpl(figsize=(8, 9))
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from pyogi.board import Board from pyogi.plot import plot_board if __name__ == '__main__': board = Board() board.set_initial_state() board.players = ['先手', '後手'] board.move('+7776FU') board.move('-3334FU') board.move('+2868HI') board.move('-2288UM') board.move('+7988GI') # Plot by materials savepath = 'example_pic.png' if os.path.exists(savepath): savepath = None plot_board(board, savepath=savepath, mode='pic') # Plot using matplotlib board.plot_state_mpl(figsize=(8, 9))
Disable output example_pic.png if exists
Disable output example_pic.png if exists
Python
mit
tosh1ki/pyogi,tosh1ki/pyogi
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +import os from pyogi.board import Board from pyogi.plot import plot_board @@ -19,7 +20,11 @@ board.move('+7988GI') # Plot by materials - plot_board(board, savepath='example_pic.png', mode='pic') + savepath = 'example_pic.png' + if os.path.exists(savepath): + savepath = None + + plot_board(board, savepath=savepath, mode='pic') # Plot using matplotlib board.plot_state_mpl(figsize=(8, 9))
7f113399e4277ecbbfdde41d683c22082f7e19bd
scrapi/harvesters/smithsonian.py
scrapi/harvesters/smithsonian.py
''' Harvester for the Smithsonian Digital Repository for the SHARE project Example API call: http://repository.si.edu/oai/request?verb=ListRecords&metadataPrefix=oai_dc ''' from __future__ import unicode_literals from scrapi.base import OAIHarvester class SiHarvester(OAIHarvester): short_name = 'smithsonian' long_name = 'Smithsonian Digital Repository' url = 'http://repository.si.edu/oai/request' base_url = 'http://repository.si.edu/oai/request' property_list = ['date', 'identifier', 'type', 'format', 'setSpec'] timezone_granularity = True
''' Harvester for the Smithsonian Digital Repository for the SHARE project Example API call: http://repository.si.edu/oai/request?verb=ListRecords&metadataPrefix=oai_dc ''' from __future__ import unicode_literals import re from scrapi.base import helpers from scrapi.base import OAIHarvester class SiHarvester(OAIHarvester): short_name = 'smithsonian' long_name = 'Smithsonian Digital Repository' url = 'http://repository.si.edu/oai/request' @property def schema(self): return helpers.updated_schema(self._schema, { "uris": { "objectUris": [('//dc:identifier/node()', get_doi_from_identifier)] } }) base_url = 'http://repository.si.edu/oai/request' property_list = ['date', 'identifier', 'type', 'format', 'setSpec'] timezone_granularity = True def get_doi_from_identifier(identifiers): doi_re = re.compile(r'10\.\S*\/\S*') identifiers = [identifiers] if not isinstance(identifiers, list) else identifiers for identifier in identifiers: try: found_doi = doi_re.search(identifier).group() return 'http://dx.doi.org/{}'.format(found_doi) except AttributeError: continue
Add DOI parsing to identifiers
Add DOI parsing to identifiers
Python
apache-2.0
CenterForOpenScience/scrapi,alexgarciac/scrapi,jeffreyliu3230/scrapi,felliott/scrapi,fabianvf/scrapi,mehanig/scrapi,mehanig/scrapi,fabianvf/scrapi,erinspace/scrapi,erinspace/scrapi,felliott/scrapi,CenterForOpenScience/scrapi
--- +++ @@ -5,6 +5,9 @@ ''' from __future__ import unicode_literals +import re + +from scrapi.base import helpers from scrapi.base import OAIHarvester @@ -13,6 +16,25 @@ long_name = 'Smithsonian Digital Repository' url = 'http://repository.si.edu/oai/request' + @property + def schema(self): + return helpers.updated_schema(self._schema, { + "uris": { + "objectUris": [('//dc:identifier/node()', get_doi_from_identifier)] + } + }) + base_url = 'http://repository.si.edu/oai/request' property_list = ['date', 'identifier', 'type', 'format', 'setSpec'] timezone_granularity = True + + +def get_doi_from_identifier(identifiers): + doi_re = re.compile(r'10\.\S*\/\S*') + identifiers = [identifiers] if not isinstance(identifiers, list) else identifiers + for identifier in identifiers: + try: + found_doi = doi_re.search(identifier).group() + return 'http://dx.doi.org/{}'.format(found_doi) + except AttributeError: + continue
3f90d0ec25491eb64f164180139d4baf9ff238a9
libravatar/context_processors.py
libravatar/context_processors.py
# Copyright (C) 2010 Jonathan Harker <jon@jon.geek.nz> # # This file is part of Libravatar # # Libravatar is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Libravatar is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Libravatar. If not, see <http://www.gnu.org/licenses/>. import settings """ Default useful variables for the base page template. """ def basepage(request): context = {} context["site_name"] = settings.SITE_NAME context["libravatar_version"] = settings.LIBRAVATAR_VERSION context["avatar_url"] = settings.AVATAR_URL context["secure_avatar_url"] = settings.SECURE_AVATAR_URL context["media_url"] = settings.MEDIA_URL context["site_url"] = settings.SITE_URL context["disable_signup"] = settings.DISABLE_SIGNUP context["analytics_propertyid"] = settings.ANALYTICS_PROPERTYID context['support_email'] = settings.SUPPORT_EMAIL return context
# Copyright (C) 2010 Jonathan Harker <jon@jon.geek.nz> # # This file is part of Libravatar # # Libravatar is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Libravatar is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Libravatar. If not, see <http://www.gnu.org/licenses/>. import settings """ Default useful variables for the base page template. """ def basepage(request): context = {} context['analytics_propertyid'] = settings.ANALYTICS_PROPERTYID context['avatar_url'] = settings.AVATAR_URL context['disable_signup'] = settings.DISABLE_SIGNUP context['libravatar_version'] = settings.LIBRAVATAR_VERSION context['media_url'] = settings.MEDIA_URL context['secure_avatar_url'] = settings.SECURE_AVATAR_URL context['site_name'] = settings.SITE_NAME context['site_url'] = settings.SITE_URL context['support_email'] = settings.SUPPORT_EMAIL return context
Sort the context list in alphabetical order
Sort the context list in alphabetical order
Python
agpl-3.0
libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar
--- +++ @@ -22,14 +22,14 @@ """ def basepage(request): context = {} - context["site_name"] = settings.SITE_NAME - context["libravatar_version"] = settings.LIBRAVATAR_VERSION - context["avatar_url"] = settings.AVATAR_URL - context["secure_avatar_url"] = settings.SECURE_AVATAR_URL - context["media_url"] = settings.MEDIA_URL - context["site_url"] = settings.SITE_URL - context["disable_signup"] = settings.DISABLE_SIGNUP - context["analytics_propertyid"] = settings.ANALYTICS_PROPERTYID + context['analytics_propertyid'] = settings.ANALYTICS_PROPERTYID + context['avatar_url'] = settings.AVATAR_URL + context['disable_signup'] = settings.DISABLE_SIGNUP + context['libravatar_version'] = settings.LIBRAVATAR_VERSION + context['media_url'] = settings.MEDIA_URL + context['secure_avatar_url'] = settings.SECURE_AVATAR_URL + context['site_name'] = settings.SITE_NAME + context['site_url'] = settings.SITE_URL context['support_email'] = settings.SUPPORT_EMAIL return context
5a682fccfb6d8e6db3eb100262cf628bfc10e829
categories/serializers.py
categories/serializers.py
from .models import Category, Keyword from rest_framework import serializers class CategorySerializer(serializers.ModelSerializer): class Meta(object): model = Category fields = ('pk', 'name', 'weight', 'comment_required') class KeywordSerializer(serializers.ModelSerializer): class Meta(object): model = Keyword fields = ('pk', 'name')
from .models import Category, Keyword from rest_framework import serializers class CategorySerializer(serializers.ModelSerializer): class Meta(object): model = Category fields = ('pk', 'name', 'comment_required') class KeywordSerializer(serializers.ModelSerializer): class Meta(object): model = Keyword fields = ('pk', 'name')
Remove weight from category serializer
Remove weight from category serializer
Python
apache-2.0
belatrix/BackendAllStars
--- +++ @@ -5,7 +5,7 @@ class CategorySerializer(serializers.ModelSerializer): class Meta(object): model = Category - fields = ('pk', 'name', 'weight', 'comment_required') + fields = ('pk', 'name', 'comment_required') class KeywordSerializer(serializers.ModelSerializer):
2b7bdf39497809749c504d10399dffabe52e97ca
testutils/base_server.py
testutils/base_server.py
from testrunner import testhelp class BaseServer(object): "Base server class. Responsible with setting up the ports etc." # We only want standalone repositories to have SSL support added via # useSSL sslEnabled = False def start(self, resetDir = True): raise NotImplementedError def cleanup(self): pass def stop(self): raise NotImplementedError def reset(self): raise NotImplementedError def initPort(self): ports = testhelp.findPorts(num = 1, closeSockets=False)[0] self.port = ports[0] self.socket = ports[1]
from testrunner import testhelp class BaseServer(object): "Base server class. Responsible with setting up the ports etc." # We only want standalone repositories to have SSL support added via # useSSL sslEnabled = False def start(self, resetDir = True): raise NotImplementedError def cleanup(self): pass def stop(self): raise NotImplementedError def reset(self): raise NotImplementedError def isStarted(self): raise NotImplementedError def initPort(self): ports = testhelp.findPorts(num = 1, closeSockets=False)[0] self.port = ports[0] self.socket = ports[1] def __del__(self): if self.isStarted(): print 'warning: %r was not stopped before freeing' % self try: self.stop() except: print 'warning: could not stop %r in __del__' % self
Implement a noisy __del__ in BaseServer.
Implement a noisy __del__ in BaseServer. It will complain if the server is still running, and attempt to stop it.
Python
apache-2.0
sassoftware/testutils,sassoftware/testutils,sassoftware/testutils
--- +++ @@ -18,7 +18,18 @@ def reset(self): raise NotImplementedError + def isStarted(self): + raise NotImplementedError + def initPort(self): ports = testhelp.findPorts(num = 1, closeSockets=False)[0] self.port = ports[0] self.socket = ports[1] + + def __del__(self): + if self.isStarted(): + print 'warning: %r was not stopped before freeing' % self + try: + self.stop() + except: + print 'warning: could not stop %r in __del__' % self
018583a7b8ce3b74b3942402b37b642d37b54c6d
scripts/prepared_json_to_fasta.py
scripts/prepared_json_to_fasta.py
""" Convert a prepared JSON file from augur into a FASTA file. """ import argparse import Bio import json import logging import sys sys.path.append('..') from base.sequences_process import sequence_set if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("json", help="prepared JSON from augur") parser.add_argument("fasta", help="FASTA output for sequences in JSON file") args = parser.parse_args() # Setup the logger. logger = logging.getLogger(__name__) # Load the JSON data. with open(args.json, "r") as fh: data = json.load(fh) # Prepare a sequence set. sequences = sequence_set( logger, data["sequences"], data["reference"], data["info"]["date_format"] ) # Add the reference to output sequences if it isn't already included. output_sequences = sequences.seqs.values() if not sequences.reference_in_dataset: output_sequences.append(sequences.reference_seq) # Write sequences to disk. Bio.SeqIO.write(output_sequences, args.fasta, "fasta")
""" Convert a prepared JSON file from augur into a FASTA file. """ import argparse import Bio import json import logging import sys sys.path.append('..') from base.sequences_process import sequence_set if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert a prepared JSON file from augur into a FASTA file.") parser.add_argument("json", help="prepared JSON from augur") args = parser.parse_args() # Setup the logger. logger = logging.getLogger(__name__) # Load the JSON data. with open(args.json, "r") as fh: data = json.load(fh) # Prepare a sequence set. sequences = sequence_set( logger, data["sequences"], data["reference"], data["info"]["date_format"] ) # Add the reference to output sequences if it isn't already included. output_sequences = sequences.seqs.values() if not sequences.reference_in_dataset: output_sequences.append(sequences.reference_seq) # Write sequences to standard out. Bio.SeqIO.write(output_sequences, sys.stdout, "fasta")
Write FASTA output to standard out.
Write FASTA output to standard out.
Python
agpl-3.0
blab/nextstrain-augur,nextstrain/augur,nextstrain/augur,nextstrain/augur
--- +++ @@ -13,9 +13,8 @@ if __name__ == "__main__": - parser = argparse.ArgumentParser() + parser = argparse.ArgumentParser(description="Convert a prepared JSON file from augur into a FASTA file.") parser.add_argument("json", help="prepared JSON from augur") - parser.add_argument("fasta", help="FASTA output for sequences in JSON file") args = parser.parse_args() @@ -39,5 +38,5 @@ if not sequences.reference_in_dataset: output_sequences.append(sequences.reference_seq) - # Write sequences to disk. - Bio.SeqIO.write(output_sequences, args.fasta, "fasta") + # Write sequences to standard out. + Bio.SeqIO.write(output_sequences, sys.stdout, "fasta")
1bacf677311b211ec75780298a4e366c9c65e307
apps/polls/tests.py
apps/polls/tests.py
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
import datetime from django.utils import timezone from django.test import TestCase from apps.polls.models import Poll class PollMethodTests(TestCase): def test_was_published_recently_with_future_poll(self): """ was_published_recently() should return False for polls whose pub_date is in the future """ future_poll = Poll(pub_date=timezone.now() + datetime.timedelta(days=30)) self.assertEqual(future_poll.was_published_recently(), False)
Create a test to expose the bug
Create a test to expose the bug
Python
bsd-3-clause
cuzen1/teracy-tutorial,cuzen1/teracy-tutorial,cuzen1/teracy-tutorial
--- +++ @@ -1,16 +1,16 @@ -""" -This file demonstrates writing tests using the unittest module. These will pass -when you run "manage.py test". +import datetime -Replace this with more appropriate tests for your application. -""" - +from django.utils import timezone from django.test import TestCase +from apps.polls.models import Poll -class SimpleTest(TestCase): - def test_basic_addition(self): +class PollMethodTests(TestCase): + + def test_was_published_recently_with_future_poll(self): """ - Tests that 1 + 1 always equals 2. + was_published_recently() should return False for polls whose + pub_date is in the future """ - self.assertEqual(1 + 1, 2) + future_poll = Poll(pub_date=timezone.now() + datetime.timedelta(days=30)) + self.assertEqual(future_poll.was_published_recently(), False)
9fcf408dad5b97094445677eb42429beaa830c22
apps/homepage/templatetags/homepage_tags.py
apps/homepage/templatetags/homepage_tags.py
from django import template from homepage.models import Tab register = template.Library() @register.tag(name="get_tabs") def get_tabs(parser, token): return GetElementNode() class GetElementNode(template.Node): def __init__(self): pass def render(self, context): context['tabs'] = Tab.objects.all() return ''
from django import template from homepage.models import Tab register = template.Library() @register.tag(name="get_tabs") def get_tabs(parser, token): return GetElementNode() class GetElementNode(template.Node): def __init__(self): pass def render(self, context): context['tabs'] = Tab.objects.all().select_related('grid') return ''
Reduce queries on all pages by using select_related in the get_tabs template tag.
Reduce queries on all pages by using select_related in the get_tabs template tag.
Python
mit
benracine/opencomparison,audreyr/opencomparison,QLGu/djangopackages,cartwheelweb/packaginator,QLGu/djangopackages,miketheman/opencomparison,nanuxbe/djangopackages,QLGu/djangopackages,miketheman/opencomparison,nanuxbe/djangopackages,audreyr/opencomparison,cartwheelweb/packaginator,nanuxbe/djangopackages,cartwheelweb/packaginator,pydanny/djangopackages,pydanny/djangopackages,pydanny/djangopackages,benracine/opencomparison
--- +++ @@ -15,5 +15,5 @@ pass def render(self, context): - context['tabs'] = Tab.objects.all() + context['tabs'] = Tab.objects.all().select_related('grid') return ''
53a2d8781e3e5d8e5879d4ef7c62752483323cf9
bfg9000/shell/__init__.py
bfg9000/shell/__init__.py
import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """A special subclass of list used to mark that this command line uses special shell characters.""" pass def execute(args, shell=False, env=None, quiet=False): if quiet: devnull = open(os.devnull, 'wb') try: return subprocess.check_output( args, universal_newlines=True, shell=shell, env=env ) except: if quiet: devnull.close() raise
import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """A special subclass of list used to mark that this command line uses special shell characters.""" pass def execute(args, shell=False, env=None, quiet=False): stderr = None if quiet: stderr = open(os.devnull, 'wb') try: return subprocess.check_output( args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) except: if quiet: stderr.close() raise
Fix "quiet" mode for shell.execute()
Fix "quiet" mode for shell.execute()
Python
bsd-3-clause
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
--- +++ @@ -16,13 +16,14 @@ def execute(args, shell=False, env=None, quiet=False): + stderr = None if quiet: - devnull = open(os.devnull, 'wb') + stderr = open(os.devnull, 'wb') try: return subprocess.check_output( - args, universal_newlines=True, shell=shell, env=env + args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) except: if quiet: - devnull.close() + stderr.close() raise
fa3c02a164dd81d91d105a4c1a1ddea8ca50d702
main.py
main.py
#!/usr/bin/env python3 """TODO: * more flexible sorting options * use -o to specify output file * check more explicitly for errors in JSON files """ import json, sys if len(sys.argv) > 1: inFn = sys.argv[1] with open(inFn, 'r') as f: try: defs = json.load(f) except: sys.exit('{} has a syntax error'.format(inFn)) sort = sorted(defs) print('# My Dictionary') print('## Definitions') for k in sort: print('* *{}* - {}'.format(k, defs[k]))
#!/usr/bin/env python3 """TODO: * more flexible sorting options * use -o to specify output file * check more explicitly for errors in JSON files """ import json, sys if len(sys.argv) > 1: inFn = sys.argv[1] with open(inFn, 'r') as f: try: defs = json.load(f) except: sys.exit('{} has a syntax error'.format(inFn)) sort = sorted(defs) print('# My Dictionary') print('## Definitions') curLetter = None for k in sort: l = k[0].upper() if curLetter != l: curLetter = l print('### {}'.format(curLetter)) print('* *{}* - {}'.format(k, defs[k]))
Mark beginning of each section with a letter
Mark beginning of each section with a letter
Python
mit
JoshuaBrockschmidt/dictbuilder
--- +++ @@ -21,5 +21,10 @@ print('# My Dictionary') print('## Definitions') +curLetter = None for k in sort: + l = k[0].upper() + if curLetter != l: + curLetter = l + print('### {}'.format(curLetter)) print('* *{}* - {}'.format(k, defs[k]))
4244f9c4d9e64783d391139457d7761dbc19e546
softwareindex/handlers/coreapi.py
softwareindex/handlers/coreapi.py
# This is a software index handler that gives a score based on the # number of mentions in open access articles. It uses the CORE # aggregator (http://core.ac.uk/) to search the full text of indexed # articles. # # Inputs: # - identifier (String) # # Outputs: # - score (Number) # - description (String) import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' class core_handler: def get_score(self, identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score def get_description(self): return 'mentions in Open Access articles (via http://core.ac.uk/)'
# This is a software index handler that gives a score based on the # number of mentions in open access articles. It uses the CORE # aggregator (http://core.ac.uk/) to search the full text of indexed # articles. # # Inputs: # - identifier (String) # # Outputs: # - score (Number) # - description (String) import requests, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' class core_handler: def get_score(self, identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score def get_description(self): return 'mentions in Open Access articles (via http://core.ac.uk/)'
Remove unneeded import of json module.
Remove unneeded import of json module.
Python
bsd-3-clause
softwaresaved/softwareindex,softwaresaved/softwareindex
--- +++ @@ -10,7 +10,7 @@ # - score (Number) # - description (String) -import requests, json, urllib +import requests, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN'
7897b985a1ec8fe240c9edead2b53567221cd095
projectkey/k_runner.py
projectkey/k_runner.py
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK import os, imp, inspect from interpreter import cli_interface def k_runner(): """CLI interpreter for the k command.""" # Check every directory from the current all the way to / for a file named key.py checkdirectory = os.getcwd() directories_checked = [] keypy_filename = None while not os.path.ismount(checkdirectory): directories_checked.append(checkdirectory) if os.path.exists("{0}{1}key.py".format(checkdirectory, os.sep)): keypy_filename = "{0}{1}key.py".format(checkdirectory, os.sep) break else: checkdirectory = os.path.abspath(os.path.join(checkdirectory, os.pardir)) if not keypy_filename: print "key.py not found in the following directories:\n" print '\n'.join(directories_checked) print "\nSee http://projectkey.readthedocs.org/en/latest/quickstart.html" return 1 else: cli_interface(imp.load_source("key", keypy_filename))
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK import os, imp, inspect, sys from interpreter import cli_interface def k_runner(): """CLI interpreter for the k command.""" # Check every directory from the current all the way to / for a file named key.py checkdirectory = os.getcwd() directories_checked = [] keypy_filename = None while not os.path.ismount(checkdirectory): directories_checked.append(checkdirectory) if os.path.exists("{0}{1}key.py".format(checkdirectory, os.sep)): keypy_filename = "{0}{1}key.py".format(checkdirectory, os.sep) break else: checkdirectory = os.path.abspath(os.path.join(checkdirectory, os.pardir)) if not keypy_filename: sys.stderr.write("key.py not found in the following directories:\n\n") sys.stderr.write('\n'.join(directories_checked)) sys.stderr.write("\n\nSee http://projectkey.readthedocs.org/en/latest/quickstart.html\n") sys.exit(1) else: cli_interface(imp.load_source("key", keypy_filename))
Convert print statement to sys.stderr.write()
Convert print statement to sys.stderr.write()
Python
mit
crdoconnor/projectkey
--- +++ @@ -1,6 +1,6 @@ #!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK -import os, imp, inspect +import os, imp, inspect, sys from interpreter import cli_interface def k_runner(): @@ -18,9 +18,9 @@ checkdirectory = os.path.abspath(os.path.join(checkdirectory, os.pardir)) if not keypy_filename: - print "key.py not found in the following directories:\n" - print '\n'.join(directories_checked) - print "\nSee http://projectkey.readthedocs.org/en/latest/quickstart.html" - return 1 + sys.stderr.write("key.py not found in the following directories:\n\n") + sys.stderr.write('\n'.join(directories_checked)) + sys.stderr.write("\n\nSee http://projectkey.readthedocs.org/en/latest/quickstart.html\n") + sys.exit(1) else: cli_interface(imp.load_source("key", keypy_filename))
85be48f42b03273ea458b7c4db3303ae8b991558
telethon/events/messageedited.py
telethon/events/messageedited.py
from .common import name_inner_event from .newmessage import NewMessage from ..tl import types @name_inner_event class MessageEdited(NewMessage): """ Event fired when a message has been edited. """ @classmethod def build(cls, update): if isinstance(update, (types.UpdateEditMessage, types.UpdateEditChannelMessage)): event = cls.Event(update.message) else: return event._entities = update._entities return event class Event(NewMessage.Event): pass # Required if we want a different name for it
from .common import name_inner_event from .newmessage import NewMessage from ..tl import types @name_inner_event class MessageEdited(NewMessage): """ Event fired when a message has been edited. .. warning:: On channels, `Message.out <telethon.tl.custom.message.Message>` will be ``True`` if you sent the message originally, **not if you edited it**! This can be dangerous if you run outgoing commands on edits. Some examples follow: * You send a message "A", ``out is True``. * You edit "A" to "B", ``out is True``. * Someone else edits "B" to "C", ``out is True`` (**be careful!**). * Someone sends "X", ``out is False``. * Someone edits "X" to "Y", ``out is False``. * You edit "Y" to "Z", ``out is False``. Since there are useful cases where you need the right ``out`` value, the library cannot do anything automatically to help you. Instead, consider using ``from_users='me'`` (it won't work in broadcast channels at all since the sender is the channel and not you). """ @classmethod def build(cls, update): if isinstance(update, (types.UpdateEditMessage, types.UpdateEditChannelMessage)): event = cls.Event(update.message) else: return event._entities = update._entities return event class Event(NewMessage.Event): pass # Required if we want a different name for it
Document misleading message.out value for events.MessageEdited
Document misleading message.out value for events.MessageEdited
Python
mit
LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,expectocode/Telethon
--- +++ @@ -7,6 +7,28 @@ class MessageEdited(NewMessage): """ Event fired when a message has been edited. + + .. warning:: + + On channels, `Message.out <telethon.tl.custom.message.Message>` + will be ``True`` if you sent the message originally, **not if + you edited it**! This can be dangerous if you run outgoing + commands on edits. + + Some examples follow: + + * You send a message "A", ``out is True``. + * You edit "A" to "B", ``out is True``. + * Someone else edits "B" to "C", ``out is True`` (**be careful!**). + * Someone sends "X", ``out is False``. + * Someone edits "X" to "Y", ``out is False``. + * You edit "Y" to "Z", ``out is False``. + + Since there are useful cases where you need the right ``out`` + value, the library cannot do anything automatically to help you. + Instead, consider using ``from_users='me'`` (it won't work in + broadcast channels at all since the sender is the channel and + not you). """ @classmethod def build(cls, update):
ad6a0b466c47d945265423c66c71777d61a82de0
utils/http.py
utils/http.py
import httplib2 def url_exists(url): """ Check that a url- when following redirection - exists. This is needed because django's validators rely on python's urllib2 which in verions < 2.6 won't follow redirects. """ h = httplib2.Http() resp, content = h.request(url) h.follow_all_redirects = True return 200<= resp.status <400
import httplib2 def url_exists(url): """ Check that a url- when following redirection - exists. This is needed because django's validators rely on python's urllib2 which in verions < 2.6 won't follow redirects. """ h = httplib2.Http() resp, content = h.request(url, method="HEAD") h.follow_all_redirects = True return 200<= resp.status <400
Make url field check work over head requests
Make url field check work over head requests
Python
agpl-3.0
pculture/unisubs,pculture/unisubs,pculture/unisubs,ReachingOut/unisubs,norayr/unisubs,eloquence/unisubs,norayr/unisubs,ujdhesa/unisubs,norayr/unisubs,ofer43211/unisubs,ujdhesa/unisubs,eloquence/unisubs,ReachingOut/unisubs,pculture/unisubs,wevoice/wesub,ofer43211/unisubs,eloquence/unisubs,wevoice/wesub,ujdhesa/unisubs,wevoice/wesub,wevoice/wesub,ofer43211/unisubs,ujdhesa/unisubs,eloquence/unisubs,norayr/unisubs,ReachingOut/unisubs,ReachingOut/unisubs,ofer43211/unisubs
--- +++ @@ -8,6 +8,6 @@ """ h = httplib2.Http() - resp, content = h.request(url) + resp, content = h.request(url, method="HEAD") h.follow_all_redirects = True return 200<= resp.status <400
c4c2845d2be318a3aaa23e1f279df9b2180add41
test/systems/test_skill_check.py
test/systems/test_skill_check.py
from roglick.engine.ecs import Entity,EntityManager from roglick.components import SkillComponent,SkillSubComponent from roglick.systems import SkillSystem from roglick.engine import event from roglick.events import SkillCheckEvent def test_skill_check(): wins = 0 iters = 1000 em = EntityManager() em.set_component(em.pc, SkillComponent()) skills = em.get_component(em.pc, SkillComponent) # 7 has ~41% odds of success skills.skills['Dagger'] = SkillSubComponent(7) sys = SkillSystem() sys.set_entity_manager(em) event.register(sys) for x in range(iters): ch = SkillCheckEvent(em.pc, "Dagger") event.dispatch(ch) if ch.result[2]: wins += 1 # Use a fudge factor, because random assert wins >= (iters * 0.38) assert wins <= (iters * 0.44)
from roglick.engine.ecs import Entity,EntityManager from roglick.components import SkillComponent,SkillSubComponent from roglick.systems import SkillSystem from roglick.engine import event from roglick.events import SkillCheckEvent def test_skill_check(): wins = 0 iters = 1000 em = EntityManager() em.set_component(em.pc, SkillComponent()) skills = em.get_component(em.pc, SkillComponent) # 7 has ~41% odds of success skills.skills['melee.swords.dagger'] = SkillSubComponent(7) sys = SkillSystem() sys.set_entity_manager(em) event.register(sys) for x in range(iters): ch = SkillCheckEvent(em.pc, "melee.swords.dagger") event.dispatch(ch) if ch.result[2]: wins += 1 # Use a fudge factor, because random assert wins >= (iters * 0.38) assert wins <= (iters * 0.44)
Fix tests to use new key structure
Fix tests to use new key structure
Python
mit
Kromey/roglick
--- +++ @@ -14,14 +14,14 @@ skills = em.get_component(em.pc, SkillComponent) # 7 has ~41% odds of success - skills.skills['Dagger'] = SkillSubComponent(7) + skills.skills['melee.swords.dagger'] = SkillSubComponent(7) sys = SkillSystem() sys.set_entity_manager(em) event.register(sys) for x in range(iters): - ch = SkillCheckEvent(em.pc, "Dagger") + ch = SkillCheckEvent(em.pc, "melee.swords.dagger") event.dispatch(ch) if ch.result[2]:
096a8972d610379356d668d57d92010707fcf9e1
blockbuster/__init__.py
blockbuster/__init__.py
__author__ = 'matt' from flask import Flask app = Flask(__name__) def startup(): import blockbuster.bb_dbconnector_factory import blockbuster.bb_logging as log import blockbuster.bb_auditlogger as audit try: if blockbuster.bb_dbconnector_factory.DBConnectorInterfaceFactory().create().db_version_check(): import blockbuster.bb_routes print("Running...") else: raise RuntimeError("Incorrect database schema version.") except RuntimeError, e: log.logger.exception("Incorrect database schema version.") audit.BBAuditLoggerFactory().create().logException('app', 'STARTUP', 'Incorrect database schema version.') startup()
__author__ = 'matt' __version__ = '1.24.02' target_schema_version = '1.24.00' from flask import Flask app = Flask(__name__) def startup(): import blockbuster.bb_dbconnector_factory import blockbuster.bb_logging as log import blockbuster.bb_auditlogger as audit try: if blockbuster.bb_dbconnector_factory.DBConnectorInterfaceFactory().create().db_version_check(): import blockbuster.bb_routes print("Running...") else: raise RuntimeError("Incorrect database schema version.") except RuntimeError, e: log.logger.exception("Incorrect database schema version.") audit.BBAuditLoggerFactory().create().logException('app', 'STARTUP', 'Incorrect database schema version.') startup()
Move version numbers back to the package init file
Move version numbers back to the package init file
Python
mit
mattstibbs/blockbuster-server,mattstibbs/blockbuster-server
--- +++ @@ -1,4 +1,6 @@ __author__ = 'matt' +__version__ = '1.24.02' +target_schema_version = '1.24.00' from flask import Flask app = Flask(__name__)
d4f7178decbb55a9d6f559e7f94ad2cc6d806b18
dashboard/ratings/models.py
dashboard/ratings/models.py
import uuid from django.db import models class Submission(models.Model): uuid = models.UUIDField(default=uuid.uuid4,editable=False) application_date = models.DateTimeField() submission_date = models.DateTimeField() def __str__(self): uid = self.uuid.urn return uid[9:] class Media(models.Model): filename = models.TextField() filetype = models.CharField(max_length=200) submission = models.ForeignKey(Submission) def __str__(self): return self.filename class Rating(models.Model): score = models.DecimalField(default=0,max_digits=5,decimal_places=2) code_quality = models.IntegerField(default=0) documentation = models.IntegerField(default=0) problem_solving = models.IntegerField(default=0) effort = models.IntegerField(default=0) creativity = models.IntegerField(default=0) originality = models.IntegerField(default=0) submission = models.OneToOneField(Submission) def __str__(self): return self.score
import uuid from django.db import models class Submission(models.Model): uuid = models.UUIDField(default=uuid.uuid4,editable=False) application_date = models.DateTimeField() submission_date = models.DateTimeField() def __str__(self): uid = self.uuid.urn return uid[9:] class Media(models.Model): filename = models.TextField() filetype = models.CharField(max_length=200) submission = models.ForeignKey(Submission) def __str__(self): return self.filename class Rating(models.Model): score = models.DecimalField(default=0,max_digits=5,decimal_places=2) code_quality = models.IntegerField(default=0) documentation = models.IntegerField(default=0) problem_solving = models.IntegerField(default=0) effort = models.IntegerField(default=0) creativity = models.IntegerField(default=0) originality = models.IntegerField(default=0) submission = models.OneToOneField(Submission) def __str__(self): return self.submission.uuid.urn[9:] + ": " + str(self.score)
Fix Rating model str method
Fix Rating model str method
Python
mit
daltonamitchell/rating-dashboard,daltonamitchell/rating-dashboard,daltonamitchell/rating-dashboard
--- +++ @@ -29,4 +29,4 @@ originality = models.IntegerField(default=0) submission = models.OneToOneField(Submission) def __str__(self): - return self.score + return self.submission.uuid.urn[9:] + ": " + str(self.score)
1e3b23597e5bff437dca0f94fdbd644b1454e395
scrapi/harvesters/scholarsarchiveosu.py
scrapi/harvesters/scholarsarchiveosu.py
''' Harvester for the ScholarsArchive@OSU for the SHARE project Example API call: http://ir.library.oregonstate.edu/oai/request?verb=ListRecords&metadataPrefix=oai_dc ''' from __future__ import unicode_literals from scrapi.base import helpers from scrapi.base import OAIHarvester class ScholarsarchiveosuHarvester(OAIHarvester): short_name = 'scholarsarchiveosu' long_name = 'ScholarsArchive@OSU' url = 'http://ir.library.oregonstate.edu/oai/request' base_url = 'http://ir.library.oregonstate.edu/oai/request' @property def schema(self): return helpers.updated_schema(self._schema, { "uris": { "objectUris": [('//dc:identifier/node()', helpers.extract_doi_from_text)] } }) # TODO - return date once we figure out es parsing errors property_list = ['relation', 'identifier', 'type', 'setSpec'] timezone_granularity = True
''' Harvester for the ScholarsArchive@OSU for the SHARE project Example API call: http://ir.library.oregonstate.edu/oai/request?verb=ListRecords&metadataPrefix=oai_dc ''' from __future__ import unicode_literals from scrapi.base import helpers from scrapi.base import OAIHarvester class ScholarsarchiveosuHarvester(OAIHarvester): short_name = 'scholarsarchiveosu' long_name = 'ScholarsArchive@OSU' url = 'http://ir.library.oregonstate.edu/' base_url = 'http://ir.library.oregonstate.edu/oai/request' @property def schema(self): return helpers.updated_schema(self._schema, { "uris": { "objectUris": [('//dc:identifier/node()', helpers.extract_doi_from_text)] } }) # TODO - return date once we figure out es parsing errors property_list = ['relation', 'identifier', 'type', 'setSpec'] timezone_granularity = True
Update url for OSU harvester
Update url for OSU harvester
Python
apache-2.0
erinspace/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,alexgarciac/scrapi,jeffreyliu3230/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,erinspace/scrapi,mehanig/scrapi,mehanig/scrapi,fabianvf/scrapi
--- +++ @@ -12,7 +12,7 @@ class ScholarsarchiveosuHarvester(OAIHarvester): short_name = 'scholarsarchiveosu' long_name = 'ScholarsArchive@OSU' - url = 'http://ir.library.oregonstate.edu/oai/request' + url = 'http://ir.library.oregonstate.edu/' base_url = 'http://ir.library.oregonstate.edu/oai/request'
e665154e1b522feac8cd46c39ba523bc7197afab
annoying/tests/urls.py
annoying/tests/urls.py
"""URLs for django-annoying's tests""" from __future__ import absolute_import from django.conf.urls import url from . import views urlpatterns = [ url(r'^ajax-request/$', views.ajax_request_view), url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view), url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg), url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg), url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional), ]
"""URLs for django-annoying's tests""" from __future__ import absolute_import from django.conf.urls import url from . import views import django from distutils.version import StrictVersion django_version = django.get_version() # Use old URL Conf settings for Django <= 1.8. if StrictVersion(django_version) < StrictVersion('1.8.0'): from django.conf.urls import patterns urlpatterns = patterns('', (r'^ajax-request/$', views.ajax_request_view), (r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view), (r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg), (r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg), (r'^render-to-content-type-positional/$', views.render_to_content_type_positional), ) else: urlpatterns = [ url(r'^ajax-request/$', views.ajax_request_view), url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view), url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg), url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg), url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional), ]
Use old URL Conf settings for Django <= 1.8.
Use old URL Conf settings for Django <= 1.8.
Python
bsd-3-clause
kabakchey/django-annoying,skorokithakis/django-annoying,YPCrumble/django-annoying,kabakchey/django-annoying,skorokithakis/django-annoying
--- +++ @@ -4,10 +4,25 @@ from django.conf.urls import url from . import views -urlpatterns = [ - url(r'^ajax-request/$', views.ajax_request_view), - url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view), - url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg), - url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg), - url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional), -] +import django +from distutils.version import StrictVersion +django_version = django.get_version() + +# Use old URL Conf settings for Django <= 1.8. +if StrictVersion(django_version) < StrictVersion('1.8.0'): + from django.conf.urls import patterns + urlpatterns = patterns('', + (r'^ajax-request/$', views.ajax_request_view), + (r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view), + (r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg), + (r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg), + (r'^render-to-content-type-positional/$', views.render_to_content_type_positional), + ) +else: + urlpatterns = [ + url(r'^ajax-request/$', views.ajax_request_view), + url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view), + url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg), + url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg), + url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional), + ]
bb4a0ca8626f0287a5366e97313018fcc59bcf8f
demo/__init__.py
demo/__init__.py
__project__ = 'TemplateDemo' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__)
from pkg_resources import DistributionNotFound, get_distribution try: __version__ = get_distribution('TemplateDemo').version except DistributionNotFound: __version__ = '(local)'
Deploy Travis CI build 1156 to GitHub
Deploy Travis CI build 1156 to GitHub
Python
mit
jacebrowning/template-python-demo
--- +++ @@ -1,4 +1,7 @@ -__project__ = 'TemplateDemo' -__version__ = '0.0.0' +from pkg_resources import DistributionNotFound, get_distribution -VERSION = "{0} v{1}".format(__project__, __version__) + +try: + __version__ = get_distribution('TemplateDemo').version +except DistributionNotFound: + __version__ = '(local)'
0baa14975ae1b0729021ecf4d0d88acadb866414
pfamserver/api.py
pfamserver/api.py
from application import app from flask.ext.restful import Api, Resource import os from subprocess import Popen as run, PIPE from distutils.sysconfig import get_python_lib from autoupdate import lib_path, db_path api = Api(app) fetch = '{:s}/hmmer/easel/miniapps/esl-afetch'.format(lib_path) def db(query): cmd = [fetch, db_path, query] return run(cmd, stdout=PIPE).communicate()[0] class QueryAPI(Resource): def get(self, query): queries = [query, query.capitalize(), query.upper(), query.lower()] for q in queries: output = db(q) if output: return {'query': q, 'output': output} return {'query': query, 'output': output} api.add_resource(QueryAPI, '/api/query/<string:query>', endpoint = 'query')
from application import app from flask.ext.restful import Api, Resource import os from subprocess import Popen as run, PIPE from distutils.sysconfig import get_python_lib from autoupdate import lib_path, db_path api = Api(app) fetch = '{:s}/hmmer/easel/miniapps/esl-afetch'.format(lib_path) def db(query): cmd = [fetch, db_path, query] return run(cmd, stdout=PIPE).communicate()[0] class QueryAPI(Resource): def get(self, query): queries = [query, query.upper(), query.capitalize(), query.lower()] for q in queries: output = db(q) if output: return {'query': q, 'output': output} return {'query': query, 'output': output} api.add_resource(QueryAPI, '/api/query/<string:query>', endpoint = 'query')
Improve the query execution order.
Improve the query execution order.
Python
agpl-3.0
ecolell/pfamserver,ecolell/pfamserver,ecolell/pfamserver
--- +++ @@ -18,7 +18,7 @@ class QueryAPI(Resource): def get(self, query): - queries = [query, query.capitalize(), query.upper(), query.lower()] + queries = [query, query.upper(), query.capitalize(), query.lower()] for q in queries: output = db(q)
92bcca68aad8ba7c8be378ef005c6e94018c2bda
instance/tests/integration/base.py
instance/tests/integration/base.py
# -*- coding: utf-8 -*- # # OpenCraft -- tools to aid developing and hosting free software projects # Copyright (C) 2015 OpenCraft <xavier@opencraft.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Tests - Integration - Base """ # Imports ##################################################################### from huey import djhuey from instance.models.server import OpenStackServer from instance.tests.base import TestCase # Tests ####################################################################### class IntegrationTestCase(TestCase): """ Base class for API tests """ def setUp(self): # Override the environment setting - always run task in the same process djhuey.HUEY.always_eager = True def tearDown(self): # Ensure we don't leave any VM running OpenStackServer.objects.terminate()
# -*- coding: utf-8 -*- # # OpenCraft -- tools to aid developing and hosting free software projects # Copyright (C) 2015 OpenCraft <xavier@opencraft.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Tests - Integration - Base """ # Imports ##################################################################### from huey import djhuey from instance.models.server import OpenStackServer from instance.tests.base import TestCase # Tests ####################################################################### class IntegrationTestCase(TestCase): """ Base class for API tests """ def setUp(self): super().setUp() # Override the environment setting - always run task in the same process djhuey.HUEY.always_eager = True def tearDown(self): OpenStackServer.objects.terminate() super().tearDown()
Make sure integration tests call super.
Make sure integration tests call super.
Python
agpl-3.0
omarkhan/opencraft,omarkhan/opencraft,open-craft/opencraft,omarkhan/opencraft,open-craft/opencraft,open-craft/opencraft,open-craft/opencraft,omarkhan/opencraft,open-craft/opencraft
--- +++ @@ -35,9 +35,10 @@ Base class for API tests """ def setUp(self): + super().setUp() # Override the environment setting - always run task in the same process djhuey.HUEY.always_eager = True def tearDown(self): - # Ensure we don't leave any VM running OpenStackServer.objects.terminate() + super().tearDown()
0aece66f694a1d8d64a76f35ebfd559b8fd2284a
bridge_common/config.py
bridge_common/config.py
""" Configuration options registration and useful routines. """ from oslo_config import cfg CONF = cfg.CONF
""" Configuration options registration and useful routines. """ from oslo_config import cfg CONF = cfg.CONF
Fix pep8 issues for HEAD
Fix pep8 issues for HEAD
Python
lgpl-2.1
Tendrl/commons,rishubhjain/commons,r0h4n/commons
0a7c6011607bccc61570c8f027c547425e8d53cf
iterm2_tools/tests/test_ipython.py
iterm2_tools/tests/test_ipython.py
from __future__ import print_function, division, absolute_import import subprocess import sys import os def test_IPython(): ipython = os.path.join(sys.prefix, 'bin', 'ipython') if not os.path.exists(ipython): raise Exception("IPython must be installed in %s to run the IPython tests" % os.path.join(sys.prefix, 'bin')) commands = b"""\ 1 raise Exception undefined def f(): pass f() """ p = subprocess.Popen([ipython, '--quick', '--colors=LightBG', '--no-banner'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate(input=commands) assert (stdout, stderr) == (b'', b'')
from __future__ import print_function, division, absolute_import import subprocess import sys import os from IPython.testing.tools import get_ipython_cmd def test_IPython(): ipython = get_ipython_cmd() commands = b"""\ 1 raise Exception undefined def f(): pass f() """ p = subprocess.Popen([ipython, '--quick', '--colors=LightBG', '--no-banner'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate(input=commands) assert (stdout, stderr) == (b'', b'')
Use get_ipython_cmd in IPython test
Use get_ipython_cmd in IPython test
Python
mit
asmeurer/iterm2-tools
--- +++ @@ -4,11 +4,10 @@ import sys import os +from IPython.testing.tools import get_ipython_cmd + def test_IPython(): - ipython = os.path.join(sys.prefix, 'bin', 'ipython') - if not os.path.exists(ipython): - raise Exception("IPython must be installed in %s to run the IPython tests" % os.path.join(sys.prefix, 'bin')) - + ipython = get_ipython_cmd() commands = b"""\ 1
a61a09a08322c3e74800c0635c4848280ad9341e
src/syntax/infix_coordination.py
src/syntax/infix_coordination.py
__author__ = 's7a' # All imports from nltk.tree import Tree # The infix coordination class class InfixCoordination: # Constructor for the infix coordination def __init__(self): self.has_infix_coordination = False # Break the tree def break_tree(self, tree): self.has_infix_coordination = False self.parse_tree(tree) print "Infix Coordination: " + str(self.has_infix_coordination) # Parse the tree def parse_tree(self, tree): if type(tree) == Tree: sentence_root = tree[0] if type(sentence_root) == Tree: if sentence_root.label() == "S": print "Valid Tree" for node in sentence_root: if type(node) == Tree: if node.label() == "CC": self.has_infix_coordination |= True
__author__ = 's7a' # All imports from nltk.tree import Tree # The infix coordination class class InfixCoordination: # Constructor for the infix coordination def __init__(self): self.has_infix_coordination = False self.slice_point = -1 self.subtree_list = [] # Break the tree def break_tree(self, tree): self.has_infix_coordination = False self.slice_point = -1 self.subtree_list = [] self.parse_tree(tree) print "Infix Coordination: " + str(self.has_infix_coordination) print self.slice_point print self.subtree_list result_string = ' '.join(self.subtree_list[:self.slice_point-1]) +\ '. ' + ' '.join(self.subtree_list[self.slice_point:]) print result_string return result_string # Parse the tree def parse_tree(self, tree): if type(tree) == Tree: sentence_root = tree[0] if type(sentence_root) == Tree: if sentence_root.label() == "S": print "Valid Tree" counter = 0 for node in sentence_root: counter += 1 self.subtree_list.append(' '.join(node.leaves())) if type(node) == Tree: if node.label() == "CC": self.has_infix_coordination |= True self.slice_point = counter
Split the sentence in case of infix coordinatiin
Split the sentence in case of infix coordinatiin
Python
mit
Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify
--- +++ @@ -10,12 +10,27 @@ # Constructor for the infix coordination def __init__(self): self.has_infix_coordination = False + self.slice_point = -1 + self.subtree_list = [] # Break the tree def break_tree(self, tree): self.has_infix_coordination = False + self.slice_point = -1 + self.subtree_list = [] + self.parse_tree(tree) + print "Infix Coordination: " + str(self.has_infix_coordination) + print self.slice_point + print self.subtree_list + + result_string = ' '.join(self.subtree_list[:self.slice_point-1]) +\ + '. ' + ' '.join(self.subtree_list[self.slice_point:]) + + print result_string + + return result_string # Parse the tree def parse_tree(self, tree): @@ -24,7 +39,14 @@ if type(sentence_root) == Tree: if sentence_root.label() == "S": print "Valid Tree" + + counter = 0 for node in sentence_root: + counter += 1 + + self.subtree_list.append(' '.join(node.leaves())) + if type(node) == Tree: if node.label() == "CC": self.has_infix_coordination |= True + self.slice_point = counter
56f7c35722b4d90e04bf2da3d7d72ef0bfd52602
tests/test_decorators.py
tests/test_decorators.py
import pytest from funcy.decorators import * def test_decorator_no_args(): @decorator def inc(call): return call() + 1 @inc def ten(): return 10 assert ten() == 11 def test_decorator_with_args(): @decorator def add(call, n): return call() + n @add(2) def ten(): return 10 assert ten() == 12 def test_decorator_access_arg(): @decorator def multiply(call): return call() * call.n @multiply def square(n): return n assert square(5) == 25 def test_decorator_access_nonexistent_arg(): @decorator def return_x(call): return call.x @return_x def f(): pass with pytest.raises(AttributeError): f() def test_decorator_with_method(): @decorator def inc(call): return call() + 1 class A(object): def ten(self): return 10 @classmethod def ten_cls(cls): return 10 @staticmethod def ten_static(): return 10 assert inc(A().ten)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_static)() == 11
import pytest from funcy.decorators import * def test_decorator_no_args(): @decorator def inc(call): return call() + 1 @inc def ten(): return 10 assert ten() == 11 def test_decorator_with_args(): @decorator def add(call, n): return call() + n @add(2) def ten(): return 10 assert ten() == 12 def test_decorator_access_arg(): @decorator def multiply(call): return call() * call.n @multiply def square(n): return n assert square(5) == 25 def test_decorator_access_nonexistent_arg(): @decorator def return_x(call): return call.x @return_x def f(): pass with pytest.raises(AttributeError): f() def test_decorator_with_method(): @decorator def inc(call): return call() + 1 class A(object): def ten(self): return 10 @classmethod def ten_cls(cls): return 10 @staticmethod def ten_static(): return 10 assert inc(A().ten)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_static)() == 11 @pytest.mark.xfail def test_chain_arg_access(): @decorator def decor(call): return call.x + call() @decor @decor def func(x): return x assert func(2) == 6
Add a test on failed arg introspection in chained decorators
Add a test on failed arg introspection in chained decorators This is a consequence of not preserving function signature. So this could be fixed by preserving signature or by some workaround.
Python
bsd-3-clause
musicpax/funcy,ma-ric/funcy,Suor/funcy
--- +++ @@ -71,3 +71,17 @@ assert inc(A.ten_cls)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_static)() == 11 + + +@pytest.mark.xfail +def test_chain_arg_access(): + @decorator + def decor(call): + return call.x + call() + + @decor + @decor + def func(x): + return x + + assert func(2) == 6
df8efcc0f86fa9a311ec444da7e6488de2e86d8a
tests/test_repr.py
tests/test_repr.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> import pytest import numpy as np from parameters import T_VALUES, KPT @pytest.mark.parametrize('t', T_VALUES) def test_repr_reload(t, get_model): m1 = get_model(*t) m2 = eval(repr(m1)) for k in KPT: assert np.isclose(m1.hamilton(k), m2.hamilton(k)).all()
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> import pytest import tbmodels # pylint: disable=unused-import import numpy as np from tbmodels._ptools.sparse_matrix import csr # pylint: disable=unused-import from parameters import T_VALUES, KPT @pytest.mark.parametrize('t', T_VALUES) def test_repr_reload(t, get_model): m1 = get_model(*t) m2 = eval(repr(m1)) for k in KPT: assert np.isclose(m1.hamilton(k), m2.hamilton(k)).all()
Add back imports to repr test.
Add back imports to repr test.
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
--- +++ @@ -5,8 +5,11 @@ # Author: Dominik Gresch <greschd@gmx.ch> import pytest +import tbmodels # pylint: disable=unused-import import numpy as np + +from tbmodels._ptools.sparse_matrix import csr # pylint: disable=unused-import from parameters import T_VALUES, KPT
fc123442727ae25f03c5aa8d2fa7bc6fae388ae2
thecure/levels/level1.py
thecure/levels/level1.py
from thecure.levels.base import Level from thecure.sprites import Direction, InfectedHuman class Level1(Level): name = 'level1' start_pos = (900, 6200) def setup(self): boy = InfectedHuman('boy1') self.main_layer.add(boy) boy.move_to(300, 160) boy.set_direction(Direction.DOWN) girl = InfectedHuman('girl1') self.main_layer.add(girl) girl.move_to(470, 200) girl.set_direction(Direction.LEFT) def draw_bg(self, surface): surface.fill((237, 243, 255))
from thecure.levels.base import Level from thecure.sprites import Direction, InfectedHuman class Level1(Level): name = 'level1' start_pos = (900, 6200) def setup(self): boy = InfectedHuman('boy1') self.main_layer.add(boy) boy.move_to(1536, 5696) boy.set_direction(Direction.DOWN) girl = InfectedHuman('girl1') self.main_layer.add(girl) girl.move_to(1536, 5824) girl.set_direction(Direction.UP) def draw_bg(self, surface): surface.fill((237, 243, 255))
Move the kids onto the field.
Move the kids onto the field.
Python
mit
chipx86/the-cure
--- +++ @@ -9,13 +9,13 @@ def setup(self): boy = InfectedHuman('boy1') self.main_layer.add(boy) - boy.move_to(300, 160) + boy.move_to(1536, 5696) boy.set_direction(Direction.DOWN) girl = InfectedHuman('girl1') self.main_layer.add(girl) - girl.move_to(470, 200) - girl.set_direction(Direction.LEFT) + girl.move_to(1536, 5824) + girl.set_direction(Direction.UP) def draw_bg(self, surface): surface.fill((237, 243, 255))
35bbc1d720ba36631fc0a821f7aa953dd8736f2a
laalaa/apps/advisers/middleware.py
laalaa/apps/advisers/middleware.py
from django.http import HttpResponse from django.utils.deprecation import MiddlewareMixin class PingMiddleware(MiddlewareMixin): def process_request(self, request): if request.method == "GET": if request.path == "/ping.json": return self.ping(request) pass def ping(self, request): """ Returns that the server is alive. """ return HttpResponse("OK")
from django.http import HttpResponse class PingMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.ping(request) or self.get_response(request) def ping(self, request): """ Returns that the server is alive. """ if request.method == "GET": if request.path == "/ping.json": return HttpResponse("OK")
Remove use of django.utils.deprecation.MiddlewareMixin for PingMiddleware and upgrade Middleware to latest spec
Remove use of django.utils.deprecation.MiddlewareMixin for PingMiddleware and upgrade Middleware to latest spec
Python
mit
ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api
--- +++ @@ -1,16 +1,17 @@ from django.http import HttpResponse -from django.utils.deprecation import MiddlewareMixin -class PingMiddleware(MiddlewareMixin): - def process_request(self, request): - if request.method == "GET": - if request.path == "/ping.json": - return self.ping(request) - pass +class PingMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + return self.ping(request) or self.get_response(request) def ping(self, request): """ Returns that the server is alive. """ - return HttpResponse("OK") + if request.method == "GET": + if request.path == "/ping.json": + return HttpResponse("OK")
bcc2e41717e5287908867958c60ceb09ca824d7a
tests/apps/flask_app/__init__.py
tests/apps/flask_app/__init__.py
# (c) Copyright IBM Corp. 2021 # (c) Copyright Instana Inc. 2020 import os from .app import flask_server as server from ..utils import launch_background_thread app_thread = None if not os.environ('CASSANDRA_TEST') and app_thread is None: app_thread = launch_background_thread(server.serve_forever, "Flask")
# (c) Copyright IBM Corp. 2021 # (c) Copyright Instana Inc. 2020 import os from .app import flask_server as server from ..utils import launch_background_thread app_thread = None if not os.environ.get('CASSANDRA_TEST') and app_thread is None: app_thread = launch_background_thread(server.serve_forever, "Flask")
Use falsy values for test environment variable in flask_app
test: Use falsy values for test environment variable in flask_app Signed-off-by: Ferenc Géczi <056c6d27de7ab660258538226bb901048afb31e4@ibm.com>
Python
mit
instana/python-sensor,instana/python-sensor
--- +++ @@ -7,5 +7,5 @@ app_thread = None -if not os.environ('CASSANDRA_TEST') and app_thread is None: +if not os.environ.get('CASSANDRA_TEST') and app_thread is None: app_thread = launch_background_thread(server.serve_forever, "Flask")
4c3a21a73dbdf47d5cac04bfda20df7f85596b22
tests/suite/kube_config_utils.py
tests/suite/kube_config_utils.py
"""Describe methods to work with kubeconfig file.""" import pytest import yaml def get_current_context_name(kube_config) -> str: """ Get current-context from kubeconfig. :param kube_config: absolute path to kubeconfig :return: str """ with open(kube_config) as conf: dep = yaml.load(conf) return dep['current-context'] def ensure_context_in_config(kube_config, context_name) -> None: """ Verify that kubeconfig contains specific context and fail if it doesn't. :param kube_config: absolute path to kubeconfig :param context_name: context name to verify :return: """ with open(kube_config) as conf: dep = yaml.load(conf) for users in dep['users']: if users['name'] == context_name: return pytest.fail(f"Failed to find context '{context_name}' in the kubeconfig file: {kube_config}")
"""Describe methods to work with kubeconfig file.""" import pytest import yaml def get_current_context_name(kube_config) -> str: """ Get current-context from kubeconfig. :param kube_config: absolute path to kubeconfig :return: str """ with open(kube_config) as conf: dep = yaml.load(conf) return dep['current-context'] def ensure_context_in_config(kube_config, context_name) -> None: """ Verify that kubeconfig contains specific context and fail if it doesn't. :param kube_config: absolute path to kubeconfig :param context_name: context name to verify :return: """ with open(kube_config) as conf: dep = yaml.load(conf) for contexts in dep['contexts']: if contexts['name'] == context_name: return pytest.fail(f"Failed to find context '{context_name}' in the kubeconfig file: {kube_config}")
Fix parsing of the kubeconfig file
Fix parsing of the kubeconfig file
Python
apache-2.0
nginxinc/kubernetes-ingress,nginxinc/kubernetes-ingress,nginxinc/kubernetes-ingress,nginxinc/kubernetes-ingress
--- +++ @@ -25,7 +25,7 @@ """ with open(kube_config) as conf: dep = yaml.load(conf) - for users in dep['users']: - if users['name'] == context_name: + for contexts in dep['contexts']: + if contexts['name'] == context_name: return pytest.fail(f"Failed to find context '{context_name}' in the kubeconfig file: {kube_config}")
4f577eabc45acb6e9a8880d062daa225cc76d64c
logparser/logs/micro/micro.py
logparser/logs/micro/micro.py
# Log Parser for RTI Connext. # # Copyright 2016 Real-Time Innovations, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Log parsing functions for Micro.""" from __future__ import absolute_import from json import load from pkg_resources import resource_filename def init(state): """Init Micro logs.""" filename = resource_filename( 'logparser.logs.micro', 'error_logs.json') with open(filename) as json_errors: state["json_errors"] = load(json_errors) def on_micro_error(match, state, logger): """Error on Micro was thrown.""" module_id = match[2] error_id = match[3] errors = state["json_errors"] error_description = errors[module_id][error_id]["description"] error_name = errors[module_id][error_id]["name"] logger.error("[" + error_name + "] " + error_description)
# Log Parser for RTI Connext. # # Copyright 2016 Real-Time Innovations, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Log parsing functions for Micro.""" from __future__ import absolute_import from json import load from pkg_resources import resource_filename def init(state): """Init Micro logs.""" filename = resource_filename( 'logparser.logs.micro', 'error_logs.json') with open(filename) as json_errors: state["json_errors"] = load(json_errors) def on_micro_error(match, state, logger): """Error on Micro was thrown.""" module_id = match[2] error_id = match[3] errors = state["json_errors"] if module_id in errors: module = errors[module_id] if error_id in module: error_description = module[error_id]["description"] error_name = module[error_id]["name"] logger.error("[" + error_name + "] " + error_description)
Check if module and error code exist
Check if module and error code exist
Python
apache-2.0
rticommunity/rticonnextdds-logparser,rticommunity/rticonnextdds-logparser
--- +++ @@ -34,7 +34,9 @@ error_id = match[3] errors = state["json_errors"] - error_description = errors[module_id][error_id]["description"] - error_name = errors[module_id][error_id]["name"] - - logger.error("[" + error_name + "] " + error_description) + if module_id in errors: + module = errors[module_id] + if error_id in module: + error_description = module[error_id]["description"] + error_name = module[error_id]["name"] + logger.error("[" + error_name + "] " + error_description)
f5369b9b0175e221743101abb936b5a2947a3808
polyaxon/libs/paths.py
polyaxon/libs/paths.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import logging import os import shutil logger = logging.getLogger('polyaxon.libs.paths') def delete_path(path): if not os.path.exists(path): return try: shutil.rmtree(path) except OSError: logger.warning('Could not delete path `{}`'.format(path)) def create_path(path): os.mkdir(path) os.chmod(path, 0o777)
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import logging import os import shutil logger = logging.getLogger('polyaxon.libs.paths') def delete_path(path): if not os.path.exists(path): return try: if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) except OSError: logger.warning('Could not delete path `{}`'.format(path)) def create_path(path): os.mkdir(path) os.chmod(path, 0o777)
Check if file or dir before deleting
Check if file or dir before deleting
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
--- +++ @@ -12,7 +12,10 @@ if not os.path.exists(path): return try: - shutil.rmtree(path) + if os.path.isfile(path): + os.remove(path) + else: + shutil.rmtree(path) except OSError: logger.warning('Could not delete path `{}`'.format(path))
9e40fbd1992854db138157d9a7c2fd995722f5ea
massa/__init__.py
massa/__init__.py
# -*- coding: utf-8 -*- from flask import Flask, render_template, g from .container import build from .web import bp as web from .api import bp as api def create_app(config=None): app = Flask('massa') app.config.from_object(config or 'massa.config.Production') sl = build(app.config) app.register_blueprint(web) app.register_blueprint(api, url_prefix='/api') @app.before_request def globals(): g.sl = sl return app
# -*- coding: utf-8 -*- from flask import Flask, render_template, g from .container import build from .web import bp as web from .api import bp as api def create_app(config=None): app = Flask('massa') app.config.from_object(config or 'massa.config.Production') app.config.from_envvar('MASSA_CONFIG', silent=True) sl = build(app.config) app.register_blueprint(web) app.register_blueprint(api, url_prefix='/api') @app.before_request def globals(): g.sl = sl return app
Add the ability to specify an alternative configuration object.
Add the ability to specify an alternative configuration object.
Python
mit
jaapverloop/massa
--- +++ @@ -9,6 +9,7 @@ def create_app(config=None): app = Flask('massa') app.config.from_object(config or 'massa.config.Production') + app.config.from_envvar('MASSA_CONFIG', silent=True) sl = build(app.config)
bb48c975cfb4f43b8ffc5c7edfd42a8253fa7d66
skan/test/test_pipe.py
skan/test/test_pipe.py
import os import pytest import tempfile import pandas from skan import pipe @pytest.fixture def image_filename(): rundir = os.path.abspath(os.path.dirname(__file__)) datadir = os.path.join(rundir, 'data') return os.path.join(datadir, 'retic.tif') def test_pipe(image_filename): data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075, 'Scan/PixelHeight') assert type(data) == pandas.DataFrame assert data.shape[0] > 0 def test_pipe_figure(image_filename): with tempfile.TemporaryDirectory() as tempdir: data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075, 'Scan/PixelHeight', save_skeleton='skeleton-plot-', output_folder=tempdir) assert type(data) == pandas.DataFrame assert data.shape[0] > 0 assert os.path.exists(os.path.join(tempdir, 'skeleton-plot-' + image_filename[:-4] + '.png'))
import os import pytest import tempfile import pandas from skan import pipe @pytest.fixture def image_filename(): rundir = os.path.abspath(os.path.dirname(__file__)) datadir = os.path.join(rundir, 'data') return os.path.join(datadir, 'retic.tif') def test_pipe(image_filename): data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075, 'Scan/PixelHeight') assert type(data) == pandas.DataFrame assert data.shape[0] > 0 def test_pipe_figure(image_filename): with tempfile.TemporaryDirectory() as tempdir: data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075, 'Scan/PixelHeight', save_skeleton='skeleton-plot-', output_folder=tempdir) assert type(data) == pandas.DataFrame assert data.shape[0] > 0 expected_output = os.path.join(tempdir, 'skeleton-plot-' + os.path.basename(image_filename)[:-4] + '.png') assert os.path.exists(expected_output)
Fix test for output skeleton plot
Fix test for output skeleton plot
Python
bsd-3-clause
jni/skan
--- +++ @@ -27,7 +27,7 @@ output_folder=tempdir) assert type(data) == pandas.DataFrame assert data.shape[0] > 0 - assert os.path.exists(os.path.join(tempdir, - 'skeleton-plot-' + - image_filename[:-4] + - '.png')) + expected_output = os.path.join(tempdir, 'skeleton-plot-' + + os.path.basename(image_filename)[:-4] + + '.png') + assert os.path.exists(expected_output)
157d5c2f680134fa5b9f4f69320259416c46f44b
tp/netlib/objects/Order_Probe.py
tp/netlib/objects/Order_Probe.py
import copy from Order import Order class Order_Probe(Order): no = 34 def __init__(self, sequence, \ id, slot, type, \ *args, **kw): self.no = 34 apply(Order.__init__, (self, sequence, id, slot, type, -1, [])+args, kw)
import copy from Order import Order class Order_Probe(Order): no = 34 def __init__(self, *args, **kw): self.no = 34 Order.__init__(self, *args, **kw)
Fix the Order Probe message for the new order stuff.
Fix the Order Probe message for the new order stuff.
Python
lgpl-2.1
thousandparsec/libtpproto-py,thousandparsec/libtpproto-py
--- +++ @@ -4,8 +4,6 @@ class Order_Probe(Order): no = 34 - def __init__(self, sequence, \ - id, slot, type, \ - *args, **kw): + def __init__(self, *args, **kw): self.no = 34 - apply(Order.__init__, (self, sequence, id, slot, type, -1, [])+args, kw) + Order.__init__(self, *args, **kw)
5619b04f55418c943e7a7af606b5247ce4441160
examples/IPLoM_example.py
examples/IPLoM_example.py
# for local run, before pygraphc packaging import sys sys.path.insert(0, '../pygraphc/misc') from IPLoM import * sys.path.insert(0, '../pygraphc/clustering') from ClusterUtility import * from ClusterEvaluation import * # set path ip_address = '161.166.232.17' standard_path = '/home/hudan/Git/labeled-authlog/dataset/' + ip_address standard_file = standard_path + 'auth.log.anon.labeled' analyzed_file = 'auth.log.anon' prediction_file = 'iplom-result-' + ip_address + '.txt' OutputPath = './results' para = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath) # call IPLoM and get clusters myparser = IPLoM(para) time = myparser.main_process() clusters = myparser.get_clusters() original_logs = myparser.get_logs() # set cluster label to get evaluation metrics ClusterUtility.set_cluster_label_id(None, clusters, original_logs, prediction_file) homogeneity_completeness_vmeasure = ClusterEvaluation.get_homogeneity_completeness_vmeasure(standard_file, prediction_file) print homogeneity_completeness_vmeasure print ('The running time of IPLoM is', time)
# for local run, before pygraphc packaging import sys sys.path.insert(0, '../pygraphc/misc') from IPLoM import * sys.path.insert(0, '../pygraphc/evaluation') from ExternalEvaluation import * # set path ip_address = '161.166.232.17' standard_path = '/home/hudan/Git/labeled-authlog/dataset/' + ip_address standard_file = standard_path + 'auth.log.anon.labeled' analyzed_file = 'auth.log.anon' prediction_file = 'iplom-result-' + ip_address + '.txt' OutputPath = './results' para = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath) # call IPLoM and get clusters myparser = IPLoM(para) time = myparser.main_process() clusters = myparser.get_clusters() original_logs = myparser.logs # set cluster label to get evaluation metrics ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file) homogeneity_completeness_vmeasure = ExternalEvaluation.get_homogeneity_completeness_vmeasure(standard_file, prediction_file) print homogeneity_completeness_vmeasure print ('The running time of IPLoM is', time)
Change module path for cluster evaluation
Change module path for cluster evaluation
Python
mit
studiawan/pygraphc
--- +++ @@ -2,9 +2,8 @@ import sys sys.path.insert(0, '../pygraphc/misc') from IPLoM import * -sys.path.insert(0, '../pygraphc/clustering') -from ClusterUtility import * -from ClusterEvaluation import * +sys.path.insert(0, '../pygraphc/evaluation') +from ExternalEvaluation import * # set path ip_address = '161.166.232.17' @@ -19,11 +18,11 @@ myparser = IPLoM(para) time = myparser.main_process() clusters = myparser.get_clusters() -original_logs = myparser.get_logs() +original_logs = myparser.logs # set cluster label to get evaluation metrics -ClusterUtility.set_cluster_label_id(None, clusters, original_logs, prediction_file) -homogeneity_completeness_vmeasure = ClusterEvaluation.get_homogeneity_completeness_vmeasure(standard_file, +ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file) +homogeneity_completeness_vmeasure = ExternalEvaluation.get_homogeneity_completeness_vmeasure(standard_file, prediction_file) print homogeneity_completeness_vmeasure
8a1bb5a252fa50138316fcaae949de4554fe40e0
fmn/lib/pkgdb.py
fmn/lib/pkgdb.py
""" fedmsg-notifications pkgdb client """ import json import logging import requests log = logging.getLogger(__name__) PKGDB_API_URL = 'http://209.132.184.188/api/' def get_package_of_user(username, acl='commit', branch=None): """ Retrieve the list of packages where the specified user has the specified acl on the specified branch. :arg username: the fas username of the packager whose packages are of interest. :kwarg acl: the acl that the specified user has on the packages returned. Defaults to ``commit``. :kwarg branch: the branch on which the specified user has the specified acl. Defaults to ``None`` == all branches. :return: a set listing all the packages where the specified user has the specified ACL on the specified branch(es). """ req = requests.get( '{0}/packager/acl/{1}'.format(PKGDB_API_URL, username)) if not req.status_code == 200: return [] data = json.loads(req.text) packages = set() for pkgacl in data['acls']: if pkgacl['status'] != 'Approved': continue if pkgacl['acl'] != acl: continue if branch and pkgacl['packagelist']['collection']['branchname'] != branch: continue packages.add(pkgacl['packagelist']['package']['name']) return packages
""" fedmsg-notifications pkgdb client """ import json import logging import requests log = logging.getLogger(__name__) ## TODO: Move this variable into a configuration file PKGDB_API_URL = 'http://209.132.184.188/api/' ## TODO: cache the results of this method # This might mean removing the acl and branch argument # Can be done using dogpile.cache def get_package_of_user(username, acl='commit', branch=None): """ Retrieve the list of packages where the specified user has the specified acl on the specified branch. :arg username: the fas username of the packager whose packages are of interest. :kwarg acl: the acl that the specified user has on the packages returned. Defaults to ``commit``. :kwarg branch: the branch on which the specified user has the specified acl. Defaults to ``None`` == all branches. :return: a set listing all the packages where the specified user has the specified ACL on the specified branch(es). """ req = requests.get( '{0}/packager/acl/{1}'.format(PKGDB_API_URL, username)) if not req.status_code == 200: return [] data = json.loads(req.text) packages = set() for pkgacl in data['acls']: if pkgacl['status'] != 'Approved': continue if pkgacl['acl'] != acl: continue if branch and pkgacl['packagelist']['collection']['branchname'] != branch: continue packages.add(pkgacl['packagelist']['package']['name']) return packages
Add a couple of TODOs
Add a couple of TODOs
Python
lgpl-2.1
jeremycline/fmn,jeremycline/fmn,jeremycline/fmn
--- +++ @@ -5,8 +5,12 @@ import requests log = logging.getLogger(__name__) +## TODO: Move this variable into a configuration file PKGDB_API_URL = 'http://209.132.184.188/api/' +## TODO: cache the results of this method +# This might mean removing the acl and branch argument +# Can be done using dogpile.cache def get_package_of_user(username, acl='commit', branch=None): """ Retrieve the list of packages where the specified user has the specified acl on the specified branch.
6fc9032bc372aad7b9c1217b44ff081ac9108af2
manoseimas/common/tests/utils/test_words.py
manoseimas/common/tests/utils/test_words.py
# coding: utf-8 from __future__ import unicode_literals import unittest from manoseimas.scrapy import textutils class WordCountTest(unittest.TestCase): def test_get_word_count(self): word_count = textutils.get_word_count('Žodžiai, lietuviškai.') self.assertEqual(word_count, 2) def test_get_words(self): words = textutils.get_words('Žodžiai, lietuviškai.') self.assertEqual(words, ['Žodžiai', 'lietuviškai'])
# coding: utf-8 from __future__ import unicode_literals import unittest from manoseimas.common.utils import words class WordCountTest(unittest.TestCase): def test_get_word_count(self): word_count = words.get_word_count('Žodžiai, lietuviškai.') self.assertEqual(word_count, 2) def test_get_words(self): words_list = words.get_words('Žodžiai, lietuviškai.') self.assertEqual(words_list, ['Žodžiai', 'lietuviškai'])
Fix word_count test import paths.
Fix word_count test import paths.
Python
agpl-3.0
ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt
--- +++ @@ -4,14 +4,14 @@ import unittest -from manoseimas.scrapy import textutils +from manoseimas.common.utils import words class WordCountTest(unittest.TestCase): def test_get_word_count(self): - word_count = textutils.get_word_count('Žodžiai, lietuviškai.') + word_count = words.get_word_count('Žodžiai, lietuviškai.') self.assertEqual(word_count, 2) def test_get_words(self): - words = textutils.get_words('Žodžiai, lietuviškai.') - self.assertEqual(words, ['Žodžiai', 'lietuviškai']) + words_list = words.get_words('Žodžiai, lietuviškai.') + self.assertEqual(words_list, ['Žodžiai', 'lietuviškai'])
2df1c9f6b9833c1ae44a62d3dfbe208e2e42805a
Python/Product/PythonTools/ptvsd/setup.py
Python/Product/PythonTools/ptvsd/setup.py
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------- from distutils.core import setup setup(name='ptvsd', version='2.1.0b1', description='Python Tools for Visual Studio remote debugging server', license='Apache License 2.0', author='Microsoft Corporation', author_email='ptvshelp@microsoft.com', url='https://pytools.codeplex.com/', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: Apache Software License'], packages=['ptvsd'] )
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------- from distutils.core import setup setup(name='ptvsd', version='2.1.0b2', description='Python Tools for Visual Studio remote debugging server', license='Apache License 2.0', author='Microsoft Corporation', author_email='ptvshelp@microsoft.com', url='https://pytools.codeplex.com/', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: Apache Software License'], packages=['ptvsd'] )
Update ptvsd version number for 2.0 beta 2.
Update ptvsd version number for 2.0 beta 2.
Python
apache-2.0
fivejjs/PTVS,fivejjs/PTVS,xNUTs/PTVS,DEVSENSE/PTVS,Microsoft/PTVS,fivejjs/PTVS,DinoV/PTVS,gilbertw/PTVS,MetSystem/PTVS,crwilcox/PTVS,christer155/PTVS,bolabola/PTVS,DinoV/PTVS,int19h/PTVS,gomiero/PTVS,zooba/PTVS,Habatchii/PTVS,mlorbetske/PTVS,MetSystem/PTVS,xNUTs/PTVS,christer155/PTVS,fjxhkj/PTVS,Microsoft/PTVS,gomiero/PTVS,ChinaQuants/PTVS,msunardi/PTVS,Habatchii/PTVS,jkorell/PTVS,denfromufa/PTVS,huguesv/PTVS,Habatchii/PTVS,modulexcite/PTVS,jkorell/PTVS,christer155/PTVS,jkorell/PTVS,DinoV/PTVS,gomiero/PTVS,denfromufa/PTVS,modulexcite/PTVS,fivejjs/PTVS,dut3062796s/PTVS,DinoV/PTVS,huguesv/PTVS,christer155/PTVS,jkorell/PTVS,crwilcox/PTVS,Habatchii/PTVS,DEVSENSE/PTVS,juanyaw/PTVS,xNUTs/PTVS,dut3062796s/PTVS,MetSystem/PTVS,msunardi/PTVS,xNUTs/PTVS,huguesv/PTVS,zooba/PTVS,msunardi/PTVS,zooba/PTVS,huguesv/PTVS,int19h/PTVS,fjxhkj/PTVS,ChinaQuants/PTVS,modulexcite/PTVS,juanyaw/PTVS,denfromufa/PTVS,mlorbetske/PTVS,int19h/PTVS,alanch-ms/PTVS,gilbertw/PTVS,denfromufa/PTVS,dut3062796s/PTVS,gomiero/PTVS,crwilcox/PTVS,alanch-ms/PTVS,mlorbetske/PTVS,huguesv/PTVS,Habatchii/PTVS,alanch-ms/PTVS,int19h/PTVS,modulexcite/PTVS,gomiero/PTVS,crwilcox/PTVS,denfromufa/PTVS,crwilcox/PTVS,bolabola/PTVS,Microsoft/PTVS,int19h/PTVS,msunardi/PTVS,ChinaQuants/PTVS,alanch-ms/PTVS,fjxhkj/PTVS,alanch-ms/PTVS,DinoV/PTVS,Microsoft/PTVS,juanyaw/PTVS,Habatchii/PTVS,DEVSENSE/PTVS,Microsoft/PTVS,ChinaQuants/PTVS,denfromufa/PTVS,juanyaw/PTVS,jkorell/PTVS,msunardi/PTVS,DEVSENSE/PTVS,bolabola/PTVS,gilbertw/PTVS,alanch-ms/PTVS,huguesv/PTVS,xNUTs/PTVS,dut3062796s/PTVS,mlorbetske/PTVS,zooba/PTVS,zooba/PTVS,fjxhkj/PTVS,ChinaQuants/PTVS,msunardi/PTVS,jkorell/PTVS,mlorbetske/PTVS,MetSystem/PTVS,MetSystem/PTVS,gomiero/PTVS,modulexcite/PTVS,zooba/PTVS,gilbertw/PTVS,christer155/PTVS,MetSystem/PTVS,dut3062796s/PTVS,DinoV/PTVS,juanyaw/PTVS,bolabola/PTVS,christer155/PTVS,fjxhkj/PTVS,gilbertw/PTVS,modulexcite/PTVS,Microsoft/PTVS,xNUTs/PTVS,bolabola/PTVS,fivejjs/PTVS,gilbertw/PTVS,int19h/PTVS,mlorbetske/PTVS,fivejjs/PTVS,juanyaw/PTVS,ChinaQuants/PTVS,dut3062796s/PTVS,crwilcox/PTVS,DEVSENSE/PTVS,DEVSENSE/PTVS,bolabola/PTVS,fjxhkj/PTVS
--- +++ @@ -18,7 +18,7 @@ from distutils.core import setup setup(name='ptvsd', - version='2.1.0b1', + version='2.1.0b2', description='Python Tools for Visual Studio remote debugging server', license='Apache License 2.0', author='Microsoft Corporation',
2e0c4940b208d0b029e7b43f8c3595fa3b6d2f18
examples/list-pods-watch.py
examples/list-pods-watch.py
import asyncio import powershift.endpoints as endpoints import powershift.resources as resources client = endpoints.AsyncClient() async def run_query(): projects = await client.oapi.v1.projects.get() #print(projects) #print(resources.dumps(projects, indent=4, sort_keys=True)) #print() project = projects.items[0] namespace = project.metadata.name print('namespace=%r' % namespace) async with client.api.v1.namespaces(namespace=namespace).pods.get(watch='') as items: async for item in items: action = item['type'] pod = item['object'] print(' %s pod=%r' % (action, pod.metadata.name)) loop = asyncio.get_event_loop() loop.run_until_complete(run_query())
import sys import asyncio import powershift.endpoints as endpoints async def run_query(): namespace = sys.argv[1] print('namespace=%r' % namespace) client = endpoints.AsyncClient() pods = await client.api.v1.namespaces(namespace=namespace).pods.get() for pod in pods.items: print(' OBJECT %s pod=%r' % (pod.metadata.resource_version, pod.metadata.name)) resource_version = pods.metadata.resource_version while True: try: async with client.api.v1.namespaces(namespace=namespace).pods.get(watch='', resource_version=resource_version, timeout_seconds=10) as items: async for item in items: action = item['type'] pod = item['object'] print(' %s %s pod=%r' % (action, pod.metadata.resource_version, pod.metadata.name)) resource_version = pod.metadata.resource_version except Exception: pass loop = asyncio.get_event_loop() loop.run_until_complete(run_query())
Make watch example for pods more durable.
Make watch example for pods more durable.
Python
bsd-2-clause
getwarped/powershift
--- +++ @@ -1,28 +1,34 @@ +import sys import asyncio import powershift.endpoints as endpoints -import powershift.resources as resources - -client = endpoints.AsyncClient() async def run_query(): - projects = await client.oapi.v1.projects.get() - - #print(projects) - #print(resources.dumps(projects, indent=4, sort_keys=True)) - #print() - - project = projects.items[0] - namespace = project.metadata.name + namespace = sys.argv[1] print('namespace=%r' % namespace) - async with client.api.v1.namespaces(namespace=namespace).pods.get(watch='') as items: - async for item in items: - action = item['type'] - pod = item['object'] - print(' %s pod=%r' % (action, pod.metadata.name)) + client = endpoints.AsyncClient() + + pods = await client.api.v1.namespaces(namespace=namespace).pods.get() + + for pod in pods.items: + print(' OBJECT %s pod=%r' % (pod.metadata.resource_version, pod.metadata.name)) + + resource_version = pods.metadata.resource_version + + while True: + try: + async with client.api.v1.namespaces(namespace=namespace).pods.get(watch='', resource_version=resource_version, timeout_seconds=10) as items: + async for item in items: + action = item['type'] + pod = item['object'] + + print(' %s %s pod=%r' % (action, pod.metadata.resource_version, pod.metadata.name)) + + resource_version = pod.metadata.resource_version + except Exception: + pass loop = asyncio.get_event_loop() - loop.run_until_complete(run_query())
7a81312d1e7b4b0de0343a907e91dd120625f807
lily/users/authentication/social_auth/providers/google.py
lily/users/authentication/social_auth/providers/google.py
from django.conf import settings from ..exceptions import InvalidProfileError from .base import BaseAuthProvider class GoogleAuthProvider(BaseAuthProvider): client_id = settings.SOCIAL_AUTH_GOOGLE_CLIENT_ID client_secret = settings.SOCIAL_AUTH_GOOGLE_SECRET scope = ['openid', 'email', 'profile'] auth_uri = 'https://accounts.google.com/o/oauth2/v2/auth' token_uri = 'https://www.googleapis.com/oauth2/v4/token' jwks_uri = 'https://www.googleapis.com/oauth2/v3/certs' def parse_profile(self, session, token): id_token = token['id_token'] email = id_token.get('email', '') if not email or not id_token.get('email_verified', False): raise InvalidProfileError() picture = self.get_picture(session=session, url=id_token.get('picture', '')) language = self.get_language(id_token.get('locale', '')) return { 'email': email, 'picture': picture, 'first_name': id_token.get('given_name', ''), 'last_name': id_token.get('family_name', ''), 'language': language, }
from django.conf import settings from ..exceptions import InvalidProfileError from .base import BaseAuthProvider class GoogleAuthProvider(BaseAuthProvider): client_id = settings.SOCIAL_AUTH_GOOGLE_CLIENT_ID client_secret = settings.SOCIAL_AUTH_GOOGLE_SECRET scope = [ 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ] auth_uri = 'https://accounts.google.com/o/oauth2/v2/auth' token_uri = 'https://www.googleapis.com/oauth2/v4/token' jwks_uri = 'https://www.googleapis.com/oauth2/v3/certs' def parse_profile(self, session, token): id_token = token['id_token'] email = id_token.get('email', '') if not email or not id_token.get('email_verified', False): raise InvalidProfileError() picture = self.get_picture(session=session, url=id_token.get('picture', '')) language = self.get_language(id_token.get('locale', '')) return { 'email': email, 'picture': picture, 'first_name': id_token.get('given_name', ''), 'last_name': id_token.get('family_name', ''), 'language': language, }
Update scopes for Google Auth2
Update scopes for Google Auth2
Python
agpl-3.0
HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily
--- +++ @@ -7,7 +7,11 @@ class GoogleAuthProvider(BaseAuthProvider): client_id = settings.SOCIAL_AUTH_GOOGLE_CLIENT_ID client_secret = settings.SOCIAL_AUTH_GOOGLE_SECRET - scope = ['openid', 'email', 'profile'] + scope = [ + 'https://www.googleapis.com/auth/plus.me', + 'https://www.googleapis.com/auth/userinfo.email', + 'https://www.googleapis.com/auth/userinfo.profile' + ] auth_uri = 'https://accounts.google.com/o/oauth2/v2/auth' token_uri = 'https://www.googleapis.com/oauth2/v4/token' jwks_uri = 'https://www.googleapis.com/oauth2/v3/certs'
2ef20e1658eaf5631395940bbb8583be628e6483
utils/package_version.py
utils/package_version.py
#!/usr/bin/env python import sys import subprocess mep_version = "MEP_VERSION" os_family = "OS_FAMILY" output = subprocess.check_output( [ "curl", "-s", "http://package.mapr.com/releases/MEP/MEP-%s/%s/" % (mep_version, os_family) ] ) for line in output.splitlines(): index1 = line.find('"mapr') if index1 < 0: continue index2 = line.find('rpm"') if index2 < 0: continue package_version = line[index1+1:index2+3] pvitems = package_version.split('-') package = '-'.join( pvitems[0:-2] ) version = pvitems[-2] vitems = [] for item in version.split("."): if len(item) <= 2: vitems.append(item) else: break version = ".".join(vitems) print "%s=%s" % (package+":version", version)
#!/usr/bin/env python import sys import subprocess mep_version = "MEP_VERSION" os_family = "OS_FAMILY" output = subprocess.check_output( [ "curl", "-s", "http://package.mapr.com/releases/MEP/MEP-%s/%s/" % (mep_version, os_family) ] ) for line in output.splitlines(): index1 = line.find('"mapr') if index1 < 0: continue index2 = line.find('rpm"') if index2 < 0: continue package_version = line[index1+1:index2+3] pvitems = package_version.split('-') package = '-'.join( pvitems[0:-2] ) version = pvitems[-2] vitems = [] for item in version.split("."): if len(item) <= 2: vitems.append(item) else: # ignore build number which like: 201901301208 break # Starting with MEP-6.1.0, versions can contains 4 numbers like '2.3.2.0' in # mapr-spark-2.3.2.0.201901301208-1.noarch # but the version directory contains still 3 numbers. Let us take only the # first 3 numbers. version = ".".join(vitems[0:3]) print "%s=%s" % (package+":version", version)
Support MEP-6.1.0 which has version containing 4 numbers like mapr-spark-2.3.2.0 while the version directory contains still 3 numbers
Support MEP-6.1.0 which has version containing 4 numbers like mapr-spark-2.3.2.0 while the version directory contains still 3 numbers
Python
apache-2.0
qinjunjerry/MapRSetup,qinjunjerry/MapRSetup,qinjunjerry/MapRSetup
--- +++ @@ -29,7 +29,12 @@ if len(item) <= 2: vitems.append(item) else: + # ignore build number which like: 201901301208 break - version = ".".join(vitems) + # Starting with MEP-6.1.0, versions can contains 4 numbers like '2.3.2.0' in + # mapr-spark-2.3.2.0.201901301208-1.noarch + # but the version directory contains still 3 numbers. Let us take only the + # first 3 numbers. + version = ".".join(vitems[0:3]) print "%s=%s" % (package+":version", version)
1303890759afb3ae0466066dcdc9309b50dd73ef
CodeFights/weakNumbers.py
CodeFights/weakNumbers.py
#!/usr/local/bin/python # Code Fights Weak Numbers Problem def weakNumbers(n): def get_divisors(n): divs = [] for i in range(1, n + 1): count = 0 for d in range(1, i + 1): if i % d == 0: count += 1 divs.append(count) return divs divs = get_divisors(n) w = [] def main(): tests = [ [9, [2, 2]], [1, [0, 1]], [2, [0, 2]], [7, [2, 1]], [500, [403, 1]], [4, [0, 4]] ] for t in tests: res = weakNumbers(t[0]) ans = t[1] if ans == res: print("PASSED: weakNumbers({}) returned {}" .format(t[0], res)) else: print("FAILED: weakNumbers({}) returned {}, answer: {}" .format(t[0], res, ans)) if __name__ == '__main__': main()
#!/usr/local/bin/python # Code Fights Weak Numbers Problem def weakNumbers(n): def get_divisors(n): divs = [] for i in range(1, n + 1): count = 0 for d in range(1, i + 1): if i % d == 0: count += 1 divs.append(count) return divs divs = get_divisors(n) weaks = [sum([1 for item in divs[:i + 1] if item > div]) for i, div in enumerate(divs)] return [max(weaks), weaks.count(max(weaks))] def main(): tests = [ [9, [2, 2]], [1, [0, 1]], [2, [0, 2]], [7, [2, 1]], [500, [403, 1]], [4, [0, 4]] ] for t in tests: res = weakNumbers(t[0]) ans = t[1] if ans == res: print("PASSED: weakNumbers({}) returned {}" .format(t[0], res)) else: print("FAILED: weakNumbers({}) returned {}, answer: {}" .format(t[0], res, ans)) if __name__ == '__main__': main()
Solve Code Fights weak numbers problem
Solve Code Fights weak numbers problem
Python
mit
HKuz/Test_Code
--- +++ @@ -14,7 +14,9 @@ return divs divs = get_divisors(n) - w = [] + weaks = [sum([1 for item in divs[:i + 1] if item > div]) for i, div + in enumerate(divs)] + return [max(weaks), weaks.count(max(weaks))] def main():
818a1b6537c6daedaa4f8320aeb8ff4b25f365d9
inboxen/tests/settings.py
inboxen/tests/settings.py
from __future__ import absolute_import import os os.environ['INBOX_TESTING'] = '1' os.environ["INBOXEN_ADMIN_ACCESS"] = '1' from inboxen.settings import * CACHES = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache" } } db = os.environ.get('DB') postgres_user = os.environ.get('PG_USER', 'postgres') SECRET_KEY = "This is a test, you don't need secrets" ENABLE_REGISTRATION = True SECURE_SSL_REDIRECT = False if db == "sqlite": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } elif db == "postgres": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'inboxen', 'USER': postgres_user, }, } else: raise NotImplementedError("Please check tests/settings.py for valid DB values")
from __future__ import absolute_import import os os.environ['INBOX_TESTING'] = '1' os.environ["INBOXEN_ADMIN_ACCESS"] = '1' from inboxen.settings import * CACHES = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache" } } db = os.environ.get('DB', "sqlite") postgres_user = os.environ.get('PG_USER', 'postgres') SECRET_KEY = "This is a test, you don't need secrets" ENABLE_REGISTRATION = True SECURE_SSL_REDIRECT = False if db == "sqlite": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } elif db == "postgres": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'inboxen', 'USER': postgres_user, }, } else: raise NotImplementedError("Please check tests/settings.py for valid DB values")
Make tests run with sqlite by default
Make tests run with sqlite by default
Python
agpl-3.0
Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen
--- +++ @@ -11,7 +11,7 @@ } } -db = os.environ.get('DB') +db = os.environ.get('DB', "sqlite") postgres_user = os.environ.get('PG_USER', 'postgres') SECRET_KEY = "This is a test, you don't need secrets"
c045dc59bc313055eb74513e2961ce2cbae87450
corehq/apps/api/util.py
corehq/apps/api/util.py
from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext as _ from couchdbkit.exceptions import ResourceNotFound def get_object_or_not_exist(cls, doc_id, domain, additional_doc_types=None): """ Given a Document class, id, and domain, get that object or raise an ObjectDoesNotExist exception if it's not found, not the right type, or doesn't belong to the domain. """ additional_doc_types = additional_doc_types or [] doc_type = getattr(cls, '_doc_type', cls.__name__) additional_doc_types.append(doc_type) try: doc = cls.get(doc_id) if doc and doc.domain == domain and doc.doc_type in additional_doc_types: return doc except ResourceNotFound: pass # covered by the below except AttributeError: # there's a weird edge case if you reference a form with a case id # that explodes on the "version" property. might as well swallow that # too. pass raise object_does_not_exist(doc_type, doc_id) def object_does_not_exist(doc_type, doc_id): """ Builds a 404 error message with standard, translated, verbiage """ return ObjectDoesNotExist(_("Could not find %(doc_type)s with id %(id)s") % \ {"doc_type": doc_type, "id": doc_id})
from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext as _ from couchdbkit.exceptions import ResourceNotFound def get_object_or_not_exist(cls, doc_id, domain, additional_doc_types=None): """ Given a Document class, id, and domain, get that object or raise an ObjectDoesNotExist exception if it's not found, not the right type, or doesn't belong to the domain. """ additional_doc_types = additional_doc_types or [] doc_type = getattr(cls, '_doc_type', cls.__name__) additional_doc_types.append(doc_type) try: doc_json = cls.get_db().get(doc_id) if doc_json['doc_type'] not in additional_doc_types: raise ResourceNotFound doc = cls.wrap(doc_json) if doc and doc.domain == domain: return doc except ResourceNotFound: pass # covered by the below except AttributeError: # there's a weird edge case if you reference a form with a case id # that explodes on the "version" property. might as well swallow that # too. pass raise object_does_not_exist(doc_type, doc_id) def object_does_not_exist(doc_type, doc_id): """ Builds a 404 error message with standard, translated, verbiage """ return ObjectDoesNotExist(_("Could not find %(doc_type)s with id %(id)s") % \ {"doc_type": doc_type, "id": doc_id})
Check doc type before wrapping
Check doc type before wrapping
Python
bsd-3-clause
dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq
--- +++ @@ -12,8 +12,11 @@ doc_type = getattr(cls, '_doc_type', cls.__name__) additional_doc_types.append(doc_type) try: - doc = cls.get(doc_id) - if doc and doc.domain == domain and doc.doc_type in additional_doc_types: + doc_json = cls.get_db().get(doc_id) + if doc_json['doc_type'] not in additional_doc_types: + raise ResourceNotFound + doc = cls.wrap(doc_json) + if doc and doc.domain == domain: return doc except ResourceNotFound: pass # covered by the below
da65e041a7d05eee1cdda7c6f5a23ae2fea70103
rules/arm-toolchain.py
rules/arm-toolchain.py
import xyz class ArmToolchain(xyz.BuildProtocol): group_only = True pkg_name = 'arm-toolchain' deps = [('gcc', {'target': 'arm-none-eabi'}), ('binutils', {'target': 'arm-none-eabi'}), ('gdb', {'target': 'arm-none-eabi'}) ] rules = ArmToolchain
import xyz class ArmToolchain(xyz.BuildProtocol): group_only = True pkg_name = 'arm-toolchain' deps = [('gcc', {'target': 'arm-none-eabi'}), ('binutils', {'target': 'arm-none-eabi'}), ('gdb', {'target': 'arm-none-eabi'}), ('stlink', {}) ] rules = ArmToolchain
Add stlink package to arm toolchain
Add stlink package to arm toolchain
Python
mit
BreakawayConsulting/xyz
--- +++ @@ -5,7 +5,8 @@ pkg_name = 'arm-toolchain' deps = [('gcc', {'target': 'arm-none-eabi'}), ('binutils', {'target': 'arm-none-eabi'}), - ('gdb', {'target': 'arm-none-eabi'}) + ('gdb', {'target': 'arm-none-eabi'}), + ('stlink', {}) ] rules = ArmToolchain
a225eb1925c54c2c0fef857b1bf78fbc93375f1f
airflow_pipeline/pipelines.py
airflow_pipeline/pipelines.py
from functools import partial def pipeline_trigger(parent_task): """ Use this function with TriggerDagOperator to always trigger a DAG and pass pipeline information to the next DAG """ def trigger(parent_task, context, dag_run_obj): """ Use this function with TriggerDagOperator to always trigger a DAG and pass pipeline information to the next DAG """ ti = context['task_instance'] dr = context['dag_run'] dag_run_obj.payload = {} for key in ['folder', 'session_id', 'participant_id', 'scan_date', 'spm_output', 'spm_error']: dag_run_obj.payload[key] = ti.xcom_pull(task_ids=parent_task, key=key) | dr.conf[key] | None return dag_run_obj return partial(trigger, parent_task=parent_task)
from functools import partial def pipeline_trigger(parent_task): """ Use this function with TriggerDagRunOperator to always trigger a DAG and pass pipeline information to the next DAG """ def trigger(parent_task, context, dag_run_obj): """ Use this function with TriggerDagRunOperator to always trigger a DAG and pass pipeline information to the next DAG """ ti = context['task_instance'] dr = context['dag_run'] dag_run_obj.payload = {} for key in ['folder', 'session_id', 'participant_id', 'scan_date', 'spm_output', 'spm_error']: dag_run_obj.payload[key] = ti.xcom_pull(task_ids=parent_task, key=key) | dr.conf[key] | None return dag_run_obj return partial(trigger, parent_task=parent_task)
Fix name of operator in docs
Fix name of operator in docs
Python
apache-2.0
LREN-CHUV/airflow-imaging-plugins,LREN-CHUV/airflow-imaging-plugins
--- +++ @@ -3,13 +3,13 @@ def pipeline_trigger(parent_task): """ - Use this function with TriggerDagOperator to always trigger a DAG and + Use this function with TriggerDagRunOperator to always trigger a DAG and pass pipeline information to the next DAG """ def trigger(parent_task, context, dag_run_obj): """ - Use this function with TriggerDagOperator to always trigger a DAG and + Use this function with TriggerDagRunOperator to always trigger a DAG and pass pipeline information to the next DAG """ ti = context['task_instance']
bb1ab6d72850fdb9ecc9119afa53045a3564a7e2
test/unit/test_flask_multi_redis.py
test/unit/test_flask_multi_redis.py
#! /usr/bin/env python # -*- coding: utf-8 -*- import sys sys.modules['redis'] = None def test_redis_import_error(): """Test that we can load FlaskMultiRedis even if redis module is not available.""" from flask_multi_redis import FlaskMultiRedis f = FlaskMultiRedis() assert f.provider_class is None def test_constructor_app(mocker): """Test that the constructor passes the app to FlaskMultiRedis.init_app.""" from flask_multi_redis import FlaskMultiRedis mocker.patch.object(FlaskMultiRedis, 'init_app', autospec=True) app_stub = mocker.stub(name='app_stub') FlaskMultiRedis(app_stub) FlaskMultiRedis.init_app.assert_called_once_with(mocker.ANY, app_stub)
#! /usr/bin/env python # -*- coding: utf-8 -*- from sys import modules, version_info if version_info >= (3,): from imp import reload def test_redis_import_error(): """Test that we can load FlaskMultiRedis even if redis module is not available.""" import flask_multi_redis modules['redis'] = None flask_multi_redis = reload(flask_multi_redis) FlaskMultiRedis = flask_multi_redis.FlaskMultiRedis f = FlaskMultiRedis() assert f.provider_class is None def test_constructor_app(mocker): """Test that the constructor passes the app to FlaskMultiRedis.init_app.""" import flask_multi_redis del(modules['redis']) flask_multi_redis = reload(flask_multi_redis) FlaskMultiRedis = flask_multi_redis.FlaskMultiRedis mocker.patch.object(FlaskMultiRedis, 'init_app', autospec=True) app_stub = mocker.stub(name='app_stub') FlaskMultiRedis(app_stub) FlaskMultiRedis.init_app.assert_called_once_with(mocker.ANY, app_stub)
Update unit tests to improve redis_import_error
Update unit tests to improve redis_import_error
Python
agpl-3.0
max-k/flask-multi-redis
--- +++ @@ -1,16 +1,21 @@ #! /usr/bin/env python # -*- coding: utf-8 -*- -import sys +from sys import modules, version_info -sys.modules['redis'] = None +if version_info >= (3,): + from imp import reload def test_redis_import_error(): """Test that we can load FlaskMultiRedis even if redis module is not available.""" - from flask_multi_redis import FlaskMultiRedis + import flask_multi_redis + modules['redis'] = None + flask_multi_redis = reload(flask_multi_redis) + FlaskMultiRedis = flask_multi_redis.FlaskMultiRedis + f = FlaskMultiRedis() assert f.provider_class is None @@ -18,7 +23,11 @@ def test_constructor_app(mocker): """Test that the constructor passes the app to FlaskMultiRedis.init_app.""" - from flask_multi_redis import FlaskMultiRedis + import flask_multi_redis + del(modules['redis']) + flask_multi_redis = reload(flask_multi_redis) + FlaskMultiRedis = flask_multi_redis.FlaskMultiRedis + mocker.patch.object(FlaskMultiRedis, 'init_app', autospec=True) app_stub = mocker.stub(name='app_stub')
804696126480f36fddd74a8a0d24b0c4274f0f54
ants/utils/convert_nibabel.py
ants/utils/convert_nibabel.py
__all__ = ["to_nibabel", "from_nibabel"] import os from tempfile import mktemp import numpy as np from ..core import ants_image_io as iio2 def to_nibabel(image): """ Convert an ANTsImage to a Nibabel image """ import nibabel as nib tmpfile = mktemp(suffix=".nii.gz") image.to_filename(tmpfile) new_img = nib.load(tmpfile) # os.remove(tmpfile) ## Don't remove tmpfile as nibabel lazy loads the data. return new_img def from_nibabel(nib_image): """ Convert a nibabel image to an ANTsImage """ tmpfile = mktemp(suffix=".nii.gz") nib_image.to_filename(tmpfile) new_img = iio2.image_read(tmpfile) os.remove(tmpfile) return new_img
__all__ = ["to_nibabel", "from_nibabel"] import os from tempfile import mkstemp import numpy as np from ..core import ants_image_io as iio2 def to_nibabel(image): """ Convert an ANTsImage to a Nibabel image """ import nibabel as nib fd, tmpfile = mkstemp(suffix=".nii.gz") image.to_filename(tmpfile) new_img = nib.load(tmpfile) os.close(fd) # os.remove(tmpfile) ## Don't remove tmpfile as nibabel lazy loads the data. return new_img def from_nibabel(nib_image): """ Convert a nibabel image to an ANTsImage """ fd, tmpfile = mkstemp(suffix=".nii.gz") nib_image.to_filename(tmpfile) new_img = iio2.image_read(tmpfile) os.close(fd) os.remove(tmpfile) return new_img
Use safe mkstemp instead of unsafe mktemp in format conversion
Use safe mkstemp instead of unsafe mktemp in format conversion
Python
apache-2.0
ANTsX/ANTsPy,ANTsX/ANTsPy,ANTsX/ANTsPy,ANTsX/ANTsPy
--- +++ @@ -1,7 +1,7 @@ __all__ = ["to_nibabel", "from_nibabel"] import os -from tempfile import mktemp +from tempfile import mkstemp import numpy as np from ..core import ants_image_io as iio2 @@ -11,9 +11,10 @@ Convert an ANTsImage to a Nibabel image """ import nibabel as nib - tmpfile = mktemp(suffix=".nii.gz") + fd, tmpfile = mkstemp(suffix=".nii.gz") image.to_filename(tmpfile) new_img = nib.load(tmpfile) + os.close(fd) # os.remove(tmpfile) ## Don't remove tmpfile as nibabel lazy loads the data. return new_img @@ -22,8 +23,9 @@ """ Convert a nibabel image to an ANTsImage """ - tmpfile = mktemp(suffix=".nii.gz") + fd, tmpfile = mkstemp(suffix=".nii.gz") nib_image.to_filename(tmpfile) new_img = iio2.image_read(tmpfile) + os.close(fd) os.remove(tmpfile) return new_img
c25d55643953d5bce511b1d3d32e6fce162b4ccd
hoptoad/tests.py
hoptoad/tests.py
from django.test import TestCase from django.conf import settings class BasicTests(TestCase): """Basic tests like setup and connectivity.""" def test_api_key_present(self): self.assertTrue('HOPTOAD_API_KEY' in settings.get_all_members(), msg='The HOPTOAD_API_KEY setting is not present.') self.assertTrue(settings.HOPTOAD_API_KEY, msg='The HOPTOAD_API_KEY setting is blank.')
import urllib2 from django.test import TestCase from django.conf import settings class BasicTests(TestCase): """Basic tests like setup and connectivity.""" def test_api_key_present(self): self.assertTrue('HOPTOAD_API_KEY' in settings.get_all_members(), msg='The HOPTOAD_API_KEY setting is not present.') self.assertTrue(settings.HOPTOAD_API_KEY, msg='The HOPTOAD_API_KEY setting is blank.') def test_hoptoad_connectivity(self): try: ht = urllib2.urlopen('http://hoptoadapp.com/') except urllib2.HTTPError: self.fail(msg='Could not reach hoptoadapp.com -- are you online?') self.assertEqual(ht.code, 200, msg='hoptoadapp.com is broken.')
Add a unit test for hoptoadapp.com connectivity.
Add a unit test for hoptoadapp.com connectivity.
Python
mit
sjl/django-hoptoad,sjl/django-hoptoad
--- +++ @@ -1,3 +1,4 @@ +import urllib2 from django.test import TestCase from django.conf import settings @@ -10,4 +11,10 @@ self.assertTrue(settings.HOPTOAD_API_KEY, msg='The HOPTOAD_API_KEY setting is blank.') - + def test_hoptoad_connectivity(self): + try: + ht = urllib2.urlopen('http://hoptoadapp.com/') + except urllib2.HTTPError: + self.fail(msg='Could not reach hoptoadapp.com -- are you online?') + self.assertEqual(ht.code, 200, msg='hoptoadapp.com is broken.') +
0f5aeeedd580cce2970127d4b7e69c4a6427d343
wsme/tests/test_spore.py
wsme/tests/test_spore.py
import unittest try: import simplejson as json except ImportError: import json from wsme.tests.protocol import WSTestRoot import wsme.spore class TestSpore(unittest.TestCase): def test_spore(self): spore = wsme.spore.getdesc(WSTestRoot()) print spore spore = json.loads(spore) assert len(spore['methods']) == 36, len(spore['methods']) m = spore['methods']['argtypes_setbytesarray'] assert m['path'] == '/argtypes/setbytesarray' assert m['optional_params'] == ['value'] assert m['method'] == 'POST' m = spore['methods']['argtypes_setdecimal'] assert m['path'] == '/argtypes/setdecimal' assert m['required_params'] == ['value'] assert m['method'] == 'GET'
import unittest try: import simplejson as json except ImportError: import json from wsme.tests.protocol import WSTestRoot import wsme.tests.test_restjson import wsme.spore class TestSpore(unittest.TestCase): def test_spore(self): spore = wsme.spore.getdesc(WSTestRoot()) print spore spore = json.loads(spore) assert len(spore['methods']) == 40, str(len(spore['methods'])) m = spore['methods']['argtypes_setbytesarray'] assert m['path'] == '/argtypes/setbytesarray' assert m['optional_params'] == ['value'] assert m['method'] == 'POST' m = spore['methods']['argtypes_setdecimal'] assert m['path'] == '/argtypes/setdecimal' assert m['required_params'] == ['value'] assert m['method'] == 'GET'
Fix the spore test, as some functions were added by restjson
Fix the spore test, as some functions were added by restjson
Python
mit
stackforge/wsme
--- +++ @@ -6,6 +6,7 @@ import json from wsme.tests.protocol import WSTestRoot +import wsme.tests.test_restjson import wsme.spore @@ -17,7 +18,7 @@ spore = json.loads(spore) - assert len(spore['methods']) == 36, len(spore['methods']) + assert len(spore['methods']) == 40, str(len(spore['methods'])) m = spore['methods']['argtypes_setbytesarray'] assert m['path'] == '/argtypes/setbytesarray'
d54f7a769ccb60bd5feaab46a68d636dab38b02b
main.py
main.py
import asyncio import json from discord.ext.commands import when_mentioned_or from bot import BeattieBot try: import uvloop except ImportError: pass else: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) with open('config.json') as file: config = json.load(file) token = config['token'] bot = BeattieBot(when_mentioned_or('>')) for extension in ('default', 'rpg', 'eddb', 'repl'): try: bot.load_extension(extension) except Exception as e: print(f'Failed to load extension {extension}\n{type(e).__name__}: {e}') bot.run(token)
import asyncio import json import logging import discord from discord.ext.commands import when_mentioned_or from bot import BeattieBot try: import uvloop except ImportError: pass else: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) with open('config.json') as file: config = json.load(file) token = config['token'] bot = BeattieBot(when_mentioned_or('>')) for extension in ('default', 'rpg', 'eddb', 'repl'): try: bot.load_extension(extension) except Exception as e: print(f'Failed to load extension {extension}\n{type(e).__name__}: {e}') logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) bot.run(token)
Set up logging as per documentation example.
Set up logging as per documentation example.
Python
mit
BeatButton/beattie-bot,BeatButton/beattie
--- +++ @@ -1,6 +1,8 @@ import asyncio import json +import logging +import discord from discord.ext.commands import when_mentioned_or from bot import BeattieBot @@ -25,4 +27,10 @@ except Exception as e: print(f'Failed to load extension {extension}\n{type(e).__name__}: {e}') +logger = logging.getLogger('discord') +logger.setLevel(logging.DEBUG) +handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') +handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) +logger.addHandler(handler) + bot.run(token)
25cf03a2ecfb80e0866680a7781adfe11c54ebe9
ircstat/plugins/totals.py
ircstat/plugins/totals.py
# Copyright 2013 John Reese # Licensed under the MIT license from ..lib import is_bot from ..ent import Message from ..graphs import NetworkKeyComparison, NetworkUserComparison from .base import Plugin class Totals(Plugin): """Gathers total message type statistics, broken down by channel, day and user.""" def process_message(self, message): nick = message.nick mtype = Message.type_to_name(message.type) kwargs = { mtype: 1, } self.inc_shared_stats(nick, **kwargs) def generate_graphs(self): return [ NetworkKeyComparison(title='Logged Events', network=self.network, bars=True, keys={k: k for k in Message.type_names.values()}, ), NetworkUserComparison(title='Channel Joins', network=self.network, bars=True, key=Message.type_to_name(Message.JOIN), log=True, ), ] class Wordcount(Plugin): """Tracks the average word count of messages.""" def process_message(self, message): if is_bot(message) or not message.content: return nick = message.nick word_count = len(message.content.split()) self.inc_shared_stats(nick, word_count_total=word_count, word_count_messages=1, )
# Copyright 2013 John Reese # Licensed under the MIT license from ..lib import is_bot from ..ent import Message from ..graphs import NetworkKeyComparison, NetworkUserComparison from .base import Plugin class Totals(Plugin): """Gathers total message type statistics, broken down by channel, day and user.""" def process_message(self, message): nick = message.nick mtype = Message.type_to_name(message.type) kwargs = { mtype: 1, } self.inc_shared_stats(nick, **kwargs) def generate_graphs(self): return [ NetworkKeyComparison(title='Logged Events', network=self.network, bars=True, keys={k: k for k in Message.type_names.values()}, ), NetworkUserComparison(title='Channel Joins', network=self.network, key=Message.type_to_name(Message.JOIN), ), NetworkUserComparison(title='Messages Sent', network=self.network, bars=True, key=Message.type_to_name(Message.MESSAGE) ), ] class Wordcount(Plugin): """Tracks the average word count of messages.""" def process_message(self, message): if is_bot(message) or not message.content: return nick = message.nick word_count = len(message.content.split()) self.inc_shared_stats(nick, word_count_total=word_count, word_count_messages=1, )
Add third graph for Totals plugin
Add third graph for Totals plugin
Python
mit
jreese/ircstat,jreese/ircstat
--- +++ @@ -30,9 +30,12 @@ ), NetworkUserComparison(title='Channel Joins', network=self.network, + key=Message.type_to_name(Message.JOIN), + ), + NetworkUserComparison(title='Messages Sent', + network=self.network, bars=True, - key=Message.type_to_name(Message.JOIN), - log=True, + key=Message.type_to_name(Message.MESSAGE) ), ]
3dbdc8581bcb366e5b6749d523f25589d3ede9ed
test/test_cart.py
test/test_cart.py
import cart def test_valid_cart_from_csv(): _cart = cart.cart_from_csv('test/cart_files/default_cart.csv') assert _cart._product_prices == {'apple': 0.15, 'ice cream': 3.49, 'strawberries': 2.00, 'snickers bar': 0.70}
# -*- coding: utf-8 -*- import cart from cart._compatibility import utf8 def test_valid_cart_from_csv(): _cart = cart.cart_from_csv('test/cart_files/default_cart.csv') assert _cart._product_prices == {'apple': 0.15, 'ice cream': 3.49, 'strawberries': 2.00, 'snickers bar': 0.70} def test_unicode_cart_from_csv(): _cart = cart.cart_from_csv('test/cart_files/unicode_cart.csv') assert _cart._product_prices == {utf8('somethingä'): 1.0}
Add tests for unicode csv files.
Add tests for unicode csv files.
Python
mit
davidhalter-archive/shopping_cart_example
--- +++ @@ -1,4 +1,8 @@ +# -*- coding: utf-8 -*- + import cart +from cart._compatibility import utf8 + def test_valid_cart_from_csv(): _cart = cart.cart_from_csv('test/cart_files/default_cart.csv') @@ -6,3 +10,8 @@ 'ice cream': 3.49, 'strawberries': 2.00, 'snickers bar': 0.70} + + +def test_unicode_cart_from_csv(): + _cart = cart.cart_from_csv('test/cart_files/unicode_cart.csv') + assert _cart._product_prices == {utf8('somethingä'): 1.0}
423c29e859440b4a774a924badb7da4417dbd5c6
tests/test_provider_lawrenceks.py
tests/test_provider_lawrenceks.py
import busbus from busbus.provider.lawrenceks import LawrenceTransitProvider import arrow import pytest @pytest.fixture(scope='module') def lawrenceks_provider(engine): return LawrenceTransitProvider(engine) def test_agency_phone_e164(lawrenceks_provider): agency = next(lawrenceks_provider.agencies) assert agency.phone_e164 == '+17858644644' def test_43_to_eaton_hall(lawrenceks_provider): stop = lawrenceks_provider.get(busbus.Stop, u'15TH_SPAHR_WB') route = lawrenceks_provider.get(busbus.Route, u'RT_43') assert len(list(lawrenceks_provider.arrivals.where( stop=stop, route=route, start_time=arrow.get('2015-03-10T14:00:00-05:00'), end_time=arrow.get('2015-03-10T16:00:00-05:00')))) == 13
import busbus from busbus.provider.lawrenceks import LawrenceTransitProvider import arrow import pytest @pytest.fixture(scope='module') def lawrenceks_provider(engine): return LawrenceTransitProvider(engine) def test_agency_phone_e164(lawrenceks_provider): agency = next(lawrenceks_provider.agencies) assert agency.phone_e164 == '+17858644644' @pytest.mark.parametrize('stop_id,count', [ (u'15TH_SPAHR_WB', 13), (u'SNOW_HALL_WB', 14), ]) def test_43_to_eaton_hall(lawrenceks_provider, stop_id, count): stop = lawrenceks_provider.get(busbus.Stop, stop_id) route = lawrenceks_provider.get(busbus.Route, u'RT_43') assert len(list(lawrenceks_provider.arrivals.where( stop=stop, route=route, start_time=arrow.get('2015-03-10T14:00:00-05:00'), end_time=arrow.get('2015-03-10T16:00:00-05:00')))) == count
Add another stop to test_43_to_eaton_hall
Add another stop to test_43_to_eaton_hall
Python
mit
spaceboats/busbus
--- +++ @@ -15,10 +15,14 @@ assert agency.phone_e164 == '+17858644644' -def test_43_to_eaton_hall(lawrenceks_provider): - stop = lawrenceks_provider.get(busbus.Stop, u'15TH_SPAHR_WB') +@pytest.mark.parametrize('stop_id,count', [ + (u'15TH_SPAHR_WB', 13), + (u'SNOW_HALL_WB', 14), +]) +def test_43_to_eaton_hall(lawrenceks_provider, stop_id, count): + stop = lawrenceks_provider.get(busbus.Stop, stop_id) route = lawrenceks_provider.get(busbus.Route, u'RT_43') assert len(list(lawrenceks_provider.arrivals.where( stop=stop, route=route, start_time=arrow.get('2015-03-10T14:00:00-05:00'), - end_time=arrow.get('2015-03-10T16:00:00-05:00')))) == 13 + end_time=arrow.get('2015-03-10T16:00:00-05:00')))) == count
abb61ff0b73eb06b65223e30fcff643df4114c53
tools/geometry/icqCompositeShape.py
tools/geometry/icqCompositeShape.py
#!/usr/bin/env python import re from icqShape import Shape class CompositeShapeBuilder( Shape ): def __init__( self, shape_tuples=None ): """ Constructor @param shape_tuples list of tuples (expr_var, shape) """ self.shape_tuples = shape_tuples def compose( self, expression ): if expression is None or self.shape_tuples is None: return None expr = expression for expr_var, shape in self.shape_tuples: # Return the string obtained by replacing the leftmost # non-overlapping occurrences of expr_var in expr by # the replacement shape. expr = re.sub( expr_var, shape, expr ) return eval( expr )
#!/usr/bin/env python import re from icqShape import Shape class ShapeComposer( Shape ): def __init__( self, shape_tuples=None ): self.shape_tuples = shape_tuples self.csg = None def __add__( self, other ): """ Union @param other Shape instance @return CompositeShape """ self.csg = Shape( self.csg + other.csg ) return self.csg def __sub__( self, other ): """ Removal @param other Shape instance @return CompositeShape """ self.csg = Shape( self.csg - other.csg ) return self.csg def __mul__( self, other ): """ Intersection @param other Shape instance @return CompositeShape """ self.csg = Shape( self.csg * other.csg ) return self.csg def compose( self, expression ): expr = expression for shape_tuple in self.shape_tuples: expr_var, shape = shape_tuple expr = re.sub( r'%s' % expr_var, shape, expr ) return eval( expr )
Enhance the ShapeComposer - still not working.
Enhance the ShapeComposer - still not working.
Python
unknown
gregvonkuster/icqsol,pletzer/icqsol,pletzer/icqsol,gregvonkuster/icqsol,gregvonkuster/icqsol,pletzer/icqsol,pletzer/icqsol,gregvonkuster/icqsol
--- +++ @@ -4,22 +4,42 @@ from icqShape import Shape -class CompositeShapeBuilder( Shape ): +class ShapeComposer( Shape ): def __init__( self, shape_tuples=None ): + self.shape_tuples = shape_tuples + self.csg = None + + def __add__( self, other ): """ - Constructor - @param shape_tuples list of tuples (expr_var, shape) + Union + @param other Shape instance + @return CompositeShape """ - self.shape_tuples = shape_tuples + self.csg = Shape( self.csg + other.csg ) + return self.csg + + def __sub__( self, other ): + """ + Removal + @param other Shape instance + @return CompositeShape + """ + self.csg = Shape( self.csg - other.csg ) + return self.csg + + def __mul__( self, other ): + """ + Intersection + @param other Shape instance + @return CompositeShape + """ + self.csg = Shape( self.csg * other.csg ) + return self.csg def compose( self, expression ): - if expression is None or self.shape_tuples is None: - return None expr = expression - for expr_var, shape in self.shape_tuples: - # Return the string obtained by replacing the leftmost - # non-overlapping occurrences of expr_var in expr by - # the replacement shape. - expr = re.sub( expr_var, shape, expr ) + for shape_tuple in self.shape_tuples: + expr_var, shape = shape_tuple + expr = re.sub( r'%s' % expr_var, shape, expr ) return eval( expr )
7cfb3d6be9e1fc24b5e86e3179e874bcbe01c47c
profiles/tasks.py
profiles/tasks.py
""" Celery tasks for the User Profiles portion of RAPID. """ import datetime import logging from celery.schedules import crontab from celery.task import PeriodicTask from profiles.models import Profile LOGGER = logging.getLogger(None) """The logger for this module""" # Note: Logging doesn't appear to work properly unless we get the root logger class Update_Users(PeriodicTask): """ Periodic task to update users as inactive who have not logged in for more than 90 days This class runs every day at midnight """ #run_every = crontab(minute=0, hour=0) run_every = crontab() def run(self, **kwargs): LOGGER.debug("Running Update_Users task...") print("Updating users alert flag...") current_time = datetime.datetime.utcnow() #print("current_time",current_time) expired_date = current_time - datetime.timedelta(days=90) print("expired_date:",expired_date) Profile.objects.filter(last_login__lte = expired_date).update(alerts=False,is_active=False)
""" Celery tasks for the User Profiles portion of RAPID. """ import datetime import logging from celery.schedules import crontab from celery.task import PeriodicTask from profiles.models import Profile LOGGER = logging.getLogger(None) """The logger for this module""" # Note: Logging doesn't appear to work properly unless we get the root logger class Update_Users(PeriodicTask): """ Periodic task to update users as inactive who have not logged in for more than 90 days This class runs every day at midnight """ run_every = crontab(minute=0, hour=0) def run(self, **kwargs): LOGGER.debug("Running Update_Users task...") print("Updating users alert flag...") current_time = datetime.datetime.utcnow() #print("current_time",current_time) expired_date = current_time - datetime.timedelta(days=90) print("expired_date:",expired_date) Profile.objects.filter(last_login__lte = expired_date).update(alerts=False,is_active=False)
Update the crontab schedule to run every day at midnight
Update the crontab schedule to run every day at midnight
Python
mit
gdit-cnd/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID
--- +++ @@ -20,8 +20,7 @@ This class runs every day at midnight """ - #run_every = crontab(minute=0, hour=0) - run_every = crontab() + run_every = crontab(minute=0, hour=0) def run(self, **kwargs): LOGGER.debug("Running Update_Users task...")
0684d3132271f6c08a511aa544c85b838e942910
discode_server/config/base_config.py
discode_server/config/base_config.py
import os from urllib import parse DEBUG = False DATABASE_SA = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL') bits = parse.urlparse(DATABASE_SA) DATABASE = { 'user': bits.username, 'database': bits.path[1:], 'password': bits.password, 'host': bits.hostname, 'port': bits.port, 'maxsize': 4, } # 4 worker * 5 connections = 16 connectionso # 20 is the limit on Heroku, this leaves room for error and/or other processes # (like migrations which use 1) WORKER_COUNT = 4
import os from urllib import parse DEBUG = False DATABASE_SA = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL_PGBOUNCER') bits = parse.urlparse(DATABASE_SA) DATABASE = { 'user': bits.username, 'database': bits.path[1:], 'password': bits.password, 'host': bits.hostname, 'port': bits.port, 'maxsize': 4, } # 4 worker * 5 connections = 16 connectionso # 20 is the limit on Heroku, this leaves room for error and/or other processes # (like migrations which use 1) WORKER_COUNT = 4
Switch to using the bouncer
Switch to using the bouncer
Python
bsd-2-clause
d0ugal/discode-server,d0ugal/discode-server,d0ugal/discode-server
--- +++ @@ -3,7 +3,8 @@ DEBUG = False -DATABASE_SA = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL') + +DATABASE_SA = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL_PGBOUNCER') bits = parse.urlparse(DATABASE_SA)
df43b7fc089abb2fff87841173c28b3f5849a3b1
profile_xf11id/startup/50-scans.py
profile_xf11id/startup/50-scans.py
from ophyd.userapi.scan_api import Scan, AScan, DScan, Count, estimate scan = Scan() ascan = AScan() ascan.default_triggers = [bpm_cam_acq] ascan.default_detectors = [bpm_tot5] dscan = DScan() # Use ct as a count which is a single scan. ct = Count()
from ophyd.userapi.scan_api import Scan, AScan, DScan, Count, estimate scan = Scan() ascan = AScan() ascan.default_triggers = [bpm_cam_acq] ascan.default_detectors = [bpm_tot5] dscan = DScan() # Use ct as a count which is a single scan. ct = Count() class CHXAScan(AScan): def __call__(self, *args, **kwargs): super(CHXAScan, self).__call__(*args, **kwargs) def post_scan(self): print('pos[0], det[0]: {}, {}'.format( self.positioners[0].name, self.detectors[0].name)) est = estimate(self.positioners[0].name, self.detectors[0].name) print('estimates: {}'.format(est))
Define a CHX Ascan class.
ENH: Define a CHX Ascan class.
Python
bsd-2-clause
NSLS-II-CHX/ipython_ophyd,NSLS-II-CHX/ipython_ophyd
--- +++ @@ -8,3 +8,13 @@ # Use ct as a count which is a single scan. ct = Count() + +class CHXAScan(AScan): + def __call__(self, *args, **kwargs): + super(CHXAScan, self).__call__(*args, **kwargs) + + def post_scan(self): + print('pos[0], det[0]: {}, {}'.format( + self.positioners[0].name, self.detectors[0].name)) + est = estimate(self.positioners[0].name, self.detectors[0].name) + print('estimates: {}'.format(est))
d8d01d89710cd1d752809b8cd91d934092e99adf
pythonforandroid/recipes/ruamel.yaml/__init__.py
pythonforandroid/recipes/ruamel.yaml/__init__.py
from pythonforandroid.toolchain import PythonRecipe class RuamelYamlRecipe(PythonRecipe): version = '0.14.5' url = 'https://pypi.python.org/packages/5c/13/c120a06b3add0f9763ca9190e5f6edb9faf9d34b158dd3cff7cc9097be03/ruamel.yaml-{version}.tar.gz' depends = [ ('python2', 'python3crystax') ] site_packages_name = 'ruamel' call_hostpython_via_targetpython = False patches = ['disable-pip-req.patch'] recipe = RuamelYamlRecipe()
from pythonforandroid.recipe import PythonRecipe class RuamelYamlRecipe(PythonRecipe): version = '0.15.77' url = 'https://pypi.python.org/packages/source/r/ruamel.yaml/ruamel.yaml-{version}.tar.gz' depends = [('python2', 'python3crystax'), 'setuptools'] site_packages_name = 'ruamel' call_hostpython_via_targetpython = False patches = ['disable-pip-req.patch'] recipe = RuamelYamlRecipe()
Update to last version, fixes import and deps
Update to last version, fixes import and deps
Python
mit
kronenpj/python-for-android,kronenpj/python-for-android,germn/python-for-android,kivy/python-for-android,kronenpj/python-for-android,kivy/python-for-android,rnixx/python-for-android,rnixx/python-for-android,germn/python-for-android,kivy/python-for-android,PKRoma/python-for-android,germn/python-for-android,germn/python-for-android,kivy/python-for-android,PKRoma/python-for-android,rnixx/python-for-android,germn/python-for-android,germn/python-for-android,PKRoma/python-for-android,rnixx/python-for-android,rnixx/python-for-android,PKRoma/python-for-android,kivy/python-for-android,kronenpj/python-for-android,PKRoma/python-for-android,kronenpj/python-for-android,rnixx/python-for-android
--- +++ @@ -1,14 +1,13 @@ -from pythonforandroid.toolchain import PythonRecipe +from pythonforandroid.recipe import PythonRecipe class RuamelYamlRecipe(PythonRecipe): - version = '0.14.5' - url = 'https://pypi.python.org/packages/5c/13/c120a06b3add0f9763ca9190e5f6edb9faf9d34b158dd3cff7cc9097be03/ruamel.yaml-{version}.tar.gz' - - depends = [ ('python2', 'python3crystax') ] + version = '0.15.77' + url = 'https://pypi.python.org/packages/source/r/ruamel.yaml/ruamel.yaml-{version}.tar.gz' + depends = [('python2', 'python3crystax'), 'setuptools'] site_packages_name = 'ruamel' call_hostpython_via_targetpython = False - patches = ['disable-pip-req.patch'] + recipe = RuamelYamlRecipe()
c3d40abf3b7c201836bf674da05423d86c345498
ckanext/romania_theme/plugin.py
ckanext/romania_theme/plugin.py
import ckan.model as model import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit import os def get_number_of_files(): return model.Session.execute("select count(*) from resource where state = 'active'").first()[0] def get_number_of_external_links(): return model.Session.execute("select count(*) from resource where state = 'active' and url not LIKE '%data.gov.ro%'").first()[0] class Romania_ThemePlugin(plugins.SingletonPlugin): plugins.implements(plugins.IConfigurer) plugins.implements(plugins.ITemplateHelpers) plugins.implements(plugins.IResourceController, inherit=True) # IConfigurer def update_config(self, config): toolkit.add_template_directory(config, 'templates') toolkit.add_public_directory(config, 'public') toolkit.add_resource('fanstatic', 'romania_theme') def get_helpers(self): return {'get_number_of_files': get_number_of_files, 'get_number_of_external_links': get_number_of_external_links} # IResourceController def before_create(self, context, resource): if resource['upload'].type in ['application/pdf', 'application/doc', 'application/docx']: raise toolkit.ValidationError(['Fisierele de tip PDF, DOC sau DOCX nu sunt permise.'])
import ckan.model as model import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit import os def get_number_of_files(): return model.Session.execute("select count(*) from resource where state = 'active'").first()[0] def get_number_of_external_links(): return model.Session.execute("select count(*) from resource where state = 'active' and url not LIKE '%data.gov.ro%'").first()[0] class Romania_ThemePlugin(plugins.SingletonPlugin): plugins.implements(plugins.IConfigurer) plugins.implements(plugins.ITemplateHelpers) plugins.implements(plugins.IResourceController, inherit=True) # IConfigurer def update_config(self, config): toolkit.add_template_directory(config, 'templates') toolkit.add_public_directory(config, 'public') toolkit.add_resource('fanstatic', 'romania_theme') def get_helpers(self): return {'get_number_of_files': get_number_of_files, 'get_number_of_external_links': get_number_of_external_links} # IResourceController def before_create(self, context, resource): if resource['upload'].type in ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword'] raise toolkit.ValidationError(['Fisierele de tip PDF, DOC sau DOCX nu sunt permise.'])
Add all type of unwanted files
Add all type of unwanted files
Python
agpl-3.0
govro/ckanext-romania_theme,govro/ckanext-romania_theme,govro/ckanext-romania_theme,govro/ckanext-romania_theme
--- +++ @@ -29,5 +29,5 @@ # IResourceController def before_create(self, context, resource): - if resource['upload'].type in ['application/pdf', 'application/doc', 'application/docx']: + if resource['upload'].type in ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword'] raise toolkit.ValidationError(['Fisierele de tip PDF, DOC sau DOCX nu sunt permise.'])
88fbd428ceb79d6e176ff235256c8e5951815085
inspector/inspector/urls.py
inspector/inspector/urls.py
from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TemplateView.as_view(template_name='base.html'), name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^class/', include('cbv.urls')), ) urlpatterns += staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', TemplateView.as_view(template_name='base.html'), name='home'), url(r'^projects/', include('cbv.urls')), url(r'^admin/', include(admin.site.urls)), ) urlpatterns += staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Make the url structure a bit more sensible.
Make the url structure a bit more sensible.
Python
bsd-2-clause
refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector,abhijo89/django-cbv-inspector,refreshoxford/django-cbv-inspector,abhijo89/django-cbv-inspector,refreshoxford/django-cbv-inspector,abhijo89/django-cbv-inspector,abhijo89/django-cbv-inspector
--- +++ @@ -10,8 +10,8 @@ urlpatterns = patterns('', url(r'^$', TemplateView.as_view(template_name='base.html'), name='home'), + url(r'^projects/', include('cbv.urls')), url(r'^admin/', include(admin.site.urls)), - url(r'^class/', include('cbv.urls')), ) urlpatterns += staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
a5072cecb9be257399360f68d68389274431c8ca
fraseador.py
fraseador.py
# -*- coding: utf-8 -*- import os from google.appengine.ext.webapp import template import cgi from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from syntax import clause def phrases(n=20, lf=' '): phrase_list = [] for i in range(n): phrase_list.append(repr(clause()).capitalize() + '.') return lf.join(phrase_list) class MainPage(webapp.RequestHandler): def get(self): n = int(self.request.get('num_phrases') or '20') lf = '<br>\n' if self.request.get('break_line') == 'true' else ' ' text = phrases(n, lf) template_values = { 'text': text, 'num_phrases': self.request.get('num_phrases'), 'checked': 'checked' if self.request.get('break_line') == 'true' else '' } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) application = webapp.WSGIApplication([('/', MainPage)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- import os from google.appengine.ext.webapp import template import cgi from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from syntax import clause def phrases(n=20, lf=' '): phrase_list = [repr(clause()).capitalize() + '.' for i in range(n)] return lf.join(phrase_list) class MainPage(webapp.RequestHandler): def get(self): n = int(self.request.get('num_phrases') or '20') lf = '<br>\n' if self.request.get('break_line') == 'true' else ' ' text = phrases(n, lf) template_values = { 'text': text, 'num_phrases': self.request.get('num_phrases'), 'checked': 'checked' if self.request.get('break_line') == 'true' else '' } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) application = webapp.WSGIApplication([('/', MainPage)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Refactor list append to list comprehension.
Refactor list append to list comprehension.
Python
bsd-3-clause
andlima/fraseador
--- +++ @@ -13,9 +13,8 @@ from syntax import clause def phrases(n=20, lf=' '): - phrase_list = [] - for i in range(n): - phrase_list.append(repr(clause()).capitalize() + '.') + phrase_list = [repr(clause()).capitalize() + '.' + for i in range(n)] return lf.join(phrase_list) class MainPage(webapp.RequestHandler):
85d4496a5ce7cb801c09bacbc0dd4a67c084c504
main.py
main.py
__author__ = 'tri' from controller.event_controller import EventController from controller.env_controller import EnvController from controller.main_controller import MainController import pygame env_controller = EnvController() event_controller = EventController() main_controller = MainController(event_controller, env_controller) main_controller.init_game() while not main_controller.quit_game: # Listen events event_controller.run() # Update screen main_controller.run() pygame.display.flip() pygame.quit()
__author__ = 'tri' from controller.event_controller import EventController from controller.env_controller import EnvController from controller.main_controller import MainController import pygame env_controller = EnvController() event_controller = EventController() main_controller = MainController(event_controller, env_controller) main_controller.init_game() # Control fps clock = pygame.time.Clock() while not main_controller.quit_game: # Listen events event_controller.run() # Update screen main_controller.run() pygame.display.flip() # Approximately 60fps clock.tick(60) pygame.quit()
Resolve issuse about cpu, it depends on fps
Resolve issuse about cpu, it depends on fps
Python
apache-2.0
ductri/game_programming-ass1
--- +++ @@ -11,6 +11,9 @@ main_controller.init_game() +# Control fps +clock = pygame.time.Clock() + while not main_controller.quit_game: # Listen events event_controller.run() @@ -19,4 +22,8 @@ main_controller.run() pygame.display.flip() + + # Approximately 60fps + clock.tick(60) + pygame.quit()
967a0426a32f6bdb2e82ae055fca8080681ff891
main.py
main.py
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # this is some template "hello world" code import webapp2 # imports jinja2 import jinja2 import os jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) current_block = '7' class MainHandler(webapp2.RequestHandler): def get(self): template_values = { 'block': current_block, } template = jinja_environment.get_template('frontendproto.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True) for block in Blocks: block.name =
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Import blockmodels file import BlockModels # this is some template "hello world" code import webapp2 # imports jinja2 import jinja2 import os jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class MainHandler(webapp2.RequestHandler): def get(self): schedule = schedule() template_values = { 'schedule': schedule, } template = jinja_environment.get_template('frontendproto.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True)
Set up for showing schedule
Set up for showing schedule
Python
mit
shickey/BearStatus,shickey/BearStatus,shickey/BearStatus
--- +++ @@ -15,8 +15,10 @@ # limitations under the License. # +# Import blockmodels file +import BlockModels + # this is some template "hello world" code - import webapp2 # imports jinja2 @@ -26,12 +28,12 @@ jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) -current_block = '7' class MainHandler(webapp2.RequestHandler): def get(self): + schedule = schedule() template_values = { - 'block': current_block, + 'schedule': schedule, } template = jinja_environment.get_template('frontendproto.html') @@ -42,6 +44,3 @@ ], debug=True) - -for block in Blocks: - block.name =
796bea01d77abe421ac7db2e82a481b6d77002de
pylease/extension/__init__.py
pylease/extension/__init__.py
from abc import ABCMeta, abstractmethod from pylease.logger import LOGME as logme # noqa class Extension(object): __metaclass__ = ABCMeta _IGNORE_ME_VAR_NAME = 'ignore_me' ignore_me = False def __init__(self, lizy): super(Extension, self).__init__() logme.debug("Initializing {}".format(self.__class__.__name__)) self._lizy = lizy self.load() @abstractmethod def load(self): pass # pragma: no cover @classmethod def init_all(cls, lizy): extensions = cls.__subclasses__() for extension in extensions: extension.init_all(lizy) if not getattr(extension, cls._IGNORE_ME_VAR_NAME): extension(lizy)
from abc import ABCMeta, abstractmethod from pylease.logger import LOGME as logme # noqa class Extension(object): # pylint: disable=abstract-class-not-used __metaclass__ = ABCMeta _IGNORE_ME_VAR_NAME = 'ignore_me' ignore_me = False def __init__(self, lizy): super(Extension, self).__init__() logme.debug("Initializing {}".format(self.__class__.__name__)) self._lizy = lizy self.load() @abstractmethod def load(self): pass # pragma: no cover @classmethod def init_all(cls, lizy): extensions = cls.__subclasses__() for extension in extensions: extension.init_all(lizy) if not getattr(extension, cls._IGNORE_ME_VAR_NAME): extension(lizy)
Disable Extension class prospector error
Disable Extension class prospector error
Python
mit
n9code/pylease
--- +++ @@ -3,7 +3,7 @@ class Extension(object): - + # pylint: disable=abstract-class-not-used __metaclass__ = ABCMeta _IGNORE_ME_VAR_NAME = 'ignore_me'
b6a039369bc18456667c82b8e57f8b8621aed6d1
deprecated/__init__.py
deprecated/__init__.py
# -*- coding: utf-8 -*- """ Deprecated Library ================== Python ``@deprecated`` decorator to deprecate old python classes, functions or methods. """ #: Module Version Number, see `PEP 396 <https://www.python.org/dev/peps/pep-0396/>`_. __version__ = "1.2.11" from deprecated.classic import deprecated
# -*- coding: utf-8 -*- """ Deprecated Library ================== Python ``@deprecated`` decorator to deprecate old python classes, functions or methods. """ __version__ = "1.2.11" __author__ = u"Laurent LAPORTE <tantale.solutions@gmail.com>" __date__ = "unreleased" __credits__ = "(c) Laurent LAPORTE" from deprecated.classic import deprecated
Update :mod:`deprecated` metadata: add ``__author__``, ``__date__`` and ``__credits__``.
Update :mod:`deprecated` metadata: add ``__author__``, ``__date__`` and ``__credits__``.
Python
mit
tantale/deprecated
--- +++ @@ -7,7 +7,9 @@ """ -#: Module Version Number, see `PEP 396 <https://www.python.org/dev/peps/pep-0396/>`_. __version__ = "1.2.11" +__author__ = u"Laurent LAPORTE <tantale.solutions@gmail.com>" +__date__ = "unreleased" +__credits__ = "(c) Laurent LAPORTE" from deprecated.classic import deprecated
9307908f5a5816c709faf034958a8d737dc21078
tests/test_api.py
tests/test_api.py
import os import sys import json import responses import unittest CWD = os.path.dirname(os.path.abspath(__file__)) MS_WD = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Allow import of api.py if os.path.join(MS_WD, 'utils') not in sys.path: sys.path.insert(0, os.path.join(MS_WD, 'utils')) # Use multiscanner in ../ sys.path.insert(0, os.path.dirname(CWD)) import multiscanner import api HTTP_OK = 200 HTTP_CREATED = 201 class TestURLCase(unittest.TestCase): def setUp(self): self.app = api.app.test_client() def test_index(self): expected_response = {'Message': 'True'} resp = self.app.get('/') self.assertEqual(resp.status_code, HTTP_OK) self.assertEqual(json.loads(resp.data), expected_response)
import os import sys import json import responses import unittest CWD = os.path.dirname(os.path.abspath(__file__)) MS_WD = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Allow import of api.py if os.path.join(MS_WD, 'utils') not in sys.path: sys.path.insert(0, os.path.join(MS_WD, 'utils')) if os.path.join(MS_WD, 'storage') not in sys.path: sys.path.insert(0, os.path.join(MS_WD, 'storage')) # Use multiscanner in ../ sys.path.insert(0, os.path.dirname(CWD)) import multiscanner import api from sqlite_driver import Database TEST_DB_PATH = os.path.join(CWD, 'testing.db') HTTP_OK = 200 HTTP_CREATED = 201 class TestURLCase(unittest.TestCase): def setUp(self): self.sql_db = Database(TEST_DB_PATH) self.sql_db.init_sqlite_db() self.app = api.app.test_client() # Replace the real production DB w/ a testing DB api.db = self.sql_db def test_index(self): expected_response = {'Message': 'True'} resp = self.app.get('/') self.assertEqual(resp.status_code, HTTP_OK) self.assertEqual(json.loads(resp.data), expected_response) def test_empty_db(self): expected_response = {'Tasks': []} resp = self.app.get('/api/v1/tasks/list/') self.assertEqual(resp.status_code, HTTP_OK) self.assertEqual(json.loads(resp.data), expected_response) def tearDown(self): os.remove(TEST_DB_PATH)
Add unit test for newly initialized db
Add unit test for newly initialized db
Python
mpl-2.0
mitre/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,MITRECND/multiscanner,awest1339/multiscanner
--- +++ @@ -10,12 +10,17 @@ # Allow import of api.py if os.path.join(MS_WD, 'utils') not in sys.path: sys.path.insert(0, os.path.join(MS_WD, 'utils')) +if os.path.join(MS_WD, 'storage') not in sys.path: + sys.path.insert(0, os.path.join(MS_WD, 'storage')) # Use multiscanner in ../ sys.path.insert(0, os.path.dirname(CWD)) import multiscanner import api +from sqlite_driver import Database + +TEST_DB_PATH = os.path.join(CWD, 'testing.db') HTTP_OK = 200 HTTP_CREATED = 201 @@ -23,10 +28,23 @@ class TestURLCase(unittest.TestCase): def setUp(self): + self.sql_db = Database(TEST_DB_PATH) + self.sql_db.init_sqlite_db() self.app = api.app.test_client() + # Replace the real production DB w/ a testing DB + api.db = self.sql_db def test_index(self): expected_response = {'Message': 'True'} resp = self.app.get('/') self.assertEqual(resp.status_code, HTTP_OK) self.assertEqual(json.loads(resp.data), expected_response) + + def test_empty_db(self): + expected_response = {'Tasks': []} + resp = self.app.get('/api/v1/tasks/list/') + self.assertEqual(resp.status_code, HTTP_OK) + self.assertEqual(json.loads(resp.data), expected_response) + + def tearDown(self): + os.remove(TEST_DB_PATH)
0f74660466392f3183b01ae0598e5081f112654a
binder/jupyter_notebook_config.py
binder/jupyter_notebook_config.py
lab_command = ' '.join([ 'jupyter', 'lab', '--dev-mode', '--debug', '--no-browser', '--port={port}', '--ServerApp.ip=127.0.0.1', '--ServerApp.token=""', '--ServerApp.base_url={base_url}lab-dev', # Disable dns rebinding protection here, since our 'Host' header # is not going to be localhost when coming from hub.mybinder.org '--ServerApp.allow_remote_access=True' ]) c.ServerProxy.servers = { 'lab-dev': { 'command': [ '/bin/bash', '-c', # Redirect all logs to a log file f'{lab_command} >jupyterlab-dev.log 2>&1' ], 'timeout': 60, 'absolute_url': True } } c.NotebookApp.default_url = '/lab-dev' import logging c.NotebookApp.log_level = logging.DEBUG
lab_command = ' '.join([ 'jupyter', 'lab', '--dev-mode', '--debug', '--extensions-in-dev-mode', '--no-browser', '--port={port}', '--ServerApp.ip=127.0.0.1', '--ServerApp.token=""', '--ServerApp.base_url={base_url}lab-dev', # Disable dns rebinding protection here, since our 'Host' header # is not going to be localhost when coming from hub.mybinder.org '--ServerApp.allow_remote_access=True' ]) c.ServerProxy.servers = { 'lab-dev': { 'command': [ '/bin/bash', '-c', # Redirect all logs to a log file f'{lab_command} >jupyterlab-dev.log 2>&1' ], 'timeout': 60, 'absolute_url': True } } c.NotebookApp.default_url = '/lab-dev' import logging c.NotebookApp.log_level = logging.DEBUG
Add --extensions-in-dev-mode to the Binder dev mode
Add --extensions-in-dev-mode to the Binder dev mode
Python
bsd-3-clause
jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab
--- +++ @@ -3,6 +3,7 @@ 'lab', '--dev-mode', '--debug', + '--extensions-in-dev-mode', '--no-browser', '--port={port}', '--ServerApp.ip=127.0.0.1',
599b0524d4228b41990c0b4e00106660589160c2
processrunner/runcommand.py
processrunner/runcommand.py
# -*- coding: utf-8 -*- import sys from .processrunner import ProcessRunner from .writeout import writeOut def runCommand(command, outputPrefix="ProcessRunner> "): """Easy invocation of a command with default IO streams Args: command (list): List of strings to pass to subprocess.Popen Kwargs: outputPrefix(str): String to prepend to all output lines. Defaults to 'ProcessRunner> ' Returns: int The return code from the command """ proc = ProcessRunner(command) proc.mapLines(writeOut(sys.stdout, outputPrefix=outputPrefix), procPipeName="stdout") proc.mapLines(writeOut(sys.stderr, outputPrefix=outputPrefix), procPipeName="stderr") proc.wait() returnCode = proc.poll() proc.terminate() proc.shutdown() return returnCode
# -*- coding: utf-8 -*- import sys from .processrunner import ProcessRunner from .writeout import writeOut def runCommand(command, outputPrefix="ProcessRunner> ", returnAllContent=False): """Easy invocation of a command with default IO streams returnAllContent as False (default): Args: command (list): List of strings to pass to subprocess.Popen Kwargs: outputPrefix(str): String to prepend to all output lines. Defaults to 'ProcessRunner> ' returnAllContent(bool): False (default) sends command stdout/stderr to regular interfaces, True collects and returns them Returns: int The return code from the command (returnAllContent as False (default)) tuple (return code, list of output) The return code and any output content (returnAllContent as True) """ proc = ProcessRunner(command) if returnAllContent: content = proc.collectLines() else: proc.mapLines(writeOut(sys.stdout, outputPrefix=outputPrefix), procPipeName="stdout") proc.mapLines(writeOut(sys.stderr, outputPrefix=outputPrefix), procPipeName="stderr") returnCode = proc.wait().poll() proc.terminate() proc.shutdown() if returnAllContent: return (returnCode, content) else: return returnCode
Expand use for returning both exit code + content
runCommand: Expand use for returning both exit code + content
Python
mit
arobb/python-processrunner,arobb/python-processrunner
--- +++ @@ -5,25 +5,36 @@ from .writeout import writeOut -def runCommand(command, outputPrefix="ProcessRunner> "): +def runCommand(command, outputPrefix="ProcessRunner> ", returnAllContent=False): """Easy invocation of a command with default IO streams + + returnAllContent as False (default): Args: command (list): List of strings to pass to subprocess.Popen Kwargs: outputPrefix(str): String to prepend to all output lines. Defaults to 'ProcessRunner> ' + returnAllContent(bool): False (default) sends command stdout/stderr to regular interfaces, True collects and returns them Returns: - int The return code from the command + int The return code from the command (returnAllContent as False (default)) + tuple (return code, list of output) The return code and any output content (returnAllContent as True) """ proc = ProcessRunner(command) - proc.mapLines(writeOut(sys.stdout, outputPrefix=outputPrefix), procPipeName="stdout") - proc.mapLines(writeOut(sys.stderr, outputPrefix=outputPrefix), procPipeName="stderr") - proc.wait() - returnCode = proc.poll() + + if returnAllContent: + content = proc.collectLines() + else: + proc.mapLines(writeOut(sys.stdout, outputPrefix=outputPrefix), procPipeName="stdout") + proc.mapLines(writeOut(sys.stderr, outputPrefix=outputPrefix), procPipeName="stderr") + + returnCode = proc.wait().poll() proc.terminate() proc.shutdown() - return returnCode + if returnAllContent: + return (returnCode, content) + else: + return returnCode
10f931ab6831f9fb403912a0d0d357d35561d099
subliminal/__init__.py
subliminal/__init__.py
# -*- coding: utf-8 -*- # Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com> # # This file is part of subliminal. # # subliminal is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # subliminal is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with subliminal. If not, see <http://www.gnu.org/licenses/>. from .api import list_subtitles, download_subtitles from .async import Pool from .infos import __version__ import logging try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass __all__ = ['list_subtitles', 'download_subtitles', 'Pool'] logging.getLogger(__name__).addHandler(NullHandler())
# -*- coding: utf-8 -*- # Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com> # # This file is part of subliminal. # # subliminal is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # subliminal is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with subliminal. If not, see <http://www.gnu.org/licenses/>. from .api import list_subtitles, download_subtitles from .async import Pool from .core import (SERVICES, LANGUAGE_INDEX, SERVICE_INDEX, SERVICE_CONFIDENCE, MATCHING_CONFIDENCE) from .infos import __version__ import logging try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass __all__ = ['SERVICES', 'LANGUAGE_INDEX', 'SERVICE_INDEX', 'SERVICE_CONFIDENCE', 'MATCHING_CONFIDENCE', 'list_subtitles', 'download_subtitles', 'Pool'] logging.getLogger(__name__).addHandler(NullHandler())
Add some core components to subliminal
Add some core components to subliminal
Python
mit
ofir123/subliminal,fernandog/subliminal,neo1691/subliminal,nvbn/subliminal,bogdal/subliminal,ravselj/subliminal,SickRage/subliminal,oxan/subliminal,t4lwh/subliminal,Elettronik/subliminal,kbkailashbagaria/subliminal,juanmhidalgo/subliminal,hpsbranco/subliminal,h3llrais3r/subliminal,ratoaq2/subliminal,getzze/subliminal,Diaoul/subliminal,pums974/subliminal,goll/subliminal
--- +++ @@ -17,6 +17,8 @@ # along with subliminal. If not, see <http://www.gnu.org/licenses/>. from .api import list_subtitles, download_subtitles from .async import Pool +from .core import (SERVICES, LANGUAGE_INDEX, SERVICE_INDEX, SERVICE_CONFIDENCE, + MATCHING_CONFIDENCE) from .infos import __version__ import logging try: @@ -27,5 +29,6 @@ pass -__all__ = ['list_subtitles', 'download_subtitles', 'Pool'] +__all__ = ['SERVICES', 'LANGUAGE_INDEX', 'SERVICE_INDEX', 'SERVICE_CONFIDENCE', + 'MATCHING_CONFIDENCE', 'list_subtitles', 'download_subtitles', 'Pool'] logging.getLogger(__name__).addHandler(NullHandler())
f0dde60a20bbbf750f6833c624c0c5bf20c7ac9c
tests/hazmat/bindings/test_utils.py
tests/hazmat/bindings/test_utils.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function from cryptography.hazmat.bindings import utils def test_create_modulename(): cdef_sources = ["cdef sources go here"] source = "source code" name = utils._create_modulename(cdef_sources, source, "2.7") assert name == "_Cryptography_cffi_bcba7f4bx4a14b588" name = utils._create_modulename(cdef_sources, source, "3.2") assert name == "_Cryptography_cffi_a7462526x4a14b588"
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function from cryptography.hazmat.bindings import utils def test_create_modulename(): cdef_source = "cdef sources go here" source = "source code" name = utils._create_modulename(cdef_source, source, "2.7") assert name == "_Cryptography_cffi_bcba7f4bx4a14b588" name = utils._create_modulename(cdef_source, source, "3.2") assert name == "_Cryptography_cffi_a7462526x4a14b588"
Update test for new API
Update test for new API
Python
bsd-3-clause
bwhmather/cryptography,Ayrx/cryptography,kimvais/cryptography,skeuomorf/cryptography,Ayrx/cryptography,skeuomorf/cryptography,Hasimir/cryptography,kimvais/cryptography,kimvais/cryptography,sholsapp/cryptography,skeuomorf/cryptography,Hasimir/cryptography,Ayrx/cryptography,sholsapp/cryptography,Hasimir/cryptography,Ayrx/cryptography,kimvais/cryptography,bwhmather/cryptography,Hasimir/cryptography,bwhmather/cryptography,sholsapp/cryptography,bwhmather/cryptography,skeuomorf/cryptography,sholsapp/cryptography
--- +++ @@ -17,9 +17,9 @@ def test_create_modulename(): - cdef_sources = ["cdef sources go here"] + cdef_source = "cdef sources go here" source = "source code" - name = utils._create_modulename(cdef_sources, source, "2.7") + name = utils._create_modulename(cdef_source, source, "2.7") assert name == "_Cryptography_cffi_bcba7f4bx4a14b588" - name = utils._create_modulename(cdef_sources, source, "3.2") + name = utils._create_modulename(cdef_source, source, "3.2") assert name == "_Cryptography_cffi_a7462526x4a14b588"
fe97ed6d7e7155e974f229235c509b32523d4117
unit/anon_spec.py
unit/anon_spec.py
from tryp import __ from tryp.test import Spec # type: ignore class Inner: def __init__(self, z) -> None: self.z = z @property def wrap(self): return Inner(self.z * 2) def add(self, a, b): return self.z + a + b class Outer: def inner(self, z): return Inner(z) class AnonSpec(Spec): def nested(self): z = 5 a = 3 b = 4 o = Outer() f = __.inner(z).wrap.add(a, b) f(o).should.equal(2 * z + a + b) __all__ = ('AnonSpec',)
from tryp import __ from tryp.test import Spec # type: ignore class _Inner: def __init__(self, z) -> None: self.z = z @property def wrap(self): return _Inner(self.z * 2) def add(self, a, b): return self.z + a + b class _Outer: def inner(self, z): return _Inner(z) class AnonSpec(Spec): def nested(self): z = 5 a = 3 b = 4 o = _Outer() f = __.inner(z).wrap.add(a, b) f(o).should.equal(2 * z + a + b) __all__ = ('AnonSpec',)
Hide test classes for AnonFunc from spec
Hide test classes for AnonFunc from spec
Python
mit
tek/amino
--- +++ @@ -2,23 +2,23 @@ from tryp.test import Spec # type: ignore -class Inner: +class _Inner: def __init__(self, z) -> None: self.z = z @property def wrap(self): - return Inner(self.z * 2) + return _Inner(self.z * 2) def add(self, a, b): return self.z + a + b -class Outer: +class _Outer: def inner(self, z): - return Inner(z) + return _Inner(z) class AnonSpec(Spec): @@ -27,7 +27,7 @@ z = 5 a = 3 b = 4 - o = Outer() + o = _Outer() f = __.inner(z).wrap.add(a, b) f(o).should.equal(2 * z + a + b)
801c370ce88b3b2689da5890ebf09bae533089f4
tob-api/tob_api/hyperledger_indy.py
tob-api/tob_api/hyperledger_indy.py
import os import platform def config(): genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") return { "genesis_txn_path": genesis_txn_path, }
import os import platform import requests from pathlib import Path def getGenesisData(): """ Get a copy of the genesis transaction file from the web. """ genesisUrl = os.getenv('GENESIS_URL', 'http://138.197.170.136/genesis').lower() response = requests.get(genesisUrl) return response.text def checkGenesisFile(genesis_txn_path): """ Check on the genesis transaction file and create it is it does not exist. """ genesis_txn_file = Path(genesis_txn_path) if not genesis_txn_file.exists(): if not genesis_txn_file.parent.exists(): genesis_txn_file.parent.mkdir(parents = True) data = getGenesisData() with open(genesis_txn_path, 'x') as genesisFile: genesisFile.write(data) def config(): """ Get the hyperledger configuration settings for the environment. """ genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") checkGenesisFile(genesis_txn_path) return { "genesis_txn_path": genesis_txn_path, }
Add support for downloading the genesis transaction file.
Add support for downloading the genesis transaction file.
Python
apache-2.0
swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook
--- +++ @@ -1,12 +1,39 @@ import os import platform +import requests +from pathlib import Path + +def getGenesisData(): + """ + Get a copy of the genesis transaction file from the web. + """ + genesisUrl = os.getenv('GENESIS_URL', 'http://138.197.170.136/genesis').lower() + response = requests.get(genesisUrl) + return response.text + +def checkGenesisFile(genesis_txn_path): + """ + Check on the genesis transaction file and create it is it does not exist. + """ + genesis_txn_file = Path(genesis_txn_path) + if not genesis_txn_file.exists(): + if not genesis_txn_file.parent.exists(): + genesis_txn_file.parent.mkdir(parents = True) + data = getGenesisData() + with open(genesis_txn_path, 'x') as genesisFile: + genesisFile.write(data) def config(): + """ + Get the hyperledger configuration settings for the environment. + """ genesis_txn_path = "/opt/app-root/genesis" platform_name = platform.system() if platform_name == "Windows": genesis_txn_path = os.path.realpath("./app-root/genesis") + checkGenesisFile(genesis_txn_path) + return { "genesis_txn_path": genesis_txn_path, }
d4a1a75407610caaad769c26131f7d34ef977a70
flocker/ca/test/test_validation.py
flocker/ca/test/test_validation.py
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Test validation of keys generated by flocker-ca. """ from twisted.trial.unittest import SynchronousTestCase from .. import amp_server_context_factory, rest_api_context_factory from ..testtools import get_credential_sets class ClientValidationContextFactoryTests(SynchronousTestCase): """ Tests for implementation details of the context factory used by the control service. """ def test_amp_new_context_each_time(self): """ Each call to the AMP server's context factory ``getContext`` returns a new instance, to prevent issues with global shared state. """ ca_set, _ = get_credential_sets() context_factory = amp_server_context_factory( ca_set.root.credential.certificate, ca_set.control) self.assertNotIdentical(context_factory.getContext(), context_factory.getContext()) def test_rest_new_context_each_time(self): """ Each call to the REST API server's context factory ``getContext`` returns a new instance, to prevent issues with global shared state. """ ca_set, _ = get_credential_sets() context_factory = rest_api_context_factory( ca_set.root.credential.certificate, ca_set.control) self.assertNotIdentical(context_factory.getContext(), context_factory.getContext())
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Test validation of keys generated by flocker-ca. """ from twisted.trial.unittest import SynchronousTestCase from .. import amp_server_context_factory, rest_api_context_factory from ..testtools import get_credential_sets class ClientValidationContextFactoryTests(SynchronousTestCase): """ Tests for implementation details of the context factory used by the control service. """ def test_amp_new_context_each_time(self): """ Each call to the AMP server's context factory ``getContext`` returns a new instance, to prevent issues with global shared state. """ ca_set, _ = get_credential_sets() context_factory = amp_server_context_factory( ca_set.root.credential.certificate, ca_set.control) self.assertIsNot(context_factory.getContext(), context_factory.getContext()) def test_rest_new_context_each_time(self): """ Each call to the REST API server's context factory ``getContext`` returns a new instance, to prevent issues with global shared state. """ ca_set, _ = get_credential_sets() context_factory = rest_api_context_factory( ca_set.root.credential.certificate, ca_set.control) self.assertIsNot(context_factory.getContext(), context_factory.getContext())
Address review comment: More standard assertions.
Address review comment: More standard assertions.
Python
apache-2.0
hackday-profilers/flocker,achanda/flocker,mbrukman/flocker,LaynePeng/flocker,achanda/flocker,1d4Nf6/flocker,hackday-profilers/flocker,wallnerryan/flocker-profiles,LaynePeng/flocker,hackday-profilers/flocker,mbrukman/flocker,moypray/flocker,moypray/flocker,mbrukman/flocker,agonzalezro/flocker,Azulinho/flocker,wallnerryan/flocker-profiles,agonzalezro/flocker,lukemarsden/flocker,jml/flocker,adamtheturtle/flocker,w4ngyi/flocker,AndyHuu/flocker,moypray/flocker,lukemarsden/flocker,Azulinho/flocker,adamtheturtle/flocker,1d4Nf6/flocker,w4ngyi/flocker,AndyHuu/flocker,Azulinho/flocker,jml/flocker,lukemarsden/flocker,LaynePeng/flocker,AndyHuu/flocker,agonzalezro/flocker,w4ngyi/flocker,wallnerryan/flocker-profiles,adamtheturtle/flocker,jml/flocker,1d4Nf6/flocker,achanda/flocker
--- +++ @@ -23,8 +23,8 @@ ca_set, _ = get_credential_sets() context_factory = amp_server_context_factory( ca_set.root.credential.certificate, ca_set.control) - self.assertNotIdentical(context_factory.getContext(), - context_factory.getContext()) + self.assertIsNot(context_factory.getContext(), + context_factory.getContext()) def test_rest_new_context_each_time(self): """ @@ -35,5 +35,5 @@ ca_set, _ = get_credential_sets() context_factory = rest_api_context_factory( ca_set.root.credential.certificate, ca_set.control) - self.assertNotIdentical(context_factory.getContext(), - context_factory.getContext()) + self.assertIsNot(context_factory.getContext(), + context_factory.getContext())
2fead2caae3ff0e021ebfd9f14a04c8ca142c86f
blimp/users/authentication.py
blimp/users/authentication.py
from rest_framework import exceptions from rest_framework_jwt.settings import api_settings from rest_framework_jwt.authentication import JSONWebTokenAuthentication try: from django.contrib.auth import get_user_model except ImportError: # Django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() jwt_decode_handler = api_settings.JWT_DECODE_HANDLER class JWTAuthentication(JSONWebTokenAuthentication): def authenticate_credentials(self, payload): """ Returns an active user that matches the payload's user id and email. """ try: user = User.objects.get( pk=payload['user_id'], email=payload['email'], token_version=payload['token_version'], is_active=True ) except User.DoesNotExist: msg = 'Invalid signature' raise exceptions.AuthenticationFailed(msg) return user
from rest_framework import exceptions from rest_framework_jwt.settings import api_settings from rest_framework_jwt.authentication import JSONWebTokenAuthentication from .models import User jwt_decode_handler = api_settings.JWT_DECODE_HANDLER class JWTAuthentication(JSONWebTokenAuthentication): def authenticate_credentials(self, payload): """ Returns an active user that matches the payload's user id and email. """ try: user = User.objects.get( pk=payload['user_id'], email=payload['email'], token_version=payload['token_version'], is_active=True ) except User.DoesNotExist: msg = 'Invalid signature' raise exceptions.AuthenticationFailed(msg) return user
Remove unused user model import handling
Remove unused user model import handling
Python
agpl-3.0
jessamynsmith/boards-backend,GetBlimp/boards-backend,jessamynsmith/boards-backend
--- +++ @@ -2,12 +2,7 @@ from rest_framework_jwt.settings import api_settings from rest_framework_jwt.authentication import JSONWebTokenAuthentication -try: - from django.contrib.auth import get_user_model -except ImportError: # Django < 1.5 - from django.contrib.auth.models import User -else: - User = get_user_model() +from .models import User jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
8a5d52d388183000af4472afa47db1ddcec96331
byceps/application_factory.py
byceps/application_factory.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ application factory ~~~~~~~~~~~~~~~~~~~ Create and initialize the application using a configuration specified by an environment variable. :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from .application import create_app, init_app from .util.system import get_config_env_name_from_env environment = get_config_env_name_from_env(default='development') app = create_app(environment) init_app(app)
# -*- coding: utf-8 -*- """ application factory ~~~~~~~~~~~~~~~~~~~ Create and initialize the application using a configuration specified by an environment variable. :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from .application import create_app, init_app from .util.system import get_config_env_name_from_env environment = get_config_env_name_from_env(default='development') app = create_app(environment) init_app(app)
Remove unnecessary shebang line from module
Remove unnecessary shebang line from module
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps
--- +++ @@ -1,4 +1,3 @@ -#!/usr/bin/env python # -*- coding: utf-8 -*- """
4e28e43fea2eaa08006eeb4d70159c8ebd3c83b4
flask_uploads/__init__.py
flask_uploads/__init__.py
import loaders loader = loaders.Lazy( '%s.models' % __name__, ('Upload',) ) import extensions from .functions import ( delete, save, save_file, save_images, ) from .models import Upload def init(db, Storage, resizer=None): extensions.db = db extensions.resizer = resizer extensions.Storage = Storage loader.ready() __all__ = ( delete, init, save, save_file, save_images, Upload, )
import loaders loader = loaders.Lazy( '%s.models' % __name__, ('Upload',) ) import extensions from .functions import ( delete, save, save_file, save_images, ) from .models import Upload def init(db, Storage, resizer=None): if 'upload' in db.metadata.tables: return # Already registered the model. extensions.db = db extensions.resizer = resizer extensions.Storage = Storage loader.ready() __all__ = ( delete, init, save, save_file, save_images, Upload, )
Make sure model isn't added several times.
Make sure model isn't added several times.
Python
mit
FelixLoether/flask-uploads,FelixLoether/flask-image-upload-thing
--- +++ @@ -15,6 +15,9 @@ def init(db, Storage, resizer=None): + if 'upload' in db.metadata.tables: + return # Already registered the model. + extensions.db = db extensions.resizer = resizer extensions.Storage = Storage
f25f08625d369d7737516971256140af26015235
astropy/timeseries/io/__init__.py
astropy/timeseries/io/__init__.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from . import kepler
# Licensed under a 3-clause BSD style license - see LICENSE.rst from .kepler import *
Make sure I/O functions appear in API docs
Make sure I/O functions appear in API docs
Python
bsd-3-clause
bsipocz/astropy,dhomeier/astropy,StuartLittlefair/astropy,MSeifert04/astropy,bsipocz/astropy,mhvk/astropy,dhomeier/astropy,stargaser/astropy,lpsinger/astropy,pllim/astropy,lpsinger/astropy,StuartLittlefair/astropy,mhvk/astropy,stargaser/astropy,MSeifert04/astropy,MSeifert04/astropy,larrybradley/astropy,dhomeier/astropy,saimn/astropy,saimn/astropy,saimn/astropy,astropy/astropy,bsipocz/astropy,StuartLittlefair/astropy,bsipocz/astropy,larrybradley/astropy,lpsinger/astropy,saimn/astropy,dhomeier/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,stargaser/astropy,mhvk/astropy,lpsinger/astropy,larrybradley/astropy,larrybradley/astropy,lpsinger/astropy,pllim/astropy,mhvk/astropy,astropy/astropy,astropy/astropy,astropy/astropy,StuartLittlefair/astropy,saimn/astropy,astropy/astropy,MSeifert04/astropy,stargaser/astropy,larrybradley/astropy,aleksandr-bakanov/astropy,pllim/astropy,pllim/astropy,aleksandr-bakanov/astropy,pllim/astropy,aleksandr-bakanov/astropy,mhvk/astropy
--- +++ @@ -1,3 +1,3 @@ # Licensed under a 3-clause BSD style license - see LICENSE.rst -from . import kepler +from .kepler import *
8e8a4360124a033ad3c5bd26bfe2b3896155f25a
tests/TestDBControl.py
tests/TestDBControl.py
import unittest from blo.DBControl import DBControl class TestDBControl(unittest.TestCase): pass
import unittest from pathlib import Path from blo.DBControl import DBControl class TestDBControlOnMemory(unittest.TestCase): def setUp(self): self.db_control = DBControl() def test_initializer_for_file(self): file_path = "./test.sqlite" self.db_control.close_connect() self.db_control = DBControl(file_path) self.db_control.create_tables() self.assertTrue(Path(file_path).exists()) self.db_control.close_connect() Path(file_path).unlink() self.assertFalse(Path(file_path).exists()) self.db_control = DBControl() def test_create_table_and_select_all(self): self.db_control.create_tables() ret = self.db_control._select_all('Articles') self.assertIsInstance(ret, list) def doCleanups(self): self.db_control.close_connect()
Add test pattern of initializer for file.
Add test pattern of initializer for file.
Python
mit
10nin/blo,10nin/blo
--- +++ @@ -1,6 +1,27 @@ import unittest +from pathlib import Path from blo.DBControl import DBControl -class TestDBControl(unittest.TestCase): - pass +class TestDBControlOnMemory(unittest.TestCase): + def setUp(self): + self.db_control = DBControl() + + def test_initializer_for_file(self): + file_path = "./test.sqlite" + self.db_control.close_connect() + self.db_control = DBControl(file_path) + self.db_control.create_tables() + self.assertTrue(Path(file_path).exists()) + self.db_control.close_connect() + Path(file_path).unlink() + self.assertFalse(Path(file_path).exists()) + self.db_control = DBControl() + + def test_create_table_and_select_all(self): + self.db_control.create_tables() + ret = self.db_control._select_all('Articles') + self.assertIsInstance(ret, list) + + def doCleanups(self): + self.db_control.close_connect()
0b7edca1b0f75cb0b89ae28e22287950e7591cea
dash_core_components/__init__.py
dash_core_components/__init__.py
import os import dash as _dash import sys as _sys current_path = os.path.dirname(os.path.abspath(__file__)) _dash.development.component_loader.load_components( os.path.join(current_path, '../lib/metadata.json'), ['content', 'id', 'key', 'className', 'style', 'dependencies'], globals(), _sys._getframe(1).f_globals.get('__name__', '__main__') )
import os import dash as _dash import sys as _sys current_path = os.path.dirname(os.path.abspath(__file__)) _dash.development.component_loader.load_components( os.path.join(current_path, 'metadata.json'), ['content', 'id', 'key', 'className', 'style', 'dependencies'], globals(), _sys._getframe(1).f_globals.get('__name__', '__main__') )
Load metadata.json from current directory
Load metadata.json from current directory
Python
mit
plotly/dash-core-components
--- +++ @@ -5,7 +5,7 @@ current_path = os.path.dirname(os.path.abspath(__file__)) _dash.development.component_loader.load_components( - os.path.join(current_path, '../lib/metadata.json'), + os.path.join(current_path, 'metadata.json'), ['content', 'id', 'key', 'className', 'style', 'dependencies'], globals(), _sys._getframe(1).f_globals.get('__name__', '__main__')
d17b3f2da3daaea5b0a0468d231fa72ce043a6cc
game/itemsets/__init__.py
game/itemsets/__init__.py
# -*- coding: utf-8 -*- """ Item Sets - ItemSet.dbc """ from .. import * from ..globalstrings import * class ItemSet(Model): pass class ItemSetTooltip(Tooltip): def tooltip(self): items = self.obj.getItems() maxItems = len(items) self.append("name", ITEM_SET_NAME % (self.obj.getName(), 0, maxItems), color=YELLOW) for item in items: self.append("item", item.getName(), color=GREY) ret = self.values self.values = [] return ret class ItemSetProxy(object): """ WDBC proxy for item sets """ def __init__(self, cls): from pywow import wdbc self.__file = wdbc.get("ItemSet.dbc", build=-1) def get(self, id): return self.__file[id] def getItems(self, row): from ..items import Item, ItemProxy Item.initProxy(ItemProxy) ret = [] for i in range(1, 11): id = row._raw("item_%i" % (i)) if id: ret.append(Item(id)) return ret def getName(self, row): return row.name_enus
# -*- coding: utf-8 -*- """ Item Sets - ItemSet.dbc """ from .. import * from ..globalstrings import * class ItemSet(Model): pass class ItemSetTooltip(Tooltip): def tooltip(self): items = self.obj.getItems() maxItems = len(items) self.append("name", ITEM_SET_NAME % (self.obj.getName(), 0, maxItems), color=YELLOW) for item in items: self.append("item", " %s" % (item.getName()), color=GREY) ret = self.values self.values = [] return ret class ItemSetProxy(object): """ WDBC proxy for item sets """ def __init__(self, cls): from pywow import wdbc self.__file = wdbc.get("ItemSet.dbc", build=-1) def get(self, id): return self.__file[id] def getItems(self, row): from ..items import Item, ItemProxy Item.initProxy(ItemProxy) ret = [] for i in range(1, 11): id = row._raw("item_%i" % (i)) if id: ret.append(Item(id)) return ret def getName(self, row): return row.name_enus
Use spaces before the item name string in itemsets
Use spaces before the item name string in itemsets
Python
cc0-1.0
jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow
--- +++ @@ -20,7 +20,7 @@ self.append("name", ITEM_SET_NAME % (self.obj.getName(), 0, maxItems), color=YELLOW) for item in items: - self.append("item", item.getName(), color=GREY) + self.append("item", " %s" % (item.getName()), color=GREY) ret = self.values self.values = []
9cc09cc388d4bb9d503375083501ce566b57b65f
backend/io/connectors/Tellstick.py
backend/io/connectors/Tellstick.py
import os import socket import tftpy import time from RAXA.settings import PROJECT_ROOT from backend.io.connector import Connector class Tellstick(Connector): TYPE = 'Tellstick' def is_usable(self): return self.connector.version.startswith('RAXA') def update(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 9001)) s.send('get_ip' + self.connector.code+'\n') ip = s.recv(2048) s.close() path = os.path.join(PROJECT_ROOT, 'other', 'connector.tellstick', 'TellStickNet.hex') if ip is not None: print 'atftp -p -l %s --tftp-timeout 1 %s' % (path, ip) os.system('atftp -p -l %s --tftp-timeout 1 %s' % (path, ip)) time.sleep(10) def send(self, string): string = '{%s,"tellstick":"%s"}' % (string, self.connector.code) print string self._send('send%s' % string) def scan(self): self._send('broadcastD') def _send(self, message): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 9001)) s.send(message) s.close()
import os import socket import time from RAXA.settings import PROJECT_ROOT from backend.io.connector import Connector class Tellstick(Connector): TYPE = 'Tellstick' def is_usable(self): return self.connector.version.startswith('RAXA') def update(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 9001)) s.send('get_ip' + self.connector.code+'\n') ip = s.recv(2048) s.close() path = os.path.join(PROJECT_ROOT, 'other', 'connector.tellstick', 'TellStickNet.hex') if ip is not None: print 'atftp -p -l %s --tftp-timeout 1 %s' % (path, ip) os.system('atftp -p -l %s --tftp-timeout 1 %s' % (path, ip)) time.sleep(10) def send(self, string): string = '{%s,"tellstick":"%s"}' % (string, self.connector.code) print string self._send('send%s' % string) def scan(self): self._send('broadcastD') def _send(self, message): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 9001)) s.send(message) s.close()
Fix unused import which could creates crashes
Fix unused import which could creates crashes
Python
agpl-3.0
Pajn/RAXA-Django,Pajn/RAXA-Django
--- +++ @@ -1,6 +1,5 @@ import os import socket -import tftpy import time from RAXA.settings import PROJECT_ROOT from backend.io.connector import Connector
bf006aa3dc8ee331eccb4abd8244a134949c8cc0
bawebauth/apps/bawebauth/fields.py
bawebauth/apps/bawebauth/fields.py
# -*- coding: utf-8 -*- from django.db import models class PositiveBigIntegerField(models.PositiveIntegerField): """Represents MySQL's unsigned BIGINT data type (works with MySQL only!)""" empty_strings_allowed = False def get_internal_type(self): return "PositiveBigIntegerField" def db_type(self, connection): if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql': # This is how MySQL defines 64 bit unsigned integer data types return "BIGINT UNSIGNED" return super(PositiveBigIntegerField, self).db_type(connection) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField']) except ImportError: pass
# -*- coding: utf-8 -*- from django.db import models class PositiveBigIntegerField(models.PositiveIntegerField): """Represents MySQL's unsigned BIGINT data type (works with MySQL only!)""" empty_strings_allowed = False def db_type(self, connection): if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql': # This is how MySQL defines 64 bit unsigned integer data types return "BIGINT UNSIGNED" return super(PositiveBigIntegerField, self).db_type(connection) try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField']) except ImportError: pass
Fix tests by removing obsolete internal field type declaration
Fix tests by removing obsolete internal field type declaration
Python
mit
mback2k/django-bawebauth,mback2k/django-bawebauth,mback2k/django-bawebauth,mback2k/django-bawebauth
--- +++ @@ -4,9 +4,6 @@ class PositiveBigIntegerField(models.PositiveIntegerField): """Represents MySQL's unsigned BIGINT data type (works with MySQL only!)""" empty_strings_allowed = False - - def get_internal_type(self): - return "PositiveBigIntegerField" def db_type(self, connection): if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
0ca48ecf091e2194aef962e8880447b59066e462
src/competition/api/serializers.py
src/competition/api/serializers.py
from django.contrib.auth.models import User from rest_framework import serializers from competition.models import Team class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = ('name', 'slug', 'url') url = serializers.SerializerMethodField(read_only=True) def get_url(self, obj): return obj.get_absolute_url() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('name', 'url') name = serializers.SerializerMethodField(read_only=True) url = serializers.SerializerMethodField(read_only=True) def get_name(self, obj): username = obj.username full_name = obj.get_full_name() if full_name: return u"{} ({})".format(username, full_name) return username def get_url(self, obj): return obj.get_absolute_url()
from django.contrib.auth.models import User from rest_framework import serializers from competition.models import Team class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = ('id', 'name', 'slug', 'url') url = serializers.SerializerMethodField(read_only=True) def get_url(self, obj): return obj.get_absolute_url() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('name', 'url') name = serializers.SerializerMethodField(read_only=True) url = serializers.SerializerMethodField(read_only=True) def get_name(self, obj): username = obj.username full_name = obj.get_full_name() if full_name: return u"{} ({})".format(username, full_name) return username def get_url(self, obj): return obj.get_absolute_url()
Add team id field to API output
Add team id field to API output
Python
bsd-3-clause
michaelwisely/django-competition,michaelwisely/django-competition,michaelwisely/django-competition
--- +++ @@ -9,7 +9,7 @@ class Meta: model = Team - fields = ('name', 'slug', 'url') + fields = ('id', 'name', 'slug', 'url') url = serializers.SerializerMethodField(read_only=True)
f82fe96cf520ec2f635f34f911bc8d4ccd78d776
mfnd/todotask.py
mfnd/todotask.py
#!/usr/bin/env python3 """ Module for tasks in the to-do list """ class TodoTask: """ Represents a task in the to-do list """ def __init__(self, description): """ Initialize a to-do list task item """ self.description = description self.completionStatus = 0 self.visible = True self.mode = 0
#!/usr/bin/env python3 """ Module for tasks in the to-do list """ class TodoTask: """ Represents a task in the to-do list """ def __init__(self, description): """ Initialize a to-do list task item """ self.description = description self.completionStatus = 0 self.visible = True self.mode = 0 def __str__(self): if completionStatus == 0: return self.description elif completionStatus == 1: return "--- " + self.description + " ---"
Implement str method for TodoTask class
feature: Implement str method for TodoTask class
Python
mit
mes32/mfnd
--- +++ @@ -20,3 +20,9 @@ self.completionStatus = 0 self.visible = True self.mode = 0 + + def __str__(self): + if completionStatus == 0: + return self.description + elif completionStatus == 1: + return "--- " + self.description + " ---"
688292246b9db3eb0aa5be752612ae2df2fcff67
tools/tests/factory_configuration/factory_configuration_test.py
tools/tests/factory_configuration/factory_configuration_test.py
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the configuration for each BuildFactory matches its expectation. """ import os import sys sys.path.append('master') sys.path.append('site_config') sys.path.append(os.path.join('third_party', 'chromium_buildbot', 'scripts')) sys.path.append(os.path.join('third_party', 'chromium_buildbot', 'site_config')) sys.path.append(os.path.join('third_party', 'chromium_buildbot', 'third_party', 'buildbot_8_4p1')) import config import config_private import master_builders_cfg def main(): c = {} c['schedulers'] = [] c['builders'] = [] # Make sure that the configuration errors out if validation fails. config_private.die_on_validation_failure = True # Pretend that the master is the production master, so that the tested # configuration is identical to that of the production master. config.Master.Skia.is_production_host = True # Run the configuration. master_builders_cfg.Update(config, config.Master.Skia, c) if '__main__' == __name__: sys.exit(main())
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the configuration for each BuildFactory matches its expectation. """ import os import sys buildbot_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir, os.pardir, os.pardir) sys.path.append(os.path.join(buildbot_path, 'master')) sys.path.append(os.path.join(buildbot_path, 'site_config')) sys.path.append(os.path.join(buildbot_path, 'third_party', 'chromium_buildbot', 'scripts')) sys.path.append(os.path.join(buildbot_path, 'third_party', 'chromium_buildbot', 'site_config')) sys.path.append(os.path.join(buildbot_path, 'third_party', 'chromium_buildbot', 'third_party', 'buildbot_8_4p1')) import config import config_private import master_builders_cfg def main(): c = {} c['schedulers'] = [] c['builders'] = [] # Make sure that the configuration errors out if validation fails. config_private.die_on_validation_failure = True # Pretend that the master is the production master, so that the tested # configuration is identical to that of the production master. config.Master.Skia.is_production_host = True # Run the configuration. master_builders_cfg.Update(config, config.Master.Skia, c) if '__main__' == __name__: sys.exit(main())
Update factory configuration test to work independently of working directory
Update factory configuration test to work independently of working directory (SkipBuildbotRuns) R=rmistry@google.com Review URL: https://codereview.chromium.org/15317003 git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9186 2bbb7eff-a529-9590-31e7-b0007b416f81
Python
bsd-3-clause
Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot
--- +++ @@ -9,12 +9,16 @@ import os import sys -sys.path.append('master') -sys.path.append('site_config') -sys.path.append(os.path.join('third_party', 'chromium_buildbot', 'scripts')) -sys.path.append(os.path.join('third_party', 'chromium_buildbot', 'site_config')) -sys.path.append(os.path.join('third_party', 'chromium_buildbot', 'third_party', - 'buildbot_8_4p1')) +buildbot_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), + os.pardir, os.pardir, os.pardir) +sys.path.append(os.path.join(buildbot_path, 'master')) +sys.path.append(os.path.join(buildbot_path, 'site_config')) +sys.path.append(os.path.join(buildbot_path, 'third_party', 'chromium_buildbot', + 'scripts')) +sys.path.append(os.path.join(buildbot_path, 'third_party', 'chromium_buildbot', + 'site_config')) +sys.path.append(os.path.join(buildbot_path, 'third_party', 'chromium_buildbot', + 'third_party', 'buildbot_8_4p1')) import config import config_private
fc3f2e2f9fdf8a19756bbf8b5bd1442b71ac3a87
scrapi/settings/__init__.py
scrapi/settings/__init__.py
import logging from raven import Client from fluent import sender from raven.contrib.celery import register_signal from scrapi.settings.defaults import * from scrapi.settings.local import * logging.basicConfig(level=logging.INFO) logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARNING) if USE_FLUENTD: sender.setup(**FLUENTD_ARGS) if SENTRY_DSN: client = Client(SENTRY_DSN) register_signal(client) CELERY_ENABLE_UTC = True CELERY_RESULT_BACKEND = None CELERY_TASK_SERIALIZER = 'pickle' CELERY_ACCEPT_CONTENT = ['pickle'] CELERY_RESULT_SERIALIZER = 'pickle' CELERY_IMPORTS = ('scrapi.tasks', )
import logging from raven import Client from fluent import sender from raven.contrib.celery import register_signal from scrapi.settings.defaults import * from scrapi.settings.local import * logging.basicConfig(level=logging.INFO) logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARNING) if USE_FLUENTD: sender.setup(**FLUENTD_ARGS) if SENTRY_DSN: client = Client(SENTRY_DSN) register_signal(client) CELERY_ENABLE_UTC = True CELERY_RESULT_BACKEND = None CELERY_TASK_SERIALIZER = 'pickle' CELERY_ACCEPT_CONTENT = ['pickle'] CELERY_RESULT_SERIALIZER = 'pickle' CELERY_IMPORTS = ('scrapi.tasks', 'scrapi.migrations')
Add new place to look for celery tasks
Add new place to look for celery tasks
Python
apache-2.0
CenterForOpenScience/scrapi,erinspace/scrapi,felliott/scrapi,mehanig/scrapi,fabianvf/scrapi,mehanig/scrapi,felliott/scrapi,jeffreyliu3230/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,alexgarciac/scrapi,fabianvf/scrapi,ostwald/scrapi,icereval/scrapi
--- +++ @@ -26,4 +26,4 @@ CELERY_TASK_SERIALIZER = 'pickle' CELERY_ACCEPT_CONTENT = ['pickle'] CELERY_RESULT_SERIALIZER = 'pickle' -CELERY_IMPORTS = ('scrapi.tasks', ) +CELERY_IMPORTS = ('scrapi.tasks', 'scrapi.migrations')
96eca23792541979e73ccb247368394cd28e9530
Code/Native/update_module_builder.py
Code/Native/update_module_builder.py
""" This script downloads and updates the module builder. """ # Dont checkout all files IGNORE_FILES = [ "__init__.py", ".gitignore", "LICENSE", "README.md", "config.ini", "Source/config_module.cpp", "Source/config_module.h", "Source/ExampleClass.cpp", "Source/ExampleClass.h", "Source/ExampleClass.I", ] import sys import os sys.path.insert(0, "../../") from Code.Util.SubmoduleDownloader import SubmoduleDownloader if __name__ == "__main__": curr_dir = os.path.dirname(os.path.realpath(__file__)) SubmoduleDownloader.download_submodule("tobspr", "P3DModuleBuilder", curr_dir, IGNORE_FILES)
""" This script downloads and updates the module builder. """ # Dont checkout all files IGNORE_FILES = [ "__init__.py", ".gitignore", "LICENSE", "README.md", "config.ini", "Source/config_module.cpp", "Source/config_module.h", "Source/ExampleClass.cpp", "Source/ExampleClass.h", "Source/ExampleClass.I", ] import sys import os sys.path.insert(0, "../../") from Code.Util.SubmoduleDownloader import SubmoduleDownloader if __name__ == "__main__": curr_dir = os.path.dirname(os.path.realpath(__file__)) SubmoduleDownloader.download_submodule("tobspr", "P3DModuleBuilder", curr_dir, IGNORE_FILES) # Make the init file at the Scripts directory with open(os.path.join(curr_dir, "Scripts/__init__.py"), "w") as handle: pass
Fix missing __init__ in native directory
Fix missing __init__ in native directory
Python
mit
croxis/SpaceDrive,croxis/SpaceDrive,croxis/SpaceDrive
--- +++ @@ -27,3 +27,7 @@ if __name__ == "__main__": curr_dir = os.path.dirname(os.path.realpath(__file__)) SubmoduleDownloader.download_submodule("tobspr", "P3DModuleBuilder", curr_dir, IGNORE_FILES) + + # Make the init file at the Scripts directory + with open(os.path.join(curr_dir, "Scripts/__init__.py"), "w") as handle: + pass
e977331dff6fc4f03eef42be504ec3d747e3f9ad
sana_builder/webapp/models.py
sana_builder/webapp/models.py
from django.db import models # Create your models here.
from django.db import models from django.contrib.auth.models import User class Procedure(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) uuid = models.IntegerField(null=True) version = models.CharField(max_length=50, null=True) owner = models.ForeignKey(User, unique=True) class Page(models.Model): procedure = models.ForeignKey(Procedure)
Create a Procedure model and an example Page model
Create a Procedure model and an example Page model Page only contains a foreign key to a procedure for now.
Python
bsd-3-clause
SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder
--- +++ @@ -1,3 +1,12 @@ from django.db import models +from django.contrib.auth.models import User -# Create your models here. +class Procedure(models.Model): + title = models.CharField(max_length=50) + author = models.CharField(max_length=50) + uuid = models.IntegerField(null=True) + version = models.CharField(max_length=50, null=True) + owner = models.ForeignKey(User, unique=True) + +class Page(models.Model): + procedure = models.ForeignKey(Procedure)
322cd948a7eef9d0af1d39de682c267094fb7324
test.py
test.py
import li import unittest class LIAPITestSequence(unittest.TestCase): def setup(self): pass def test_get_permits(self): """Returns the first 1,000 most recent permits as a list/JSON """ results = li.get_permits({}) self.assertEqual(type(results), list) self.assertEqual(len(results), 1000) def test_get_permit(self): """Returns details for a single permit """ results = li.get_permit(333274) self.assertEqual(type(results), dict) self.assertTrue(results.has_key('permit_type_code')) def test_get_permit_with_related(self): """Returns details for a specific permit """ results = li.get_permit(333274, related=True) self.assertEqual(type(results), dict) self.assertTrue(results.has_key('permit_type_code')) self.assertTrue(results['zoningboardappeals'].has_key('results')) self.assertTrue(results['locations'].has_key('street_name')) self.assertTrue(results['buildingboardappeals'].has_key('results')) if __name__ == '__main__': unittest.main()
import li import unittest class LIAPITestSequence(unittest.TestCase): def setup(self): pass def test_get_permits(self): """Returns the first 1,000 most recent permits as a list/JSON """ results = li.get_permits({}) self.assertEqual(type(results), list) self.assertEqual(len(results), 1000) def test_get_permit(self): """Returns details for a single permit """ results = li.get_permit(333274) self.assertEqual(type(results), dict) self.assertTrue('permit_type_code' in results.keys()) def test_get_permit_with_related(self): """Returns details for a specific permit """ results = li.get_permit(333274, related=True) self.assertEqual(type(results), dict) self.assertTrue('permit_type_code' in results.keys()) self.assertTrue('results' in results['zoningboardappeals'].keys()) self.assertTrue('street_name' in results['locations'].keys()) self.assertTrue('results' in results['buildingboardappeals'].keys()) if __name__ == '__main__': unittest.main()
Remove used of deprecated has_key() and replace with in
Remove used of deprecated has_key() and replace with in
Python
mit
AxisPhilly/py-li
--- +++ @@ -21,7 +21,7 @@ results = li.get_permit(333274) self.assertEqual(type(results), dict) - self.assertTrue(results.has_key('permit_type_code')) + self.assertTrue('permit_type_code' in results.keys()) def test_get_permit_with_related(self): """Returns details for a specific permit @@ -29,10 +29,10 @@ results = li.get_permit(333274, related=True) self.assertEqual(type(results), dict) - self.assertTrue(results.has_key('permit_type_code')) - self.assertTrue(results['zoningboardappeals'].has_key('results')) - self.assertTrue(results['locations'].has_key('street_name')) - self.assertTrue(results['buildingboardappeals'].has_key('results')) + self.assertTrue('permit_type_code' in results.keys()) + self.assertTrue('results' in results['zoningboardappeals'].keys()) + self.assertTrue('street_name' in results['locations'].keys()) + self.assertTrue('results' in results['buildingboardappeals'].keys()) if __name__ == '__main__':
37c3e8f804b508247d3899a63c861102d76d1593
docs/conf.py
docs/conf.py
import os import pathlib import sys import toml # Allow autodoc to import listparser. sys.path.append(os.path.abspath("../src")) # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ["sphinx.ext.autodoc"] # The suffix of source filenames. source_suffix = ".rst" # The master toctree document. master_doc = "index" # General information about the project. project = "listparser" copyright = "2009-2022 Kurt McKee" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # info = toml.load(pathlib.Path(__file__) / "../../pyproject.toml") version = release = info["tool"]["poetry"]["version"] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = () # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx"
import os import pathlib import sys import toml # Allow autodoc to import listparser. sys.path.append(os.path.abspath("../src")) # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ["sphinx.ext.autodoc"] # The suffix of source filenames. source_suffix = ".rst" # The master toctree document. master_doc = "index" # General information about the project. project = "listparser" copyright = "2009-2022 Kurt McKee" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # info = toml.load(pathlib.Path(__file__).parent.parent / "pyproject.toml") version = release = info["tool"]["poetry"]["version"] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = () # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx"
Fix a build error reported by ReadTheDocs
Fix a build error reported by ReadTheDocs
Python
mit
kurtmckee/listparser
--- +++ @@ -29,7 +29,7 @@ # |version| and |release|, also used in various other places throughout the # built documents. # -info = toml.load(pathlib.Path(__file__) / "../../pyproject.toml") +info = toml.load(pathlib.Path(__file__).parent.parent / "pyproject.toml") version = release = info["tool"]["poetry"]["version"] # List of directories, relative to source directory, that shouldn't be searched
f571c0754a519f1b2aa6a7ecc4f9de2c23ce0a0c
x10d.py
x10d.py
#!/usr/bin/env python from daemon import Daemon, SerialDispatcher from serial import Serial from threading import Thread import sys def callback(event): if event: print("EVENT: {0.house}{0.unit}: {0.command}".format(event)) def listen(daemon): house, unit, act = input().split() unit = int(unit) if act.upper() == "ON": daemon.on(house, unit) elif act.upper() == "OFF": daemon.off(house, unit) def main(args): serial_port = args[1] baud = 9600 s = Serial(serial_port, baud) dispatcher = SerialDispatcher(s) daemon = Daemon(dispatcher) daemon.subscribe(callback) daemon_thread = Thread(target=daemon.listen, name="daemon-listener") daemon_thread.start() daemon_thread.join() s.close() if __name__ == "__main__": # TODO: Parse arguments for things main(sys.argv)
#!/usr/bin/env python from daemon import Daemon, SerialDispatcher from serial import Serial from threading import Thread import sys def callback(event): if event: print("EVENT: {0.house}{0.unit}: {0.command}".format(event)) def listen(daemon): house, unit, act = input().split() unit = int(unit) if act.upper() == "ON": daemon.on(house, unit) elif act.upper() == "OFF": daemon.off(house, unit) def main(args): serial_port = args[1] baud = 9600 s = Serial(serial_port, baud) dispatcher = SerialDispatcher(s) daemon = Daemon(dispatcher) daemon.subscribe(callback) daemon_thread = Thread(target=daemon.listen, name="daemon-listener") daemon_thread.start() user_thread = Thread(target=listen, args=(daemon,), name="user-listener") user_thread.start() daemon_thread.join() user_thread.join() s.close() if __name__ == "__main__": # TODO: Parse arguments for things main(sys.argv)
Add user input to daemon
Add user input to daemon
Python
unlicense
umbc-hackafe/x10-controller
--- +++ @@ -19,15 +19,20 @@ def main(args): serial_port = args[1] baud = 9600 - s = Serial(serial_port, baud) + dispatcher = SerialDispatcher(s) daemon = Daemon(dispatcher) daemon.subscribe(callback) daemon_thread = Thread(target=daemon.listen, name="daemon-listener") daemon_thread.start() + + user_thread = Thread(target=listen, args=(daemon,), name="user-listener") + user_thread.start() + daemon_thread.join() + user_thread.join() s.close() if __name__ == "__main__":
9a8964281bfb5af0af2128e6d26968a92b110da3
setup.py
setup.py
# -*- coding: utf-8 -*- from setuptools import setup import ogres requirements = ["tensorflow>=0.10"] version = ogres.__version__ setup( name="ogres", version=version, url="https://github.com/butternutdog/ogres", download_url="https://github.com/butternutdog/ogres/tarball/{0}".format(version), license="MIT", author="Martin Singh-Blom, Jonny Reichwald", author_email="ogres@butternutdog.com", maintainer="ogres@butternutdog.com", description="Thin tensorflow wrapper. Requires tensorflow", long_description=None, packages=["ogres"], install_requires=requirements, scripts=[], platforms="any", zip_safe=True, classifiers=[ "Operating System :: OS Independent", "Programming Language :: Python", "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha", ] )
# -*- coding: utf-8 -*- from setuptools import setup import ogres requirements = [] # Requires tensorflow, but no easy install script exist version = ogres.__version__ setup( name="ogres", version=version, url="https://github.com/butternutdog/ogres", download_url="https://github.com/butternutdog/ogres/tarball/{0}".format(version), license="MIT", author="Martin Singh-Blom, Jonny Reichwald", author_email="ogres@butternutdog.com", maintainer="ogres@butternutdog.com", description="Thin tensorflow wrapper. Requires tensorflow", long_description=None, packages=["ogres"], install_requires=requirements, scripts=[], platforms="any", zip_safe=True, classifiers=[ "Operating System :: OS Independent", "Programming Language :: Python", "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha", ] )
Remove tensorflow as dependency for now
Remove tensorflow as dependency for now
Python
mit
butternutdog/ogres
--- +++ @@ -3,7 +3,7 @@ from setuptools import setup import ogres -requirements = ["tensorflow>=0.10"] +requirements = [] # Requires tensorflow, but no easy install script exist version = ogres.__version__