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
b999c9a9bbd8052771ade80bad14f8aef2bef58b
conda/python-scons/system.py
conda/python-scons/system.py
import platform from SCons.Script import AddOption, GetOption SYSTEMS = dict(Linux = "linux", Darwin = "osx", Windows = "windows") system = str(platform.system()) if not system in SYSTEMS: system = "unknown" AddOption('--system', dest = 'system', type = 'string'...
import platform from SCons.Script import AddOption, GetOption SYSTEMS = dict(Linux = "linux", Darwin = "osx", Windows = "windows") system = str(platform.system()) if not system in SYSTEMS: system = "unknown" AddOption('--system', dest = 'system', type = 'choice'...
Test add site_scons as SCons module
Test add site_scons as SCons module
Python
apache-2.0
StatisKit/StatisKit,StatisKit/StatisKit
--- +++ @@ -12,7 +12,7 @@ AddOption('--system', dest = 'system', - type = 'string', + type = 'choice', nargs = 1, action = 'store', help = 'system',
2d05ede4db8bf80834e04ffb5f9d0ec11982851d
normandy/recipes/validators.py
normandy/recipes/validators.py
import json import jsonschema from django.core.exceptions import ValidationError # Add path to required validator so we can get property name def _required(validator, required, instance, schema): '''Validate 'required' properties.''' if not validator.is_type(instance, 'object'): return for index...
import json import jsonschema from django.core.exceptions import ValidationError # Add path to required validator so we can get property name def _required(validator, required, instance, schema): '''Validate 'required' properties.''' if not validator.is_type(instance, 'object'): return for index...
Check for empty strings in required validator
Check for empty strings in required validator
Python
mpl-2.0
Osmose/normandy,mozilla/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,mozilla/normandy
--- +++ @@ -11,7 +11,7 @@ return for index, requirement in enumerate(required): - if requirement not in instance: + if requirement not in instance or instance[requirement] == '': error = jsonschema.ValidationError( 'This field may not be blank.', ...
fe8221e398bb9a1ddabf08002441acb37dfef515
scripts/release_test/arguments.py
scripts/release_test/arguments.py
import argparse, common, sys, tests from features import check_features, get_features def arguments(argv=sys.argv[1:]): parser = argparse.ArgumentParser() parser.add_argument( 'tests', nargs='*', help='The list of tests to run') parser.add_argument( '--features', '-f', default=[], action...
import argparse, common, sys, tests from features import check_features, get_features, FEATURES def arguments(argv=sys.argv[1:]): parser = argparse.ArgumentParser() names = [t.__name__.split('.')[1] for t in tests.__all__] names = ', '.join(names) parser.add_argument( 'tests', nargs='*', ...
Improve help messages from release_test
Improve help messages from release_test
Python
mit
ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel
--- +++ @@ -1,16 +1,22 @@ import argparse, common, sys, tests -from features import check_features, get_features +from features import check_features, get_features, FEATURES def arguments(argv=sys.argv[1:]): parser = argparse.ArgumentParser() - parser.add_argument( - 'tests', nargs='*', help='T...
95d1bf068ebf2f57eaf44accbe15aa30d236d8ea
astropy/coordinates/tests/test_distance.py
astropy/coordinates/tests/test_distance.py
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import print_function from numpy import testing as npt from ... import units as u """ This includes tests for distances/cartesian points that are *not* in the API tests. Right now that's just regression tests. "...
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import print_function from numpy import testing as npt from ... import units as u """ This includes tests for distances/cartesian points that are *not* in the API tests. Right now that's just regression tests. "...
Add test for applying a distance to a coordinate via a quantity
Add test for applying a distance to a coordinate via a quantity
Python
bsd-3-clause
pllim/astropy,astropy/astropy,dhomeier/astropy,dhomeier/astropy,bsipocz/astropy,pllim/astropy,astropy/astropy,pllim/astropy,tbabej/astropy,aleksandr-bakanov/astropy,larrybradley/astropy,larrybradley/astropy,joergdietrich/astropy,aleksandr-bakanov/astropy,tbabej/astropy,StuartLittlefair/astropy,kelle/astropy,MSeifert04/...
--- +++ @@ -29,3 +29,14 @@ c.distance = Distance(2, unit=u.kpc) assert c.x == oldx * 2 + +def test_distance_from_quantity(): + from .. import RA, Dec, ICRSCoordinates, Distance + + ra = RA("4:08:15.162342", unit=u.hour) + dec = Dec("-41:08:15.162342", unit=u.degree) + c = ICRSCoordinates(ra, d...
1975aeb06a85d8983a3815ffd89076af66d61561
payments/urls.py
payments/urls.py
from django.conf.urls import patterns, url try: from account.decorators import login_required except ImportError: from django.contrib.auth.decorators import login_required from .views import ( CancelView, ChangeCardView, ChangePlanView, HistoryView, SubscribeView ) urlpatterns = patterns...
from django.conf.urls import patterns, url try: from account.decorators import login_required except ImportError: from django.contrib.auth.decorators import login_required from .views import ( CancelView, ChangeCardView, ChangePlanView, HistoryView, SubscribeView, webhook, subscrib...
Use imported views instead of lazy import
Use imported views instead of lazy import
Python
mit
pinax/django-stripe-payments
--- +++ @@ -10,17 +10,22 @@ ChangeCardView, ChangePlanView, HistoryView, - SubscribeView + SubscribeView, + webhook, + subscribe, + change_card, + change_plan, + cancel ) urlpatterns = patterns( - "payments.views", - url(r"^webhook/$", "webhook", name="payments_webhook"...
d85a288cbacf6bc31b1d544dd269d392aed4a1ec
openquake/hazardlib/general.py
openquake/hazardlib/general.py
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2014, GEM Foundation. # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, ...
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2014, GEM Foundation. # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, ...
Add stderr redirect to git_suffix to get more clean messages
Add stderr redirect to git_suffix to get more clean messages
Python
agpl-3.0
larsbutler/oq-hazardlib,rcgee/oq-hazardlib,gem/oq-engine,silviacanessa/oq-hazardlib,rcgee/oq-hazardlib,gem/oq-hazardlib,gem/oq-engine,g-weatherill/oq-hazardlib,larsbutler/oq-hazardlib,silviacanessa/oq-hazardlib,silviacanessa/oq-hazardlib,silviacanessa/oq-hazardlib,vup1120/oq-hazardlib,g-weatherill/oq-hazardlib,g-weathe...
--- +++ @@ -27,7 +27,7 @@ """ try: gh = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], - cwd=os.path.dirname(fname)).strip() + stderr=open(os.devnull, 'w'), cwd=os.path.dirname(fname)).strip() gh = "-git" + gh if gh else '' return gh ...
32508dea4ef00fb54919c0260b7ba2902835faf5
prepareupload.py
prepareupload.py
import sys import olrcdb import os # Globals COUNT = 0 class FileParser(object): '''Object used to parse through a directory for all it's files. Collects the paths of all the files and stores a record of these in a new table in the database. The Schema of the database is: NewTable(path, uploade...
import sys import olrcdb import os # Globals COUNT = 0 class FileParser(object): '''Object used to parse through a directory for all it's files. Collects the paths of all the files and stores a record of these in a new table in the database. The Schema of the database is: NewTable(path, uploade...
Print messages for prepare upload.
Print messages for prepare upload.
Python
bsd-3-clause
OLRC/SwiftBulkUploader,cudevmaxwell/SwiftBulkUploader
--- +++ @@ -37,6 +37,9 @@ if os.path.isfile(file_path): connect.insert_path(file_path, table_name) COUNT += 1 + + sys.stdout.flush() + sys.stdout.write("\r{0} parsed. \n".format(COUNT)) else: prepare_upload(connect, file_path, table_name) ...
66b20aa7fbd322a051ab7ae26ecd8c46f7605763
ptoolbox/tags.py
ptoolbox/tags.py
# -*- coding: utf-8 -*- from datetime import datetime TAG_WIDTH = 'EXIF ExifImageWidth' TAG_HEIGHT = 'EXIF ExifImageLength' TAG_DATETIME = 'Image DateTime' TAG_ORIENTATION = 'Image Orientation' # XXX: this is a terrible way to retrieve the orientations. Exifread regretfully does not # get back raw EXIF orientations,...
# -*- coding: utf-8 -*- from datetime import datetime TAG_WIDTH = 'EXIF ExifImageWidth' TAG_HEIGHT = 'EXIF ExifImageLength' TAG_DATETIME = 'Image DateTime' def parse_time(tags): tag = tags.get(TAG_DATETIME, None) if not tag: raise KeyError(TAG_DATETIME) return datetime.strptime(str(tag), "%Y:%m:%...
Remove orientation tag parsing, not needed.
Remove orientation tag parsing, not needed.
Python
mit
vperron/picasa-toolbox
--- +++ @@ -5,21 +5,6 @@ TAG_WIDTH = 'EXIF ExifImageWidth' TAG_HEIGHT = 'EXIF ExifImageLength' TAG_DATETIME = 'Image DateTime' -TAG_ORIENTATION = 'Image Orientation' - -# XXX: this is a terrible way to retrieve the orientations. Exifread regretfully does not -# get back raw EXIF orientations, and no other library ...
ad3a495e38e22f3759a724a23ce0492cd42e0bc4
qual/calendar.py
qual/calendar.py
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar...
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar...
Use from_date to construct from year, month, day.
Use from_date to construct from year, month, day.
Python
apache-2.0
jwg4/calexicon,jwg4/qual
--- +++ @@ -24,5 +24,5 @@ def date(self, year, month, day): d = date(year, month, day) d = d + timedelta(days=10) - return DateWithCalendar(JulianCalendar, d) + return self.from_date(d)
e5a392c5c0e5a3c1e71764a422cbea16d81ba3a6
app.py
app.py
from flask import Flask, request, jsonify, send_from_directory import os import uuid app = Flask(__name__) UPLOAD_FOLDER = "uploads/" @app.route("/") def index(): return send_from_directory('', 'index.html') @app.route("/sounds") def get_sounds_list(): if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPL...
from flask import Flask, request, jsonify, send_from_directory import os import uuid app = Flask(__name__) UPLOAD_FOLDER = "uploads/" @app.route("/") def index(): return send_from_directory('', 'index.html') @app.route("/sounds") def get_sounds_list(): if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPL...
Remove '.wav' addition to all files uploaded
Remove '.wav' addition to all files uploaded
Python
mit
spb201/turbulent-octo-rutabaga-api,spb201/turbulent-octo-rutabaga-api,spb201/turbulent-octo-rutabaga-api
--- +++ @@ -26,7 +26,7 @@ if file: if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) - filename = uuid.uuid4().__str__() + ".wav" + filename = uuid.uuid4().__str__() file.save(os.path.join(UPLOAD_FOLDER, filename)) return filename + "\n"
4303a5cb38f2252dfe09a0ca21320d4bd67bd966
byceps/blueprints/user/current/forms.py
byceps/blueprints/user/current/forms.py
""" byceps.blueprints.user.current.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from wtforms import DateField, StringField from wtforms.validators import InputRequired, Length, Optional from ....util.l10n import LocalizedFo...
""" byceps.blueprints.user.current.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from wtforms import DateField, StringField from wtforms.fields.html5 import TelField from wtforms.validators import InputRequired, Length, Optio...
Use `<input type="tel">` for phone number field
Use `<input type="tel">` for phone number field
Python
bsd-3-clause
m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
--- +++ @@ -7,6 +7,7 @@ """ from wtforms import DateField, StringField +from wtforms.fields.html5 import TelField from wtforms.validators import InputRequired, Length, Optional from ....util.l10n import LocalizedForm @@ -22,4 +23,4 @@ zip_code = StringField('PLZ', [Optional()]) city = StringField('S...
333aa4499e0118eebaa6ce72e97aef5f9e701865
skyfield/tests/test_magnitudes.py
skyfield/tests/test_magnitudes.py
from skyfield.api import load from skyfield.magnitudelib import planetary_magnitude def test_magnitudes(): ts = load.timescale() #t = ts.utc(1995, 5, 22) # Rings edge-on from Earth. t = ts.utc(2021, 10, 4) eph = load('de421.bsp') names = [ 'mercury', 'venus', 'mars', 'jupiter barycenter', ...
from skyfield.api import load from skyfield.magnitudelib import planetary_magnitude def test_magnitudes(): ts = load.timescale() #t = ts.utc(1995, 5, 22) # Rings edge-on from Earth. t = ts.utc(2021, 10, 4) eph = load('de421.bsp') names = [ 'mercury', 'venus', 'mars', 'jupiter barycenter', ...
Fix magnitudes test for Python 2.7 in CI
Fix magnitudes test for Python 2.7 in CI
Python
mit
skyfielders/python-skyfield,skyfielders/python-skyfield
--- +++ @@ -13,6 +13,6 @@ e = eph['earth'].at(t) positions = [e.observe(eph[name]) for name in names] magnitudes = [planetary_magnitude(position) for position in positions] - assert [f'{m:.3f}' for m in magnitudes] == [ + assert ['%.3f' % m for m in magnitudes] == [ '2.393', '-4.278', '1...
71c9235a7e48882fc8c1393e9527fea4531c536c
filter_plugins/fap.py
filter_plugins/fap.py
#!/usr/bin/python import ipaddress def site_code(ipv4): # Verify IP address _ = ipaddress.ip_address(ipv4) segments = ipv4.split(".") return int(segments[1]) class FilterModule(object): def filters(self): return {"site_code": site_code}
#!/usr/bin/python import ipaddress def site_code(ipv4): # Verify IP address _ = ipaddress.ip_address(ipv4) segments = ipv4.split(".") return int(segments[1]) # rest:https://restic.storage.tjoda.fap.no/rpi1.ldn.fap.no # rclone:Jotta:storage.tjoda.fap.no # /Volumes/storage/restic/kramacbook def res...
Add really hacky way to reformat restic repos
Add really hacky way to reformat restic repos
Python
mit
kradalby/plays,kradalby/plays
--- +++ @@ -12,6 +12,33 @@ return int(segments[1]) +# rest:https://restic.storage.tjoda.fap.no/rpi1.ldn.fap.no +# rclone:Jotta:storage.tjoda.fap.no +# /Volumes/storage/restic/kramacbook +def restic_repo_friendly_name(repo: str) -> str: + if "https://" in repo: + repo = repo.replace("https://", "") ...
478bdba2edf9654fc90e1a50bad60cd5b89791f9
ueberwachungspaket/decorators.py
ueberwachungspaket/decorators.py
from urllib.parse import urlparse, urlunparse from functools import wraps from flask import abort, current_app, request from twilio.twiml import Response from twilio.util import RequestValidator from config import * def twilio_request(f): @wraps(f) def decorated_function(*args, **kwargs): validator = R...
from urllib.parse import urlparse, urlunparse from functools import wraps from flask import abort, current_app, request from twilio.twiml.voice_response import VoiceResponse from twilio.request_validator import RequestValidator from config import * def twilio_request(f): @wraps(f) def decorated_function(*args,...
Make it compile with recent version of twilio
Make it compile with recent version of twilio
Python
mit
AKVorrat/ueberwachungspaket.at,AKVorrat/ueberwachungspaket.at,AKVorrat/ueberwachungspaket.at
--- +++ @@ -1,8 +1,8 @@ from urllib.parse import urlparse, urlunparse from functools import wraps from flask import abort, current_app, request -from twilio.twiml import Response -from twilio.util import RequestValidator +from twilio.twiml.voice_response import VoiceResponse +from twilio.request_validator import R...
e9ca748641e04f63944521ef0bc3090960f77cab
deployment/datapusher_settings.py
deployment/datapusher_settings.py
import uuid DEBUG = False TESTING = False SECRET_KEY = str(uuid.uuid4()) USERNAME = str(uuid.uuid4()) PASSWORD = str(uuid.uuid4()) NAME = 'datapusher' # database SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/job_store.db' # webserver host and port HOST = '0.0.0.0' PORT = 8800 # logging #FROM_EMAIL = 'server-error@e...
import os import uuid DEBUG = False TESTING = False SECRET_KEY = str(uuid.uuid4()) USERNAME = str(uuid.uuid4()) PASSWORD = str(uuid.uuid4()) NAME = 'datapusher' # Webserver host and port HOST = os.environ.get('DATAPUSHER_HOST', '0.0.0.0') PORT = os.environ.get('DATAPUSHER_PORT', 8800) # Database SQLALCHEMY_DATABA...
Add missing config options, allow to define via env vars
Add missing config options, allow to define via env vars
Python
agpl-3.0
ckan/datapusher
--- +++ @@ -1,3 +1,4 @@ +import os import uuid DEBUG = False @@ -8,19 +9,24 @@ NAME = 'datapusher' -# database +# Webserver host and port -SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/job_store.db' +HOST = os.environ.get('DATAPUSHER_HOST', '0.0.0.0') +PORT = os.environ.get('DATAPUSHER_PORT', 8800) -# webser...
417415283d87654b066c11d807516d3cd5b5bf3d
tests/test_probabilistic_interleave_speed.py
tests/test_probabilistic_interleave_speed.py
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(100, 200)) for i in range(1000): method = il....
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(50, 150)) r3 = list(range(100, 200)) r4 = list(ra...
Add tests for measuring the speed of probabilistic interleaving
Add tests for measuring the speed of probabilistic interleaving
Python
mit
mpkato/interleaving
--- +++ @@ -8,8 +8,10 @@ def test_interleave(self): r1 = list(range(100)) - r2 = list(range(100, 200)) + r2 = list(range(50, 150)) + r3 = list(range(100, 200)) + r4 = list(range(150, 250)) for i in range(1000): - method = il.Probabilistic([r1, r2]) + ...
b8839af335757f58fa71916ff3394f5a6806165d
user_management/api/tests/test_exceptions.py
user_management/api/tests/test_exceptions.py
from django.test import TestCase from rest_framework.status import HTTP_400_BAD_REQUEST from ..exceptions import InvalidExpiredToken class InvalidExpiredTokenTest(TestCase): """Assert `InvalidExpiredToken` behaves as expected.""" def test_raise(self): """Assert `InvalidExpiredToken` can be raised."""...
from django.test import TestCase from rest_framework.status import HTTP_400_BAD_REQUEST from ..exceptions import InvalidExpiredToken class InvalidExpiredTokenTest(TestCase): """Assert `InvalidExpiredToken` behaves as expected.""" def test_raise(self): """Assert `InvalidExpiredToken` can be raised."""...
Use more explicit name for error
Use more explicit name for error
Python
bsd-2-clause
incuna/django-user-management,incuna/django-user-management
--- +++ @@ -8,8 +8,8 @@ """Assert `InvalidExpiredToken` behaves as expected.""" def test_raise(self): """Assert `InvalidExpiredToken` can be raised.""" - with self.assertRaises(InvalidExpiredToken) as e: + with self.assertRaises(InvalidExpiredToken) as error: raise Invali...
287dc6f7a7f0321fec8e35d1dc08f07a3b12f63b
test/342-winter-sports-pistes.py
test/342-winter-sports-pistes.py
# http://www.openstreetmap.org/way/313466665 assert_has_feature( 15, 5467, 12531, 'roads', { 'kind': 'piste', 'piste_type': 'downhill', 'piste_difficulty': 'easy', 'id': 313466665 }) # http://www.openstreetmap.org/way/313466720 assert_has_feature( 15, 5467, 12531, 'roads', { 'kind': '...
# http://www.openstreetmap.org/way/313466665 assert_has_feature( 15, 5467, 12531, 'roads', { 'kind': 'piste', 'piste_type': 'downhill', 'piste_difficulty': 'easy', 'id': 313466665 }) # http://www.openstreetmap.org/way/313466720 assert_has_feature( 15, 5467, 12531, 'roads', { 'kind': '...
Add piste test to catch dev issue
Add piste test to catch dev issue
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
--- +++ @@ -13,3 +13,11 @@ 'piste_type': 'downhill', 'piste_difficulty': 'expert', 'id': 313466720 }) + +# Way: 49'er (313466490) http://www.openstreetmap.org/way/313466490 +assert_has_feature( + 16, 10939, 25061, 'roads', + { 'kind': 'piste', + 'piste_type': 'downhill', + 'piste_...
2627a89fb56e8fc6ae0a4704333e9ed0012048bd
vitrage/tests/functional/datasources/base.py
vitrage/tests/functional/datasources/base.py
# Copyright 2016 - Nokia # # 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, sof...
# Copyright 2016 - Nokia # # 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, sof...
Use assertGreater(len(x), y) instead of assertTrue(len(x) > y)
Use assertGreater(len(x), y) instead of assertTrue(len(x) > y) assertGreater provides a nicer error message if it fails. Change-Id: Ibfe6a85760a766d310d75bc484e933e96cb0c02f
Python
apache-2.0
openstack/vitrage,openstack/vitrage,openstack/vitrage
--- +++ @@ -24,6 +24,6 @@ VProps.CATEGORY: EntityCategory.RESOURCE, VProps.TYPE: type_ }) - self.assertTrue(len(entity_vertices) > 0) + self.assertGreater(len(entity_vertices), 0) return entity_vertices[0][VProps.ID]
3eb796eca4d3dbfd5db9af52166f96cb34654dc8
networking_nec/plugins/necnwa/l3/db_api.py
networking_nec/plugins/necnwa/l3/db_api.py
# Copyright 2015-2016 NEC Corporation. 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 requ...
# Copyright 2015-2016 NEC Corporation. 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 requ...
Move return to inside try
Move return to inside try It is easy to understand if 'return' statement is moved inside try clause and there is no need to initialize a value. Follow-up minor fixes for review 276086 Change-Id: I3968e1702c0129ae02517e817da189ca137e7ab4
Python
apache-2.0
openstack/networking-nec,openstack/networking-nec,stackforge/networking-nec,stackforge/networking-nec
--- +++ @@ -21,13 +21,11 @@ def get_tenant_id_by_router(session, router_id): - rt_tid = None with session.begin(subtransactions=True): try: router = session.query(l3_db.Router).filter_by(id=router_id).one() rt_tid = router.tenant_id + LOG.debug("rt_tid=%s", r...
40653d829efcc0461d0da9472111aa89b41e08f1
hasjob/views/login.py
hasjob/views/login.py
# -*- coding: utf-8 -*- from flask import Response, redirect, flash from flask.ext.lastuser.sqlalchemy import UserManager from coaster.views import get_next_url from hasjob import app, lastuser from hasjob.models import db, User lastuser.init_usermanager(UserManager(db, User)) @app.route('/login') @lastuser.login...
# -*- coding: utf-8 -*- from flask import Response, redirect, flash from flask.ext.lastuser.sqlalchemy import UserManager from coaster.views import get_next_url from hasjob import app, lastuser from hasjob.models import db, User lastuser.init_usermanager(UserManager(db, User)) @app.route('/login') @lastuser.login...
Support for Lastuser push notifications.
Support for Lastuser push notifications.
Python
agpl-3.0
qitianchan/hasjob,qitianchan/hasjob,hasgeek/hasjob,hasgeek/hasjob,nhannv/hasjob,hasgeek/hasjob,sindhus/hasjob,sindhus/hasjob,nhannv/hasjob,sindhus/hasjob,qitianchan/hasjob,sindhus/hasjob,qitianchan/hasjob,ashwin01/hasjob,ashwin01/hasjob,hasgeek/hasjob,ashwin01/hasjob,ashwin01/hasjob,nhannv/hasjob,nhannv/hasjob,qitianch...
--- +++ @@ -32,6 +32,13 @@ return redirect(get_next_url()) +@app.route('/login/notify') +@lastuser.notification_handler +def lastusernotify(user): + # Save the user object + db.session.commit() + + @lastuser.auth_error_handler def lastuser_error(error, error_description=None, error_uri=None): if...
a05403c2cfe99926b650024e8de08942eda837c6
indexdigest/linters/linter_0034_missing_primary_index.py
indexdigest/linters/linter_0034_missing_primary_index.py
""" This linter reports missing primary / unique index """ from collections import OrderedDict from indexdigest.utils import LinterEntry def check_missing_primary_index(database): """ :type database indexdigest.database.Database :rtype: list[LinterEntry] """ for table in database.get_tables(): ...
""" This linter reports missing primary / unique index """ from collections import OrderedDict from indexdigest.utils import LinterEntry def check_missing_primary_index(database): """ :type database indexdigest.database.Database :rtype: list[LinterEntry] """ for table in database.get_tables(): ...
Use list comprehension as pylint suggests
Use list comprehension as pylint suggests
Python
mit
macbre/index-digest,macbre/index-digest
--- +++ @@ -15,10 +15,10 @@ # list non-primary (and non-unique) indices only # @see https://bugs.mysql.com/bug.php?id=76252 # @see https://github.com/Wikia/app/pull/9863 - indices = list(filter( - lambda index: index.is_primary or index.is_unique, - database.get...
dce404d65f1f2b8f297cfa066210b885621d38d0
graphene/commands/exit_command.py
graphene/commands/exit_command.py
from graphene.commands.command import Command class ExitCommand(Command): def __init__(self): pass
from graphene.commands.command import Command class ExitCommand(Command): def __init__(self): pass def execute(self, storage_manager, timer=None): # This should never be used anyway. pass
Fix EXIT command to have execute method for abstract class
Fix EXIT command to have execute method for abstract class
Python
apache-2.0
PHB-CS123/graphene,PHB-CS123/graphene,PHB-CS123/graphene
--- +++ @@ -3,3 +3,7 @@ class ExitCommand(Command): def __init__(self): pass + + def execute(self, storage_manager, timer=None): + # This should never be used anyway. + pass
baea090319eafa6c6cfac397c6b0be4d7ca34342
rplugin/python3/deoplete/sources/LanguageClientSource.py
rplugin/python3/deoplete/sources/LanguageClientSource.py
from .base import Base CompleteOutputs = "g:LanguageClient_omniCompleteResults" class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = "LanguageClient" self.mark = "[LC]" self.rank = 1000 self.min_pattern_length = 1 self.filetypes = vim.ev...
from .base import Base COMPLETE_OUTPUTS = "g:LanguageClient_omniCompleteResults" class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = "LanguageClient" self.mark = "[LC]" self.rank = 1000 self.min_pattern_length = 1 self.filetypes = vim.e...
Fix deoplete variable naming and conditional logic
Fix deoplete variable naming and conditional logic * Module-level variables should be CAPITALIZED. * if len(my_list) != 0 can be more-safely changed to "if my_list" * An empty list if falsey, a non-empty list is truthy. We're also safe from unexpected "None" values now. * Cleans up unnecessary comments that someho...
Python
mit
autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/L...
--- +++ @@ -1,7 +1,7 @@ from .base import Base -CompleteOutputs = "g:LanguageClient_omniCompleteResults" +COMPLETE_OUTPUTS = "g:LanguageClient_omniCompleteResults" class Source(Base): @@ -18,8 +18,8 @@ def gather_candidates(self, context): if context["is_async"]: - outputs = self....
0850a64ac3758b935a99730733a31710e5178ee7
readthedocs/settings/postgres.py
readthedocs/settings/postgres.py
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'docs', 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', 'HOST': '10.177.73.97', 'PORT': '', } } DEBUG = False TEMPLATE_DE...
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'docs', 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', 'HOST': '10.177.73.97', 'PORT': '', } } DEBUG = False TEMPLATE_DE...
Remove this haystack setting as well.
Remove this haystack setting as well.
Python
mit
wijerasa/readthedocs.org,GovReady/readthedocs.org,kenwang76/readthedocs.org,jerel/readthedocs.org,sid-kap/readthedocs.org,ojii/readthedocs.org,asampat3090/readthedocs.org,gjtorikian/readthedocs.org,attakei/readthedocs-oauth,tddv/readthedocs.org,espdev/readthedocs.org,attakei/readthedocs-oauth,techtonik/readthedocs.org,...
--- +++ @@ -20,7 +20,7 @@ CACHE_BACKEND = 'memcached://localhost:11211/' SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" -HAYSTACK_SEARCH_ENGINE = 'solr' +#HAYSTACK_SEARCH_ENGINE = 'solr' HAYSTACK_SOLR_URL = 'http://odin:8983/solr' SLUMBER_API_HOST = 'http://readthedocs.org'
c7578896036bc07bb1edc2d79f699968c25ca89e
bika/lims/upgrade/to1117.py
bika/lims/upgrade/to1117.py
from Acquisition import aq_inner from Acquisition import aq_parent from Products.CMFCore.utils import getToolByName def upgrade(tool): """ Enable portlets for key=/ (re-import portlets.xml): issue #695 """ portal = aq_parent(aq_inner(tool)) setup = portal.portal_setup setup.runImportStepFromProfi...
from Acquisition import aq_inner from Acquisition import aq_parent from Products.CMFCore.utils import getToolByName def upgrade(tool): """ Enable portlets for key=/ (re-import portlets.xml): issue #695 """ portal = aq_parent(aq_inner(tool)) setup = portal.portal_setup setup.runImportStepFromProfi...
Upgrade 1117 - add run_dependencies=False
Upgrade 1117 - add run_dependencies=False Somehow re-importing the 'portlets' step, causes a beforeDelete handler to fail a HoldingReference check.
Python
agpl-3.0
labsanmartin/Bika-LIMS,veroc/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS,anneline/Bika-LIMS,rockfruit/bika.lims,rockfruit/bika.lims,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS,DeBortoliWines/Bika-LIMS,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS
--- +++ @@ -9,4 +9,5 @@ portal = aq_parent(aq_inner(tool)) setup = portal.portal_setup - setup.runImportStepFromProfile('profile-bika.lims:default', 'portlets') + setup.runImportStepFromProfile('profile-bika.lims:default', 'portlets', + run_dependencies=False)
7cde5e713ace2b0a1d9cdef01ac912f3a53814cd
run_scripts/build_phylogenies.py
run_scripts/build_phylogenies.py
#!/usr/bin/env python # Automatically generate phylogenies from a settings file # specifying input fasta and genomes import sys import dendrogenous as dg import dendrogenous.settings import dendrogenous.utils import dendrogenous.core import multiprocessing def main(settings_file): settings = dg.settings.S...
#!/usr/bin/env python # Automatically generate phylogenies from a settings file # specifying input fasta and genomes import sys import dendrogenous as dg import dendrogenous.settings import dendrogenous.utils import dendrogenous.core import joblib import pickle #multiprocessing def main(settings_file): settings =...
Change run script to use worker pool
Change run script to use worker pool
Python
bsd-3-clause
fmaguire/dendrogenous
--- +++ @@ -6,27 +6,32 @@ import dendrogenous.settings import dendrogenous.utils import dendrogenous.core -import multiprocessing +import joblib +import pickle +#multiprocessing def main(settings_file): - settings = dg.settings.Settings(settings_file) + settings = dg.settings.Settings(settings_f...
a11c839988b71e9f769cb5ba856474205b7aeefb
jsonschema/tests/fuzz_validate.py
jsonschema/tests/fuzz_validate.py
""" Fuzzing setup for OSS-Fuzz. See https://github.com/google/oss-fuzz/tree/master/projects/jsonschema for the other half of the setup here. """ import sys from hypothesis import given, strategies import jsonschema PRIM = strategies.one_of( strategies.booleans(), strategies.integers(), strategies.floats...
""" Fuzzing setup for OSS-Fuzz. See https://github.com/google/oss-fuzz/tree/master/projects/jsonschema for the other half of the setup here. """ import sys from hypothesis import given, strategies import jsonschema PRIM = strategies.one_of( strategies.booleans(), strategies.integers(), strategies.floats...
Fix fuzzer to include instrumentation
Fix fuzzer to include instrumentation
Python
mit
python-jsonschema/jsonschema
--- +++ @@ -36,6 +36,7 @@ def main(): + atheris.instrument_all() atheris.Setup( sys.argv, test_schemas.hypothesis.fuzz_one_input,
da843b10a92cd4f2f95f18f78f9ea03dcd9a67d5
packages/Python/lldbsuite/support/seven.py
packages/Python/lldbsuite/support/seven.py
import six if six.PY2: import commands get_command_output = commands.getoutput get_command_status_output = commands.getstatusoutput cmp_ = cmp else: def get_command_status_output(command): try: import subprocess return ( 0, subprocess...
import six if six.PY2: import commands get_command_output = commands.getoutput get_command_status_output = commands.getstatusoutput cmp_ = cmp else: def get_command_status_output(command): try: import subprocess return ( 0, subprocess...
Remove trailing characters from command output.
[testsuite] Remove trailing characters from command output. When running the test suite on macOS with Python 3 we noticed a difference in behavior between Python 2 and Python 3 for seven.get_command_output. The output contained a newline with Python 3, but not for Python 2. This resulted in an invalid SDK path passed ...
Python
apache-2.0
apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb
--- +++ @@ -15,7 +15,7 @@ subprocess.check_output( command, shell=True, - universal_newlines=True)) + universal_newlines=True).rstrip()) except subprocess.CalledProcessError as e: return (e.returncod...
224d9f4e243f6645e88b32ad7342a55128f19eeb
html5lib/__init__.py
html5lib/__init__.py
""" HTML parsing library based on the WHATWG "HTML5" specification. The parser is designed to be compatible with existing HTML found in the wild and implements well-defined error recovery that is largely compatible with modern desktop web browsers. Example usage: import html5lib f = open("my_document.html") tree = ht...
""" HTML parsing library based on the WHATWG "HTML5" specification. The parser is designed to be compatible with existing HTML found in the wild and implements well-defined error recovery that is largely compatible with modern desktop web browsers. Example usage:: import html5lib f = open("my_document.html") ...
Fix formatting of docstring example
Fix formatting of docstring example It runs together in the built HTML.
Python
mit
html5lib/html5lib-python,html5lib/html5lib-python,html5lib/html5lib-python
--- +++ @@ -4,11 +4,11 @@ HTML found in the wild and implements well-defined error recovery that is largely compatible with modern desktop web browsers. -Example usage: +Example usage:: -import html5lib -f = open("my_document.html") -tree = html5lib.parse(f) + import html5lib + f = open("my_document.html"...
f748facb9edd35ca6c61be336cad3109cafbbc89
tests/test_authentication.py
tests/test_authentication.py
import unittest from flask import json from api import create_app, db class AuthenticationTestCase(unittest.TestCase): def setUp(self): self.app = create_app(config_name='TestingEnv') self.client = self.app.test_client() # Binds the app to current context with self.app.app_context...
import unittest from flask import json from api import db from api.BucketListAPI import app from instance.config import application_config class AuthenticationTestCase(unittest.TestCase): def setUp(self): app.config.from_object(application_config['TestingEnv']) self.client = app.test_client() ...
Add test for index route
Add test for index route
Python
mit
patlub/BucketListAPI,patlub/BucketListAPI
--- +++ @@ -1,28 +1,32 @@ import unittest from flask import json -from api import create_app, db +from api import db +from api.BucketListAPI import app +from instance.config import application_config class AuthenticationTestCase(unittest.TestCase): def setUp(self): - self.app = create_app(config_na...
1bc9bf9b3bab521c4a144e00d24477afae0eb0df
examples/basic_datalogger.py
examples/basic_datalogger.py
from pymoku import Moku from pymoku.instruments import * import time, logging logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.DEBUG) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku('192.168.1.117') i = m.discover...
from pymoku import Moku from pymoku.instruments import * import time, logging logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.DEBUG) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku('192.168.1.104') i = m.discover...
Fix the datalogger example script to use roll mode and a high decimation
Fix the datalogger example script to use roll mode and a high decimation
Python
mit
liquidinstruments/pymoku,benizl/pymoku
--- +++ @@ -6,7 +6,7 @@ logging.getLogger('pymoku').setLevel(logging.DEBUG) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP -m = Moku('192.168.1.117') +m = Moku('192.168.1.104') i = m.discover_instrument() @@ -18,7 +18,9 @@ print "Attached to existing Oscilloscope" i.set_defaults() ...
644896c856b1e6ad20a3790234439b8ac8403917
examples/dft/12-camb3lyp.py
examples/dft/12-camb3lyp.py
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # ''' The default XC functional library (libxc) supports the energy and nuclear gradients for range separated functionals. Nuclear Hessian and TDDFT gradients need xcfun library. See also example 32-xcfun_as_default.py for how to set xcfun library a...
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # '''Density functional calculations can be run with either the default backend library, libxc, or an alternative library, xcfun. See also example 32-xcfun_as_default.py for how to set xcfun as the default XC functional library. ''' from pyscf impor...
Update the camb3lyp example to libxc 5 series
Update the camb3lyp example to libxc 5 series
Python
apache-2.0
sunqm/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf
--- +++ @@ -3,36 +3,42 @@ # Author: Qiming Sun <osirpt.sun@gmail.com> # -''' -The default XC functional library (libxc) supports the energy and nuclear -gradients for range separated functionals. Nuclear Hessian and TDDFT gradients -need xcfun library. See also example 32-xcfun_as_default.py for how to set -xcf...
bf007267246bd317dc3ccad9f5cf8a9f452b3e0b
firecares/utils/__init__.py
firecares/utils/__init__.py
from django.core.files.storage import get_storage_class from storages.backends.s3boto import S3BotoStorage from PIL import Image def convert_png_to_jpg(img): """ Converts a png to a jpg. :param img: Absolute path to the image. :returns: the filename """ im = Image.open(img) bg = Image.new(...
from django.core.files.storage import get_storage_class from storages.backends.s3boto import S3BotoStorage from PIL import Image class CachedS3BotoStorage(S3BotoStorage): """ S3 storage backend that saves the files locally, too. """ def __init__(self, *args, **kwargs): super(CachedS3BotoStorag...
Remove the unused convert_png_to_jpg method.
Remove the unused convert_png_to_jpg method.
Python
mit
FireCARES/firecares,FireCARES/firecares,meilinger/firecares,meilinger/firecares,FireCARES/firecares,meilinger/firecares,HunterConnelly/firecares,HunterConnelly/firecares,FireCARES/firecares,HunterConnelly/firecares,FireCARES/firecares,meilinger/firecares,HunterConnelly/firecares
--- +++ @@ -1,20 +1,6 @@ from django.core.files.storage import get_storage_class from storages.backends.s3boto import S3BotoStorage from PIL import Image - - -def convert_png_to_jpg(img): - """ - Converts a png to a jpg. - :param img: Absolute path to the image. - :returns: the filename - """ - i...
49f5802a02a550cc8cee3be417426a83c31de5c9
Source/Git/Experiments/git_log.py
Source/Git/Experiments/git_log.py
#!/usr/bin/python3 import sys import git r = git.Repo( sys.argv[1] ) def printTree( tree, indent=0 ): prefix = ' '*indent print( prefix, '-' * 16 ) print( prefix, 'Tree path %s' % (tree.path,) ) for blob in tree: print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) ) for chi...
#!/usr/bin/python3 import sys import git r = git.Repo( sys.argv[1] ) def printTree( tree, indent=0 ): prefix = ' '*indent print( prefix, '-' * 16 ) print( prefix, 'Tree path %s' % (tree.path,) ) for blob in tree: print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) ) for chi...
Exit the loop early when experimenting.
Exit the loop early when experimenting.
Python
apache-2.0
barry-scott/scm-workbench,barry-scott/scm-workbench,barry-scott/scm-workbench
--- +++ @@ -42,3 +42,6 @@ tree = commit.tree printTree( tree ) + + if index > 1: + break
4e6ec9cc5b052341094723433f58a21020fa82f0
tools/scheduler/scheduler/core.py
tools/scheduler/scheduler/core.py
# scheduler.core: Data structures for managing K3 jobs. class Job: def __init__(self, roles): self.roles = roles self.tasks = None self.status = None class Role: def __init__(self, peers = 0, variables {}, inputs {}, hostmask = r"*"): self.peers = peers self.variables = variables, self.inp...
# scheduler.core: Data structures for managing K3 jobs. class Job: def __init__(self, roles, binary_url): self.roles = roles self.binary_url = binary_url self.tasks = None self.status = None class Role: def __init__(self, peers = 0, variables {}, inputs {}, hostmask = r"*"): self.peers = peers...
Add binary_url member to Job.
Add binary_url member to Job.
Python
apache-2.0
DaMSL/K3,DaMSL/K3,yliu120/K3
--- +++ @@ -1,8 +1,9 @@ # scheduler.core: Data structures for managing K3 jobs. class Job: - def __init__(self, roles): + def __init__(self, roles, binary_url): self.roles = roles + self.binary_url = binary_url self.tasks = None self.status = None
0c266606ec10a8814ce749925a727ea57dd32aeb
test/343-winter-sports-resorts.py
test/343-winter-sports-resorts.py
assert_has_feature( 15, 5467, 12531, 'landuse', { 'kind': 'winter_sports', 'sort_key': 33 })
assert_has_feature( 15, 5467, 12531, 'landuse', { 'kind': 'winter_sports', 'sort_key': 36 })
Fix other failure - assuming that the change in sort key value for winter sports was intentional.
Fix other failure - assuming that the change in sort key value for winter sports was intentional.
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
--- +++ @@ -1,4 +1,4 @@ assert_has_feature( 15, 5467, 12531, 'landuse', { 'kind': 'winter_sports', - 'sort_key': 33 }) + 'sort_key': 36 })
40d204c996e41a030dac240c99c66a25f8f8586e
scripts/generate-bcrypt-hashed-password.py
scripts/generate-bcrypt-hashed-password.py
#!/usr/bin/env python """ A script to return a bcrypt hash of a password. It's intended use is for creating known passwords to replace user passwords in cleaned up databases. Cost-factor is the log2 number of rounds of hashing to use for the salt. It's worth researching how many rounds you need for your use context, ...
#!/usr/bin/env python """ A script to return a bcrypt hash of a password. It's intended use is for creating known passwords to replace user passwords in cleaned up databases. Cost-factor is the log2 number of rounds of hashing to use for the salt. It's worth researching how many rounds you need for your use context, ...
Fix "string argument without an encoding" python3 error in bcrypt script
Fix "string argument without an encoding" python3 error in bcrypt script generate-bcrypt-hashed-password raises an error on python3 since `bytes` is called without an encoding argument. Replacing it with `.encode` should fix the problem.
Python
mit
alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws
--- +++ @@ -16,7 +16,7 @@ def hash_password(password, cost_factor): - return bcrypt.hashpw(bytes(password), bcrypt.gensalt(cost_factor)).decode('utf-8') + return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(cost_factor)).decode('utf-8') if __name__ == "__main__": arguments = docopt(__doc_...
4037036de79f6503921bbd426bb5352f2f86f12b
plyer/platforms/android/camera.py
plyer/platforms/android/camera.py
from os import unlink from jnius import autoclass, cast from plyer.facades import Camera from plyer.platforms.android import activity Intent = autoclass('android.content.Intent') PythonActivity = autoclass('org.renpy.android.PythonActivity') MediaStore = autoclass('android.provider.MediaStore') Uri = autoclass('androi...
import android import android.activity from os import unlink from jnius import autoclass, cast from plyer.facades import Camera from plyer.platforms.android import activity Intent = autoclass('android.content.Intent') PythonActivity = autoclass('org.renpy.android.PythonActivity') MediaStore = autoclass('android.provi...
Revert "Activity was imported twice"
Revert "Activity was imported twice" This reverts commit a0600929774c1e90c7dc43043ff87b5ea84213b4.
Python
mit
johnbolia/plyer,johnbolia/plyer,kived/plyer,kivy/plyer,cleett/plyer,kived/plyer,kivy/plyer,kivy/plyer,KeyWeeUsr/plyer,KeyWeeUsr/plyer,cleett/plyer,kostyll/plyer,KeyWeeUsr/plyer,kostyll/plyer
--- +++ @@ -1,3 +1,6 @@ + +import android +import android.activity from os import unlink from jnius import autoclass, cast from plyer.facades import Camera @@ -15,8 +18,8 @@ assert(on_complete is not None) self.on_complete = on_complete self.filename = filename - activity.unbind(o...
7a5b86bcb8c0a2e8c699c7602cef50bed2acef1b
src/keybar/tests/factories/user.py
src/keybar/tests/factories/user.py
import factory from django.contrib.auth.hashers import make_password from keybar.models.user import User class UserFactory(factory.DjangoModelFactory): email = factory.Sequence(lambda i: '{0}@none.none'.format(i)) is_active = True class Meta: model = User @classmethod def _prepare(cls, ...
import factory from django.contrib.auth.hashers import make_password from keybar.models.user import User class UserFactory(factory.DjangoModelFactory): email = factory.Sequence(lambda i: '{0}@none.none'.format(i)) is_active = True class Meta: model = User @classmethod def _prepare(cls, ...
Use pdbkdf_sha256 hasher for testing too.
Use pdbkdf_sha256 hasher for testing too.
Python
bsd-3-clause
keybar/keybar
--- +++ @@ -15,5 +15,5 @@ def _prepare(cls, create, **kwargs): raw_password = kwargs.pop('raw_password', 'secret') if 'password' not in kwargs: - kwargs['password'] = make_password(raw_password, hasher='md5') + kwargs['password'] = make_password(raw_password, hasher='pbkdf...
5c29b4322d1a24c4f389076f2a9b8acbeabd89e2
python/lumidatumclient/classes.py
python/lumidatumclient/classes.py
import os import requests class LumidatumClient(object): def __init__(self, authentication_token, model_id=None, host_address='https://www.lumidatum.com'): self.authentication_token = authentication_token self.model_id = model_id self.host_address = host_address def getRecommendatio...
import os import requests class LumidatumClient(object): def __init__(self, authentication_token, model_id=None, host_address='https://www.lumidatum.com'): self.authentication_token = authentication_token self.model_id = str(model_id) self.host_address = host_address def getRecommen...
Fix for os.path.join with model_id, was breaking on non-string model_id values.
Fix for os.path.join with model_id, was breaking on non-string model_id values.
Python
mit
Lumidatum/lumidatumclients,Lumidatum/lumidatumclients,daws/lumidatumclients,Lumidatum/lumidatumclients
--- +++ @@ -7,7 +7,7 @@ def __init__(self, authentication_token, model_id=None, host_address='https://www.lumidatum.com'): self.authentication_token = authentication_token - self.model_id = model_id + self.model_id = str(model_id) self.host_address = host_address def getR...
7b2dac39cdcbc8d5f05d4979df06bf1ab1ae065f
goetia/pythonizors/pythonize_parsing.py
goetia/pythonizors/pythonize_parsing.py
from goetia.pythonizors.utils import is_template_inst def pythonize_goetia_parsing(klass, name): is_fastx, _ = is_template_inst(name, 'FastxParser') if is_fastx: def __iter__(self): while not self.is_complete(): record = self.next() if record: ...
from goetia.pythonizors.utils import is_template_inst def pythonize_goetia_parsing(klass, name): is_fastx, _ = is_template_inst(name, 'FastxParser') if is_fastx: def __iter__(self): while not self.is_complete(): record = self.next() if record: ...
Fix std::optional access in SplitPairedReader pythonization
Fix std::optional access in SplitPairedReader pythonization
Python
mit
camillescott/boink,camillescott/boink,camillescott/boink,camillescott/boink
--- +++ @@ -16,9 +16,8 @@ if is_split: def __iter__(self): while not self.is_complete(): - pair = self.next() - left = pair.left if pair.has_left else None - right = pair.right if pair.has_right else None + left, right = self.next...
ccb7446b02b394af308f4fba0500d402240f117e
home/migrations/0002_create_homepage.py
home/migrations/0002_create_homepage.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def create_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') Home...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def create_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') Home...
Remove any existing localhost sites and use the page id rather than the object to set the default homepage.
Remove any existing localhost sites and use the page id rather than the object to set the default homepage.
Python
mit
OpenCanada/lindinitiative,OpenCanada/lindinitiative
--- +++ @@ -29,9 +29,15 @@ url_path='/home/', ) + Site = apps.get_model('wagtailcore.Site') + HomePage = apps.get_model("core", "HomePage") + homepage = HomePage.objects.get(slug="home") + + Site.objects.filter(hostname='localhost').delete() + # Create a site with the new homepage set...
1179163881fe1dedab81a02a940c711479a334ab
Instanssi/admin_auth/forms.py
Instanssi/admin_auth/forms.py
# -*- coding: utf-8 -*- from django import forms from uni_form.helper import FormHelper from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder class LoginForm(forms.Form): username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät ke...
# -*- coding: utf-8 -*- from django import forms from uni_form.helper import FormHelper from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder class LoginForm(forms.Form): username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät ke...
Use passwordinput in password field.
admin_auth: Use passwordinput in password field.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
--- +++ @@ -6,7 +6,7 @@ class LoginForm(forms.Form): username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät kelpaa!") - password = forms.CharField(label=u"Salasana") + password = forms.CharField(label=u"Salasana", widget=forms.Pass...
ab7856950c058d00aac99874669839e09bc116c6
models.py
models.py
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.File...
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.File...
Order feedback items by their timestamp.
Order feedback items by their timestamp.
Python
bsd-3-clause
littleweaver/django-talkback,littleweaver/django-talkback,littleweaver/django-talkback
--- +++ @@ -30,3 +30,6 @@ username=self.user.get_full_name(), path = self.request_path ) + + class Meta: + ordering = ["-timestamp"]
cdaffa187b41f3a84cb5a6b44f2e781a9b249f2b
tests/test_users.py
tests/test_users.py
from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self...
from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self...
Update test to reflect new method name.
Update test to reflect new method name.
Python
mit
nhshd-slot/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT
--- +++ @@ -12,5 +12,5 @@ assert result is False def test_convert_dict_to_user_instance_returns_valid_user_instance(self): - result = uc.convert_dict_to_user_instance({}) + result = uc.return_user_instance_or_anonymous({}) assert result
63276c6de1b61fb9e9a5b7b4a4eac5813e433f80
tests/test_utils.py
tests/test_utils.py
import mock import unittest2 from thanatos import utils class UtilsTestCase(unittest2.TestCase): def setUp(self): pass @mock.patch('thanatos.questions.Question.__subclasses__') def test_required_tables_returns_unique_set(self, mock_subclasses): """ """ mock_subclass_1 = mock....
import mock import unittest2 from thanatos import utils class UtilsTestCase(unittest2.TestCase): def setUp(self): pass @mock.patch('thanatos.questions.base.Question.__subclasses__') def test_required_tables_returns_unique_set(self, mock_subclasses): """ """ mock_subclass_1 = ...
Fix mock path to fix broken test.
Fix mock path to fix broken test.
Python
mit
evetrivia/thanatos
--- +++ @@ -11,7 +11,7 @@ def setUp(self): pass - @mock.patch('thanatos.questions.Question.__subclasses__') + @mock.patch('thanatos.questions.base.Question.__subclasses__') def test_required_tables_returns_unique_set(self, mock_subclasses): """ """ mock_subclass_1 = mock....
a3cce9e4840cc687f6dcdd0b88577d2f13f3258e
onlineweb4/settings/raven.py
onlineweb4/settings/raven.py
import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:pass@sentry.io/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), }
import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:pass@sentry.io/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), ...
Make it possible to specify which app to represent in sentry
Make it possible to specify which app to represent in sentry
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
--- +++ @@ -8,4 +8,5 @@ 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), + 'tags': { 'app': config('OW4_RAVEN_APP_NAME', default='') }, }
e2cc9c822abb675a196468ee89b063e0162c16d5
changes/api/author_build_index.py
changes/api/author_build_index.py
from __future__ import absolute_import, division, unicode_literals from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.api.auth import get_current_user from changes.models import Author, Build class AuthorBuildIndexAPIView(APIView): def _get_author(self, author_id): i...
from __future__ import absolute_import, division, unicode_literals from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.api.auth import get_current_user from changes.models import Author, Build class AuthorBuildIndexAPIView(APIView): def _get_author(self, author_id): i...
Move 'me' check outside of author lookup
Move 'me' check outside of author lookup
Python
apache-2.0
wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,dropbox/changes
--- +++ @@ -18,10 +18,11 @@ return Author.query.get(author_id) def get(self, author_id): + if author_id == 'me' and not get_current_user(): + return '', 401 + author = self._get_author(author_id) if not author: - if author_id == 'me': - ret...
5d9ec3c24972772814921fb8500845ca3d8fa8b3
chempy/electrochemistry/nernst.py
chempy/electrochemistry/nernst.py
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None, backend=math): """ Calculates the Nernst potential using the Nernst equation for a particular i...
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None, backend=math): """ Calculates the Nernst potential using the Nernst equation for a particular i...
Use actual constant name (molar_gas_constant)
Use actual constant name (molar_gas_constant)
Python
bsd-2-clause
bjodah/aqchem,bjodah/aqchem,bjodah/chempy,bjodah/aqchem,bjodah/chempy
--- +++ @@ -41,6 +41,6 @@ R *= units.joule / units.kelvin / units.mol else: F = constants.Faraday_constant - R = constants.ideal_gas_constant + R = constants.molar_gas_constant return (R * T) / (charge * F) * backend.log(ion_conc_out / ion_conc_in)
b8a7dd2dfc9322498dc7500f840bedd20d807ae1
samples/numpy_blir.py
samples/numpy_blir.py
import numpy as np from blaze.blir import compile, execute source = """ def main(x: array[int], n : int) -> void { var int i; var int j; for i in range(n) { for j in range(n) { x[i,j] = i+j; } x[i-1,j-1] = 10; } } """ N = 14 ast, env = compile(source) arr = np.eye(...
import numpy as np from blaze.blir import compile, execute source = """ def main(x: array[int], n : int) -> void { var int i; var int j; for i in range(n) { for j in range(n) { x[i,j] = i+j; } } } """ N = 15 ast, env = compile(source) arr = np.eye(N, dtype='int32') args = ...
Fix dumb out of bounds error.
Fix dumb out of bounds error.
Python
bsd-2-clause
seibert/blaze-core,seibert/blaze-core,seibert/blaze-core,seibert/blaze-core,seibert/blaze-core
--- +++ @@ -9,12 +9,11 @@ for j in range(n) { x[i,j] = i+j; } - x[i-1,j-1] = 10; } } """ -N = 14 +N = 15 ast, env = compile(source) arr = np.eye(N, dtype='int32')
3335c3fed0718bac401e0dc305edc73830ea8c6b
EmeraldAI/Entities/PipelineArgs.py
EmeraldAI/Entities/PipelineArgs.py
#!/usr/bin/python # -*- coding: utf-8 -*- import random from EmeraldAI.Entities.BaseObject import BaseObject class PipelineArgs(BaseObject): def __init__(self, input): # Original Input self.Input = input self.Normalized = input # Input Language | List of EmeraldAI.Entities.BaseOb...
#!/usr/bin/python # -*- coding: utf-8 -*- import random from EmeraldAI.Entities.BaseObject import BaseObject class PipelineArgs(BaseObject): def __init__(self, input): # Original Input self.Input = input self.Normalized = input # Input Language | List of EmeraldAI.Entities.BaseOb...
Fix Pipeline Args Bug on dict length
Fix Pipeline Args Bug on dict length
Python
apache-2.0
MaxMorgenstern/EmeraldAI,MaxMorgenstern/EmeraldAI,MaxMorgenstern/EmeraldAI,MaxMorgenstern/EmeraldAI,MaxMorgenstern/EmeraldAI
--- +++ @@ -38,7 +38,7 @@ def GetSentencesWithHighestValue(self, margin=0): - if self.SentenceList != None and len(self.SentenceList) > 0: + if self.SentenceList != None and self.SentenceList: highestRanking = max(node.Rating for node in self.SentenceList.values()) if ...
379c6254da0d6a06f8c01cd7cd2632a1d59624ac
comics/sets/context_processors.py
comics/sets/context_processors.py
from comics.sets.models import UserSet def user_set(request): try: user_set = UserSet.objects.get(user=request.user) return { 'user_set': user_set, 'user_set_comics': user_set.comics.all(), } except UserSet.DoesNotExist: return {}
def user_set(request): if hasattr(request, 'user_set'): return { 'user_set': request.user_set, 'user_set_comics': request.user_set.comics.all(), } else: return {}
Use request.user_set in context preprocessor
Use request.user_set in context preprocessor
Python
agpl-3.0
datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics
--- +++ @@ -1,11 +1,8 @@ -from comics.sets.models import UserSet - def user_set(request): - try: - user_set = UserSet.objects.get(user=request.user) + if hasattr(request, 'user_set'): return { - 'user_set': user_set, - 'user_set_comics': user_set.comics.all(), + ...
3aa2f858f93ed3945bf1960d5c5d1d90df34422c
MoodJournal/entries/serializers.py
MoodJournal/entries/serializers.py
from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator, UniqueForDateValidator from .models import UserDefinedCategory from .models import EntryInstance class UserDefinedCategorySerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentity...
from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from .models import UserDefinedCategory from .models import EntryInstance class UserDefinedCategorySerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='categor...
Revert "unique for date validator"
Revert "unique for date validator" This reverts commit 7d2eee38eebf62787b77cdd41e7677cfdad6d47b.
Python
mit
swpease/MoodJournal,swpease/MoodJournal,swpease/MoodJournal
--- +++ @@ -1,5 +1,5 @@ from rest_framework import serializers -from rest_framework.validators import UniqueTogetherValidator, UniqueForDateValidator +from rest_framework.validators import UniqueTogetherValidator from .models import UserDefinedCategory from .models import EntryInstance @@ -29,12 +29,4 @@ ...
e394c1889eccb5806a480033dca467da51d515e5
scripts/test_setup.py
scripts/test_setup.py
#! /usr/bin/python import platform import subprocess import sys def _execute(*args, **kwargs): result = subprocess.call(*args, **kwargs) if result != 0: sys.exit(result) if __name__ == '__main__': python_version = platform.python_version() deps = [ "execnet", "Jinja2", ...
#! /usr/bin/python import platform import subprocess import sys def _execute(*args, **kwargs): result = subprocess.call(*args, **kwargs) if result != 0: sys.exit(result) if __name__ == '__main__': python_version = platform.python_version() deps = [ "execnet", "nose", "...
Test dependencies: On Python 2.5, require Jinja 2.6
Test dependencies: On Python 2.5, require Jinja 2.6
Python
bsd-3-clause
omergertel/logbook,pombredanne/logbook,Rafiot/logbook,alonho/logbook,Rafiot/logbook,alonho/logbook,omergertel/logbook,Rafiot/logbook,FintanH/logbook,DasIch/logbook,DasIch/logbook,RazerM/logbook,mitsuhiko/logbook,omergertel/logbook,DasIch/logbook,dommert/logbook,alonho/logbook
--- +++ @@ -13,8 +13,8 @@ deps = [ "execnet", - "Jinja2", "nose", + "sqlalchemy", ] if python_version < "2.6": @@ -22,12 +22,20 @@ "ssl", "multiprocessing", "pyzmq==2.1.11", - "sqlalchemy", "simplejson", ...
52f0b4569429da6b331e150496fe2b7ebef17597
gssapi/__about__.py
gssapi/__about__.py
from __future__ import unicode_literals __title__ = 'python-gssapi' __author__ = 'Hugh Cole-Baker and contributors' __version__ = '0.6.2' __license__ = 'The MIT License (MIT)' __copyright__ = 'Copyright 2014 {0}'.format(__author__)
from __future__ import unicode_literals __title__ = 'python-gssapi' __author__ = 'Hugh Cole-Baker and contributors' __version__ = '0.6.3pre' __license__ = 'The MIT License (MIT)' __copyright__ = 'Copyright 2014 {0}'.format(__author__)
Prepare for next development version
Prepare for next development version
Python
mit
sigmaris/python-gssapi,sigmaris/python-gssapi,sigmaris/python-gssapi,sigmaris/python-gssapi
--- +++ @@ -2,7 +2,7 @@ __title__ = 'python-gssapi' __author__ = 'Hugh Cole-Baker and contributors' -__version__ = '0.6.2' +__version__ = '0.6.3pre' __license__ = 'The MIT License (MIT)' __copyright__ = 'Copyright 2014 {0}'.format(__author__)
da54fa6d681ab7f2e3146b55d562e5a4d68623cc
luigi/tasks/export/ftp/__init__.py
luigi/tasks/export/ftp/__init__.py
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute 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...
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute 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...
Make GO term export part of FTP export
Make GO term export part of FTP export
Python
apache-2.0
RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline
--- +++ @@ -20,6 +20,7 @@ from .rfam import RfamAnnotationExport from .fasta import FastaExport from .ensembl import EnsemblExport +from .go_annotations import GoAnnotationExport class FtpExport(luigi.WrapperTask): @@ -29,3 +30,4 @@ yield RfamAnnotationExport yield FastaExport yield...
eb496468d61ff3245adbdec4108a04bc40a357fc
Grid.py
Grid.py
from boomslang.LineStyle import LineStyle class Grid(object): def __init__(self, color="#dddddd", style="-", visible=True): self.color = color self._lineStyle = LineStyle() self._lineStyle.style = style self.visible = visible @property def style(self): return self._...
from boomslang.LineStyle import LineStyle class Grid(object): def __init__(self, color="#dddddd", style="-", visible=True): self.color = color self._lineStyle = LineStyle() self._lineStyle.style = style self.visible = visible self.which = 'major' @property def style...
Allow gridlines on both major and minor axes.
Allow gridlines on both major and minor axes.
Python
bsd-3-clause
alexras/boomslang
--- +++ @@ -6,6 +6,7 @@ self._lineStyle = LineStyle() self._lineStyle.style = style self.visible = visible + self.which = 'major' @property def style(self): @@ -21,6 +22,7 @@ def draw(self, fig, axes): if self.visible: - axes.grid(color=self.col...
8ae82e08fc42d89402550f5f545dbaa258196c8c
ibmcnx/test/test.py
ibmcnx/test/test.py
#import ibmcnx.test.loadFunction import sys from java.lang import String from java.util import HashSet from java.util import HashMap import java import lotusConnectionsCommonAdmin globdict = globals() def loadFilesService(): global globdict execfile( "filesAdmin.py", globdict ) loadFilesService() FilesPolic...
#import ibmcnx.test.loadFunction import sys from java.lang import String from java.util import HashSet from java.util import HashMap import java import lotusConnectionsCommonAdmin globdict = globals() def loadFilesService(): global globdict execfile( "filesAdmin.py", globdict ) loadFilesService() test = Fil...
Customize scripts to work with menu
Customize scripts to work with menu
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
--- +++ @@ -14,4 +14,5 @@ loadFilesService() -FilesPolicyService.browse( "title", "true", 1, 25 ) +test = FilesPolicyService.browse( "title", "true", 1, 25 ) +print test
fc42c3cf72abeb053560c21e1870e8507aa2d666
examples/framework/faren/faren.py
examples/framework/faren/faren.py
#!/usr/bin/env python import gtk from kiwi.controllers import BaseController from kiwi.ui.views import BaseView from kiwi.ui.gadgets import quit_if_last class FarenControl(BaseController): def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() def after_temperature__changed(self, entry, ...
#!/usr/bin/env python import gtk from kiwi.controllers import BaseController from kiwi.ui.views import BaseView from kiwi.ui.gadgets import quit_if_last class FarenControl(BaseController): def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() def after_temperature__insert_text(self, ent...
Use insert_text instead of changed
Use insert_text instead of changed
Python
lgpl-2.1
stoq/kiwi
--- +++ @@ -10,7 +10,7 @@ def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() - def after_temperature__changed(self, entry, *args): + def after_temperature__insert_text(self, entry, *args): try: temp = float(entry.get_text()) except ValueError:
a859890c9f17b2303061b2d68e5c58ad27e07b35
grizli/pipeline/__init__.py
grizli/pipeline/__init__.py
""" Automated processing of associated exposures """
""" Automated processing of associated exposures """ def fetch_from_AWS_bucket(root='j022644-044142', id=1161, product='.beams.fits', bucket_name='aws-grivam', verbose=True, dryrun=False, output_path='./', get_fit_args=False, skip_existing=True): """ Fetch products from the Grizli AWS bucket. Boto3 ...
Add script to fetch data from AWS
Add script to fetch data from AWS
Python
mit
gbrammer/grizli
--- +++ @@ -2,4 +2,35 @@ Automated processing of associated exposures """ - +def fetch_from_AWS_bucket(root='j022644-044142', id=1161, product='.beams.fits', bucket_name='aws-grivam', verbose=True, dryrun=False, output_path='./', get_fit_args=False, skip_existing=True): + """ + Fetch products from the Grizl...
1859a5c4ae4f13b1eb8c586578909a943d15f673
invocations/docs.py
invocations/docs.py
import os from invoke import ctask as task, Collection docs_dir = 'docs' build_dir = os.path.join(docs_dir, '_build') @task(aliases=['c']) def _clean(ctx): ctx.run("rm -rf %s" % build_dir) @task(aliases=['b']) def _browse(ctx): ctx.run("open %s" % os.path.join(build_dir, 'index.html')) @task(default=Tr...
import os from invoke import ctask as task, Collection @task(aliases=['c']) def _clean(ctx): ctx.run("rm -rf {0}".format(ctx['sphinx.target'])) @task(aliases=['b']) def _browse(ctx): index = os.path.join(ctx['sphinx.target'], 'index.html') ctx.run("open {0}".format(index)) @task(default=True) def bui...
Make use of new collection config vector
Make use of new collection config vector
Python
bsd-2-clause
alex/invocations,singingwolfboy/invocations,pyinvoke/invocations,mrjmad/invocations
--- +++ @@ -3,26 +3,31 @@ from invoke import ctask as task, Collection -docs_dir = 'docs' -build_dir = os.path.join(docs_dir, '_build') - - @task(aliases=['c']) def _clean(ctx): - ctx.run("rm -rf %s" % build_dir) + ctx.run("rm -rf {0}".format(ctx['sphinx.target'])) @task(aliases=['b']) def _browse(...
f46059285851d47a9bee2174e32e9e084efe1182
jirafs/constants.py
jirafs/constants.py
from jirafs import __version__ as version # Metadata filenames TICKET_DETAILS = 'fields.jira' TICKET_COMMENTS = 'comments.read_only.jira' TICKET_NEW_COMMENT = 'new_comment.jira' TICKET_LINKS = 'links.jira' TICKET_FILE_FIELD_TEMPLATE = u'{field_name}.jira' # Generic settings LOCAL_ONLY_FILE = '.jirafs_local' REMOTE_IG...
from jirafs import __version__ as version # Metadata filenames TICKET_DETAILS = 'fields.jira' TICKET_COMMENTS = 'comments.read_only.jira' TICKET_NEW_COMMENT = 'new_comment.jira' TICKET_LINKS = 'links.jira' TICKET_FILE_FIELD_TEMPLATE = u'{field_name}.jira' # Generic settings LOCAL_ONLY_FILE = '.jirafs_local' REMOTE_IG...
Remove my personal domain from the public jirafs git config.
Remove my personal domain from the public jirafs git config.
Python
mit
coddingtonbear/jirafs,coddingtonbear/jirafs
--- +++ @@ -16,7 +16,7 @@ TICKET_OPERATION_LOG = 'operation.log' METADATA_DIR = '.jirafs' GLOBAL_CONFIG = '.jirafs_config' -GIT_AUTHOR = 'Jirafs %s <jirafs@adamcoddington.net>' % ( +GIT_AUTHOR = 'Jirafs %s <jirafs@localhost>' % ( version )
1690c1981614e20183d33de4d117af0aa62ae9c5
kboard/board/urls.py
kboard/board/urls.py
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_p...
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new...
Modify board_slug in url regex to pass numeric letter
Modify board_slug in url regex to pass numeric letter
Python
mit
kboard/kboard,guswnsxodlf/k-board,kboard/kboard,cjh5414/kboard,hyesun03/k-board,cjh5414/kboard,hyesun03/k-board,guswnsxodlf/k-board,kboard/kboard,hyesun03/k-board,darjeeling/k-board,cjh5414/kboard,guswnsxodlf/k-board
--- +++ @@ -7,10 +7,10 @@ app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), - url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'), - url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'), + url(r'^(?P<board_slug>[-a-z]+)/$', views.pos...
ff34a0b9ffc3fed7be9d30d65f9e8f0c24a3cf83
abusehelper/contrib/spamhaus/xbl.py
abusehelper/contrib/spamhaus/xbl.py
""" Spamhaus XBL list handler. Maintainer: Sauli Pahlman <sauli@codenomicon.com> """ import idiokit from abusehelper.core import cymruwhois, bot, events class SpamhausXblBot(bot.PollingBot): xbl_filepath = bot.Param("Filename of Spamhaus XBL file") @idiokit.stream def poll(self): skip_chars = [...
""" Spamhaus XBL list handler. Maintainer: Sauli Pahlman <sauli@codenomicon.com> """ import idiokit from abusehelper.core import cymruwhois, bot, events class SpamhausXblBot(bot.PollingBot): xbl_filepath = bot.Param("Filename of Spamhaus XBL file") @idiokit.stream def poll(self): skip_chars = [...
Make the bot to save memory by sending events as soon as it reads through the corresponding lines of the input file.
Make the bot to save memory by sending events as soon as it reads through the corresponding lines of the input file.
Python
mit
abusesa/abusehelper
--- +++ @@ -15,7 +15,6 @@ def poll(self): skip_chars = ["#", ":", "$"] self.log.info("Opening %s" % self.xbl_filepath) - entries = [] try: with open(self.xbl_filepath, "r") as f: @@ -24,17 +23,13 @@ if line and line[0] in skip_chars: ...
0d73cc1b38703653c3302d8f9ff4efbeaaa2b406
credentials/apps/records/models.py
credentials/apps/records/models.py
""" Models for the records app. """ import uuid from django.db import models from django_extensions.db.models import TimeStampedModel from credentials.apps.catalog.models import CourseRun, Program from credentials.apps.core.models import User class UserGrade(TimeStampedModel): """ A grade for a specific use...
""" Models for the records app. """ import uuid from django.db import models from django_extensions.db.models import TimeStampedModel from credentials.apps.catalog.models import CourseRun, Program from credentials.apps.core.models import User from credentials.apps.credentials.models import ProgramCertificate class ...
Revert early removal of certificate field
Revert early removal of certificate field
Python
agpl-3.0
edx/credentials,edx/credentials,edx/credentials,edx/credentials
--- +++ @@ -8,6 +8,7 @@ from credentials.apps.catalog.models import CourseRun, Program from credentials.apps.core.models import User +from credentials.apps.credentials.models import ProgramCertificate class UserGrade(TimeStampedModel): @@ -28,6 +29,7 @@ """ Connects a User with a Program """ +...
14482126c8d26e4d822a55d525ff276953adbaff
src/som/primitives/symbol_primitives.py
src/som/primitives/symbol_primitives.py
from som.primitives.primitives import Primitives from som.vmobjects.primitive import Primitive def _asString(ivkbl, frame, interpreter): rcvr = frame.pop() frame.push(interpreter.get_universe().new_string(rcvr.get_embedded_string())) def _equals(ivkbl, frame, interpreter): op1 = frame.pop() op2 = ...
from som.primitives.primitives import Primitives from som.vmobjects.primitive import Primitive def _asString(ivkbl, frame, interpreter): rcvr = frame.pop() frame.push(interpreter.get_universe().new_string(rcvr.get_embedded_string())) def _equals(ivkbl, frame, interpreter): op1 = frame.pop() op2 = ...
Fix Symbol equality to be reference equal
Fix Symbol equality to be reference equal Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
Python
mit
smarr/PySOM,SOM-st/PySOM,SOM-st/RPySOM,SOM-st/PySOM,SOM-st/RPySOM,smarr/PySOM
--- +++ @@ -11,7 +11,7 @@ op1 = frame.pop() op2 = frame.pop() # rcvr universe = interpreter.get_universe() - if op1 == op2: + if op1 is op2: frame.push(universe.trueObject) else: frame.push(universe.falseObject)
efd44be24e84a35db353ac79dae7cc7392a18b0c
matador/commands/deploy_ticket.py
matador/commands/deploy_ticket.py
#!/usr/bin/env python from .command import Command from matador import utils import subprocess import os class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, r...
#!/usr/bin/env python from .command import Command from matador import utils import subprocess import os class DeployTicket(Command): def _add_arguments(self, parser): parser.prog = 'matador deploy-ticket' parser.add_argument( '-e', '--environment', type=str, r...
Add ticket and branch arguments
Add ticket and branch arguments
Python
mit
Empiria/matador
--- +++ @@ -16,6 +16,18 @@ help='Agresso environment name') parser.add_argument( + '-t', '--ticket', + type=str, + required=True, + help='Ticket name') + + parser.add_argument( + '-b', '--branch', + type=str, + ...
6795e02c14fa99da2c0812fe6694bbd503f89ad1
tests/mock_vws/test_invalid_given_id.py
tests/mock_vws/test_invalid_given_id.py
""" Tests for passing invalid endpoints which require a target ID to be given. """ import pytest import requests from requests import codes from mock_vws._constants import ResultCodes from tests.mock_vws.utils import ( TargetAPIEndpoint, VuforiaDatabaseKeys, assert_vws_failure, delete_target, ) @pyt...
""" Tests for passing invalid endpoints which require a target ID to be given. """ import pytest import requests from requests import codes from mock_vws._constants import ResultCodes from tests.mock_vws.utils import ( TargetAPIEndpoint, VuforiaDatabaseKeys, assert_vws_failure, delete_target, ) @pyt...
Use any_endpoint on invalid id test
Use any_endpoint on invalid id test
Python
mit
adamtheturtle/vws-python,adamtheturtle/vws-python
--- +++ @@ -25,13 +25,14 @@ def test_not_real_id( self, vuforia_database_keys: VuforiaDatabaseKeys, - endpoint: TargetAPIEndpoint, + any_endpoint: TargetAPIEndpoint, target_id: str, ) -> None: """ A `NOT_FOUND` error is returned when an endpoint is ...
4eda3f3535d28e2486745f33504c417ba6837c3a
stdnum/nz/__init__.py
stdnum/nz/__init__.py
# __init__.py - collection of New Zealand numbers # coding: utf-8 # # Copyright (C) 2019 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the Licen...
# __init__.py - collection of New Zealand numbers # coding: utf-8 # # Copyright (C) 2019 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the Licen...
Add missing vat alias for New Zealand
Add missing vat alias for New Zealand Closes https://github.com/arthurdejong/python-stdnum/pull/202
Python
lgpl-2.1
arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum
--- +++ @@ -19,3 +19,6 @@ # 02110-1301 USA """Collection of New Zealand numbers.""" + +# provide aliases +from stdnum.nz import ird as vat # noqa: F401
9e75c0b90d15222af3089d2362c28be726861558
nbresuse/handlers.py
nbresuse/handlers.py
import os import json import psutil from notebook.utils import url_path_join from notebook.base.handlers import IPythonHandler def get_metrics(): cur_process = psutil.Process() all_processes = [cur_process] + cur_process.children(recursive=True) rss = sum([p.memory_info().rss for p in all_processes]) r...
import os import json import psutil from notebook.utils import url_path_join from notebook.base.handlers import IPythonHandler def get_metrics(): cur_process = psutil.Process() all_processes = [cur_process] + cur_process.children(recursive=True) rss = sum([p.memory_info().rss for p in all_processes]) r...
Use final Memory limit env variable name
Use final Memory limit env variable name
Python
bsd-2-clause
allanlwu/allangdrive,yuvipanda/nbresuse,allanlwu/allangdrive,yuvipanda/nbresuse
--- +++ @@ -11,7 +11,7 @@ return { 'rss': rss, 'limits': { - 'memory': int(os.environ.get('LIMIT_MEM', None)) + 'memory': int(os.environ.get('MEM_LIMIT', None)) } }
ea3a72443f2fa841ea0bc73ec461968c447f39c1
egg_timer/apps/utils/management/commands/check_requirements.py
egg_timer/apps/utils/management/commands/check_requirements.py
import subprocess from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Ensure that all installed packages are in requirements.txt' def _get_file_contents(self, name): req_file = open('requirements/%s.txt' % name) reqs = req_file.read() req_file.clos...
import subprocess from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Ensure that all installed packages are in requirements.txt' def handle(self, *args, **options): proc = subprocess.Popen(['pip', 'freeze'], stdout=subprocess.PIPE) freeze_results = proc.c...
Revert "Added a prod option to the rquirements checker"
Revert "Added a prod option to the rquirements checker" This reverts commit 5b9ae76d157d068ef456d5caa5c4352a139f528b.
Python
mit
jessamynsmith/eggtimer-server,jessamynsmith/eggtimer-server,jessamynsmith/eggtimer-server,jessamynsmith/eggtimer-server
--- +++ @@ -6,32 +6,19 @@ class Command(BaseCommand): help = 'Ensure that all installed packages are in requirements.txt' - def _get_file_contents(self, name): - req_file = open('requirements/%s.txt' % name) - reqs = req_file.read() - req_file.close() - req_list = reqs.split('\n...
8014285e5dc8fb13377b729f9fd19b4187fbaf29
fireplace/carddata/spells/other.py
fireplace/carddata/spells/other.py
from ..card import * # The Coin class GAME_005(Card): def action(self): self.controller.tempMana += 1
from ..card import * # The Coin class GAME_005(Card): def action(self): self.controller.tempMana += 1 # RFG # Adrenaline Rush class NEW1_006(Card): action = drawCard combo = drawCards(2)
Implement Adrenaline Rush why not
Implement Adrenaline Rush why not
Python
agpl-3.0
Ragowit/fireplace,butozerca/fireplace,Meerkov/fireplace,smallnamespace/fireplace,amw2104/fireplace,liujimj/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,oftc-ftw/fireplace,butozerca/fireplace,NightKev/fireplace,jleclanche/fireplace,liujimj/fireplace,Meerkov/fireplace,beheh/fireplace,smallnamespace/fireplace,amw2104/fi...
--- +++ @@ -5,3 +5,11 @@ class GAME_005(Card): def action(self): self.controller.tempMana += 1 + + +# RFG + +# Adrenaline Rush +class NEW1_006(Card): + action = drawCard + combo = drawCards(2)
9410ceb83d85d70a484bbf08ecc274216fa0589f
mythril/support/source_support.py
mythril/support/source_support.py
from mythril.solidity.soliditycontract import SolidityContract from mythril.ethereum.evmcontract import EVMContract class Source: def __init__( self, source_type=None, source_format=None, source_list=None, meta=None ): self.source_type = source_type self.source_format = source_format ...
from mythril.solidity.soliditycontract import SolidityContract from mythril.ethereum.evmcontract import EVMContract class Source: """Class to handle to source data""" def __init__( self, source_type=None, source_format=None, source_list=None, meta=None ): """ :param source_type: w...
Add documentation for Source class
Add documentation for Source class
Python
mit
b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril
--- +++ @@ -3,15 +3,28 @@ class Source: + """Class to handle to source data""" + def __init__( self, source_type=None, source_format=None, source_list=None, meta=None ): + """ + :param source_type: whether it is a solidity-file or evm-bytecode + :param source_format: wh...
db46374695aed370aa8d8a51c34043d6a48a702d
waldo/tests/unit/test_contrib_config.py
waldo/tests/unit/test_contrib_config.py
# pylint: disable=R0904,W0212 # Copyright (c) 2011-2013 Rackspace Hosting # 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/lice...
# pylint: disable=C0103,C0111,R0903,R0904,W0212,W0232 # Copyright (c) 2011-2013 Rackspace Hosting # 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 # # ht...
Add common ignore list per README
Add common ignore list per README
Python
apache-2.0
checkmate/simpl,ryandub/simpl,ziadsawalha/simpl,samstav/simpl,larsbutler/simpl
--- +++ @@ -1,4 +1,4 @@ -# pylint: disable=R0904,W0212 +# pylint: disable=C0103,C0111,R0903,R0904,W0212,W0232 # Copyright (c) 2011-2013 Rackspace Hosting # All Rights Reserved.
ad98e3c25434dc251fe6d7ace3acfe418a4d8955
simplekv/db/mongo.py
simplekv/db/mongo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from .. import KeyValueStore from .._compat import BytesIO from .._compat import pickle from bson.binary import Binary class MongoStore(KeyValueStore): """Uses a MongoDB collection as the backend, using pickle as a serializer. :param db: A (already authenticate...
#!/usr/bin/env python # -*- coding: utf-8 -*- from .. import KeyValueStore from .._compat import BytesIO from .._compat import pickle from bson.binary import Binary class MongoStore(KeyValueStore): """Uses a MongoDB collection as the backend, using pickle as a serializer. :param db: A (already authenticate...
Fix Python3s lack of .next().
Fix Python3s lack of .next().
Python
mit
mbr/simplekv,karteek/simplekv,mbr/simplekv,fmarczin/simplekv,karteek/simplekv,fmarczin/simplekv
--- +++ @@ -27,7 +27,7 @@ def _get(self, key): try: - item = self.db[self.collection].find({"_id": key}).next() + item = next(self.db[self.collection].find({"_id": key})) return pickle.loads(item["v"]) except StopIteration: raise KeyError(key)
b61188d2a842c4bde0b5e5c14d60db86806b0502
pdftools/__init__.py
pdftools/__init__.py
""" pdftools Package. :author: Stefan Lehmann <stlm@posteo.de> :license: MIT, see license file or https://opensource.org/licenses/MIT :created on 2018-04-14 20:35:21 :last modified by: Stefan Lehmann :last modified time: 2018-10-28 16:57:24 """ __version__ = "1.1.4" from .pdftools import ( pdf_merge, pdf...
""" pdftools Package. :author: Stefan Lehmann <stlm@posteo.de> :license: MIT, see license file or https://opensource.org/licenses/MIT :created on 2018-04-14 20:35:21 :last modified by: Stefan Lehmann :last modified time: 2018-10-28 16:57:24 """ __version__ = "2.0.0" from .pdftools import ( pdf_merge, pdf...
Update to new mayor version
Update to new mayor version
Python
mit
MrLeeh/pdftools
--- +++ @@ -9,7 +9,7 @@ :last modified time: 2018-10-28 16:57:24 """ -__version__ = "1.1.4" +__version__ = "2.0.0" from .pdftools import (
f87a923678f5d7e9f6390ffcb42eae6b2a0f9cc2
services/views.py
services/views.py
import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request....
import json import requests from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .patch_ssl import get_session @csrf_exempt def post_service_request(request): if request....
Use separate API key for feedback about app.
Use separate API key for feedback about app.
Python
agpl-3.0
City-of-Helsinki/smbackend,City-of-Helsinki/smbackend
--- +++ @@ -11,7 +11,13 @@ return HttpResponseNotAllowed(['POST']) payload = request.POST.copy() outgoing = payload.dict() - outgoing['api_key'] = settings.OPEN311['API_KEY'] + if outgoing.get('internal_feedback', False): + if 'internal_feedback' in outgoing: + del outgoing[...
b92c1caa8e19376c17f503de1464d4466e547cdf
api/base/content_negotiation.py
api/base/content_negotiation.py
from rest_framework.negotiation import BaseContentNegotiation class CustomClientContentNegotiation(BaseContentNegotiation): def select_parser(self, request, parsers): """ Select the first parser in the `.parser_classes` list. """ return parsers[0] def select_renderer(self, req...
from rest_framework.negotiation import BaseContentNegotiation class CustomClientContentNegotiation(BaseContentNegotiation): def select_parser(self, request, parsers): """ Select the first parser in the `.parser_classes` list. """ return parsers[0] def select_renderer(self, req...
Select third renderer if 'text/html' in accept
Select third renderer if 'text/html' in accept
Python
apache-2.0
brianjgeiger/osf.io,arpitar/osf.io,TomHeatwole/osf.io,Nesiehr/osf.io,zachjanicki/osf.io,RomanZWang/osf.io,DanielSBrown/osf.io,doublebits/osf.io,crcresearch/osf.io,amyshi188/osf.io,acshi/osf.io,monikagrabowska/osf.io,petermalcolm/osf.io,GageGaskins/osf.io,kwierman/osf.io,TomHeatwole/osf.io,cslzchen/osf.io,brandonPurvis/...
--- +++ @@ -10,6 +10,9 @@ def select_renderer(self, request, renderers, format_suffix): """ - Select the first renderer in the `.renderer_classes` list. + Select the third renderer in the `.renderer_classes` list for the browsable API, + otherwise use the first renderer which has ...
69de2261c30a8bab1ac4d0749cf32baec49e0cc4
webapp/byceps/blueprints/board/views.py
webapp/byceps/blueprints/board/views.py
# -*- coding: utf-8 -*- """ byceps.blueprints.board.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2014 Jochen Kupperschmidt """ from ...util.framework import create_blueprint from ...util.templating import templated from ..authorization.registry import permission_registry from .authorization import BoardPos...
# -*- coding: utf-8 -*- """ byceps.blueprints.board.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2014 Jochen Kupperschmidt """ from ...util.framework import create_blueprint from ...util.templating import templated from ..authorization.registry import permission_registry from .authorization import BoardPos...
Throw 404 if category/topic with given id is not found.
Throw 404 if category/topic with given id is not found.
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps
--- +++ @@ -35,7 +35,7 @@ @templated def category_view(id): """List latest topics in the category.""" - category = Category.query.get(id) + category = Category.query.get_or_404(id) return {'category': category} @@ -43,5 +43,5 @@ @templated def topic_view(id): """List postings for the topi...
b890c9046d36687a65d46be724cfaa8726417b5d
selectable/tests/runtests.py
selectable/tests/runtests.py
#!/usr/bin/env python import os import sys from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', } }, INSTALLED_APPS=( ...
#!/usr/bin/env python import os import sys from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', } }, INSTALLED_APPS=( ...
Add SITE_ID to test settings setup for Django 1.3.
Add SITE_ID to test settings setup for Django 1.3.
Python
bsd-2-clause
mlavin/django-selectable,affan2/django-selectable,makinacorpus/django-selectable,makinacorpus/django-selectable,affan2/django-selectable,mlavin/django-selectable,mlavin/django-selectable,affan2/django-selectable
--- +++ @@ -21,6 +21,7 @@ 'django.contrib.messages', 'selectable', ), + SITE_ID=1, ROOT_URLCONF='selectable.tests.urls', )
2d3b899011c79324195a36aaf3bd53dae6abe961
seleniumrequests/__init__.py
seleniumrequests/__init__.py
from selenium.webdriver import Firefox, Chrome, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote from seleniumrequests.request import RequestsSessionMixin class Firefox(RequestsSessionMixin, Firefox): pass class Chrome(RequestsSessionMixin, Chrome): pass class Ie(RequestsSessionMixin, Ie):...
from selenium.webdriver import _Firefox, _Chrome, _Ie, _Edge, _Opera, _Safari, _BlackBerry, _PhantomJS, _Android, \ _Remote from seleniumrequests.request import RequestsSessionMixin class Firefox(RequestsSessionMixin, _Firefox): pass class Chrome(RequestsSessionMixin, _Chrome): pass class Ie(Requests...
Fix PyCharm warnings like this: "Cannot find reference `request` in `PhantomJS | WebDriver`"
Fix PyCharm warnings like this: "Cannot find reference `request` in `PhantomJS | WebDriver`"
Python
mit
cryzed/Selenium-Requests
--- +++ @@ -1,43 +1,44 @@ -from selenium.webdriver import Firefox, Chrome, Ie, Edge, Opera, Safari, BlackBerry, PhantomJS, Android, Remote +from selenium.webdriver import _Firefox, _Chrome, _Ie, _Edge, _Opera, _Safari, _BlackBerry, _PhantomJS, _Android, \ + _Remote from seleniumrequests.request import RequestsS...
1e0327c852b851f867d21a182ba7604b42d15331
examples/charts/file/stacked_bar.py
examples/charts/file/stacked_bar.py
from bokeh.charts import Bar, output_file, show from bokeh.charts.operations import blend from bokeh.charts.attributes import cat, color from bokeh.charts.utils import df_from_json from bokeh.sampledata.olympics2014 import data from bokeh.models.tools import HoverTool # utilize utility to make it easy to get json/dic...
from bokeh.charts import Bar, output_file, show from bokeh.charts.operations import blend from bokeh.charts.attributes import cat, color from bokeh.charts.utils import df_from_json from bokeh.sampledata.olympics2014 import data # utilize utility to make it easy to get json/dict data converted to a dataframe df = df_fr...
Update stacked bar example to use the hover kwarg.
Update stacked bar example to use the hover kwarg.
Python
bsd-3-clause
Karel-van-de-Plassche/bokeh,rs2/bokeh,jakirkham/bokeh,msarahan/bokeh,DuCorey/bokeh,schoolie/bokeh,schoolie/bokeh,quasiben/bokeh,timsnyder/bokeh,KasperPRasmussen/bokeh,ericmjl/bokeh,stonebig/bokeh,bokeh/bokeh,ericmjl/bokeh,bokeh/bokeh,aavanian/bokeh,dennisobrien/bokeh,clairetang6/bokeh,DuCorey/bokeh,ericmjl/bokeh,azjps/...
--- +++ @@ -3,8 +3,6 @@ from bokeh.charts.attributes import cat, color from bokeh.charts.utils import df_from_json from bokeh.sampledata.olympics2014 import data - -from bokeh.models.tools import HoverTool # utilize utility to make it easy to get json/dict data converted to a dataframe df = df_from_json(data) ...
05419e49c438c3f867c1ab4bd37021755ec09332
skimage/exposure/__init__.py
skimage/exposure/__init__.py
from .exposure import histogram, equalize, equalize_hist, \ rescale_intensity, cumulative_distribution, \ adjust_gamma, adjust_sigmoid, adjust_log from ._adapthist import equalize_adapthist __all__ = ['histogram', 'equalize', 'equalize_hist', ...
from .exposure import histogram, equalize, equalize_hist, \ rescale_intensity, cumulative_distribution, \ adjust_gamma, adjust_sigmoid, adjust_log from ._adapthist import equalize_adapthist from .unwrap import unwrap __all__ = ['histogram', 'equalize', ...
Make unwrap visible in the exposure package.
Make unwrap visible in the exposure package.
Python
bsd-3-clause
SamHames/scikit-image,ClinicalGraphics/scikit-image,chintak/scikit-image,bennlich/scikit-image,robintw/scikit-image,rjeli/scikit-image,youprofit/scikit-image,ClinicalGraphics/scikit-image,rjeli/scikit-image,chriscrosscutler/scikit-image,SamHames/scikit-image,blink1073/scikit-image,youprofit/scikit-image,GaZ3ll3/scikit-...
--- +++ @@ -3,6 +3,7 @@ adjust_gamma, adjust_sigmoid, adjust_log from ._adapthist import equalize_adapthist +from .unwrap import unwrap __all__ = ['histogram', 'equalize', @@ -12,4 +13,5 @@ 'cumulative_distribution', 'adjust_gamma', 'adjust_...
a4c2b68a69d89a293568fb257b4a8c0549a5ef9b
solitude/settings/sites/dev/db.py
solitude/settings/sites/dev/db.py
"""private_base will be populated from puppet and placed in this directory""" import logging import dj_database_url import private_base as private ADMINS = () DATABASES = {} DATABASES['default'] = dj_database_url.parse(private.DATABASES_DEFAULT_URL) DATABASES['default']['ENGINE'] = 'django.db.backends.mysql' DATA...
"""private_base will be populated from puppet and placed in this directory""" import logging import dj_database_url import private_base as private ADMINS = () DATABASES = {} DATABASES['default'] = dj_database_url.parse(private.DATABASES_DEFAULT_URL) DATABASES['default']['ENGINE'] = 'django.db.backends.mysql' DATA...
Revert "turn proxy back on"
Revert "turn proxy back on" This reverts commit c5b3a15a2815ff362104afaa6a996fab6f35ae1a.
Python
bsd-3-clause
muffinresearch/solitude,muffinresearch/solitude
--- +++ @@ -41,4 +41,9 @@ PAYPAL_PROXY = private.PAYPAL_PROXY PAYPAL_URL_WHITELIST = ('https://marketplace-dev.allizom.org',) -BANGO_PROXY = private.BANGO_PROXY +# Swap these around when bug 831576 is fixed. +# Speak to Bango directly. +BANGO_ENV = 'test' +BANGO_AUTH = private.BANGO_AUTH +# Use the proxy. +#BANGO...
27e137ef5f3b6c4f6c8679edc6412b2c237b8fb4
plasmapy/physics/tests/test_parameters_cython.py
plasmapy/physics/tests/test_parameters_cython.py
"""Tests for functions that calculate plasma parameters using cython.""" import numpy as np import pytest from astropy import units as u from warnings import simplefilter from ...utils.exceptions import RelativityWarning, RelativityError from ...utils.exceptions import PhysicsError from ...constants import c, m_p, m_...
"""Tests for functions that calculate plasma parameters using cython.""" import numpy as np import pytest from astropy import units as u from warnings import simplefilter from plasmapy.utils.exceptions import RelativityWarning, RelativityError from plasmapy.utils.exceptions import PhysicsError from plasmapy.constants...
Update tests for cython parameters
Update tests for cython parameters
Python
bsd-3-clause
StanczakDominik/PlasmaPy
--- +++ @@ -5,13 +5,12 @@ from astropy import units as u from warnings import simplefilter -from ...utils.exceptions import RelativityWarning, RelativityError -from ...utils.exceptions import PhysicsError -from ...constants import c, m_p, m_e, e, mu0 +from plasmapy.utils.exceptions import RelativityWarning, Relat...
81bb47c28af70936be76f319ba780f2ad89ba2a0
Train_SDAE/tools/evaluate_model.py
Train_SDAE/tools/evaluate_model.py
import numpy as np # import pandas as pd # import sys from scipy.special import expit from sklearn import ensemble def get_activations(exp_data, w, b): exp_data = np.transpose(exp_data) prod = exp_data.dot(w) prod_with_bias = prod + b return( expit(prod_with_bias) ) # Order of *args: first all the wei...
import numpy as np from scipy.special import expit from sklearn import ensemble def get_activations(exp_data, w, b): exp_data = np.transpose(exp_data) prod = exp_data.dot(w) prod_with_bias = prod + b return( expit(prod_with_bias) ) # Order of *args: first all the weights and then all the biases def ru...
Support for variable number of layers
Support for variable number of layers
Python
apache-2.0
glrs/StackedDAE,glrs/StackedDAE
--- +++ @@ -1,6 +1,4 @@ import numpy as np -# import pandas as pd -# import sys from scipy.special import expit from sklearn import ensemble @@ -11,20 +9,19 @@ return( expit(prod_with_bias) ) # Order of *args: first all the weights and then all the biases -def run_random_forest(nHLayers, exp_data, labels...
4986f02edbe45d73f8509b01270490cd8c8f90dd
docs/source/examples/chapel.sfile-inline.py
docs/source/examples/chapel.sfile-inline.py
from pych.extern import Chapel @Chapel(sfile="/home/safl/pychapel/module/ext/src/mymodule.chpl") def hello_mymodule(): return None @Chapel() def hello_inline(): """ writeln("Hello from inline."); """ return None if __name__ == "__main__": hello_mymodule() hello_inline()
from pych.extern import Chapel import os currentloc = os.getcwd(); # Note: depends on test living in a specific location relative to # mymodule.chpl. Not ideal, but also not a huge issue. @Chapel(sfile=currentloc + "/../../../module/ext/src/mymodule.chpl") def hello_mymodule(): return None @Chapel() def hello_i...
Use repository hierarchy instead of absolute path for sfile
Use repository hierarchy instead of absolute path for sfile The test chapel.sfile-inline.py was depending on an absolute path to find the location of a chapel file that was outside the normal sfile storage location. The absolute location was both machine and user-specific. I replaced the path with a relative path tha...
Python
apache-2.0
chapel-lang/pychapel,chapel-lang/pychapel,russel/pychapel,safl/pychapel,chapel-lang/pychapel,safl/pychapel,safl/pychapel,russel/pychapel,russel/pychapel,safl/pychapel
--- +++ @@ -1,6 +1,11 @@ from pych.extern import Chapel +import os -@Chapel(sfile="/home/safl/pychapel/module/ext/src/mymodule.chpl") +currentloc = os.getcwd(); + +# Note: depends on test living in a specific location relative to +# mymodule.chpl. Not ideal, but also not a huge issue. +@Chapel(sfile=currentloc + ...
6b23446292ce8e35f1e4fd5fa0bb73ca5596eddb
plotly/tests/test_core/test_plotly/test_credentials.py
plotly/tests/test_core/test_plotly/test_credentials.py
import plotly.plotly.plotly as py import plotly.tools as tls def test_get_credentials(): if 'username' in py._credentials: del py._credentials['username'] if 'api_key' in py._credentials: del py._credentials['api_key'] creds = py.get_credentials() file_creds = tls.get_credentials_file(...
from unittest import TestCase import plotly.plotly.plotly as py import plotly.tools as tls def test_get_credentials(): if 'username' in py._credentials: del py._credentials['username'] if 'api_key' in py._credentials: del py._credentials['api_key'] creds = py.get_credentials() file_cre...
Add a test for get_config()
Add a test for get_config()
Python
mit
ee-in/python-api,plotly/python-api,plotly/plotly.py,ee-in/python-api,plotly/plotly.py,ee-in/python-api,plotly/python-api,plotly/python-api,plotly/plotly.py
--- +++ @@ -1,3 +1,4 @@ +from unittest import TestCase import plotly.plotly.plotly as py import plotly.tools as tls @@ -25,3 +26,22 @@ assert creds['api_key'] == ak # TODO, and check it! # assert creds['stream_ids'] == si + + +class TestSignIn(TestCase): + + def test_get_config(self): + p...
90974a088813dcc3a0c4a7cae5758f67c4b52a15
qual/tests/test_calendar.py
qual/tests/test_calendar.py
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def test_valid_date(self): d = self.calendar.date(1200, 2, 29) self.assertIsNotNone(d)
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNon...
Check a leap year date from before the start of the calendar.
Check a leap year date from before the start of the calendar. This is not really a strong test of the proleptic calendar. All days back to year 1 which are valid in the Julian calendar are valid in the Gregorian calendar.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
--- +++ @@ -8,7 +8,10 @@ def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() - def test_valid_date(self): - d = self.calendar.date(1200, 2, 29) + def check_valid_date(self, year, month, day): + d = self.calendar.date(year, month, day) self.assertIsNotNone(d)...
dc70fb35a104e260b40425fce23cba84b9770994
addons/event/models/res_partner.py
addons/event/models/res_partner.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResPartner(models.Model): _inherit = 'res.partner' event_count = fields.Integer("Events", compute='_compute_event_count', help="Number of events the partner has partic...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResPartner(models.Model): _inherit = 'res.partner' event_count = fields.Integer("Events", compute='_compute_event_count', help="Number of events the partner has partic...
Set default value for event_count
[FIX] event: Set default value for event_count Fixes https://github.com/odoo/odoo/pull/39583 This commit adds a default value for event_count Assigning default value for non-stored compute fields is required in 13.0 closes odoo/odoo#39974 X-original-commit: 9ca72b98f54d7686c0e6019870b40f14dbdd2881 Signed-off-by: Vi...
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
--- +++ @@ -9,6 +9,7 @@ event_count = fields.Integer("Events", compute='_compute_event_count', help="Number of events the partner has participated.") def _compute_event_count(self): + self.event_count = 0 if not self.user_has_groups('event.group_event_user'): return f...
4f776ca2260419c06c2594568c73ce279426d039
GenotypeNetwork/test_genotype_network.py
GenotypeNetwork/test_genotype_network.py
import GenotypeNetwork as gn import os import networkx as nx GN = gn.GenotypeNetwork() GN.read_sequences('test/Demo_052715.fasta') GN.generate_genotype_network() GN.write_genotype_network('test/Demo_052715.pkl') GN.read_genotype_network('test/Demo_052715.pkl') def test_read_sequences_works_correctly(): """ C...
import GenotypeNetwork as gn import os import networkx as nx # Change cwd for tests to the current path. here = os.path.dirname(os.path.realpath(__file__)) os.chdir(here) GN = gn.GenotypeNetwork() GN.read_sequences('test/Demo_052715.fasta') GN.generate_genotype_network() GN.write_genotype_network('test/Demo_052715.pk...
Make tests run from correct directory.
Make tests run from correct directory.
Python
mit
ericmjl/genotype-network
--- +++ @@ -1,6 +1,10 @@ import GenotypeNetwork as gn import os import networkx as nx + +# Change cwd for tests to the current path. +here = os.path.dirname(os.path.realpath(__file__)) +os.chdir(here) GN = gn.GenotypeNetwork() GN.read_sequences('test/Demo_052715.fasta')
43f58f5378dda9c90f4d891d22d6f44debb3700e
service/es_access.py
service/es_access.py
from elasticsearch import Elasticsearch from elasticsearch_dsl import Search from service import app ELASTICSEARCH_ENDPOINT = app.config['ELASTIC_SEARCH_ENDPOINT'] MAX_NUMBER_SEARCH_RESULTS = app.config['MAX_NUMBER_SEARCH_RESULTS'] # TODO: write integration tests for this module def get_properties_for_postcode(postc...
from elasticsearch import Elasticsearch from elasticsearch_dsl import Search from service import app ELASTICSEARCH_ENDPOINT = app.config['ELASTIC_SEARCH_ENDPOINT'] MAX_NUMBER_SEARCH_RESULTS = app.config['MAX_NUMBER_SEARCH_RESULTS'] # TODO: write integration tests for this module def get_properties_for_postcode(postc...
Order only by house/initial number then address string
Order only by house/initial number then address string
Python
mit
LandRegistry/digital-register-api,LandRegistry/digital-register-api
--- +++ @@ -10,15 +10,7 @@ def get_properties_for_postcode(postcode): search = create_search('property_by_postcode_3') query = search.filter('term', postcode=postcode).sort( - {'street_name': {'missing': '_last'}}, - {'house_no': {'missing': '_last'}}, - {'house_alpha': {'missing': '_l...
453af98b1a05c62acd55afca431236d8f54fdae3
test_bert_trainer.py
test_bert_trainer.py
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(out...
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(out...
Test for deterministic results when testing BERT model
Test for deterministic results when testing BERT model
Python
apache-2.0
googleinterns/smart-news-query-embeddings,googleinterns/smart-news-query-embeddings
--- +++ @@ -24,6 +24,10 @@ trainer.train(train_features, label_list) results = trainer.test(test_features) print('Evaluation results:', results) + results2 = trainer.test(test_features) + print('Evaluation results:', results2) + eval_acc1, eval_acc2 = results['eval_accu...
1d3e956dcf667601feb871eab2a462fa09d0d101
tests/test_length.py
tests/test_length.py
from math import sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_le...
from math import fabs, sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import floats, isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)],...
Test the axioms of normed vector spaces
tests/length: Test the axioms of normed vector spaces
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
--- +++ @@ -1,10 +1,10 @@ -from math import sqrt +from math import fabs, sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector -from utils import isclose, vectors +from utils import floats, isclose, vectors @pytest.mark.parametrize( @@ -24,3 +24,21 @@ def test_leng...
21e03d5f22cc7952bdb12912bd5498755855925a
trac/web/__init__.py
trac/web/__init__.py
# With mod_python we'll have to delay importing trac.web.api until # modpython_frontend.handler() has been called since the # PYTHON_EGG_CACHE variable is set from there # # TODO: Remove this once the Genshi zip_safe issue has been resolved. import os from pkg_resources import get_distribution if not os.path.isdir(get_...
# Workaround for http://bugs.python.org/issue6763 and # http://bugs.python.org/issue5853 thread issues import mimetypes mimetypes.init() # With mod_python we'll have to delay importing trac.web.api until # modpython_frontend.handler() has been called since the # PYTHON_EGG_CACHE variable is set from there # # TODO: Re...
Fix race condition during `mimetypes` initialization.
Fix race condition during `mimetypes` initialization. Initial patch from Steven R. Loomis. Closes #8629. git-svn-id: eda3d06fcef731589ace1b284159cead3416df9b@9740 af82e41b-90c4-0310-8c96-b1721e28e2e2
Python
bsd-3-clause
netjunki/trac-Pygit2,jun66j5/trac-ja,jun66j5/trac-ja,netjunki/trac-Pygit2,jun66j5/trac-ja,walty8/trac,walty8/trac,jun66j5/trac-ja,walty8/trac,netjunki/trac-Pygit2,walty8/trac
--- +++ @@ -1,8 +1,14 @@ +# Workaround for http://bugs.python.org/issue6763 and +# http://bugs.python.org/issue5853 thread issues +import mimetypes +mimetypes.init() + # With mod_python we'll have to delay importing trac.web.api until # modpython_frontend.handler() has been called since the # PYTHON_EGG_CACHE vari...
675b860af3576251b32d14b10600f756fd1aebdf
tests/chainer_tests/functions_tests/math_tests/test_sqrt.py
tests/chainer_tests/functions_tests/math_tests/test_sqrt.py
import unittest import numpy import chainer.functions as F from chainer import testing def make_data(dtype, shape): x = numpy.random.uniform(0.1, 1, shape).astype(dtype) gy = numpy.random.uniform(-1, 1, shape).astype(dtype) return x, gy # # sqrt @testing.math_function_test(F.sqrt, make_data=make_data...
import unittest import numpy import chainer.functions as F from chainer import testing def make_data(dtype, shape): x = numpy.random.uniform(0.1, 5, shape).astype(dtype) gy = numpy.random.uniform(-1, 1, shape).astype(dtype) return x, gy # # sqrt @testing.math_function_test(F.sqrt, make_data=make_data...
Use larger values for stable test.
Use larger values for stable test.
Python
mit
cupy/cupy,ktnyt/chainer,ronekko/chainer,okuta/chainer,aonotas/chainer,keisuke-umezawa/chainer,jnishi/chainer,tkerola/chainer,jnishi/chainer,cupy/cupy,wkentaro/chainer,pfnet/chainer,okuta/chainer,hvy/chainer,chainer/chainer,okuta/chainer,hvy/chainer,niboshi/chainer,kiyukuta/chainer,wkentaro/chainer,wkentaro/chainer,keis...
--- +++ @@ -7,7 +7,7 @@ def make_data(dtype, shape): - x = numpy.random.uniform(0.1, 1, shape).astype(dtype) + x = numpy.random.uniform(0.1, 5, shape).astype(dtype) gy = numpy.random.uniform(-1, 1, shape).astype(dtype) return x, gy
052f06b0ef4f3c2befaf0cbbfd605e42553b48da
h2o-hadoop-common/tests/python/pyunit_trace.py
h2o-hadoop-common/tests/python/pyunit_trace.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- import sys import os sys.path.insert(1, os.path.join("..","..","..")) import h2o from h2o.exceptions import H2OServerError from tests import pyunit_utils def trace_request(): err = None try: h2o.api("TRACE /") except H2OServerError as e: err ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- import sys, os sys.path.insert(1, os.path.join("..", "..", "..", "h2o-py")) import h2o from h2o.exceptions import H2OServerError from tests import pyunit_utils def trace_request(): err = None try: h2o.api("TRACE /") except H2OServerError as e: ...
Fix TRACE test also in rel-yau
Fix TRACE test also in rel-yau
Python
apache-2.0
h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3
--- +++ @@ -1,8 +1,7 @@ #!/usr/bin/env python # -*- encoding: utf-8 -*- -import sys -import os -sys.path.insert(1, os.path.join("..","..","..")) +import sys, os +sys.path.insert(1, os.path.join("..", "..", "..", "h2o-py")) import h2o from h2o.exceptions import H2OServerError from tests import pyunit_utils @@ -15...
209a8e029e14766027376bb6d8f0b2e0a4a07f1b
simulator-perfect.py
simulator-perfect.py
#!/usr/bin/env python3 import timer import sys import utils # A set of files already in the storage seen = set() # The total number of uploads total_uploads = 0 # The number of files in the storage files_in = 0 tmr = timer.Timer() for (hsh, _) in utils.read_upload_stream(): if hsh not in seen: files_in ...
#!/usr/bin/env python3 import timer import sys import utils def simulate(): # A set of files already in the storage seen = set() # The size of the all uploads combined (deduplicated or not) total_in = 0 # The size of the data sent to the service data_in = 0 tmr = timer.Timer() for (...
Modify the perfect simulator to calculate dedup percentages based on file sizes (1 - data_in / data_total)
Modify the perfect simulator to calculate dedup percentages based on file sizes (1 - data_in / data_total)
Python
apache-2.0
sjakthol/dedup-simulator,sjakthol/dedup-simulator
--- +++ @@ -3,30 +3,36 @@ import sys import utils -# A set of files already in the storage -seen = set() -# The total number of uploads -total_uploads = 0 +def simulate(): + # A set of files already in the storage + seen = set() -# The number of files in the storage -files_in = 0 + # The size of the ...
dbe57e9b76194b13d90834163ebe8bf924464dd0
src/mcedit2/util/lazyprop.py
src/mcedit2/util/lazyprop.py
""" ${NAME} """ from __future__ import absolute_import, division, print_function, unicode_literals import logging log = logging.getLogger(__name__) def lazyprop(fn): """ Lazily computed property wrapper. >>> class Foo(object): ... @lazyprop ... def func(self): ... print("B...
""" ${NAME} """ from __future__ import absolute_import, division, print_function, unicode_literals import logging import weakref log = logging.getLogger(__name__) def lazyprop(fn): """ Lazily computed property wrapper. >>> class Foo(object): ... @lazyprop ... def func(self): ... ...
Add a property descriptor for weakref'd members
Add a property descriptor for weakref'd members
Python
bsd-3-clause
vorburger/mcedit2,Rubisk/mcedit2,Rubisk/mcedit2,vorburger/mcedit2
--- +++ @@ -3,6 +3,8 @@ """ from __future__ import absolute_import, division, print_function, unicode_literals import logging +import weakref + log = logging.getLogger(__name__) def lazyprop(fn): @@ -44,3 +46,16 @@ return _lazyprop + +class weakrefprop(object): + def __init__(self, name): + ...