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
e53d324f2ac4874c1f56bbf00dfee47c6b059e5d
fluidreview/admin.py
fluidreview/admin.py
"""Admin interface for fluidreview""" from django.contrib import admin from bootcamp.utils import get_field_names from fluidreview.models import WebhookRequest, OAuthToken class WebhookRequestAdmin(admin.ModelAdmin): """Admin for WebhookRequest""" model = WebhookRequest readonly_fields = get_field_names(WebhookRequest) def has_add_permission(self, request): return False def has_delete_permission(self, request, obj=None): return False class OAuthTokenAdmin(admin.ModelAdmin): """Admin for OAuthToken""" model = OAuthToken admin.site.register(WebhookRequest, WebhookRequestAdmin) admin.site.register(OAuthToken, OAuthTokenAdmin)
"""Admin interface for fluidreview""" from django.contrib import admin from bootcamp.utils import get_field_names from fluidreview.models import WebhookRequest, OAuthToken class WebhookRequestAdmin(admin.ModelAdmin): """Admin for WebhookRequest""" model = WebhookRequest readonly_fields = get_field_names(WebhookRequest) ordering = ('-created_on',) list_filter = ('award_id', 'status') search_fields = ('user_email', 'user_id', 'submission_id') def has_add_permission(self, request): return False def has_delete_permission(self, request, obj=None): return False class OAuthTokenAdmin(admin.ModelAdmin): """Admin for OAuthToken""" model = OAuthToken admin.site.register(WebhookRequest, WebhookRequestAdmin) admin.site.register(OAuthToken, OAuthTokenAdmin)
Sort webhook requests by date
Sort webhook requests by date
Python
bsd-3-clause
mitodl/bootcamp-ecommerce,mitodl/bootcamp-ecommerce,mitodl/bootcamp-ecommerce,mitodl/bootcamp-ecommerce
--- +++ @@ -9,6 +9,9 @@ """Admin for WebhookRequest""" model = WebhookRequest readonly_fields = get_field_names(WebhookRequest) + ordering = ('-created_on',) + list_filter = ('award_id', 'status') + search_fields = ('user_email', 'user_id', 'submission_id') def has_add_permission(self, request): return False
fd6e6f07c1119142456c607c7bc10528c9214cc2
bluebottle/settings/production.py
bluebottle/settings/production.py
try: from .secrets import * except ImportError: import sys sys.exit('secrets.py settings file not found. Please run `prepare.sh` to create one.') from .base import * # # Put production server environment specific overrides below. # DEBUG = False TEMPLATE_DEBUG = DEBUG INSTALLED_APPS += ( 'gunicorn', ) COWRY_RETURN_URL_BASE = 'https://production.onepercentclub.com' COWRY_LIVE_PAYMENTS = True # Send email for real EMAIL_BACKEND = 'apps.bluebottle_utils.email_backend.DKIMBackend'
try: from .secrets import * except ImportError: import sys sys.exit('secrets.py settings file not found. Please run `prepare.sh` to create one.') from .base import * # # Put production server environment specific overrides below. # DEBUG = False TEMPLATE_DEBUG = DEBUG INSTALLED_APPS += ( 'gunicorn', ) COWRY_RETURN_URL_BASE = 'https://onepercentclub.com' COWRY_LIVE_PAYMENTS = True # Send email for real EMAIL_BACKEND = 'apps.bluebottle_utils.email_backend.DKIMBackend'
Adjust cowry return url now that we're up and running.
Adjust cowry return url now that we're up and running.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
--- +++ @@ -17,7 +17,7 @@ 'gunicorn', ) -COWRY_RETURN_URL_BASE = 'https://production.onepercentclub.com' +COWRY_RETURN_URL_BASE = 'https://onepercentclub.com' COWRY_LIVE_PAYMENTS = True # Send email for real
678ddb9813edbc8a0013e8cf9ae5ff17cf3c72f7
test/test_grid.py
test/test_grid.py
import pytest import torch from torch import Tensor import syft as sy def test_virtual_grid(workers): """This tests our ability to simplify tuple types. This test is pretty simple since tuples just serialize to themselves, with a tuple wrapper with the correct ID (1) for tuples so that the detailer knows how to interpret it.""" print(len(workers)) print(workers) bob = workers["bob"] alice = workers["alice"] james = workers["james"] grid = sy.grid.VirtualGrid(*[bob, alice, james]) x = torch.tensor([1, 2, 3, 4]).tag("#bob", "#male").send(bob) y = torch.tensor([1, 2, 3, 4]).tag("#alice", "#female").send(alice) z = torch.tensor([1, 2, 3, 4]).tag("#james", "#male").send(james) results, tags = grid.search("#bob") assert len(results) == 3 assert "bob" in results.keys() assert "alice" in results.keys() assert "james" in results.keys() results, tags = grid.search("#bob") assert len(results["bob"]) == 1 assert len(results["alice"]) == 0 assert len(results["james"]) == 0 results, tags = grid.search("#male") assert len(results["bob"]) == 1 assert len(results["alice"]) == 0 assert len(results["james"]) == 1
import pytest import torch from torch import Tensor import syft as sy def test_virtual_grid(workers): """This tests our ability to simplify tuple types. This test is pretty simple since tuples just serialize to themselves, with a tuple wrapper with the correct ID (1) for tuples so that the detailer knows how to interpret it.""" print(len(workers)) print(workers) bob = workers["bob"] alice = workers["alice"] james = workers["james"] grid = sy.grid.VirtualGrid(*[bob, alice, james]) x = torch.tensor([1, 2, 3, 4]).tag("#bob", "#male").send(bob) y = torch.tensor([1, 2, 3, 4]).tag("#alice", "#female").send(alice) z = torch.tensor([1, 2, 3, 4]).tag("#james", "#male").send(james) results, tags = grid.search() assert len(results) == 3 assert "bob" in results.keys() assert "alice" in results.keys() assert "james" in results.keys() results, tags = grid.search("#bob") assert len(results["bob"]) == 1 assert "alice" not in results assert "james" not in results results, tags = grid.search("#male") assert len(results["bob"]) == 1 assert "alice" not in results assert len(results["james"]) == 1
Fix test on grid search
Fix test on grid search
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
--- +++ @@ -24,7 +24,7 @@ y = torch.tensor([1, 2, 3, 4]).tag("#alice", "#female").send(alice) z = torch.tensor([1, 2, 3, 4]).tag("#james", "#male").send(james) - results, tags = grid.search("#bob") + results, tags = grid.search() assert len(results) == 3 assert "bob" in results.keys() @@ -33,10 +33,10 @@ results, tags = grid.search("#bob") assert len(results["bob"]) == 1 - assert len(results["alice"]) == 0 - assert len(results["james"]) == 0 + assert "alice" not in results + assert "james" not in results results, tags = grid.search("#male") assert len(results["bob"]) == 1 - assert len(results["alice"]) == 0 + assert "alice" not in results assert len(results["james"]) == 1
49cd32a7d1b3f70da19ed6f90d930646914d9756
testTwitterAPI.py
testTwitterAPI.py
''' Created on Apr 25, 2015 @author: Sherry ''' from json import dumps from twitterDataAcquisition import TwitterDataAcquisition def main(): twitterData = TwitterDataAcquisition() #jsonFile = ("twitter_data.json", "w") #jsonFile.write(str(twitterData)) #jsonFile.close() print dumps(twitterData) if __name__ == '__main__': main()
''' Created on Apr 25, 2015 @author: Sherry ''' from json import dumps from twitterDataAcquisition import TwitterDataAcquisition from twitterScreenScrape import TwitterScreenScrape def main(): appsList = ["Messenger", "Criminal Case", "Facebook", "Pandora Radio", "Instagram", "Snapchat", "Dubsmash","Super-Bright LED Flashlight", "Spotify Music", "Clean Master (Speed Booster)"] #twitterData = TwitterDataAcquisition() #jsonFile = ("twitter_data.json", "w") #jsonFile.write(str(twitterData)) #jsonFile.close() #print dumps(twitterData) TwitterScreenScrape(appsList) #TwitterScreenScrape(["Messenger"]) if __name__ == '__main__': main()
Include call for screen scraping
Include call for screen scraping
Python
apache-2.0
WenTr/TrendingApps
--- +++ @@ -7,15 +7,23 @@ from json import dumps from twitterDataAcquisition import TwitterDataAcquisition +from twitterScreenScrape import TwitterScreenScrape def main(): - twitterData = TwitterDataAcquisition() + appsList = ["Messenger", "Criminal Case", "Facebook", "Pandora Radio", "Instagram", + "Snapchat", "Dubsmash","Super-Bright LED Flashlight", "Spotify Music", + "Clean Master (Speed Booster)"] + + #twitterData = TwitterDataAcquisition() #jsonFile = ("twitter_data.json", "w") #jsonFile.write(str(twitterData)) #jsonFile.close() - print dumps(twitterData) + #print dumps(twitterData) + + TwitterScreenScrape(appsList) + #TwitterScreenScrape(["Messenger"]) if __name__ == '__main__': main()
3e56590159d5685c668e6d6dfcea3164e82f87f5
cob/cli/testserver_cli.py
cob/cli/testserver_cli.py
import click import logbook from ..app import build_app from ..bootstrapping import ensure_project_bootstrapped _logger = logbook.Logger(__name__) @click.command() @click.option('-p', '--port', type=int, default=5000) @click.option('--debug/--no-debug', is_flag=True, default=True) def testserver(port, debug): ensure_project_bootstrapped() flask_app = build_app(config_overrides={'TESTING': True, 'DEBUG': debug}) flask_app.run(port=port, debug=debug)
import click import logbook from ..app import build_app from ..bootstrapping import ensure_project_bootstrapped _logger = logbook.Logger(__name__) @click.command() @click.option('-p', '--port', type=int, default=5000) @click.option('--debug/--no-debug', is_flag=True, default=True) def testserver(port, debug): ensure_project_bootstrapped() flask_app = build_app(config_overrides={'TESTING': True, 'DEBUG': debug}) logbook.StderrHandler(level=logbook.DEBUG).push_application() flask_app.run(port=port, debug=debug)
Add debug log output to `cob testserver`
Add debug log output to `cob testserver`
Python
bsd-3-clause
getweber/weber-cli
--- +++ @@ -13,4 +13,5 @@ def testserver(port, debug): ensure_project_bootstrapped() flask_app = build_app(config_overrides={'TESTING': True, 'DEBUG': debug}) + logbook.StderrHandler(level=logbook.DEBUG).push_application() flask_app.run(port=port, debug=debug)
dd64801ffa4949f0458eec2721a333a480a8fc3c
app/runserver.py
app/runserver.py
from flask_script import Manager from config.config import app manager = Manager(app) @manager.command def run_local(): app.run(debug=True) @manager.command def run_test(): # To-Do pass @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run()
from flask_script import Manager from config.config import app manager = Manager(app) # Deploy for development @manager.command def run_dev(): app.run(debug=True) # Deploy for intergation tests @manager.command def run_test(): # To-Do pass # Deploy for production @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run()
Change naming schema for deploy
Change naming schema for deploy
Python
mit
tforrest/soda-automation,tforrest/soda-automation
--- +++ @@ -3,15 +3,17 @@ manager = Manager(app) +# Deploy for development @manager.command -def run_local(): +def run_dev(): app.run(debug=True) +# Deploy for intergation tests @manager.command def run_test(): # To-Do pass - +# Deploy for production @manager.command def run_production(): # TO-DO
2b477a2f4cbbcb1ac25c48ace0597d3d5713cafd
tastytaps/urls.py
tastytaps/urls.py
from django.conf.urls import include, url from django.contrib import admin from .views import HomePageView urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), url(r'^admin/', include(admin.site.urls)), ]
from django.conf.urls import url from .views import HomePageView urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), ]
Drop the admin for srs this time
Drop the admin for srs this time
Python
bsd-3-clause
tastybrew/tastytaps,tastybrew/tastytaps
--- +++ @@ -1,10 +1,8 @@ -from django.conf.urls import include, url -from django.contrib import admin +from django.conf.urls import url from .views import HomePageView urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), - url(r'^admin/', include(admin.site.urls)), ]
8b321c2aa37d57cc3cfc092ab2d887ce685284b6
junction/conferences/serializers.py
junction/conferences/serializers.py
from rest_framework import serializers from .models import Conference, ConferenceVenue, Room class ConferenceSerializer(serializers.HyperlinkedModelSerializer): status = serializers.CharField(source='get_status_display') class Meta: model = Conference fields = ('id', 'name', 'slug', 'description', 'start_date', 'end_date', 'status', 'venue') class VenueSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ConferenceVenue fields = ('name', 'address', 'latitude', 'longitudes') class RoomSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Room fields = ('name', 'venue', 'note')
from rest_framework import serializers from .models import Conference, ConferenceVenue, Room class ConferenceSerializer(serializers.HyperlinkedModelSerializer): status = serializers.CharField(source='get_status_display') class Meta: model = Conference fields = ('id', 'name', 'slug', 'description', 'start_date', 'end_date', 'status', 'venue') class VenueSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ConferenceVenue fields = ('id', 'name', 'address', 'latitude', 'longitudes') class RoomSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Room fields = ('id', 'name', 'venue', 'note')
Add id in the room, venue endpoint
Add id in the room, venue endpoint
Python
mit
praba230890/junction,nava45/junction,ChillarAnand/junction,farhaanbukhsh/junction,praba230890/junction,praba230890/junction,ChillarAnand/junction,farhaanbukhsh/junction,farhaanbukhsh/junction,pythonindia/junction,ChillarAnand/junction,nava45/junction,ChillarAnand/junction,praba230890/junction,pythonindia/junction,pythonindia/junction,nava45/junction,nava45/junction,pythonindia/junction,farhaanbukhsh/junction
--- +++ @@ -15,10 +15,10 @@ class VenueSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ConferenceVenue - fields = ('name', 'address', 'latitude', 'longitudes') + fields = ('id', 'name', 'address', 'latitude', 'longitudes') class RoomSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Room - fields = ('name', 'venue', 'note') + fields = ('id', 'name', 'venue', 'note')
1a88833845776d7592bbdef33571cd2da836cb91
ookoobah/tools.py
ookoobah/tools.py
class BaseTool (object): draw_locks = False def update_cursor(self, mouse): mouse.set_cursor(None) class DrawTool (BaseTool): def __init__(self, block_class): self.block_class = block_class def apply(self, pos, game, editor): old = game.grid.get(pos) if old.__class__ == self.block_class: old.cycle_states() else: game.place_block(pos, self.block_class, not editor) game.grid[pos].locked = editor return True def update_cursor(self, mouse): mouse.set_cursor(self.block_class) class EraseTool (BaseTool): def apply(self, pos, game, editor): game.erase_block(pos) class LockTool (BaseTool): draw_locks = True def apply(self, pos, game, editor): obj = game.grid.get(pos) if obj: obj.locked = not obj.locked class TriggerTool (BaseTool): def apply(self, pos, game, editor): if pos in game.grid: game.grid[pos].cycle_states()
class BaseTool (object): draw_locks = False def update_cursor(self, mouse): mouse.set_cursor(None) class DrawTool (BaseTool): def __init__(self, block_class): self.block_class = block_class def apply(self, pos, game, editor): old = game.grid.get(pos) if old.__class__ == self.block_class: old.cycle_states() else: game.place_block(pos, self.block_class, not editor) game.grid[pos].locked = editor return True def update_cursor(self, mouse): mouse.set_cursor(self.block_class) class EraseTool (BaseTool): def apply(self, pos, game, editor): game.erase_block(pos) return True class LockTool (BaseTool): draw_locks = True def apply(self, pos, game, editor): obj = game.grid.get(pos) if obj: obj.locked = not obj.locked class TriggerTool (BaseTool): def apply(self, pos, game, editor): if pos in game.grid: game.grid[pos].cycle_states()
Return update flag from erase tool.
Return update flag from erase tool. Fixes a bug introduced a couple commits earlier.
Python
mit
vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah
--- +++ @@ -22,6 +22,7 @@ class EraseTool (BaseTool): def apply(self, pos, game, editor): game.erase_block(pos) + return True class LockTool (BaseTool): draw_locks = True
2190e8dbdda5ed926fe9ab1875c0ad0d9bab690b
webparticipation/apps/send_token/tasks.py
webparticipation/apps/send_token/tasks.py
from celery import task from django.core.mail import EmailMessage from webparticipation.apps.ureporter.models import delete_user_from_rapidpro as delete_from @task() def send_verification_token(ureporter): if ureporter.token: subject = 'Hello' body = 'Welcome to ureport. To complete the registration process, ' \ 'use this code to verify your account: ' + str(ureporter.token) + ' .' \ '\n\n-----\nThanks' signature = '\nureport team' recipients = [ureporter.user.email] message = EmailMessage(subject, body + signature, to=recipients) message.send() @task() def delete_user_from_rapidpro(ureporter): delete_from(ureporter)
from celery import task from django.core.mail import EmailMessage from webparticipation.apps.ureporter.models import delete_user_from_rapidpro as delete_from @task() def send_verification_token(ureporter): if ureporter.token: subject = 'U-Report Registration' body = 'Thank you for registering with U-Report. ' \ 'Here is your code to complete your U-Report profile: ' + str(ureporter.token) + ' .' \ '\n\nWe are so happy for you to join us to speak out on the important issues ' \ 'affecting young people in your community.' signature = '\n\n-----\nU-Report\nVoice Matters' \ '\n\nThis is an automated email so please don\'t reply.' \ '\nFor more information about U-Report go to www.ureport.in/about ' \ 'or follow us on Twitter @UReportGlobal' recipients = [ureporter.user.email] message = EmailMessage(subject, body + signature, to=recipients) message.send() @task() def delete_user_from_rapidpro(ureporter): delete_from(ureporter)
Change subject and content of registration email.
Change subject and content of registration email.
Python
agpl-3.0
rapidpro/ureport-web-participation,rapidpro/ureport-web-participation,rapidpro/ureport-web-participation
--- +++ @@ -6,11 +6,15 @@ @task() def send_verification_token(ureporter): if ureporter.token: - subject = 'Hello' - body = 'Welcome to ureport. To complete the registration process, ' \ - 'use this code to verify your account: ' + str(ureporter.token) + ' .' \ - '\n\n-----\nThanks' - signature = '\nureport team' + subject = 'U-Report Registration' + body = 'Thank you for registering with U-Report. ' \ + 'Here is your code to complete your U-Report profile: ' + str(ureporter.token) + ' .' \ + '\n\nWe are so happy for you to join us to speak out on the important issues ' \ + 'affecting young people in your community.' + signature = '\n\n-----\nU-Report\nVoice Matters' \ + '\n\nThis is an automated email so please don\'t reply.' \ + '\nFor more information about U-Report go to www.ureport.in/about ' \ + 'or follow us on Twitter @UReportGlobal' recipients = [ureporter.user.email] message = EmailMessage(subject, body + signature, to=recipients) message.send()
954030c1c7e048e00bda0fe129434b2e9391befd
utensils/views.py
utensils/views.py
# encoding: utf-8 from django.views.generic import ListView from .viewmixins import OrderByMixin, PaginateMixin, SearchFormMixin class BaseListView(PaginateMixin, OrderByMixin, SearchFormMixin, ListView): """ Defines a base list view that supports pagination, ordering and basic search. Supports a filter description that can be used in templates: class ActiveCustomerList(BaseListView): filter_description = u"Active" queryset = Artist.active.all() {% block content %} <h2> {% if filter_description %} {{ filter_description|title }} customers {% else %} Customers {% endif %} </h2> <! -- more template --> {% end block %} """ def get_filter_description(self): if hasattr(self, 'filter_description'): return self.filter_description def get_context_data(self, **kwargs): data = super(BaseListView, self).get_context_data(**kwargs) filter_description = self.get_filter_description() if filter_description: data.update({'filter_description': filter_description}) return data
# encoding: utf-8 from django.views.generic import ListView from .viewmixins import OrderByMixin, PaginateMixin, SearchFormMixin class BaseListView(PaginateMixin, OrderByMixin, SearchFormMixin, ListView): """ Defines a base list view that supports pagination, ordering and basic search. Supports a filter description that can be used in templates: class ActiveCustomerList(BaseListView): filter_description = u"Active" queryset = Customer.active.all() {% block content %} <h2> {% if filter_description %} {{ filter_description|title }} customers {% else %} Customers {% endif %} </h2> <! -- more template --> {% end block %} """ def get_filter_description(self): if hasattr(self, 'filter_description'): return self.filter_description def get_context_data(self, **kwargs): data = super(BaseListView, self).get_context_data(**kwargs) filter_description = self.get_filter_description() if filter_description: data.update({'filter_description': filter_description}) return data
Correct model reference in comments.
Correct model reference in comments.
Python
mit
code-kitchen/django-utensils,code-kitchen/django-utensils,code-kitchen/django-utensils
--- +++ @@ -12,7 +12,7 @@ class ActiveCustomerList(BaseListView): filter_description = u"Active" - queryset = Artist.active.all() + queryset = Customer.active.all() {% block content %}
31f39a8bef65a3ea47c8f2c080b4f0ec769dbfb1
util/meta_line.py
util/meta_line.py
from colors import Colors from line import Line import re prefixes = [ ("Start", "", Colors.GREEN_FG), ("Pass", "", Colors.GREEN_FG), ("Debug", "", Colors.BLUE_FG), ("Error", "", Colors.RED_FG), ("Fail", "", Colors.RED_FG), ("Duration", "s;", Colors.BLUE_FG), ("logElementTree", "", Colors.BLUE_FG), ] class MetaLine(Line): color = Colors.NORMAL prefix = "" body = "" def __init__(self, line): self.body = line for (p, end, c) in prefixes: match = re.compile(".*%s ?: ?" % p).match(line) if match: self.color = c self.prefix = p (_, index) = match.span() body = line[index:] if end != "": index = body.find(end) if index != -1: body = body[:index] body += "\n" self.body = body break def str(self): return "%s%s%s: %s" % (self.color, self.prefix, Colors.NORMAL, self.body)
from colors import Colors from line import Line import re prefixes = [ ("Start", "", Colors.MAGENTA_FG), ("Pass", "", Colors.GREEN_FG), ("Fail", "", Colors.RED_FG), ("Debug", "", Colors.BLUE_FG), ("Error", "", Colors.RED_FG), ("Default", "", Colors.MAGENTA_FG), ("Warning", "", Colors.YELLOW_FG), ("Duration", "s;", Colors.BLUE_FG), ("logElementTree", "", Colors.BLUE_FG), ] class MetaLine(Line): color = Colors.NORMAL prefix = "" body = "" def __init__(self, line): self.body = line if line.find("Waiting for device to boot") != -1: self.color = Colors.CYAN_FG self.prefix = "Instruments" self.body = "Booting device\n" return for (p, end, c) in prefixes: match = re.compile(".*%s ?: ?" % p).match(line) if match: self.color = c self.prefix = p (_, index) = match.span() body = line[index:] if end != "": index = body.find(end) if index != -1: body = body[:index] body += "\n" self.body = body break def str(self): return "%s%s%s: %s" % (self.color, self.prefix, Colors.NORMAL, self.body)
Add support for more instrument output types
Add support for more instrument output types
Python
mit
JBarberU/strawberry_py
--- +++ @@ -3,11 +3,13 @@ import re prefixes = [ - ("Start", "", Colors.GREEN_FG), + ("Start", "", Colors.MAGENTA_FG), ("Pass", "", Colors.GREEN_FG), + ("Fail", "", Colors.RED_FG), ("Debug", "", Colors.BLUE_FG), ("Error", "", Colors.RED_FG), - ("Fail", "", Colors.RED_FG), + ("Default", "", Colors.MAGENTA_FG), + ("Warning", "", Colors.YELLOW_FG), ("Duration", "s;", Colors.BLUE_FG), ("logElementTree", "", Colors.BLUE_FG), ] @@ -19,6 +21,12 @@ def __init__(self, line): self.body = line + if line.find("Waiting for device to boot") != -1: + self.color = Colors.CYAN_FG + self.prefix = "Instruments" + self.body = "Booting device\n" + return + for (p, end, c) in prefixes: match = re.compile(".*%s ?: ?" % p).match(line) if match:
7a6cd5ebe2e2fc357bc4f58409ca177f36814859
glanceclient/common/exceptions.py
glanceclient/common/exceptions.py
# This is here for compatibility purposes. Once all known OpenStack clients # are updated to use glanceclient.exc, this file should be removed from glanceclient.exc import * # noqa
# 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 here for compatibility purposes. Once all known OpenStack clients # are updated to use glanceclient.exc, this file should be removed from glanceclient.exc import * # noqa
Add Apache 2.0 license to source file
Add Apache 2.0 license to source file As per OpenStack licensing guide lines [1]: [H102 H103] Newly contributed Source Code should be licensed under the Apache 2.0 license. [H104] Files with no code shouldn't contain any license header nor comments, and must be left completely empty. [1] http://docs.openstack.org/developer/hacking/#openstack-licensing Change-Id: I15cbb71d028e9297cb49b5aab7d0427f7be36c49
Python
apache-2.0
openstack/python-glanceclient,openstack/python-glanceclient
--- +++ @@ -1,3 +1,15 @@ +# 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 here for compatibility purposes. Once all known OpenStack clients # are updated to use glanceclient.exc, this file should be removed from glanceclient.exc import * # noqa
853bfc4d010f6c80bef6878a356df73a60f09596
test_config.py
test_config.py
import tempfile import shutil import os from voltgrid import ConfigManager def test_config_manager(): c = ConfigManager('voltgrid.conf.example') c.write_envs() def test_config_is_empty(): with tempfile.NamedTemporaryFile() as tmp_f: c = ConfigManager(tmp_f.name) def test_config_not_exist(): c = ConfigManager('does-not-exist') def test_git_config(): git_url = 'git@github.com:voltgrid/voltgrid-pie.git' os.environ['GIT_URL'] = git_url c = ConfigManager() assert(c.git_url == git_url)
import tempfile import shutil import os from voltgrid import ConfigManager VG_CFG = 'voltgrid.conf.example' def test_config_manager(): c = ConfigManager(VG_CFG) c.write_envs() def test_config_is_empty(): with tempfile.NamedTemporaryFile() as tmp_f: c = ConfigManager(tmp_f.name) def test_config_not_exist(): c = ConfigManager('does-not-exist') def test_git_config(): git_url = 'git@github.com:voltgrid/voltgrid-pie.git' os.environ['GIT_URL'] = git_url c = ConfigManager(VG_CFG) assert(c.git_url == git_url)
Fix test loading wrong config
Fix test loading wrong config
Python
bsd-3-clause
voltgrid/voltgrid-pie
--- +++ @@ -4,9 +4,11 @@ from voltgrid import ConfigManager +VG_CFG = 'voltgrid.conf.example' + def test_config_manager(): - c = ConfigManager('voltgrid.conf.example') + c = ConfigManager(VG_CFG) c.write_envs() @@ -22,5 +24,5 @@ def test_git_config(): git_url = 'git@github.com:voltgrid/voltgrid-pie.git' os.environ['GIT_URL'] = git_url - c = ConfigManager() + c = ConfigManager(VG_CFG) assert(c.git_url == git_url)
0d7db5b134aaed2721dff8f7be300878fffa0c44
genestack_client/__init__.py
genestack_client/__init__.py
# -*- coding: utf-8 -*- import sys if not ((2, 7, 5) <= sys.version_info < (3, 0)): sys.stderr.write( 'Python version "%s" is not supported. Required version 2.7.5+, Python 3 is not supported\n' % sys.version ) exit(1) from version import __version__ from genestack_exceptions import (GenestackAuthenticationException, GenestackBaseException, GenestackConnectionFailure, GenestackException, GenestackResponseError, GenestackServerException, GenestackVersionException) from genestack_connection import Connection, Application from file_types import FileTypes from file_permissions import Permissions from metainfo_scalar_values import * from bio_meta_keys import BioMetaKeys from genestack_metainfo import Metainfo from bio_metainfo import BioMetainfo from data_importer import DataImporter from file_initializer import FileInitializer from genome_query import GenomeQuery from utils import get_connection, get_user, make_connection_parser, validate_constant from file_filters import * from share_util import ShareUtil from files_util import FilesUtil, MatchType, SortOrder, SpecialFolders from datasets_util import DatasetsUtil from groups_util import GroupsUtil from organization_util import OrganizationUtil from task_log_viewer import TaskLogViewer from cla import * from expression_navigator import *
# -*- coding: utf-8 -*- import sys if not ((2, 7, 5) <= sys.version_info < (3, 0)): sys.stderr.write( 'Python version "%s" is not supported. Required version 2.7.5+, Python 3 is not supported\n' % sys.version ) exit(1) from version import __version__ from genestack_exceptions import (GenestackAuthenticationException, GenestackBaseException, GenestackConnectionFailure, GenestackException, GenestackResponseError, GenestackServerException, GenestackVersionException) from genestack_connection import Connection, Application from file_types import FileTypes from file_permissions import Permissions from metainfo_scalar_values import * from bio_meta_keys import BioMetaKeys from genestack_metainfo import Metainfo from bio_metainfo import BioMetainfo from data_importer import DataImporter from file_initializer import FileInitializer from genome_query import GenomeQuery from utils import get_connection, get_user, make_connection_parser, validate_constant from file_filters import * from share_util import ShareUtil from files_util import FilesUtil, SortOrder, SpecialFolders from datasets_util import DatasetsUtil from groups_util import GroupsUtil from organization_util import OrganizationUtil from task_log_viewer import TaskLogViewer from cla import * from expression_navigator import *
Delete findMetainfoRelatedTerms method from Genestack Core findMetainfoRelatedTerms is deleted
[JBKB-996] Delete findMetainfoRelatedTerms method from Genestack Core findMetainfoRelatedTerms is deleted
Python
mit
genestack/python-client
--- +++ @@ -27,7 +27,7 @@ from utils import get_connection, get_user, make_connection_parser, validate_constant from file_filters import * from share_util import ShareUtil -from files_util import FilesUtil, MatchType, SortOrder, SpecialFolders +from files_util import FilesUtil, SortOrder, SpecialFolders from datasets_util import DatasetsUtil from groups_util import GroupsUtil from organization_util import OrganizationUtil
ac5b065e948a923f71b5f3bc9e98bcb8791a46c9
git_code_debt/write_logic.py
git_code_debt/write_logic.py
from __future__ import absolute_import from __future__ import unicode_literals def insert_metric_ids(db, metric_ids): for metric_id in metric_ids: db.execute( "INSERT INTO metric_names ('name') VALUES (?)", [metric_id], ) def insert_metric_values(db, metric_values, metric_mapping, commit): for metric_name, value in metric_values.items(): metric_id = metric_mapping[metric_name] db.execute( '\n'.join(( 'INSERT INTO metric_data', '(sha, metric_id, timestamp, running_value)', 'VALUES (?, ?, ?, ?)', )), [commit.sha, metric_id, commit.date, value], ) def insert_metric_changes(db, metrics, metric_mapping, commit): """Insert into the metric_changes tables. :param metrics: `list` of `Metric` objects :param dict metric_mapping: Maps metric names to ids :param Commit commit: """ for metric in metrics: # Sparse table, ignore zero. if metric.value == 0: continue metric_id = metric_mapping[metric.name] db.execute( '\n'.join(( 'INSERT INTO metric_changes', '(sha, metric_id, value)', 'VALUES (?, ?, ?)', )), [commit.sha, metric_id, metric.value], )
from __future__ import absolute_import from __future__ import unicode_literals def insert_metric_ids(db, metric_ids): values = [[x] for x in metric_ids] db.executemany("INSERT INTO metric_names ('name') VALUES (?)", values) def insert_metric_values(db, metric_values, metric_mapping, commit): values = [ [commit.sha, metric_mapping[metric_name], commit.date, value] for metric_name, value in metric_values.items() ] db.executemany( 'INSERT INTO metric_data\n' '(sha, metric_id, timestamp, running_value)\n' 'VALUES (?, ?, ?, ?)\n', values, ) def insert_metric_changes(db, metrics, metric_mapping, commit): """Insert into the metric_changes tables. :param metrics: `list` of `Metric` objects :param dict metric_mapping: Maps metric names to ids :param Commit commit: """ values = [ [commit.sha, metric_mapping[metric.name], metric.value] for metric in metrics # Sparse table, ignore zero. if metric.value != 0 ] db.executemany( 'INSERT INTO metric_changes (sha, metric_id, value) VALUES (?, ?, ?)', values, )
Use executemany instead of execute in write logic
Use executemany instead of execute in write logic
Python
mit
Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt
--- +++ @@ -3,23 +3,21 @@ def insert_metric_ids(db, metric_ids): - for metric_id in metric_ids: - db.execute( - "INSERT INTO metric_names ('name') VALUES (?)", [metric_id], - ) + values = [[x] for x in metric_ids] + db.executemany("INSERT INTO metric_names ('name') VALUES (?)", values) def insert_metric_values(db, metric_values, metric_mapping, commit): - for metric_name, value in metric_values.items(): - metric_id = metric_mapping[metric_name] - db.execute( - '\n'.join(( - 'INSERT INTO metric_data', - '(sha, metric_id, timestamp, running_value)', - 'VALUES (?, ?, ?, ?)', - )), - [commit.sha, metric_id, commit.date, value], - ) + values = [ + [commit.sha, metric_mapping[metric_name], commit.date, value] + for metric_name, value in metric_values.items() + ] + db.executemany( + 'INSERT INTO metric_data\n' + '(sha, metric_id, timestamp, running_value)\n' + 'VALUES (?, ?, ?, ?)\n', + values, + ) def insert_metric_changes(db, metrics, metric_mapping, commit): @@ -29,17 +27,13 @@ :param dict metric_mapping: Maps metric names to ids :param Commit commit: """ - for metric in metrics: + values = [ + [commit.sha, metric_mapping[metric.name], metric.value] + for metric in metrics # Sparse table, ignore zero. - if metric.value == 0: - continue - - metric_id = metric_mapping[metric.name] - db.execute( - '\n'.join(( - 'INSERT INTO metric_changes', - '(sha, metric_id, value)', - 'VALUES (?, ?, ?)', - )), - [commit.sha, metric_id, metric.value], - ) + if metric.value != 0 + ] + db.executemany( + 'INSERT INTO metric_changes (sha, metric_id, value) VALUES (?, ?, ?)', + values, + )
9a746c3ea33057efaf01cb8b700d4ea5d38863bf
tests/regression_test.py
tests/regression_test.py
""" A regression test for computing three kinds of spectrogram. Just to ensure we didn't break anything. """ import numpy as np import os from tfr.files import load_wav from tfr.spectrogram_features import spectrogram_features DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') def test_spectrograms(): for spectrogram_type in ['stft', 'reassigned', 'chromagram']: yield assert_spectrogram_is_ok, spectrogram_type def assert_spectrogram_is_ok(spectrogram_type): x, fs = load_wav(os.path.join(DATA_DIR, 'she_brings_to_me.wav')) X = spectrogram_features(x, fs, block_size=4096, hop_size=2048, spectrogram_type=spectrogram_type, to_log=True) npz_file = os.path.join(DATA_DIR, 'she_brings_to_me_%s.npz' % spectrogram_type) X_expected = np.load(npz_file)['arr_0'] assert np.allclose(X, X_expected)
""" A regression test for computing three kinds of spectrogram. Just to ensure we didn't break anything. """ import numpy as np import os from tfr.files import load_wav from tfr.spectrogram_features import spectrogram_features DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') def test_spectrograms(): for spectrogram_type in ['stft', 'reassigned', 'chromagram']: yield assert_spectrogram_is_ok, spectrogram_type def assert_spectrogram_is_ok(spectrogram_type): x, fs = load_wav(os.path.join(DATA_DIR, 'she_brings_to_me.wav')) X = spectrogram_features(x, fs, block_size=4096, hop_size=2048, spectrogram_type=spectrogram_type, to_log=True) npz_file = os.path.join(DATA_DIR, 'she_brings_to_me_%s.npz' % spectrogram_type) X_expected = np.load(npz_file)['arr_0'] print('spectrogram [%s]: max abs error' % spectrogram_type, abs(X - X_expected).max()) assert np.allclose(X, X_expected)
Print the error in the regression test.
Print the error in the regression test.
Python
mit
bzamecnik/tfr,bzamecnik/tfr
--- +++ @@ -21,4 +21,5 @@ spectrogram_type=spectrogram_type, to_log=True) npz_file = os.path.join(DATA_DIR, 'she_brings_to_me_%s.npz' % spectrogram_type) X_expected = np.load(npz_file)['arr_0'] + print('spectrogram [%s]: max abs error' % spectrogram_type, abs(X - X_expected).max()) assert np.allclose(X, X_expected)
6f6199240009ac91da7e663030125df439d8fe7e
tests/test_trust_list.py
tests/test_trust_list.py
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import unittest import sys from oscrypto import trust_list from asn1crypto.x509 import Certificate if sys.version_info < (3,): byte_cls = str else: byte_cls = bytes class TrustListTests(unittest.TestCase): def test_extract_from_system(self): certs = trust_list.extract_from_system() self.assertIsInstance(certs, list) for cert in certs: self.assertIsInstance(cert, byte_cls) _ = Certificate.load(cert).native
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import unittest import sys from oscrypto import trust_list from asn1crypto.x509 import Certificate if sys.version_info < (3,): byte_cls = str else: byte_cls = bytes class TrustListTests(unittest.TestCase): def test_extract_from_system(self): certs = trust_list.extract_from_system() self.assertIsInstance(certs, list) self.assertLess(10, len(certs)) for cert in certs: self.assertIsInstance(cert, byte_cls) _ = Certificate.load(cert).native
Add more sanity checks to the trust list test
Add more sanity checks to the trust list test
Python
mit
wbond/oscrypto
--- +++ @@ -19,6 +19,7 @@ def test_extract_from_system(self): certs = trust_list.extract_from_system() self.assertIsInstance(certs, list) + self.assertLess(10, len(certs)) for cert in certs: self.assertIsInstance(cert, byte_cls) _ = Certificate.load(cert).native
1aaa2034020297fe78c2a0e12b713b835e13a156
thumborizeme/settings.py
thumborizeme/settings.py
import os # REDIS REDIS_HOST = '127.0.0.1' REDIS_PORT = 6379 HOST = os.environ.get('HOST', 'http://localhost:9000') THUMBOR_HOST = os.environ.get('HOST', 'http://localhost:8001')
import os # REDIS REDIS_HOST = os.environ.get('REDIS_URL', '127.0.0.1') REDIS_PORT = os.environ.get('REDIS_PORT', 6379) HOST = os.environ.get('HOST', 'http://localhost:9000') THUMBOR_HOST = os.environ.get('HOST', 'http://localhost:8001')
Change redis url and redis port
Change redis url and redis port
Python
mit
heynemann/thumborizeme,heynemann/thumborizeme,heynemann/thumborizeme
--- +++ @@ -1,8 +1,8 @@ import os # REDIS -REDIS_HOST = '127.0.0.1' -REDIS_PORT = 6379 +REDIS_HOST = os.environ.get('REDIS_URL', '127.0.0.1') +REDIS_PORT = os.environ.get('REDIS_PORT', 6379) HOST = os.environ.get('HOST', 'http://localhost:9000') THUMBOR_HOST = os.environ.get('HOST', 'http://localhost:8001')
cd70e1150d3822a0f158e06c382ad8841760040e
mla_game/apps/transcript/management/commands/update_stats_for_all_eligible_transcripts.py
mla_game/apps/transcript/management/commands/update_stats_for_all_eligible_transcripts.py
from django.core.management.base import BaseCommand from django.db.models import Prefetch from mla_game.apps.transcript.tasks import update_transcript_stats from ...models import ( Transcript, TranscriptPhraseVote, TranscriptPhraseCorrection, ) class Command(BaseCommand): help = '''Find all Transcripts with votes or corrections and update stats for that transcript''' def handle(self, *args, **options): eligible_transcripts = set() transcript_qs = Transcript.objects.only('pk') downvotes = TranscriptPhraseVote.objects.filter( upvote=False ).prefetch_related( Prefetch('transcript_phrase__transcript', queryset=transcript_qs) ) upvotes = TranscriptPhraseCorrection.objects.all().prefetch_related( Prefetch('transcript_phrase__transcript', queryset=transcript_qs) ) eligible_transcripts.update( [vote.transcript_phrase.transcript.pk for vote in downvotes] ) eligible_transcripts.update( [vote.transcript_phrase.transcript.pk for vote in upvotes] ) transcripts_to_process = Transcript.objects.filter( pk__in=eligible_transcripts).only('pk') for transcript in transcripts_to_process: update_transcript_stats(transcript)
from django.core.management.base import BaseCommand from django.db.models import Prefetch from mla_game.apps.transcript.tasks import update_transcript_stats from ...models import ( Transcript, TranscriptPhraseVote, TranscriptPhraseCorrection, ) class Command(BaseCommand): help = '''Find all Transcripts with votes or corrections and update stats for that transcript''' def handle(self, *args, **options): eligible_transcripts = set() transcript_qs = Transcript.objects.only('pk') votes = TranscriptPhraseVote.objects.filter( upvote__in=[True, False] ).prefetch_related( Prefetch('transcript_phrase__transcript', queryset=transcript_qs) ) corrections = TranscriptPhraseCorrection.objects.all().prefetch_related( Prefetch('transcript_phrase__transcript', queryset=transcript_qs) ) eligible_transcripts.update( [vote.transcript_phrase.transcript.pk for vote in votes] ) eligible_transcripts.update( [correction.transcript_phrase.transcript.pk for correction in corrections] ) transcripts_to_process = Transcript.objects.filter( pk__in=eligible_transcripts).only('pk') for transcript in transcripts_to_process: update_transcript_stats(transcript)
Update management command for various changes
Update management command for various changes
Python
mit
WGBH/FixIt,WGBH/FixIt,WGBH/FixIt
--- +++ @@ -15,20 +15,20 @@ def handle(self, *args, **options): eligible_transcripts = set() transcript_qs = Transcript.objects.only('pk') - downvotes = TranscriptPhraseVote.objects.filter( - upvote=False + votes = TranscriptPhraseVote.objects.filter( + upvote__in=[True, False] ).prefetch_related( Prefetch('transcript_phrase__transcript', queryset=transcript_qs) ) - - upvotes = TranscriptPhraseCorrection.objects.all().prefetch_related( + corrections = TranscriptPhraseCorrection.objects.all().prefetch_related( Prefetch('transcript_phrase__transcript', queryset=transcript_qs) ) + eligible_transcripts.update( - [vote.transcript_phrase.transcript.pk for vote in downvotes] + [vote.transcript_phrase.transcript.pk for vote in votes] ) eligible_transcripts.update( - [vote.transcript_phrase.transcript.pk for vote in upvotes] + [correction.transcript_phrase.transcript.pk for correction in corrections] ) transcripts_to_process = Transcript.objects.filter(
850d5be6b5a53bafd0197e1454da2583abb6db77
test/test_pipeline/components/regression/test_random_forests.py
test/test_pipeline/components/regression/test_random_forests.py
import unittest from autosklearn.pipeline.components.regression.random_forest import RandomForest from autosklearn.pipeline.util import _test_regressor, _test_regressor_iterative_fit import sklearn.metrics class RandomForestComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(RandomForest) self.assertAlmostEqual(0.40965687834764064, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) def test_default_configuration_sparse(self): for i in range(10): predictions, targets = _test_regressor(RandomForest, sparse=True) self.assertAlmostEqual(0.24147637508106434, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) def test_default_configuration_iterative_fit(self): for i in range(10): predictions, targets = \ _test_regressor_iterative_fit(RandomForest) self.assertAlmostEqual(0.40965687834764064, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions))
import unittest from autosklearn.pipeline.components.regression.random_forest import RandomForest from autosklearn.pipeline.util import _test_regressor, _test_regressor_iterative_fit import sklearn.metrics class RandomForestComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(RandomForest) self.assertAlmostEqual(0.41795829411621988, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) def test_default_configuration_sparse(self): for i in range(10): predictions, targets = _test_regressor(RandomForest, sparse=True) self.assertAlmostEqual(0.24225685933770469, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) def test_default_configuration_iterative_fit(self): for i in range(10): predictions, targets = \ _test_regressor_iterative_fit(RandomForest) self.assertAlmostEqual(0.41795829411621988, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) def test_default_configuration_iterative_fit_sparse(self): for i in range(10): predictions, targets = \ _test_regressor_iterative_fit(RandomForest, sparse=True) self.assertAlmostEqual(0.24225685933770469, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions))
ADD test to test iterative fit sparse
ADD test to test iterative fit sparse
Python
bsd-3-clause
automl/auto-sklearn,automl/auto-sklearn
--- +++ @@ -11,19 +11,25 @@ for i in range(10): predictions, targets = _test_regressor(RandomForest) - self.assertAlmostEqual(0.40965687834764064, + self.assertAlmostEqual(0.41795829411621988, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) - def test_default_configuration_sparse(self): for i in range(10): predictions, targets = _test_regressor(RandomForest, sparse=True) - self.assertAlmostEqual(0.24147637508106434, + self.assertAlmostEqual(0.24225685933770469, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) def test_default_configuration_iterative_fit(self): for i in range(10): predictions, targets = \ _test_regressor_iterative_fit(RandomForest) - self.assertAlmostEqual(0.40965687834764064, + self.assertAlmostEqual(0.41795829411621988, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) + + def test_default_configuration_iterative_fit_sparse(self): + for i in range(10): + predictions, targets = \ + _test_regressor_iterative_fit(RandomForest, sparse=True) + self.assertAlmostEqual(0.24225685933770469, + sklearn.metrics.r2_score(y_true=targets, y_pred=predictions))
c9abba3a9ca6ccf1a9bed5fad5cda12557b3266c
tests/chainer_tests/training_tests/extensions_tests/test_plot_report.py
tests/chainer_tests/training_tests/extensions_tests/test_plot_report.py
import unittest import warnings from chainer import testing from chainer.training import extensions class TestPlotReport(unittest.TestCase): def test_available(self): try: import matplotlib # NOQA available = True except ImportError: available = False with warnings.catch_warnings(record=True) as w: self.assertEqual(extensions.PlotReport.available(), available) # It shows warning only when matplotlib.pyplot is not available if available: self.assertEqual(len(w), 0) else: self.assertEqual(len(w), 1) @unittest.skipUnless( extensions.PlotReport.available(), 'matplotlib is not installed') def test_lazy_import(self): # To support python2, we do not use self.assertWarns() with warnings.catch_warnings(record=True) as w: import matplotlib matplotlib.use('Agg') self.assertEqual(len(w), 0) testing.run_module(__name__, __file__)
import unittest import warnings from chainer import testing from chainer.training import extensions class TestPlotReport(unittest.TestCase): def test_available(self): try: import matplotlib # NOQA available = True except ImportError: available = False with warnings.catch_warnings(record=True) as w: self.assertEqual(extensions.PlotReport.available(), available) # It shows warning only when matplotlib is not available if available: self.assertEqual(len(w), 0) else: self.assertEqual(len(w), 1) # In Python 2 the above test does not raise UserWarning, # so we use plot_report._available instead of PlotReport.available() @unittest.skipUnless( extensions.plot_report._available, 'matplotlib is not installed') def test_lazy_import(self): # To support python2, we do not use self.assertWarns() with warnings.catch_warnings(record=True) as w: import matplotlib matplotlib.use('Agg') self.assertEqual(len(w), 0) testing.run_module(__name__, __file__)
Use plot_report._available instead of available()
Use plot_report._available instead of available()
Python
mit
hvy/chainer,jnishi/chainer,niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,hvy/chainer,chainer/chainer,jnishi/chainer,niboshi/chainer,okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,hvy/chainer,okuta/chainer,okuta/chainer,chainer/chainer,hvy/chainer,ktnyt/chainer,ktnyt/chainer,wkentaro/chainer,jnishi/chainer,keisuke-umezawa/chainer,tkerola/chainer,wkentaro/chainer,ktnyt/chainer,ronekko/chainer,keisuke-umezawa/chainer,ktnyt/chainer,aonotas/chainer,rezoo/chainer,kashif/chainer,anaruse/chainer,jnishi/chainer,chainer/chainer,okuta/chainer,niboshi/chainer,niboshi/chainer,pfnet/chainer,chainer/chainer
--- +++ @@ -17,14 +17,16 @@ with warnings.catch_warnings(record=True) as w: self.assertEqual(extensions.PlotReport.available(), available) - # It shows warning only when matplotlib.pyplot is not available + # It shows warning only when matplotlib is not available if available: self.assertEqual(len(w), 0) else: self.assertEqual(len(w), 1) + # In Python 2 the above test does not raise UserWarning, + # so we use plot_report._available instead of PlotReport.available() @unittest.skipUnless( - extensions.PlotReport.available(), 'matplotlib is not installed') + extensions.plot_report._available, 'matplotlib is not installed') def test_lazy_import(self): # To support python2, we do not use self.assertWarns() with warnings.catch_warnings(record=True) as w:
ca8b4640a858936f1f1cfdbed8e5ef1e771fe310
jugfile.py
jugfile.py
def compfeats(url): print 'Feats called: ', url return url def nfold(imgs, feats): print 'nfold called: ', imgs, feats imgs = ['images/img1.png','images/img2.png'] feats = [Compute('featurecomputation',compfeats,url=img) for img in imgs] tenfold = Compute('10 fold',nfold,imgs=imgs,feats=feats)
def compfeats(url): print 'Feats called: ', url return url+'feats' def nfold(imgs, feats): print 'nfold called: ', imgs, feats imgs = ['images/img1.png','images/img2.png'] feats = [Compute('featurecomputation',compfeats,url=img) for img in imgs] tenfold = Compute('10 fold',nfold,imgs=imgs,feats=feats)
Make sure we're calling functions correctly
Make sure we're calling functions correctly
Python
mit
luispedro/jug,luispedro/jug,unode/jug,unode/jug
--- +++ @@ -1,6 +1,6 @@ def compfeats(url): print 'Feats called: ', url - return url + return url+'feats' def nfold(imgs, feats): print 'nfold called: ', imgs, feats
060eeae718154c9b131a36c45e34d745530ff20d
launch_control/models/sw_image.py
launch_control/models/sw_image.py
""" Module with the SoftwareImage model. """ from launch_control.utils.json.pod import PlainOldData class SoftwareImage(PlainOldData): """ Model for representing software images. """ __slots__ = ('name',) def __init__(self, desc): self.name = name
""" Module with the SoftwareImage model. """ from launch_control.utils.json.pod import PlainOldData class SoftwareImage(PlainOldData): """ Model for representing software images. """ __slots__ = ('name',) def __init__(self, name): self.name = name
Fix slot name in SoftwareImage
Fix slot name in SoftwareImage
Python
agpl-3.0
Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server
--- +++ @@ -12,5 +12,5 @@ __slots__ = ('name',) - def __init__(self, desc): + def __init__(self, name): self.name = name
94737c504ffdf55ddc8a0a24561f52fc531b6047
djangorest_alchemy/apibuilder.py
djangorest_alchemy/apibuilder.py
""" API Builder Build dynamic API based on the provided SQLAlchemy model """ from managers import AlchemyModelManager from viewsets import AlchemyModelViewSet from rest_framework_nested import routers class APIModelBuilder(object): def __init__(self, models, base_managers, base_viewsets=None, *args, **kwargs): self.models = models if not isinstance(base_managers, (tuple, list)): base_managers = [base_managers] if not isinstance(base_managers, tuple): base_managers = tuple(base_managers) if base_viewsets is None: base_viewsets = (AlchemyModelViewSet,) self.base_managers = base_managers self.base_viewsets = base_viewsets @property def urls(self): router = routers.SimpleRouter() for model in self.models: manager = type( str('{}Manager'.format(model.__name__)), self.base_managers + (AlchemyModelManager,), { 'model_class': model, } ) viewset = type( str('{}ModelViewSet'.format(model.__name__)), self.base_viewsets, { 'manager_class': manager, 'paginate_by': 10, } ) router.register('data-api/' + model.__name__.lower() + 's', viewset, base_name=model.__name__) return router.urls
""" API Builder Build dynamic API based on the provided SQLAlchemy model """ from managers import AlchemyModelManager from viewsets import AlchemyModelViewSet from routers import ReadOnlyRouter class APIModelBuilder(object): def __init__(self, models, base_managers, base_viewsets=None, *args, **kwargs): self.models = models if not isinstance(base_managers, (tuple, list)): base_managers = [base_managers] if not isinstance(base_managers, tuple): base_managers = tuple(base_managers) if base_viewsets is None: base_viewsets = (AlchemyModelViewSet,) self.base_managers = base_managers self.base_viewsets = base_viewsets @property def urls(self): router = ReadOnlyRouter() for model in self.models: manager = type( str('{}Manager'.format(model.__name__)), self.base_managers + (AlchemyModelManager,), { 'model_class': model, } ) viewset = type( str('{}ModelViewSet'.format(model.__name__)), self.base_viewsets, { 'manager_class': manager, 'paginate_by': 10, } ) router.register('data-api/' + model.__name__.lower() + 's', viewset, base_name=model.__name__) return router.urls
Change to use read-only router for data-apis
Change to use read-only router for data-apis
Python
mit
dealertrack/djangorest-alchemy,pombredanne/djangorest-alchemy
--- +++ @@ -4,7 +4,7 @@ """ from managers import AlchemyModelManager from viewsets import AlchemyModelViewSet -from rest_framework_nested import routers +from routers import ReadOnlyRouter class APIModelBuilder(object): @@ -27,7 +27,7 @@ @property def urls(self): - router = routers.SimpleRouter() + router = ReadOnlyRouter() for model in self.models: manager = type(
6dcd30cba47798e8d6f2ef99f2b6c13cf7d60cad
migrations/versions/216_add_folder_separator_column_for_generic_.py
migrations/versions/216_add_folder_separator_column_for_generic_.py
"""add folder_separator column for generic imap Revision ID: 4f8e995d1dba Revises: 31aae1ecb374 Create Date: 2016-02-02 01:17:24.746355 """ # revision identifiers, used by Alembic. revision = '4f8e995d1dba' down_revision = '4bfecbcc7dbd' from alembic import op from sqlalchemy.sql import text def upgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) conn.execute(text("""ALTER TABLE genericaccount ADD COLUMN folder_separator varchar(16), ADD COLUMN folder_prefix varchar(191);""")) def downgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) conn.execute(text("ALTER TABLE genericaccount DROP COLUMN folder_separator, DROP COLUMN folder_prefix"))
"""add folder_separator column for generic imap Revision ID: 4f8e995d1dba Revises: 31aae1ecb374 Create Date: 2016-02-02 01:17:24.746355 """ # revision identifiers, used by Alembic. revision = '4f8e995d1dba' down_revision = '4bfecbcc7dbd' from alembic import op from sqlalchemy.sql import text def upgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) conn.execute(text("ALTER TABLE genericaccount ADD COLUMN folder_separator varchar(16)")) conn.execute(text("ALTER TABLE genericaccount ADD COLUMN folder_prefix varchar(191)")) def downgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) conn.execute(text("ALTER TABLE genericaccount DROP COLUMN folder_separator")) conn.execute(text("ALTER TABLE genericaccount DROP COLUMN folder_prefix"))
Revert "merge alter statements together."
Revert "merge alter statements together." This reverts commit 0ed919a86c835956596e9e897423e6176625f158. Reverting all IMAP folder handling patches.
Python
agpl-3.0
closeio/nylas,nylas/sync-engine,closeio/nylas,jobscore/sync-engine,nylas/sync-engine,jobscore/sync-engine,nylas/sync-engine,closeio/nylas,nylas/sync-engine,jobscore/sync-engine,jobscore/sync-engine,closeio/nylas
--- +++ @@ -17,11 +17,12 @@ def upgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) - conn.execute(text("""ALTER TABLE genericaccount ADD COLUMN folder_separator varchar(16), - ADD COLUMN folder_prefix varchar(191);""")) + conn.execute(text("ALTER TABLE genericaccount ADD COLUMN folder_separator varchar(16)")) + conn.execute(text("ALTER TABLE genericaccount ADD COLUMN folder_prefix varchar(191)")) def downgrade(): conn = op.get_bind() conn.execute(text("set @@lock_wait_timeout = 20;")) - conn.execute(text("ALTER TABLE genericaccount DROP COLUMN folder_separator, DROP COLUMN folder_prefix")) + conn.execute(text("ALTER TABLE genericaccount DROP COLUMN folder_separator")) + conn.execute(text("ALTER TABLE genericaccount DROP COLUMN folder_prefix"))
f72b7ec93401bc817245c49790303fd925adb2c4
server/plugins/remoteconnection/machine_detail_remote_connection.py
server/plugins/remoteconnection/machine_detail_remote_connection.py
"""Machine detail plugin to allow easy VNC or SSH connections.""" import sal.plugin from server.models import Machine, SalSetting from server.utils import get_setting class RemoteConnection(sal.plugin.DetailPlugin): description = "Initiate VNC or SSH connections from a machine detail page." supported_os_families = [sal.plugin.OSFamilies.darwin] def get_context(self, queryset, **kwargs): context = self.super_get_context(queryset, **kwargs) ip_address = "" if queryset.conditions.count() > 0: try: ip_addresses = queryset.conditions.get( condition_name="ipv4_address").condition_data # Machines may have multiple IPs. Just use the first. ip_address = ip_addresses.split(",")[0] except Machine.DoesNotExist: pass context['ssh_account'] = get_setting(name='ssh_account', default='').replace('@', '') context["ssh_url"] = "ssh://{}{}".format(context['ssh_account'], ip_address) context["vnc_url"] = "vnc://{}{}".format(context['ssh_account'], ip_address) return context
"""Machine detail plugin to allow easy VNC or SSH connections.""" import sal.plugin from server.models import Machine, SalSetting from server.utils import get_setting class RemoteConnection(sal.plugin.DetailPlugin): description = "Initiate VNC or SSH connections from a machine detail page." supported_os_families = [sal.plugin.OSFamilies.darwin] def get_context(self, queryset, **kwargs): context = self.super_get_context(queryset, **kwargs) ip_address = "" if queryset.conditions.count() > 0: try: ip_addresses = queryset.conditions.get( condition_name="ipv4_address").condition_data # Machines may have multiple IPs. Just use the first. ip_address = ip_addresses.split(",")[0] except Machine.DoesNotExist: pass account = get_setting(name='ssh_account', default='').strip() context['ssh_account'] = account delimiter = '' if not account else '@' context["ssh_url"] = "ssh://{}{}{}".format(account, delimiter, ip_address) context["vnc_url"] = "vnc://{}{}{}".format(account, delimiter, ip_address) return context
Fix user account prepending to machine detail remote connection plugin.
Fix user account prepending to machine detail remote connection plugin.
Python
apache-2.0
salopensource/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal
--- +++ @@ -24,8 +24,10 @@ except Machine.DoesNotExist: pass - context['ssh_account'] = get_setting(name='ssh_account', default='').replace('@', '') - context["ssh_url"] = "ssh://{}{}".format(context['ssh_account'], ip_address) - context["vnc_url"] = "vnc://{}{}".format(context['ssh_account'], ip_address) + account = get_setting(name='ssh_account', default='').strip() + context['ssh_account'] = account + delimiter = '' if not account else '@' + context["ssh_url"] = "ssh://{}{}{}".format(account, delimiter, ip_address) + context["vnc_url"] = "vnc://{}{}{}".format(account, delimiter, ip_address) return context
af173cbf4ca75c0c1dae459d2da8a1ebf54d0e50
debug_toolbar/panels/redirects.py
debug_toolbar/panels/redirects.py
from django.template.response import SimpleTemplateResponse from django.utils.translation import gettext_lazy as _ from debug_toolbar.panels import Panel class RedirectsPanel(Panel): """ Panel that intercepts redirects and displays a page with debug info. """ has_content = False nav_title = _("Intercept redirects") def process_request(self, request): response = super().process_request(request) if 300 <= int(response.status_code) < 400: redirect_to = response.get("Location", None) if redirect_to: status_line = "{} {}".format( response.status_code, response.reason_phrase ) cookies = response.cookies context = {"redirect_to": redirect_to, "status_line": status_line} # Using SimpleTemplateResponse avoids running global context processors. response = SimpleTemplateResponse( "debug_toolbar/redirect.html", context ) response.cookies = cookies response.render() return response
from django.template.response import SimpleTemplateResponse from django.utils.translation import gettext_lazy as _ from debug_toolbar.panels import Panel class RedirectsPanel(Panel): """ Panel that intercepts redirects and displays a page with debug info. """ has_content = False nav_title = _("Intercept redirects") def process_request(self, request): response = super().process_request(request) if 300 <= response.status_code < 400: redirect_to = response.get("Location", None) if redirect_to: status_line = "{} {}".format( response.status_code, response.reason_phrase ) cookies = response.cookies context = {"redirect_to": redirect_to, "status_line": status_line} # Using SimpleTemplateResponse avoids running global context processors. response = SimpleTemplateResponse( "debug_toolbar/redirect.html", context ) response.cookies = cookies response.render() return response
Remove unnecessary coerce to int
Remove unnecessary coerce to int Since Django commit https://github.com/django/django/commit/190d2ff4a7a392adfe0b12552bd71871791d87aa HttpResponse.status_code is always an int.
Python
bsd-3-clause
tim-schilling/django-debug-toolbar,spookylukey/django-debug-toolbar,spookylukey/django-debug-toolbar,jazzband/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,tim-schilling/django-debug-toolbar,jazzband/django-debug-toolbar,tim-schilling/django-debug-toolbar,jazzband/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,spookylukey/django-debug-toolbar
--- +++ @@ -15,7 +15,7 @@ def process_request(self, request): response = super().process_request(request) - if 300 <= int(response.status_code) < 400: + if 300 <= response.status_code < 400: redirect_to = response.get("Location", None) if redirect_to: status_line = "{} {}".format(
852989f9899593148d8f16b49142979c6ee509f2
offenerhaushalt/default_settings.py
offenerhaushalt/default_settings.py
DEBUG = True SECRET_KEY = 'no' SITES_FILE = 'sites.yaml' FREEZER_DESTINATION = '../build' FREEZER_REMOVE_EXTRA_FILES = True FLATPAGES_AUTO_RELOAD = True
DEBUG = True ASSETS_DEBUG = True SECRET_KEY = 'no' SITES_FILE = 'sites.yaml' FREEZER_DESTINATION = '../build' FREEZER_REMOVE_EXTRA_FILES = True FLATPAGES_AUTO_RELOAD = True
Switch assets to debug by default.
Switch assets to debug by default.
Python
mit
Opendatal/offenerhaushalt.de,Opendatal/offenerhaushalt.de,Opendatal/offenerhaushalt.de
--- +++ @@ -1,4 +1,5 @@ DEBUG = True +ASSETS_DEBUG = True SECRET_KEY = 'no' SITES_FILE = 'sites.yaml'
707f09d7d8f2c1e3ad37947a3084acb90faf84cf
IPython/extensions/tests/test_storemagic.py
IPython/extensions/tests/test_storemagic.py
import tempfile, os import nose.tools as nt ip = get_ipython() ip.magic('load_ext storemagic') def test_store_restore(): ip.user_ns['foo'] = 78 ip.magic('alias bar echo "hello"') tmpd = tempfile.mkdtemp() ip.magic('cd ' + tmpd) ip.magic('store foo') ip.magic('store bar') # Check storing nt.assert_equal(ip.db['autorestore/foo'], 78) nt.assert_in('bar', ip.db['stored_aliases']) # Remove those items ip.user_ns.pop('foo', None) ip.alias_manager.undefine_alias('bar') ip.magic('cd -') ip.user_ns['_dh'][:] = [] # Check restoring ip.magic('store -r') nt.assert_equal(ip.user_ns['foo'], 78) nt.assert_in('bar', ip.alias_manager.alias_table) nt.assert_in(tmpd, ip.user_ns['_dh']) os.rmdir(tmpd)
import tempfile, os import nose.tools as nt ip = get_ipython() ip.magic('load_ext storemagic') def test_store_restore(): ip.user_ns['foo'] = 78 ip.magic('alias bar echo "hello"') tmpd = tempfile.mkdtemp() ip.magic('cd ' + tmpd) ip.magic('store foo') ip.magic('store bar') # Check storing nt.assert_equal(ip.db['autorestore/foo'], 78) nt.assert_in('bar', ip.db['stored_aliases']) # Remove those items ip.user_ns.pop('foo', None) ip.alias_manager.undefine_alias('bar') ip.magic('cd -') ip.user_ns['_dh'][:] = [] # Check restoring ip.magic('store -r') nt.assert_equal(ip.user_ns['foo'], 78) nt.assert_in('bar', ip.alias_manager.alias_table) nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh']) os.rmdir(tmpd)
Store magic test. On MacOSX the temp dir in /var is symlinked into /private/var thus making this comparison fail. This is solved by using os.path.realpath to expand the tempdir into is's real directory.
Store magic test. On MacOSX the temp dir in /var is symlinked into /private/var thus making this comparison fail. This is solved by using os.path.realpath to expand the tempdir into is's real directory.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
--- +++ @@ -27,6 +27,6 @@ ip.magic('store -r') nt.assert_equal(ip.user_ns['foo'], 78) nt.assert_in('bar', ip.alias_manager.alias_table) - nt.assert_in(tmpd, ip.user_ns['_dh']) + nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh']) os.rmdir(tmpd)
617437824c875f368e8244bc6d9373217f15cb7d
website/project/utils.py
website/project/utils.py
from .views import node # Alias the project serializer serialize_node = node._view_project
# -*- coding: utf-8 -*- """Various node-related utilities.""" from website.project.views import node from website.project.views import file as file_views # Alias the project serializer serialize_node = node._view_project # File rendering utils get_cache_content = file_views.get_cache_content get_cache_path = file_views.get_cache_path prepare_file = file_views.prepare_file
Add aliases for MFR-related utilites
Add aliases for MFR-related utilites
Python
apache-2.0
revanthkolli/osf.io,Johnetordoff/osf.io,chrisseto/osf.io,felliott/osf.io,barbour-em/osf.io,emetsger/osf.io,njantrania/osf.io,danielneis/osf.io,caseyrygt/osf.io,emetsger/osf.io,crcresearch/osf.io,danielneis/osf.io,caseyrygt/osf.io,zachjanicki/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,jmcarp/osf.io,leb2dg/osf.io,jinluyuan/osf.io,icereval/osf.io,wearpants/osf.io,cldershem/osf.io,mattclark/osf.io,mluo613/osf.io,rdhyee/osf.io,DanielSBrown/osf.io,mfraezz/osf.io,kch8qx/osf.io,revanthkolli/osf.io,CenterForOpenScience/osf.io,acshi/osf.io,HalcyonChimera/osf.io,kch8qx/osf.io,mluo613/osf.io,billyhunt/osf.io,billyhunt/osf.io,petermalcolm/osf.io,rdhyee/osf.io,cosenal/osf.io,icereval/osf.io,Nesiehr/osf.io,HarryRybacki/osf.io,TomHeatwole/osf.io,abought/osf.io,cldershem/osf.io,billyhunt/osf.io,lamdnhan/osf.io,Ghalko/osf.io,petermalcolm/osf.io,DanielSBrown/osf.io,mluo613/osf.io,danielneis/osf.io,bdyetton/prettychart,sbt9uc/osf.io,Ghalko/osf.io,Nesiehr/osf.io,amyshi188/osf.io,felliott/osf.io,Johnetordoff/osf.io,chennan47/osf.io,caseyrygt/osf.io,aaxelb/osf.io,zamattiac/osf.io,arpitar/osf.io,bdyetton/prettychart,mattclark/osf.io,rdhyee/osf.io,crcresearch/osf.io,ticklemepierce/osf.io,revanthkolli/osf.io,haoyuchen1992/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,njantrania/osf.io,abought/osf.io,kushG/osf.io,revanthkolli/osf.io,TomHeatwole/osf.io,zachjanicki/osf.io,njantrania/osf.io,samchrisinger/osf.io,kushG/osf.io,kushG/osf.io,haoyuchen1992/osf.io,mattclark/osf.io,jeffreyliu3230/osf.io,cslzchen/osf.io,TomHeatwole/osf.io,jnayak1/osf.io,zamattiac/osf.io,billyhunt/osf.io,jeffreyliu3230/osf.io,abought/osf.io,kwierman/osf.io,brandonPurvis/osf.io,jolene-esposito/osf.io,saradbowman/osf.io,sloria/osf.io,chrisseto/osf.io,samanehsan/osf.io,jnayak1/osf.io,laurenrevere/osf.io,chennan47/osf.io,TomBaxter/osf.io,fabianvf/osf.io,cwisecarver/osf.io,sloria/osf.io,acshi/osf.io,chennan47/osf.io,caneruguz/osf.io,brandonPurvis/osf.io,GaryKriebel/osf.io,ticklemepierce/osf.io,alexschiller/osf.io,doublebits/osf.io,AndrewSallans/osf.io,samanehsan/osf.io,jmcarp/osf.io,GaryKriebel/osf.io,dplorimer/osf,KAsante95/osf.io,chrisseto/osf.io,caneruguz/osf.io,KAsante95/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,HarryRybacki/osf.io,mluke93/osf.io,RomanZWang/osf.io,GageGaskins/osf.io,wearpants/osf.io,njantrania/osf.io,zachjanicki/osf.io,jmcarp/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,MerlinZhang/osf.io,aaxelb/osf.io,kwierman/osf.io,himanshuo/osf.io,zachjanicki/osf.io,brianjgeiger/osf.io,samanehsan/osf.io,GaryKriebel/osf.io,emetsger/osf.io,saradbowman/osf.io,KAsante95/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,brandonPurvis/osf.io,Ghalko/osf.io,himanshuo/osf.io,icereval/osf.io,mfraezz/osf.io,leb2dg/osf.io,RomanZWang/osf.io,sbt9uc/osf.io,caseyrollins/osf.io,asanfilippo7/osf.io,haoyuchen1992/osf.io,wearpants/osf.io,samchrisinger/osf.io,binoculars/osf.io,mluke93/osf.io,alexschiller/osf.io,jnayak1/osf.io,cwisecarver/osf.io,samchrisinger/osf.io,mluke93/osf.io,ZobairAlijan/osf.io,bdyetton/prettychart,hmoco/osf.io,cosenal/osf.io,brandonPurvis/osf.io,TomBaxter/osf.io,kch8qx/osf.io,hmoco/osf.io,adlius/osf.io,emetsger/osf.io,binoculars/osf.io,adlius/osf.io,fabianvf/osf.io,zkraime/osf.io,samanehsan/osf.io,Johnetordoff/osf.io,dplorimer/osf,HarryRybacki/osf.io,cosenal/osf.io,samchrisinger/osf.io,Nesiehr/osf.io,reinaH/osf.io,alexschiller/osf.io,zkraime/osf.io,jeffreyliu3230/osf.io,fabianvf/osf.io,mluo613/osf.io,lyndsysimon/osf.io,baylee-d/osf.io,reinaH/osf.io,jinluyuan/osf.io,dplorimer/osf,MerlinZhang/osf.io,acshi/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,dplorimer/osf,laurenrevere/osf.io,caseyrygt/osf.io,ckc6cz/osf.io,arpitar/osf.io,SSJohns/osf.io,RomanZWang/osf.io,erinspace/osf.io,alexschiller/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,ticklemepierce/osf.io,CenterForOpenScience/osf.io,jmcarp/osf.io,pattisdr/osf.io,felliott/osf.io,TomHeatwole/osf.io,AndrewSallans/osf.io,pattisdr/osf.io,laurenrevere/osf.io,chrisseto/osf.io,adlius/osf.io,RomanZWang/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,DanielSBrown/osf.io,jinluyuan/osf.io,danielneis/osf.io,SSJohns/osf.io,cwisecarver/osf.io,reinaH/osf.io,mluo613/osf.io,caneruguz/osf.io,cwisecarver/osf.io,doublebits/osf.io,doublebits/osf.io,haoyuchen1992/osf.io,mluke93/osf.io,acshi/osf.io,jinluyuan/osf.io,kushG/osf.io,lamdnhan/osf.io,barbour-em/osf.io,sbt9uc/osf.io,caneruguz/osf.io,HalcyonChimera/osf.io,GageGaskins/osf.io,billyhunt/osf.io,zamattiac/osf.io,jeffreyliu3230/osf.io,doublebits/osf.io,hmoco/osf.io,amyshi188/osf.io,Ghalko/osf.io,baylee-d/osf.io,sbt9uc/osf.io,GageGaskins/osf.io,cldershem/osf.io,petermalcolm/osf.io,GaryKriebel/osf.io,TomBaxter/osf.io,brianjgeiger/osf.io,himanshuo/osf.io,ZobairAlijan/osf.io,kch8qx/osf.io,MerlinZhang/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,jolene-esposito/osf.io,kwierman/osf.io,erinspace/osf.io,rdhyee/osf.io,wearpants/osf.io,DanielSBrown/osf.io,acshi/osf.io,ckc6cz/osf.io,arpitar/osf.io,Nesiehr/osf.io,cldershem/osf.io,caseyrollins/osf.io,asanfilippo7/osf.io,jolene-esposito/osf.io,sloria/osf.io,lyndsysimon/osf.io,zamattiac/osf.io,alexschiller/osf.io,lamdnhan/osf.io,ZobairAlijan/osf.io,asanfilippo7/osf.io,Johnetordoff/osf.io,reinaH/osf.io,zkraime/osf.io,brianjgeiger/osf.io,ticklemepierce/osf.io,binoculars/osf.io,himanshuo/osf.io,cosenal/osf.io,kch8qx/osf.io,amyshi188/osf.io,abought/osf.io,mfraezz/osf.io,KAsante95/osf.io,monikagrabowska/osf.io,arpitar/osf.io,fabianvf/osf.io,ckc6cz/osf.io,erinspace/osf.io,SSJohns/osf.io,kwierman/osf.io,HarryRybacki/osf.io,doublebits/osf.io,petermalcolm/osf.io,brandonPurvis/osf.io,ckc6cz/osf.io,bdyetton/prettychart,felliott/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,KAsante95/osf.io,zkraime/osf.io,jnayak1/osf.io,barbour-em/osf.io,hmoco/osf.io,mfraezz/osf.io,RomanZWang/osf.io,lyndsysimon/osf.io,caseyrollins/osf.io,lyndsysimon/osf.io,jolene-esposito/osf.io,cslzchen/osf.io,asanfilippo7/osf.io,barbour-em/osf.io,MerlinZhang/osf.io,baylee-d/osf.io,SSJohns/osf.io,amyshi188/osf.io,lamdnhan/osf.io
--- +++ @@ -1,5 +1,13 @@ -from .views import node +# -*- coding: utf-8 -*- +"""Various node-related utilities.""" +from website.project.views import node +from website.project.views import file as file_views # Alias the project serializer serialize_node = node._view_project + +# File rendering utils +get_cache_content = file_views.get_cache_content +get_cache_path = file_views.get_cache_path +prepare_file = file_views.prepare_file
57ab42c16ddc8591153980b2f3bb8c4ba6090160
tests/conftest.py
tests/conftest.py
"""Module grouping session scoped PyTest fixtures.""" import pytest from _pytest.monkeypatch import MonkeyPatch import pydov def pytest_runtest_setup(): pydov.hooks = [] @pytest.fixture(scope='module') def monkeymodule(): mpatch = MonkeyPatch() yield mpatch mpatch.undo()
"""Module grouping session scoped PyTest fixtures.""" import pytest from _pytest.monkeypatch import MonkeyPatch import pydov def pytest_runtest_setup(): pydov.hooks = [] def pytest_configure(config): config.addinivalue_line("markers", "online: mark test that requires internet access") @pytest.fixture(scope='module') def monkeymodule(): mpatch = MonkeyPatch() yield mpatch mpatch.undo()
Add pytest hook to register online marker
Add pytest hook to register online marker
Python
mit
DOV-Vlaanderen/pydov
--- +++ @@ -9,6 +9,9 @@ def pytest_runtest_setup(): pydov.hooks = [] +def pytest_configure(config): + config.addinivalue_line("markers", + "online: mark test that requires internet access") @pytest.fixture(scope='module') def monkeymodule():
b9f40dd83a603f7457588190bd7d968e30fa74a7
frigg/settings/rest_framework.py
frigg/settings/rest_framework.py
REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'anon': '5000/day', } }
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'anon': '5000/day', } }
Set drf to onyl render json response on all requests
Set drf to onyl render json response on all requests
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
--- +++ @@ -1,4 +1,7 @@ REST_FRAMEWORK = { + 'DEFAULT_RENDERER_CLASSES': ( + 'rest_framework.renderers.JSONRenderer', + ), 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', ),
2f14d64e73dba23a62e82fe3f4f06e6539356117
demo/datasetGeneration.py
demo/datasetGeneration.py
from demo7 import get_answer import json class TripleError(Exception): """ Raised when a triple contains connectors (e.g. AND, FIRST). """ def __init__(self, expression, message): self.expression = expression self.message = message def string_of_triple(t,missing,separator): if t.type == 'missing': return missing if t.type == 'resource': return str(t.value) if t.type == 'triple': _subject = string_of_triple(t.subject,missing,separator) _predicate = string_of_triple(t.predicate,missing,separator) _object = string_of_triple(t.object,missing,separator) return "({1}{0}{2}{0}{3})".format(separator,_subject,_predicate,_object) raise TripleError(t,"Wrong triple (new datamodel connectors?).") def process_string(s,missing='?',separator=','): return string_of_triple(get_answer(s),missing,separator) if __name__ == "__main__": while True: try: s = input("") except EOFError: break print(process_string(s))
from demo7 import get_answer import json class TripleError(Exception): """ Raised when a triple contains connectors (e.g. AND, FIRST). """ def __init__(self, expression, message): self.expression = expression self.message = message def string_of_triple(t,missing,separator): if t.type == 'missing': return missing if t.type == 'resource': return str(t.value) if t.type == 'triple': _subject = string_of_triple(t.subject,missing,separator) _predicate = string_of_triple(t.predicate,missing,separator) _object = string_of_triple(t.object,missing,separator) return "({1}{0}{2}{0}{3})".format(separator,_subject,_predicate,_object) raise TripleError(t,"Wrong triple (new datamodel connectors?).") def process_string(s,missing='?',separator=','): return string_of_triple(get_answer(s),missing,separator) if __name__ == "__main__": while True: try: s = input("") except EOFError: break print(s) print(process_string(s))
Revert "Do not display quesitons in script."
Revert "Do not display quesitons in script." This reverts commit 5c7286c1dc6348f2212266871876376df15592c0.
Python
agpl-3.0
ProjetPP/PPP-QuestionParsing-Grammatical,ProjetPP/PPP-QuestionParsing-Grammatical
--- +++ @@ -31,4 +31,5 @@ s = input("") except EOFError: break + print(s) print(process_string(s))
0036095ed79c3ea6b14732555dbed9a987172366
ue-crash-dummy.py
ue-crash-dummy.py
from flask import Flask from flask_socketio import SocketIO ## Instanciate Flask (Static files and REST API) app = Flask(__name__) ## Instanciate SocketIO (Websockets, used for events) on top of it socketio = SocketIO(app) @socketio.on('testEvent') def test_event(): print "Got test event" @socketio.on('testEventWithException') def test_event_with_exception(): print "Got test event, throwing exception NOW" raise Exception() if __name__ == '__main__': socketio.run(app, host='0.0.0.0')
from flask import Flask from flask_socketio import SocketIO ## Instanciate Flask (Static files and REST API) app = Flask(__name__) ## Instanciate SocketIO (Websockets, used for events) on top of it socketio = SocketIO(app) @socketio.on('testEvent') def test_event(_=None): print "Got test event" @socketio.on('testEventWithException') def test_event_with_exception(_=None): print "Got test event, throwing exception NOW" raise Exception() if __name__ == '__main__': socketio.run(app, host='0.0.0.0')
Add dummy parameter for UE4.
[Bugfix] Add dummy parameter for UE4. Signed-off-by: Juri Berlanda <5bfdca9e82c53adb0603ce7083f4ba4f2da5cacf@hotmail.com>
Python
mit
j-be/ue4-socketio-crash
--- +++ @@ -9,11 +9,11 @@ @socketio.on('testEvent') -def test_event(): +def test_event(_=None): print "Got test event" @socketio.on('testEventWithException') -def test_event_with_exception(): +def test_event_with_exception(_=None): print "Got test event, throwing exception NOW" raise Exception()
a4825083c9a18fe8665d750bfad00a9d6fa40944
tartpy/eventloop.py
tartpy/eventloop.py
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import queue import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): """A generic event loop object.""" def __init__(self): self.queue = queue.Queue() def schedule(self, event): """Schedule an event. An `event` is a thunk. """ self.queue.put(event) def stop(self): """Stop the loop.""" pass def run_step(self, block=True): """Process one event.""" ev = self.queue.get(block=block) ev() def run(self, block=False): """Process all events in the queue.""" try: while True: self.run_step(block=block) except queue.Empty: return def run_in_thread(self): self.thread = threading.Thread(target=self.run, args=(True,), name='event_loop') self.thread.daemon = True self.thread.start()
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): """A generic event loop object.""" def __init__(self): self.scheduler = sched.scheduler() def schedule(self, event): """Schedule an event. An `event` is a thunk. """ self.scheduler.enter(0, 1, event) def stop(self): """Stop the loop.""" pass def run(self, block=False): self.scheduler.run(blocking=block) def run_in_thread(self): self.thread = threading.Thread(target=self.run, args=(True,), name='event_loop') self.thread.daemon = True self.thread.start()
Use Python scheduler rather than the home-made one
Use Python scheduler rather than the home-made one
Python
mit
waltermoreira/tartpy
--- +++ @@ -13,6 +13,7 @@ """ import queue +import sched import threading import time @@ -23,7 +24,7 @@ """A generic event loop object.""" def __init__(self): - self.queue = queue.Queue() + self.scheduler = sched.scheduler() def schedule(self, event): """Schedule an event. @@ -31,25 +32,15 @@ An `event` is a thunk. """ - self.queue.put(event) + self.scheduler.enter(0, 1, event) def stop(self): """Stop the loop.""" pass - def run_step(self, block=True): - """Process one event.""" - ev = self.queue.get(block=block) - ev() + def run(self, block=False): + self.scheduler.run(blocking=block) - def run(self, block=False): - """Process all events in the queue.""" - try: - while True: - self.run_step(block=block) - except queue.Empty: - return - def run_in_thread(self): self.thread = threading.Thread(target=self.run, args=(True,), name='event_loop')
3d5c68421b889abb4f56319b082aaff554ebaa0e
tests/test_parse.py
tests/test_parse.py
import json import logging import os import unittest import ptn class ParseTest(unittest.TestCase): def test_parser(self): with open('files/input.json') as input_file: torrents = json.load(input_file) with open('files/output.json') as output_file: results = json.load(output_file) for torrent, result in zip(torrents, results): logging.info('Checking %s', torrent) self.assertEqual(ptn.parse(torrent), result) if __name__ == '__main__': unittest.main()
import json import os import unittest import ptn class ParseTest(unittest.TestCase): def test_parser(self): with open(os.path.join( os.path.dirname(__file__), 'files/input.json' )) as input_file: torrents = json.load(input_file) with open(os.path.join( os.path.dirname(__file__), 'files/output.json' )) as output_file: expected_results = json.load(output_file) for torrent, expected_result in zip(torrents, expected_results): result = ptn.parse(torrent) self.assertItemsEqual(result, expected_result) if __name__ == '__main__': unittest.main()
Fix minor syntax error in test
Fix minor syntax error in test
Python
mit
divijbindlish/parse-torrent-name,nivertech/parse-torrent-name
--- +++ @@ -1,5 +1,4 @@ import json -import logging import os import unittest @@ -9,15 +8,21 @@ class ParseTest(unittest.TestCase): def test_parser(self): - with open('files/input.json') as input_file: + with open(os.path.join( + os.path.dirname(__file__), + 'files/input.json' + )) as input_file: torrents = json.load(input_file) - with open('files/output.json') as output_file: - results = json.load(output_file) + with open(os.path.join( + os.path.dirname(__file__), + 'files/output.json' + )) as output_file: + expected_results = json.load(output_file) - for torrent, result in zip(torrents, results): - logging.info('Checking %s', torrent) - self.assertEqual(ptn.parse(torrent), result) + for torrent, expected_result in zip(torrents, expected_results): + result = ptn.parse(torrent) + self.assertItemsEqual(result, expected_result) if __name__ == '__main__':
da51183e64875119377d3dd5ffe85c958c23fc16
moksha/api/widgets/flot/flot.py
moksha/api/widgets/flot/flot.py
# This file is part of Moksha. # # Moksha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Moksha 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Moksha. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2008, Red Hat, Inc. # Authors: Luke Macken <lmacken@redhat.com> from tw.jquery.flot import FlotWidget from moksha.api.widgets import LiveWidget class LiveFlotWidget(LiveWidget): """ A live graphing widget """ topic = 'flot_demo' params = ['id', 'data', 'options', 'height', 'width', 'onmessage'] children = [FlotWidget('flot')] onmessage = '$.plot($("#${id}"),json[0]["data"],json[0]["options"])' template = '<div id="${id}" style="width:${width};height:${height};" />' height = '250px' width = '390px' options = {} data = [{}]
# This file is part of Moksha. # # Moksha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Moksha 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Moksha. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2008, Red Hat, Inc. # Authors: Luke Macken <lmacken@redhat.com> from tw.jquery.flot import flot_js, excanvas_js, flot_css from moksha.api.widgets import LiveWidget class LiveFlotWidget(LiveWidget): """ A live graphing widget """ topic = 'flot_demo' params = ['id', 'data', 'options', 'height', 'width', 'onmessage'] onmessage = '$.plot($("#${id}"),json[0]["data"],json[0]["options"])' template = '<div id="${id}" style="width:${width};height:${height};" />' javascript = [flot_js, excanvas_js] css = [flot_css] height = '250px' width = '390px' options = {} data = [{}]
Make our LiveFlotWidget not pull in jQuery
Make our LiveFlotWidget not pull in jQuery
Python
apache-2.0
lmacken/moksha,ralphbean/moksha,pombredanne/moksha,ralphbean/moksha,ralphbean/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,lmacken/moksha,lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha
--- +++ @@ -16,16 +16,17 @@ # Copyright 2008, Red Hat, Inc. # Authors: Luke Macken <lmacken@redhat.com> -from tw.jquery.flot import FlotWidget +from tw.jquery.flot import flot_js, excanvas_js, flot_css from moksha.api.widgets import LiveWidget class LiveFlotWidget(LiveWidget): """ A live graphing widget """ topic = 'flot_demo' params = ['id', 'data', 'options', 'height', 'width', 'onmessage'] - children = [FlotWidget('flot')] onmessage = '$.plot($("#${id}"),json[0]["data"],json[0]["options"])' template = '<div id="${id}" style="width:${width};height:${height};" />' + javascript = [flot_js, excanvas_js] + css = [flot_css] height = '250px' width = '390px' options = {}
99be93029ecec0ed4c1e17e0fc2f199c2ad0f6c6
go/apps/dialogue/dialogue_api.py
go/apps/dialogue/dialogue_api.py
"""Go API action dispatcher for dialogue conversations.""" from go.api.go_api.action_dispatcher import ConversationActionDispatcher class DialogueActionDispatcher(ConversationActionDispatcher): def handle_get_poll(self, conv): pass def handle_save_poll(self, conv, poll): pass
"""Go API action dispatcher for dialogue conversations.""" from go.api.go_api.action_dispatcher import ConversationActionDispatcher class DialogueActionDispatcher(ConversationActionDispatcher): def handle_get_poll(self, conv): return {"poll": conv.config.get("poll")} def handle_save_poll(self, conv, poll): conv.config["poll"] = poll d = conv.save() d.addCallback(lambda r: {"saved": True}) return d
Implement poll saving and getting.
Implement poll saving and getting.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
--- +++ @@ -5,7 +5,10 @@ class DialogueActionDispatcher(ConversationActionDispatcher): def handle_get_poll(self, conv): - pass + return {"poll": conv.config.get("poll")} def handle_save_poll(self, conv, poll): - pass + conv.config["poll"] = poll + d = conv.save() + d.addCallback(lambda r: {"saved": True}) + return d
d831826ec23114a3f56b5f327205257c7ca4ac58
gym/configuration.py
gym/configuration.py
import logging import sys import gym logger = logging.getLogger(__name__) root_logger = logging.getLogger() requests_logger = logging.getLogger('requests') # Set up the default handler formatter = logging.Formatter('[%(asctime)s] %(message)s') handler = logging.StreamHandler(sys.stderr) handler.setFormatter(formatter) # We need to take in the gym logger explicitly since this is called # at initialization time. def logger_setup(gym_logger): root_logger.addHandler(handler) root_logger.setLevel(logging.INFO) # When set to INFO, this will print out the hostname of every # connection it makes. requests_logger.setLevel(logging.WARN) def undo_logger_setup(): """Undoes the automatic logging setup done by OpenAI Gym. You should call this function if you want to manually configure logging yourself. Typical usage would involve putting something like the following at the top of your script: gym.undo_logger_setup() logger = logging.getLogger() logger.addHandler(logging.StreamHandler(sys.stderr)) """ root_logger.removeHandler(handler) root_logger.setLevel(logging.NOTSET) requests_logger.setLevel(logging.NOTSET)
import logging import sys import gym logger = logging.getLogger(__name__) root_logger = logging.getLogger() requests_logger = logging.getLogger('requests') # Set up the default handler formatter = logging.Formatter('[%(asctime)s] %(message)s') handler = logging.StreamHandler(sys.stderr) handler.setFormatter(formatter) # We need to take in the gym logger explicitly since this is called # at initialization time. def logger_setup(gym_logger): root_logger.addHandler(handler) gym_logger.setLevel(logging.INFO) def undo_logger_setup(): """Undoes the automatic logging setup done by OpenAI Gym. You should call this function if you want to manually configure logging yourself. Typical usage would involve putting something like the following at the top of your script: gym.undo_logger_setup() logger = logging.getLogger() logger.addHandler(logging.StreamHandler(sys.stderr)) """ root_logger.removeHandler(handler) gym.logger.setLevel(logging.NOTSET)
Downgrade to just setting the gym logger
Downgrade to just setting the gym logger
Python
mit
dianchen96/gym,Farama-Foundation/Gymnasium,Farama-Foundation/Gymnasium,dianchen96/gym
--- +++ @@ -17,10 +17,7 @@ # at initialization time. def logger_setup(gym_logger): root_logger.addHandler(handler) - root_logger.setLevel(logging.INFO) - # When set to INFO, this will print out the hostname of every - # connection it makes. - requests_logger.setLevel(logging.WARN) + gym_logger.setLevel(logging.INFO) def undo_logger_setup(): """Undoes the automatic logging setup done by OpenAI Gym. You should call @@ -33,5 +30,4 @@ logger.addHandler(logging.StreamHandler(sys.stderr)) """ root_logger.removeHandler(handler) - root_logger.setLevel(logging.NOTSET) - requests_logger.setLevel(logging.NOTSET) + gym.logger.setLevel(logging.NOTSET)
0b80b573049b771f551b2fa47e570d849cd14ea4
packages/syft/src/syft/core/node/common/node_manager/node_route_manager.py
packages/syft/src/syft/core/node/common/node_manager/node_route_manager.py
# third party from sqlalchemy.engine import Engine # relative from ..node_table.node_route import NodeRoute from .database_manager import DatabaseManager class NodeRouteManager(DatabaseManager): schema = NodeRoute def __init__(self, database: Engine) -> None: super().__init__(schema=NodeRouteManager.schema, db=database) def update_route_for_node( self, node_id: int, host_or_ip: str, is_vpn: bool = False ) -> NodeRoute: # node_id is a database int id # host_or_ip can have a port as well node_route = self.first(host_or_ip=host_or_ip) if node_route: self.modify( query={"host_or_ip": host_or_ip}, values={"is_vpn": is_vpn, "node_id": node_id}, ) else: self.register( **{"node_id": node_id, "host_or_ip": host_or_ip, "is_vpn": is_vpn} ) node_route = self.first(host_or_ip=host_or_ip) return node_route
# third party from sqlalchemy.engine import Engine # relative from ..node_table.node_route import NodeRoute from .database_manager import DatabaseManager class NodeRouteManager(DatabaseManager): schema = NodeRoute def __init__(self, database: Engine) -> None: super().__init__(schema=NodeRouteManager.schema, db=database) def update_route_for_node( self, node_id: int, host_or_ip: str, is_vpn: bool = False, vpn_endpoint: str = "", vpn_key: str = "", ) -> NodeRoute: # node_id is a database int id # host_or_ip can have a port as well node_route = self.first(host_or_ip=host_or_ip) values = {"is_vpn": is_vpn, "node_id": node_id, "host_or_ip": host_or_ip} # Only change optional columns if parameters aren't empty strings. if vpn_endpoint: values["vpn_endpoint"] = vpn_endpoint if vpn_key: values["vpn_key"] = vpn_key if node_route: self.modify( query={"host_or_ip": host_or_ip}, values=values, ) else: values["node_id"] = node_id self.register(**values) node_route = self.first(host_or_ip=host_or_ip) return node_route
UPDATE update_route_for_node method to accept new parameters (vpn_endpoint/vpn_key)
UPDATE update_route_for_node method to accept new parameters (vpn_endpoint/vpn_key)
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
--- +++ @@ -13,20 +13,32 @@ super().__init__(schema=NodeRouteManager.schema, db=database) def update_route_for_node( - self, node_id: int, host_or_ip: str, is_vpn: bool = False + self, + node_id: int, + host_or_ip: str, + is_vpn: bool = False, + vpn_endpoint: str = "", + vpn_key: str = "", ) -> NodeRoute: # node_id is a database int id # host_or_ip can have a port as well node_route = self.first(host_or_ip=host_or_ip) + values = {"is_vpn": is_vpn, "node_id": node_id, "host_or_ip": host_or_ip} + + # Only change optional columns if parameters aren't empty strings. + if vpn_endpoint: + values["vpn_endpoint"] = vpn_endpoint + if vpn_key: + values["vpn_key"] = vpn_key + if node_route: self.modify( query={"host_or_ip": host_or_ip}, - values={"is_vpn": is_vpn, "node_id": node_id}, + values=values, ) else: - self.register( - **{"node_id": node_id, "host_or_ip": host_or_ip, "is_vpn": is_vpn} - ) + values["node_id"] = node_id + self.register(**values) node_route = self.first(host_or_ip=host_or_ip) return node_route
9bb0e3b082b509b5498d25df248d4c74be53bcc3
oppia/tests/javascript_tests.py
oppia/tests/javascript_tests.py
# Copyright 2012 Google Inc. 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. import subprocess import unittest class JavaScriptTests(unittest.TestCase): def test_with_karma(self): subprocess.call([ 'third_party/node-0.10.1/bin/karma', 'start', 'oppia/tests/karma.conf.js'])
# Copyright 2012 Google Inc. 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. import subprocess import unittest class JavaScriptTests(unittest.TestCase): def test_with_karma(self): return_code = subprocess.call([ 'third_party/node-0.10.1/bin/karma', 'start', 'oppia/tests/karma.conf.js']) self.assertEqual(return_code, 0)
Make failing Karma tests actually count as failures.
Make failing Karma tests actually count as failures.
Python
apache-2.0
sunu/oppia,directorlive/oppia,michaelWagner/oppia,jestapinski/oppia,kennho/oppia,mit0110/oppia,himanshu-dixit/oppia,zgchizi/oppia-uc,won0089/oppia,brianrodri/oppia,leandrotoledo/oppia,fernandopinhati/oppia,rackstar17/oppia,aldeka/oppia,Dev4X/oppia,amgowano/oppia,oulan/oppia,raju249/oppia,aldeka/oppia,dippatel1994/oppia,AllanYangZhou/oppia,michaelWagner/oppia,wangsai/oppia,sarahfo/oppia,terrameijar/oppia,kaffeel/oppia,Atlas-Sailed-Co/oppia,DewarM/oppia,anggorodewanto/oppia,MaximLich/oppia,prasanna08/oppia,fernandopinhati/oppia,directorlive/oppia,sdulal/oppia,himanshu-dixit/oppia,rackstar17/oppia,brianrodri/oppia,dippatel1994/oppia,cleophasmashiri/oppia,dippatel1994/oppia,zgchizi/oppia-uc,asandyz/oppia,amgowano/oppia,terrameijar/oppia,mit0110/oppia,felipecocco/oppia,danieljjh/oppia,hazmatzo/oppia,asandyz/oppia,himanshu-dixit/oppia,kevinlee12/oppia,nagyistoce/oppia,virajprabhu/oppia,MaximLich/oppia,leandrotoledo/oppia,anthkris/oppia,virajprabhu/oppia,felipecocco/oppia,felipecocco/oppia,sanyaade-teachings/oppia,VictoriaRoux/oppia,VictoriaRoux/oppia,kevinlee12/oppia,anthkris/oppia,directorlive/oppia,jestapinski/oppia,sunu/oh-missions-oppia-beta,kaffeel/oppia,kennho/oppia,BenHenning/oppia,whygee/oppia,zgchizi/oppia-uc,sunu/oh-missions-oppia-beta,Cgruppo/oppia,brylie/oppia,mindpin/mindpin_oppia,AllanYangZhou/oppia,DewarM/oppia,sbhowmik89/oppia,anggorodewanto/oppia,asandyz/oppia,michaelWagner/oppia,kingctan/oppia,sbhowmik89/oppia,virajprabhu/oppia,VictoriaRoux/oppia,oulan/oppia,asandyz/oppia,infinyte/oppia,whygee/oppia,oppia/oppia,kaffeel/oppia,souravbadami/oppia,nagyistoce/oppia,kevinlee12/oppia,mit0110/oppia,sunu/oppia,sunu/oppia,kingctan/oppia,toooooper/oppia,Dev4X/oppia,miyucy/oppia,sanyaade-teachings/oppia,danieljjh/oppia,Atlas-Sailed-Co/oppia,virajprabhu/oppia,sbhowmik89/oppia,oppia/oppia,whygee/oppia,aldeka/oppia,won0089/oppia,Cgruppo/oppia,bjvoth/oppia,hazmatzo/oppia,michaelWagner/oppia,wangsai/oppia,Dev4X/oppia,gale320/oppia,mit0110/oppia,bjvoth/oppia,leandrotoledo/oppia,miyucy/oppia,danieljjh/oppia,google-code-export/oppia,openhatch/oh-missions-oppia-beta,felipecocco/oppia,infinyte/oppia,MaximLich/oppia,brianrodri/oppia,VictoriaRoux/oppia,brylie/oppia,openhatch/oh-missions-oppia-beta,amitdeutsch/oppia,rackstar17/oppia,MAKOSCAFEE/oppia,raju249/oppia,mindpin/mindpin_oppia,miyucy/oppia,virajprabhu/oppia,kennho/oppia,sunu/oh-missions-oppia-beta,danieljjh/oppia,BenHenning/oppia,amgowano/oppia,AllanYangZhou/oppia,bjvoth/oppia,sarahfo/oppia,hazmatzo/oppia,asandyz/oppia,BenHenning/oppia,DewarM/oppia,raju249/oppia,Dev4X/oppia,CMDann/oppia,miyucy/oppia,CMDann/oppia,anggorodewanto/oppia,CMDann/oppia,sdulal/oppia,MAKOSCAFEE/oppia,AllanYangZhou/oppia,shaz13/oppia,kingctan/oppia,anggorodewanto/oppia,google-code-export/oppia,fernandopinhati/oppia,felipecocco/oppia,Cgruppo/oppia,sunu/oh-missions-oppia-beta,prasanna08/oppia,sanyaade-teachings/oppia,hazmatzo/oppia,amgowano/oppia,infinyte/oppia,amitdeutsch/oppia,sanyaade-teachings/oppia,oppia/oppia,souravbadami/oppia,kaffeel/oppia,kaffeel/oppia,amitdeutsch/oppia,Atlas-Sailed-Co/oppia,kingctan/oppia,jestapinski/oppia,prasanna08/oppia,won0089/oppia,sdulal/oppia,google-code-export/oppia,gale320/oppia,dippatel1994/oppia,prasanna08/oppia,amitdeutsch/oppia,bjvoth/oppia,oulan/oppia,brianrodri/oppia,kevinlee12/oppia,sdulal/oppia,toooooper/oppia,raju249/oppia,kevinlee12/oppia,sarahfo/oppia,mindpin/mindpin_oppia,sbhowmik89/oppia,leandrotoledo/oppia,cleophasmashiri/oppia,Atlas-Sailed-Co/oppia,CMDann/oppia,edallison/oppia,gale320/oppia,brylie/oppia,edallison/oppia,MAKOSCAFEE/oppia,gale320/oppia,oppia/oppia,CMDann/oppia,souravbadami/oppia,directorlive/oppia,zgchizi/oppia-uc,openhatch/oh-missions-oppia-beta,cleophasmashiri/oppia,hazmatzo/oppia,amitdeutsch/oppia,brianrodri/oppia,Atlas-Sailed-Co/oppia,terrameijar/oppia,won0089/oppia,wangsai/oppia,edallison/oppia,cleophasmashiri/oppia,google-code-export/oppia,anthkris/oppia,mit0110/oppia,google-code-export/oppia,shaz13/oppia,nagyistoce/oppia,sarahfo/oppia,oulan/oppia,prasanna08/oppia,edallison/oppia,sunu/oppia,shaz13/oppia,DewarM/oppia,michaelWagner/oppia,fernandopinhati/oppia,oppia/oppia,gale320/oppia,sdulal/oppia,BenHenning/oppia,whygee/oppia,brylie/oppia,anthkris/oppia,BenHenning/oppia,wangsai/oppia,sbhowmik89/oppia,MaximLich/oppia,cleophasmashiri/oppia,aldeka/oppia,sanyaade-teachings/oppia,infinyte/oppia,toooooper/oppia,mindpin/mindpin_oppia,Dev4X/oppia,souravbadami/oppia,VictoriaRoux/oppia,shaz13/oppia,terrameijar/oppia,danieljjh/oppia,directorlive/oppia,rackstar17/oppia,sunu/oppia,whygee/oppia,kingctan/oppia,toooooper/oppia,brylie/oppia,dippatel1994/oppia,nagyistoce/oppia,infinyte/oppia,openhatch/oh-missions-oppia-beta,DewarM/oppia,won0089/oppia,sarahfo/oppia,jestapinski/oppia,kennho/oppia,bjvoth/oppia,toooooper/oppia,wangsai/oppia,fernandopinhati/oppia,himanshu-dixit/oppia,Cgruppo/oppia,nagyistoce/oppia,oulan/oppia,leandrotoledo/oppia,MAKOSCAFEE/oppia,kennho/oppia,souravbadami/oppia,Cgruppo/oppia
--- +++ @@ -19,5 +19,7 @@ class JavaScriptTests(unittest.TestCase): def test_with_karma(self): - subprocess.call([ - 'third_party/node-0.10.1/bin/karma', 'start', 'oppia/tests/karma.conf.js']) + return_code = subprocess.call([ + 'third_party/node-0.10.1/bin/karma', 'start', + 'oppia/tests/karma.conf.js']) + self.assertEqual(return_code, 0)
824b4c1f979f49bb8debc3891f47c53bf6699227
components/all/platform-config/x86-64-im-n29xx-t40n-r0/src/python/onlpc.py
components/all/platform-config/x86-64-im-n29xx-t40n-r0/src/python/onlpc.py
#!/usr/bin/python ############################################################ # # Copyright 2015 Interface Masters Technologies, Inc. # # Platform Driver for x86-64-im-n29xx-t40n-r0 # ############################################################ import os import struct import time import subprocess from onl.platform.base import * from onl.vendor.imt import * class OpenNetworkPlatformImplementation(OpenNetworkPlatformIMT): def model(self): # different IMT hw is supported by one image. return 'IM29XX' def platform(self): return 'x86-64-im-n29xx-t40n-r0' def _plat_info_dict(self): return { # TODO IMT: check how to improve this # different IMT hw is supported by one image. platinfo.LAG_COMPONENT_MAX : -1, platinfo.PORT_COUNT : -1 } def _plat_oid_table(self): return None def get_environment(self): return "Not implemented." if __name__ == "__main__": import sys p = OpenNetworkPlatformImplementation() if len(sys.argv) == 1 or sys.argv[1] == 'info': print p elif sys.argv[1] == 'env': print p.get_environment()
#!/usr/bin/python ############################################################ # # Copyright 2015 Interface Masters Technologies, Inc. # # Platform Driver for x86-64-im-n29xx-t40n-r0 # ############################################################ import os import struct import time import subprocess from onl.platform.base import * from onl.vendor.imt import * class OpenNetworkPlatformImplementation(OpenNetworkPlatformIMT): def model(self): # different IMT hw is supported by one image. return 'IM29XX' def platform(self): return 'x86-64-im-n29xx-t40n-r0' def _plat_info_dict(self): return { # TODO IMT: check how to improve this # different IMT hw is supported by one image. platinfo.LAG_COMPONENT_MAX : -1, platinfo.PORT_COUNT : -1 } def _plat_oid_table(self): return None def sys_oid_platform(self): return ".30324.29" def get_environment(self): return "Not implemented." if __name__ == "__main__": import sys p = OpenNetworkPlatformImplementation() if len(sys.argv) == 1 or sys.argv[1] == 'info': print p elif sys.argv[1] == 'env': print p.get_environment()
Add IANA OID to file
Add IANA OID to file
Python
epl-1.0
InterfaceMasters/ONL,InterfaceMasters/ONL
--- +++ @@ -33,6 +33,9 @@ def _plat_oid_table(self): return None + def sys_oid_platform(self): + return ".30324.29" + def get_environment(self): return "Not implemented."
f9223d3e12881dd638a2815bb1019071d1857541
laalaa/apps/advisers/geocoder.py
laalaa/apps/advisers/geocoder.py
import re import postcodeinfo import pc_fallback class GeocoderError(Exception): pass class PostcodeNotFound(GeocoderError): def __init__(self, postcode, *args, **kwargs): super(PostcodeNotFound, self).__init__(*args, **kwargs) self.postcode = postcode def geocode(postcode): try: if len(postcode) < 5: result = postcodeinfo.Client().lookup_partial_postcode(postcode) else: result = postcodeinfo.Client().lookup_postcode(postcode) if not result.valid: result = pc_fallback.geocode(postcode) if not result: raise PostcodeNotFound(postcode) return result except postcodeinfo.PostcodeInfoException as e: raise GeocoderError(e)
import re import postcodeinfo import pc_fallback class GeocoderError(Exception): pass class PostcodeNotFound(GeocoderError): def __init__(self, postcode, *args, **kwargs): super(PostcodeNotFound, self).__init__(*args, **kwargs) self.postcode = postcode def geocode(postcode): try: postcode_client = postcodeinfo.Client(timeout = 30) if len(postcode) < 5: result = postcode_client.lookup_partial_postcode(postcode) else: result = postcode_client.lookup_postcode(postcode) if not result.valid: result = pc_fallback.geocode(postcode) if not result: raise PostcodeNotFound(postcode) return result except postcodeinfo.PostcodeInfoException as e: raise GeocoderError(e)
Increase default timeout for postcodeinfo to 30s
Increase default timeout for postcodeinfo to 30s It seems that the current default of 5 seconds is too low for most of the "legal provider upload" use cases.
Python
mit
ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api
--- +++ @@ -15,10 +15,11 @@ def geocode(postcode): try: + postcode_client = postcodeinfo.Client(timeout = 30) if len(postcode) < 5: - result = postcodeinfo.Client().lookup_partial_postcode(postcode) + result = postcode_client.lookup_partial_postcode(postcode) else: - result = postcodeinfo.Client().lookup_postcode(postcode) + result = postcode_client.lookup_postcode(postcode) if not result.valid: result = pc_fallback.geocode(postcode)
57e66ae6cd833b1b0da5b71e1c4b6e223c8ca062
test/test_data.py
test/test_data.py
"""Tests for coverage.data""" import unittest from coverage.data import CoverageData class DataTest(unittest.TestCase): def test_reading(self): covdata = CoverageData() covdata.read() self.assertEqual(covdata.summary(), {})
"""Tests for coverage.data""" from coverage.data import CoverageData from coveragetest import CoverageTest class DataTest(CoverageTest): def test_reading(self): covdata = CoverageData() covdata.read() self.assertEqual(covdata.summary(), {})
Use our CoverageTest base class to get isolation (in a new directory) for the data tests.
Use our CoverageTest base class to get isolation (in a new directory) for the data tests.
Python
apache-2.0
7WebPages/coveragepy,larsbutler/coveragepy,7WebPages/coveragepy,jayhetee/coveragepy,nedbat/coveragepy,7WebPages/coveragepy,blueyed/coveragepy,jayhetee/coveragepy,blueyed/coveragepy,larsbutler/coveragepy,larsbutler/coveragepy,blueyed/coveragepy,larsbutler/coveragepy,7WebPages/coveragepy,hugovk/coveragepy,hugovk/coveragepy,nedbat/coveragepy,blueyed/coveragepy,larsbutler/coveragepy,jayhetee/coveragepy,nedbat/coveragepy,blueyed/coveragepy,nedbat/coveragepy,hugovk/coveragepy,nedbat/coveragepy,hugovk/coveragepy,jayhetee/coveragepy,jayhetee/coveragepy,hugovk/coveragepy
--- +++ @@ -1,9 +1,9 @@ """Tests for coverage.data""" -import unittest from coverage.data import CoverageData +from coveragetest import CoverageTest -class DataTest(unittest.TestCase): +class DataTest(CoverageTest): def test_reading(self): covdata = CoverageData() covdata.read()
dfdcbda02ad2fcc744e90d437051afe911e47c60
gapipy/resources/booking/agent.py
gapipy/resources/booking/agent.py
from __future__ import unicode_literals from ..base import Resource from .agency import Agency class Agent(Resource): _resource_name = 'agents' _is_listable = False _as_is_fields = [ 'id', 'href', 'role', 'first_name', 'last_name', 'email', 'phone_numbers', 'username', 'active', ] _resource_fields = [('agency', Agency)]
from __future__ import unicode_literals from ..base import BaseModel, Resource from .agency import Agency class AgentRole(BaseModel): _as_is_fields = ['id', 'name'] class AgentPhoneNumber(BaseModel): _as_is_fields = ['number', 'type'] class Agent(Resource): _resource_name = 'agents' _is_listable = False _as_is_fields = [ 'id', 'href', 'first_name', 'last_name', 'email', 'username', 'active', ] _model_fields = [ ('role', AgentRole), ] _model_collection_fields = [ ('phone_numbers', AgentPhoneNumber), ] _resource_fields = [('agency', Agency)]
Update Agent to use BaseModel classes to...
Update Agent to use BaseModel classes to... represent Agent.role & Agent.phone_numbers fields This will enable attribute access semantics for these fields i.e. > agent = client.agent.get(1234) > agent.role['id'] > agent.phone_numbers[0]['number'] > agent.role.id > agent.phone_numbers[0].number
Python
mit
gadventures/gapipy
--- +++ @@ -1,8 +1,16 @@ from __future__ import unicode_literals -from ..base import Resource +from ..base import BaseModel, Resource from .agency import Agency + + +class AgentRole(BaseModel): + _as_is_fields = ['id', 'name'] + + +class AgentPhoneNumber(BaseModel): + _as_is_fields = ['number', 'type'] class Agent(Resource): @@ -10,7 +18,18 @@ _is_listable = False _as_is_fields = [ - 'id', 'href', 'role', 'first_name', 'last_name', 'email', - 'phone_numbers', 'username', 'active', + 'id', + 'href', + 'first_name', + 'last_name', + 'email', + 'username', + 'active', + ] + _model_fields = [ + ('role', AgentRole), + ] + _model_collection_fields = [ + ('phone_numbers', AgentPhoneNumber), ] _resource_fields = [('agency', Agency)]
6b1ebf85ec2b76bee889936726c3caac45203675
pubsubpull/tests/test_config.py
pubsubpull/tests/test_config.py
from slumber.connector.ua import get from django.test import TestCase from pubsubpull.models import * class TestConfiguration(TestCase): def test_slumber(self): response, json = get('/slumber/') self.assertEquals(response.status_code, 200, response)
from slumber.connector.ua import get from django.test import TestCase from pubsubpull.models import * class TestConfiguration(TestCase): def test_slumber(self): response, json = get('/slumber/') self.assertEquals(response.status_code, 200, response) self.assertTrue(json.has_key('apps'), json) self.assertTrue(json['apps'].has_key('pubsubpull'), json)
Make sure pubsubpull is installed.
Make sure pubsubpull is installed.
Python
mit
KayEss/django-pubsubpull,KayEss/django-pubsubpull,KayEss/django-pubsubpull
--- +++ @@ -9,3 +9,5 @@ def test_slumber(self): response, json = get('/slumber/') self.assertEquals(response.status_code, 200, response) + self.assertTrue(json.has_key('apps'), json) + self.assertTrue(json['apps'].has_key('pubsubpull'), json)
9014dfde50d5f54cf79c544ce01e81266effa87d
game_info/tests/test_commands.py
game_info/tests/test_commands.py
from django.core.management import call_command from django.test import TestCase class ServerTest(TestCase): def test_update_game_info(self): call_command('update_game_info')
from django.core.management import call_command from django.test import TestCase from game_info.models import Server class ServerTest(TestCase): def create_server(self, title="Test Server", host="example.org", port=27015): return Server.objects.create(title=title, host=host, port=port) def test_update_game_info(self): self.create_server().save() call_command('update_game_info')
Fix testing on update_game_info management command
Fix testing on update_game_info management command
Python
bsd-3-clause
Azelphur-Servers/django-game-info
--- +++ @@ -1,7 +1,12 @@ from django.core.management import call_command from django.test import TestCase +from game_info.models import Server class ServerTest(TestCase): + def create_server(self, title="Test Server", host="example.org", port=27015): + return Server.objects.create(title=title, host=host, port=port) + def test_update_game_info(self): + self.create_server().save() call_command('update_game_info')
bee8527854577f2c663cd43719bbb2cd05cdbf1a
TwitterStatsLib/Output.py
TwitterStatsLib/Output.py
""" Module providing standard output classes """ from abc import ABCMeta, abstractmethod from mako.template import Template from mako.lookup import TemplateLookup class Output(object): """ Abstract class base for output classes """ __metaclass__ = ABCMeta @abstractmethod def render(self, data): """ Render passed data """ pass class HTMLOutput(Output): """ HTML output renderer, using Mako templates """ def _preprocess(self, text, data): """ Preprocess mako template, to automatically access data dictionary as we cannot unpack data in render_unicode directly using ** operator because unpacking is accessing individual items via __getitem__ advantages of LazyDict Because of this preprocessing you can write in mako template e.g.: ${tweet_count_total} Instead of: ${data['tweet_count_total']} """ for key in data.keys(): text = text.replace(key, 'data[\'' + key + '\']') return text def render(self, data): """ Render HTML file """ template_lookup = TemplateLookup(directories=['templates/'], module_directory='tmp/', preprocessor=lambda text: self._preprocess(text, data)) mako_template = template_lookup.get_template('html_template.mako') return mako_template.render_unicode(data=data)
""" Module providing standard output classes """ import re from abc import ABCMeta, abstractmethod from mako.template import Template from mako.lookup import TemplateLookup class Output(object): """ Abstract class base for output classes """ __metaclass__ = ABCMeta @abstractmethod def render(self, data): """ Render passed data """ pass class HTMLOutput(Output): """ HTML output renderer, using Mako templates """ def _preprocess(self, text, data): """ Preprocess mako template, to automatically access data dictionary as we cannot unpack data in render_unicode directly using ** operator because unpacking is accessing individual items via __getitem__ advantages of LazyDict Because of this preprocessing you can write in mako template e.g.: ${tweet_count_total} Instead of: ${data['tweet_count_total']} """ regex_str = '' for key in data.keys(): regex_str += r'\b' + key + r'\b|' regex_str = r'((?:' + regex_str[:-1] + r')+)' regex = re.compile(regex_str) text = regex.sub(r"data['\1']", text) return text def render(self, data): """ Render HTML file """ template_lookup = TemplateLookup(directories=['templates/'], module_directory='tmp/', preprocessor=lambda text: self._preprocess(text, data)) mako_template = template_lookup.get_template('html_template.mako') return mako_template.render_unicode(data=data)
Use regex instead of replace for Mako template preprocess
Use regex instead of replace for Mako template preprocess
Python
mit
pecet/pytosg,pecet/pytosg
--- +++ @@ -1,5 +1,6 @@ """ Module providing standard output classes """ +import re from abc import ABCMeta, abstractmethod from mako.template import Template from mako.lookup import TemplateLookup @@ -28,8 +29,13 @@ Instead of: ${data['tweet_count_total']} """ + + regex_str = '' for key in data.keys(): - text = text.replace(key, 'data[\'' + key + '\']') + regex_str += r'\b' + key + r'\b|' + regex_str = r'((?:' + regex_str[:-1] + r')+)' + regex = re.compile(regex_str) + text = regex.sub(r"data['\1']", text) return text def render(self, data):
28cf62f316e2e726331f9b0773270db64c4869c8
grammpy/IsMethodsRuleExtension.py
grammpy/IsMethodsRuleExtension.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from .Rule import Rule class IsMethodsRuleExtension(Rule): @classmethod def is_regular(cls): raise NotImplementedError() @classmethod def is_contextfree(cls): raise NotImplementedError() @classmethod def is_context(cls): raise NotImplementedError() @classmethod def is_unrestricted(cls): raise NotImplementedError() @classmethod def is_valid(cls, grammar): raise NotImplementedError()
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from .Rule import Rule class IsMethodsRuleExtension(Rule): @classmethod def is_regular(cls): raise NotImplementedError() @classmethod def is_contextfree(cls): raise NotImplementedError() @classmethod def is_context(cls): raise NotImplementedError() @classmethod def is_unrestricted(cls): raise NotImplementedError() @classmethod def validate(cls, grammar): raise NotImplementedError() @classmethod def is_valid(cls, grammar): raise NotImplementedError()
Add Rule.validate class method that will raise exceptions
Add Rule.validate class method that will raise exceptions
Python
mit
PatrikValkovic/grammpy
--- +++ @@ -28,5 +28,9 @@ raise NotImplementedError() @classmethod + def validate(cls, grammar): + raise NotImplementedError() + + @classmethod def is_valid(cls, grammar): raise NotImplementedError()
7417c91f630528cc23aba77ef06430504f918fc7
campos_sms/models/res_partner.py
campos_sms/models/res_partner.py
# -*- coding: utf-8 -*- from openerp import models, fields, api import string class ResPartner(models.Model): _inherit = ['res.partner'] mobile_clean = fields.Char(compute='_compute_mobile_clean') @api.multi @api.depends('mobile') def _compute_mobile_clean(self): allowed_chars = '+0123456789' for p in self: # Filter allowed chars mobile_clean = ''.join([c for c in p.mobile if c in allowed_chars]) if p.mobile else '' # Make sure number starts with country code if len(mobile_clean) > 0 and mobile_clean[0] != '+': if len(mobile_clean) >= 2 and mobile_clean[0:2] == '00': mobile_clean = '+' + mobile_clean[2:] else: # @todo: Use country prefix from partner's country setting mobile_clean = '+45' + mobile_clean # Number can only have '+' as the first char - and length must be less than 18 chars # (two numbers will be at least 2 * 8 + 3 = 19 chars (3 for '+45') if '+' in mobile_clean[1:] or len(mobile_clean) > 18: mobile_clean = False p.mobile_clean = mobile_clean
# -*- coding: utf-8 -*- from openerp import models, fields, api import string class ResPartner(models.Model): _inherit = ['res.partner'] mobile_clean = fields.Char(compute='_compute_mobile_clean', store=True) @api.multi @api.depends('mobile','phone') def _compute_mobile_clean(self): allowed_chars = '+0123456789' for p in self: # Filter allowed chars if not p.mobile: p.mobile = p.phone mobile_clean = ''.join([c for c in p.mobile if c in allowed_chars]) if p.mobile else '' # Make sure number starts with country code if len(mobile_clean) > 0 and mobile_clean[0] != '+': if len(mobile_clean) >= 2 and mobile_clean[0:2] == '00': mobile_clean = '+' + mobile_clean[2:] else: # @todo: Use country prefix from partner's country setting mobile_clean = '+45' + mobile_clean # Number can only have '+' as the first char - and length must be less than 18 chars # (two numbers will be at least 2 * 8 + 3 = 19 chars (3 for '+45') if '+' in mobile_clean[1:] or len(mobile_clean) > 18: mobile_clean = False p.mobile_clean = mobile_clean
Store cleanet phone number for use in SQL extracts
Store cleanet phone number for use in SQL extracts
Python
agpl-3.0
sl2017/campos
--- +++ @@ -6,14 +6,16 @@ class ResPartner(models.Model): _inherit = ['res.partner'] - mobile_clean = fields.Char(compute='_compute_mobile_clean') + mobile_clean = fields.Char(compute='_compute_mobile_clean', store=True) @api.multi - @api.depends('mobile') + @api.depends('mobile','phone') def _compute_mobile_clean(self): allowed_chars = '+0123456789' for p in self: # Filter allowed chars + if not p.mobile: + p.mobile = p.phone mobile_clean = ''.join([c for c in p.mobile if c in allowed_chars]) if p.mobile else '' # Make sure number starts with country code if len(mobile_clean) > 0 and mobile_clean[0] != '+':
c1d27fba7097c4b0521512e83c2bef4b3df57735
hoomd/md/pytest/test_thermoHMA.py
hoomd/md/pytest/test_thermoHMA.py
import hoomd def test_before_attaching(): filt = hoomd.filter.All() thermoHMA = hoomd.md.compute.ThermoHMA(filt, 1.0) assert thermoHMA._filter == filt assert thermoHMA.temperature == 1.0 assert thermoHMA.harmonicPressure == 0.0 assert thermoHMA.potential_energyHMA is None assert thermoHMA.pressureHMA is None thermoHMA = hoomd.md.compute.ThermoHMA(filt, 2.5, 0.6) assert thermoHMA.temperature == 2.5 assert thermoHMA.harmonicPressure == 0.6 def test_after_attaching(simulation_factory, two_particle_snapshot_factory): filt = hoomd.filter.All() thermoHMA = hoomd.md.compute.ThermoHMA(filt, 1.0) sim = simulation_factory(two_particle_snapshot_factory()) sim.operations.add(thermoHMA) assert len(sim.operations.computes) == 1 sim.run(0) assert isinstance(thermoHMA.potential_energyHMA, float) assert isinstance(thermoHMA.pressureHMA, float) sim.operations.remove(thermoHMA) assert len(sim.operations.computes) == 0 assert thermoHMA.potential_energyHMA is None assert thermoHMA.pressureHMA is None
import hoomd def test_before_attaching(): filt = hoomd.filter.All() thermoHMA = hoomd.md.compute.ThermoHMA(filt, 1.0) assert thermoHMA._filter == filt assert thermoHMA.temperature == 1.0 assert thermoHMA.harmonic_pressure == 0.0 assert thermoHMA.potential_energyHMA is None assert thermoHMA.pressureHMA is None thermoHMA = hoomd.md.compute.ThermoHMA(filt, 2.5, 0.6) assert thermoHMA.temperature == 2.5 assert thermoHMA.harmonic_pressure == 0.6 def test_after_attaching(simulation_factory, two_particle_snapshot_factory): filt = hoomd.filter.All() thermoHMA = hoomd.md.compute.ThermoHMA(filt, 1.0) sim = simulation_factory(two_particle_snapshot_factory()) sim.operations.add(thermoHMA) assert len(sim.operations.computes) == 1 sim.run(0) assert isinstance(thermoHMA.potential_energyHMA, float) assert isinstance(thermoHMA.pressureHMA, float) sim.operations.remove(thermoHMA) assert len(sim.operations.computes) == 0 assert thermoHMA.potential_energyHMA is None assert thermoHMA.pressureHMA is None
Fix property name in test
Fix property name in test
Python
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
--- +++ @@ -6,13 +6,13 @@ thermoHMA = hoomd.md.compute.ThermoHMA(filt, 1.0) assert thermoHMA._filter == filt assert thermoHMA.temperature == 1.0 - assert thermoHMA.harmonicPressure == 0.0 + assert thermoHMA.harmonic_pressure == 0.0 assert thermoHMA.potential_energyHMA is None assert thermoHMA.pressureHMA is None thermoHMA = hoomd.md.compute.ThermoHMA(filt, 2.5, 0.6) assert thermoHMA.temperature == 2.5 - assert thermoHMA.harmonicPressure == 0.6 + assert thermoHMA.harmonic_pressure == 0.6 def test_after_attaching(simulation_factory, two_particle_snapshot_factory):
e99c63af5c0143c95f9af10e3a79083235bb7da4
lc0340_longest_substring_with_at_most_k_distinct_characters.py
lc0340_longest_substring_with_at_most_k_distinct_characters.py
"""Leetcode 340. Longest Substring with At Most K Distinct Characters Hard URL: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/ Given a string, find the length of the longest substring T that contains at most k distinct characters. Example 1: Input: s = "eceba", k = 2 Output: 3 Explanation: T is "ece" which its length is 3. Example 2: Input: s = "aa", k = 1 Output: 2 Explanation: T is "aa" which its length is 2. """ class Solution(object): def lengthOfLongestSubstringKDistinct(self, s, k): """ :type s: str :type k: int :rtype: int """ pass def main(): pass if __name__ == '__main__': main()
"""Leetcode 340. Longest Substring with At Most K Distinct Characters Hard URL: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/ Given a string, find the length of the longest substring T that contains at most k distinct characters. Example 1: Input: s = "eceba", k = 2 Output: 3 Explanation: T is "ece" which its length is 3. Example 2: Input: s = "aa", k = 1 Output: 2 Explanation: T is "aa" which its length is 2. """ class SolutionTwoPointerCharCountDictIter(object): def lengthOfLongestSubstringKDistinct(self, s, k): """ :type s: str :type k: int :rtype: int Time complexity: O(n). Space complexity: O(k). """ from collections import defaultdict # Apply sliding window with two pointers to increment dict:char->count. char_count_d = defaultdict(int) max_len = 0 i = 0 # Move right pointer j iteratively. for j in range(len(s)): # Increment char count for s[j]. char_count_d[s[j]] += 1 if len(char_count_d) > k: # If distinct char number > k, decrement char count for s[i]. char_count_d[s[i]] -= 1 if char_count_d[s[i]] == 0: del char_count_d[s[i]] i += 1 max_len = max(max_len, j - i + 1) return max_len def main(): # Output: 3 s = "eceba" k = 2 print SolutionTwoPointerCharCountDictIter().lengthOfLongestSubstringKDistinct(s, k) # Output: 2 s = "aa" k = 1 print SolutionTwoPointerCharCountDictIter().lengthOfLongestSubstringKDistinct(s, k) if __name__ == '__main__': main()
Complete two pointers char count dict sol w/ time/space complexity
Complete two pointers char count dict sol w/ time/space complexity
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -18,18 +18,52 @@ """ -class Solution(object): +class SolutionTwoPointerCharCountDictIter(object): def lengthOfLongestSubstringKDistinct(self, s, k): """ :type s: str :type k: int :rtype: int + + Time complexity: O(n). + Space complexity: O(k). """ - pass + from collections import defaultdict + + # Apply sliding window with two pointers to increment dict:char->count. + char_count_d = defaultdict(int) + + max_len = 0 + i = 0 + + # Move right pointer j iteratively. + for j in range(len(s)): + # Increment char count for s[j]. + char_count_d[s[j]] += 1 + + if len(char_count_d) > k: + # If distinct char number > k, decrement char count for s[i]. + char_count_d[s[i]] -= 1 + if char_count_d[s[i]] == 0: + del char_count_d[s[i]] + + i += 1 + + max_len = max(max_len, j - i + 1) + + return max_len def main(): - pass + # Output: 3 + s = "eceba" + k = 2 + print SolutionTwoPointerCharCountDictIter().lengthOfLongestSubstringKDistinct(s, k) + + # Output: 2 + s = "aa" + k = 1 + print SolutionTwoPointerCharCountDictIter().lengthOfLongestSubstringKDistinct(s, k) if __name__ == '__main__':
a3425b010cb252db7dcb19ca6023f1e09999912e
leetcode/389-Find-the-Difference/FindtheDifference_Bit_and_Hash.py
leetcode/389-Find-the-Difference/FindtheDifference_Bit_and_Hash.py
class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ chrs = {} res = 0 for w in t: if w not in chrs: chrs[w] = 1 << (ord(w) - 97) res += chrs[w] for w in s: res -= chrs[w] return chr(len(bin(res)) + 94)
class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ chrs = {} res = 0 for w in t: if w not in chrs: chrs[w] = 1 << (ord(w) - 97) res += chrs[w] # it can be overflow for w in s: res -= chrs[w] return chr(len(bin(res)) + 94)
Comment overflow problem on FindtheDiff_BitHash
Comment overflow problem on FindtheDiff_BitHash
Python
mit
Chasego/codi,Chasego/cod,cc13ny/algo,Chasego/codi,Chasego/codirit,cc13ny/Allin,Chasego/codi,cc13ny/Allin,Chasego/codi,cc13ny/Allin,Chasego/codi,cc13ny/Allin,Chasego/cod,Chasego/cod,Chasego/codirit,cc13ny/Allin,Chasego/codirit,Chasego/cod,cc13ny/algo,cc13ny/algo,cc13ny/algo,Chasego/cod,Chasego/codirit,Chasego/codirit,cc13ny/algo
--- +++ @@ -10,7 +10,7 @@ for w in t: if w not in chrs: chrs[w] = 1 << (ord(w) - 97) - res += chrs[w] + res += chrs[w] # it can be overflow for w in s: res -= chrs[w] return chr(len(bin(res)) + 94)
b0fd7fc1866cd85e9d68d5716d8f5aeaff1218c1
tests/__init__.py
tests/__init__.py
"""Unit test suite for HXL proxy.""" import os import re import hxl import unittest.mock TEST_DATA_FILE = os.path.join(os.path.dirname(__file__), 'test-data.sql') # # Mock URL access for local testing # def mock_open_url(url, allow_local=False, timeout=None, verify=True): """ Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/' + filename) else: # Assume it's a file path = url return open(path, 'rb') def resolve_path(filename): """Resolve a relative path against this module's directory.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url # end
"""Unit test suite for HXL proxy.""" import os import re import hxl import unittest.mock TEST_DATA_FILE = os.path.join(os.path.dirname(__file__), 'test-data.sql') # # Mock URL access for local testing # def mock_open_url(url, allow_local=False, timeout=None, verify=True): """ Open local files instead of URLs. If it's a local file path, leave it alone; otherwise, open as a file under ./files/ This is meant as a side effect for unittest.mock.Mock """ if re.match(r'https?:', url): # Looks like a URL filename = re.sub(r'^.*/([^/]+)$', '\\1', url) path = resolve_path('files/' + filename) else: # Assume it's a file path = url return (open(path, 'rb'), None, None, None) def resolve_path(filename): """Resolve a relative path against this module's directory.""" return os.path.join(os.path.dirname(__file__), filename) # Target function to replace for mocking URL access. URL_MOCK_TARGET = 'hxl.io.open_url_or_file' # Mock object to replace hxl.io.make_stream URL_MOCK_OBJECT = unittest.mock.Mock() URL_MOCK_OBJECT.side_effect = mock_open_url # end
Update mock method to match changed return value for libhxl
Update mock method to match changed return value for libhxl
Python
unlicense
HXLStandard/hxl-proxy,HXLStandard/hxl-proxy,HXLStandard/hxl-proxy,HXLStandard/hxl-proxy
--- +++ @@ -26,7 +26,7 @@ else: # Assume it's a file path = url - return open(path, 'rb') + return (open(path, 'rb'), None, None, None) def resolve_path(filename): """Resolve a relative path against this module's directory."""
bd8b0c2c47c1a9433c38123f2533c796fd7f8521
tracing/tracing/extras/symbolizer/symbolize_trace_macho_reader_unittest.py
tracing/tracing/extras/symbolizer/symbolize_trace_macho_reader_unittest.py
#!/usr/bin/env python # Copyright 2017 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. import sys import unittest from . import symbolize_trace_macho_reader class AtosRegexTest(unittest.TestCase): def testRegex(self): if sys.platform != "darwin": return file_name = "/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit" result = symbolize_trace_macho_reader.ReadMachOTextLoadAddress(file_name) self.assertNotEqual(None, result) file_name = "/System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa" result = symbolize_trace_macho_reader.ReadMachOTextLoadAddress(file_name) self.assertNotEqual(None, result) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # Copyright 2017 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. import os import sys import unittest from . import symbolize_trace_macho_reader class AtosRegexTest(unittest.TestCase): def testRegex(self): if sys.platform != "darwin": return file_name = "/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit" # TODO(crbug.com/1275181) if os.path.exists(file_name): result = symbolize_trace_macho_reader.ReadMachOTextLoadAddress(file_name) self.assertNotEqual(None, result) file_name = "/System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa" # TODO(crbug.com/1275181) if os.path.exists(file_name): result = symbolize_trace_macho_reader.ReadMachOTextLoadAddress(file_name) self.assertNotEqual(None, result) if __name__ == '__main__': unittest.main()
Work around test failure on Catapult CQ
[Catapult] Work around test failure on Catapult CQ Bug: chromium:1275181 Change-Id: I78e2f62371ebc872706366bb897336c8e5c7f02f Reviewed-on: https://chromium-review.googlesource.com/c/catapult/+/3309287 Commit-Queue: John Chen <334fbfbb4df7c78f091ea1b77c69ca6ac731a3f3@chromium.org> Commit-Queue: Ryan Heise <50ee0a56d43e9e15503d071e9ceb1a6059353025@google.com> Auto-Submit: John Chen <334fbfbb4df7c78f091ea1b77c69ca6ac731a3f3@chromium.org> Reviewed-by: Ryan Heise <50ee0a56d43e9e15503d071e9ceb1a6059353025@google.com>
Python
bsd-3-clause
catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult
--- +++ @@ -3,6 +3,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import os import sys import unittest @@ -14,12 +15,16 @@ if sys.platform != "darwin": return file_name = "/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit" - result = symbolize_trace_macho_reader.ReadMachOTextLoadAddress(file_name) - self.assertNotEqual(None, result) + # TODO(crbug.com/1275181) + if os.path.exists(file_name): + result = symbolize_trace_macho_reader.ReadMachOTextLoadAddress(file_name) + self.assertNotEqual(None, result) file_name = "/System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa" - result = symbolize_trace_macho_reader.ReadMachOTextLoadAddress(file_name) - self.assertNotEqual(None, result) + # TODO(crbug.com/1275181) + if os.path.exists(file_name): + result = symbolize_trace_macho_reader.ReadMachOTextLoadAddress(file_name) + self.assertNotEqual(None, result) if __name__ == '__main__':
0b4562d15c1c8b544847e7988d26120556a3110d
tests/conftest.py
tests/conftest.py
import os TEST_CONFIG = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cosmoconfig_test.yaml') # Check to make sure that the test config file is being used. If not, don't run the tests if os.environ['COSMO_CONFIG'] != TEST_CONFIG: raise TypeError('Tests should only be executed with the testing configuration file')
import os import pytest TEST_CONFIG = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cosmoconfig_test.yaml') # Check to make sure that the test config file is being used. If not, don't run the tests if os.environ['COSMO_CONFIG'] != TEST_CONFIG: raise TypeError('Tests should only be executed with the testing configuration file') @pytest.fixture(scope='session', autouse=True) def db_cleanup(): yield # The tests don't actually need this test "value" # Cleanup os.remove('test.db') # Delete test database file after the completion of all tests # Remove temporary shared memory file if it exists if os.path.exists('test.db-shm'): os.remove('test.db-shm') # Remove temporary write-ahead log file if it exists if os.path.exists('test.db-wal'): os.remove('test.db-wal')
Add session-scope clean up that removes the test database
Add session-scope clean up that removes the test database
Python
bsd-3-clause
justincely/cos_monitoring
--- +++ @@ -1,7 +1,24 @@ import os +import pytest TEST_CONFIG = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cosmoconfig_test.yaml') # Check to make sure that the test config file is being used. If not, don't run the tests if os.environ['COSMO_CONFIG'] != TEST_CONFIG: raise TypeError('Tests should only be executed with the testing configuration file') + + +@pytest.fixture(scope='session', autouse=True) +def db_cleanup(): + yield # The tests don't actually need this test "value" + + # Cleanup + os.remove('test.db') # Delete test database file after the completion of all tests + + # Remove temporary shared memory file if it exists + if os.path.exists('test.db-shm'): + os.remove('test.db-shm') + + # Remove temporary write-ahead log file if it exists + if os.path.exists('test.db-wal'): + os.remove('test.db-wal')
056f794012033fdb6c1eeecfd48dbf3aa76f036a
tests/runtests.py
tests/runtests.py
#!/usr/bin/env python import os import sys from unittest import defaultTestLoader, TextTestRunner, TestSuite TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n') def make_suite(prefix='', extra=()): tests = TESTS + extra test_names = list(prefix + x for x in tests) suite = TestSuite() suite.addTest(defaultTestLoader.loadTestsFromNames(test_names)) return suite def additional_tests(): """ This is called automatically by setup.py test """ return make_suite('tests.') def main(): extra_tests = tuple(x for x in sys.argv[1:] if '-' not in x) suite = make_suite('', ) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) runner = TextTestRunner(verbosity=(sys.argv.count('-v') - sys.argv.count('-q') + 1)) result = runner.run(suite) sys.exit(not result.wasSuccessful()) if __name__ == '__main__': main()
#!/usr/bin/env python import os import sys from unittest import defaultTestLoader, TextTestRunner, TestSuite TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n') def make_suite(prefix='', extra=()): tests = TESTS + extra test_names = list(prefix + x for x in tests) suite = TestSuite() suite.addTest(defaultTestLoader.loadTestsFromNames(test_names)) return suite def additional_tests(): """ This is called automatically by setup.py test """ return make_suite('tests.') def main(): extra_tests = tuple(x for x in sys.argv[1:] if '-' not in x) suite = make_suite('', extra_tests) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) runner = TextTestRunner(verbosity=(sys.argv.count('-v') - sys.argv.count('-q') + 1)) result = runner.run(suite) sys.exit(not result.wasSuccessful()) if __name__ == '__main__': main()
Add back in running of extra tests
Add back in running of extra tests
Python
bsd-3-clause
Khan/wtforms
--- +++ @@ -20,7 +20,7 @@ def main(): extra_tests = tuple(x for x in sys.argv[1:] if '-' not in x) - suite = make_suite('', ) + suite = make_suite('', extra_tests) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
07c7f18733bad651ef110b529422fd42bdcf27aa
src/encoded/views/__init__.py
src/encoded/views/__init__.py
from pyramid.httpexceptions import HTTPNotFound from pyramid.view import view_config from random import randint from ..contentbase import ( Root, location_root, ) def includeme(config): # Random processid so etags are invalidated after restart. config.registry['encoded.processid'] = randint(0, 2 ** 32) config.add_route('schema', '/profiles/{item_type}.json') config.add_route('graph', '/profiles/graph.dot') config.scan() @location_root class EncodedRoot(Root): properties = { 'title': 'Home', 'portal_title': 'ENCODE 3', } @view_config(context=Root, request_method='GET') def home(context, request): result = context.__json__(request) result.update({ '@id': request.resource_path(context), '@type': ['portal'], # 'login': {'href': request.resource_path(context, 'login')}, }) return result @view_config(route_name='schema', request_method='GET') def schema(context, request): item_type = request.matchdict['item_type'] try: collection = context.by_item_type[item_type] except KeyError: raise HTTPNotFound(item_type) return collection.schema
import os from pyramid.httpexceptions import HTTPNotFound from pyramid.view import view_config from random import randint from ..contentbase import ( Root, location_root, ) def includeme(config): config.registry['encoded.processid'] = os.getppid() config.add_route('schema', '/profiles/{item_type}.json') config.add_route('graph', '/profiles/graph.dot') config.scan() @location_root class EncodedRoot(Root): properties = { 'title': 'Home', 'portal_title': 'ENCODE 3', } @view_config(context=Root, request_method='GET') def home(context, request): result = context.__json__(request) result.update({ '@id': request.resource_path(context), '@type': ['portal'], # 'login': {'href': request.resource_path(context, 'login')}, }) return result @view_config(route_name='schema', request_method='GET') def schema(context, request): item_type = request.matchdict['item_type'] try: collection = context.by_item_type[item_type] except KeyError: raise HTTPNotFound(item_type) return collection.schema
Use parent process id, that of the apache process.
Use parent process id, that of the apache process.
Python
mit
T2DREAM/t2dream-portal,kidaa/encoded,T2DREAM/t2dream-portal,ENCODE-DCC/encoded,4dn-dcic/fourfront,ENCODE-DCC/encoded,ClinGen/clincoded,philiptzou/clincoded,hms-dbmi/fourfront,kidaa/encoded,4dn-dcic/fourfront,ClinGen/clincoded,T2DREAM/t2dream-portal,kidaa/encoded,kidaa/encoded,ENCODE-DCC/snovault,T2DREAM/t2dream-portal,philiptzou/clincoded,ENCODE-DCC/snovault,4dn-dcic/fourfront,4dn-dcic/fourfront,philiptzou/clincoded,ClinGen/clincoded,philiptzou/clincoded,hms-dbmi/fourfront,ENCODE-DCC/snovault,ENCODE-DCC/encoded,hms-dbmi/fourfront,kidaa/encoded,hms-dbmi/fourfront,ENCODE-DCC/snovault,ClinGen/clincoded,ENCODE-DCC/snovault,philiptzou/clincoded,hms-dbmi/fourfront,ENCODE-DCC/encoded,ClinGen/clincoded
--- +++ @@ -1,3 +1,4 @@ +import os from pyramid.httpexceptions import HTTPNotFound from pyramid.view import view_config from random import randint @@ -8,8 +9,7 @@ def includeme(config): - # Random processid so etags are invalidated after restart. - config.registry['encoded.processid'] = randint(0, 2 ** 32) + config.registry['encoded.processid'] = os.getppid() config.add_route('schema', '/profiles/{item_type}.json') config.add_route('graph', '/profiles/graph.dot') config.scan()
0bfee1fff698a984130a99c7ccbff4a787a68eca
cla_backend/apps/status/tests/smoketests.py
cla_backend/apps/status/tests/smoketests.py
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.connect() conn.release()
import unittest from celery import Celery from django.conf import settings from django.db import connection class SmokeTests(unittest.TestCase): def setUp(self): pass def test_can_access_db(self): "access the database" cursor = connection.cursor() cursor.execute('SELECT 1') row = cursor.fetchone() self.assertEqual(1, row[0]) def test_can_access_celery(self): "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() conn.config_from_object('django.conf:settings') conn.connect() conn.release()
Use same settings in smoke test as in real use
Use same settings in smoke test as in real use
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
--- +++ @@ -21,5 +21,6 @@ "connect to SQS" if not getattr(settings, 'CELERY_ALWAYS_EAGER', False): conn = Celery('cla_backend').connection() + conn.config_from_object('django.conf:settings') conn.connect() conn.release()
186d3c637760668d960c50c9f94fad7ff4769598
molly/utils/management/commands/generate_cache_manifest.py
molly/utils/management/commands/generate_cache_manifest.py
import os import os.path from django.core.management.base import NoArgsCommand from django.conf import settings class Command(NoArgsCommand): can_import_settings = True def handle_noargs(self, **options): cache_manifest_path = os.path.join(settings.STATIC_ROOT, 'cache.manifest') static_prefix_length = len(settings.STATIC_ROOT.split(os.sep)) with open(cache_manifest_path, 'w') as cache_manifest: print >>cache_manifest, "CACHE MANIFEST" print >>cache_manifest, "CACHE:" for root, dirs, files in os.walk(settings.STATIC_ROOT): url = '/'.join(root.split(os.sep)[static_prefix_length:]) for file in files: print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
import os import os.path from django.core.management.base import NoArgsCommand from django.conf import settings class Command(NoArgsCommand): can_import_settings = True def handle_noargs(self, **options): cache_manifest_path = os.path.join(settings.STATIC_ROOT, 'cache.manifest') static_prefix_length = len(settings.STATIC_ROOT.split(os.sep)) with open(cache_manifest_path, 'w') as cache_manifest: print >>cache_manifest, "CACHE MANIFEST" print >>cache_manifest, "CACHE:" for root, dirs, files in os.walk(settings.STATIC_ROOT): if root == settings.STATIC_ROOT: # Don't cache admin media or markers dirs.remove('admin') dirs.remove('markers') url = '/'.join(root.split(os.sep)[static_prefix_length:]) for file in files: # Don't cache uncompressed JS/CSS _, ext = os.path.splitext(file) if ext in ('.js','.css') and 'c' != url.split('/')[0]: continue print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
Revert "Revert "Don't cache markers, admin files or uncompressed JS/CSS""
Revert "Revert "Don't cache markers, admin files or uncompressed JS/CSS"" This reverts commit 6c488d267cd5919eb545855a522d5cd7ec7d0fec.
Python
apache-2.0
mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject
--- +++ @@ -16,6 +16,14 @@ print >>cache_manifest, "CACHE MANIFEST" print >>cache_manifest, "CACHE:" for root, dirs, files in os.walk(settings.STATIC_ROOT): + if root == settings.STATIC_ROOT: + # Don't cache admin media or markers + dirs.remove('admin') + dirs.remove('markers') url = '/'.join(root.split(os.sep)[static_prefix_length:]) for file in files: + # Don't cache uncompressed JS/CSS + _, ext = os.path.splitext(file) + if ext in ('.js','.css') and 'c' != url.split('/')[0]: + continue print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
223c268d58645fbecdddb24ff84587dc803bfc87
braubuddy/tests/thermometer/test_auto.py
braubuddy/tests/thermometer/test_auto.py
""" Braubuddy Dummy thermometer unit tests. """ import unittest from mock import patch, call, MagicMock from braubuddy.thermometer import auto from braubuddy.thermometer import dummy from braubuddy.thermometer import ds18b20_gpio from braubuddy.thermometer import temper_usb from braubuddy.thermometer import DeviceError from braubuddy.thermometer import ReadError class TestAuto(unittest.TestCase): @patch('braubuddy.thermometer.ds18b20_gpio.ds18b20') @patch('braubuddy.thermometer.temper_usb.temperusb') def test_dummy_returned_if_no_devices(self, mk_temperusb, mk_ds18b20): """Dummy thermometer is created if no real thermometers discovered.""" mk_ds18b20.DS18B20 = MagicMock(side_effect = Exception('Some Error')) mk_temperusb.TemperHandler.return_value.get_devices.return_value = [] thermometer = auto.AutoThermometer() self.assertIsInstance(thermometer, dummy.DummyThermometer)
""" Braubuddy Auto thermometer unit tests. """ import unittest from mock import patch, call, MagicMock from braubuddy.thermometer import auto from braubuddy.thermometer import dummy from braubuddy.thermometer import ds18b20_gpio from braubuddy.thermometer import temper_usb class TestAuto(unittest.TestCase): @patch('braubuddy.thermometer.ds18b20_gpio.ds18b20') @patch('braubuddy.thermometer.temper_usb.temperusb') def test_dummy_returned_if_no_devices(self, mk_temperusb, mk_ds18b20): """Dummy thermometer is created if no real thermometers discovered.""" mk_ds18b20.DS18B20 = MagicMock(side_effect = Exception('Some Error')) mk_temperusb.TemperHandler.return_value.get_devices.return_value = [] thermometer = auto.AutoThermometer() self.assertIsInstance(thermometer, dummy.DummyThermometer)
Fix docstring and remove unnecessary imports.
Fix docstring and remove unnecessary imports.
Python
bsd-3-clause
amorphic/braubuddy,amorphic/braubuddy,amorphic/braubuddy
--- +++ @@ -1,5 +1,5 @@ """ -Braubuddy Dummy thermometer unit tests. +Braubuddy Auto thermometer unit tests. """ import unittest @@ -8,8 +8,6 @@ from braubuddy.thermometer import dummy from braubuddy.thermometer import ds18b20_gpio from braubuddy.thermometer import temper_usb -from braubuddy.thermometer import DeviceError -from braubuddy.thermometer import ReadError class TestAuto(unittest.TestCase):
53c751e86b6ca2dd5076e0a09e7c0e4663c1fcbc
edx_data_research/cli/commands.py
edx_data_research/cli/commands.py
""" In this module we define the interface between the cli input provided by the user and the analytics required by the user """ from edx_data_research.reporting.basic import (user_info, ip_to_country, course_completers) from edx_data_research.reporting.edx_base import EdX def cmd_list(args): """ List all the analytics commands and their summary """ print 'list all' def cmd_report_basic(args): """ Run basic analytics """ edx_obj = EdX(args) globals()[args.basic.replace('-', '_')](edx_obj) def cmd_report_problem_id(args): print 'problem id!!!'
""" In this module we define the interface between the cli input provided by the user and the analytics required by the user """ from edx_data_research.reporting.basic import (user_info, ip_to_country, course_completers) from edx_data_research.reporting.edx_base import EdX from edx_data_research.reporting.problem_ids.problem_id import (ProblemId, problem_id) def cmd_list(args): """ List all the analytics commands and their summary """ print 'list all' def cmd_report_basic(args): """ Run basic analytics """ edx_obj = EdX(args) globals()[args.basic.replace('-', '_')](edx_obj) def cmd_report_problem_id(args): edx_obj = ProblemId(args) problem_id(edx_obj)
Add function to call problem_ids report generation
Add function to call problem_ids report generation
Python
mit
McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research
--- +++ @@ -5,6 +5,8 @@ from edx_data_research.reporting.basic import (user_info, ip_to_country, course_completers) from edx_data_research.reporting.edx_base import EdX +from edx_data_research.reporting.problem_ids.problem_id import (ProblemId, + problem_id) def cmd_list(args): @@ -21,4 +23,5 @@ globals()[args.basic.replace('-', '_')](edx_obj) def cmd_report_problem_id(args): - print 'problem id!!!' + edx_obj = ProblemId(args) + problem_id(edx_obj)
fe715bb784326a661b14d01e02189074228e7c13
securedrop/tests/test_manage.py
securedrop/tests/test_manage.py
# -*- coding: utf-8 -*- import manage import unittest class TestManagePy(unittest.TestCase): def test_parse_args(self): # just test that the arg parser is stable manage.get_args()
# -*- coding: utf-8 -*- import manage import mock from StringIO import StringIO import sys import unittest import __builtin__ import utils class TestManagePy(unittest.TestCase): def test_parse_args(self): # just test that the arg parser is stable manage.get_args() class TestManagementCommand(unittest.TestCase): def setUp(self): utils.env.setup() def tearDown(self): utils.env.teardown() @mock.patch("__builtin__.raw_input", return_value='N') @mock.patch("manage.getpass", return_value='testtesttest') @mock.patch("sys.stdout", new_callable=StringIO) def test_exception_handling_when_duplicate_username(self, mock_raw_input, mock_getpass, mock_stdout): """Regression test for duplicate username logic in manage.py""" # Inserting the user for the first time should succeed return_value = manage._add_user() self.assertEqual(return_value, 0) self.assertIn('successfully added', sys.stdout.getvalue()) # Inserting the user for a second time should fail return_value = manage._add_user() self.assertEqual(return_value, 1) self.assertIn('ERROR: That username is already taken!', sys.stdout.getvalue())
Add unit test to check duplicate username error is handled in manage.py
Add unit test to check duplicate username error is handled in manage.py
Python
agpl-3.0
heartsucker/securedrop,conorsch/securedrop,ageis/securedrop,garrettr/securedrop,heartsucker/securedrop,conorsch/securedrop,conorsch/securedrop,ehartsuyker/securedrop,micahflee/securedrop,heartsucker/securedrop,micahflee/securedrop,ehartsuyker/securedrop,ehartsuyker/securedrop,ageis/securedrop,ehartsuyker/securedrop,garrettr/securedrop,garrettr/securedrop,micahflee/securedrop,ageis/securedrop,ehartsuyker/securedrop,conorsch/securedrop,ehartsuyker/securedrop,ageis/securedrop,garrettr/securedrop,heartsucker/securedrop,heartsucker/securedrop,micahflee/securedrop,conorsch/securedrop
--- +++ @@ -1,10 +1,43 @@ # -*- coding: utf-8 -*- import manage +import mock +from StringIO import StringIO +import sys import unittest +import __builtin__ + +import utils class TestManagePy(unittest.TestCase): def test_parse_args(self): # just test that the arg parser is stable manage.get_args() + + +class TestManagementCommand(unittest.TestCase): + def setUp(self): + utils.env.setup() + + def tearDown(self): + utils.env.teardown() + + @mock.patch("__builtin__.raw_input", return_value='N') + @mock.patch("manage.getpass", return_value='testtesttest') + @mock.patch("sys.stdout", new_callable=StringIO) + def test_exception_handling_when_duplicate_username(self, mock_raw_input, + mock_getpass, + mock_stdout): + """Regression test for duplicate username logic in manage.py""" + + # Inserting the user for the first time should succeed + return_value = manage._add_user() + self.assertEqual(return_value, 0) + self.assertIn('successfully added', sys.stdout.getvalue()) + + # Inserting the user for a second time should fail + return_value = manage._add_user() + self.assertEqual(return_value, 1) + self.assertIn('ERROR: That username is already taken!', + sys.stdout.getvalue())
f137f5b6f5453938e0cc858268a79ee5ef8283d0
version.py
version.py
major = 0 minor=0 patch=21 branch="master" timestamp=1376526439.16
major = 0 minor=0 patch=22 branch="master" timestamp=1376526477.22
Tag commit for v0.0.22-master generated by gitmake.py
Tag commit for v0.0.22-master generated by gitmake.py
Python
mit
ryansturmer/gitmake
--- +++ @@ -1,5 +1,5 @@ major = 0 minor=0 -patch=21 +patch=22 branch="master" -timestamp=1376526439.16 +timestamp=1376526477.22
c0cecdc7e754090f25f48637de88d2d07a3ef58f
ctypeslib/test/test_dynmodule.py
ctypeslib/test/test_dynmodule.py
# Basic test of dynamic code generation import unittest import os, glob import stdio from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): def tearDown(self): for fnm in glob.glob(stdio._gen_basename + ".*"): try: os.remove(fnm) except IOError: pass def test_fopen(self): self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE)) self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING]) def test_constants(self): self.failUnlessEqual(stdio.O_RDONLY, 0) self.failUnlessEqual(stdio.O_WRONLY, 1) self.failUnlessEqual(stdio.O_RDWR, 2) def test_compiler_errors(self): from ctypeslib.codegen.cparser import CompilerError from ctypeslib.dynamic_module import include self.failUnlessRaises(CompilerError, lambda: include("#error")) if __name__ == "__main__": unittest.main()
# Basic test of dynamic code generation import unittest import os, glob import stdio from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): def test_fopen(self): self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE)) self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING]) def test_constants(self): self.failUnlessEqual(stdio.O_RDONLY, 0) self.failUnlessEqual(stdio.O_WRONLY, 1) self.failUnlessEqual(stdio.O_RDWR, 2) def test_compiler_errors(self): from ctypeslib.codegen.cparser import CompilerError from ctypeslib.dynamic_module import include self.failUnlessRaises(CompilerError, lambda: include("#error")) if __name__ == "__main__": unittest.main()
Remove now useless TearDown method.
Remove now useless TearDown method.
Python
mit
sugarmanz/ctypeslib
--- +++ @@ -6,12 +6,6 @@ from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): - def tearDown(self): - for fnm in glob.glob(stdio._gen_basename + ".*"): - try: - os.remove(fnm) - except IOError: - pass def test_fopen(self): self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE))
dbbbb763db09fdf777558b781a29d4b8a71b3e62
src/DeepLearn/venv/Lab/Array.py
src/DeepLearn/venv/Lab/Array.py
import numpy as np arr1 = np.array([[1,2],[3,4]]) arr2 = np.array([[5,6],[7,8]]) arr3 = np.array([[1,2],[3,4],[5,6]]) arr4 = np.array([7,8]) # 列出矩陣的維度 # print(arr1.shape) # print(arr1.shape[0]) # 矩陣乘積 # print(np.dot(arr1,arr2)) print(np.dot(arr3,arr4)) # print(arr1*arr2)
import numpy as np arr1 = np.array([[1,2],[3,4]]) arr2 = np.array([[5,6],[7,8]]) arr3 = np.array([[1,2],[3,4],[5,6]]) arr4 = np.array([7,8]) # 列出矩陣的維度 # print(arr1.shape) # print(arr1.shape[0]) # 矩陣乘積 # print(np.dot(arr1,arr2)) print(np.dot(arr3,arr4)) print(1*7+2*7) # print(arr1*arr2)
Create 3 layer nt sample
Create 3 layer nt sample
Python
mit
KarateJB/Python.Practice,KarateJB/Python.Practice,KarateJB/Python.Practice,KarateJB/Python.Practice
--- +++ @@ -11,7 +11,9 @@ # 矩陣乘積 # print(np.dot(arr1,arr2)) -print(np.dot(arr3,arr4)) +print(np.dot(arr3,arr4)) + +print(1*7+2*7) # print(arr1*arr2)
84aaf1b99c609cffe4f2a9d8825f20fa585fc3d9
calaccess_website/management/commands/updatedownloadswebsite.py
calaccess_website/management/commands/updatedownloadswebsite.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ import logging from django.core.management import call_command from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand logger = logging.getLogger(__name__) class Command(updatecommand): """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ help = 'Update to the latest CAL-ACCESS snapshot and bake static website pages' def add_arguments(self, parser): """ Adds custom arguments specific to this command. """ super(Command, self).add_arguments(parser) parser.add_argument( "--publish", action="store_true", dest="keep_files", default=False, help="Publish baked content" ) def handle(self, *args, **options): """ Make it happen. """ super(Command, self).handle(*args, **options) self.header('Creating latest file links') call_command('createlatestlinks') self.header('Baking downloads-website content') call_command('build') if options['publish']: self.header('Publishing baked content to S3 bucket.') call_command('publish') self.success("Done!")
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ import logging from django.core.management import call_command from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand logger = logging.getLogger(__name__) class Command(updatecommand): """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ help = 'Update to the latest CAL-ACCESS snapshot and bake static website pages' def add_arguments(self, parser): """ Adds custom arguments specific to this command. """ super(Command, self).add_arguments(parser) parser.add_argument( "--publish", action="store_true", dest="publish", default=False, help="Publish baked content" ) def handle(self, *args, **options): """ Make it happen. """ super(Command, self).handle(*args, **options) self.header('Creating latest file links') call_command('createlatestlinks') self.header('Baking downloads-website content') call_command('build') if options['publish']: self.header('Publishing baked content to S3 bucket.') call_command('publish') self.success("Done!")
Store --keep-publish value in options['publish'] (duh)
Store --keep-publish value in options['publish'] (duh)
Python
mit
california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website
--- +++ @@ -23,7 +23,7 @@ parser.add_argument( "--publish", action="store_true", - dest="keep_files", + dest="publish", default=False, help="Publish baked content" )
9756366d7bca75c0ea89ce1fface6a7d224f54f7
web/api/__init__.py
web/api/__init__.py
from flask import Blueprint from . import v0 bp = Blueprint('api', __name__) v0.api.init_app(bp) def errorpage(e): code = getattr(e, 'code', 500) if code == 404: return jsonify(msg=str(e)) return jsonify(msg="error", code=code)
from flask import Blueprint from . import v0 bp = Blueprint('api', __name__) v0.api.init_app(bp) def errorpage(e): return v0.api.handle_error(e)
Improve error handling of sipa API
Improve error handling of sipa API
Python
apache-2.0
agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft
--- +++ @@ -6,7 +6,4 @@ v0.api.init_app(bp) def errorpage(e): - code = getattr(e, 'code', 500) - if code == 404: - return jsonify(msg=str(e)) - return jsonify(msg="error", code=code) + return v0.api.handle_error(e)
439f57419d861b7e180453263e413ed2b3c56826
restclients/catalyst/gradebook.py
restclients/catalyst/gradebook.py
""" This is the interface for interacting w/ Catalyst GradeBook """ from restclients.catalyst import Catalyst from restclients.exceptions import DataFailureException from restclients.dao import Catalyst_DAO class GradeBook(object): def get_grades_for_student_and_term(self, netid, year, quarter): """ returns a restclients.models.catalyst.CourseGradeData object """ url = "/rest/gradebook/v1/grades/%s/%s/%s" % (netid, year, quarter) dao = Catalyst_DAO() response = dao.getURL(url, { "Accept": "application/json" }) if response.status != 200: raise DataFailureException(url, response.status, response.data) return Catalyst().parse_grade_data("GradeBook", response.data)
""" This is the interface for interacting w/ Catalyst GradeBook """ from restclients.catalyst import Catalyst from restclients.exceptions import DataFailureException from restclients.dao import Catalyst_DAO class GradeBook(object): def get_grades_for_student_and_term(self, netid, year, quarter): """ returns a restclients.models.catalyst.CourseGradeData object """ quarter = quarter.capitalize() url = "/rest/gradebook/v1/grades/%s/%s/%s" % (netid, year, quarter) dao = Catalyst_DAO() response = dao.getURL(url, { "Accept": "application/json" }) if response.status != 200: raise DataFailureException(url, response.status, response.data) return Catalyst().parse_grade_data("GradeBook", response.data)
Make sure quarters are in the format catalyst wants
Make sure quarters are in the format catalyst wants git-svn-id: 24222aecec59d6833d1342da1ba59f27d6df2b08@636 3f86a6b1-f777-4bc2-bf3d-37c8dbe90857
Python
apache-2.0
uw-it-aca/uw-restclients,uw-it-aca/uw-restclients,UWIT-IAM/uw-restclients,UWIT-IAM/uw-restclients,uw-it-cte/uw-restclients,jeffFranklin/uw-restclients,UWIT-IAM/uw-restclients,jeffFranklin/uw-restclients,uw-it-cte/uw-restclients,jeffFranklin/uw-restclients,uw-it-cte/uw-restclients
--- +++ @@ -12,6 +12,7 @@ """ returns a restclients.models.catalyst.CourseGradeData object """ + quarter = quarter.capitalize() url = "/rest/gradebook/v1/grades/%s/%s/%s" % (netid, year, quarter) dao = Catalyst_DAO() response = dao.getURL(url, { "Accept": "application/json" })
2b933faaf2f9aba9158d56c49367e423ea1a2ea3
pelican/plugins/related_posts.py
pelican/plugins/related_posts.py
from pelican import signals """ Related posts plugin for Pelican ================================ Adds related_posts variable to article's context """ related_posts = [] def add_related_posts(generator, metadata): if 'tags' in metadata: for tag in metadata['tags']: #print tag for related_article in generator.tags[tag]: related_posts.append(related_article) if len(related_posts) < 1: return relation_score = dict( \ zip(set(related_posts), \ map(related_posts.count, \ set(related_posts)))) ranked_related = sorted(relation_score, key=relation_score.get) metadata["related_posts"] = ranked_related[:5] else: return def register(): signals.article_generate_context.connect(add_related_posts)
from pelican import signals """ Related posts plugin for Pelican ================================ Adds related_posts variable to article's context Settings -------- To enable, add from pelican.plugins import related_posts PLUGINS = [related_posts] to your settings.py. Usage ----- {% if article.related_posts %} <ul> {% for related_post in article.related_posts %} <li>{{ related_post }}</li> {% endfor %} </ul> {% endif %} """ related_posts = [] def add_related_posts(generator, metadata): if 'tags' in metadata: for tag in metadata['tags']: #print tag for related_article in generator.tags[tag]: related_posts.append(related_article) if len(related_posts) < 1: return relation_score = dict( \ zip(set(related_posts), \ map(related_posts.count, \ set(related_posts)))) ranked_related = sorted(relation_score, key=relation_score.get) metadata["related_posts"] = ranked_related[:5] else: return def register(): signals.article_generate_context.connect(add_related_posts)
Add usage and intallation instructions
Add usage and intallation instructions
Python
agpl-3.0
alexras/pelican,HyperGroups/pelican,jvehent/pelican,11craft/pelican,51itclub/pelican,number5/pelican,avaris/pelican,treyhunner/pelican,number5/pelican,deved69/pelican-1,lazycoder-ru/pelican,Polyconseil/pelican,simonjj/pelican,ehashman/pelican,koobs/pelican,florianjacob/pelican,joetboole/pelican,sunzhongwei/pelican,GiovanniMoretti/pelican,Summonee/pelican,Scheirle/pelican,rbarraud/pelican,jimperio/pelican,karlcow/pelican,ls2uper/pelican,lazycoder-ru/pelican,janaurka/git-debug-presentiation,catdog2/pelican,GiovanniMoretti/pelican,JeremyMorgan/pelican,zackw/pelican,levanhien8/pelican,levanhien8/pelican,jimperio/pelican,ehashman/pelican,liyonghelpme/myBlog,liyonghelpme/myBlog,goerz/pelican,btnpushnmunky/pelican,abrahamvarricatt/pelican,crmackay/pelican,iurisilvio/pelican,arty-name/pelican,deanishe/pelican,TC01/pelican,goerz/pelican,UdeskDeveloper/pelican,Scheirle/pelican,alexras/pelican,janaurka/git-debug-presentiation,justinmayer/pelican,farseerfc/pelican,iKevinY/pelican,jimperio/pelican,treyhunner/pelican,JeremyMorgan/pelican,karlcow/pelican,abrahamvarricatt/pelican,51itclub/pelican,11craft/pelican,talha131/pelican,Rogdham/pelican,eevee/pelican,joetboole/pelican,number5/pelican,catdog2/pelican,btnpushnmunky/pelican,lucasplus/pelican,farseerfc/pelican,HyperGroups/pelican,gymglish/pelican,11craft/pelican,deved69/pelican-1,simonjj/pelican,florianjacob/pelican,jvehent/pelican,Scheirle/pelican,getpelican/pelican,Polyconseil/pelican,kennethlyn/pelican,karlcow/pelican,eevee/pelican,douglaskastle/pelican,ls2uper/pelican,eevee/pelican,lucasplus/pelican,jo-tham/pelican,garbas/pelican,Rogdham/pelican,levanhien8/pelican,joetboole/pelican,iurisilvio/pelican,0xMF/pelican,garbas/pelican,Rogdham/pelican,florianjacob/pelican,koobs/pelican,GiovanniMoretti/pelican,simonjj/pelican,ls2uper/pelican,kernc/pelican,kernc/pelican,treyhunner/pelican,ionelmc/pelican,iKevinY/pelican,rbarraud/pelican,JeremyMorgan/pelican,HyperGroups/pelican,douglaskastle/pelican,abrahamvarricatt/pelican,crmackay/pelican,crmackay/pelican,kernc/pelican,deanishe/pelican,zackw/pelican,ehashman/pelican,lazycoder-ru/pelican,sunzhongwei/pelican,janaurka/git-debug-presentiation,talha131/pelican,rbarraud/pelican,UdeskDeveloper/pelican,deved69/pelican-1,kennethlyn/pelican,51itclub/pelican,avaris/pelican,alexras/pelican,fbs/pelican,iurisilvio/pelican,TC01/pelican,douglaskastle/pelican,TC01/pelican,kennethlyn/pelican,Summonee/pelican,ingwinlu/pelican,Summonee/pelican,sunzhongwei/pelican,jo-tham/pelican,sunzhongwei/pelican,gymglish/pelican,koobs/pelican,zackw/pelican,deanishe/pelican,liyonghelpme/myBlog,catdog2/pelican,liyonghelpme/myBlog,getpelican/pelican,garbas/pelican,UdeskDeveloper/pelican,ingwinlu/pelican,btnpushnmunky/pelican,lucasplus/pelican,Natim/pelican,gymglish/pelican,liyonghelpme/myBlog,jvehent/pelican,goerz/pelican
--- +++ @@ -5,7 +5,29 @@ ================================ Adds related_posts variable to article's context + +Settings +-------- +To enable, add + + from pelican.plugins import related_posts + PLUGINS = [related_posts] + +to your settings.py. + +Usage +----- + {% if article.related_posts %} + <ul> + {% for related_post in article.related_posts %} + <li>{{ related_post }}</li> + {% endfor %} + </ul> + {% endif %} + + """ + related_posts = [] def add_related_posts(generator, metadata): if 'tags' in metadata:
755e4c5ca84072d9983de0b1a0e76419cde77f66
lib/repo/git_hooks/update.d/02-block_change_top_level_master.py
lib/repo/git_hooks/update.d/02-block_change_top_level_master.py
#!/usr/bin/env python3 import os import subprocess import sys if __name__ == '__main__': ref_name = sys.argv[1] old_commit = sys.argv[2] new_commit = sys.argv[3] # no need to check if old_commit or new_commit are 0, master can't be deleted or created if ref_name == 'refs/heads/master' and os.environ.get('REMOTE_USER') is not None: # push not coming from MarkUs # check 1: created/deleted top level files/directories old_ls = subprocess.run(['git', 'ls-tree', '--name-only', old_commit], stdout=subprocess.PIPE, universal_newlines=True) new_ls = subprocess.run(['git', 'ls-tree', '--name-only', new_commit], stdout=subprocess.PIPE, universal_newlines=True) if old_ls.stdout != new_ls.stdout: print('[MARKUS] Error: creating/deleting top level files and directories is not allowed on master!') exit(1) # check 2: modified top level files changes = subprocess.run(['git', 'diff', '--name-only', old_commit, new_commit], stdout=subprocess.PIPE, universal_newlines=True) if any(os.sep not in change for change in changes.stdout.splitlines()): print('[MARKUS] Error: modifying top level files is not allowed on master!') exit(1)
#!/usr/bin/env python3 import os import subprocess import sys if __name__ == '__main__': ref_name = sys.argv[1] old_commit = sys.argv[2] new_commit = sys.argv[3] # no need to check if old_commit or new_commit are 0, master can't be deleted or created if ref_name == 'refs/heads/master' and os.environ.get('REMOTE_USER') is not None: # push not coming from MarkUs # check 1: created/deleted top level files/directories old_ls = subprocess.run(['git', 'ls-tree', '--name-only', old_commit], stdout=subprocess.PIPE, universal_newlines=True) new_ls = subprocess.run(['git', 'ls-tree', '--name-only', new_commit], stdout=subprocess.PIPE, universal_newlines=True) if old_ls.stdout != new_ls.stdout: print('[MARKUS] Error: creating/deleting top level files and directories is not allowed on master!') exit(1) # check 2: modified top level files changes = subprocess.run(['git', 'diff', '--name-only', '--no-renames', old_commit, new_commit], stdout=subprocess.PIPE, universal_newlines=True) if any(os.sep not in change for change in changes.stdout.splitlines()): print('[MARKUS] Error: modifying top level files is not allowed on master!') exit(1)
Fix top level hook to not use renames
git: Fix top level hook to not use renames
Python
mit
benjaminvialle/Markus,MarkUsProject/Markus,MarkUsProject/Markus,benjaminvialle/Markus,benjaminvialle/Markus,benjaminvialle/Markus,benjaminvialle/Markus,MarkUsProject/Markus,MarkUsProject/Markus,benjaminvialle/Markus,MarkUsProject/Markus,MarkUsProject/Markus,benjaminvialle/Markus,MarkUsProject/Markus,MarkUsProject/Markus
--- +++ @@ -20,8 +20,8 @@ print('[MARKUS] Error: creating/deleting top level files and directories is not allowed on master!') exit(1) # check 2: modified top level files - changes = subprocess.run(['git', 'diff', '--name-only', old_commit, new_commit], stdout=subprocess.PIPE, - universal_newlines=True) + changes = subprocess.run(['git', 'diff', '--name-only', '--no-renames', old_commit, new_commit], + stdout=subprocess.PIPE, universal_newlines=True) if any(os.sep not in change for change in changes.stdout.splitlines()): print('[MARKUS] Error: modifying top level files is not allowed on master!') exit(1)
c43d58ac79d6144eb6252ff611cc9605f290006d
patches/1401/p01_move_related_property_setters_to_custom_field.py
patches/1401/p01_move_related_property_setters_to_custom_field.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import webnotes from webnotes.model.meta import get_field def execute(): webnotes.reload_doc("core", "doctype", "custom_field") custom_fields = {} for cf in webnotes.conn.sql("""select dt, fieldname from `tabCustom Field`""", as_dict=1): custom_fields.setdefault(cf.dt, []).append(cf.fieldname) delete_list = [] for ps in webnotes.conn.sql("""select * from `tabProperty Setter`""", as_dict=1): if ps.field_name in custom_fields.get(ps.doc_type, []): if ps.property == "previous_field": property_name = "insert_after" field_meta = get_field(ps.doc_type, ps.value) property_value = field_meta.label if field_meta else "" else: property_name = ps.property property_value =ps.value webnotes.conn.sql("""update `tabCustom Field` set %s=%s where dt=%s and fieldname=%s""" % (property_name, '%s', '%s', '%s'), (property_value, ps.doc_type, ps.field_name)) delete_list.append(ps.name) if delete_list: webnotes.conn.sql("""delete from `tabProperty Setter` where name in (%s)""" % ', '.join(['%s']*len(delete_list)), tuple(delete_list))
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import webnotes def execute(): webnotes.reload_doc("core", "doctype", "custom_field") cf_doclist = webnotes.get_doctype("Custom Field") delete_list = [] for d in webnotes.conn.sql("""select cf.name as cf_name, ps.property, ps.value, ps.name as ps_name from `tabProperty Setter` ps, `tabCustom Field` cf where ps.doctype_or_field = 'DocField' and ps.property != 'previous_field' and ps.doc_type=cf.dt and ps.field_name=cf.fieldname""", as_dict=1): if cf_doclist.get_field(d.property): webnotes.conn.sql("""update `tabCustom Field` set `%s`=%s where name=%s""" % (d.property, '%s', '%s'), (d.value, d.cf_name)) delete_list.append(d.ps_name) if delete_list: webnotes.conn.sql("""delete from `tabProperty Setter` where name in (%s)""" % ', '.join(['%s']*len(delete_list)), tuple(delete_list))
Delete Property Setters for Custom Fields, and set them inside Custom Field
Delete Property Setters for Custom Fields, and set them inside Custom Field
Python
agpl-3.0
hatwar/buyback-erpnext,indictranstech/osmosis-erpnext,suyashphadtare/vestasi-erp-jan-end,Drooids/erpnext,gangadharkadam/saloon_erp_install,indictranstech/buyback-erp,suyashphadtare/gd-erp,geekroot/erpnext,gangadhar-kadam/verve_erp,anandpdoshi/erpnext,suyashphadtare/vestasi-update-erp,anandpdoshi/erpnext,sagar30051991/ozsmart-erp,shft117/SteckerApp,indictranstech/tele-erpnext,hatwar/focal-erpnext,gangadhar-kadam/verve_live_erp,Tejal011089/paypal_erpnext,indictranstech/fbd_erpnext,hatwar/focal-erpnext,suyashphadtare/sajil-final-erp,Tejal011089/digitales_erpnext,saurabh6790/omnitech-apps,tmimori/erpnext,fuhongliang/erpnext,njmube/erpnext,Suninus/erpnext,gangadhar-kadam/smrterp,suyashphadtare/vestasi-erp-jan-end,gangadharkadam/sher,gangadharkadam/letzerp,gmarke/erpnext,aruizramon/alec_erpnext,rohitwaghchaure/New_Theme_Erp,SPKian/Testing,mbauskar/alec_frappe5_erpnext,gangadharkadam/office_erp,anandpdoshi/erpnext,dieface/erpnext,shft117/SteckerApp,indictranstech/Das_Erpnext,hanselke/erpnext-1,saurabh6790/test-erp,saurabh6790/trufil_app,pombredanne/erpnext,Suninus/erpnext,gangadhar-kadam/hrerp,Tejal011089/trufil-erpnext,pawaranand/phrerp,Tejal011089/paypal_erpnext,hatwar/Das_erpnext,hanselke/erpnext-1,susuchina/ERPNEXT,rohitwaghchaure/erpnext_smart,indictranstech/fbd_erpnext,mbauskar/omnitech-erpnext,mbauskar/omnitech-erpnext,tmimori/erpnext,shitolepriya/test-erp,saurabh6790/omni-apps,Tejal011089/fbd_erpnext,saurabh6790/test-erp,hatwar/Das_erpnext,hanselke/erpnext-1,mbauskar/helpdesk-erpnext,gangadharkadam/v6_erp,indictranstech/vestasi-erpnext,netfirms/erpnext,indictranstech/reciphergroup-erpnext,gangadhar-kadam/powapp,rohitwaghchaure/erpnext_smart,SPKian/Testing2,rohitwaghchaure/New_Theme_Erp,saurabh6790/aimobilize-app-backup,indictranstech/trufil-erpnext,gangadharkadam/vlinkerp,rohitwaghchaure/digitales_erpnext,SPKian/Testing2,netfirms/erpnext,netfirms/erpnext,indictranstech/erpnext,saurabh6790/omn-app,indictranstech/tele-erpnext,gangadharkadam/sher,gangadharkadam/contributionerp,gangadharkadam/verveerp,suyashphadtare/test,mahabuber/erpnext,mbauskar/helpdesk-erpnext,meisterkleister/erpnext,MartinEnder/erpnext-de,pombredanne/erpnext,gangadharkadam/saloon_erp,Tejal011089/huntercamp_erpnext,gangadhar-kadam/laganerp,gangadharkadam/johnerp,BhupeshGupta/erpnext,gangadharkadam/vlinkerp,Tejal011089/med2-app,mbauskar/internal-hr,mbauskar/sapphire-erpnext,gangadhar-kadam/verve_test_erp,indictranstech/phrerp,gangadhar-kadam/verve-erp,fuhongliang/erpnext,indictranstech/erpnext,suyashphadtare/sajil-erp,4commerce-technologies-AG/erpnext,gangadharkadam/saloon_erp_install,shitolepriya/test-erp,indictranstech/internal-erpnext,gsnbng/erpnext,indictranstech/vestasi-erpnext,mbauskar/Das_Erpnext,shitolepriya/test-erp,susuchina/ERPNEXT,sagar30051991/ozsmart-erp,Tejal011089/huntercamp_erpnext,hatwar/Das_erpnext,njmube/erpnext,SPKian/Testing,Tejal011089/osmosis_erpnext,MartinEnder/erpnext-de,indictranstech/buyback-erp,ThiagoGarciaAlves/erpnext,gangadharkadam/contributionerp,Tejal011089/osmosis_erpnext,mbauskar/Das_Erpnext,treejames/erpnext,indictranstech/biggift-erpnext,suyashphadtare/sajil-final-erp,gangadharkadam/v4_erp,gangadharkadam/sterp,saurabh6790/test-erp,BhupeshGupta/erpnext,dieface/erpnext,indictranstech/biggift-erpnext,Tejal011089/fbd_erpnext,mbauskar/phrerp,mbauskar/omnitech-erpnext,gangadharkadam/tailorerp,gangadhar-kadam/latestchurcherp,gangadharkadam/letzerp,MartinEnder/erpnext-de,rohitwaghchaure/New_Theme_Erp,gangadhar-kadam/powapp,indictranstech/internal-erpnext,gsnbng/erpnext,mbauskar/internal-hr,indictranstech/phrerp,indictranstech/buyback-erp,Tejal011089/osmosis_erpnext,Tejal011089/trufil-erpnext,saurabh6790/omnitech-apps,ThiagoGarciaAlves/erpnext,mbauskar/Das_Erpnext,gangadhar-kadam/prjapp,gangadharkadam/verveerp,indictranstech/fbd_erpnext,Tejal011089/Medsyn2_app,SPKian/Testing,indictranstech/trufil-erpnext,njmube/erpnext,Tejal011089/fbd_erpnext,rohitwaghchaure/erpnext_smart,mbauskar/phrerp,indictranstech/reciphergroup-erpnext,saurabh6790/omnisys-app,saurabh6790/aimobilize-app-backup,gangadhar-kadam/helpdesk-erpnext,hernad/erpnext,geekroot/erpnext,gangadhar-kadam/verve_test_erp,Drooids/erpnext,gmarke/erpnext,Tejal011089/huntercamp_erpnext,fuhongliang/erpnext,suyashphadtare/vestasi-update-erp,Tejal011089/paypal_erpnext,hanselke/erpnext-1,saurabh6790/omnisys-app,suyashphadtare/sajil-erp,gangadharkadam/v5_erp,saurabh6790/omni-apps,gangadharkadam/saloon_erp,Tejal011089/digitales_erpnext,hatwar/buyback-erpnext,gangadharkadam/vlinkerp,gangadhar-kadam/verve_erp,gangadhar-kadam/helpdesk-erpnext,gangadharkadam/office_erp,Tejal011089/Medsyn2_app,dieface/erpnext,indictranstech/reciphergroup-erpnext,gangadharkadam/smrterp,suyashphadtare/test,anandpdoshi/erpnext,gangadharkadam/letzerp,Aptitudetech/ERPNext,Tejal011089/digitales_erpnext,Suninus/erpnext,mbauskar/omnitech-demo-erpnext,gangadharkadam/verveerp,gangadharkadam/v5_erp,indictranstech/Das_Erpnext,gangadhar-kadam/smrterp,gangadhar-kadam/latestchurcherp,hatwar/Das_erpnext,sheafferusa/erpnext,gangadharkadam/contributionerp,gangadharkadam/office_erp,SPKian/Testing,gangadhar-kadam/nassimapp,suyashphadtare/vestasi-erp-1,mbauskar/alec_frappe5_erpnext,pawaranand/phrerp,Tejal011089/trufil-erpnext,meisterkleister/erpnext,gangadharkadam/saloon_erp_install,BhupeshGupta/erpnext,gangadhar-kadam/verve_erp,Tejal011089/paypal_erpnext,Tejal011089/med2-app,geekroot/erpnext,indictranstech/phrerp,Drooids/erpnext,saurabh6790/trufil_app,ThiagoGarciaAlves/erpnext,saurabh6790/tru_app_back,indictranstech/focal-erpnext,gangadharkadam/saloon_erp,tmimori/erpnext,rohitwaghchaure/erpnext-receipher,gangadharkadam/sterp,dieface/erpnext,suyashphadtare/vestasi-erp-final,ShashaQin/erpnext,sagar30051991/ozsmart-erp,gangadharkadam/letzerp,indictranstech/internal-erpnext,gangadhar-kadam/helpdesk-erpnext,mbauskar/phrerp,gangadhar-kadam/verve-erp,njmube/erpnext,gangadhar-kadam/verve_live_erp,sheafferusa/erpnext,suyashphadtare/gd-erp,gangadharkadam/vlinkerp,gsnbng/erpnext,sheafferusa/erpnext,indictranstech/erpnext,mbauskar/alec_frappe5_erpnext,pombredanne/erpnext,saurabh6790/pow-app,tmimori/erpnext,SPKian/Testing2,aruizramon/alec_erpnext,indictranstech/phrerp,meisterkleister/erpnext,gangadharkadam/tailorerp,hatwar/focal-erpnext,suyashphadtare/sajil-final-erp,mbauskar/helpdesk-erpnext,indictranstech/vestasi-erpnext,gangadhar-kadam/verve_test_erp,gangadharkadam/johnerp,saurabh6790/pow-app,ShashaQin/erpnext,sheafferusa/erpnext,rohitwaghchaure/erpnext-receipher,indictranstech/biggift-erpnext,suyashphadtare/vestasi-erp-final,mahabuber/erpnext,rohitwaghchaure/digitales_erpnext,indictranstech/osmosis-erpnext,mbauskar/omnitech-demo-erpnext,hernad/erpnext,gangadhar-kadam/laganerp,gangadhar-kadam/latestchurcherp,indictranstech/internal-erpnext,suyashphadtare/vestasi-erp-jan-end,BhupeshGupta/erpnext,mbauskar/Das_Erpnext,suyashphadtare/vestasi-erp-1,rohitwaghchaure/digitales_erpnext,mbauskar/alec_frappe5_erpnext,saurabh6790/test-erp,saurabh6790/omnit-app,SPKian/Testing2,gangadhar-kadam/laganerp,suyashphadtare/vestasi-erp-final,fuhongliang/erpnext,mahabuber/erpnext,hatwar/buyback-erpnext,sagar30051991/ozsmart-erp,gangadhar-kadam/verve_live_erp,ThiagoGarciaAlves/erpnext,gangadharkadam/verveerp,suyashphadtare/test,indictranstech/osmosis-erpnext,rohitwaghchaure/GenieManager-erpnext,Tejal011089/huntercamp_erpnext,4commerce-technologies-AG/erpnext,gangadharkadam/v5_erp,Tejal011089/trufil-erpnext,indictranstech/fbd_erpnext,Drooids/erpnext,hatwar/buyback-erpnext,treejames/erpnext,indictranstech/erpnext,suyashphadtare/vestasi-erp-1,indictranstech/tele-erpnext,mbauskar/helpdesk-erpnext,suyashphadtare/gd-erp,saurabh6790/omn-app,gangadharkadam/v4_erp,treejames/erpnext,gangadharkadam/smrterp,susuchina/ERPNEXT,gangadhar-kadam/hrerp,indictranstech/Das_Erpnext,indictranstech/reciphergroup-erpnext,indictranstech/biggift-erpnext,aruizramon/alec_erpnext,shft117/SteckerApp,gangadhar-kadam/nassimapp,gangadhar-kadam/powapp,gangadhar-kadam/prjapp,mbauskar/sapphire-erpnext,mbauskar/omnitech-erpnext,Tejal011089/osmosis_erpnext,indictranstech/focal-erpnext,hernad/erpnext,gsnbng/erpnext,shft117/SteckerApp,indictranstech/vestasi-erpnext,mbauskar/phrerp,gangadhar-kadam/verve_test_erp,Tejal011089/digitales_erpnext,indictranstech/trufil-erpnext,gangadharkadam/v6_erp,gangadharkadam/saloon_erp,mbauskar/omnitech-demo-erpnext,pombredanne/erpnext,mbauskar/internal-hr,mbauskar/sapphire-erpnext,mbauskar/omnitech-demo-erpnext,rohitwaghchaure/GenieManager-erpnext,gangadhar-kadam/verve-erp,gangadharkadam/v4_erp,pawaranand/phrerp,gangadharkadam/saloon_erp_install,gangadharkadam/v6_erp,indictranstech/trufil-erpnext,MartinEnder/erpnext-de,gangadharkadam/v6_erp,gangadhar-kadam/latestchurcherp,indictranstech/buyback-erp,rohitwaghchaure/erpnext-receipher,rohitwaghchaure/erpnext-receipher,rohitwaghchaure/GenieManager-erpnext,hatwar/focal-erpnext,pawaranand/phrerp,suyashphadtare/sajil-erp,saurabh6790/omnit-app,gangadharkadam/v4_erp,Tejal011089/fbd_erpnext,gmarke/erpnext,geekroot/erpnext,saurabh6790/tru_app_back,suyashphadtare/gd-erp,rohitwaghchaure/digitales_erpnext,gangadhar-kadam/verve_live_erp,treejames/erpnext,gangadhar-kadam/helpdesk-erpnext,indictranstech/focal-erpnext,4commerce-technologies-AG/erpnext,rohitwaghchaure/GenieManager-erpnext,gangadhar-kadam/verve_erp,aruizramon/alec_erpnext,mbauskar/sapphire-erpnext,meisterkleister/erpnext,netfirms/erpnext,gangadharkadam/contributionerp,indictranstech/focal-erpnext,indictranstech/tele-erpnext,hernad/erpnext,shitolepriya/test-erp,susuchina/ERPNEXT,suyashphadtare/vestasi-update-erp,mahabuber/erpnext,gmarke/erpnext,gangadharkadam/v5_erp,rohitwaghchaure/New_Theme_Erp,indictranstech/Das_Erpnext,Suninus/erpnext,ShashaQin/erpnext,suyashphadtare/vestasi-erp-jan-end,ShashaQin/erpnext,indictranstech/osmosis-erpnext
--- +++ @@ -2,34 +2,24 @@ # License: GNU General Public License v3. See license.txt import webnotes -from webnotes.model.meta import get_field def execute(): webnotes.reload_doc("core", "doctype", "custom_field") - custom_fields = {} - for cf in webnotes.conn.sql("""select dt, fieldname from `tabCustom Field`""", as_dict=1): - custom_fields.setdefault(cf.dt, []).append(cf.fieldname) - + cf_doclist = webnotes.get_doctype("Custom Field") + delete_list = [] - for ps in webnotes.conn.sql("""select * from `tabProperty Setter`""", as_dict=1): - if ps.field_name in custom_fields.get(ps.doc_type, []): - - if ps.property == "previous_field": - property_name = "insert_after" + for d in webnotes.conn.sql("""select cf.name as cf_name, ps.property, + ps.value, ps.name as ps_name + from `tabProperty Setter` ps, `tabCustom Field` cf + where ps.doctype_or_field = 'DocField' and ps.property != 'previous_field' + and ps.doc_type=cf.dt and ps.field_name=cf.fieldname""", as_dict=1): + if cf_doclist.get_field(d.property): + webnotes.conn.sql("""update `tabCustom Field` + set `%s`=%s where name=%s""" % (d.property, '%s', '%s'), (d.value, d.cf_name)) - field_meta = get_field(ps.doc_type, ps.value) - property_value = field_meta.label if field_meta else "" - else: - property_name = ps.property - property_value =ps.value + delete_list.append(d.ps_name) - webnotes.conn.sql("""update `tabCustom Field` - set %s=%s where dt=%s and fieldname=%s""" % (property_name, '%s', '%s', '%s'), - (property_value, ps.doc_type, ps.field_name)) - - delete_list.append(ps.name) - if delete_list: webnotes.conn.sql("""delete from `tabProperty Setter` where name in (%s)""" % ', '.join(['%s']*len(delete_list)), tuple(delete_list))
6af3c515a98ac1be7f6acf5ddb6a2d114ac1336c
shifter.py
shifter.py
from image import ImageWithWCS import numpy as np from os import path def shift_images(files, source_dir, output_file='_shifted'): """Align images based on astrometry.""" ref = files[0] # TODO: make reference image an input ref_im = ImageWithWCS(path.join(source_dir, ref)) ref_pix = np.int32(np.array(ref_im.data.shape) / 2) ref_ra_dec = ref_im.wcs_pix2sky(ref_pix) base, ext = path.splitext(files[0]) ref_im.save(path.join(source_dir, base + output_file + ext)) for fil in files[1:]: img = ImageWithWCS(path.join(source_dir, fil)) ra_dec_pix = img.wcs_sky2pix(ref_ra_dec) shift = ref_pix - np.int32(ra_dec_pix) print shift img.shift(shift, in_place=True) base, ext = path.splitext(fil) img.save(path.join(source_dir, base + output_file + ext))
from image import ImageWithWCS import numpy as np from os import path def shift_images(files, source_dir, output_file='_shifted'): """Align images based on astrometry.""" ref = files[0] # TODO: make reference image an input ref_im = ImageWithWCS(path.join(source_dir, ref)) ref_pix = np.int32(np.array(ref_im.data.shape) / 2) ref_ra_dec = ref_im.wcs_pix2sky(ref_pix) base, ext = path.splitext(files[0]) ref_im.save(path.join(source_dir, base + output_file + ext)) for fil in files[1:]: img = ImageWithWCS(path.join(source_dir, fil)) ra_dec_pix = img.wcs_sky2pix(ref_ra_dec) shift = ref_pix - np.int32(ra_dec_pix) # FITS order of axes opposite of numpy, so swap: shift = shift[::-1] img.shift(shift, in_place=True) base, ext = path.splitext(fil) img.save(path.join(source_dir, base + output_file + ext))
Fix order of components of shift
Fix order of components of shift FITS and bumpy have opposite conventions as to which axis is the first axis
Python
bsd-3-clause
mwcraig/msumastro
--- +++ @@ -16,7 +16,8 @@ img = ImageWithWCS(path.join(source_dir, fil)) ra_dec_pix = img.wcs_sky2pix(ref_ra_dec) shift = ref_pix - np.int32(ra_dec_pix) - print shift + # FITS order of axes opposite of numpy, so swap: + shift = shift[::-1] img.shift(shift, in_place=True) base, ext = path.splitext(fil) img.save(path.join(source_dir, base + output_file + ext))
8063e3b863ff4944f95ac27ff4329716fa03efc8
paystackapi/tests/test_cpanel.py
paystackapi/tests/test_cpanel.py
import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.cpanel import ControlPanel class TestPage(BaseTestCase): @httpretty.activate def test_fetch_payment_session_timeout(self): """Method defined to test fetch payment session timeout.""" httpretty.register_uri( httpretty.get, self.endpoint_url("/integration/payment_session_timeout"), content_type='text/json', body='{"status": true, "message": "Payment session timeout retrieved"}', status=201, ) response = ControlPanel.fetch_payment_session_timeout() self.assertTrue(response['status'])
import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.cpanel import ControlPanel class TestPage(BaseTestCase): @httpretty.activate def test_fetch_payment_session_timeout(self): """Method defined to test fetch payment session timeout.""" httpretty.register_uri( httpretty.GET, self.endpoint_url("/integration/payment_session_timeout"), content_type='text/json', body='{"status": true, "message": "Payment session timeout retrieved"}', status=201, ) response = ControlPanel.fetch_payment_session_timeout() self.assertTrue(response['status'])
Update control panel test for fetch
Update control panel test for fetch
Python
mit
andela-sjames/paystack-python
--- +++ @@ -10,7 +10,7 @@ def test_fetch_payment_session_timeout(self): """Method defined to test fetch payment session timeout.""" httpretty.register_uri( - httpretty.get, + httpretty.GET, self.endpoint_url("/integration/payment_session_timeout"), content_type='text/json', body='{"status": true, "message": "Payment session timeout retrieved"}',
cc7319fa8ac99049b3fcc86c7f2f075ebd2e7124
pylatex/base_classes/section.py
pylatex/base_classes/section.py
# -*- coding: utf-8 -*- """ This module implements the class that deals with sections. .. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ from . import Container, Command class SectionBase(Container): """A class that is the base for all section type classes.""" def __init__(self, title, numbering=True, *args, **kwargs): """. Args ---- title: str The section title. numbering: bool Add a number before the section title. """ self.title = title self.numbering = numbering super().__init__(*args, **kwargs) def dumps(self): """Represent the section as a string in LaTeX syntax. Returns ------- str """ if not self.numbering: num = '*' else: num = '' string = Command(self.latex_name + num, self.title).dumps() string += self.dumps_content() return string
# -*- coding: utf-8 -*- """ This module implements the class that deals with sections. .. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ from . import Container, Command class SectionBase(Container): """A class that is the base for all section type classes.""" #: A section should normally start in its own paragraph end_paragraph = True def __init__(self, title, numbering=True, *args, **kwargs): """. Args ---- title: str The section title. numbering: bool Add a number before the section title. """ self.title = title self.numbering = numbering super().__init__(*args, **kwargs) def dumps(self): """Represent the section as a string in LaTeX syntax. Returns ------- str """ if not self.numbering: num = '*' else: num = '' string = Command(self.latex_name + num, self.title).dumps() string += self.dumps_content() return string
Set end_paragraph to True by default
Section: Set end_paragraph to True by default
Python
mit
bjodah/PyLaTeX,JelteF/PyLaTeX,bjodah/PyLaTeX,ovaskevich/PyLaTeX,ovaskevich/PyLaTeX,JelteF/PyLaTeX
--- +++ @@ -12,6 +12,9 @@ class SectionBase(Container): """A class that is the base for all section type classes.""" + + #: A section should normally start in its own paragraph + end_paragraph = True def __init__(self, title, numbering=True, *args, **kwargs): """.
29aa1a440a9ff225d3f9a4773f9097a5efcbd0de
test/integration/test_output.py
test/integration/test_output.py
from ..helpers import * def test_honcho_start_joins_stderr_into_stdout(): ret, out, err = get_honcho_output(['-f', 'Procfile.output', 'start']) assert_equal(ret, 0) assert_in('some normal output', out) assert_in('and then write to stderr', out) assert_equal(err, '') def test_honcho_run_keeps_stderr_and_stdout_separate(): ret, out, err = get_honcho_output(['run', 'python', 'output.py']) assert_equal(ret, 0) assert_equal(out, 'some normal output\n') assert_equal(err, 'and then write to stderr\n')
from ..helpers import * def test_honcho_start_joins_stderr_into_stdout(): ret, out, err = get_honcho_output(['-f', 'Procfile.output', 'start']) assert_equal(ret, 0) assert_regexp_matches(out, r'some normal output') assert_regexp_matches(out, r'and then write to stderr') assert_equal(err, '') def test_honcho_run_keeps_stderr_and_stdout_separate(): ret, out, err = get_honcho_output(['run', 'python', 'output.py']) assert_equal(ret, 0) assert_equal(out, 'some normal output\n') assert_equal(err, 'and then write to stderr\n')
Rewrite assertions for Python 2.6 compatibility
Rewrite assertions for Python 2.6 compatibility
Python
mit
janusnic/honcho,xarisd/honcho,myyk/honcho,gratipay/honcho,nickstenning/honcho,nickstenning/honcho,gratipay/honcho
--- +++ @@ -6,8 +6,8 @@ assert_equal(ret, 0) - assert_in('some normal output', out) - assert_in('and then write to stderr', out) + assert_regexp_matches(out, r'some normal output') + assert_regexp_matches(out, r'and then write to stderr') assert_equal(err, '')
bdb7da410d6085a783fdb3cca55b9353fad9b9ed
knowledge_repo/app/auth_providers/debug.py
knowledge_repo/app/auth_providers/debug.py
import flask from flask import request, render_template, flash, redirect, url_for from flask_login import login_user from ..models import User from ..utils.auth import is_safe_url from ..auth_provider import KnowledgeAuthProvider class DebugAuthProvider(KnowledgeAuthProvider): _registry_keys = ['debug'] def prompt(self): if request.method == 'POST': user = request.form['username'] login_user(User(identifier=user)) flash('Logged in successfully.') next = request.args.get('next') # is_safe_url should check if the url is safe for redirects. # See http://flask.pocoo.org/snippets/62/ for an example. if not is_safe_url(next): return flask.abort(400) return redirect(next or url_for('index.render_feed')) return render_template('auth-login-form.html', skip_password=True) def get_user(self): return User(identifier=request.form['username'])
from ..auth_provider import KnowledgeAuthProvider from ..models import User from ..utils.auth import is_safe_url import flask from flask import ( flash, redirect, render_template, request, url_for, ) from flask_login import login_user class DebugAuthProvider(KnowledgeAuthProvider): _registry_keys = ['debug'] def prompt(self): if request.method == 'POST': user = request.form['username'] login_user(User(identifier=user)) flash('Logged in successfully.') next = request.args.get('next') # is_safe_url should check if the url is safe for redirects. # See http://flask.pocoo.org/snippets/62/ for an example. if not is_safe_url(next): return flask.abort(400) return redirect(next or url_for('index.render_feed')) return render_template('auth-login-form.html', skip_password=True) def get_user(self): return User(identifier=request.form['username'])
Adjust import statements to be sorted
Adjust import statements to be sorted
Python
apache-2.0
airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo
--- +++ @@ -1,11 +1,15 @@ -import flask -from flask import request, render_template, flash, redirect, url_for -from flask_login import login_user - +from ..auth_provider import KnowledgeAuthProvider from ..models import User from ..utils.auth import is_safe_url - -from ..auth_provider import KnowledgeAuthProvider +import flask +from flask import ( + flash, + redirect, + render_template, + request, + url_for, +) +from flask_login import login_user class DebugAuthProvider(KnowledgeAuthProvider):
26b2ed8c6f47eb87a2851c746e10f2bbe331dc4c
python/qibuild/actions/config.py
python/qibuild/actions/config.py
## Copyright (C) 2011 Aldebaran Robotics """Display the current config """ import os import qitools def configure_parser(parser): """Configure parser for this action """ qitools.qiworktree.work_tree_parser(parser) parser.add_argument("--edit", action="store_true", help="edit the configuration") def do(args): """Main entry point""" qiwt = qitools.qiworktree_open(args.work_tree, use_env=True) if not args.edit: print qiwt.configstore return config_path = qiwt.user_config_path editor = qiwt.configstore.get("general", "env", "editor") if not editor: editor = os.environ.get("VISUAL") if not editor: editor = os.environ.get("EDITOR") if not editor: # Ask the user to choose, and store the answer so # that we never ask again print "Could not find the editor to use." editor = qitools.interact.ask_string("Please enter an editor") qitools.configstore.update_config(config_path, "general", "env", "editor", editor) qitools.command.check_call([editor, config_path]) if __name__ == "__main__" : import sys qitools.cmdparse.sub_command_main(sys.modules[__name__])
## Copyright (C) 2011 Aldebaran Robotics """Display the current config """ import os import qitools def configure_parser(parser): """Configure parser for this action """ qitools.qiworktree.work_tree_parser(parser) parser.add_argument("--edit", action="store_true", help="edit the configuration") def do(args): """Main entry point""" qiwt = qitools.qiworktree_open(args.work_tree, use_env=True) if not args.edit: print qiwt.configstore return config_path = qiwt.user_config_path editor = qiwt.configstore.get("general", "env", "editor") if not editor: editor = os.environ.get("VISUAL") if not editor: editor = os.environ.get("EDITOR") if not editor: # Ask the user to choose, and store the answer so # that we never ask again print "Could not find the editor to use." editor = qitools.interact.ask_string("Please enter an editor") qitools.command.check_is_in_path(editor) qitools.configstore.update_config(config_path, "general", "env", "editor", editor) qitools.command.check_call([editor, config_path]) if __name__ == "__main__" : import sys qitools.cmdparse.sub_command_main(sys.modules[__name__])
Check that editor exists when adding
Check that editor exists when adding
Python
bsd-3-clause
dmerejkowsky/qibuild,dmerejkowsky/qibuild,aldebaran/qibuild,dmerejkowsky/qibuild,aldebaran/qibuild,aldebaran/qibuild,dmerejkowsky/qibuild,aldebaran/qibuild,dmerejkowsky/qibuild
--- +++ @@ -29,20 +29,13 @@ # that we never ask again print "Could not find the editor to use." editor = qitools.interact.ask_string("Please enter an editor") + qitools.command.check_is_in_path(editor) qitools.configstore.update_config(config_path, "general", "env", "editor", editor) qitools.command.check_call([editor, config_path]) - - - - - - - - if __name__ == "__main__" : import sys qitools.cmdparse.sub_command_main(sys.modules[__name__])
2794f71e1a4c9ac8aa70f22ce3c9d01bf2d7737a
humanize/__init__.py
humanize/__init__.py
__version__ = VERSION = (0, 5, 1) from humanize.time import * from humanize.number import * from humanize.filesize import * from humanize.i18n import activate, deactivate __all__ = ['__version__', 'VERSION', 'naturalday', 'naturaltime', 'ordinal', 'intword', 'naturaldelta', 'intcomma', 'apnumber', 'fractional', 'naturalsize', 'activate', 'deactivate', 'naturaldate']
__version__ = VERSION = (0, 5, 1) from humanize.time import * from humanize.number import * from humanize.filesize import * from humanize.i18n import activate, deactivate __all__ = [ "__version__", "activate", "apnumber", "deactivate", "fractional", "intcomma", "intword", "naturaldate", "naturalday", "naturaldelta", "naturalsize", "naturaltime", "ordinal", "VERSION", ]
Format with Black and sort
Format with Black and sort
Python
mit
jmoiron/humanize,jmoiron/humanize
--- +++ @@ -5,6 +5,19 @@ from humanize.filesize import * from humanize.i18n import activate, deactivate -__all__ = ['__version__', 'VERSION', 'naturalday', 'naturaltime', 'ordinal', 'intword', - 'naturaldelta', 'intcomma', 'apnumber', 'fractional', 'naturalsize', - 'activate', 'deactivate', 'naturaldate'] +__all__ = [ + "__version__", + "activate", + "apnumber", + "deactivate", + "fractional", + "intcomma", + "intword", + "naturaldate", + "naturalday", + "naturaldelta", + "naturalsize", + "naturaltime", + "ordinal", + "VERSION", +]
88592970d58eeff43837a5e175bba95386a8491b
neutron/db/migration/alembic_migrations/versions/newton/expand/3d0e74aa7d37_add_flavor_id_to_routers.py
neutron/db/migration/alembic_migrations/versions/newton/expand/3d0e74aa7d37_add_flavor_id_to_routers.py
# Copyright 2016 Mirantis # # 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. # """Add flavor_id to Router Revision ID: 3d0e74aa7d37 Revises: a963b38d82f4 Create Date: 2016-05-05 00:22:47.618593 """ from alembic import op import sqlalchemy as sa from neutron.db import migration # revision identifiers, used by Alembic. revision = '3d0e74aa7d37' down_revision = 'a963b38d82f4' # milestone identifier, used by neutron-db-manage neutron_milestone = [migration.NEWTON] def upgrade(): op.add_column('routers', sa.Column('flavor_id', sa.String(length=36), sa.ForeignKey('flavors.id'), nullable=True))
# Copyright 2016 Mirantis # # 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. # """Add flavor_id to Router Revision ID: 3d0e74aa7d37 Revises: a963b38d82f4 Create Date: 2016-05-05 00:22:47.618593 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '3d0e74aa7d37' down_revision = 'a963b38d82f4' def upgrade(): op.add_column('routers', sa.Column('flavor_id', sa.String(length=36), sa.ForeignKey('flavors.id'), nullable=True))
Remove erroneous newton milestone tag
Remove erroneous newton milestone tag Change https://review.openstack.org/268941 inadvertently tagged alembic migration 3d0e74aa7d37 with the newton milestone. Remove it. Change-Id: I46f98a824d2a190c29fb26b62025772de2e4e33e Partial-Bug: #1623108
Python
apache-2.0
openstack/neutron,huntxu/neutron,cloudbase/neutron,sebrandon1/neutron,mahak/neutron,noironetworks/neutron,openstack/neutron,cloudbase/neutron,openstack/neutron,mahak/neutron,huntxu/neutron,noironetworks/neutron,mahak/neutron,eayunstack/neutron,eayunstack/neutron,sebrandon1/neutron
--- +++ @@ -24,15 +24,10 @@ from alembic import op import sqlalchemy as sa -from neutron.db import migration - # revision identifiers, used by Alembic. revision = '3d0e74aa7d37' down_revision = 'a963b38d82f4' - -# milestone identifier, used by neutron-db-manage -neutron_milestone = [migration.NEWTON] def upgrade():
e1068913bf56d9a8b3bc763eb15673c81d23c85b
openstack/common/report/utils.py
openstack/common/report/utils.py
# Copyright 2013 Red Hat, 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. """Various utilities for report generation This module includes various utilities used in generating reports. """ import gc class StringWithAttrs(str): """A String that can have arbitrary attributes """ pass def _find_objects(t): """Find Objects in the GC State This horribly hackish method locates objects of a given class in the current python instance's garbage collection state. In case you couldn't tell, this is horribly hackish, but is necessary for locating all green threads, since they don't keep track of themselves like normal threads do in python. :param class t: the class of object to locate :rtype: list :returns: a list of objects of the given type """ return filter(lambda o: isinstance(o, t), gc.get_objects())
# Copyright 2013 Red Hat, 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. """Various utilities for report generation This module includes various utilities used in generating reports. """ import gc class StringWithAttrs(str): """A String that can have arbitrary attributes """ pass def _find_objects(t): """Find Objects in the GC State This horribly hackish method locates objects of a given class in the current python instance's garbage collection state. In case you couldn't tell, this is horribly hackish, but is necessary for locating all green threads, since they don't keep track of themselves like normal threads do in python. :param class t: the class of object to locate :rtype: list :returns: a list of objects of the given type """ return [o for o in gc.get_objects() if isinstance(o, t)]
Fix filter() usage due to python 3 compability
Fix filter() usage due to python 3 compability Built-in method filter() returns a list in Python 2.x [1], but it returns an iterator in Python 3.x [2]. To remove the difference (and make code more readable, also), we use list comprehension instead of filer(). [1] http://docs.python.org/2/library/functions.html#filter [2] http://docs.python.org/3/library/functions.html#filter Related to blueprint make-python3-compatible Change-Id: Ifd42403309ba3a44693e0c7c856a64b861eca3e9
Python
apache-2.0
openstack/oslo.reports,citrix-openstack-build/oslo.reports,DirectXMan12/oslo.reports
--- +++ @@ -43,4 +43,4 @@ :returns: a list of objects of the given type """ - return filter(lambda o: isinstance(o, t), gc.get_objects()) + return [o for o in gc.get_objects() if isinstance(o, t)]
f1c414d91d9b1d9ed90a6b5c676cdc2fb60c4fe4
mongotools/semaphore/semaphore.py
mongotools/semaphore/semaphore.py
class Semaphore(object): """docstring for Semaphore""" def __init__(self, db, id, counter, value, collection_name='mongotools.semaphore'): self._db = db self._name = collection_name self._id = id self._counter = counter self._max = value doc = self._db[self._name].find_and_modify(dict(_id=id), {'$setOnInsert':{counter:value}}, upsert=True, new=True) if counter not in doc: self._db[self._name].update({'_id':id, counter:{'$exists':False}}, {'$set': {counter:value}}, w=1) def acquire(self): doc = self._db[self._name].update({'_id':self._id, self._counter:{'$gt':0}}, {'$inc': {self._counter:-1} }, w=1) return doc['updatedExisting'] def release(self): self._db[self._name].update({'_id':self._id, self._counter:{'$lt':self._max}}, {'$inc': {self._counter:1}})
class Semaphore(object): """docstring for Semaphore""" def __init__(self, db, id, counter, value, collection_name='mongotools.semaphore'): self._db = db self._name = collection_name self._id = id self._counter = counter self._max = value doc = self._db[self._name].find_and_modify(dict(_id=id), {'$setOnInsert':{counter:value}}, upsert=True, new=True) if counter not in doc: self._db[self._name].update({'_id':id, counter:{'$exists':False}}, {'$set': {counter:value}}, w=1) def acquire(self): doc = self._db[self._name].update({'_id':self._id, self._counter:{'$gt':0}}, {'$inc': {self._counter:-1} }, w=1) return doc['updatedExisting'] def release(self): self._db[self._name].update({'_id':self._id, self._counter:{'$lt':self._max}}, {'$inc': {self._counter:1}}) def peek(self): doc = self._db[self._name].find_one({'_id':self._id}) return doc[self._counter] def status(self): """ Returns True if the the semaphore is available to be acquired (greater than 0), but does not actually acquire the semaphore. """ doc = self._db[self._name].find_one({'_id':self._id}) return doc[self._counter] > 0
Add peek to get counter
Add peek to get counter
Python
mit
rick446/MongoTools
--- +++ @@ -1,4 +1,4 @@ - + class Semaphore(object): """docstring for Semaphore""" @@ -19,3 +19,14 @@ def release(self): self._db[self._name].update({'_id':self._id, self._counter:{'$lt':self._max}}, {'$inc': {self._counter:1}}) + def peek(self): + doc = self._db[self._name].find_one({'_id':self._id}) + return doc[self._counter] + + def status(self): + """ + Returns True if the the semaphore is available to be acquired (greater than 0), + but does not actually acquire the semaphore. + """ + doc = self._db[self._name].find_one({'_id':self._id}) + return doc[self._counter] > 0
d827256b7d074f8b5086afd78383408d0d6a2ba4
meinberlin/apps/offlineevents/dashboard.py
meinberlin/apps/offlineevents/dashboard.py
from django.utils.translation import ugettext_lazy as _ from meinberlin.apps.dashboard2 import DashboardComponent from meinberlin.apps.dashboard2 import content from . import views from .apps import Config class OfflineEventsComponent(DashboardComponent): app_label = Config.label label = 'offlineevents' identifier = 'offlineevents' def get_menu_label(self, project): return _('Offline Events') def get_progress(self, project): return 0, 0 def get_urls(self): return [ (r'^offlineevent/projects/(?P<project_slug>[-\w_]+)/$', views.OfflineEventListView.as_view(component=self), 'offlineevent-list'), (r'^offlineevent/create/project/(?P<project_slug>[-\w_]+)/$', views.OfflineEventCreateView.as_view(component=self), 'offlineevent-create'), (r'^offlineevent/(?P<slug>[-\w_]+)/update/$', views.OfflineEventUpdateView.as_view(component=self), 'offlineevent-update'), (r'^offlineevent/(?P<slug>[-\w_]+)/delete/$', views.OfflineEventDeleteView.as_view(component=self), 'offlineevent-delete') ] content.register_project(OfflineEventsComponent())
from django.utils.translation import ugettext_lazy as _ from meinberlin.apps.dashboard2 import DashboardComponent from meinberlin.apps.dashboard2 import content from . import views from .apps import Config class OfflineEventsComponent(DashboardComponent): app_label = Config.label label = 'offlineevents' identifier = 'offlineevents' def get_menu_label(self, project): return _('Offline Events') def get_progress(self, project): return 0, 0 def get_urls(self): return [ (r'^offlineevents/projects/(?P<project_slug>[-\w_]+)/$', views.OfflineEventListView.as_view(component=self), 'offlineevent-list'), (r'^offlineevents/create/project/(?P<project_slug>[-\w_]+)/$', views.OfflineEventCreateView.as_view(component=self), 'offlineevent-create'), (r'^offlineevents/(?P<slug>[-\w_]+)/update/$', views.OfflineEventUpdateView.as_view(component=self), 'offlineevent-update'), (r'^offlineevents/(?P<slug>[-\w_]+)/delete/$', views.OfflineEventDeleteView.as_view(component=self), 'offlineevent-delete') ] content.register_project(OfflineEventsComponent())
Rename offlineevent to offlineevents route
Rename offlineevent to offlineevents route
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
--- +++ @@ -20,16 +20,16 @@ def get_urls(self): return [ - (r'^offlineevent/projects/(?P<project_slug>[-\w_]+)/$', + (r'^offlineevents/projects/(?P<project_slug>[-\w_]+)/$', views.OfflineEventListView.as_view(component=self), 'offlineevent-list'), - (r'^offlineevent/create/project/(?P<project_slug>[-\w_]+)/$', + (r'^offlineevents/create/project/(?P<project_slug>[-\w_]+)/$', views.OfflineEventCreateView.as_view(component=self), 'offlineevent-create'), - (r'^offlineevent/(?P<slug>[-\w_]+)/update/$', + (r'^offlineevents/(?P<slug>[-\w_]+)/update/$', views.OfflineEventUpdateView.as_view(component=self), 'offlineevent-update'), - (r'^offlineevent/(?P<slug>[-\w_]+)/delete/$', + (r'^offlineevents/(?P<slug>[-\w_]+)/delete/$', views.OfflineEventDeleteView.as_view(component=self), 'offlineevent-delete') ]
e8ff222331d9fe6ea5b91a7c673e631effe3d9ec
traits/tests/test_regression.py
traits/tests/test_regression.py
""" General regression tests for fixed bugs. """ import gc import unittest import sys from traits.has_traits import HasTraits def _create_subclass(): class Subclass(HasTraits): pass return Subclass class TestRegression(unittest.TestCase): def test_subclasses_weakref(self): """ Make sure that dynamically created subclasses are not held strongly by HasTraits. """ previous_subclasses = HasTraits.__subclasses__() _create_subclass() _create_subclass() _create_subclass() _create_subclass() gc.collect() self.assertEqual(previous_subclasses, HasTraits.__subclasses__())
""" General regression tests for fixed bugs. """ import gc import unittest import sys from traits.has_traits import HasTraits def _create_subclass(): class Subclass(HasTraits): pass return Subclass class TestRegression(unittest.TestCase): def test_subclasses_weakref(self): """ Make sure that dynamically created subclasses are not held strongly by HasTraits. """ previous_subclasses = HasTraits.__subclasses__() _create_subclass() _create_subclass() _create_subclass() _create_subclass() gc.collect() self.assertEqual(previous_subclasses, HasTraits.__subclasses__()) def test_leaked_property_tuple(self): """ the property ctrait constructor shouldn't leak a tuple. """ class A(HasTraits): prop = Property() a = A() self.assertEqual(sys.getrefcount(a.trait('prop').property()), 1) if __name__ == '__main__': unittest.main()
Add a test case for the tuple leak in ctraits property.
Add a test case for the tuple leak in ctraits property. Courtesy Robert Kern.
Python
bsd-3-clause
burnpanck/traits,burnpanck/traits
--- +++ @@ -27,3 +27,14 @@ _create_subclass() gc.collect() self.assertEqual(previous_subclasses, HasTraits.__subclasses__()) + + def test_leaked_property_tuple(self): + """ the property ctrait constructor shouldn't leak a tuple. """ + class A(HasTraits): + prop = Property() + a = A() + self.assertEqual(sys.getrefcount(a.trait('prop').property()), 1) + + +if __name__ == '__main__': + unittest.main()
3bc8aa5499d111e66a6e71882a95bd6c357ac6f6
src/python/tensorflow_cloud/core/tests/examples/multi_file_example/create_model.py
src/python/tensorflow_cloud/core/tests/examples/multi_file_example/create_model.py
# Copyright 2020 Google LLC. 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. import os import tensorflow as tf # Create the model def create_keras_model(): model = tf.keras.Sequential( [ tf.keras.layers.Conv2D(32, 3, activation="relu", input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dense(64, activation="relu"), tf.keras.layers.Dense(10, activation="softmax"), ] ) model.compile( loss="sparse_categorical_crossentropy", optimizer=tf.keras.optimizers.Adam(), metrics=["accuracy"], ) return model
# Copyright 2020 Google LLC. 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. import os import tensorflow as tf def create_keras_model(): model = tf.keras.Sequential( [ tf.keras.layers.Conv2D(32, 3, activation="relu", input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dense(64, activation="relu"), tf.keras.layers.Dense(10, activation="softmax"), ] ) model.compile( loss="sparse_categorical_crossentropy", optimizer=tf.keras.optimizers.Adam(), metrics=["sparse_categorical_accuracy"], ) return model
Format code using black and remove comments
Format code using black and remove comments
Python
apache-2.0
tensorflow/cloud,tensorflow/cloud
--- +++ @@ -16,7 +16,6 @@ import tensorflow as tf -# Create the model def create_keras_model(): model = tf.keras.Sequential( @@ -32,7 +31,7 @@ model.compile( loss="sparse_categorical_crossentropy", optimizer=tf.keras.optimizers.Adam(), - metrics=["accuracy"], + metrics=["sparse_categorical_accuracy"], ) return model
dd110868f3c4fa373e9aeaced58ebcb626d1187b
server.py
server.py
import web from os import path rootdir = path.abspath('./build') def getFile(filename): filename = path.join(rootdir, filename) print filename if (not filename.startswith(rootdir)): return None if (not path.exists(filename)): return None f = open(filename, 'r') contents = f.read() f.close() return contents class index: def handle(self, filename, i): if (filename == ""): filename = "recon.html" contents = getFile(filename) if ("data" in i): data = i.data.replace("'", "\\'") return contents.replace("<!-- POSTed data goes here -->", "<script language='javascript'>handlePOSTdata('%s')</script>" % data) return contents def POST(self, filename): return self.handle(filename, web.input()) def GET(self, filename): return self.handle(filename, web.input()) web.config.debug = False urls = ('/(.*)', 'index') app = web.application(urls, globals()) if __name__ == "__main__": web.httpserver.runsimple(app.wsgifunc(), ("localhost",9777))
import web from os import path rootdir = path.abspath('./build') def getFile(filename): filename = path.join(rootdir, filename) print filename if (not filename.startswith(rootdir)): return None if (not path.exists(filename)): return None f = open(filename, 'r') contents = f.read() f.close() return contents class index: def handle(self, filename, i): if (filename == ""): filename = "recon.html" web.header('Content-type','text/html') contents = getFile(filename) if ("data" in i): data = i.data.replace("'", "\\'") return contents.replace("<!-- POSTed data goes here -->", "<script language='javascript'>handlePOSTdata('%s')</script>" % data) return contents def POST(self, filename): return self.handle(filename, web.input()) def GET(self, filename): return self.handle(filename, web.input()) web.config.debug = False urls = ('/(.*)', 'index') app = web.application(urls, globals()) if __name__ == "__main__": web.httpserver.runsimple(app.wsgifunc(), ("localhost",9777))
Add a Content-type when it's not clear
Add a Content-type when it's not clear
Python
bsd-2-clause
rictic/reconciliation_ui,rictic/reconciliation_ui,rictic/reconciliation_ui
--- +++ @@ -18,6 +18,7 @@ def handle(self, filename, i): if (filename == ""): filename = "recon.html" + web.header('Content-type','text/html') contents = getFile(filename) if ("data" in i): data = i.data.replace("'", "\\'")
3640a8c6057ffac8f8d0f7cd6af8954b4169543d
commands.py
commands.py
from runcommands import command from runcommands.commands import local as _local @command def format_code(check=False): _local(f"black . {'--check' if check else ''}") @command def lint(): _local("flake8 .") @command def test(with_coverage=True, check=True): if with_coverage: _local( "coverage run " "--source src/local_settings " "-m unittest discover " "-t . -s tests " "&& coverage report" ) else: _local("python -m unittest discover -t . -s tests") if check: format_code(check=True) lint() @command def tox(clean=False): _local(f"tox {'-r' if clean else ''}")
from runcommands import command from runcommands.commands import local as _local @command def format_code(check=False): _local(f"black . {'--check' if check else ''}") @command def lint(): _local("flake8 .") @command def test(with_coverage=True, check=True, fail_fast=False): if with_coverage: _local( "coverage run " "--source src/local_settings " "-m unittest discover " "-t . -s tests " "&& coverage report" ) else: fail_fast = "-f" if fail_fast else "" _local(f"python -m unittest discover -t . -s tests {fail_fast}") if check: format_code(check=True) lint() @command def tox(clean=False): _local(f"tox {'-r' if clean else ''}")
Add --fail-fast flag to test command
Add --fail-fast flag to test command
Python
mit
wylee/django-local-settings
--- +++ @@ -13,7 +13,7 @@ @command -def test(with_coverage=True, check=True): +def test(with_coverage=True, check=True, fail_fast=False): if with_coverage: _local( "coverage run " @@ -23,7 +23,8 @@ "&& coverage report" ) else: - _local("python -m unittest discover -t . -s tests") + fail_fast = "-f" if fail_fast else "" + _local(f"python -m unittest discover -t . -s tests {fail_fast}") if check: format_code(check=True) lint()
53a3c61a9facf246810b8be7638b62eda5214a47
djoauth2/conf.py
djoauth2/conf.py
# coding: utf-8 from django.conf import settings from appconf import AppConf class DJOAuth2Conf(AppConf): class Meta: prefix = 'djoauth2' ACCESS_TOKEN_LENGTH = 30 ACCESS_TOKEN_LIFETIME = 3600 ACCESS_TOKENS_REFRESHABLE = True AUTHORIZATION_CODE_LENGTH = 30 AUTHORIZATION_CODE_LIFETIME = 120 CLIENT_KEY_LENGTH = 30 CLIENT_SECRET_LENGTH = 30 REFRESH_TOKEN_LENGTH = 30 REALM = '' REQUIRE_STATE = True SSL_ONLY = True
# coding: utf-8 from django.conf import settings from appconf import AppConf class DJOAuth2Conf(AppConf): class Meta: prefix = 'djoauth2' ACCESS_TOKEN_LENGTH = 30 ACCESS_TOKEN_LIFETIME = 3600 ACCESS_TOKENS_REFRESHABLE = True AUTHORIZATION_CODE_LENGTH = 30 # The specification ( http://tools.ietf.org/html/rfc6749#section-4.1.1 ) # recommends a liftime of 10 minutes. AUTHORIZATION_CODE_LIFETIME = 600 CLIENT_KEY_LENGTH = 30 CLIENT_SECRET_LENGTH = 30 REFRESH_TOKEN_LENGTH = 30 REALM = '' REQUIRE_STATE = True SSL_ONLY = True
Update default authorization code lifetime.
Update default authorization code lifetime.
Python
mit
Locu/djoauth2,vden/djoauth2-ng,Locu/djoauth2,seler/djoauth2,seler/djoauth2,vden/djoauth2-ng
--- +++ @@ -12,7 +12,9 @@ ACCESS_TOKENS_REFRESHABLE = True AUTHORIZATION_CODE_LENGTH = 30 - AUTHORIZATION_CODE_LIFETIME = 120 + # The specification ( http://tools.ietf.org/html/rfc6749#section-4.1.1 ) + # recommends a liftime of 10 minutes. + AUTHORIZATION_CODE_LIFETIME = 600 CLIENT_KEY_LENGTH = 30 CLIENT_SECRET_LENGTH = 30
18e0a57f133779b2001b93f9d16ef500f449ebd9
responsive/context_processors.py
responsive/context_processors.py
from __future__ import unicode_literals from .conf import BREAKPOINTS def _get_device_type(width): "Returns the type based on set breakpoints." sorted_types = sorted(BREAKPOINTS.items(), key=lambda x: x[1]) default_type = None for name, cutoff in sorted_types: if cutoff is None: default_type = name elif width <= cutoff: return name return default_type def device_info(request): "Add processed device info into the template context." default = {'width': None, 'height': None} info = getattr(request, 'device_info', default) width = info.get('width', None) if width is not None: info['type'] = _get_device_type(width) else: info['type'] = None return {'device_info': info}
from __future__ import unicode_literals from .conf import BREAKPOINTS def _get_device_type(width): "Returns the type based on set breakpoints." sorted_types = sorted(BREAKPOINTS.items(), key=lambda x: x[1] or 0) default_type = None for name, cutoff in sorted_types: if cutoff is None: default_type = name elif width <= cutoff: return name return default_type def device_info(request): "Add processed device info into the template context." default = {'width': None, 'height': None} info = getattr(request, 'device_info', default) width = info.get('width', None) if width is not None: info['type'] = _get_device_type(width) else: info['type'] = None return {'device_info': info}
Fix sorting dictionary key, value pairs in Python 3.
Fix sorting dictionary key, value pairs in Python 3.
Python
bsd-2-clause
mlavin/django-responsive,mlavin/django-responsive,mlavin/django-responsive
--- +++ @@ -5,7 +5,7 @@ def _get_device_type(width): "Returns the type based on set breakpoints." - sorted_types = sorted(BREAKPOINTS.items(), key=lambda x: x[1]) + sorted_types = sorted(BREAKPOINTS.items(), key=lambda x: x[1] or 0) default_type = None for name, cutoff in sorted_types: if cutoff is None:
72ed5473c1b530357bd518149fcfafdea1bc3987
murano_tempest_tests/tests/api/service_broker/test_service_broker_negative.py
murano_tempest_tests/tests/api/service_broker/test_service_broker_negative.py
# Copyright (c) 2015 Mirantis, Inc. # 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. import unittest from tempest import test from tempest_lib import exceptions from murano_tempest_tests.tests.api.service_broker import base from murano_tempest_tests import utils class ServiceBrokerNegativeTest(base.BaseServiceBrokerAdminTest): # NOTE(freerunner): Tempest will fail with this test, because its # _parse_resp function trying to parse a nullable JSON. # https://review.openstack.org/#/c/260659/ # XFail until this one merged and tempest-lib released. @unittest.expectedFailure @test.attr(type=['gate', 'negative']) def test_get_status_with_not_present_instance_id(self): not_present_instance_id = utils.generate_uuid() self.assertRaises( exceptions.Gone, self.service_broker_client.get_last_status, not_present_instance_id)
# Copyright (c) 2015 Mirantis, Inc. # 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 tempest import test from tempest_lib import exceptions from murano_tempest_tests.tests.api.service_broker import base from murano_tempest_tests import utils class ServiceBrokerNegativeTest(base.BaseServiceBrokerAdminTest): @test.attr(type=['gate', 'negative']) def test_get_status_with_not_present_instance_id(self): not_present_instance_id = utils.generate_uuid() self.assertRaises( exceptions.Gone, self.service_broker_client.get_last_status, not_present_instance_id)
Remove xfail in service broker negative tests
Remove xfail in service broker negative tests After tempest-lib 0.14.0 release all fixes in tempest become present. This patch removes xfail for negative test in service broker test suite. Change-Id: Ide900d53fd478885208e53c333d6759e938a960b Closes-Bug: #1527949
Python
apache-2.0
NeCTAR-RC/murano,satish-avninetworks/murano,DavidPurcell/murano_temp,satish-avninetworks/murano,olivierlemasle/murano,olivierlemasle/murano,openstack/murano,DavidPurcell/murano_temp,DavidPurcell/murano_temp,NeCTAR-RC/murano,NeCTAR-RC/murano,openstack/murano,satish-avninetworks/murano,NeCTAR-RC/murano,satish-avninetworks/murano,olivierlemasle/murano,DavidPurcell/murano_temp,olivierlemasle/murano
--- +++ @@ -13,8 +13,6 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest - from tempest import test from tempest_lib import exceptions @@ -24,11 +22,6 @@ class ServiceBrokerNegativeTest(base.BaseServiceBrokerAdminTest): - # NOTE(freerunner): Tempest will fail with this test, because its - # _parse_resp function trying to parse a nullable JSON. - # https://review.openstack.org/#/c/260659/ - # XFail until this one merged and tempest-lib released. - @unittest.expectedFailure @test.attr(type=['gate', 'negative']) def test_get_status_with_not_present_instance_id(self): not_present_instance_id = utils.generate_uuid()
8fbc125eb242716873d5c8cb0420206077f6acc5
stocks.py
stocks.py
#!/usr/bin/python import sys from pprint import pprint import ystockquote for quote in sys.argv[1:]: print 'Finding quote for %s' % quote # First thing we want is some basic information on the quote. details = ystockquote.get_all(quote)
#!/usr/bin/python import sys from pprint import pprint import ystockquote for quote in sys.argv[1:]: print 'Finding quote for %s' % quote # First thing we want is some basic information on the quote. details = ystockquote.get_all(quote) print 'Last Open: $%s' % details.get('today_open')
Print out the last open price
Print out the last open price
Python
mit
johndavidback/stock-picker
--- +++ @@ -12,7 +12,7 @@ # First thing we want is some basic information on the quote. details = ystockquote.get_all(quote) - + print 'Last Open: $%s' % details.get('today_open')
d27f5e92d6a0fef27b903f75de59c1d85ca35430
packages/Python/lldbsuite/test/lang/cpp/modules-import/TestCXXModulesImport.py
packages/Python/lldbsuite/test/lang/cpp/modules-import/TestCXXModulesImport.py
"""Test that importing modules in C++ works as expected.""" from __future__ import print_function from distutils.version import StrictVersion import unittest2 import os import time import lldb import platform from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class CXXModulesImportTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipUnlessDarwin @skipIf(macos_version=["<", "10.12"]) def test_expr(self): self.build() exe = self.getBuildArtifact("a.out") target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( self, 'break here', lldb.SBFileSpec('main.cpp')) self.expect("expr -- @import Bar") self.expect("expr -- Bar()", substrs = ["success"])
"""Test that importing modules in C++ works as expected.""" from __future__ import print_function from distutils.version import StrictVersion import unittest2 import os import time import lldb import platform from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class CXXModulesImportTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipUnlessDarwin @skipIf(macos_version=["<", "10.12"]) def test_expr(self): self.build() exe = self.getBuildArtifact("a.out") target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( self, 'break here', lldb.SBFileSpec('main.cpp')) self.expect("expr -l Objective-C++ -- @import Bar") self.expect("expr -- Bar()", substrs = ["success"])
Add explicit language specifier to test.
Add explicit language specifier to test. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@354048 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb
--- +++ @@ -27,5 +27,5 @@ target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( self, 'break here', lldb.SBFileSpec('main.cpp')) - self.expect("expr -- @import Bar") + self.expect("expr -l Objective-C++ -- @import Bar") self.expect("expr -- Bar()", substrs = ["success"])
6ee135dc454b7ae13dbd4603de60b5eba12cc5c9
saleor/graphql/core/decorators.py
saleor/graphql/core/decorators.py
from functools import wraps from django.core.exceptions import PermissionDenied def permission_required(permissions): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): info = args[1] user = info.context.user if not user.has_perm(permissions): raise PermissionDenied( 'You have no permission to use %s' % info.field_name) return func(*args, **kwargs) return wrapper return decorator
from functools import wraps from django.core.exceptions import PermissionDenied from graphql.execution.base import ResolveInfo def permission_required(permissions): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): info = args[1] assert isinstance(info, ResolveInfo) user = info.context.user if not user.has_perm(permissions): raise PermissionDenied( 'You have no permission to use %s' % info.field_name) return func(*args, **kwargs) return wrapper return decorator
Make sure decorator is being used with proper function signatures
Make sure decorator is being used with proper function signatures
Python
bsd-3-clause
UITools/saleor,UITools/saleor,mociepka/saleor,mociepka/saleor,maferelo/saleor,maferelo/saleor,UITools/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,UITools/saleor
--- +++ @@ -1,6 +1,7 @@ from functools import wraps from django.core.exceptions import PermissionDenied +from graphql.execution.base import ResolveInfo def permission_required(permissions): @@ -8,6 +9,7 @@ @wraps(func) def wrapper(*args, **kwargs): info = args[1] + assert isinstance(info, ResolveInfo) user = info.context.user if not user.has_perm(permissions): raise PermissionDenied(
5557fbff1e6843261a902f260ef9415e1e795879
test_elasticsearch/run_tests.py
test_elasticsearch/run_tests.py
#!/usr/bin/env python import sys from os import path import nose def run_all(argv=None): sys.exitfunc = lambda: sys.stderr.write('Shutting down....\n') # always insert coverage when running tests if argv is None: argv = [ 'nosetests', '--with-xunit', '--with-xcoverage', '--cover-package=elasticsearch', '--cover-erase', '--nocapture', '--nologcapture', '--verbose', ] else: for p in ('--with-coverage', '--cover-package=elasticsearch', '--cover-erase'): if p not in argv: argv.append(p) nose.run_exit( argv=argv, defaultTest=path.abspath(path.dirname(__file__)) ) if __name__ == '__main__': run_all(sys.argv)
#!/usr/bin/env python import sys from os import path import nose def run_all(argv=None): sys.exitfunc = lambda: sys.stderr.write('Shutting down....\n') # always insert coverage when running tests if argv is None: argv = [ 'nosetests', '--with-xunit', '--with-xcoverage', '--cover-package=elasticsearch', '--cover-erase', '--logging-filter=elasticsearch', '--logging-level=DEBUG', '--verbose', ] else: for p in ('--with-coverage', '--cover-package=elasticsearch', '--cover-erase'): if p not in argv: argv.append(p) nose.run_exit( argv=argv, defaultTest=path.abspath(path.dirname(__file__)) ) if __name__ == '__main__': run_all(sys.argv)
Make sure jenkins output contains logs
Make sure jenkins output contains logs
Python
apache-2.0
prinsherbert/elasticsearch-py,veatch/elasticsearch-py,gardsted/elasticsearch-py,AlexMaskovyak/elasticsearch-py,Garrett-R/elasticsearch-py,elastic/elasticsearch-py,konradkonrad/elasticsearch-py,chrisseto/elasticsearch-py,liuyi1112/elasticsearch-py,kelp404/elasticsearch-py,brunobell/elasticsearch-py,tailhook/elasticsearch-py,mjhennig/elasticsearch-py,thomdixon/elasticsearch-py,brunobell/elasticsearch-py,elastic/elasticsearch-py
--- +++ @@ -11,7 +11,7 @@ argv = [ 'nosetests', '--with-xunit', '--with-xcoverage', '--cover-package=elasticsearch', '--cover-erase', - '--nocapture', '--nologcapture', + '--logging-filter=elasticsearch', '--logging-level=DEBUG', '--verbose', ] else:
390fc84183c0f680c5fb1a980ee3c1227b187611
HowLong/HowLong.py
HowLong/HowLong.py
#!/usr/bin/env python3 import argparse from datetime import timedelta from subprocess import Popen from time import time, sleep def red(text): RED = '\033[91m' END = '\033[0m' return RED + text + END class HowLong(object): def __init__(self): parser = argparse.ArgumentParser(description='Time a process') parser.add_argument('-i', type=float, nargs='?', metavar='interval', help='the timer interval, defaults to 1 second') parser.add_argument('command', metavar='C', type=str, nargs='+', help='a valid command') self.parsed_args = parser.parse_args() self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1 self.readable_command = " ".join(self.parsed_args.command) def run(self): print("Running", self.readable_command) process = Popen(self.parsed_args.command) start_time = time() while process.poll() is None: sleep(self.timer_interval) elapsed_time = (time() - start_time) * 1000 print(red(str(timedelta(milliseconds=elapsed_time)))) print("Finished", self.readable_command) def howlong(): HowLong().run() if __name__ == "__main__": howlong()
from __future__ import print_function import sys import argparse from datetime import timedelta from subprocess import Popen from time import time, sleep def red(text): RED = '\033[91m' END = '\033[0m' return RED + text + END def log(*args): print(*args, file=sys.stderr) sys.stderr.flush() class HowLong(object): def __init__(self): parser = argparse.ArgumentParser(description='Time a process') parser.add_argument('-i', type=float, nargs='?', metavar='interval', help='the timer interval, defaults to 1 second') parser.add_argument('command', metavar='C', type=str, nargs='+', help='a valid command') self.parsed_args = parser.parse_args() self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1 self.readable_command = " ".join(self.parsed_args.command) def run(self): log("Running", self.readable_command) process = Popen(self.parsed_args.command) start_time = time() while process.poll() is None: sleep(self.timer_interval) elapsed_time = (time() - start_time) * 1000 log(red(str(timedelta(milliseconds=elapsed_time)))) log("Finished", self.readable_command) def howlong(): HowLong().run() if __name__ == "__main__": howlong()
Print debug info to stderr
MINOR: Print debug info to stderr
Python
apache-2.0
mattjegan/HowLong
--- +++ @@ -1,5 +1,5 @@ -#!/usr/bin/env python3 - +from __future__ import print_function +import sys import argparse from datetime import timedelta from subprocess import Popen @@ -10,6 +10,11 @@ RED = '\033[91m' END = '\033[0m' return RED + text + END + + +def log(*args): + print(*args, file=sys.stderr) + sys.stderr.flush() class HowLong(object): @@ -26,18 +31,20 @@ self.readable_command = " ".join(self.parsed_args.command) def run(self): - print("Running", self.readable_command) + log("Running", self.readable_command) process = Popen(self.parsed_args.command) start_time = time() while process.poll() is None: sleep(self.timer_interval) elapsed_time = (time() - start_time) * 1000 - print(red(str(timedelta(milliseconds=elapsed_time)))) + log(red(str(timedelta(milliseconds=elapsed_time)))) - print("Finished", self.readable_command) + log("Finished", self.readable_command) + def howlong(): HowLong().run() + if __name__ == "__main__": howlong()
5086a41e9aae7da16e4b189285613c2dade2b95a
common_rg_bar.py
common_rg_bar.py
#!/usr/bin/env python3 ''' Given: 1. status code: (0 - OK, other value - BAD) 2. terminal window width shows red/green bar to visualize return code of previous command ''' import sys def main(): if len(sys.argv) >= 2: code = sys.argv[1] if code == 'x': col_char = '3' cols_limit = 78 else: if code == 'y': col_char = '3' else: value = int(code) if value: col_char = '1' else: col_char = '2' cols_limit = int(sys.argv[2]) esc = chr(27) print (''.join(( esc, '[4', col_char, 'm', ' ' * (cols_limit - 2 - len(code)), code, esc, '[0m', ))) else: print (''' Usage: %(prog_name)s status_code number_of_columns 1. status code: 0 - OK (green color), other values - BAD (red color) 2. number of columns: the width of text console ''' % dict( prog_name=sys.argv[0], ))
#!/usr/bin/env python3 ''' Given: 1. status code: (0 - OK, other value - BAD) 2. terminal window width shows red/green bar to visualize return code of previous command ''' import sys def main(): if len(sys.argv) >= 2: code = sys.argv[1] if code == 'x': col_char = '3' cols_limit = 78 code = '' # No code provided - only yellow bar else: if code == 'y': col_char = '3' else: value = int(code) if value: col_char = '1' else: col_char = '2' cols_limit = int(sys.argv[2]) esc = chr(27) print (''.join(( esc, '[4', col_char, 'm', ' ' * (cols_limit - 2 - len(code)), code, esc, '[0m', ))) else: print (''' Usage: %(prog_name)s status_code number_of_columns 1. status code: 0 - OK (green color), other values - BAD (red color) 2. number of columns: the width of text console ''' % dict( prog_name=sys.argv[0], ))
Stop displaying x as the code
Stop displaying x as the code
Python
mit
kwadrat/rgb_tdd
--- +++ @@ -16,6 +16,7 @@ if code == 'x': col_char = '3' cols_limit = 78 + code = '' # No code provided - only yellow bar else: if code == 'y': col_char = '3'
093f8971b09dec696da94ccf5f14f191cbf3d672
src/dicomweb_client/__init__.py
src/dicomweb_client/__init__.py
__version__ = '0.3.1rc' from dicomweb_client.api import DICOMWebClient
__version__ = '0.3.1' from dicomweb_client.api import DICOMWebClient
Increase version for 0.3.1 release
Increase version for 0.3.1 release
Python
mit
MGHComputationalPathology/dicomweb-client
--- +++ @@ -1,3 +1,3 @@ -__version__ = '0.3.1rc' +__version__ = '0.3.1' from dicomweb_client.api import DICOMWebClient
b4aee8dc8e582940fa5a983ea0a90ab9b4e4f9e6
torchtext/legacy/data/__init__.py
torchtext/legacy/data/__init__.py
from .batch import Batch from .example import Example from .field import RawField, Field, ReversibleField, SubwordField, NestedField, LabelField from .iterator import (batch, BucketIterator, Iterator, BPTTIterator, pool) from .pipeline import Pipeline from .dataset import Dataset, TabularDataset # Those are not in the legacy folder. from ...data.metrics import bleu_score from ...data.utils import get_tokenizer, interleave_keys from ...data.functional import generate_sp_model, \ load_sp_model, \ sentencepiece_numericalizer, \ sentencepiece_tokenizer, custom_replace, simple_space_split, \ numericalize_tokens_from_iterator __all__ = ["Batch", "Example", "RawField", "Field", "ReversibleField", "SubwordField", "NestedField", "LabelField", "batch", "BucketIterator", "Iterator", "BPTTIterator", "pool", "Pipeline", "Dataset", "TabularDataset", "bleu_score", "get_tokenizer", "interleave_keys", "generate_sp_model", "load_sp_model", "sentencepiece_numericalizer", "sentencepiece_tokenizer", "custom_replace", "simple_space_split", "numericalize_tokens_from_iterator"]
from .batch import Batch from .example import Example from .field import RawField, Field, ReversibleField, SubwordField, NestedField, LabelField from .iterator import (batch, BucketIterator, Iterator, BPTTIterator, pool) from .pipeline import Pipeline from .dataset import Dataset, TabularDataset # Those are not in the legacy folder. from ...data import metrics from ...data.metrics import bleu_score from ...data import utils from ...data.utils import get_tokenizer, interleave_keys from ...data import functional from ...data.functional import generate_sp_model, \ load_sp_model, \ sentencepiece_numericalizer, \ sentencepiece_tokenizer, custom_replace, simple_space_split, \ numericalize_tokens_from_iterator __all__ = ["Batch", "Example", "RawField", "Field", "ReversibleField", "SubwordField", "NestedField", "LabelField", "batch", "BucketIterator", "Iterator", "BPTTIterator", "pool", "Pipeline", "Dataset", "TabularDataset", "metrics", "bleu_score", "utils", "get_tokenizer", "interleave_keys", "functional", "generate_sp_model", "load_sp_model", "sentencepiece_numericalizer", "sentencepiece_tokenizer", "custom_replace", "simple_space_split", "numericalize_tokens_from_iterator"]
Enable importing metrics/utils/functional from torchtext.legacy.data
Enable importing metrics/utils/functional from torchtext.legacy.data
Python
bsd-3-clause
pytorch/text,pytorch/text,pytorch/text,pytorch/text
--- +++ @@ -5,8 +5,11 @@ from .pipeline import Pipeline from .dataset import Dataset, TabularDataset # Those are not in the legacy folder. +from ...data import metrics from ...data.metrics import bleu_score +from ...data import utils from ...data.utils import get_tokenizer, interleave_keys +from ...data import functional from ...data.functional import generate_sp_model, \ load_sp_model, \ sentencepiece_numericalizer, \ @@ -20,8 +23,11 @@ "batch", "BucketIterator", "Iterator", "BPTTIterator", "pool", "Pipeline", "Dataset", "TabularDataset", + "metrics", "bleu_score", + "utils", "get_tokenizer", "interleave_keys", + "functional", "generate_sp_model", "load_sp_model", "sentencepiece_numericalizer", "sentencepiece_tokenizer", "custom_replace", "simple_space_split",
5a252090eb8fe75a5faf058151009bccd3645e70
upload.py
upload.py
import os import re import datetime from trovebox import Trovebox def main(): try: client = Trovebox() client.configure(api_version=2) except IOError, e: print print '!! Could not initialize Trovebox connection.' print '!! Check that ~/.config/trovebox/default exists and contains proper information.' print raise e starttime = datetime.datetime.now() for root, folders, files in os.walk(os.getcwd()): folder_name = None for filename in files: if not re.match(r'^.+\.jpg$', filename, flags=re.IGNORECASE): continue if not folder_name: folder_name = root.split('/')[-1] print 'Entering folder %s' % root print 'Uploading %s...' % filename path = '%s/%s' % (root, filename) client.photo.upload(path, tags=['API test', folder_name]) print datetime.datetime.now() - starttime if __name__ == "__main__": main()
import os import re import datetime from trovebox import Trovebox def main(): try: client = Trovebox() client.configure(api_version=2) except IOError, e: print print '!! Could not initialize Trovebox connection.' print '!! Check that ~/.config/trovebox/default exists and contains proper information.' print raise e starttime = datetime.datetime.now() for root, folders, files in os.walk(os.getcwd()): folder_name = album = None for filename in files: if not re.match(r'^.+\.jpg$', filename, flags=re.IGNORECASE): continue if not folder_name: folder_name = root.split('/')[-1] album = client.album.create(folder_name) print 'Entering folder %s' % root print 'Uploading %s...' % filename path = '%s/%s' % (root, filename) client.photo.upload(path, albums=[album.id]) print datetime.datetime.now() - starttime if __name__ == "__main__": main()
Create albums for each folder instead of tags
Create albums for each folder instead of tags
Python
mit
nip3o/trovebox-uploader
--- +++ @@ -19,7 +19,7 @@ starttime = datetime.datetime.now() for root, folders, files in os.walk(os.getcwd()): - folder_name = None + folder_name = album = None for filename in files: if not re.match(r'^.+\.jpg$', filename, flags=re.IGNORECASE): @@ -27,12 +27,13 @@ if not folder_name: folder_name = root.split('/')[-1] + album = client.album.create(folder_name) print 'Entering folder %s' % root print 'Uploading %s...' % filename path = '%s/%s' % (root, filename) - client.photo.upload(path, tags=['API test', folder_name]) + client.photo.upload(path, albums=[album.id]) print datetime.datetime.now() - starttime