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
c2789dd620a6f6d4c08e4608e94656a0d2b906c7
parsimonious/utils.py
parsimonious/utils.py
"""General tools which don't depend on other parts of Parsimonious""" import ast from sys import version_info from six import python_2_unicode_compatible class StrAndRepr(object): """Mix-in to add a ``__str__`` and ``__repr__`` which return the UTF-8-encoded value of ``__unicode__``""" if version_info >= (3,): # Don't return the "bytes" type from Python 3's __str__: def __repr__(self): return self.__str__() else: def __repr__(self): return self.__str__().encode('utf-8') def evaluate_string(string): """Piggyback on Python's string support so we can have backslash escaping and niceties like \n, \t, etc. string.decode('string_escape') would have been a lower-level possibility. """ return ast.literal_eval(string) @python_2_unicode_compatible class Token(StrAndRepr): """A class to represent tokens, for use with TokenGrammars You will likely want to subclass this to hold additional information, like the characters that you lexed to create this token. Alternately, feel free to create your own class from scratch. The only contract is that tokens must have a ``type`` attr. """ __slots__ = ['type'] def __init__(self, type): self.type = type def __str__(self): return u'<Token "%s">' % (self.type,) def __eq__(self, other): return self.type == other.type
"""General tools which don't depend on other parts of Parsimonious""" import ast from six import python_2_unicode_compatible class StrAndRepr(object): """Mix-in to which gives the class the same __repr__ and __str__.""" def __repr__(self): return self.__str__() def evaluate_string(string): """Piggyback on Python's string support so we can have backslash escaping and niceties like \n, \t, etc. string.decode('string_escape') would have been a lower-level possibility. """ return ast.literal_eval(string) @python_2_unicode_compatible class Token(StrAndRepr): """A class to represent tokens, for use with TokenGrammars You will likely want to subclass this to hold additional information, like the characters that you lexed to create this token. Alternately, feel free to create your own class from scratch. The only contract is that tokens must have a ``type`` attr. """ __slots__ = ['type'] def __init__(self, type): self.type = type def __str__(self): return u'<Token "%s">' % (self.type,) def __eq__(self, other): return self.type == other.type
Fix a bug in unicode encoding of reprs.
Fix a bug in unicode encoding of reprs. The previous implementation could lead to double-decoding: >>> from parsimonious.utils import Token >>> repr(Token('asdf')) '<Token "asdf">' >>> repr(Token(u'💣')) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "parsimonious/utils.py", line 19, in __repr__ return self.__str__().encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xf0 in position 8: ordinal not in range(128)
Python
mit
lucaswiman/parsimonious,erikrose/parsimonious
--- +++ @@ -1,22 +1,15 @@ """General tools which don't depend on other parts of Parsimonious""" import ast -from sys import version_info from six import python_2_unicode_compatible class StrAndRepr(object): - """Mix-in to add a ``__str__`` and ``__repr__`` which return the - UTF-8-encoded value of ``__unicode__``""" + """Mix-in to which gives the class the same __repr__ and __str__.""" - if version_info >= (3,): - # Don't return the "bytes" type from Python 3's __str__: - def __repr__(self): - return self.__str__() - else: - def __repr__(self): - return self.__str__().encode('utf-8') + def __repr__(self): + return self.__str__() def evaluate_string(string):
c32165b680356fe9f1e422a1d11127f867065f94
wiring/categories.py
wiring/categories.py
__all__ = ( 'Category', ) class Category(tuple): """ This type acts as tuple with one key difference - two instances of it are equal only when they have the same type. This allows you to easily mitigate collisions when using common types (like string) in a dict or as a Wiring :term:`specification`. Example:: from wiring import Graph, Category class Public(Category): pass class Secret(Category): pass graph = Graph() graph.register_instance(Public('database', 1), 'db://public/1') graph.register_instance(Private('database', 1), 'db://private/1') assert Public('database', 1) != Private('database', 1) assert ( graph.get(Public('database', 1)) != graph.get(Private('database', 1)) ) """ def __new__(cls, *args): return super(Category, cls).__new__(cls, args) def __repr__(self): return type(self).__name__ + super(Category, self).__repr__() def __str__(self): return repr(self) def __eq__(self, other): return ( type(self) == type(other) and super(Category, self).__eq__(other) ) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(( type(self), super(Category, self).__hash__() ))
__all__ = ( 'Category', ) class Category(tuple): """ This type acts as tuple with one key difference - two instances of it are equal only when they have the same type. This allows you to easily mitigate collisions when using common types (like string) in a dict or as a Wiring :term:`specification`. Example:: from wiring import Graph, Category class Public(Category): pass class Secret(Category): pass graph = Graph() graph.register_instance(Public('database', 1), 'db://public/1') graph.register_instance(Secret('database', 1), 'db://private/1') assert Public('database', 1) != Private('database', 1) assert ( graph.get(Public('database', 1)) != graph.get(Private('database', 1)) ) """ def __new__(cls, *args): return super(Category, cls).__new__(cls, args) def __repr__(self): return type(self).__name__ + super(Category, self).__repr__() def __str__(self): return repr(self) def __eq__(self, other): return ( type(self) == type(other) and super(Category, self).__eq__(other) ) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(( type(self), super(Category, self).__hash__() ))
Fix error in docstring example.
Fix error in docstring example.
Python
apache-2.0
msiedlarek/wiring,msiedlarek/wiring
--- +++ @@ -22,7 +22,7 @@ graph = Graph() graph.register_instance(Public('database', 1), 'db://public/1') - graph.register_instance(Private('database', 1), 'db://private/1') + graph.register_instance(Secret('database', 1), 'db://private/1') assert Public('database', 1) != Private('database', 1) assert (
72f93daa9d47a37e374605610043a24731aef7a8
test/test_sampling.py
test/test_sampling.py
# -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stat, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=5) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stat(profiler.stats, 'spin_100ms') stat2 = find_stat(profiler.stats, 'spin_500ms') ratio = stat1.deep_count / stat2.deep_count assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5
# -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stat, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stat(profiler.stats, 'spin_100ms') stat2 = find_stat(profiler.stats, 'spin_500ms') ratio = stat1.deep_count / stat2.deep_count assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5
Increase re-running limit of test_profiler
Increase re-running limit of test_profiler
Python
bsd-3-clause
sublee/profiling,JeanPaulShapo/profiling,JeanPaulShapo/profiling,what-studio/profiling,what-studio/profiling,sublee/profiling
--- +++ @@ -17,7 +17,7 @@ spin(0.5) -@pytest.mark.flaky(reruns=5) +@pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001))
79ff39c4d6a5ad91a32cfdc7b59a89fa5461d244
MongoHN/forms.py
MongoHN/forms.py
""" MongoHN.forms - WTForms used by MongoHN """ from MongoHN.models import User from flask.ext.wtf import Form from wtforms import SubmitField, TextField, BooleanField, PasswordField from wtforms.validators import Required, DataRequired class LoginForm(Form): username = TextField('Username', validators = [ Required() ]) password = PasswordField('Password', validators = [ Required() ]) remember_me = BooleanField('remember_me', default = False) submit = SubmitField('Login') def validate(self): rv = Form.validate(self) if not rv: return False user = User.objects(username=self.username.data).first() if user is None: self.username.errors.append('Unknown username') return False if not user.check_password(self.password.data): self.password.errors.append('Invalid password') return False self.user = user return True class RegistrationForm(Form): username = TextField('Username', validators=[ DataRequired() ]) password = PasswordField('Password', validators=[ DataRequired() ]) email = TextField('Email', validators=[ DataRequired() ]) submit = SubmitField('Register', validators=[ Required() ]) def validate_username(form, field): if User.objects(username=field.data).first(): raise ValueError("Username already exists.") def create_user(self): user = User() user.username = self.username.data user.password = self.password.data user.email = self.email.data user.save() self.user = user #
""" MongoHN.forms - WTForms used by MongoHN """ from MongoHN.models import User from flask.ext.wtf import Form from wtforms import SubmitField, TextField, BooleanField, PasswordField from wtforms.validators import Required, DataRequired, ValidationError class LoginForm(Form): username = TextField('Username', validators = [ Required() ]) password = PasswordField('Password', validators = [ Required() ]) remember_me = BooleanField('remember_me', default = False) submit = SubmitField('Login') def validate(self): rv = Form.validate(self) if not rv: return False user = User.objects(username=self.username.data).first() if user is None: self.username.errors.append('Unknown username') return False if not user.check_password(self.password.data): self.password.errors.append('Invalid password') return False self.user = user return True class RegistrationForm(Form): username = TextField('Username', validators=[ DataRequired() ]) password = PasswordField('Password', validators=[ DataRequired() ]) email = TextField('Email', validators=[ DataRequired() ]) submit = SubmitField('Register', validators=[ Required() ]) def validate_username(form, field): if User.objects(username=field.data).first(): raise ValidationError("Username already exists.") def create_user(self): user = User() user.username = self.username.data user.password = self.password.data user.email = self.email.data user.save() self.user = user #
Use ValidationError rather than ValueError
Use ValidationError rather than ValueError
Python
mit
bsandrow/MongoHN,bsandrow/MongoHN
--- +++ @@ -3,7 +3,7 @@ from MongoHN.models import User from flask.ext.wtf import Form from wtforms import SubmitField, TextField, BooleanField, PasswordField -from wtforms.validators import Required, DataRequired +from wtforms.validators import Required, DataRequired, ValidationError class LoginForm(Form): username = TextField('Username', validators = [ Required() ]) @@ -37,7 +37,7 @@ def validate_username(form, field): if User.objects(username=field.data).first(): - raise ValueError("Username already exists.") + raise ValidationError("Username already exists.") def create_user(self): user = User()
3e5af3f8ba0eacc8f29e51daec43e395eae27ab8
partner_email_check/models/res_partner.py
partner_email_check/models/res_partner.py
# Copyright 2019 Komit <https://komit-consulting.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import logging from odoo import api, models, _ from odoo.exceptions import UserError _logger = logging.getLogger(__name__) try: from validate_email import validate_email except ImportError: _logger.error('Cannot import "validate_email".') def validate_email(email): _logger.warning( 'Can not validate email, ' 'python dependency required "validate_email"') return True class ResPartner(models.Model): _inherit = 'res.partner' @api.constrains('email') def constrains_email(self): for rec in self.filtered("email"): self.email_check(rec.email) @api.model def email_check(self, email): if validate_email(email): return True raise UserError(_('Invalid e-mail!'))
# Copyright 2019 Komit <https://komit-consulting.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import logging from odoo import api, models, _ from odoo.exceptions import UserError _logger = logging.getLogger(__name__) try: from validate_email import validate_email except ImportError: _logger.debug('Cannot import "validate_email".') def validate_email(email): _logger.warning( 'Can not validate email, ' 'python dependency required "validate_email"') return True class ResPartner(models.Model): _inherit = 'res.partner' @api.constrains('email') def constrains_email(self): for rec in self.filtered("email"): self.email_check(rec.email) @api.model def email_check(self, email): if validate_email(email): return True raise UserError(_('Invalid e-mail!'))
Make debugger record a debug message instead of error when importing validate_email in partner_email_check
[FIX][11.0] Make debugger record a debug message instead of error when importing validate_email in partner_email_check
Python
agpl-3.0
Vauxoo/partner-contact,Vauxoo/partner-contact
--- +++ @@ -10,7 +10,7 @@ try: from validate_email import validate_email except ImportError: - _logger.error('Cannot import "validate_email".') + _logger.debug('Cannot import "validate_email".') def validate_email(email): _logger.warning(
543c7307f26553d78bf3f18b5f93a2bc23cfb875
reports/admin.py
reports/admin.py
# coding: utf-8 from django.contrib import admin from .models import Report class ReportAdmin(admin.ModelAdmin): list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at') list_filter = ['created_at'] search_fields = ['addressed_to', 'reported_from', 'content', 'signed_from'] admin.site.register(Report, ReportAdmin)
# coding: utf-8 from django.contrib import admin from .models import Report class ReportAdmin(admin.ModelAdmin): list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at') list_filter = ['created_at', 'content'] search_fields = ['addressed_to', 'reported_from__username', 'content', 'signed_from'] admin.site.register(Report, ReportAdmin)
Fix some issues, because of models change
Fix some issues, because of models change
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
--- +++ @@ -4,7 +4,7 @@ class ReportAdmin(admin.ModelAdmin): list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at') - list_filter = ['created_at'] - search_fields = ['addressed_to', 'reported_from', 'content', 'signed_from'] + list_filter = ['created_at', 'content'] + search_fields = ['addressed_to', 'reported_from__username', 'content', 'signed_from'] admin.site.register(Report, ReportAdmin)
c553db9e84344897ca995f56c710944da88c0a56
packages/syft/src/syft/core/node/domain/domain_interface.py
packages/syft/src/syft/core/node/domain/domain_interface.py
# third party from pydantic import BaseSettings # relative from ...adp.adversarial_accountant import AdversarialAccountant from ..abstract.node_service_interface import NodeServiceInterface from ..common.node_manager.association_request_manager import AssociationRequestManager from ..common.node_manager.dataset_manager import DatasetManager from ..common.node_manager.group_manager import GroupManager from ..common.node_manager.role_manager import RoleManager from ..common.node_manager.setup_manager import SetupManager from ..common.node_manager.user_manager import UserManager class DomainInterface(NodeServiceInterface): groups: GroupManager users: UserManager roles: RoleManager association_requests: AssociationRequestManager datasets: DatasetManager setup: SetupManager acc: AdversarialAccountant settings: BaseSettings
# third party from pydantic import BaseSettings # relative from ...adp.adversarial_accountant import AdversarialAccountant from ..abstract.node_service_interface import NodeServiceInterface from ..common.node_manager.association_request_manager import AssociationRequestManager from ..common.node_manager.dataset_manager import DatasetManager from ..common.node_manager.role_manager import RoleManager from ..common.node_manager.setup_manager import SetupManager from ..common.node_manager.user_manager import UserManager class DomainInterface(NodeServiceInterface): users: UserManager roles: RoleManager association_requests: AssociationRequestManager datasets: DatasetManager setup: SetupManager acc: AdversarialAccountant settings: BaseSettings
Remove groups attribute from DomainInterface
Remove groups attribute from DomainInterface
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
--- +++ @@ -6,14 +6,12 @@ from ..abstract.node_service_interface import NodeServiceInterface from ..common.node_manager.association_request_manager import AssociationRequestManager from ..common.node_manager.dataset_manager import DatasetManager -from ..common.node_manager.group_manager import GroupManager from ..common.node_manager.role_manager import RoleManager from ..common.node_manager.setup_manager import SetupManager from ..common.node_manager.user_manager import UserManager class DomainInterface(NodeServiceInterface): - groups: GroupManager users: UserManager roles: RoleManager association_requests: AssociationRequestManager
d7d1200846a3e19eb9399b3c47ec553e8c118046
smap-nepse/preprocessing/feat_select.py
smap-nepse/preprocessing/feat_select.py
import pandas as pd from sklearn.feature_selection import SelectKBest, f_classif def select_kbest_clf(data_frame, target, k=4): """ Selecting K-Best features for classification :param data_frame: A pandas dataFrame with the training data :param target: target variable name in DataFrame :param k: desired number of features from the data :returns feature_scores: scores for each feature in the data as pandas DataFrame """ feat_selector = SelectKBest(f_classif, k=k) _ = feat_selector.fit(data_frame.drop(target, axis=1), data_frame[target]) feat_scores = pd.DataFrame() feat_scores["F Score"] = feat_selector.scores_ feat_scores["P Value"] = feat_selector.pvalues_ feat_scores["Support"] = feat_selector.get_support() feat_scores["Attribute"] = data_frame.drop(target, axis=1).columns return feat_scores df = pd.read_csv("NABIL.csv") df.drop(df.columns[[1]], axis=1, inplace=True) #print(df.columns) kbest_feat = select_kbest_clf(df, 'Signal', k=4) kbest_feat = kbest_feat.sort(["F Score", "P Value"], ascending=[False, False]) print(kbest_feat)
import pandas as pd from sklearn.feature_selection import SelectKBest, f_classif def select_kbest_clf(data_frame, target, k=4): """ Selecting K-Best features for classification :param data_frame: A pandas dataFrame with the training data :param target: target variable name in DataFrame :param k: desired number of features from the data :returns feature_scores: scores for each feature in the data as pandas DataFrame """ feat_selector = SelectKBest(f_classif, k=k) _ = feat_selector.fit(data_frame.drop(target, axis=1), data_frame[target]) feat_scores = pd.DataFrame() feat_scores["F Score"] = feat_selector.scores_ feat_scores["P Value"] = feat_selector.pvalues_ feat_scores["Support"] = feat_selector.get_support() feat_scores["Attribute"] = data_frame.drop(target, axis=1).columns return feat_scores df = pd.read_csv("NABIL.csv") df.drop(df.columns[[0,1,9,13]], axis=1, inplace=True) df.drop(df.index[:19],inplace=True) kbest_feat = select_kbest_clf(df, 'Updown', k=4) kbest_feat = kbest_feat.sort(["F Score", "P Value"], ascending=[False, False]) print("\nFeature scores using classification method \n") print(kbest_feat)
Select features using classification model
Select features using classification model
Python
mit
samshara/Stock-Market-Analysis-and-Prediction
--- +++ @@ -22,10 +22,11 @@ return feat_scores df = pd.read_csv("NABIL.csv") -df.drop(df.columns[[1]], axis=1, inplace=True) -#print(df.columns) +df.drop(df.columns[[0,1,9,13]], axis=1, inplace=True) +df.drop(df.index[:19],inplace=True) +kbest_feat = select_kbest_clf(df, 'Updown', k=4) +kbest_feat = kbest_feat.sort(["F Score", "P Value"], ascending=[False, False]) +print("\nFeature scores using classification method \n") +print(kbest_feat) -kbest_feat = select_kbest_clf(df, 'Signal', k=4) -kbest_feat = kbest_feat.sort(["F Score", "P Value"], ascending=[False, False]) -print(kbest_feat)
d50703ee3da5feb264c53d622c039a0bde67d233
airplay-sniff.py
airplay-sniff.py
#!/usr/bin/env python2 from scapy.all import * def airplay_callback(pkt): try: if pkt['Raw'].load[0:5] == 'SETUP': # Someone is starting to play! Add them to the list yo with open('/tmp/playing.txt', 'w') as f: f.write(pkt[IP].src) print "Updated playing.txt to " + pkt[IP].src elif pkt['Raw'].load[0:5] == 'TEARD': # Someone is getting *off* those speakers, yo with open('/tmp/playing.txt', 'w') as f: pass # Rewrite it with nothing print "Updated playing.txt to be blank" except: pass # meh sniff(filter="tcp and port 5000", store=0, prn=airplay_callback);
#!/usr/bin/env python2 from scapy.all import * cur_ip = False def airplay_callback(pkt): try: if pkt[IP].sprintf('%proto%') == 'tcp': # This could be anything! Parse further if pkt['Raw'].load[0:5] == 'TEARD': # Anyone can teardown, only remove the IP if it's the currently playing person global cur_ip if cur_ip == pkt[IP].src: # Someone is getting *off* those speakers, yo with open('/tmp/playing.txt', 'w') as f: pass # Rewrite it with nothing print "Updated playing.txt to be blank" else: # Should be UDP if cur_ip != pkt[IP].src: # A new person! with open('/tmp/playing.txt', 'w') as f: f.write(pkt[IP].src) cur_ip = pkt[IP].src print "Updated playing.txt to " + pkt[IP].src except: pass # meh sniff(filter="port 5000 or port 6001", store=0, prn=airplay_callback);
Change sniffing to be more robust
Change sniffing to be more robust Known bugs: Will update playing.txt when someone tries to use the speakers if already in use. Saving grace is it'll change to the right person a second later.
Python
bsd-2-clause
ss23/airplay-control-intercept,ss23/airplay-control-intercept,ss23/airplay-control-intercept
--- +++ @@ -1,18 +1,28 @@ #!/usr/bin/env python2 from scapy.all import * +cur_ip = False + def airplay_callback(pkt): try: - if pkt['Raw'].load[0:5] == 'SETUP': - # Someone is starting to play! Add them to the list yo - with open('/tmp/playing.txt', 'w') as f: - f.write(pkt[IP].src) - print "Updated playing.txt to " + pkt[IP].src - elif pkt['Raw'].load[0:5] == 'TEARD': - # Someone is getting *off* those speakers, yo - with open('/tmp/playing.txt', 'w') as f: - pass # Rewrite it with nothing - print "Updated playing.txt to be blank" + if pkt[IP].sprintf('%proto%') == 'tcp': + # This could be anything! Parse further + if pkt['Raw'].load[0:5] == 'TEARD': + # Anyone can teardown, only remove the IP if it's the currently playing person + global cur_ip + if cur_ip == pkt[IP].src: + # Someone is getting *off* those speakers, yo + with open('/tmp/playing.txt', 'w') as f: + pass # Rewrite it with nothing + print "Updated playing.txt to be blank" + else: + # Should be UDP + if cur_ip != pkt[IP].src: + # A new person! + with open('/tmp/playing.txt', 'w') as f: + f.write(pkt[IP].src) + cur_ip = pkt[IP].src + print "Updated playing.txt to " + pkt[IP].src except: pass # meh -sniff(filter="tcp and port 5000", store=0, prn=airplay_callback); +sniff(filter="port 5000 or port 6001", store=0, prn=airplay_callback);
6b9c9f98ce10db9e9a767c1ae81c0655c9d4d28c
runtests.py
runtests.py
#!/usr/bin/env python import os import sys import subprocess from importlib import import_module if __name__ == '__main__': # Test using django.test.runner.DiscoverRunner os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' # We need to use subprocess.call instead of django's execute_from_command_line # because we can only setup django's settings once, and it's bad # practice to change them at runtime subprocess.call(['django-admin', 'test', '--nomigrations']) subprocess.call(['django-admin', 'test', '-n']) # Test using django_nose.NoseTestSuiteRunner os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.nose_settings' for module in ('nose', 'django_nose',): try: import_module(module) except ImportError: print("Testing failed: could not import {0}, try pip installing it".format(module)) sys.exit(1) # Add pdb flag is this is only supported by nose subprocess.call(['django-admin', 'test', 'tests.myapp.nose_tests', '--nomigrations', '--pdb']) subprocess.call(['django-admin', 'test', 'tests.myapp.nose_tests', '-n', '--pdb'])
#!/usr/bin/env python import os import sys import subprocess from importlib import import_module if __name__ == '__main__': # Test using django.test.runner.DiscoverRunner os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' # We need to use subprocess.call instead of django's execute_from_command_line # because we can only setup django's settings once, and it's bad # practice to change them at runtime subprocess.call(['django-admin', 'test', '--nomigrations']) subprocess.call(['django-admin', 'test', '-n']) # Test using django_nose.NoseTestSuiteRunner os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.nose_settings' for module in ('nose', 'django_nose',): try: import_module(module) except ImportError: print("Testing failed: could not import {0}, try pip installing it".format(module)) sys.exit(1) # Add pdb flag as this is only supported by nose subprocess.call(['django-admin', 'test', 'tests.myapp.nose_tests', '--nomigrations', '--pdb']) subprocess.call(['django-admin', 'test', 'tests.myapp.nose_tests', '-n', '--pdb'])
Fix typo is -> as
Fix typo is -> as
Python
mit
henriquebastos/django-test-without-migrations,henriquebastos/django-test-without-migrations
--- +++ @@ -26,6 +26,6 @@ print("Testing failed: could not import {0}, try pip installing it".format(module)) sys.exit(1) - # Add pdb flag is this is only supported by nose + # Add pdb flag as this is only supported by nose subprocess.call(['django-admin', 'test', 'tests.myapp.nose_tests', '--nomigrations', '--pdb']) subprocess.call(['django-admin', 'test', 'tests.myapp.nose_tests', '-n', '--pdb'])
5d812fbacab2970a1a601f8d801b08305873490d
src/ekklesia_portal/concepts/argument/argument_contracts.py
src/ekklesia_portal/concepts/argument/argument_contracts.py
from colander import Length from deform import Form from deform.widget import TextAreaWidget from ekklesia_portal.helper.contract import Schema, string_property from ekklesia_portal.helper.translation import _ class ArgumentSchema(Schema): title = string_property(title=_('title'), validator=Length(min=5, max=80)) abstract = string_property(title=_('abstract'), validator=Length(min=5, max=140)) details = string_property(title=_('details'), validator=Length(min=10, max=4096), missing='') argument_widgets = { 'abstract': TextAreaWidget(rows=2), 'details': TextAreaWidget(rows=4) } class ArgumentForm(Form): def __init__(self, request, action): super().__init__(ArgumentSchema(), request, action, buttons=("submit", )) self.set_widgets(argument_widgets)
from colander import Length from deform import Form from deform.widget import TextAreaWidget, TextInputWidget from ekklesia_portal.helper.contract import Schema, string_property from ekklesia_portal.helper.translation import _ TITLE_MAXLENGTH = 80 ABSTRACT_MAXLENGTH = 160 class ArgumentSchema(Schema): title = string_property(title=_('title'), validator=Length(min=5, max=TITLE_MAXLENGTH)) abstract = string_property(title=_('abstract'), validator=Length(min=5, max=ABSTRACT_MAXLENGTH)) details = string_property(title=_('details'), validator=Length(min=10, max=4096), missing='') argument_widgets = { 'title': TextInputWidget(attributes={'maxlength': TITLE_MAXLENGTH}), 'abstract': TextAreaWidget(rows=2, attributes={'maxlength': ABSTRACT_MAXLENGTH}), 'details': TextAreaWidget(rows=4) } class ArgumentForm(Form): def __init__(self, request, action): super().__init__(ArgumentSchema(), request, action, buttons=("submit", )) self.set_widgets(argument_widgets)
Add maxlength to argument form title and abstract
Add maxlength to argument form title and abstract
Python
agpl-3.0
dpausp/arguments,dpausp/arguments,dpausp/arguments,dpausp/arguments
--- +++ @@ -1,18 +1,23 @@ from colander import Length from deform import Form -from deform.widget import TextAreaWidget +from deform.widget import TextAreaWidget, TextInputWidget from ekklesia_portal.helper.contract import Schema, string_property from ekklesia_portal.helper.translation import _ +TITLE_MAXLENGTH = 80 +ABSTRACT_MAXLENGTH = 160 + + class ArgumentSchema(Schema): - title = string_property(title=_('title'), validator=Length(min=5, max=80)) - abstract = string_property(title=_('abstract'), validator=Length(min=5, max=140)) + title = string_property(title=_('title'), validator=Length(min=5, max=TITLE_MAXLENGTH)) + abstract = string_property(title=_('abstract'), validator=Length(min=5, max=ABSTRACT_MAXLENGTH)) details = string_property(title=_('details'), validator=Length(min=10, max=4096), missing='') argument_widgets = { - 'abstract': TextAreaWidget(rows=2), + 'title': TextInputWidget(attributes={'maxlength': TITLE_MAXLENGTH}), + 'abstract': TextAreaWidget(rows=2, attributes={'maxlength': ABSTRACT_MAXLENGTH}), 'details': TextAreaWidget(rows=4) }
8ee00372c7ae005d6060ac2813a13b8db447b292
stock_request_direction/models/stock_request_order.py
stock_request_direction/models/stock_request_order.py
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' direction = fields.Selection([('outbound', 'Outbound'), ('inbound', 'Inbound')], string='Direction', states={'draft': [('readonly', False)]}, readonly=True) @api.onchange('direction') def _onchange_location_id(self): if self.direction == 'outbound': # Stock Location set to Partner Locations/Customers self.location_id = \ self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = \ self.warehouse_id.lot_stock_id.id @api.onchange('warehouse_id') def _onchange_warehouse_id(self): if self.direction: self.direction = False for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get('no_change_childs', False): for line in self.stock_request_ids: line.direction = self.direction
# Copyright (c) 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' direction = fields.Selection([('outbound', 'Outbound'), ('inbound', 'Inbound')], string='Direction', states={'draft': [('readonly', False)]}, readonly=True) @api.onchange('warehouse_id', 'direction') def _onchange_location_id(self): if self.direction == 'outbound': # Stock Location set to Partner Locations/Customers self.location_id = \ self.company_id.partner_id.property_stock_customer.id else: # Otherwise the Stock Location of the Warehouse self.location_id = \ self.warehouse_id.lot_stock_id.id for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False def change_childs(self): super().change_childs() if not self._context.get('no_change_childs', False): for line in self.stock_request_ids: line.direction = self.direction
Add warehouse_id to existing onchange.
[IMP] Add warehouse_id to existing onchange.
Python
agpl-3.0
Vauxoo/stock-logistics-warehouse,Vauxoo/stock-logistics-warehouse,Vauxoo/stock-logistics-warehouse
--- +++ @@ -13,7 +13,7 @@ states={'draft': [('readonly', False)]}, readonly=True) - @api.onchange('direction') + @api.onchange('warehouse_id', 'direction') def _onchange_location_id(self): if self.direction == 'outbound': # Stock Location set to Partner Locations/Customers @@ -23,11 +23,6 @@ # Otherwise the Stock Location of the Warehouse self.location_id = \ self.warehouse_id.lot_stock_id.id - - @api.onchange('warehouse_id') - def _onchange_warehouse_id(self): - if self.direction: - self.direction = False for stock_request in self.stock_request_ids: if stock_request.route_id: stock_request.route_id = False
94a55dfc68fcd2352f867b01fc703a202c87f453
troposphere/events.py
troposphere/events.py
# Copyright (c) 2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty class Target(AWSProperty): props = { 'Arn': (basestring, True), 'Id': (basestring, True), 'Input': (basestring, False), 'InputPath': (basestring, False) } class Rule(AWSObject): resource_type = "AWS::Events::Rule" props = { 'Description': (basestring, False), 'EventPattern': (dict, False), 'Name': (basestring, False), 'RoleArn': (basestring, False), 'ScheduleExpression': (basestring, False), 'State': (basestring, False), 'Targets': ([Target], False) }
# Copyright (c) 2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty class Target(AWSProperty): props = { 'Arn': (basestring, True), 'Id': (basestring, True), 'Input': (basestring, False), 'InputPath': (basestring, False), 'RoleArn': (basestring, False), } class Rule(AWSObject): resource_type = "AWS::Events::Rule" props = { 'Description': (basestring, False), 'EventPattern': (dict, False), 'Name': (basestring, False), 'ScheduleExpression': (basestring, False), 'State': (basestring, False), 'Targets': ([Target], False), }
Remove RoleArn from Events::Rule and add to Target property
Remove RoleArn from Events::Rule and add to Target property
Python
bsd-2-clause
pas256/troposphere,pas256/troposphere,ikben/troposphere,7digital/troposphere,ikben/troposphere,cloudtools/troposphere,7digital/troposphere,johnctitus/troposphere,johnctitus/troposphere,cloudtools/troposphere
--- +++ @@ -11,8 +11,8 @@ 'Arn': (basestring, True), 'Id': (basestring, True), 'Input': (basestring, False), - 'InputPath': (basestring, False) - + 'InputPath': (basestring, False), + 'RoleArn': (basestring, False), } @@ -24,9 +24,7 @@ 'Description': (basestring, False), 'EventPattern': (dict, False), 'Name': (basestring, False), - 'RoleArn': (basestring, False), 'ScheduleExpression': (basestring, False), 'State': (basestring, False), - 'Targets': ([Target], False) - + 'Targets': ([Target], False), }
f6df4f359b3d949b3f87a22bda1a78237c396aef
tests/integrations/current/test_read.py
tests/integrations/current/test_read.py
import os from tests.integrations.base import BaseTest class TestReadCurrentView(BaseTest): def test_listdirs(self): dirs = set(os.listdir("%s/current" % self.mount_path)) assert dirs == set(['testing', 'me']) def test_read_from_a_file(self): with open("%s/current/testing" % self.mount_path) as f: assert f.read() == "just testing around here\n" def test_get_correct_stats(self): filename = "%s/current/testing" % self.mount_path stats = os.stat(filename) # TODO: get created + modified time attrs = { 'st_uid': os.getuid(), 'st_gid': os.getgid(), 'st_mode': 0100644 } for name, value in attrs.iteritems(): assert getattr(stats, name) == value
import os from tests.integrations.base import BaseTest class TestReadCurrentView(BaseTest): def test_listdirs(self): dirs = set(os.listdir("%s/current" % self.mount_path)) assert dirs == set(['testing', 'me']) def test_read_from_a_file(self): with open("%s/current/testing" % self.mount_path) as f: assert f.read() == "just testing around here\n" def test_get_correct_stats(self): filename = "%s/current/testing" % self.mount_path stats = os.stat(filename) filename = "%s/testing_repo/testing" % self.repo_path real_stats = os.stat(filename) attrs = { 'st_uid': os.getuid(), 'st_gid': os.getgid(), 'st_mode': 0100644, 'st_ctime': real_stats.st_ctime, 'st_mtime': real_stats.st_mtime, 'st_atime': real_stats.st_atime, } for name, value in attrs.iteritems(): assert getattr(stats, name) == value
Test time related stats from current view
Test time related stats from current view
Python
apache-2.0
bussiere/gitfs,PressLabs/gitfs,ksmaheshkumar/gitfs,rowhit/gitfs,PressLabs/gitfs
--- +++ @@ -16,11 +16,16 @@ filename = "%s/current/testing" % self.mount_path stats = os.stat(filename) - # TODO: get created + modified time + filename = "%s/testing_repo/testing" % self.repo_path + real_stats = os.stat(filename) + attrs = { 'st_uid': os.getuid(), 'st_gid': os.getgid(), - 'st_mode': 0100644 + 'st_mode': 0100644, + 'st_ctime': real_stats.st_ctime, + 'st_mtime': real_stats.st_mtime, + 'st_atime': real_stats.st_atime, } for name, value in attrs.iteritems():
662791d49deb945e911be5e07af2bbb3499a45ca
tests/test_load_cfg.py
tests/test_load_cfg.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test load qc configurations (utils.load_cfg) """ import pkg_resources from cotede.utils import load_cfg CFG = [f[:-5] for f in pkg_resources.resource_listdir('cotede', 'qc_cfg') if f[-5:] == '.json'] def test_inout(): """ load_cfg shouldn't overwrite input variable cfg """ cfg = 'cotede' out = load_cfg(cfg) assert out != cfg def test_dict(): cfg = {'main': {'valid_datetime': None}} cfg_out = load_cfg(cfg) assert cfg_out == cfg def test_default(): cfg_out = load_cfg() assert type(cfg_out) is dict assert len(cfg_out) > 0 def test_factory_cfgs(): for cfg in CFG: print("Loading %s" % cfg) cfg_out = load_cfg(cfg) assert type(cfg_out) is dict assert len(cfg_out) > 0 # Missing a test to load cfg at ~/.cotede
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test load qc configurations (utils.load_cfg) """ import os.path import pkg_resources from cotede.utils import load_cfg, cotede_dir CFG = [f[:-5] for f in pkg_resources.resource_listdir('cotede', 'qc_cfg') if f[-5:] == '.json'] def test_no_local_duplicate_cfg(): """ Avoid local cfg of default procedures Guarantee that there is no local copy of a default cfg json file, otherwise the default cfg could be breaking, and the tests safely escaping into a local, non-distributed, cfg. """ for cfg in CFG: local_cfg = os.path.join(cotede_dir(), "cfg", "%s.json" % cfg) assert not os.path.exists(local_cfg), \ "Redundant local cfg file: %s" % cfg def test_inout(): """ load_cfg shouldn't overwrite input variable cfg """ cfg = 'cotede' out = load_cfg(cfg) assert out != cfg def test_dict(): cfg = {'main': {'valid_datetime': None}} cfg_out = load_cfg(cfg) assert cfg_out == cfg def test_default(): cfg_out = load_cfg() assert type(cfg_out) is dict assert len(cfg_out) > 0 def test_factory_cfgs(): for cfg in CFG: print("Loading %s" % cfg) cfg_out = load_cfg(cfg) assert type(cfg_out) is dict assert len(cfg_out) > 0 # Missing a test to load cfg at ~/.cotede
Test to check cfg duplicate in local cfg.
Test to check cfg duplicate in local cfg. If the factory config fail, the default is to fail safe searching to a local cfg file, what could hide problems with the builtin cfg file.
Python
bsd-3-clause
castelao/CoTeDe
--- +++ @@ -4,13 +4,28 @@ """ Test load qc configurations (utils.load_cfg) """ +import os.path import pkg_resources -from cotede.utils import load_cfg +from cotede.utils import load_cfg, cotede_dir CFG = [f[:-5] for f in pkg_resources.resource_listdir('cotede', 'qc_cfg') if f[-5:] == '.json'] + + +def test_no_local_duplicate_cfg(): + """ Avoid local cfg of default procedures + + Guarantee that there is no local copy of a default cfg json file, + otherwise the default cfg could be breaking, and the tests safely + escaping into a local, non-distributed, cfg. + """ + + for cfg in CFG: + local_cfg = os.path.join(cotede_dir(), "cfg", "%s.json" % cfg) + assert not os.path.exists(local_cfg), \ + "Redundant local cfg file: %s" % cfg def test_inout():
c95d78378c7b3b234439e1d9a9bc41539b9080f5
preferences/models.py
preferences/models.py
import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True, null=True) lat = models.FloatField(null=True, blank=True) lon = models.FloatField(null=True, blank=True) apikey = models.UUIDField(default=uuid.uuid4) class PersonFollow(models.Model): user = models.ForeignKey(User, related_name='person_follows') person = models.ForeignKey(Person, related_name='follows') class TopicFollow(models.Model): user = models.ForeignKey(User, related_name='topic_follows') topic = models.CharField(max_length=100) class LocationFollow(models.Model): user = models.ForeignKey(User, related_name='location_follows') location = models.CharField(max_length=100)
import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True, null=True) lat = models.FloatField(null=True, blank=True) lon = models.FloatField(null=True, blank=True) rep_from_address = models.CharField(max_length=255, blank=True, null=True) sen_from_address = models.CharField(max_length=255, blank=True, null=True) apikey = models.UUIDField(default=uuid.uuid4) class PersonFollow(models.Model): user = models.ForeignKey(User, related_name='person_follows') person = models.ForeignKey(Person, related_name='follows') class TopicFollow(models.Model): user = models.ForeignKey(User, related_name='topic_follows') topic = models.CharField(max_length=100) class LocationFollow(models.Model): user = models.ForeignKey(User, related_name='location_follows') location = models.CharField(max_length=100)
Add rep and sen from address fields to Preferences model
Add rep and sen from address fields to Preferences model
Python
mit
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
--- +++ @@ -9,6 +9,8 @@ address = models.CharField(max_length=100, blank=True, null=True) lat = models.FloatField(null=True, blank=True) lon = models.FloatField(null=True, blank=True) + rep_from_address = models.CharField(max_length=255, blank=True, null=True) + sen_from_address = models.CharField(max_length=255, blank=True, null=True) apikey = models.UUIDField(default=uuid.uuid4)
2bebbbfc12e1013e3c5c0a42329bac520c574b9b
tests/test_settings.py
tests/test_settings.py
import pytest import npc import os from tests.util import fixture_dir @pytest.fixture def settings(): return npc.settings.Settings() def test_creation(settings): assert settings is not None def test_override(settings): override_path = fixture_dir(['settings/settings-vim.json']) old_editor = settings.get('editor') settings.load_more(override_path) assert settings.get('editor') != old_editor def test_nested_get(settings): assert settings.get('paths.characters') == 'Characters' def test_get_settings_path(settings): assert settings.get_settings_path('default') == os.path.join(settings.default_settings_path, 'settings-default.json') assert settings.get_settings_path('campaign') == os.path.join(settings.campaign_settings_path, 'settings.json') def test_support_paths(settings): """Paths loaded from additional files should be expanded relative to that file""" override_path = fixture_dir(['settings/settings-paths.json']) settings.load_more(override_path) assert settings.get('support.testpath') == fixture_dir(['settings/nothing.json'])
import pytest import npc import os from tests.util import fixture_dir def test_creation(prefs): assert prefs is not None def test_override(prefs): override_path = fixture_dir(['settings/settings-vim.json']) old_editor = prefs.get('editor') prefs.load_more(override_path) assert prefs.get('editor') != old_editor def test_nested_get(prefs): assert prefs.get('paths.characters') == 'Characters' def test_get_settings_path(prefs): assert prefs.get_settings_path('default') == os.path.join(prefs.default_settings_path, 'settings-default.json') assert prefs.get_settings_path('campaign') == os.path.join(prefs.campaign_settings_path, 'settings.json') def test_support_paths(prefs): """Paths loaded from additional files should be expanded relative to that file""" override_path = fixture_dir(['settings/settings-paths.json']) prefs.load_more(override_path) assert prefs.get('support.testpath') == fixture_dir(['settings/nothing.json'])
Refactor settings tests to use global fixture
Refactor settings tests to use global fixture
Python
mit
aurule/npc,aurule/npc
--- +++ @@ -3,28 +3,24 @@ import os from tests.util import fixture_dir -@pytest.fixture -def settings(): - return npc.settings.Settings() +def test_creation(prefs): + assert prefs is not None -def test_creation(settings): - assert settings is not None +def test_override(prefs): + override_path = fixture_dir(['settings/settings-vim.json']) + old_editor = prefs.get('editor') + prefs.load_more(override_path) + assert prefs.get('editor') != old_editor -def test_override(settings): - override_path = fixture_dir(['settings/settings-vim.json']) - old_editor = settings.get('editor') - settings.load_more(override_path) - assert settings.get('editor') != old_editor +def test_nested_get(prefs): + assert prefs.get('paths.characters') == 'Characters' -def test_nested_get(settings): - assert settings.get('paths.characters') == 'Characters' +def test_get_settings_path(prefs): + assert prefs.get_settings_path('default') == os.path.join(prefs.default_settings_path, 'settings-default.json') + assert prefs.get_settings_path('campaign') == os.path.join(prefs.campaign_settings_path, 'settings.json') -def test_get_settings_path(settings): - assert settings.get_settings_path('default') == os.path.join(settings.default_settings_path, 'settings-default.json') - assert settings.get_settings_path('campaign') == os.path.join(settings.campaign_settings_path, 'settings.json') - -def test_support_paths(settings): +def test_support_paths(prefs): """Paths loaded from additional files should be expanded relative to that file""" override_path = fixture_dir(['settings/settings-paths.json']) - settings.load_more(override_path) - assert settings.get('support.testpath') == fixture_dir(['settings/nothing.json']) + prefs.load_more(override_path) + assert prefs.get('support.testpath') == fixture_dir(['settings/nothing.json'])
7a8569fb28a1214b4898b113c384eb3967c656ef
tlsenum/parse_hello.py
tlsenum/parse_hello.py
import construct from tlsenum import hello_constructs class ClientHello(object): @property def protocol_version(self): return self._protocol_version @protocol_version.setter def protocol_version(self, protocol_version): assert protocol_version in ["3.0", "1.0", "1.1", "1.2"] self._protocol_version = protocol_version if protocol_version == "3.0": self._protocol_minor = 0 elif protocol_version == "1.0": self._protocol_minor = 1 elif protocol_version == "1.1": self._protocol_minor = 2 elif protocol_version == "1.2": self._protocol_minor = 3 def build(self): return hello_constructs.ProtocolVersion.build( construct.Container(major=3, minor=self._protocol_minor) )
import time import os import construct from tlsenum import hello_constructs class ClientHello(object): @property def protocol_version(self): return self._protocol_version @protocol_version.setter def protocol_version(self, protocol_version): assert protocol_version in ["3.0", "1.0", "1.1", "1.2"] self._protocol_version = protocol_version if protocol_version == "3.0": self._protocol_minor = 0 elif protocol_version == "1.0": self._protocol_minor = 1 elif protocol_version == "1.1": self._protocol_minor = 2 elif protocol_version == "1.2": self._protocol_minor = 3 def build(self): protocol_version = construct.Container( major=3, minor=self._protocol_minor ) random = construct.Container( gmt_unix_time=int(time.time()), random_bytes=os.urandom(28) ) session_id = construct.Container( length=0, session_id=b"" ) return hello_constructs.ClientHello.build( construct.Container( version=protocol_version, random=random, session_id=session_id ) )
Add random and session_id fields.
Add random and session_id fields.
Python
mit
Ayrx/tlsenum,Ayrx/tlsenum
--- +++ @@ -1,3 +1,6 @@ +import time +import os + import construct from tlsenum import hello_constructs @@ -25,6 +28,20 @@ self._protocol_minor = 3 def build(self): - return hello_constructs.ProtocolVersion.build( - construct.Container(major=3, minor=self._protocol_minor) + protocol_version = construct.Container( + major=3, minor=self._protocol_minor ) + + random = construct.Container( + gmt_unix_time=int(time.time()), random_bytes=os.urandom(28) + ) + + session_id = construct.Container( + length=0, session_id=b"" + ) + + return hello_constructs.ClientHello.build( + construct.Container( + version=protocol_version, random=random, session_id=session_id + ) + )
c64a9a586a5997c3a5a8683913e6a52075618ac8
virtool/uploads/models.py
virtool/uploads/models.py
import enum from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum from virtool.postgres import Base class UploadType(str, enum.Enum): hmm = "hmm" reference = "reference" reads = "reads" subtraction = "subtraction" class Upload(Base): __tablename__ = "uploads" id = Column(Integer, primary_key=True) created_at = Column(DateTime) name = Column(String) name_on_disk = Column(String, unique=True) ready = Column(Boolean) removed = Column(Boolean) removed_at = Column(DateTime) reserved = Column(Boolean) size = Column(Integer) type = Column(Enum(UploadType)) user = Column(String) uploaded_at = Column(DateTime) def __repr__(self): return f"<Upload(id={self.id}, created_at={self.created_at}, name={self.name}, " \ f"name_on_disk={self.name_on_disk}, ready={self.ready}, removed={self.removed}, " \ f"reserved={self.reserved}, " f"size={self.size}, type={self.type}, user={self.user}, " \ f"uploaded_at={self.uploaded_at}>"
import enum from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum from virtool.postgres import Base class UploadType(str, enum.Enum): hmm = "hmm" reference = "reference" reads = "reads" subtraction = "subtraction" class Upload(Base): __tablename__ = "uploads" id = Column(Integer, primary_key=True) created_at = Column(DateTime) name = Column(String) name_on_disk = Column(String, unique=True) ready = Column(Boolean) removed = Column(Boolean) removed_at = Column(DateTime) reserved = Column(Boolean) size = Column(Integer) type = Column(Enum(UploadType)) user = Column(String) uploaded_at = Column(DateTime) def __repr__(self): return f"<Upload(id={self.id}, created_at={self.created_at}, name={self.name}, " \ f"name_on_disk={self.name_on_disk}, ready={self.ready}, removed={self.removed}, " \ f"reserved={self.reserved}, " f"size={self.size}, type={self.type}, user={self.user}, " \ f"uploaded_at={self.uploaded_at})>"
Fix format issue with `__repr__`
Fix format issue with `__repr__`
Python
mit
virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool
--- +++ @@ -32,4 +32,4 @@ return f"<Upload(id={self.id}, created_at={self.created_at}, name={self.name}, " \ f"name_on_disk={self.name_on_disk}, ready={self.ready}, removed={self.removed}, " \ f"reserved={self.reserved}, " f"size={self.size}, type={self.type}, user={self.user}, " \ - f"uploaded_at={self.uploaded_at}>" + f"uploaded_at={self.uploaded_at})>"
1089413956f3eff9d233d276ebe728e89d814096
matchers/sifter.py
matchers/sifter.py
from base import BaseMatcher import os import requests import re import json NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b' API_KEY = os.environ.get('SIFTER') def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s' api = url % number r = requests.get(api, headers=headers) data = json.loads(r.content) for issue in data['issues']: if str(issue['number']) == number: return format_ticket(issue) def format_ticket(issue): url = "https://unisubs.sifterapp.com/issue/%s" % issue['number'] return "%s - %s - %s" % (issue['number'], issue['subject'], url) def parse(text): issues = re.findall(NUM_REGEX, text) return map(find_ticket, issues) class SifterMatcher(BaseMatcher): name = 'sifter' def respond(self, message, user=None): issues = parse(message) if len(issues) == 0: return message = str(", ".join(issues)) self.speak(message)
from base import BaseMatcher import os import requests import re import json NUM_REGEX = r'(?:[\s#]|^)(\d\d\d\d?\d?)(?:[\s\.,\?!]|$)' API_KEY = os.environ.get('SIFTER') def find_ticket(number): headers = { 'X-Sifter-Token': API_KEY } url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s' api = url % number r = requests.get(api, headers=headers) data = json.loads(r.content) for issue in data['issues']: if str(issue['number']) == number: return format_ticket(issue) def format_ticket(issue): url = "https://unisubs.sifterapp.com/issue/%s" % issue['number'] return "%s - %s - %s" % (issue['number'], issue['subject'], url) def parse(text): issues = re.findall(NUM_REGEX, text) return map(find_ticket, issues) class SifterMatcher(BaseMatcher): name = 'sifter' def respond(self, message, user=None): issues = parse(message) if len(issues) == 0: return message = str(", ".join(issues)) self.speak(message)
Make the Sifter issue matching more specific.
Make the Sifter issue matching more specific. Now it matches: * 3-5 digit numbers * Preceded by a #, whitespace, or beginning-of-line. * Followed by a comma, period, question mark, exclamation point, whitespace, or end-of-line.
Python
bsd-2-clause
honza/nigel
--- +++ @@ -5,7 +5,7 @@ import json -NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b' +NUM_REGEX = r'(?:[\s#]|^)(\d\d\d\d?\d?)(?:[\s\.,\?!]|$)' API_KEY = os.environ.get('SIFTER')
061386e402fb3f1300c0c71be9b07ecc16590ecc
cronjobs/extract_kalliope_originators.py
cronjobs/extract_kalliope_originators.py
#!/usr/bin/python3 import re import sys import xml.etree.ElementTree as ET valid_gnd = re.compile('[0-9\-X]+') def Main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " kalliope_originator_record_file") exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} for recordData in root.findall('.//{*}recordData'): genre = recordData.find('.//{*}genre') name = recordData.find('.//{*}name') if genre is not None and name is not None : gnd = name.get('valueURI').replace('https://d-nb.info/gnd/','') if name.get('valueURI') else None originator_type = genre.text if gnd and originator_type and valid_gnd.match(gnd): if gnd in gnds_and_type and not originator_type in gnds_and_type[gnd]: gnds_and_type[gnd].add(originator_type) else: gnds_and_type[gnd] = { originator_type } for gnd, originator_type in gnds_and_type.items(): print(gnd, ' - ', end='') print(*originator_type, sep=', ') try: Main() except Exception as e: print("ERROR: " + e)
#!/usr/bin/python3 import re import sys import xml.etree.ElementTree as ET valid_gnd = re.compile('[0-9\-X]+') def Main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " kalliope_originator_record_file") exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} for recordData in root.findall('.//{http://www.loc.gov/zing/srw/}recordData'): genre = recordData.find('.//{http://www.loc.gov/mods/v3}genre') name = recordData.find('.//{http://www.loc.gov/mods/v3}name') if genre is not None and name is not None : gnd = name.get('valueURI').replace('https://d-nb.info/gnd/','') if name.get('valueURI') else None originator_type = genre.text if gnd and originator_type and valid_gnd.match(gnd): if gnd in gnds_and_type and not originator_type in gnds_and_type[gnd]: gnds_and_type[gnd].add(originator_type) else: gnds_and_type[gnd] = { originator_type } for gnd, originator_type in gnds_and_type.items(): print(gnd, ' - ', end='') print(*originator_type, sep=', ') try: Main() except Exception as e: print("ERROR: " + e)
Make compatible with CentOS 8
Make compatible with CentOS 8
Python
agpl-3.0
ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools
--- +++ @@ -11,9 +11,9 @@ exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} - for recordData in root.findall('.//{*}recordData'): - genre = recordData.find('.//{*}genre') - name = recordData.find('.//{*}name') + for recordData in root.findall('.//{http://www.loc.gov/zing/srw/}recordData'): + genre = recordData.find('.//{http://www.loc.gov/mods/v3}genre') + name = recordData.find('.//{http://www.loc.gov/mods/v3}name') if genre is not None and name is not None : gnd = name.get('valueURI').replace('https://d-nb.info/gnd/','') if name.get('valueURI') else None originator_type = genre.text
dc8a2d710acbdf79444d05cc266b9f1ef13e838e
pykwalify/__init__.py
pykwalify/__init__.py
# -*- coding: utf-8 -*- """ pykwalify """ # python stdlib import logging import logging.config import os __author__ = 'Grokzen <Grokzen@gmail.com>' __version_info__ = (1, 6, 0) __version__ = '.'.join(map(str, __version_info__)) log_level_to_string_map = { 5: "DEBUG", 4: "INFO", 3: "WARNING", 2: "ERROR", 1: "CRITICAL", 0: "INFO" } def init_logging(log_level): """ Init logging settings with default set to INFO """ l = log_level_to_string_map[min(log_level, 5)] msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if l in os.environ else "%(levelname)s - %(message)s" logging_conf = { "version": 1, "root": { "level": l, "handlers": ["console"] }, "handlers": { "console": { "class": "logging.StreamHandler", "level": l, "formatter": "simple", "stream": "ext://sys.stdout" } }, "formatters": { "simple": { "format": " {0}".format(msg) } } } logging.config.dictConfig(logging_conf) partial_schemas = {}
# -*- coding: utf-8 -*- """ pykwalify """ # python stdlib import logging import logging.config import os __author__ = 'Grokzen <Grokzen@gmail.com>' __version_info__ = (1, 6, 0) __version__ = '.'.join(map(str, __version_info__)) log_level_to_string_map = { 5: "DEBUG", 4: "INFO", 3: "WARNING", 2: "ERROR", 1: "CRITICAL", 0: "INFO" } def init_logging(log_level): """ Init logging settings with default set to INFO """ log_level = log_level_to_string_map[min(log_level, 5)] msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if log_level in os.environ else "%(levelname)s - %(message)s" logging_conf = { "version": 1, "root": { "level": log_level, "handlers": ["console"] }, "handlers": { "console": { "class": "logging.StreamHandler", "level": log_level, "formatter": "simple", "stream": "ext://sys.stdout" } }, "formatters": { "simple": { "format": " {0}".format(msg) } } } logging.config.dictConfig(logging_conf) partial_schemas = {}
Change ambigous variable name to be more clear what it is
Change ambigous variable name to be more clear what it is
Python
mit
grokzen/pykwalify
--- +++ @@ -26,20 +26,20 @@ """ Init logging settings with default set to INFO """ - l = log_level_to_string_map[min(log_level, 5)] + log_level = log_level_to_string_map[min(log_level, 5)] - msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if l in os.environ else "%(levelname)s - %(message)s" + msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if log_level in os.environ else "%(levelname)s - %(message)s" logging_conf = { "version": 1, "root": { - "level": l, + "level": log_level, "handlers": ["console"] }, "handlers": { "console": { "class": "logging.StreamHandler", - "level": l, + "level": log_level, "formatter": "simple", "stream": "ext://sys.stdout" }
197662c014704d6b32597fc7e059800315a57ebd
dashboard_app/tests/models/sw_package.py
dashboard_app/tests/models/sw_package.py
""" Test for the SoftwarePackage model """ from django.db import IntegrityError from django.test import TestCase from dashboard_app.models import SoftwarePackage from launch_control.utils.call_helper import ObjectFactoryMixIn class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn): class Dummy: class SoftwarePackage: name = 'libfoo' version = '1.2.0' def test_creation_1(self): dummy, sw_package = self.make_and_get_dummy(SoftwarePackage) sw_package.save() self.assertEqual(sw_package.name, dummy.name) self.assertEqual(sw_package.version, dummy.version) def test_uniqueness(self): pkg1 = self.make(SoftwarePackage) pkg1.save() pkg2 = self.make(SoftwarePackage) self.assertRaises(IntegrityError, pkg2.save) def test_unicode(self): obj = SoftwarePackage(name="foo", version="1.2") self.assertEqual(unicode(obj), u"foo 1.2")
""" Test for the SoftwarePackage model """ from django.db import IntegrityError from django.test import TestCase from dashboard_app.models import SoftwarePackage from launch_control.utils.call_helper import ObjectFactoryMixIn class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn): class Dummy: class SoftwarePackage: name = 'libfoo' version = '1.2.0' def test_creation_1(self): dummy, sw_package = self.make_and_get_dummy(SoftwarePackage) sw_package.save() self.assertEqual(sw_package.name, dummy.name) self.assertEqual(sw_package.version, dummy.version) def test_LP744922(self): """ Regression test for https://bugs.launchpad.net/launch-control/+bug/744922 """ sw_package = SoftwarePackage.objects.create(name='foo', version='x' * 33) sw_package.save() self.assertEqual(len(sw_package.version), 33) def test_uniqueness(self): pkg1 = self.make(SoftwarePackage) pkg1.save() pkg2 = self.make(SoftwarePackage) self.assertRaises(IntegrityError, pkg2.save) def test_unicode(self): obj = SoftwarePackage(name="foo", version="1.2") self.assertEqual(unicode(obj), u"foo 1.2")
Add regression tests for LP:744922
Add regression tests for LP:744922
Python
agpl-3.0
OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server
--- +++ @@ -22,6 +22,14 @@ self.assertEqual(sw_package.name, dummy.name) self.assertEqual(sw_package.version, dummy.version) + def test_LP744922(self): + """ + Regression test for https://bugs.launchpad.net/launch-control/+bug/744922 + """ + sw_package = SoftwarePackage.objects.create(name='foo', version='x' * 33) + sw_package.save() + self.assertEqual(len(sw_package.version), 33) + def test_uniqueness(self): pkg1 = self.make(SoftwarePackage) pkg1.save()
d79fde9a1bceea2ea8bc9aa8d14e5ec66a44600d
mesoblog/models.py
mesoblog/models.py
from django.db import models # Represents a category which articles can be part of class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255) def __str__(self): return self.name+" ["+str(self.id)+"]" # Article model represents one article in the blog. class Article(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) contents = models.TextField() date_published = models.DateTimeField() published = models.BooleanField() primary_category = models.ForeignKey(Category, related_name='+') categories = models.ManyToManyField(Category) def __str__(self): return self.title+" ["+str(self.id)+"]"
from django.db import models import random import re import string # Represents a category which articles can be part of class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255) def __str__(self): return self.name+" ["+str(self.id)+"]" def save(self): # Make sure that the slug is: # a) not just integers so it doen't look like an ID # b) unique amongst all other objects of that type # a): if re.match(r'^\d+$', self.slug): self.slug += "_" # b): try: other = Category.objects.get(slug=self.slug) self.slug += "_" self.slug += ''.join(random.sample(string.ascii_lowercase + string.digits, 8)) except self.DoesNotExist: pass super(Category, self).save() # Article model represents one article in the blog. class Article(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) contents = models.TextField() date_published = models.DateTimeField() published = models.BooleanField() primary_category = models.ForeignKey(Category, related_name='+') categories = models.ManyToManyField(Category) def __str__(self): return self.title+" ["+str(self.id)+"]" def save(self): # Make sure that the slug is: # a) not just integers so it doen't look like an ID # b) unique amongst all other objects of that type # a): if re.match(r'^\d+$', self.slug): self.slug += "_" # b): try: other = Article.objects.get(slug=self.slug) self.slug += "_" self.slug += ''.join(random.sample(string.ascii_lowercase + string.digits, 8)) except self.DoesNotExist: pass super(Category, self).save()
Make sure slugs are unique and not integer only.
Make sure slugs are unique and not integer only. This fixes issues #1, #2 & #5
Python
mit
grundleborg/mesosphere
--- +++ @@ -1,4 +1,8 @@ from django.db import models + +import random +import re +import string # Represents a category which articles can be part of class Category(models.Model): @@ -7,6 +11,23 @@ def __str__(self): return self.name+" ["+str(self.id)+"]" + + def save(self): + # Make sure that the slug is: + # a) not just integers so it doen't look like an ID + # b) unique amongst all other objects of that type + + # a): + if re.match(r'^\d+$', self.slug): + self.slug += "_" + # b): + try: + other = Category.objects.get(slug=self.slug) + self.slug += "_" + self.slug += ''.join(random.sample(string.ascii_lowercase + string.digits, 8)) + except self.DoesNotExist: + pass + super(Category, self).save() # Article model represents one article in the blog. @@ -22,4 +43,22 @@ def __str__(self): return self.title+" ["+str(self.id)+"]" + def save(self): + # Make sure that the slug is: + # a) not just integers so it doen't look like an ID + # b) unique amongst all other objects of that type + + # a): + if re.match(r'^\d+$', self.slug): + self.slug += "_" + # b): + try: + other = Article.objects.get(slug=self.slug) + self.slug += "_" + self.slug += ''.join(random.sample(string.ascii_lowercase + string.digits, 8)) + except self.DoesNotExist: + pass + super(Category, self).save() + +
8492e70a50abe4641d96b7ecdd0e7f583167b755
lambda_utils/logger.py
lambda_utils/logger.py
# -*- coding: utf-8 -*- import os import logging import threading class Logger(object): def configure_logging(self): log_level = getattr(logging, os.environ.get('LOGLEVEL', 'INFO').upper()) logging.getLogger().setLevel(log_level) def __call__(self, function): self.configure_logging() self.function = function return self.wrapped_function def wrapped_function(self, event, context): try: timeout_notification = self.add_logging_on_timeout(context) logging.debug(event) response = self.function(event, context) logging.debug(response) return response except Exception as ex: logging.exception(ex.message) raise finally: if timeout_notification: timeout_notification.cancel() def add_logging_on_timeout(self, context): try: timer = threading.Timer((context.get_remaining_time_in_millis() / 1000.00) - 0.5, timeout) timer.start() return timer except AttributeError as ex: logging.debug('Add Timeout notification failed. context.get_remaining_time_in_millis() missing?') def timeout(): logging.error("Execution is about to timeout.")
# -*- coding: utf-8 -*- import os import logging import threading class Logger(object): def configure_logging(self): log_level = getattr(logging, os.environ.get('LOGLEVEL', 'INFO').upper()) logging.getLogger().setLevel(log_level) def __call__(self, function): self.configure_logging() self.function = function return self.wrapped_function def wrapped_function(self, event, context): timeout_notification = self.add_logging_on_timeout(context) try: logging.debug(event) response = self.function(event, context) logging.debug(response) return response except Exception as ex: logging.exception(ex.message) raise finally: if timeout_notification: timeout_notification.cancel() def add_logging_on_timeout(self, context): if hasattr(context, 'get_remaining_time_in_millis'): seconds = (context.get_remaining_time_in_millis() / 1000.00) - 0.5 timer = threading.Timer(seconds, logging.error, args=["Execution is about to timeout."]) timer.start() return timer else: logging.debug('Add logging on timeout failed. context.get_remaining_time_in_millis() missing?')
Reduce complexity and try/catch block in Logger
Reduce complexity and try/catch block in Logger
Python
mit
CloudHeads/lambda_utils
--- +++ @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - import os import logging import threading @@ -16,8 +15,8 @@ return self.wrapped_function def wrapped_function(self, event, context): + timeout_notification = self.add_logging_on_timeout(context) try: - timeout_notification = self.add_logging_on_timeout(context) logging.debug(event) response = self.function(event, context) logging.debug(response) @@ -29,14 +28,10 @@ if timeout_notification: timeout_notification.cancel() def add_logging_on_timeout(self, context): - try: - timer = threading.Timer((context.get_remaining_time_in_millis() / 1000.00) - 0.5, timeout) + if hasattr(context, 'get_remaining_time_in_millis'): + seconds = (context.get_remaining_time_in_millis() / 1000.00) - 0.5 + timer = threading.Timer(seconds, logging.error, args=["Execution is about to timeout."]) timer.start() return timer - - except AttributeError as ex: - logging.debug('Add Timeout notification failed. context.get_remaining_time_in_millis() missing?') - - -def timeout(): - logging.error("Execution is about to timeout.") + else: + logging.debug('Add logging on timeout failed. context.get_remaining_time_in_millis() missing?')
c91e42c32d8314d3d156c577f854fa311c5b1b67
model_presenter.py
model_presenter.py
import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import FormatStrFormatter from tempfile import NamedTemporaryFile def plot_to_file(symbol, timestamp, close, score): fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(timestamp, close, color='r', marker='.', label="close") ax2.plot(timestamp, score, color='b', marker='.', label="score") plt.title("%s: score %0.2f" % (symbol, score[-1])) fig.autofmt_xdate() ax1.xaxis.set_major_formatter(DateFormatter("%H:%M")) ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) h1, l1 = ax1.get_legend_handles_labels() h2, l2 = ax2.get_legend_handles_labels() ax1.legend(h1 + h2, l1 + l2) png_file = NamedTemporaryFile(delete=False, suffix='.png') png_file.close() fig.set_dpi(100) fig.set_size_inches(10, 4) fig.set_tight_layout(True) fig.savefig(png_file.name) plt.close(fig) return png_file.name
import matplotlib # Do not use X for plotting matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import FormatStrFormatter from tempfile import NamedTemporaryFile def plot_to_file(symbol, timestamp, close, score): fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(timestamp, close, color='r', marker='.', label="close") ax2.plot(timestamp, score, color='b', marker='.', label="score") plt.title("%s: score %0.2f" % (symbol, score[-1])) fig.autofmt_xdate() ax1.xaxis.set_major_formatter(DateFormatter("%H:%M")) ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) h1, l1 = ax1.get_legend_handles_labels() h2, l2 = ax2.get_legend_handles_labels() ax1.legend(h1 + h2, l1 + l2) png_file = NamedTemporaryFile(delete=False, suffix='.png') png_file.close() fig.set_dpi(100) fig.set_size_inches(10, 4) fig.set_tight_layout(True) fig.savefig(png_file.name) plt.close(fig) return png_file.name
Fix the error that X is required for plotting
Fix the error that X is required for plotting This enables money-monkey in server environment
Python
mit
cjluo/money-monkey
--- +++ @@ -1,3 +1,7 @@ +import matplotlib +# Do not use X for plotting +matplotlib.use('Agg') + import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import FormatStrFormatter
cc99acd8381522e02703497121201cafd2f820a4
website/oauth/views.py
website/oauth/views.py
import httplib as http from flask import redirect from framework.auth.decorators import must_be_logged_in from framework.exceptions import HTTPError from website.oauth.models import ExternalAccount from website.oauth.utils import get_service @must_be_logged_in def oauth_disconnect(external_account_id, auth): account = ExternalAccount.load(external_account_id) user = auth.user if account is None: HTTPError(http.NOT_FOUND) if account not in user.external_accounts: HTTPError(http.FORBIDDEN) # iterate AddonUserSettings for addons for user_settings in user.get_addons(): user_settings.revoke_oauth_access(account) user_settings.save() ExternalAccount.remove_one(account) # # only after all addons have been dealt with can we remove it from the user # user.external_accounts.remove(account) user.save() @must_be_logged_in def oauth_connect(service_name, auth): service = get_service(service_name) return redirect(service.auth_url) @must_be_logged_in def oauth_callback(service_name, auth): user = auth.user provider = get_service(service_name) # Retrieve permanent credentials from provider provider.auth_callback(user=user) if provider.account not in user.external_accounts: user.external_accounts.append(provider.account) user.save() return {}
import httplib as http from flask import redirect from framework.auth.decorators import must_be_logged_in from framework.exceptions import HTTPError from website.oauth.models import ExternalAccount from website.oauth.utils import get_service @must_be_logged_in def oauth_disconnect(external_account_id, auth): account = ExternalAccount.load(external_account_id) user = auth.user if account is None: HTTPError(http.NOT_FOUND) if account not in user.external_accounts: HTTPError(http.FORBIDDEN) # iterate AddonUserSettings for addons for user_settings in user.get_addons(): user_settings.revoke_oauth_access(account) user_settings.save() # ExternalAccount.remove_one(account) # # only after all addons have been dealt with can we remove it from the user user.external_accounts.remove(account) user.save() @must_be_logged_in def oauth_connect(service_name, auth): service = get_service(service_name) return redirect(service.auth_url) @must_be_logged_in def oauth_callback(service_name, auth): user = auth.user provider = get_service(service_name) # Retrieve permanent credentials from provider provider.auth_callback(user=user) if provider.account not in user.external_accounts: user.external_accounts.append(provider.account) user.save() return {}
Change behavior of removing an external account to persist the object
Change behavior of removing an external account to persist the object
Python
apache-2.0
caseyrygt/osf.io,hmoco/osf.io,mluo613/osf.io,baylee-d/osf.io,erinspace/osf.io,amyshi188/osf.io,zkraime/osf.io,Johnetordoff/osf.io,zachjanicki/osf.io,mfraezz/osf.io,caneruguz/osf.io,himanshuo/osf.io,revanthkolli/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,zachjanicki/osf.io,HalcyonChimera/osf.io,ZobairAlijan/osf.io,zamattiac/osf.io,DanielSBrown/osf.io,mluke93/osf.io,ckc6cz/osf.io,RomanZWang/osf.io,HarryRybacki/osf.io,lamdnhan/osf.io,abought/osf.io,haoyuchen1992/osf.io,rdhyee/osf.io,crcresearch/osf.io,danielneis/osf.io,Johnetordoff/osf.io,billyhunt/osf.io,hmoco/osf.io,ckc6cz/osf.io,laurenrevere/osf.io,dplorimer/osf,TomHeatwole/osf.io,zamattiac/osf.io,TomBaxter/osf.io,alexschiller/osf.io,reinaH/osf.io,lamdnhan/osf.io,GaryKriebel/osf.io,mfraezz/osf.io,SSJohns/osf.io,leb2dg/osf.io,samchrisinger/osf.io,laurenrevere/osf.io,mfraezz/osf.io,kushG/osf.io,cldershem/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,mluke93/osf.io,CenterForOpenScience/osf.io,amyshi188/osf.io,brianjgeiger/osf.io,jinluyuan/osf.io,caseyrygt/osf.io,haoyuchen1992/osf.io,GageGaskins/osf.io,acshi/osf.io,leb2dg/osf.io,felliott/osf.io,njantrania/osf.io,jmcarp/osf.io,Nesiehr/osf.io,ticklemepierce/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,ckc6cz/osf.io,MerlinZhang/osf.io,leb2dg/osf.io,billyhunt/osf.io,caneruguz/osf.io,amyshi188/osf.io,bdyetton/prettychart,SSJohns/osf.io,sloria/osf.io,acshi/osf.io,jeffreyliu3230/osf.io,felliott/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,kch8qx/osf.io,TomBaxter/osf.io,CenterForOpenScience/osf.io,barbour-em/osf.io,samchrisinger/osf.io,bdyetton/prettychart,rdhyee/osf.io,icereval/osf.io,pattisdr/osf.io,chennan47/osf.io,jnayak1/osf.io,caneruguz/osf.io,crcresearch/osf.io,cslzchen/osf.io,cosenal/osf.io,kushG/osf.io,ticklemepierce/osf.io,Johnetordoff/osf.io,chrisseto/osf.io,haoyuchen1992/osf.io,himanshuo/osf.io,reinaH/osf.io,GageGaskins/osf.io,cslzchen/osf.io,lyndsysimon/osf.io,wearpants/osf.io,zkraime/osf.io,kushG/osf.io,cwisecarver/osf.io,kwierman/osf.io,cwisecarver/osf.io,binoculars/osf.io,monikagrabowska/osf.io,dplorimer/osf,zamattiac/osf.io,mluo613/osf.io,jeffreyliu3230/osf.io,jolene-esposito/osf.io,monikagrabowska/osf.io,njantrania/osf.io,felliott/osf.io,HarryRybacki/osf.io,barbour-em/osf.io,acshi/osf.io,amyshi188/osf.io,abought/osf.io,arpitar/osf.io,petermalcolm/osf.io,jnayak1/osf.io,jmcarp/osf.io,laurenrevere/osf.io,hmoco/osf.io,SSJohns/osf.io,billyhunt/osf.io,arpitar/osf.io,zachjanicki/osf.io,GaryKriebel/osf.io,brandonPurvis/osf.io,ticklemepierce/osf.io,mattclark/osf.io,asanfilippo7/osf.io,petermalcolm/osf.io,cldershem/osf.io,cosenal/osf.io,icereval/osf.io,doublebits/osf.io,arpitar/osf.io,jinluyuan/osf.io,caseyrollins/osf.io,aaxelb/osf.io,barbour-em/osf.io,billyhunt/osf.io,zkraime/osf.io,cwisecarver/osf.io,kwierman/osf.io,zamattiac/osf.io,GageGaskins/osf.io,alexschiller/osf.io,jolene-esposito/osf.io,ticklemepierce/osf.io,njantrania/osf.io,fabianvf/osf.io,sbt9uc/osf.io,doublebits/osf.io,MerlinZhang/osf.io,wearpants/osf.io,samanehsan/osf.io,RomanZWang/osf.io,rdhyee/osf.io,alexschiller/osf.io,mluke93/osf.io,asanfilippo7/osf.io,monikagrabowska/osf.io,RomanZWang/osf.io,petermalcolm/osf.io,doublebits/osf.io,cwisecarver/osf.io,dplorimer/osf,DanielSBrown/osf.io,ZobairAlijan/osf.io,alexschiller/osf.io,Ghalko/osf.io,jeffreyliu3230/osf.io,cldershem/osf.io,ZobairAlijan/osf.io,KAsante95/osf.io,caseyrygt/osf.io,saradbowman/osf.io,lamdnhan/osf.io,njantrania/osf.io,bdyetton/prettychart,Ghalko/osf.io,reinaH/osf.io,HarryRybacki/osf.io,hmoco/osf.io,fabianvf/osf.io,cosenal/osf.io,KAsante95/osf.io,emetsger/osf.io,Ghalko/osf.io,baylee-d/osf.io,samchrisinger/osf.io,adlius/osf.io,Nesiehr/osf.io,adlius/osf.io,caseyrollins/osf.io,jinluyuan/osf.io,himanshuo/osf.io,RomanZWang/osf.io,kch8qx/osf.io,wearpants/osf.io,abought/osf.io,zachjanicki/osf.io,kwierman/osf.io,abought/osf.io,brandonPurvis/osf.io,aaxelb/osf.io,mluke93/osf.io,monikagrabowska/osf.io,revanthkolli/osf.io,Nesiehr/osf.io,chennan47/osf.io,danielneis/osf.io,pattisdr/osf.io,barbour-em/osf.io,MerlinZhang/osf.io,MerlinZhang/osf.io,felliott/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,samanehsan/osf.io,mattclark/osf.io,jolene-esposito/osf.io,asanfilippo7/osf.io,Nesiehr/osf.io,TomBaxter/osf.io,zkraime/osf.io,alexschiller/osf.io,caneruguz/osf.io,KAsante95/osf.io,lyndsysimon/osf.io,rdhyee/osf.io,brianjgeiger/osf.io,sbt9uc/osf.io,danielneis/osf.io,jolene-esposito/osf.io,kushG/osf.io,chrisseto/osf.io,mattclark/osf.io,kch8qx/osf.io,lamdnhan/osf.io,ckc6cz/osf.io,caseyrygt/osf.io,sbt9uc/osf.io,bdyetton/prettychart,mluo613/osf.io,emetsger/osf.io,doublebits/osf.io,jmcarp/osf.io,GaryKriebel/osf.io,TomHeatwole/osf.io,brandonPurvis/osf.io,adlius/osf.io,GageGaskins/osf.io,leb2dg/osf.io,sloria/osf.io,TomHeatwole/osf.io,mluo613/osf.io,revanthkolli/osf.io,jmcarp/osf.io,jnayak1/osf.io,billyhunt/osf.io,brandonPurvis/osf.io,adlius/osf.io,crcresearch/osf.io,TomHeatwole/osf.io,erinspace/osf.io,kch8qx/osf.io,reinaH/osf.io,DanielSBrown/osf.io,mluo613/osf.io,HarryRybacki/osf.io,SSJohns/osf.io,samanehsan/osf.io,erinspace/osf.io,arpitar/osf.io,sbt9uc/osf.io,binoculars/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,cosenal/osf.io,DanielSBrown/osf.io,petermalcolm/osf.io,jeffreyliu3230/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,emetsger/osf.io,samanehsan/osf.io,fabianvf/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,acshi/osf.io,sloria/osf.io,samchrisinger/osf.io,ZobairAlijan/osf.io,Ghalko/osf.io,emetsger/osf.io,danielneis/osf.io,kwierman/osf.io,cldershem/osf.io,KAsante95/osf.io,brandonPurvis/osf.io,doublebits/osf.io,lyndsysimon/osf.io,chennan47/osf.io,wearpants/osf.io,KAsante95/osf.io,jnayak1/osf.io,lyndsysimon/osf.io,acshi/osf.io,chrisseto/osf.io,dplorimer/osf,jinluyuan/osf.io,asanfilippo7/osf.io,kch8qx/osf.io,binoculars/osf.io,fabianvf/osf.io,RomanZWang/osf.io,haoyuchen1992/osf.io,icereval/osf.io,revanthkolli/osf.io,himanshuo/osf.io,GaryKriebel/osf.io
--- +++ @@ -24,9 +24,9 @@ user_settings.revoke_oauth_access(account) user_settings.save() - ExternalAccount.remove_one(account) + # ExternalAccount.remove_one(account) # # only after all addons have been dealt with can we remove it from the user - # user.external_accounts.remove(account) + user.external_accounts.remove(account) user.save() @must_be_logged_in
748e4d7e30e71f88095554db3d898c1702d17b50
wuvt/admin/__init__.py
wuvt/admin/__init__.py
from flask import Blueprint bp = Blueprint('admin', __name__) from wuvt.admin import views
from flask import Blueprint bp = Blueprint('admin', __name__) from wuvt.admin import views from wuvt import app from wuvt import format_datetime @app.context_processor def utility_processor(): def format_price(amount, currency='$'): return u'{1}{0:.2f}'.format(amount/100, currency) return dict(format_price=format_price, format_datetime=format_datetime)
Add format_price and format_datetime to jinja context.
Add format_price and format_datetime to jinja context.
Python
agpl-3.0
wuvt/wuvt-site,wuvt/wuvt-site,wuvt/wuvt-site,wuvt/wuvt-site
--- +++ @@ -3,3 +3,11 @@ bp = Blueprint('admin', __name__) from wuvt.admin import views +from wuvt import app +from wuvt import format_datetime + +@app.context_processor +def utility_processor(): + def format_price(amount, currency='$'): + return u'{1}{0:.2f}'.format(amount/100, currency) + return dict(format_price=format_price, format_datetime=format_datetime)
e08799591061e5b30723758a8c74e6118e9fe342
bgui/gl_utils.py
bgui/gl_utils.py
# This file handles differences between BGL and PyOpenGL, and provides various # utility functions for OpenGL try: from OpenGL.GL import * from OpenGL.GLU import * from bgl import Buffer USING_BGL = False except ImportError: from bgl import * USING_BGL = True if USING_BGL: _glGenTextures = glGenTextures def glGenTextures(n, textures=None): id_buf = Buffer(GL_INT, n) _glGenTextures(n, id_buf) if textures: textures.extend(id_buf.to_list()) return id_buf.to_list()[0] if n == 1 else id_buf.to_list() _glDeleteTextures = glDeleteTextures def glDeleteTextures(textures): n = len(textures) id_buf = Buffer(GL_INT, n, textures) _glDeleteTextures(n, id_buf) _glGetIntegerv = glGetIntegerv def glGetIntegerv(pname): # Only used for GL_VIEWPORT right now, so assume we want a size 4 Buffer buf = Buffer(GL_INT, 4) _glGetIntegerv(pname, buf) return buf.to_list() else: _glTexImage2D = glTexImage2D def glTexImage2D(target, level, internalFormat, width, height, border, format, type, data): _glTexImage2D(target, level, internalFormat, width, height, border, format, type, data.to_list())
# This file handles differences between BGL and PyOpenGL, and provides various # utility functions for OpenGL try: from bgl import * USING_BGL = True except ImportError: from OpenGL.GL import * from OpenGL.GLU import * from bgl import Buffer if USING_BGL: _glGenTextures = glGenTextures def glGenTextures(n, textures=None): id_buf = Buffer(GL_INT, n) _glGenTextures(n, id_buf) if textures: textures.extend(id_buf.to_list()) return id_buf.to_list()[0] if n == 1 else id_buf.to_list() _glDeleteTextures = glDeleteTextures def glDeleteTextures(textures): n = len(textures) id_buf = Buffer(GL_INT, n, textures) _glDeleteTextures(n, id_buf) _glGetIntegerv = glGetIntegerv def glGetIntegerv(pname): # Only used for GL_VIEWPORT right now, so assume we want a size 4 Buffer buf = Buffer(GL_INT, 4) _glGetIntegerv(pname, buf) return buf.to_list() else: _glTexImage2D = glTexImage2D def glTexImage2D(target, level, internalFormat, width, height, border, format, type, data): _glTexImage2D(target, level, internalFormat, width, height, border, format, type, data.to_list())
Make bgl the default OpenGL implementation snice it is currently faster than PyOpenGL.
Make bgl the default OpenGL implementation snice it is currently faster than PyOpenGL.
Python
mit
Moguri/bgui,Moguri/bgui,Remwrath/bgui,marcioreyes/bgui
--- +++ @@ -2,13 +2,12 @@ # utility functions for OpenGL try: + from bgl import * + USING_BGL = True +except ImportError: from OpenGL.GL import * from OpenGL.GLU import * from bgl import Buffer - USING_BGL = False -except ImportError: - from bgl import * - USING_BGL = True if USING_BGL: _glGenTextures = glGenTextures
0aac6e12a66cec9021a7f5ad0e6beb8821a82d1d
test/lldbplatformutil.py
test/lldbplatformutil.py
""" This module contains functions used by the test cases to hide the architecture and/or the platform dependent nature of the tests. """ def check_first_register_readable(test_case): if test_case.getArchitecture() in ['x86_64', 'i386']: test_case.expect("register read eax", substrs = ['eax = 0x']) elif test_case.getArchitecture() in ['aarch64']: test_case.expect("register read x0", substrs = ['x0 = 0x']) else: # TODO: Add check for other architectures test_case.fail("Unsupported architecture for test case (arch: %s)" % test_case.getArchitecture())
""" This module contains functions used by the test cases to hide the architecture and/or the platform dependent nature of the tests. """ def check_first_register_readable(test_case): if test_case.getArchitecture() in ['amd64', 'x86_64', 'i386']: test_case.expect("register read eax", substrs = ['eax = 0x']) elif test_case.getArchitecture() in ['aarch64']: test_case.expect("register read x0", substrs = ['x0 = 0x']) else: # TODO: Add check for other architectures test_case.fail("Unsupported architecture for test case (arch: %s)" % test_case.getArchitecture())
Add amd64 architecture alias for x86_64
test: Add amd64 architecture alias for x86_64 64-bit x86 is called amd64 on FreeBSD. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@234164 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb
--- +++ @@ -2,7 +2,7 @@ architecture and/or the platform dependent nature of the tests. """ def check_first_register_readable(test_case): - if test_case.getArchitecture() in ['x86_64', 'i386']: + if test_case.getArchitecture() in ['amd64', 'x86_64', 'i386']: test_case.expect("register read eax", substrs = ['eax = 0x']) elif test_case.getArchitecture() in ['aarch64']: test_case.expect("register read x0", substrs = ['x0 = 0x'])
0a97195dc8bb5f6caf68d84b96631c26e0c8c348
linguine/untokenize.py
linguine/untokenize.py
import string def untokenize(tokens): return "".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in tokens]).strip()
import string def untokenize(tokens): #Joins all tokens in the list into a single string. #If a token doesn't start with an apostrophe and isn't a punctuation mark, add a space in front of it before joining. #Then strip the total string so that leading spaces and trailing spaces are removed. return "".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in tokens]).strip()
Add comment clarifying how it operates.
Add comment clarifying how it operates.
Python
mit
jmp3833/linguine-python,rigatoni/linguine-python,kmp3325/linguine-python,Pastafarians/linguine-python
--- +++ @@ -1,3 +1,6 @@ import string def untokenize(tokens): + #Joins all tokens in the list into a single string. + #If a token doesn't start with an apostrophe and isn't a punctuation mark, add a space in front of it before joining. + #Then strip the total string so that leading spaces and trailing spaces are removed. return "".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in tokens]).strip()
3bfaff43564c0776912213afefe2e25664f0b1c0
server/server/urls.py
server/server/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from accounts import views as views admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'django_inventory.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^django/inventory/$', 'inventory.views.index'), url(r'^django/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.detail'), url(r'^django/update/inventory/(?P<item_id>[a-zA-Z0-9-]+)/(?P<new_item_count>\d+)/$', 'inventory.views.updatecount'), url(r'^django/delete/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.delete'), url(r'^django/create/inventory/$', 'inventory.views.create'), url(r'^django/accounts/users/$', views.UserView.as_view()), url(r'^django/accounts/auth/$', views.AuthView.as_view(), name='authenticate'), url(r'^django/admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin from accounts import views as views admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'django_inventory.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^django/inventory/$', 'inventory.views.index'), url(r'^django/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.detail'), url(r'^django/update/inventory/(?P<item_id>[a-zA-Z0-9-]+)/(?P<new_item_count>\d+)/$', 'inventory.views.updatecount'), url(r'^django/delete/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.delete'), url(r'^django/create/inventory/$', 'inventory.views.create'), url(r'^django/accounts/users/$', views.UserView.as_view({'get': 'list', 'post': 'create'})), url(r'^django/accounts/auth/$', views.AuthView.as_view(), name='authenticate'), url(r'^django/admin/', include(admin.site.urls)), )
Add get and post functionality to the auth user stuff.
Add get and post functionality to the auth user stuff.
Python
agpl-3.0
TomDataworks/angular-inventory,TomDataworks/angular-inventory
--- +++ @@ -14,7 +14,7 @@ url(r'^django/update/inventory/(?P<item_id>[a-zA-Z0-9-]+)/(?P<new_item_count>\d+)/$', 'inventory.views.updatecount'), url(r'^django/delete/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.delete'), url(r'^django/create/inventory/$', 'inventory.views.create'), - url(r'^django/accounts/users/$', views.UserView.as_view()), + url(r'^django/accounts/users/$', views.UserView.as_view({'get': 'list', 'post': 'create'})), url(r'^django/accounts/auth/$', views.AuthView.as_view(), name='authenticate'), url(r'^django/admin/', include(admin.site.urls)), )
5ddaf8f653df98752ca67b8bfec9b8adfcf168b1
pgcli/pgtoolbar.py
pgcli/pgtoolbar.py
from prompt_toolkit.layout.toolbars import Toolbar from prompt_toolkit.layout.utils import TokenList from pygments.token import Token class PGToolbar(Toolbar): def __init__(self, token=None): token = token or Token.Toolbar.Status super(self.__class__, self).__init__(token=token) def get_tokens(self, cli, width): result = TokenList() result.append((self.token, ' ')) if cli.current_buffer.completer.smart_completion: result.append((self.token.On, '[F2] Smart Completion: ON ')) else: result.append((self.token.Off, '[F2] Smart Completion: OFF ')) if cli.current_buffer.always_multiline: result.append((self.token.On, '[F3] Multiline: ON')) else: result.append((self.token.Off, '[F3] Multiline: OFF')) if cli.current_buffer.always_multiline: result.append((self.token, ' (Semi-colon [;] will end the line)')) return result
from prompt_toolkit.layout.toolbars import Toolbar from prompt_toolkit.layout.utils import TokenList from pygments.token import Token class PGToolbar(Toolbar): def __init__(self, token=None): token = token or Token.Toolbar.Status super(self.__class__, self).__init__(token=token) def get_tokens(self, cli, width): result = TokenList() result.append((self.token, ' ')) if cli.buffers['default'].completer.smart_completion: result.append((self.token.On, '[F2] Smart Completion: ON ')) else: result.append((self.token.Off, '[F2] Smart Completion: OFF ')) if cli.buffers['default'].always_multiline: result.append((self.token.On, '[F3] Multiline: ON')) else: result.append((self.token.Off, '[F3] Multiline: OFF')) if cli.buffers['default'].always_multiline: result.append((self.token, ' (Semi-colon [;] will end the line)')) return result
Use the default buffer instead of current_buffer.
Use the default buffer instead of current_buffer.
Python
bsd-3-clause
nosun/pgcli,TamasNo1/pgcli,d33tah/pgcli,MattOates/pgcli,suzukaze/pgcli,zhiyuanshi/pgcli,dbcli/vcli,bitemyapp/pgcli,janusnic/pgcli,thedrow/pgcli,dbcli/pgcli,bitemyapp/pgcli,n-someya/pgcli,koljonen/pgcli,johshoff/pgcli,d33tah/pgcli,koljonen/pgcli,lk1ngaa7/pgcli,darikg/pgcli,w4ngyi/pgcli,j-bennet/pgcli,MattOates/pgcli,darikg/pgcli,w4ngyi/pgcli,dbcli/vcli,TamasNo1/pgcli,joewalnes/pgcli,j-bennet/pgcli,nosun/pgcli,yx91490/pgcli,johshoff/pgcli,n-someya/pgcli,janusnic/pgcli,zhiyuanshi/pgcli,dbcli/pgcli,thedrow/pgcli,bitmonk/pgcli,joewalnes/pgcli,lk1ngaa7/pgcli,yx91490/pgcli,bitmonk/pgcli,suzukaze/pgcli
--- +++ @@ -10,17 +10,17 @@ def get_tokens(self, cli, width): result = TokenList() result.append((self.token, ' ')) - if cli.current_buffer.completer.smart_completion: + if cli.buffers['default'].completer.smart_completion: result.append((self.token.On, '[F2] Smart Completion: ON ')) else: result.append((self.token.Off, '[F2] Smart Completion: OFF ')) - if cli.current_buffer.always_multiline: + if cli.buffers['default'].always_multiline: result.append((self.token.On, '[F3] Multiline: ON')) else: result.append((self.token.Off, '[F3] Multiline: OFF')) - if cli.current_buffer.always_multiline: + if cli.buffers['default'].always_multiline: result.append((self.token, ' (Semi-colon [;] will end the line)'))
2edd0ee699cfc0ef66d27ccb87ddefad26aa1a77
Challenges/chall_31.py
Challenges/chall_31.py
#!/usr/local/bin/python3 # Python Challenge - 31 # http://www.pythonchallenge.com/pc/ring/grandpa.html # http://www.pythonchallenge.com/pc/rock/grandpa.html # Username: repeat; Password: switch # Keyword: kohsamui, thailand; ''' Uses Anaconda environment with Pillow for image processing - Python 3.7, numpy, and Pillow (PIL) - Run `source activate imgPIL`, `python chall_31.py` ''' from PIL import Image def main(): ''' Hint: where am I? Picture of rock near a beach short break, this ***REALLY*** has nothing to do with Python Login required: island: country Next page: UFO's ? That was too easy. You are still on 31... Window element with iterations attribute of 128 ''' left = 0.34 top = 0.57 width = 0.036 height = 0.027 max_iter = 128 with Image.open('./mandelbrot_chall_31/mandelbrot.gif') as mandelbrot: pass return 0 if __name__ == '__main__': main()
#!/usr/local/bin/python3 # Python Challenge - 31 # http://www.pythonchallenge.com/pc/ring/grandpa.html # http://www.pythonchallenge.com/pc/rock/grandpa.html # Username: repeat; Password: switch # Keyword: kohsamui, thailand; ''' Uses Anaconda environment with Pillow for image processing - Python 3.7, numpy, and Pillow (PIL) - Run `source activate imgPIL`, `python chall_31.py` ''' from PIL import Image def main(): ''' Hint: where am I? Picture of rock near a beach short break, this ***REALLY*** has nothing to do with Python Login required: island: country -> search for Grandpa rock Next page: UFO's ? That was too easy. You are still on 31... Window element with iterations attribute of 128 ''' left = 0.34 top = 0.57 w_step = 0.036 # x-axis = reals h_step = 0.027 # y-axis = imaginaries max_iter = 128 with Image.open('./mandelbrot_chall_31/mandelbrot.gif') as mandelbrot: w, h = mandelbrot.size print('W: {}, H: {}'.format(w, h)) # f_c(z) = z^2 + c for f_c(0), f_c(f_c(0)), etc. for n_iter in range(max_iter): pass return 0 if __name__ == '__main__': main()
Add info for mandelbrot set
Add info for mandelbrot set
Python
mit
HKuz/PythonChallenge
--- +++ @@ -18,7 +18,7 @@ ''' Hint: where am I? Picture of rock near a beach short break, this ***REALLY*** has nothing to do with Python - Login required: island: country + Login required: island: country -> search for Grandpa rock Next page: UFO's ? That was too easy. You are still on 31... @@ -26,12 +26,18 @@ ''' left = 0.34 top = 0.57 - width = 0.036 - height = 0.027 + w_step = 0.036 # x-axis = reals + h_step = 0.027 # y-axis = imaginaries max_iter = 128 with Image.open('./mandelbrot_chall_31/mandelbrot.gif') as mandelbrot: - pass + w, h = mandelbrot.size + print('W: {}, H: {}'.format(w, h)) + + # f_c(z) = z^2 + c for f_c(0), f_c(f_c(0)), etc. + for n_iter in range(max_iter): + pass + return 0
c5c458cb367a22205e21087b93ff3cc5ed0a149a
app/soc/models/grading_project_survey.py
app/soc/models/grading_project_survey.py
#!/usr/bin/python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GradingProjectSurvey model. """ __authors__ = [ '"Daniel Diniz" <ajaksu@gmail.com>', '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from soc.models.project_survey import ProjectSurvey class GradingProjectSurvey(ProjectSurvey): """Survey for Mentors for each of their StudentProjects. """ def __init__(self, *args, **kwargs): super(GradingProjectSurvey, self).__init__(*args, **kwargs) self.taking_access = 'mentor'
#!/usr/bin/python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GradingProjectSurvey model. """ __authors__ = [ '"Daniel Diniz" <ajaksu@gmail.com>', '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from soc.models.project_survey import ProjectSurvey class GradingProjectSurvey(ProjectSurvey): """Survey for Mentors for each of their StudentProjects. """ def __init__(self, *args, **kwargs): super(GradingProjectSurvey, self).__init__(*args, **kwargs) self.taking_access = 'org'
Set default taking access for GradingProjectSurvey to org.
Set default taking access for GradingProjectSurvey to org. This will allow Mentors and Org Admins to take GradingProjectSurveys in case that an Org Admin has no Mentor roles.
Python
apache-2.0
rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son
--- +++ @@ -32,4 +32,4 @@ def __init__(self, *args, **kwargs): super(GradingProjectSurvey, self).__init__(*args, **kwargs) - self.taking_access = 'mentor' + self.taking_access = 'org'
9e1ea2d7ec5c8e7cfd0c1a15f552b1d5dcdd7546
helusers/providers/helsinki/provider.py
helusers/providers/helsinki/provider.py
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class HelsinkiAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('html_url') def get_avatar_url(self): return self.account.extra_data.get('avatar_url') def to_str(self): dflt = super(HelsinkiAccount, self).to_str() return self.account.extra_data.get('name', dflt) class HelsinkiProvider(OAuth2Provider): id = 'helsinki' name = 'City of Helsinki employees' package = 'helusers.providers.helsinki' account_class = HelsinkiAccount def extract_uid(self, data): return str(data['uuid']) def extract_common_fields(self, data): return dict(email=data.get('email'), username=data.get('username'), name=data.get('full_name')) def get_default_scope(self): return ['read'] providers.registry.register(HelsinkiProvider)
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider from allauth.socialaccount.adapter import DefaultSocialAccountAdapter class HelsinkiAccount(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get('html_url') def get_avatar_url(self): return self.account.extra_data.get('avatar_url') def to_str(self): dflt = super(HelsinkiAccount, self).to_str() return self.account.extra_data.get('name', dflt) class HelsinkiProvider(OAuth2Provider): id = 'helsinki' name = 'City of Helsinki employees' package = 'helusers.providers.helsinki' account_class = HelsinkiAccount def extract_uid(self, data): return str(data['uuid']) def extract_common_fields(self, data): return data.copy() def get_default_scope(self): return ['read'] providers.registry.register(HelsinkiProvider) class SocialAccountAdapter(DefaultSocialAccountAdapter): def populate_user(self, request, sociallogin, data): user = sociallogin.user exclude_fields = ['is_staff', 'password', 'is_superuser'] user_fields = [f.name for f in user._meta.fields if f not in exclude_fields] for field in user_fields: if field in data: setattr(user, field, data[field]) return user
Add account adapter for allauth
Add account adapter for allauth
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
--- +++ @@ -1,6 +1,7 @@ from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider +from allauth.socialaccount.adapter import DefaultSocialAccountAdapter class HelsinkiAccount(ProviderAccount): @@ -25,11 +26,21 @@ return str(data['uuid']) def extract_common_fields(self, data): - return dict(email=data.get('email'), - username=data.get('username'), - name=data.get('full_name')) + return data.copy() def get_default_scope(self): return ['read'] providers.registry.register(HelsinkiProvider) + + +class SocialAccountAdapter(DefaultSocialAccountAdapter): + + def populate_user(self, request, sociallogin, data): + user = sociallogin.user + exclude_fields = ['is_staff', 'password', 'is_superuser'] + user_fields = [f.name for f in user._meta.fields if f not in exclude_fields] + for field in user_fields: + if field in data: + setattr(user, field, data[field]) + return user
df56478315c7b58526fbecf3fdfc4df5326d5ba0
custom_fixers/fix_alt_unicode.py
custom_fixers/fix_alt_unicode.py
# Taken from jinja2. Thanks, Armin Ronacher. # See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide from lib2to3 import fixer_base from lib2to3.fixer_util import Name, BlankLine class FixAltUnicode(fixer_base.BaseFix): PATTERN = """ func=funcdef< 'def' name='__unicode__' parameters< '(' NAME ')' > any+ > """ def transform(self, node, results): name = results['name'] name.replace(Name('__str__', prefix=name.prefix))
# Taken from jinja2. Thanks, Armin Ronacher. # See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide from lib2to3 import fixer_base class FixAltUnicode(fixer_base.BaseFix): PATTERN = "'__unicode__'" def transform(self, node, results): new = node.clone() new.value = '__str__' return new
Simplify python3 unicode fixer and make it replace all occurrences of __unicode__ with __str__.
Simplify python3 unicode fixer and make it replace all occurrences of __unicode__ with __str__.
Python
mit
andreas-h/pybtex,andreas-h/pybtex,chbrown/pybtex,chbrown/pybtex
--- +++ @@ -3,15 +3,12 @@ from lib2to3 import fixer_base -from lib2to3.fixer_util import Name, BlankLine class FixAltUnicode(fixer_base.BaseFix): - PATTERN = """ - func=funcdef< 'def' name='__unicode__' - parameters< '(' NAME ')' > any+ > - """ + PATTERN = "'__unicode__'" def transform(self, node, results): - name = results['name'] - name.replace(Name('__str__', prefix=name.prefix)) + new = node.clone() + new.value = '__str__' + return new
cb83a61df5ed82dd9af7ebd3c01d00a3d88e3491
infosystem/subsystem/domain/resource.py
infosystem/subsystem/domain/resource.py
from infosystem.database import db from infosystem.common.subsystem import entity class Domain(entity.Entity, db.Model): attributes = ['active', 'name', 'parent_id'] attributes += entity.Entity.attributes active = db.Column(db.Boolean(), nullable=False) name = db.Column(db.String(60), nullable=False, unique=True) parent_id = db.Column( db.CHAR(32), db.ForeignKey("domain.id"), nullable=True) def __init__(self, id, name, active=True, parent_id=None, created_at=None, created_by=None, updated_at=None, updated_by=None): super().__init__(id, created_at, created_by, updated_at, updated_by) self.active = active self.name = name self.parent_id = parent_id
from infosystem.database import db from infosystem.common.subsystem import entity class Domain(entity.Entity, db.Model): attributes = ['name', 'parent_id'] attributes += entity.Entity.attributes name = db.Column(db.String(60), nullable=False, unique=True) parent_id = db.Column( db.CHAR(32), db.ForeignKey("domain.id"), nullable=True) def __init__(self, id, name, active=True, parent_id=None, created_at=None, created_by=None, updated_at=None, updated_by=None): super().__init__(id, active, created_at, created_by, updated_at, updated_by) self.name = name self.parent_id = parent_id
Remove attribute from domain and get from entity
Remove attribute from domain and get from entity
Python
apache-2.0
samueldmq/infosystem
--- +++ @@ -4,10 +4,9 @@ class Domain(entity.Entity, db.Model): - attributes = ['active', 'name', 'parent_id'] + attributes = ['name', 'parent_id'] attributes += entity.Entity.attributes - active = db.Column(db.Boolean(), nullable=False) name = db.Column(db.String(60), nullable=False, unique=True) parent_id = db.Column( db.CHAR(32), db.ForeignKey("domain.id"), nullable=True) @@ -15,7 +14,7 @@ def __init__(self, id, name, active=True, parent_id=None, created_at=None, created_by=None, updated_at=None, updated_by=None): - super().__init__(id, created_at, created_by, updated_at, updated_by) - self.active = active + super().__init__(id, active, created_at, created_by, + updated_at, updated_by) self.name = name self.parent_id = parent_id
7ac48c9a474f5a0edd10121f58442326d6e8d75c
backend/geonature/core/command/__init__.py
backend/geonature/core/command/__init__.py
import os import sys from geonature.core.command.main import main import geonature.core.command.create_gn_module # Load modules commands from geonature.utils.env import ROOT_DIR plugin_folder = os.path.join(str(ROOT_DIR), 'external_modules') sys.path.insert(0, os.path.join(plugin_folder)) for dirname in os.listdir(plugin_folder): cmd_file = os.path.join( plugin_folder, dirname, 'backend', 'commands', 'geonature_cmd.py' ) if (os.path.isfile(cmd_file)): module_cms = __import__( "{}.backend.commands.geonature_cmd".format(dirname) )
import os import sys from pathlib import Path from geonature.core.command.main import main import geonature.core.command.create_gn_module # Load modules commands from geonature.utils.env import ROOT_DIR def import_cmd(dirname): try: print("Import module {}".format(dirname)) module_cms = __import__( "{}.backend.commands.geonature_cmd".format(dirname) ) print(" ... Module imported".format(dirname)) except FileNotFoundError as e: # Si l'erreur est liée à un fichier inexistant # création du fichier et réimport de la commande print(" ... FileNotFoundError", e.filename) Path(os.path.dirname(e.filename)).mkdir( parents=True, exist_ok=True ) import_cmd(dirname) plugin_folder = os.path.join(str(ROOT_DIR), 'external_modules') sys.path.insert(0, os.path.join(plugin_folder)) for dirname in os.listdir(plugin_folder): cmd_file = os.path.join( plugin_folder, dirname, 'backend', 'commands', 'geonature_cmd.py' ) if (os.path.isfile(cmd_file)): import_cmd(dirname)
TEST : gestion des exceptions de type FileNotFoundError lors de l'import des commandes d'un module
TEST : gestion des exceptions de type FileNotFoundError lors de l'import des commandes d'un module
Python
bsd-2-clause
PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature
--- +++ @@ -1,5 +1,6 @@ import os import sys +from pathlib import Path from geonature.core.command.main import main import geonature.core.command.create_gn_module @@ -7,6 +8,26 @@ # Load modules commands from geonature.utils.env import ROOT_DIR + + +def import_cmd(dirname): + try: + print("Import module {}".format(dirname)) + + module_cms = __import__( + "{}.backend.commands.geonature_cmd".format(dirname) + ) + + print(" ... Module imported".format(dirname)) + except FileNotFoundError as e: + # Si l'erreur est liée à un fichier inexistant + # création du fichier et réimport de la commande + print(" ... FileNotFoundError", e.filename) + Path(os.path.dirname(e.filename)).mkdir( + parents=True, exist_ok=True + ) + import_cmd(dirname) + plugin_folder = os.path.join(str(ROOT_DIR), 'external_modules') sys.path.insert(0, os.path.join(plugin_folder)) @@ -20,6 +41,5 @@ ) if (os.path.isfile(cmd_file)): - module_cms = __import__( - "{}.backend.commands.geonature_cmd".format(dirname) - ) + import_cmd(dirname) +
e1819c59cc5debde7da26a76fb9d2589b2ad6879
Rynda/settings/test.py
Rynda/settings/test.py
# coding: utf-8 from .local import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } TEST_RUNNER = 'discover_runner.DiscoverRunner' TEST_DISCOVER_ROOT = os.path.join(SITE_ROOT, 'test')
# coding: utf-8 from .local import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } TEST_RUNNER = 'discover_runner.DiscoverRunner' TEST_DISCOVER_ROOT = os.path.join(SITE_ROOT, 'test') SOUTH_TESTS_MIGRATE = False
Test database creator using syncdb instead of South
Test database creator using syncdb instead of South
Python
mit
sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/Rynda
--- +++ @@ -14,3 +14,4 @@ } TEST_RUNNER = 'discover_runner.DiscoverRunner' TEST_DISCOVER_ROOT = os.path.join(SITE_ROOT, 'test') +SOUTH_TESTS_MIGRATE = False
5a8275a498a84d2110f58c1dbde4e67ddfa3748c
scripts/assemble_quests.py
scripts/assemble_quests.py
""" Assembles the zone configurations for each quest into one file. Every quest that is in quest_dir and every zone that is in each quest will be included. Example output: { quest1: [ { zone: A, ... }, { zone: B, ... } ], quest2: [ { zone: X, ... } ] } """ import json import os quest_dir = 'src/quests' output_path = 'src/quests.json' output = {} for quest in os.listdir(quest_dir): questPath = os.path.join(quest_dir, quest) if os.path.isdir(questPath): output[quest] = { 'zones': [] } for zone in sorted(os.listdir(questPath)): with open(os.path.join(questPath, zone, 'zone.json')) as f: data = json.load(f) output[quest]['zones'].append(data) with open(output_path, 'w') as output_file: json.dump(output, output_file, indent=4) print 'Generated ' + output_path
""" Assembles the zone configurations for each quest into one file. Every quest that is in quest_dir and every zone that is in each quest will be included. Example output: { quest1: [ { zone: A, ... }, { zone: B, ... } ], quest2: [ { zone: X, ... } ] } """ import json import os quest_dir = 'src/quests' output_path = 'src/quests.json' output = {} for quest in os.listdir(quest_dir): questPath = os.path.join(quest_dir, quest) if os.path.isdir(questPath): output[quest] = { 'zones': [] } for zone in sorted(os.listdir(questPath)): if os.path.isdir(os.path.join(questPath, zone)): with open(os.path.join(questPath, zone, 'zone.json')) as f: data = json.load(f) output[quest]['zones'].append(data) with open(output_path, 'w') as output_file: json.dump(output, output_file, indent=4) print 'Generated ' + output_path
Fix build issue on OSX.
Fix build issue on OSX. Our script assumes the quest directory only has subdirectories of quests but OSX adds DS_STORE files to each directory and these were being picked up and causing the assemble quests script to fail.
Python
apache-2.0
lliss/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,lliss/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed,azavea/pwd-waterworks-revealed
--- +++ @@ -43,9 +43,10 @@ } for zone in sorted(os.listdir(questPath)): - with open(os.path.join(questPath, zone, 'zone.json')) as f: - data = json.load(f) - output[quest]['zones'].append(data) + if os.path.isdir(os.path.join(questPath, zone)): + with open(os.path.join(questPath, zone, 'zone.json')) as f: + data = json.load(f) + output[quest]['zones'].append(data) with open(output_path, 'w') as output_file: json.dump(output, output_file, indent=4)
f4b50b12ae8ad4da6e04ddc186c077c31af00611
SimpleHTTP404Server.py
SimpleHTTP404Server.py
import os import SimpleHTTPServer class GitHubHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """ Overrides the default request handler to handle GitHub custom 404 pages. (Pretty much a 404.html page in your root.) See https://help.github.com/articles/custom-404-pages This currently only works for erroneous pages in the root directory, but that's enough to test what the 404 page looks like. """ def do_GET(self): path = self.translate_path(self.path) print(self.path) print(path) # If the path doesn't exist, fake it to be the 404 page. if not os.path.exists(path): self.path = '404.html' # Call the superclass methods to actually serve the page. SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) print(self.path) print(self.translate_path(self.path)) SimpleHTTPServer.test(GitHubHandler)
import os import SimpleHTTPServer class GitHubHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """ Overrides the default request handler to handle GitHub custom 404 pages. (Pretty much a 404.html page in your root.) See https://help.github.com/articles/custom-404-pages This currently only works for erroneous pages in the root directory, but that's enough to test what the 404 page looks like. """ def do_GET(self): path = self.translate_path(self.path) # If the path doesn't exist, fake it to be the 404 page. if not os.path.exists(path): self.path = '404.html' # Call the superclass methods to actually serve the page. SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) SimpleHTTPServer.test(GitHubHandler)
Remove some print lines from the fake server.
Remove some print lines from the fake server.
Python
mit
clokep/SimpleHTTP404Server,clokep/SimpleHTTP404Server
--- +++ @@ -15,8 +15,7 @@ """ def do_GET(self): path = self.translate_path(self.path) - print(self.path) - print(path) + # If the path doesn't exist, fake it to be the 404 page. if not os.path.exists(path): self.path = '404.html' @@ -24,8 +23,5 @@ # Call the superclass methods to actually serve the page. SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) - print(self.path) - print(self.translate_path(self.path)) - SimpleHTTPServer.test(GitHubHandler)
6d924b21c40b5881d0b2c56b5550bf93f073e049
txircd/config.py
txircd/config.py
import yaml _defaults = { "bind_client": [ "tcp:6667:interface={::}", "ssl:6697:interface={::}" ], "bind_server": [] } class Config(object): def __init__(self, configFileName): self._configData = {} self._readConfig(configFileName) for key, val in _defaults: if key not in self._configData: self._configData[key] = val def _readConfig(self, fileName): try: with open(fileName, 'r') as configFile: configData = yaml.safe_load(configFile) except Exception as e: raise ConfigReadError (e) for key, val in configData.iteritems(): if key != "include" and key not in self._configData: self._configData[key] = val if "include" in configData: for fileName in configData["include"]: self._readConfig(fileName) def __len__(self): return len(self._configData) def __getitem__(self, key): return self._configData[key] def __setitem__(self, key, value): self._configData[key] = value def getWithDefault(self, key, defaultValue): try: return self._configData[key] except KeyError: return defaultValue class ConfigReadError(Exception): def __init__(self, desc): self.desc = desc def __str__(self): return "Error reading configuration file: {}".format(self.desc)
import yaml _defaults = { "bind_client": [ "tcp:6667:interface={::}" ], "bind_server": [] } class Config(object): def __init__(self, configFileName): self._configData = {} self._readConfig(configFileName) for key, val in _defaults: if key not in self._configData: self._configData[key] = val def _readConfig(self, fileName): try: with open(fileName, 'r') as configFile: configData = yaml.safe_load(configFile) except Exception as e: raise ConfigReadError (e) for key, val in configData.iteritems(): if key != "include" and key not in self._configData: self._configData[key] = val if "include" in configData: for fileName in configData["include"]: self._readConfig(fileName) def __len__(self): return len(self._configData) def __getitem__(self, key): return self._configData[key] def __setitem__(self, key, value): self._configData[key] = value def getWithDefault(self, key, defaultValue): try: return self._configData[key] except KeyError: return defaultValue class ConfigReadError(Exception): def __init__(self, desc): self.desc = desc def __str__(self): return "Error reading configuration file: {}".format(self.desc)
Remove the SSL default since it requires certs
Remove the SSL default since it requires certs
Python
bsd-3-clause
ElementalAlchemist/txircd,Heufneutje/txircd
--- +++ @@ -1,7 +1,7 @@ import yaml _defaults = { - "bind_client": [ "tcp:6667:interface={::}", "ssl:6697:interface={::}" ], + "bind_client": [ "tcp:6667:interface={::}" ], "bind_server": [] }
139eac65c71c729e7500dfe894dc9686bd384ab4
UConnRCMPy/constants.py
UConnRCMPy/constants.py
""" Constants used in UConnRCMPy. """ import cantera one_atm_in_torr = 760.0 """Conversion between atmosphere and Torr.""" one_atm_in_bar = 1.01325 """Conversion between atmosphere and bar.""" one_bar_in_pa = 1E5 """Conversion between bar and Pascal.""" cantera_version = None """Installed version of Cantera software.""" try: cantera_version = map(int, cantera.__version__.split('.')) except ValueError: cantera_version = map(int, cantera.__version__.split('.')[0:2]) cantera_version.append(int(cantera.__version__.split('.')[2][0]))
""" Constants used in UConnRCMPy. """ import cantera one_atm_in_torr = 760.0 """Conversion between atmosphere and Torr.""" one_atm_in_bar = 1.01325 """Conversion between atmosphere and bar.""" one_bar_in_pa = 1E5 """Conversion between bar and Pascal.""" cantera_version = None """Installed version of Cantera software.""" try: cantera_version = list(map(int, cantera.__version__.split('.'))) except ValueError: cantera_version = list(map(int, cantera.__version__.split('.')[0:2])) cantera_version.append(int(cantera.__version__.split('.')[2][0]))
Fix map object not subscriptable in cantera_version
Fix map object not subscriptable in cantera_version
Python
bsd-3-clause
bryanwweber/UConnRCMPy
--- +++ @@ -13,7 +13,7 @@ """Installed version of Cantera software.""" try: - cantera_version = map(int, cantera.__version__.split('.')) + cantera_version = list(map(int, cantera.__version__.split('.'))) except ValueError: - cantera_version = map(int, cantera.__version__.split('.')[0:2]) + cantera_version = list(map(int, cantera.__version__.split('.')[0:2])) cantera_version.append(int(cantera.__version__.split('.')[2][0]))
acbace21652d45a5fb17bbb487692ab6057313df
api/parsers/datanasa.py
api/parsers/datanasa.py
import json from flaskext.mongoalchemy import MongoAlchemy import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() data = db.StringField() def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) dataset_data = json.loads(response.text) dataset = Dataset(remote_id = id, data=response.text) dataset.save()
import json from flaskext.mongoalchemy import BaseQuery import requests from api import app from api import db ENDPOINT = 'http://data.nasa.gov/api/' class DatasetQuery(BaseQuery): def get_by_remote_id(self, pk): return self.filter(self.type.remote_id==pk) class Dataset(db.Document): """ Represents a dataset, we could split this out to hold all the actual data, slug, url, title, etc """ remote_id = db.IntField() data = db.StringField() query_class = DatasetQuery def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) dataset_data = json.loads(response.text) dataset = Dataset(remote_id = id, data=response.text) dataset.save()
Define a query on Dataset to retrive them by remote id
Define a query on Dataset to retrive them by remote id
Python
mit
oxford-space-apps/open-data-api
--- +++ @@ -1,5 +1,5 @@ import json -from flaskext.mongoalchemy import MongoAlchemy +from flaskext.mongoalchemy import BaseQuery import requests from api import app @@ -7,6 +7,12 @@ ENDPOINT = 'http://data.nasa.gov/api/' + + +class DatasetQuery(BaseQuery): + def get_by_remote_id(self, pk): + return self.filter(self.type.remote_id==pk) + class Dataset(db.Document): """ Represents a dataset, @@ -16,8 +22,12 @@ remote_id = db.IntField() data = db.StringField() + query_class = DatasetQuery + + def get_dataset(id): response = requests.get(ENDPOINT + 'get_dataset?id=%s' % id) dataset_data = json.loads(response.text) dataset = Dataset(remote_id = id, data=response.text) dataset.save() +
044f1169b518628c8409a38845ffa5c18b7cb748
packs/clicrud/actions/config_command.py
packs/clicrud/actions/config_command.py
# encoding: utf-8 from st2actions.runners.pythonrunner import Action from clicrud.device.generic import generic import sys class ConfigCommand(Action): def run(self, host, command, save): self.method = self.config['method'] self.username = self.config['username'] self.password = self.config['password'] self.enable = self.config['enable'] self.method = self.method.encode('utf-8', 'ignore') self.username = self.username.encode('utf-8', 'ignore') self.password = self.password.encode('utf-8', 'ignore') self.enable = self.enable.encode('utf-8', 'ignore') utf8_host = host.encode('utf-8', 'ignore') utf8_commands = [] for cmd in command: utf8_commands.append(cmd.encode('utf-8', 'ignore')) try: transport = generic(host=utf8_host, username=self.username, enable=self.enable, method=self.method, password=self.password) return_value = transport.configure(utf8_commands) _return_value = str(return_value).encode('utf-8', 'ignore') if save is True: transport.configure(["write mem"]) transport.close() return _return_value except Exception, err: self.logger.info('FUBARd') self.logger.info(err) sys.exit(2)
# encoding: utf-8 from st2actions.runners.pythonrunner import Action from clicrud.device.generic import generic import sys class ConfigCommand(Action): def run(self, host, command, save): self.method = self.config['method'] self.username = self.config['username'] self.password = self.config['password'] self.enable = self.config['enable'] self.method = self.method.encode('utf-8', 'ignore') self.username = self.username.encode('utf-8', 'ignore') self.password = self.password.encode('utf-8', 'ignore') self.enable = self.enable.encode('utf-8', 'ignore') utf8_host = host.encode('utf-8', 'ignore') utf8_commands = [] for cmd in command: utf8_commands.append(cmd.encode('utf-8', 'ignore')) transport = None try: transport = generic(host=utf8_host, username=self.username, enable=self.enable, method=self.method, password=self.password) return_value = transport.configure(utf8_commands) _return_value = str(return_value).encode('utf-8', 'ignore') if save is True: transport.configure(["write mem"]) return _return_value except Exception as err: self.logger.exception('Config command threw an exception') self.logger.error(err) sys.exit(2) finally: if transport: transport.close()
Use finally so connection is also closed on exception.
Use finally so connection is also closed on exception.
Python
apache-2.0
StackStorm/st2contrib,StackStorm/st2contrib,StackStorm/st2contrib
--- +++ @@ -24,8 +24,9 @@ for cmd in command: utf8_commands.append(cmd.encode('utf-8', 'ignore')) + transport = None + try: - transport = generic(host=utf8_host, username=self.username, enable=self.enable, method=self.method, password=self.password) @@ -36,9 +37,11 @@ if save is True: transport.configure(["write mem"]) - transport.close() return _return_value - except Exception, err: - self.logger.info('FUBARd') - self.logger.info(err) + except Exception as err: + self.logger.exception('Config command threw an exception') + self.logger.error(err) sys.exit(2) + finally: + if transport: + transport.close()
43291c827d2d7b0a350971b2efa26ca9e1c1e593
src/sentry/api/endpoints/system_health.py
src/sentry/api/endpoints/system_health.py
from __future__ import absolute_import import itertools from rest_framework.response import Response from sentry import status_checks from sentry.api.base import Endpoint from sentry.api.permissions import SuperuserPermission class SystemHealthEndpoint(Endpoint): permission_classes = (SuperuserPermission,) def get(self, request): results = status_checks.check_all() return Response({ 'problems': map( lambda problem: { 'message': problem.message, 'severity': problem.severity, 'url': problem.url, }, sorted(itertools.chain.from_iterable(results.values()), reverse=True), ), 'healthy': {type(check).__name__: not problems for check, problems in results.items()}, })
from __future__ import absolute_import import itertools from hashlib import md5 from rest_framework.response import Response from sentry import status_checks from sentry.api.base import Endpoint from sentry.api.permissions import SuperuserPermission class SystemHealthEndpoint(Endpoint): permission_classes = (SuperuserPermission,) def get(self, request): results = status_checks.check_all() return Response({ 'problems': map( lambda problem: { 'id': md5(problem.message).hexdigest(), 'message': problem.message, 'severity': problem.severity, 'url': problem.url, }, sorted(itertools.chain.from_iterable(results.values()), reverse=True), ), 'healthy': {type(check).__name__: not problems for check, problems in results.items()}, })
Add `id` to `SystemHealthEndpoint` response.
Add `id` to `SystemHealthEndpoint` response.
Python
bsd-3-clause
gencer/sentry,zenefits/sentry,looker/sentry,alexm92/sentry,JackDanger/sentry,zenefits/sentry,alexm92/sentry,ifduyue/sentry,ifduyue/sentry,beeftornado/sentry,fotinakis/sentry,jean/sentry,JamesMura/sentry,BuildingLink/sentry,mvaled/sentry,BuildingLink/sentry,mvaled/sentry,mvaled/sentry,mvaled/sentry,JamesMura/sentry,beeftornado/sentry,BuildingLink/sentry,ifduyue/sentry,ifduyue/sentry,jean/sentry,mitsuhiko/sentry,zenefits/sentry,fotinakis/sentry,jean/sentry,gencer/sentry,alexm92/sentry,mitsuhiko/sentry,mvaled/sentry,looker/sentry,JackDanger/sentry,fotinakis/sentry,looker/sentry,JackDanger/sentry,BuildingLink/sentry,jean/sentry,beeftornado/sentry,fotinakis/sentry,looker/sentry,looker/sentry,ifduyue/sentry,zenefits/sentry,gencer/sentry,JamesMura/sentry,JamesMura/sentry,jean/sentry,gencer/sentry,gencer/sentry,BuildingLink/sentry,mvaled/sentry,zenefits/sentry,JamesMura/sentry
--- +++ @@ -1,6 +1,7 @@ from __future__ import absolute_import import itertools +from hashlib import md5 from rest_framework.response import Response @@ -17,6 +18,7 @@ return Response({ 'problems': map( lambda problem: { + 'id': md5(problem.message).hexdigest(), 'message': problem.message, 'severity': problem.severity, 'url': problem.url,
8a16f7d51d34573d41846da25664b084ff6eb071
publication_figures.py
publication_figures.py
""" Create nice looking publication figures """ import numpy as np import networkx as nx import seaborn as sns import matplotlib as mpl import matplotlib.pylab as plt from tqdm import tqdm from main import analyze_system from setup import generate_basic_system from nm_data_generator import add_node_to_system def visualize_node_influence(): """ Compare examples where fourth node perturbs system and where it doesn't """ def simulate(syst, reps=1000): matrices = [] with tqdm(total=reps) as pbar: while reps >= 0: _, mat, _ = analyze_system(syst, repetition_num=1) if mat is None: continue pbar.update() reps -= 1 if mat.shape == (4, 4): mat = mat[:-1, :-1] assert mat.shape == (3, 3) matrices.append(mat) return np.asarray(matrices) def plot_correlation_hist(matrices, ax): for i, row in enumerate(matrices.T): for j, series in enumerate(row): if i == j: break sns.distplot(series, ax=ax, label=r'$c_{{{},{}}}$'.format(i,j)) ax.set_xlabel('correlation') ax.set_ylabel('count') ax.set_xlim((-1,1)) ax.legend(loc='best') def plot_system(syst, ax): graph = nx.from_numpy_matrix(syst.jacobian.T, create_using=nx.DiGraph()) nx.draw( graph, ax=ax, with_labels=True) ax.axis('off') ax.set_xticks([], []) ax.set_yticks([], []) # generate systems basic_system = generate_basic_system() more_systs = add_node_to_system(basic_system) similar_system = more_systs[42] different_system = more_systs[22] # 52 systems = { 'basic': basic_system, 'similar': similar_system, 'different_system': different_system } # simulations matrices = {} for name, syst in systems.items(): matrices[name] = (syst, simulate(syst)) # plot result for name, (syst, mats) in matrices.items(): plt.figure() plot_correlation_hist(mats, plt.gca()) plot_system(syst, plt.axes([.3,.5,.3,.3])) plt.savefig(f'images/node_influence_{name}.pdf') def main(): visualize_node_influence() if __name__ == '__main__': sns.set_style('white') plt.style.use('seaborn-poster') main()
Create some more nice figures
Create some more nice figures
Python
mit
kpj/SDEMotif,kpj/SDEMotif
--- +++ @@ -0,0 +1,93 @@ +""" + Create nice looking publication figures +""" + +import numpy as np +import networkx as nx + +import seaborn as sns +import matplotlib as mpl +import matplotlib.pylab as plt + +from tqdm import tqdm + +from main import analyze_system +from setup import generate_basic_system +from nm_data_generator import add_node_to_system + + +def visualize_node_influence(): + """ Compare examples where fourth node perturbs system and where it doesn't + """ + def simulate(syst, reps=1000): + matrices = [] + with tqdm(total=reps) as pbar: + while reps >= 0: + _, mat, _ = analyze_system(syst, repetition_num=1) + if mat is None: + continue + pbar.update() + reps -= 1 + + if mat.shape == (4, 4): + mat = mat[:-1, :-1] + assert mat.shape == (3, 3) + + matrices.append(mat) + return np.asarray(matrices) + + def plot_correlation_hist(matrices, ax): + for i, row in enumerate(matrices.T): + for j, series in enumerate(row): + if i == j: break + + sns.distplot(series, ax=ax, label=r'$c_{{{},{}}}$'.format(i,j)) + + ax.set_xlabel('correlation') + ax.set_ylabel('count') + ax.set_xlim((-1,1)) + ax.legend(loc='best') + + def plot_system(syst, ax): + graph = nx.from_numpy_matrix(syst.jacobian.T, create_using=nx.DiGraph()) + nx.draw( + graph, ax=ax, + with_labels=True) + ax.axis('off') + ax.set_xticks([], []) + ax.set_yticks([], []) + + # generate systems + basic_system = generate_basic_system() + more_systs = add_node_to_system(basic_system) + + similar_system = more_systs[42] + different_system = more_systs[22] # 52 + + systems = { + 'basic': basic_system, + 'similar': similar_system, + 'different_system': different_system + } + + # simulations + matrices = {} + for name, syst in systems.items(): + matrices[name] = (syst, simulate(syst)) + + # plot result + for name, (syst, mats) in matrices.items(): + plt.figure() + plot_correlation_hist(mats, plt.gca()) + plot_system(syst, plt.axes([.3,.5,.3,.3])) + plt.savefig(f'images/node_influence_{name}.pdf') + +def main(): + visualize_node_influence() + + +if __name__ == '__main__': + sns.set_style('white') + plt.style.use('seaborn-poster') + + main()
f617c1ce192739594c161f717d5d04cc17ede22e
distarray/local/tests/paralleltest_io.py
distarray/local/tests/paralleltest_io.py
import tempfile import h5py from numpy.testing import assert_allclose from os import path from distarray.local import LocalArray, save, load, save_hdf5 from distarray.testing import comm_null_passes, MpiTestCase class TestFlatFileIO(MpiTestCase): @comm_null_passes def test_flat_file_read_write(self): larr0 = LocalArray((7,), comm=self.comm) output_dir = tempfile.gettempdir() filename = 'outfile' output_path = path.join(output_dir, filename) save(output_path, larr0) larr1 = load(output_path, comm=self.comm) self.assertTrue(isinstance(larr1, LocalArray)) assert_allclose(larr0, larr1) class TestHDF5FileIO(MpiTestCase): @comm_null_passes def test_hdf5_file_write(self): dataset = "data" larr0 = LocalArray((51,), comm=self.comm) output_dir = tempfile.gettempdir() filename = 'outfile' output_path = path.join(output_dir, filename) save_hdf5(output_path, larr0, dataset=dataset) self.assertTrue(path.exists(output_path)) fp = h5py.File(output_path, 'r') self.assertTrue("data" in fp) fp.close()
import tempfile from numpy.testing import assert_allclose from os import path from distarray.local import LocalArray, save, load, save_hdf5 from distarray.testing import comm_null_passes, MpiTestCase class TestFlatFileIO(MpiTestCase): @comm_null_passes def test_flat_file_read_write(self): larr0 = LocalArray((7,), comm=self.comm) output_dir = tempfile.gettempdir() filename = 'outfile' output_path = path.join(output_dir, filename) save(output_path, larr0) larr1 = load(output_path, comm=self.comm) self.assertTrue(isinstance(larr1, LocalArray)) assert_allclose(larr0, larr1) class TestHDF5FileIO(MpiTestCase): @comm_null_passes def test_hdf5_file_write(self): import h5py dataset = "data" larr0 = LocalArray((51,), comm=self.comm) output_dir = tempfile.gettempdir() filename = 'outfile' output_path = path.join(output_dir, filename) save_hdf5(output_path, larr0, dataset=dataset) self.assertTrue(path.exists(output_path)) fp = h5py.File(output_path, 'r') self.assertTrue("data" in fp) fp.close()
Move h5py import into HDF test.
Move h5py import into HDF test.
Python
bsd-3-clause
RaoUmer/distarray,enthought/distarray,RaoUmer/distarray,enthought/distarray
--- +++ @@ -1,5 +1,4 @@ import tempfile -import h5py from numpy.testing import assert_allclose from os import path from distarray.local import LocalArray, save, load, save_hdf5 @@ -24,6 +23,8 @@ @comm_null_passes def test_hdf5_file_write(self): + import h5py + dataset = "data" larr0 = LocalArray((51,), comm=self.comm) output_dir = tempfile.gettempdir()
b80eae0285af97d8fe954a5df667e03b004efa12
instrument-classification/leaderboard.py
instrument-classification/leaderboard.py
import glob import numpy as np import pandas as pd def load_df(file_name): model_id = file_name.split('/')[4] df = pd.read_csv(file_name) df.rename(columns={'Unnamed: 0': 'split'}, inplace=True) df['model_id'] = model_id if 'auc' not in df.columns: df['auc'] = np.nan df = df[['model_id', 'split', 'loss', 'error', 'auc']] return df files = glob.glob('data/working/single-notes-2000/models/*/evaluation/final_metrics.csv') df = pd.concat([load_df(f) for f in files]) df_valid = df[df['split'] == 'valid'] df_valid.set_index('model_id', inplace=True) print('Ranking on the validation split metrics.\n') print('Lowest error:') print(df_valid.sort_values('error', ascending=True)[:5]) print('\nHighest AUC:') print(df_valid.sort_values('auc', ascending=False)[:5]) print('\nRank of the last few models by error, total:', len(df_valid)) print(df_valid.rank()['error'].astype(int).iloc[-5:])
import glob import numpy as np import pandas as pd def load_df(file_name): model_id = file_name.split('/')[4] df = pd.read_csv(file_name) df.rename(columns={'Unnamed: 0': 'split'}, inplace=True) df['model_id'] = model_id if 'auc' not in df.columns: df['auc'] = np.nan df = df[['model_id', 'split', 'loss', 'error', 'auc']] return df files = sorted(glob.glob('data/working/single-notes-2000/models/*/evaluation/final_metrics.csv')) df = pd.concat([load_df(f) for f in files]) df_valid = df[df['split'] == 'valid'] df_valid.set_index('model_id', inplace=True) print('Ranking on the validation split metrics.\n') print('Lowest error:') print(df_valid.sort_values('error', ascending=True)[:5]) print('\nHighest AUC:') print(df_valid.sort_values('auc', ascending=False)[:5]) print('\nRank of the last few models by error, total:', len(df_valid)) print(df_valid.rank()['error'].astype(int).iloc[-5:])
Fix ordering of latest models on the leader board.
Fix ordering of latest models on the leader board.
Python
mit
bzamecnik/ml-playground,bzamecnik/ml-playground,bzamecnik/ml,bzamecnik/ml,bzamecnik/ml
--- +++ @@ -12,7 +12,7 @@ df = df[['model_id', 'split', 'loss', 'error', 'auc']] return df -files = glob.glob('data/working/single-notes-2000/models/*/evaluation/final_metrics.csv') +files = sorted(glob.glob('data/working/single-notes-2000/models/*/evaluation/final_metrics.csv')) df = pd.concat([load_df(f) for f in files]) df_valid = df[df['split'] == 'valid']
80d0ba5716d4b6cdef1c5d64a670abfa59f81557
bin/verify_cached_graphs.py
bin/verify_cached_graphs.py
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): cached = flow.get_cached_graph(ignore_balances) if not cached: continue graph = flow.build_graph(ignore_balances) diff = compare(cached, graph) if diff: pp(diff) return False return True def compare(g1, g2): e1 = set(normalize(g1.edges(data=True))) e2 = set(normalize(g2.edges(data=True))) return e1.symmetric_difference(e2) def normalize(edge_list): return ((src, dest, data['capacity'], data['weight'], data['creditline_id']) for src, dest, data in edge_list) if __name__ == '__main__': if verify(): print 'OK.' sys.exit(0) else: print 'Mismatch.' sys.exit(1)
#!/usr/bin/env python import sys from pprint import pprint as pp from cc.payment import flow def verify(): for ignore_balances in (True, False): graph = flow.build_graph(ignore_balances) cached = flow.get_cached_graph(ignore_balances) if not cached: flow.set_cached_graph(graph, ignore_balances) continue diff = compare(cached, graph) if diff: pp(diff) return False return True def compare(g1, g2): e1 = set(normalize(g1.edges(data=True))) e2 = set(normalize(g2.edges(data=True))) return e1.symmetric_difference(e2) def normalize(edge_list): return ((src, dest, data['capacity'], data['weight'], data['creditline_id']) for src, dest, data in edge_list) if __name__ == '__main__': if verify(): print 'OK.' sys.exit(0) else: print 'Mismatch.' sys.exit(1)
Load cached graph in verify cached graphs tool if not already present.
Load cached graph in verify cached graphs tool if not already present.
Python
agpl-3.0
rfugger/villagescc,rfugger/villagescc,rfugger/villagescc,rfugger/villagescc
--- +++ @@ -7,10 +7,11 @@ def verify(): for ignore_balances in (True, False): + graph = flow.build_graph(ignore_balances) cached = flow.get_cached_graph(ignore_balances) if not cached: + flow.set_cached_graph(graph, ignore_balances) continue - graph = flow.build_graph(ignore_balances) diff = compare(cached, graph) if diff: pp(diff)
cca17afe5ed3937713e86f9a8d9c3be0dcdf60b0
aiosparkapi/__init__.py
aiosparkapi/__init__.py
import aiosparkapi.requests from .api.messages import Messages from .api.webhooks import Webhooks from .api.people import People import aiohttp class AioSparkApi: def __init__(self, *, access_token): self._client = aiohttp.ClientSession('https://api.ciscospark.com/v1/') self._requests = aiosparkapi.requests.Requests( access_token, self._client) self.messages = Messages(self._requests) self.webhooks = Webhooks(self._requests) self.people = People(self._requests) __all__ = ['AioSparkApi']
Add a AioSparkApi class to set up the whole thing
Add a AioSparkApi class to set up the whole thing
Python
mit
martiert/aiosparkapi
--- +++ @@ -0,0 +1,22 @@ +import aiosparkapi.requests +from .api.messages import Messages +from .api.webhooks import Webhooks +from .api.people import People + +import aiohttp + + +class AioSparkApi: + + def __init__(self, *, access_token): + self._client = aiohttp.ClientSession('https://api.ciscospark.com/v1/') + self._requests = aiosparkapi.requests.Requests( + access_token, + self._client) + + self.messages = Messages(self._requests) + self.webhooks = Webhooks(self._requests) + self.people = People(self._requests) + + +__all__ = ['AioSparkApi']
75cec3cef9fb73ec3a4068cc35dc33f3f492275b
bin/public/extract_challenge_uuids.py
bin/public/extract_challenge_uuids.py
# Exports all data for the particular user for the particular day # Used for debugging issues with trip and section generation import sys import logging logging.basicConfig(level=logging.DEBUG) import gzip import json import emission.core.wrapper.user as ecwu # Input data using one email per line (easy to copy/paste) # Output data using json (easy to serialize and re-read) if __name__ == '__main__': if len(sys.argv) != 3: print "Usage: %s user_email_file user_id_file" else: user_email_filename = sys.argv[1] uuid_filename = sys.argv[2] emails = open(user_email_filename).readlines() uuids = [ecwu.User.fromEmail(e.strip()).uuid for e in emails] uuid_strs = [str(u) for u in uuids] json.dump(uuid_strs, open(uuid_filename, "w"))
# Exports all data for the particular user for the particular day # Used for debugging issues with trip and section generation import sys import logging logging.basicConfig(level=logging.DEBUG) import gzip import json import emission.core.wrapper.user as ecwu # Input data using one email per line (easy to copy/paste) # Output data using json (easy to serialize and re-read) if __name__ == '__main__': if len(sys.argv) != 3: print "Usage: %s user_email_file user_id_file" else: user_email_filename = sys.argv[1] uuid_filename = sys.argv[2] emails = open(user_email_filename).readlines() uuids = [] for e in emails: user = ecwu.User.fromEmail(e.strip()) if user is None: logging.warning("Found no mapping for email %s" % e) else: uuid = user.uuid logging.debug("Mapped email %s to uuid %s" % (e, uuid)) uuids.append(uuid) uuid_strs = [str(u) for u in uuids] json.dump(uuid_strs, open(uuid_filename, "w"))
Support use case where the user sent consent from the wrong email
Support use case where the user sent consent from the wrong email
Python
bsd-3-clause
sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server
--- +++ @@ -19,6 +19,15 @@ uuid_filename = sys.argv[2] emails = open(user_email_filename).readlines() - uuids = [ecwu.User.fromEmail(e.strip()).uuid for e in emails] + uuids = [] + for e in emails: + user = ecwu.User.fromEmail(e.strip()) + if user is None: + logging.warning("Found no mapping for email %s" % e) + else: + uuid = user.uuid + logging.debug("Mapped email %s to uuid %s" % (e, uuid)) + uuids.append(uuid) + uuid_strs = [str(u) for u in uuids] json.dump(uuid_strs, open(uuid_filename, "w"))
610eeb064ba95e79617650d939ae5e9110b6ab89
restlib2/structures.py
restlib2/structures.py
import re class AttrDict(object): "A case-insensitive attribute accessible dict-like object" def __init__(self, name, *args, **kwargs): for key, value in dict(*args, **kwargs).iteritems(): if not isinstance(key, basestring) or not key: raise TypeError('attribute names must be non-empty strings') if key[0].isdigit(): raise ValueError('attribute names cannot begin with a number') _key = re.sub(r'[^\w\d_]+', ' ', re.sub(r'[\s-]+', '_', key.upper())) self.__dict__[_key] = value def __repr__(self): return u'<AttrDict: %s>' % self.name def __getattr__(self, key): _key = key.upper() if _key not in self.__dict__: raise AttributeError("AttrDict object has not attribute '{0}'".format(key)) return self.__dict__[_key] def __contains__(self, key): return self.__dict__.__contains__(key.upper()) def __iter__(self): return self.__dict__.__iter__()
import re class AttrDict(object): "A case-insensitive attribute accessible dict-like object" def __init__(self, name, *args, **kwargs): self.name = name for key, value in dict(*args, **kwargs).iteritems(): if not isinstance(key, basestring) or not key: raise TypeError('attribute names must be non-empty strings') if key[0].isdigit(): raise ValueError('attribute names cannot begin with a number') _key = re.sub(r'[^\w\d_]+', ' ', re.sub(r'[\s-]+', '_', key.upper())) self.__dict__[_key] = value def __repr__(self): return u'<AttrDict: %s>' % self.name def __getattr__(self, key): _key = key.upper() if _key not in self.__dict__: raise AttributeError("AttrDict object has not attribute '{0}'".format(key)) return self.__dict__[_key] def __contains__(self, key): return self.__dict__.__contains__(key.upper()) def __iter__(self): return self.__dict__.__iter__()
Add missing assignment of name in constructor
Add missing assignment of name in constructor
Python
bsd-2-clause
bruth/restlib2
--- +++ @@ -4,6 +4,8 @@ class AttrDict(object): "A case-insensitive attribute accessible dict-like object" def __init__(self, name, *args, **kwargs): + self.name = name + for key, value in dict(*args, **kwargs).iteritems(): if not isinstance(key, basestring) or not key: raise TypeError('attribute names must be non-empty strings')
373d5d55279695ead6b83fb99824a3249416697f
auditlog/__openerp__.py
auditlog/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
Add OCA as author of OCA addons
Add OCA as author of OCA addons In order to get visibility on https://www.odoo.com/apps the OCA board has decided to add the OCA as author of all the addons maintained as part of the association.
Python
agpl-3.0
YannickB/server-tools,YannickB/server-tools,OCA/server-tools,YannickB/server-tools,OCA/server-tools,OCA/server-tools
--- +++ @@ -22,7 +22,7 @@ { 'name': "Audit Log", 'version': "1.0", - 'author': "ABF OSIELL", + 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [
3535ea637112ef21fefd8df811721d271c109581
salt/runners/manage.py
salt/runners/manage.py
''' General management functions for salt, tools like seeing what hosts are up and what hosts are down ''' # Import salt modules import salt.client import salt.cli.key def down(): ''' Print a list of all the down or unresponsive salt minions ''' client = salt.client.LocalClient(__opts__['config']) key = salt.cli.key.Key(__opts__) minions = client.cmd('*', 'test.ping', timeout=1) keys = key._keys('acc') for minion in minions: keys.remove(minion) for minion in sorted(keys): print minion
''' General management functions for salt, tools like seeing what hosts are up and what hosts are down ''' # Import salt modules import salt.client import salt.cli.key def down(): ''' Print a list of all the down or unresponsive salt minions ''' client = salt.client.LocalClient(__opts__['config']) key = salt.cli.key.Key(__opts__) minions = client.cmd('*', 'test.ping', timeout=1) keys = key._keys('acc') for minion in minions: keys.remove(minion) for minion in sorted(keys): print minion def up(): ''' Print a list of all of the minions that are up ''' client = salt.client.LocalClient(__opts__['config']) minions = client.cmd('*', 'test.ping', timeout=1) for minion in sorted(minions): print minion
Add an "up" to list all "up" minions
Add an "up" to list all "up" minions
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -19,3 +19,12 @@ keys.remove(minion) for minion in sorted(keys): print minion + +def up(): + ''' + Print a list of all of the minions that are up + ''' + client = salt.client.LocalClient(__opts__['config']) + minions = client.cmd('*', 'test.ping', timeout=1) + for minion in sorted(minions): + print minion
c34960e07ccce749a7fb5e53ff7593b87fe453d7
sazabi/plugins/joke.py
sazabi/plugins/joke.py
import requests from random import choice from sazabi.types import SazabiBotPlugin class Joke(SazabiBotPlugin): async def parse(self, client, message, *args, **kwargs): if message.content == "~joke": response = requests.get('https://www.reddit.com/r/oneliners/new.json').json() if response is not None: try: response = choice(response.get('data').get('children')) joke_url = response.get('data').get('title') hold = await client.send_message(message.channel, joke_url) except Exception as e: self.logger.exception('Joke command failed!') raise e
import requests from random import choice from sazabi.types import SazabiBotPlugin class Joke(SazabiBotPlugin): async def parse(self, client, message, *args, **kwargs): if message.content == "~joke": response = requests.get( 'https://www.reddit.com/r/oneliners/new.json', headers={'User-agent': 'sazabi-bot'}).json() if response is not None: try: response = choice(response.get('data').get('children')) joke_url = response.get('data').get('title') hold = await client.send_message(message.channel, joke_url) except Exception as e: self.logger.exception('Joke command failed!') raise e
Add user agent to reddit request
Add user agent to reddit request
Python
mit
frankzhao/sazabi,frankzhao/sazabi
--- +++ @@ -7,7 +7,9 @@ class Joke(SazabiBotPlugin): async def parse(self, client, message, *args, **kwargs): if message.content == "~joke": - response = requests.get('https://www.reddit.com/r/oneliners/new.json').json() + response = requests.get( + 'https://www.reddit.com/r/oneliners/new.json', + headers={'User-agent': 'sazabi-bot'}).json() if response is not None: try: response = choice(response.get('data').get('children'))
dd1e6cdf2f6f040f532863549df606083f3f4bf2
utils/gyb_syntax_support/protocolsMap.py
utils/gyb_syntax_support/protocolsMap.py
SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = { 'ExpressibleAsConditionElement': [ 'ExpressibleAsConditionElementList' ], 'ExpressibleAsDeclBuildable': [ 'ExpressibleAsCodeBlockItem', 'ExpressibleAsMemberDeclListItem', 'ExpressibleAsSyntaxBuildable' ], 'ExpressibleAsStmtBuildable': [ 'ExpressibleAsCodeBlockItem', 'ExpressibleAsSyntaxBuildable' ], 'ExpressibleAsExprList': [ 'ExpressibleAsConditionElement', 'ExpressibleAsSyntaxBuildable' ] }
SYNTAX_BUILDABLE_EXPRESSIBLE_BY_CONFORMANCES = { 'ExpressibleByConditionElement': [ 'ExpressibleByConditionElementList' ], 'ExpressibleByDeclBuildable': [ 'ExpressibleByCodeBlockItem', 'ExpressibleByMemberDeclListItem', 'ExpressibleBySyntaxBuildable' ], 'ExpressibleByStmtBuildable': [ 'ExpressibleByCodeBlockItem', 'ExpressibleBySyntaxBuildable' ], 'ExpressibleByExprList': [ 'ExpressibleByConditionElement', 'ExpressibleBySyntaxBuildable' ] }
Replace ExpressibleAs protocols by ExpressibleBy protocols
[SwiftSyntax] Replace ExpressibleAs protocols by ExpressibleBy protocols The protocols in the standard library are called `ExpressibleBy*` and SwiftSyntax should follow the same naming convention.
Python
apache-2.0
JGiola/swift,apple/swift,gregomni/swift,atrick/swift,roambotics/swift,benlangmuir/swift,atrick/swift,roambotics/swift,ahoppen/swift,glessard/swift,apple/swift,ahoppen/swift,gregomni/swift,gregomni/swift,glessard/swift,atrick/swift,benlangmuir/swift,apple/swift,roambotics/swift,glessard/swift,benlangmuir/swift,gregomni/swift,atrick/swift,ahoppen/swift,JGiola/swift,benlangmuir/swift,rudkx/swift,glessard/swift,atrick/swift,glessard/swift,benlangmuir/swift,JGiola/swift,atrick/swift,roambotics/swift,ahoppen/swift,roambotics/swift,JGiola/swift,roambotics/swift,JGiola/swift,apple/swift,ahoppen/swift,rudkx/swift,rudkx/swift,rudkx/swift,gregomni/swift,ahoppen/swift,glessard/swift,apple/swift,gregomni/swift,rudkx/swift,rudkx/swift,benlangmuir/swift,JGiola/swift,apple/swift
--- +++ @@ -1,18 +1,18 @@ -SYNTAX_BUILDABLE_EXPRESSIBLE_AS_CONFORMANCES = { - 'ExpressibleAsConditionElement': [ - 'ExpressibleAsConditionElementList' +SYNTAX_BUILDABLE_EXPRESSIBLE_BY_CONFORMANCES = { + 'ExpressibleByConditionElement': [ + 'ExpressibleByConditionElementList' ], - 'ExpressibleAsDeclBuildable': [ - 'ExpressibleAsCodeBlockItem', - 'ExpressibleAsMemberDeclListItem', - 'ExpressibleAsSyntaxBuildable' + 'ExpressibleByDeclBuildable': [ + 'ExpressibleByCodeBlockItem', + 'ExpressibleByMemberDeclListItem', + 'ExpressibleBySyntaxBuildable' ], - 'ExpressibleAsStmtBuildable': [ - 'ExpressibleAsCodeBlockItem', - 'ExpressibleAsSyntaxBuildable' + 'ExpressibleByStmtBuildable': [ + 'ExpressibleByCodeBlockItem', + 'ExpressibleBySyntaxBuildable' ], - 'ExpressibleAsExprList': [ - 'ExpressibleAsConditionElement', - 'ExpressibleAsSyntaxBuildable' + 'ExpressibleByExprList': [ + 'ExpressibleByConditionElement', + 'ExpressibleBySyntaxBuildable' ] }
3642fefbb1d4b5f2aeead54135ac37f0a5b635cd
tests/general.py
tests/general.py
import unittest from app import create_app, configure_settings, db class AppTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_ctx = self.app.app_context() self.app_ctx.push() db.create_all() configure_settings(self.app) def tearDown(self): db.session.remove() db.drop_all() self.app_ctx.pop() class DummyPostData(dict): def getlist(self, key): v = self[key] if not isinstance(v, (list, tuple)): v = [v] return v
import unittest from app import create_app, db class AppTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_ctx = self.app.app_context() self.app_ctx.push() db.create_all() # Temporary. Will be removed once default settings has been set up. self.app.config['posts_per_page'] = '10' self.app.config['blog_name'] = 'flask-blogger' def tearDown(self): db.session.remove() db.drop_all() self.app_ctx.pop() class DummyPostData(dict): def getlist(self, key): v = self[key] if not isinstance(v, (list, tuple)): v = [v] return v
Add placeholder settings to unit tests
Add placeholder settings to unit tests
Python
mit
Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger
--- +++ @@ -1,6 +1,6 @@ import unittest -from app import create_app, configure_settings, db +from app import create_app, db class AppTestCase(unittest.TestCase): @@ -9,7 +9,10 @@ self.app_ctx = self.app.app_context() self.app_ctx.push() db.create_all() - configure_settings(self.app) + + # Temporary. Will be removed once default settings has been set up. + self.app.config['posts_per_page'] = '10' + self.app.config['blog_name'] = 'flask-blogger' def tearDown(self): db.session.remove()
4377cb01932fb6cb9d324f98c55b4467e803add5
tests/test_go.py
tests/test_go.py
# -*- coding: utf-8 -*- import mock import completor from completor.compat import to_unicode from completers.go import Go # noqa def test_format_cmd(vim_mod): vim_mod.funcs['line2byte'] = mock.Mock(return_value=20) vim_mod.funcs['completor#utils#tempname'] = mock.Mock( return_value=b'/tmp/vJBio2A/2.vim') vim_mod.current.window.cursor = (1, 5) go = completor.get('go') go.input_data = to_unicode('self.', 'utf-8') assert go.format_cmd() == [ 'gocode', '-f=csv', '--in=/tmp/vJBio2A/2.vim', 'autocomplete', 24] def test_parse(): data = [ b'func,,Errorf,,func(format string, a ...interface{}) error', b'func,,Fprint,,func(w io.Writer, a ...interface{}) (n int, err error)', # noqa ] go = completor.get('go') assert go.parse(data) == [{ 'word': b'Errorf', 'menu': b'func(format string, a ...interface{}) error' }, { 'word': b'Fprint', 'menu': b'func(w io.Writer, a ...interface{}) (n int, err error)' }]
# -*- coding: utf-8 -*- import mock import completor from completor.compat import to_unicode from completers.go import Go # noqa def test_format_cmd(vim_mod): vim_mod.funcs['line2byte'] = mock.Mock(return_value=20) vim_mod.funcs['completor#utils#tempname'] = mock.Mock( return_value=b'/tmp/vJBio2A/2.vim') vim_mod.current.buffer.name = '/home/vagrant/bench.vim' vim_mod.current.window.cursor = (1, 5) go = completor.get('go') go.input_data = to_unicode('self.', 'utf-8') assert go.format_cmd() == [ 'gocode', '-f=csv', '--in=/tmp/vJBio2A/2.vim', 'autocomplete', '/home/vagrant/bench.vim', 24] def test_parse(): data = [ b'func,,Errorf,,func(format string, a ...interface{}) error', b'func,,Fprint,,func(w io.Writer, a ...interface{}) (n int, err error)', # noqa ] go = completor.get('go') assert go.parse(data) == [{ 'word': b'Errorf', 'menu': b'func(format string, a ...interface{}) error' }, { 'word': b'Fprint', 'menu': b'func(w io.Writer, a ...interface{}) (n int, err error)' }]
Fix test for go completor.
Fix test for go completor.
Python
mit
maralla/completor.vim,maralla/completor.vim
--- +++ @@ -10,12 +10,14 @@ vim_mod.funcs['line2byte'] = mock.Mock(return_value=20) vim_mod.funcs['completor#utils#tempname'] = mock.Mock( return_value=b'/tmp/vJBio2A/2.vim') + vim_mod.current.buffer.name = '/home/vagrant/bench.vim' vim_mod.current.window.cursor = (1, 5) go = completor.get('go') go.input_data = to_unicode('self.', 'utf-8') assert go.format_cmd() == [ - 'gocode', '-f=csv', '--in=/tmp/vJBio2A/2.vim', 'autocomplete', 24] + 'gocode', '-f=csv', '--in=/tmp/vJBio2A/2.vim', 'autocomplete', + '/home/vagrant/bench.vim', 24] def test_parse():
c5fe052756f9fe2bfe091d24fabcb6be02bda763
server/core/management/commands/poll_urls.py
server/core/management/commands/poll_urls.py
import datetime import multiprocessing from django.conf import settings from django.core.management.base import BaseCommand, CommandError from core.models import WebPage, PageScrapeResult from core.views import scrape_url class Command(BaseCommand): help = "Poll all the urls and scrape the results" can_import_settings = True def handle(self, *args, **options): pool = multiprocessing.Pool(10) curr_min = datetime.datetime.now().minute for page in WebPage.objects.all(): if curr_min % page.interval == 0 or settings.DEBUG: pool.apply_async(scrape_url, (page, )) pool.close() pool.join()
import datetime import multiprocessing from django.conf import settings from django.core.management.base import BaseCommand, CommandError from core.models import WebPage, PageScrapeResult from core.views import scrape_url class Command(BaseCommand): help = "Poll all the urls and scrape the results" can_import_settings = True def handle(self, *args, **options): pool = multiprocessing.Pool(multiprocessing.cpu_count() + 2) curr_min = datetime.datetime.now().minute for page in WebPage.objects.all(): if curr_min % page.interval == 0 or settings.DEBUG: pool.apply_async(scrape_url, (page, )) pool.close() pool.join()
Use the cpu count for the process pool size.
Use the cpu count for the process pool size.
Python
mit
theju/atifier,theju/atifier
--- +++ @@ -13,7 +13,7 @@ can_import_settings = True def handle(self, *args, **options): - pool = multiprocessing.Pool(10) + pool = multiprocessing.Pool(multiprocessing.cpu_count() + 2) curr_min = datetime.datetime.now().minute for page in WebPage.objects.all(): if curr_min % page.interval == 0 or settings.DEBUG:
bd170dc4ce58c78213ea5dc7c9d779ad914762bb
social_core/tests/backends/test_udata.py
social_core/tests/backends/test_udata.py
import json from six.moves.urllib_parse import urlencode from .oauth import OAuth2Test class DatagouvfrOAuth2Test(OAuth2Test): backend_path = 'social_core.backends.udata.DatagouvfrOAuth2' user_data_url = 'https://www.data.gouv.fr/api/1/me/' expected_username = 'foobar' access_token_body = json.dumps({ 'access_token': 'foobar', 'token_type': 'bearer' }) request_token_body = urlencode({ 'oauth_token_secret': 'foobar-secret', 'oauth_token': 'foobar', 'oauth_callback_confirmed': 'true' }) user_data_body = json.dumps({}) def test_login(self): self.do_login() def test_partial_pipeline(self): self.do_partial_pipeline()
import json from six.moves.urllib_parse import urlencode from .oauth import OAuth2Test class DatagouvfrOAuth2Test(OAuth2Test): backend_path = 'social_core.backends.udata.DatagouvfrOAuth2' user_data_url = 'https://www.data.gouv.fr/api/1/me/' expected_username = 'foobar' access_token_body = json.dumps({ 'access_token': 'foobar', 'token_type': 'bearer', 'first_name': 'foobar', 'email': 'foobar@example.com' }) request_token_body = urlencode({ 'oauth_token_secret': 'foobar-secret', 'oauth_token': 'foobar', 'oauth_callback_confirmed': 'true' }) user_data_body = json.dumps({}) def test_login(self): self.do_login() def test_partial_pipeline(self): self.do_partial_pipeline()
Fix tests for udata/datagouvfr backend
Fix tests for udata/datagouvfr backend
Python
bsd-3-clause
python-social-auth/social-core,python-social-auth/social-core
--- +++ @@ -11,7 +11,9 @@ expected_username = 'foobar' access_token_body = json.dumps({ 'access_token': 'foobar', - 'token_type': 'bearer' + 'token_type': 'bearer', + 'first_name': 'foobar', + 'email': 'foobar@example.com' }) request_token_body = urlencode({ 'oauth_token_secret': 'foobar-secret',
83020d996733b5376cfa5814ca81c8f823029346
tests/run/pyclass_annotations_pep526.py
tests/run/pyclass_annotations_pep526.py
# cython: language_level=3 # mode: run # tag: pure3.7, pep526, pep484 from __future__ import annotations try: from typing import ClassVar except ImportError: # Py<=3.5 ClassVar = {int: int} class PyAnnotatedClass: """ >>> PyAnnotatedClass.__annotations__["CLASS_VAR"] 'ClassVar[int]' >>> PyAnnotatedClass.__annotations__["obj"] 'str' >>> PyAnnotatedClass.__annotations__["literal"] "'int'" >>> PyAnnotatedClass.__annotations__["recurse"] "'PyAnnotatedClass'" >>> PyAnnotatedClass.__annotations__["default"] 'bool' >>> PyAnnotatedClass.CLASS_VAR 1 >>> PyAnnotatedClass.default False >>> PyAnnotatedClass.obj Traceback (most recent call last): ... AttributeError: type object 'PyAnnotatedClass' has no attribute 'obj' """ CLASS_VAR: ClassVar[int] = 1 obj: str literal: "int" recurse: "PyAnnotatedClass" default: bool = False class PyVanillaClass: """ >>> PyVanillaClass.__annotations__ Traceback (most recent call last): ... AttributeError: type object 'PyVanillaClass' has no attribute '__annotations__' """
# cython: language_level=3 # mode: run # tag: pure3.7, pep526, pep484 from __future__ import annotations import sys try: from typing import ClassVar except ImportError: # Py<=3.5 ClassVar = {int: int} class PyAnnotatedClass: """ >>> PyAnnotatedClass.__annotations__["CLASS_VAR"] 'ClassVar[int]' >>> PyAnnotatedClass.__annotations__["obj"] 'str' >>> PyAnnotatedClass.__annotations__["literal"] "'int'" >>> PyAnnotatedClass.__annotations__["recurse"] "'PyAnnotatedClass'" >>> PyAnnotatedClass.__annotations__["default"] 'bool' >>> PyAnnotatedClass.CLASS_VAR 1 >>> PyAnnotatedClass.default False >>> PyAnnotatedClass.obj Traceback (most recent call last): ... AttributeError: type object 'PyAnnotatedClass' has no attribute 'obj' """ CLASS_VAR: ClassVar[int] = 1 obj: str literal: "int" recurse: "PyAnnotatedClass" default: bool = False class PyVanillaClass: """ Before Py3.10, unannotated classes did not have '__annotations__'. >>> try: ... a = PyVanillaClass.__annotations__ ... except AttributeError: ... assert sys.version_info < (3, 10) ... else: ... assert sys.version_info >= (3, 10) ... assert a == {} """
Repair a Python compatibility test in Py3.10.
Repair a Python compatibility test in Py3.10.
Python
apache-2.0
scoder/cython,scoder/cython,scoder/cython,da-woods/cython,cython/cython,cython/cython,da-woods/cython,cython/cython,da-woods/cython,da-woods/cython,scoder/cython,cython/cython
--- +++ @@ -3,6 +3,8 @@ # tag: pure3.7, pep526, pep484 from __future__ import annotations + +import sys try: from typing import ClassVar @@ -40,8 +42,13 @@ class PyVanillaClass: """ - >>> PyVanillaClass.__annotations__ - Traceback (most recent call last): - ... - AttributeError: type object 'PyVanillaClass' has no attribute '__annotations__' + Before Py3.10, unannotated classes did not have '__annotations__'. + + >>> try: + ... a = PyVanillaClass.__annotations__ + ... except AttributeError: + ... assert sys.version_info < (3, 10) + ... else: + ... assert sys.version_info >= (3, 10) + ... assert a == {} """
1517bb31a8ec0d5df96e2693977081b3d1a64f69
tests/integration/minion/test_timeout.py
tests/integration/minion/test_timeout.py
# -*- coding: utf-8 -*- ''' Tests for various minion timeouts ''' # Import Python libs from __future__ import absolute_import import os import sys import salt.utils # Import Salt Testing libs from tests.support.case import ShellCase class MinionTimeoutTestCase(ShellCase): ''' Test minion timing functions ''' def test_long_running_job(self): ''' Test that we will wait longer than the job timeout for a minion to return. ''' # Launch the command sleep_length = 30 if salt.utils.is_windows(): popen_kwargs = {'env': dict(os.environ, PYTHONPATH=';'.join(sys.path))} else: popen_kwargs = None ret = self.run_salt( 'minion test.sleep {0}'.format(sleep_length), timeout=45, catch_stderr=True, popen_kwargs=popen_kwargs, ) self.assertTrue(isinstance(ret[0], list), 'Return is not a list. Minion' ' may have returned error: {0}'.format(ret)) self.assertEqual(len(ret[0]), 2, 'Standard out wrong length {}'.format(ret)) self.assertTrue('True' in ret[0][1], 'Minion did not return True after ' '{0} seconds. ret={1}'.format(sleep_length, ret))
# -*- coding: utf-8 -*- ''' Tests for various minion timeouts ''' # Import Python libs from __future__ import absolute_import import os import sys import salt.utils.platform # Import Salt Testing libs from tests.support.case import ShellCase class MinionTimeoutTestCase(ShellCase): ''' Test minion timing functions ''' def test_long_running_job(self): ''' Test that we will wait longer than the job timeout for a minion to return. ''' # Launch the command sleep_length = 30 if salt.utils.platform.is_windows(): popen_kwargs = {'env': dict(os.environ, PYTHONPATH=';'.join(sys.path))} else: popen_kwargs = None ret = self.run_salt( 'minion test.sleep {0}'.format(sleep_length), timeout=45, catch_stderr=True, popen_kwargs=popen_kwargs, ) self.assertTrue(isinstance(ret[0], list), 'Return is not a list. Minion' ' may have returned error: {0}'.format(ret)) self.assertEqual(len(ret[0]), 2, 'Standard out wrong length {}'.format(ret)) self.assertTrue('True' in ret[0][1], 'Minion did not return True after ' '{0} seconds. ret={1}'.format(sleep_length, ret))
Update old utils paths to use new paths
Update old utils paths to use new paths
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -8,7 +8,7 @@ import os import sys -import salt.utils +import salt.utils.platform # Import Salt Testing libs from tests.support.case import ShellCase @@ -25,7 +25,7 @@ ''' # Launch the command sleep_length = 30 - if salt.utils.is_windows(): + if salt.utils.platform.is_windows(): popen_kwargs = {'env': dict(os.environ, PYTHONPATH=';'.join(sys.path))} else: popen_kwargs = None
29613035bb8af7dedec7383a62a5e488547e4795
transmutagen/tests/test_coefficients.py
transmutagen/tests/test_coefficients.py
import pytest slow = pytest.mark.skipif( not pytest.config.getoption("--runslow"), reason="need --runslow option to run" ) TOTAL_DEGREES = 2 from .crv_coeffs import coeffs as correct_coeffs # TODO: Should we use the CRAM cache here? from ..cram import CRAM_exp, CRAM_coeffs @slow def test_coefficients(): generated_coeffs = {} for degree in range(1, TOTAL_DEGREES+1): expr = CRAM_exp(degree, 30) generated_coeffs[degree] = CRAM_coeffs(expr, 20, decimal_rounding=True) assert generated_coeffs[degree] == correct_coeffs[degree]
import pytest slow = pytest.mark.skipif( not pytest.config.getoption("--runslow"), reason="need --runslow option to run" ) TOTAL_DEGREES = 2 from .crv_coeffs import coeffs as correct_coeffs # TODO: Should we use the CRAM cache here? from ..cram import CRAM_exp, CRAM_coeffs @slow @pytest.mark.parametrize('degree', range(1, TOTAL_DEGREES+1)) def test_coefficients(degree): generated_coeffs = {} expr = CRAM_exp(degree, 30) generated_coeffs[degree] = CRAM_coeffs(expr, 20, decimal_rounding=True) assert generated_coeffs[degree] == correct_coeffs[degree]
Use pytest parametrize for the coefficient tests
Use pytest parametrize for the coefficient tests
Python
bsd-3-clause
ergs/transmutagen,ergs/transmutagen
--- +++ @@ -12,10 +12,10 @@ from ..cram import CRAM_exp, CRAM_coeffs @slow -def test_coefficients(): +@pytest.mark.parametrize('degree', range(1, TOTAL_DEGREES+1)) +def test_coefficients(degree): generated_coeffs = {} - for degree in range(1, TOTAL_DEGREES+1): - expr = CRAM_exp(degree, 30) - generated_coeffs[degree] = CRAM_coeffs(expr, 20, - decimal_rounding=True) - assert generated_coeffs[degree] == correct_coeffs[degree] + expr = CRAM_exp(degree, 30) + generated_coeffs[degree] = CRAM_coeffs(expr, 20, + decimal_rounding=True) + assert generated_coeffs[degree] == correct_coeffs[degree]
4ffd42f132769b23ee93c8a5c3416877c772d47e
doc_builder/backends/pdf.py
doc_builder/backends/pdf.py
import re import os from django.conf import settings from doc_builder.base import BaseBuilder from projects.utils import run latex_re = re.compile('the LaTeX files are in (.*)\.') pdf_re = re.compile('Output written on (.*?)') class Builder(BaseBuilder): def build(self, project): self._cd_makefile(project) latex_results = run('make latex') match = latex_re.search(latex_results[1]) if match: latex_dir = match.group(1).strip() os.chdir(latex_dir) pdf_results = run('make') #Check the return code was good before symlinking pdf_match = pdf_re.search(pdf_results[1]) if pdf_match: from_path = os.path.join(os.getcwd(), "%s.pdf" % project.slug) to_path = os.path.join(settings.MEDIA_ROOT, 'pdf', project.slug, 'latest') if not os.path.exists(to_path): os.makedirs(to_path) to_file = os.path.join(to_path, pdf_match.group(1).strip()) if os.path.exists(to_file): run('ln -sf %s %s' % (from_path, to_file)) else: print "File doesn't exist, not symlinking." else: print "PDF Building failed. Moving on." if project.build_pdf: project.build_pdf = False project.save()
import re import os from django.conf import settings from doc_builder.base import BaseBuilder from projects.utils import run latex_re = re.compile('the LaTeX files are in (.*)\.') pdf_re = re.compile('Output written on (.*?)') class Builder(BaseBuilder): def build(self, project): self._cd_makefile(project) latex_results = run('make latex') match = latex_re.search(latex_results[1]) if match: latex_dir = match.group(1).strip() os.chdir(latex_dir) pdf_results = run('make') #Check the return code was good before symlinking pdf_match = pdf_re.search(pdf_results[1]) if pdf_match: from_path = os.path.join(os.getcwd(), "%s.pdf" % pdf_match.group(1).strip()) to_path = os.path.join(settings.MEDIA_ROOT, 'pdf', project.slug, 'latest') if not os.path.exists(to_path): os.makedirs(to_path) to_file = os.path.join(to_path, '%s.pdf' % project.slug) if os.path.exists(to_file): run('mv -f %s %s' % (from_path, to_file)) else: print "File doesn't exist, not symlinking." else: print "PDF Building failed. Moving on." if project.build_pdf: project.build_pdf = False project.save()
Move instead of symlink because we blow that dir away.
Move instead of symlink because we blow that dir away.
Python
mit
wanghaven/readthedocs.org,LukasBoersma/readthedocs.org,clarkperkins/readthedocs.org,CedarLogic/readthedocs.org,nyergler/pythonslides,d0ugal/readthedocs.org,sunnyzwh/readthedocs.org,soulshake/readthedocs.org,mhils/readthedocs.org,johncosta/private-readthedocs.org,nikolas/readthedocs.org,ojii/readthedocs.org,KamranMackey/readthedocs.org,soulshake/readthedocs.org,Carreau/readthedocs.org,emawind84/readthedocs.org,KamranMackey/readthedocs.org,stevepiercy/readthedocs.org,pombredanne/readthedocs.org,wijerasa/readthedocs.org,kdkeyser/readthedocs.org,laplaceliu/readthedocs.org,tddv/readthedocs.org,KamranMackey/readthedocs.org,asampat3090/readthedocs.org,LukasBoersma/readthedocs.org,raven47git/readthedocs.org,jerel/readthedocs.org,titiushko/readthedocs.org,kenshinthebattosai/readthedocs.org,GovReady/readthedocs.org,sid-kap/readthedocs.org,LukasBoersma/readthedocs.org,davidfischer/readthedocs.org,istresearch/readthedocs.org,tddv/readthedocs.org,KamranMackey/readthedocs.org,cgourlay/readthedocs.org,kenwang76/readthedocs.org,espdev/readthedocs.org,wijerasa/readthedocs.org,jerel/readthedocs.org,kenwang76/readthedocs.org,espdev/readthedocs.org,asampat3090/readthedocs.org,singingwolfboy/readthedocs.org,kenshinthebattosai/readthedocs.org,mhils/readthedocs.org,GovReady/readthedocs.org,hach-que/readthedocs.org,asampat3090/readthedocs.org,Tazer/readthedocs.org,espdev/readthedocs.org,sils1297/readthedocs.org,hach-que/readthedocs.org,royalwang/readthedocs.org,emawind84/readthedocs.org,alex/readthedocs.org,sunnyzwh/readthedocs.org,cgourlay/readthedocs.org,attakei/readthedocs-oauth,rtfd/readthedocs.org,espdev/readthedocs.org,attakei/readthedocs-oauth,stevepiercy/readthedocs.org,emawind84/readthedocs.org,atsuyim/readthedocs.org,titiushko/readthedocs.org,soulshake/readthedocs.org,kenshinthebattosai/readthedocs.org,CedarLogic/readthedocs.org,takluyver/readthedocs.org,Carreau/readthedocs.org,d0ugal/readthedocs.org,singingwolfboy/readthedocs.org,dirn/readthedocs.org,Carreau/readthedocs.org,fujita-shintaro/readthedocs.org,atsuyim/readthedocs.org,techtonik/readthedocs.org,emawind84/readthedocs.org,GovReady/readthedocs.org,davidfischer/readthedocs.org,wijerasa/readthedocs.org,titiushko/readthedocs.org,wijerasa/readthedocs.org,safwanrahman/readthedocs.org,gjtorikian/readthedocs.org,techtonik/readthedocs.org,espdev/readthedocs.org,singingwolfboy/readthedocs.org,dirn/readthedocs.org,agjohnson/readthedocs.org,johncosta/private-readthedocs.org,titiushko/readthedocs.org,ojii/readthedocs.org,fujita-shintaro/readthedocs.org,clarkperkins/readthedocs.org,atsuyim/readthedocs.org,Tazer/readthedocs.org,laplaceliu/readthedocs.org,mrshoki/readthedocs.org,agjohnson/readthedocs.org,ojii/readthedocs.org,alex/readthedocs.org,fujita-shintaro/readthedocs.org,attakei/readthedocs-oauth,laplaceliu/readthedocs.org,istresearch/readthedocs.org,SteveViss/readthedocs.org,agjohnson/readthedocs.org,techtonik/readthedocs.org,royalwang/readthedocs.org,wanghaven/readthedocs.org,SteveViss/readthedocs.org,royalwang/readthedocs.org,VishvajitP/readthedocs.org,mrshoki/readthedocs.org,sid-kap/readthedocs.org,safwanrahman/readthedocs.org,techtonik/readthedocs.org,davidfischer/readthedocs.org,GovReady/readthedocs.org,clarkperkins/readthedocs.org,mrshoki/readthedocs.org,dirn/readthedocs.org,sils1297/readthedocs.org,SteveViss/readthedocs.org,d0ugal/readthedocs.org,jerel/readthedocs.org,raven47git/readthedocs.org,singingwolfboy/readthedocs.org,atsuyim/readthedocs.org,takluyver/readthedocs.org,attakei/readthedocs-oauth,LukasBoersma/readthedocs.org,mrshoki/readthedocs.org,sils1297/readthedocs.org,gjtorikian/readthedocs.org,kdkeyser/readthedocs.org,VishvajitP/readthedocs.org,nikolas/readthedocs.org,raven47git/readthedocs.org,wanghaven/readthedocs.org,VishvajitP/readthedocs.org,mhils/readthedocs.org,CedarLogic/readthedocs.org,stevepiercy/readthedocs.org,pombredanne/readthedocs.org,tddv/readthedocs.org,cgourlay/readthedocs.org,rtfd/readthedocs.org,gjtorikian/readthedocs.org,safwanrahman/readthedocs.org,d0ugal/readthedocs.org,gjtorikian/readthedocs.org,CedarLogic/readthedocs.org,kenwang76/readthedocs.org,johncosta/private-readthedocs.org,laplaceliu/readthedocs.org,Tazer/readthedocs.org,hach-que/readthedocs.org,safwanrahman/readthedocs.org,alex/readthedocs.org,sid-kap/readthedocs.org,clarkperkins/readthedocs.org,kenshinthebattosai/readthedocs.org,davidfischer/readthedocs.org,hach-que/readthedocs.org,nyergler/pythonslides,nikolas/readthedocs.org,takluyver/readthedocs.org,VishvajitP/readthedocs.org,sunnyzwh/readthedocs.org,Tazer/readthedocs.org,fujita-shintaro/readthedocs.org,sunnyzwh/readthedocs.org,michaelmcandrew/readthedocs.org,ojii/readthedocs.org,istresearch/readthedocs.org,cgourlay/readthedocs.org,sils1297/readthedocs.org,michaelmcandrew/readthedocs.org,asampat3090/readthedocs.org,wanghaven/readthedocs.org,pombredanne/readthedocs.org,nikolas/readthedocs.org,raven47git/readthedocs.org,michaelmcandrew/readthedocs.org,agjohnson/readthedocs.org,nyergler/pythonslides,dirn/readthedocs.org,kdkeyser/readthedocs.org,istresearch/readthedocs.org,nyergler/pythonslides,mhils/readthedocs.org,sid-kap/readthedocs.org,takluyver/readthedocs.org,kdkeyser/readthedocs.org,jerel/readthedocs.org,royalwang/readthedocs.org,alex/readthedocs.org,rtfd/readthedocs.org,kenwang76/readthedocs.org,rtfd/readthedocs.org,Carreau/readthedocs.org,michaelmcandrew/readthedocs.org,SteveViss/readthedocs.org,soulshake/readthedocs.org,stevepiercy/readthedocs.org
--- +++ @@ -23,16 +23,16 @@ pdf_match = pdf_re.search(pdf_results[1]) if pdf_match: from_path = os.path.join(os.getcwd(), - "%s.pdf" % project.slug) + "%s.pdf" % pdf_match.group(1).strip()) to_path = os.path.join(settings.MEDIA_ROOT, 'pdf', project.slug, 'latest') if not os.path.exists(to_path): os.makedirs(to_path) - to_file = os.path.join(to_path, pdf_match.group(1).strip()) + to_file = os.path.join(to_path, '%s.pdf' % project.slug) if os.path.exists(to_file): - run('ln -sf %s %s' % (from_path, to_file)) + run('mv -f %s %s' % (from_path, to_file)) else: print "File doesn't exist, not symlinking." else:
9937823496db32a4d3eac3eee0fa4d310ea07e11
dvhb_hybrid/files/models.py
dvhb_hybrid/files/models.py
import uuid from django.conf import settings from django.contrib.postgres.fields import JSONField from django.db import models from django.utils.translation import ugettext_lazy as _ from ..models import UpdatedMixin from .storages import image_storage class Image(UpdatedMixin, models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='images', verbose_name=_('Author'), on_delete=models.PROTECT) uuid = models.UUIDField(_('UUID'), primary_key=True) image = models.ImageField(storage=image_storage) mime_type = models.CharField(_('content type'), max_length=99, blank=True) meta = JSONField(_('meta-information'), default={}, blank=True) class Meta: verbose_name = _('image') verbose_name_plural = _('images') ordering = ('-created_at',) def __str__(self): return self.image.name def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.uuid: uid = uuid.uuid4() self.uuid = uid self.image.name = image_storage.get_available_name( self.image.name, uuid=uid) super(Image, self).save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
import uuid from django.conf import settings from django.contrib.postgres.fields import JSONField from django.contrib.postgres.indexes import GinIndex from django.db import models from django.utils.translation import ugettext_lazy as _ from ..models import UpdatedMixin from .storages import image_storage class Image(UpdatedMixin, models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='images', verbose_name=_('Author'), on_delete=models.PROTECT) uuid = models.UUIDField(_('UUID'), primary_key=True) image = models.ImageField(storage=image_storage) mime_type = models.CharField(_('content type'), max_length=99, blank=True) meta = JSONField(_('meta-information'), default={}, blank=True) class Meta: verbose_name = _('image') verbose_name_plural = _('images') ordering = ('-created_at',) indexes = [GinIndex(fields=['meta'])] def __str__(self): return self.image.name def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.uuid: uid = uuid.uuid4() self.uuid = uid self.image.name = image_storage.get_available_name( self.image.name, uuid=uid) super(Image, self).save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
Add index for image metainformation
Add index for image metainformation
Python
mit
dvhbru/dvhb-hybrid
--- +++ @@ -2,6 +2,7 @@ from django.conf import settings from django.contrib.postgres.fields import JSONField +from django.contrib.postgres.indexes import GinIndex from django.db import models from django.utils.translation import ugettext_lazy as _ @@ -22,6 +23,7 @@ verbose_name = _('image') verbose_name_plural = _('images') ordering = ('-created_at',) + indexes = [GinIndex(fields=['meta'])] def __str__(self): return self.image.name
2d9e7843106b2fce247dda8f14bc192c3d98e91f
tests/test_simpleflow.py
tests/test_simpleflow.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from simpleflow import simpleflow def test_basic(): assert 0, 'write me!'
#!/usr/bin/env python # -*- coding: utf-8 -*- def test_basic(): import simpleflow assert True
Add basic test that only import simpleflow
Add basic test that only import simpleflow
Python
mit
botify-labs/simpleflow,botify-labs/simpleflow
--- +++ @@ -1,7 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -from simpleflow import simpleflow def test_basic(): - assert 0, 'write me!' + import simpleflow + assert True
4877f6a242b0c0ecad798ec648d919fc05065c8e
sketchbook/_version.py
sketchbook/_version.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2017 Kaede Hoshikawa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ["__version__"] _tag_version = (0, 1, 1) _dev = 0 _version_fragments = [str(i) for i in _tag_version[:3]] if _dev is not None: _version_fragments.append(f"dev{_dev}") __version__ = ".".join(_version_fragments)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2017 Kaede Hoshikawa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ["__version__"] _tag_version = (0, 1, 2) _dev = 0 _version_fragments = [str(i) for i in _tag_version[:3]] if _dev is not None: _version_fragments.append(f"dev{_dev}") __version__ = ".".join(_version_fragments)
Move master version to 0.1.2.
Move master version to 0.1.2.
Python
apache-2.0
futursolo/sketchbook,futursolo/sketchbook
--- +++ @@ -17,7 +17,7 @@ __all__ = ["__version__"] -_tag_version = (0, 1, 1) +_tag_version = (0, 1, 2) _dev = 0
6093d2954861f2783da3e5b8473cb13b0469685b
elasticquery/filterquery.py
elasticquery/filterquery.py
# ElasticQuery # File: elasticquery/filterquery.py # Desc: The base query class & metaclass import json from .util import make_dsl_object, unroll_definitions, unroll_struct class MetaFilterQuery(type): def __init__(cls, name, bases, d): super(MetaFilterQuery, cls).__init__(name, bases, d) unroll_definitions(cls._definitions) def __getattr__(cls, key): if key not in cls._definitions: raise cls._exception(key) return lambda *args, **kwargs: make_dsl_object( cls, key, cls._definitions[key], *args, **kwargs ) class BaseFilterQuery(object): _type = None _struct = None _dsl_type = None def __init__(self, dsl_type, struct): self._struct = struct self._dsl_type = dsl_type def dict(self): return { self._dsl_type: unroll_struct(self._struct) } def __str__(self): return json.dumps(self.dict(), indent=4)
# ElasticQuery # File: elasticquery/filterquery.py # Desc: The base query class & metaclass import json from .util import make_dsl_object, unroll_definitions, unroll_struct class MetaFilterQuery(type): def __init__(cls, name, bases, d): super(MetaFilterQuery, cls).__init__(name, bases, d) unroll_definitions(cls._definitions) def __getattr__(cls, key): if key == '__test__': return None if key not in cls._definitions: raise cls._exception(key) return lambda *args, **kwargs: make_dsl_object( cls, key, cls._definitions[key], *args, **kwargs ) class BaseFilterQuery(object): _type = None _struct = None _dsl_type = None def __init__(self, dsl_type, struct): self._struct = struct self._dsl_type = dsl_type def dict(self): dsl_type = self._dsl_type[:1] if self._dsl_type.endswith('_') else self._dsl_type return { dsl_type: unroll_struct(self._struct) } def __str__(self): return json.dumps(self.dict(), indent=4)
Support nosetests, handle magic names (and_, or_, etc)
Support nosetests, handle magic names (and_, or_, etc)
Python
mit
Fizzadar/ElasticQuery,Fizzadar/ElasticQuery
--- +++ @@ -13,6 +13,9 @@ unroll_definitions(cls._definitions) def __getattr__(cls, key): + if key == '__test__': + return None + if key not in cls._definitions: raise cls._exception(key) @@ -32,8 +35,10 @@ self._dsl_type = dsl_type def dict(self): + dsl_type = self._dsl_type[:1] if self._dsl_type.endswith('_') else self._dsl_type + return { - self._dsl_type: unroll_struct(self._struct) + dsl_type: unroll_struct(self._struct) } def __str__(self):
51f0cd392cab5737cb444b9eef8700fcd4713ea0
tests/recipes_test.py
tests/recipes_test.py
#!/usr/bin/env python # Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs simulation tests and lint on the recipes.""" import os import subprocess ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def recipes_py(*args): subprocess.check_call([ os.path.join(ROOT_DIR, 'recipes', 'recipes.py'), '--use-bootstrap'] + list(args)) recipes_py('test', 'run') recipes_py('lint')
#!/usr/bin/env python # Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs simulation tests and lint on the recipes.""" import os import subprocess ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def recipes_py(*args): subprocess.check_call([ os.path.join(ROOT_DIR, 'recipes', 'recipes.py') ] + list(args)) recipes_py('test', 'run') recipes_py('lint')
Remove deprecated (ignored) --use-bootstrap flag
[recipes] Remove deprecated (ignored) --use-bootstrap flag This has been ignored for a long time, and I'd like to get rid of it. R=jchinlee@chromium.org, ef4933a197ef7b4b3f55f1bec4942aead3637a2a@chromium.org Change-Id: I240d59cc10a2882041ac2c8abfeb1894237516a6 Reviewed-on: https://chromium-review.googlesource.com/c/1407425 Reviewed-by: Nodir Turakulov <ef4933a197ef7b4b3f55f1bec4942aead3637a2a@chromium.org> Commit-Queue: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org>
Python
bsd-3-clause
CoherentLabs/depot_tools,CoherentLabs/depot_tools
--- +++ @@ -13,8 +13,8 @@ def recipes_py(*args): subprocess.check_call([ - os.path.join(ROOT_DIR, 'recipes', 'recipes.py'), - '--use-bootstrap'] + list(args)) + os.path.join(ROOT_DIR, 'recipes', 'recipes.py') + ] + list(args)) recipes_py('test', 'run')
df68b821807d25d204f43d7b1805da6c25f42b43
src/lib/pagination.py
src/lib/pagination.py
from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ page_size = 25 page_size_query_param = "max_results" def get_paginated_response(self, data): links = OrderedDict() if self.page.has_next(): links['next'] = OrderedDict([ ('href', self.get_next_link()), ('title', _('page suivante')), ]) if self.page.has_previous(): links['prev'] = OrderedDict([ ('href', self.get_previous_link()), ('title', _('page précédente')), ]) meta = OrderedDict([ ('max_results', self.page.paginator.per_page), ('total', self.page.paginator.count), ('page', self.page.number), ]) return Response(OrderedDict([ ('_items', data), ('_links', links), ('_meta', meta), ]))
from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ page_size = 25 page_size_query_param = "max_results" max_page_size = 100 def get_paginated_response(self, data): links = OrderedDict() if self.page.has_next(): links['next'] = OrderedDict([ ('href', self.get_next_link()), ('title', _('page suivante')), ]) if self.page.has_previous(): links['prev'] = OrderedDict([ ('href', self.get_previous_link()), ('title', _('page précédente')), ]) meta = OrderedDict([ ('max_results', self.page.paginator.per_page), ('total', self.page.paginator.count), ('page', self.page.number), ]) return Response(OrderedDict([ ('_items', data), ('_links', links), ('_meta', meta), ]))
Set a maximum to the number of elements that may be requested
Set a maximum to the number of elements that may be requested
Python
agpl-3.0
lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django
--- +++ @@ -10,6 +10,7 @@ """ page_size = 25 page_size_query_param = "max_results" + max_page_size = 100 def get_paginated_response(self, data): links = OrderedDict()
f659e612f87ccb2a9d466ae62ed8f2b2700497ab
cms/tests/test_externals.py
cms/tests/test_externals.py
from django.test import TestCase from ..externals import External try: from contextlib import GeneratorContextManager except ImportError: from contextlib import _GeneratorContextManager as GeneratorContextManager from types import FunctionType class TestExternals(TestCase): def test_load(self): external = External('foo') with self.assertRaises(ImportError): external._load('') def test_load_class(self): external = External('foo') self.assertIsInstance(external.load_class(''), object) self.assertTrue(external.load_class('', fallback=True)) def test_load_method(self): external = External('foo') self.assertIsNone(external.load_method('')()) self.assertTrue(external.load_method('', fallback=True)) def test_context_manager(self): external = External('foo') self.assertIs(type(external.context_manager('')), FunctionType) self.assertIsInstance(external.context_manager('')(), GeneratorContextManager) self.assertTrue(external.context_manager('', fallback=True)) with external.context_manager('')(): self.assertTrue(True)
from django.test import TestCase from django.utils import six from ..externals import External from types import FunctionType import unittest class TestExternals(TestCase): def test_load(self): external = External('foo') with self.assertRaises(ImportError): external._load('') def test_load_class(self): external = External('foo') self.assertIsInstance(external.load_class(''), object) self.assertTrue(external.load_class('', fallback=True)) def test_load_method(self): external = External('foo') self.assertIsNone(external.load_method('')()) self.assertTrue(external.load_method('', fallback=True)) @unittest.skipIf(six.PY3, "Covered by Python 2.") def test_context_manager(self): from contextlib import GeneratorContextManager external = External('foo') self.assertIs(type(external.context_manager('')), FunctionType) self.assertIsInstance(external.context_manager('')(), GeneratorContextManager) self.assertTrue(external.context_manager('', fallback=True)) with external.context_manager('')(): self.assertTrue(True)
Disable an externals tests on Py3.
Disable an externals tests on Py3.
Python
bsd-3-clause
dan-gamble/cms,jamesfoley/cms,danielsamuels/cms,lewiscollard/cms,dan-gamble/cms,lewiscollard/cms,dan-gamble/cms,lewiscollard/cms,jamesfoley/cms,jamesfoley/cms,danielsamuels/cms,danielsamuels/cms,jamesfoley/cms
--- +++ @@ -1,13 +1,10 @@ from django.test import TestCase +from django.utils import six from ..externals import External -try: - from contextlib import GeneratorContextManager -except ImportError: - from contextlib import _GeneratorContextManager as GeneratorContextManager - from types import FunctionType +import unittest class TestExternals(TestCase): @@ -29,7 +26,10 @@ self.assertIsNone(external.load_method('')()) self.assertTrue(external.load_method('', fallback=True)) + @unittest.skipIf(six.PY3, "Covered by Python 2.") def test_context_manager(self): + from contextlib import GeneratorContextManager + external = External('foo') self.assertIs(type(external.context_manager('')), FunctionType) self.assertIsInstance(external.context_manager('')(), GeneratorContextManager)
658f0f6825b4f4a226349fcee63a0c5fbbd5ba9e
webapp/cached.py
webapp/cached.py
from datetime import datetime, timedelta import os class cached(object): def __init__(self, *args, **kwargs): self.cached_function_responses = {} self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE']))) def __call__(self, func): def inner(*args, **kwargs): param = args[0] if len(args) > 1: param = args[1] max_age = kwargs.get('max_age', self.default_max_age) if func not in self.cached_function_responses: self.cached_function_responses[func] = {} if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age): if 'max_age' in kwargs: del kwargs['max_age'] res = func(*args, **kwargs) self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()} return self.cached_function_responses[func][param]['data'] return inner
from datetime import datetime, timedelta import os class cached(object): def __init__(self, *args, **kwargs): self.cached_function_responses = {} self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE']))) def __call__(self, func): def inner(*args, **kwargs): param = args[1] if len(args) > 1 else args[0] max_age = kwargs.get('max_age', self.default_max_age) if func not in self.cached_function_responses: self.cached_function_responses[func] = {} if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age): if 'max_age' in kwargs: del kwargs['max_age'] res = func(*args, **kwargs) self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()} return self.cached_function_responses[func][param]['data'] return inner
Use ternary operator for arg selection.
Use ternary operator for arg selection.
Python
mit
cheddartv/stockstream.live,cheddartv/stockstream.live
--- +++ @@ -9,9 +9,7 @@ def __call__(self, func): def inner(*args, **kwargs): - param = args[0] - if len(args) > 1: - param = args[1] + param = args[1] if len(args) > 1 else args[0] max_age = kwargs.get('max_age', self.default_max_age) if func not in self.cached_function_responses: self.cached_function_responses[func] = {}
b50af9b9790dedea7902d827a86d017ce9177070
digest/management/commands/export_items.py
digest/management/commands/export_items.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.management.base import BaseCommand from django.db.models import Q from digest.management.commands.create_dataset import create_dataset from digest.models import Item class Command(BaseCommand): help = 'Create dataset' def handle(self, *args, **options): """ Основной метод - точка входа """ query = Q() urls = [ 'allmychanges.com', 'stackoverflow.com', ] for entry in urls: query = query | Q(link__contains=entry) create_dataset(Item.objects.exclude(query).order_by('?'), 'items.json')
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.db.models import Q from digest.management.commands.create_dataset import create_dataset from digest.models import Item class Command(BaseCommand): help = 'Create dataset' def handle(self, *args, **options): """ Основной метод - точка входа """ query = Q() urls = [ 'allmychanges.com', 'stackoverflow.com', ] for entry in urls: query = query | Q(link__contains=entry) # TODO make raw sql active_news = Item.objects.filter(status='active').exclude(query) links = active_news.all().values_list('link', flat=True).distinct() non_active_news = Item.objects.exclude(link__in=links).exclude(query) items_ids = list(active_news.values_list('id', flat=True)) items_ids.extend(non_active_news.values_list('id', flat=True)) items_ids = list(set(items_ids)) items = Item.objects.filter(id__in=items_ids) create_dataset(items, 'items.json')
Update export items command for dataset
Update export items command for dataset
Python
mit
pythondigest/pythondigest,pythondigest/pythondigest,pythondigest/pythondigest
--- +++ @@ -1,6 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - from django.core.management.base import BaseCommand from django.db.models import Q @@ -25,4 +23,15 @@ for entry in urls: query = query | Q(link__contains=entry) - create_dataset(Item.objects.exclude(query).order_by('?'), 'items.json') + # TODO make raw sql + active_news = Item.objects.filter(status='active').exclude(query) + links = active_news.all().values_list('link', flat=True).distinct() + non_active_news = Item.objects.exclude(link__in=links).exclude(query) + + items_ids = list(active_news.values_list('id', flat=True)) + items_ids.extend(non_active_news.values_list('id', flat=True)) + items_ids = list(set(items_ids)) + + items = Item.objects.filter(id__in=items_ids) + + create_dataset(items, 'items.json')
da252b07e661eed25d2ed23104a4b453f6785a29
ynr/apps/search/utils.py
ynr/apps/search/utils.py
import re from django.contrib.postgres.search import SearchQuery, SearchRank from django.db.models import Count, F from people.models import Person def search_person_by_name(name, synonym=True): name = name.lower() name = re.sub(r"[^a-z ]", "", name) name = " ".join(name.strip().split()) and_name = " & ".join(name.split(" ")) or_name = " | ".join(name.split(" ")) name = f"({and_name}) | ({or_name})" query = SearchQuery(name, search_type="raw", config="english") search_args = {} if synonym: search_args["name_search_vector__synonym"] = query else: search_args["name_search_vector"] = query qs = ( Person.objects.annotate(membership_count=Count("memberships")) .filter(**search_args) .annotate(rank=SearchRank(F("name_search_vector"), query)) .order_by("-rank", "membership_count") .defer("biography", "versions") ) return qs
import re from django.contrib.postgres.search import SearchQuery, SearchRank from django.db.models import Count, F from people.models import Person def search_person_by_name(name, synonym=True): name = name.lower() name = re.sub(r"[^a-z ]", " ", name) name = " ".join(name.strip().split()) and_name = " & ".join(name.split(" ")) or_name = " | ".join(name.split(" ")) name = f"({and_name}) | ({or_name})" query = SearchQuery(name, search_type="raw", config="english") search_args = {} if synonym: search_args["name_search_vector__synonym"] = query else: search_args["name_search_vector"] = query qs = ( Person.objects.annotate(membership_count=Count("memberships")) .filter(**search_args) .annotate(rank=SearchRank(F("name_search_vector"), query)) .order_by("-rank", "membership_count") .defer("biography", "versions") ) return qs
Make sure we can search names with '
Make sure we can search names with '
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
--- +++ @@ -8,7 +8,7 @@ def search_person_by_name(name, synonym=True): name = name.lower() - name = re.sub(r"[^a-z ]", "", name) + name = re.sub(r"[^a-z ]", " ", name) name = " ".join(name.strip().split()) and_name = " & ".join(name.split(" ")) or_name = " | ".join(name.split(" "))
2d24b1b2f9fd5c661a48f233480ab09322d6bf91
heltour/local/martinsmacmini.py
heltour/local/martinsmacmini.py
DEBUG = True # GOOGLE_SERVICE_ACCOUNT_KEYFILE_PATH = '/home/vagrant/heltour/gspread.conf' # SLACK_API_TOKEN_FILE_PATH = '/home/vagrant/heltour/slack-token.conf' INTERNAL_IPS = ['127.0.0.1'] # JAVAFO_COMMAND = 'java -jar /home/vagrant/heltour/javafo.jar' # STATIC_ROOT = '/home/vagrant/heltour/static' # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEBUG = True # GOOGLE_SERVICE_ACCOUNT_KEYFILE_PATH = '/home/vagrant/heltour/gspread.conf' # SLACK_API_TOKEN_FILE_PATH = '/home/vagrant/heltour/slack-token.conf' INTERNAL_IPS = ['127.0.0.1'] LICHESS_CREDS_FILE_PATH = '/Users/colwem/workshop/heltour/.ignore/lichess.conf' LINK_PROTOCOL = 'http' SITE_ID = 2 # JAVAFO_COMMAND = 'java -jar /home/vagrant/heltour/javafo.jar' # STATIC_ROOT = '/home/vagrant/heltour/static' # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Add config to local config to enable login to work
Add config to local config to enable login to work
Python
mit
cyanfish/heltour,cyanfish/heltour,cyanfish/heltour,cyanfish/heltour
--- +++ @@ -3,6 +3,10 @@ # SLACK_API_TOKEN_FILE_PATH = '/home/vagrant/heltour/slack-token.conf' INTERNAL_IPS = ['127.0.0.1'] + +LICHESS_CREDS_FILE_PATH = '/Users/colwem/workshop/heltour/.ignore/lichess.conf' +LINK_PROTOCOL = 'http' +SITE_ID = 2 # JAVAFO_COMMAND = 'java -jar /home/vagrant/heltour/javafo.jar' # STATIC_ROOT = '/home/vagrant/heltour/static'
45fb01574d410c2a764e5b40a5e93a44fa8f6584
flask_admin/contrib/geoa/form.py
flask_admin/contrib/geoa/form.py
from flask.ext.admin.model.form import converts from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter from .fields import GeoJSONField class AdminModelConverter(SQLAAdminConverter): @converts('Geometry') def convert_geom(self, column, field_args, **extra): field_args['geometry_type'] = column.type.geometry_type field_args['srid'] = column.type.srid field_args['session'] = self.session return GeoJSONField(**field_args)
from flask.ext.admin.model.form import converts from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter from .fields import GeoJSONField class AdminModelConverter(SQLAAdminConverter): @converts('Geography', 'Geometry') def convert_geom(self, column, field_args, **extra): field_args['geometry_type'] = column.type.geometry_type field_args['srid'] = column.type.srid field_args['session'] = self.session return GeoJSONField(**field_args)
Add Geography Type to GeoAlchemy Backend
Add Geography Type to GeoAlchemy Backend The current GeoAlchemy backend only works with geometry columns, and ignores geography columns (which are also supported by geoalchemy). This 1-word fix adds support for geography columns.
Python
bsd-3-clause
litnimax/flask-admin,petrus-jvrensburg/flask-admin,closeio/flask-admin,torotil/flask-admin,jmagnusson/flask-admin,marrybird/flask-admin,dxmo/flask-admin,ondoheer/flask-admin,plaes/flask-admin,LennartP/flask-admin,jamesbeebop/flask-admin,NickWoodhams/flask-admin,closeio/flask-admin,CoolCloud/flask-admin,radioprotector/flask-admin,iurisilvio/flask-admin,chase-seibert/flask-admin,marrybird/flask-admin,betterlife/flask-admin,dxmo/flask-admin,petrus-jvrensburg/flask-admin,wuxiangfeng/flask-admin,likaiguo/flask-admin,mrjoes/flask-admin,AlmogCohen/flask-admin,phantomxc/flask-admin,chase-seibert/flask-admin,chase-seibert/flask-admin,likaiguo/flask-admin,chase-seibert/flask-admin,iurisilvio/flask-admin,CoolCloud/flask-admin,Kha/flask-admin,ibushong/test-repo,Junnplus/flask-admin,quokkaproject/flask-admin,wuxiangfeng/flask-admin,ArtemSerga/flask-admin,quokkaproject/flask-admin,lifei/flask-admin,HermasT/flask-admin,torotil/flask-admin,plaes/flask-admin,AlmogCohen/flask-admin,late-warrior/flask-admin,likaiguo/flask-admin,rochacbruno/flask-admin,janusnic/flask-admin,NickWoodhams/flask-admin,toddetzel/flask-admin,ArtemSerga/flask-admin,likaiguo/flask-admin,ondoheer/flask-admin,mikelambert/flask-admin,ArtemSerga/flask-admin,ibushong/test-repo,mrjoes/flask-admin,Kha/flask-admin,phantomxc/flask-admin,CoolCloud/flask-admin,ondoheer/flask-admin,mikelambert/flask-admin,janusnic/flask-admin,jamesbeebop/flask-admin,radioprotector/flask-admin,betterlife/flask-admin,flask-admin/flask-admin,plaes/flask-admin,jschneier/flask-admin,flabe81/flask-admin,torotil/flask-admin,AlmogCohen/flask-admin,betterlife/flask-admin,betterlife/flask-admin,mikelambert/flask-admin,jmagnusson/flask-admin,jamesbeebop/flask-admin,flabe81/flask-admin,plaes/flask-admin,jamesbeebop/flask-admin,iurisilvio/flask-admin,jschneier/flask-admin,radioprotector/flask-admin,Kha/flask-admin,Kha/flask-admin,quokkaproject/flask-admin,LennartP/flask-admin,phantomxc/flask-admin,HermasT/flask-admin,janusnic/flask-admin,late-warrior/flask-admin,mrjoes/flask-admin,marrybird/flask-admin,closeio/flask-admin,CoolCloud/flask-admin,AlmogCohen/flask-admin,NickWoodhams/flask-admin,iurisilvio/flask-admin,NickWoodhams/flask-admin,ibushong/test-repo,HermasT/flask-admin,litnimax/flask-admin,late-warrior/flask-admin,Junnplus/flask-admin,jmagnusson/flask-admin,HermasT/flask-admin,torotil/flask-admin,jmagnusson/flask-admin,LennartP/flask-admin,radioprotector/flask-admin,toddetzel/flask-admin,jschneier/flask-admin,jschneier/flask-admin,phantomxc/flask-admin,mrjoes/flask-admin,petrus-jvrensburg/flask-admin,ibushong/test-repo,lifei/flask-admin,rochacbruno/flask-admin,LennartP/flask-admin,lifei/flask-admin,flask-admin/flask-admin,ondoheer/flask-admin,flask-admin/flask-admin,flask-admin/flask-admin,dxmo/flask-admin,ArtemSerga/flask-admin,janusnic/flask-admin,Junnplus/flask-admin,litnimax/flask-admin,wuxiangfeng/flask-admin,petrus-jvrensburg/flask-admin,Junnplus/flask-admin,rochacbruno/flask-admin,litnimax/flask-admin,marrybird/flask-admin,mikelambert/flask-admin,flabe81/flask-admin,lifei/flask-admin,quokkaproject/flask-admin,toddetzel/flask-admin,flabe81/flask-admin,rochacbruno/flask-admin,wuxiangfeng/flask-admin,dxmo/flask-admin,closeio/flask-admin,late-warrior/flask-admin,toddetzel/flask-admin
--- +++ @@ -4,7 +4,7 @@ class AdminModelConverter(SQLAAdminConverter): - @converts('Geometry') + @converts('Geography', 'Geometry') def convert_geom(self, column, field_args, **extra): field_args['geometry_type'] = column.type.geometry_type field_args['srid'] = column.type.srid
e8711eca94afb6ab05baf6e61ddee95d193f3cd7
fabfile/oae_env/__init__.py
fabfile/oae_env/__init__.py
def activity_hosts(): return ["activity0", "activity1", "activity2"] def app_hosts(): return ["app0", "app1", "app2", "app3"] def etherpad_hosts(): return ["etherpad0", "etherpad1", "etherpad2"] def pp_hosts(): return ["pp0", "pp1", "pp2"] def puppet_host(): return "puppet" def web_host(): return "web0"
def activity_hosts(): return ["activity0", "activity1", "activity2"] def app_hosts(): return ["app0", "app1", "app2", "app3"] def etherpad_hosts(): return ["etherpad0", "etherpad1", "etherpad2"] def pp_hosts(): return ["pp0", "pp1", "pp2"] def puppet_host(): return "puppet" def web_host(): return "web1"
Switch web node to web1
Switch web node to web1
Python
apache-2.0
oaeproject/oae-fabric
--- +++ @@ -21,4 +21,4 @@ def web_host(): - return "web0" + return "web1"
577ec0c981651cb039f768b9eb92ef91f8511017
flocker/control/_clusterstate.py
flocker/control/_clusterstate.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Combine and retrieve current cluster state. """ from twisted.application.service import Service from ._model import Deployment, Node class ClusterStateService(Service): """ Store known current cluster state, and combine partial updates with the existing known state. https://clusterhq.atlassian.net/browse/FLOC-1269 will deal with semantics of expiring data, which should happen so stale information isn't treated as correct. """ def __init__(self): self._nodes = {} def update_node_state(self, hostname, node_state): """ Update the state of a given node. :param unicode hostname: The node's identifier. :param NodeState node_state: The state of the node. """ self._nodes[hostname] = node_state def as_deployment(self): """ Return cluster state as a Deployment object. """ return Deployment(nodes=frozenset([ Node(hostname=hostname, applications=frozenset( node_state.running + node_state.not_running)) for hostname, node_state in self._nodes.items()]))
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Combine and retrieve current cluster state. """ from twisted.application.service import Service from ._model import Deployment, Node class ClusterStateService(Service): """ Store known current cluster state, and combine partial updates with the existing known state. https://clusterhq.atlassian.net/browse/FLOC-1269 will deal with semantics of expiring data, which should happen so stale information isn't treated as correct. """ def __init__(self): self._nodes = {} def update_node_state(self, hostname, node_state): """ Update the state of a given node. :param unicode hostname: The node's identifier. :param NodeState node_state: The state of the node. """ self._nodes[hostname] = node_state def as_deployment(self): """ Return cluster state as a Deployment object. :return Deployment: Current state of the cluster. """ return Deployment(nodes=frozenset([ Node(hostname=hostname, applications=frozenset( node_state.running + node_state.not_running)) for hostname, node_state in self._nodes.items()]))
Address review comment: Document return type.
Address review comment: Document return type.
Python
apache-2.0
agonzalezro/flocker,Azulinho/flocker,LaynePeng/flocker,runcom/flocker,achanda/flocker,jml/flocker,1d4Nf6/flocker,mbrukman/flocker,jml/flocker,adamtheturtle/flocker,lukemarsden/flocker,moypray/flocker,achanda/flocker,w4ngyi/flocker,LaynePeng/flocker,mbrukman/flocker,w4ngyi/flocker,1d4Nf6/flocker,achanda/flocker,Azulinho/flocker,lukemarsden/flocker,AndyHuu/flocker,lukemarsden/flocker,hackday-profilers/flocker,adamtheturtle/flocker,hackday-profilers/flocker,hackday-profilers/flocker,wallnerryan/flocker-profiles,runcom/flocker,AndyHuu/flocker,moypray/flocker,Azulinho/flocker,w4ngyi/flocker,LaynePeng/flocker,jml/flocker,wallnerryan/flocker-profiles,runcom/flocker,agonzalezro/flocker,wallnerryan/flocker-profiles,adamtheturtle/flocker,agonzalezro/flocker,mbrukman/flocker,moypray/flocker,AndyHuu/flocker,1d4Nf6/flocker
--- +++ @@ -33,6 +33,8 @@ def as_deployment(self): """ Return cluster state as a Deployment object. + + :return Deployment: Current state of the cluster. """ return Deployment(nodes=frozenset([ Node(hostname=hostname,
02f5db5fdb46684b60a9b5e9125da228a927c2c3
mrbelvedereci/build/cumulusci/config.py
mrbelvedereci/build/cumulusci/config.py
from cumulusci.core.config import YamlGlobalConfig from cumulusci.core.config import YamlProjectConfig class MrbelvedereProjectConfig(YamlProjectConfig): def __init__(self, global_config_obj, build_flow): super(MrbelvedereProjectConfig, self).__init__(global_config_obj) self.build_flow = build_flow @property def config_project_local_path(self): """ mrbelvedere never uses the local path """ return @property def repo_root(self): return self.build_flow.build_dir @property def repo_name(self): return self.build_flow.build.repo.name @property def repo_url(self): return self.build_flow.build.repo.url @property def repo_owner(self): return self.build_flow.build.repo.url.split('/')[-2] @property def repo_branch(self): return self.build_flow.build.branch.name @property def repo_commit(self): return self.build_flow.build.commit class MrbelvedereGlobalConfig(YamlGlobalConfig): project_config_class = MrbelvedereProjectConfig def get_project_config(self, build_flow): return self.project_config_class(self, build_flow)
from cumulusci.core.config import YamlGlobalConfig from cumulusci.core.config import YamlProjectConfig class MrbelvedereProjectConfig(YamlProjectConfig): def __init__(self, global_config_obj, build_flow): self.build_flow = build_flow super(MrbelvedereProjectConfig, self).__init__(global_config_obj) @property def config_project_local_path(self): """ mrbelvedere never uses the local path """ return @property def repo_root(self): return self.build_flow.build_dir @property def repo_name(self): return self.build_flow.build.repo.name @property def repo_url(self): return self.build_flow.build.repo.url @property def repo_owner(self): return self.build_flow.build.repo.url.split('/')[-2] @property def repo_branch(self): return self.build_flow.build.branch.name @property def repo_commit(self): return self.build_flow.build.commit class MrbelvedereGlobalConfig(YamlGlobalConfig): project_config_class = MrbelvedereProjectConfig def get_project_config(self, build_flow): return self.project_config_class(self, build_flow)
Set self.build_flow before calling the super __init__ method
Set self.build_flow before calling the super __init__ method
Python
bsd-3-clause
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
--- +++ @@ -3,8 +3,8 @@ class MrbelvedereProjectConfig(YamlProjectConfig): def __init__(self, global_config_obj, build_flow): + self.build_flow = build_flow super(MrbelvedereProjectConfig, self).__init__(global_config_obj) - self.build_flow = build_flow @property def config_project_local_path(self):
c8d7224f62d7a8da08514c37acfa83e2754252c6
functionaltests/api/base.py
functionaltests/api/base.py
# -*- coding: utf-8 -*- # # Copyright 2013 - Noorul Islam K M # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.common import rest_client from tempest import config import testtools CONF = config.CONF class SolumClient(rest_client.RestClient): def __init__(self, config, username, password, auth_url, tenant_name=None): super(SolumClient, self).__init__(config, username, password, auth_url, tenant_name) self.service = 'application_deployment' class TestCase(testtools.TestCase): def setUp(self): super(TestCase, self).setUp() username = CONF.identity.username password = CONF.identity.password tenant_name = CONF.identity.tenant_name auth_url = CONF.identity.uri client_args = (CONF, username, password, auth_url, tenant_name) self.client = SolumClient(*client_args)
# -*- coding: utf-8 -*- # # Copyright 2013 - Noorul Islam K M # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.common import rest_client from tempest import config import testtools CONF = config.CONF class SolumClient(rest_client.RestClient): def __init__(self, username, password, auth_url, tenant_name=None): super(SolumClient, self).__init__(username, password, auth_url, tenant_name) self.service = 'application_deployment' class TestCase(testtools.TestCase): def setUp(self): super(TestCase, self).setUp() username = CONF.identity.username password = CONF.identity.password tenant_name = CONF.identity.tenant_name auth_url = CONF.identity.uri client_args = (username, password, auth_url, tenant_name) self.client = SolumClient(*client_args)
Fix Tempest tests failing on gate-solum-devstack-dsvm
Fix Tempest tests failing on gate-solum-devstack-dsvm Due to a new commit on tempest, all our devstack tests were failing. This was due to an inheritance we have to RestClient from tempest. The signature of the constructor has changed. This patch changes the signature of our inherited classes to match the change from tempest Fixes bug 1275697 Change-Id: I848d4b70d3b5129295d4aec5edbd4c03428ca0cc
Python
apache-2.0
ed-/solum,julienvey/solum,devdattakulkarni/test-solum,openstack/solum,stackforge/solum,gilbertpilz/solum,gilbertpilz/solum,ed-/solum,devdattakulkarni/test-solum,gilbertpilz/solum,openstack/solum,stackforge/solum,ed-/solum,julienvey/solum,ed-/solum,gilbertpilz/solum
--- +++ @@ -23,9 +23,9 @@ class SolumClient(rest_client.RestClient): - def __init__(self, config, username, password, auth_url, tenant_name=None): - super(SolumClient, self).__init__(config, username, password, - auth_url, tenant_name) + def __init__(self, username, password, auth_url, tenant_name=None): + super(SolumClient, self).__init__(username, password, auth_url, + tenant_name) self.service = 'application_deployment' @@ -36,6 +36,5 @@ password = CONF.identity.password tenant_name = CONF.identity.tenant_name auth_url = CONF.identity.uri - client_args = (CONF, username, password, - auth_url, tenant_name) + client_args = (username, password, auth_url, tenant_name) self.client = SolumClient(*client_args)
998586b575149ae549b755067c831f8b066c1845
digi/migrations/0002_theme_page_add_body_and_blog_category.py
digi/migrations/0002_theme_page_add_body_and_blog_category.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-08-04 11:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wagtail.wagtailcore.blocks import wagtail.wagtailcore.fields class Migration(migrations.Migration): dependencies = [ ('blog', '__latest__'), ('digi', '0001_initial'), ] operations = [ migrations.AddField( model_name='themepage', name='blog_category', field=models.ForeignKey(blank=True, help_text='Corresponding blog category', null=True, on_delete=django.db.models.deletion.SET_NULL, to='blog.BlogCategory'), ), migrations.AddField( model_name='themepage', name='body', field=wagtail.wagtailcore.fields.StreamField((('paragraph', wagtail.wagtailcore.blocks.RichTextBlock()),), blank=True, null=True), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-08-04 11:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wagtail.wagtailcore.blocks import wagtail.wagtailcore.fields class Migration(migrations.Migration): dependencies = [ ('blog', '0005_auto_20151019_1121'), ('digi', '0001_initial'), ] operations = [ migrations.AddField( model_name='themepage', name='blog_category', field=models.ForeignKey(blank=True, help_text='Corresponding blog category', null=True, on_delete=django.db.models.deletion.SET_NULL, to='blog.BlogCategory'), ), migrations.AddField( model_name='themepage', name='body', field=wagtail.wagtailcore.fields.StreamField((('paragraph', wagtail.wagtailcore.blocks.RichTextBlock()),), blank=True, null=True), ), ]
Use exact version instead of latest in the migration dependencies
Use exact version instead of latest in the migration dependencies Changed to use the latest migration of wagtail-blog v1.6.9. Refs https://github.com/thelabnyc/wagtail_blog/blob/5147d8129127102009c9bd63b1886e7665f6ccfb/blog/migrations/0005_auto_20151019_1121.py
Python
mit
City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel
--- +++ @@ -11,7 +11,7 @@ class Migration(migrations.Migration): dependencies = [ - ('blog', '__latest__'), + ('blog', '0005_auto_20151019_1121'), ('digi', '0001_initial'), ]
3ced8676d474df3149bf78519e918cfa3b6b0ec3
src/dal_gm2m/fields.py
src/dal_gm2m/fields.py
"""GM2MField support for autocomplete fields.""" class GM2MFieldMixin(object): """GM2MField ror FutureModelForm.""" def value_from_object(self, instance, name): """Return the list of objects in the GM2MField relation.""" return None if not instance.pk else [ x for x in getattr(instance, name).all()] def save_relation_data(self, instance, name, value): """Save the relation into the GM2MField.""" setattr(instance, name, value)
"""GM2MField support for autocomplete fields.""" class GM2MFieldMixin(object): """GM2MField ror FutureModelForm.""" def value_from_object(self, instance, name): """Return the list of objects in the GM2MField relation.""" return None if not instance.pk else [ getattr(x, 'gm2m_tgt', x) for x in getattr(instance, name).all() ] def save_relation_data(self, instance, name, value): """Save the relation into the GM2MField.""" setattr(instance, name, value)
Support new versions with django-gm2m
Support new versions with django-gm2m
Python
mit
yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light
--- +++ @@ -7,7 +7,9 @@ def value_from_object(self, instance, name): """Return the list of objects in the GM2MField relation.""" return None if not instance.pk else [ - x for x in getattr(instance, name).all()] + getattr(x, 'gm2m_tgt', x) + for x in getattr(instance, name).all() + ] def save_relation_data(self, instance, name, value): """Save the relation into the GM2MField."""
4855a379c3720588168a61545ab1af3291075489
Lib/distutils/__init__.py
Lib/distutils/__init__.py
"""distutils The main package for the Python Module Distribution Utilities. Normally used from a setup script as from distutils.core import setup setup (...) """ # This module should be kept compatible with Python 2.1. __revision__ = "$Id$" # Distutils version # # Please coordinate with Marc-Andre Lemburg <mal@egenix.com> when adding # new features to distutils that would warrant bumping the version number. # # In general, major and minor version should loosely follow the Python # version number the distutils code was shipped with. # __version__ = "2.5.0"
"""distutils The main package for the Python Module Distribution Utilities. Normally used from a setup script as from distutils.core import setup setup (...) """ # This module should be kept compatible with Python 2.1. __revision__ = "$Id$" # Distutils version # # Please coordinate with Marc-Andre Lemburg <mal@egenix.com> when adding # new features to distutils that would warrant bumping the version number. # # In general, major and minor version should loosely follow the Python # version number the distutils code was shipped with. # __version__ = "2.5.1"
Bump the patch level version of distutils since there were a few bug fixes since the 2.5.0 release.
Bump the patch level version of distutils since there were a few bug fixes since the 2.5.0 release.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -20,4 +20,4 @@ # In general, major and minor version should loosely follow the Python # version number the distutils code was shipped with. # -__version__ = "2.5.0" +__version__ = "2.5.1"
07a427d687a2618c03d62eb60d849c4ed26752c4
config.example.py
config.example.py
# Must be a mysql database! database_uri = 'mysql://root@localhost/pushjet_api' # Are we debugging the server? # Do not turn this on when in production! debug = True # Limit requests? limiter = False # Google Cloud Messaging configuration (required for android!) google_api_key = '' # Message Queueing, this should be the relay zeromq_relay_uri = ''
# Must be a mysql database! database_uri = 'mysql://root@localhost/pushjet_api' # Are we debugging the server? # Do not turn this on when in production! debug = True # Limit requests? limiter = False # Google Cloud Messaging configuration (required for android!) google_api_key = '' # Message Queueing, this should be the relay zeromq_relay_uri = 'ipc:///tmp/pushjet-relay.ipc'
Add default relay uri to the default config
Add default relay uri to the default config
Python
bsd-2-clause
Pushjet/Pushjet-Server-Api
--- +++ @@ -12,4 +12,4 @@ google_api_key = '' # Message Queueing, this should be the relay -zeromq_relay_uri = '' +zeromq_relay_uri = 'ipc:///tmp/pushjet-relay.ipc'
eb175a077affcdaa1e1cea6da557dd163890d958
djlime/forms/utils.py
djlime/forms/utils.py
# -*- coding: utf-8 -*- """ djlime.forms.utils ~~~~~~~~~~~~~~~~~~ Utilities for forms. :copyright: (c) 2012 by Andrey Voronov. :license: BSD, see LICENSE for more details. """ from django.utils import simplejson def form_errors_to_json(form): return simplejson.dumps({'success': False, 'errors': dict([(k, v[0]) for k, v in form.errors.items()])})
# -*- coding: utf-8 -*- """ djlime.forms.utils ~~~~~~~~~~~~~~~~~~ Utilities for forms. :copyright: (c) 2012 by Andrey Voronov. :license: BSD, see LICENSE for more details. """ from django.utils import simplejson def _errors_to_dict(form): return dict([(k, v[0]) for k, v in form.errors.items()]) def form_errors_to_json(form): if hasattr(form, '__iter__'): rv = {'success': False, 'errors': []} for f in form: rv['errors'].append(_errors_to_dict(f)) else: rv = {'success': False, 'errors': _errors_to_dict(form)} return simplejson.dumps(rv)
Improve form_errors_to_json to handle multiple forms
Improve form_errors_to_json to handle multiple forms
Python
bsd-3-clause
freshlimestudio/djlime
--- +++ @@ -10,6 +10,16 @@ """ from django.utils import simplejson + +def _errors_to_dict(form): + return dict([(k, v[0]) for k, v in form.errors.items()]) + + def form_errors_to_json(form): - return simplejson.dumps({'success': False, - 'errors': dict([(k, v[0]) for k, v in form.errors.items()])}) + if hasattr(form, '__iter__'): + rv = {'success': False, 'errors': []} + for f in form: + rv['errors'].append(_errors_to_dict(f)) + else: + rv = {'success': False, 'errors': _errors_to_dict(form)} + return simplejson.dumps(rv)
cfd6c7c2d7af47329deac3e7ff618b66a078263c
ines/middlewares/logs.py
ines/middlewares/logs.py
# -*- coding: utf-8 -*- import sys from traceback import format_exception from pyramid.decorator import reify from pyramid.httpexceptions import HTTPInternalServerError from pyramid.interfaces import IRequestFactory from ines.middlewares import Middleware from ines.utils import format_error_to_json class LoggingMiddleware(Middleware): name = 'logging' @property def request_factory(self): return self.config.registry.queryUtility(IRequestFactory) @reify def api_name(self): return self.settings.get('logging_api_name') or 'logging' def __call__(self, environ, start_response): try: for chunk in self.application(environ, start_response): yield chunk except (BaseException, Exception): type_, value, tb = sys.exc_info() error = ''.join(format_exception(type_, value, tb)) # Save / log error request = self.request_factory(environ) request.registry = self.config.registry try: message = error.split()[-1] getattr(request.api, self.api_name).log_critical('internal_server_error', message) except (BaseException, Exception): print error internal_server_error = HTTPInternalServerError() headers = [('Content-type', 'application/json')] start_response(internal_server_error.status, headers) yield format_error_to_json(internal_server_error, request=request)
# -*- coding: utf-8 -*- import sys from traceback import format_exception from pyramid.decorator import reify from pyramid.httpexceptions import HTTPInternalServerError from pyramid.interfaces import IRequestFactory from ines.convert import force_string from ines.middlewares import Middleware from ines.utils import format_error_to_json class LoggingMiddleware(Middleware): name = 'logging' @property def request_factory(self): return self.config.registry.queryUtility(IRequestFactory) @reify def api_name(self): return self.settings.get('logging_api_name') or 'logging' def __call__(self, environ, start_response): try: for chunk in self.application(environ, start_response): yield chunk except (BaseException, Exception) as error: type_, value, tb = sys.exc_info() message = ''.join(format_exception(type_, value, tb)) # Save / log error request = self.request_factory(environ) request.registry = self.config.registry try: small_message = '%s: %s' % (error.__class__.__name__, force_string(error)) except (BaseException, Exception): small_message = error try: getattr(request.api, self.api_name).log_critical( 'internal_server_error', str(small_message)) except (BaseException, Exception): print message internal_server_error = HTTPInternalServerError() headers = [('Content-type', 'application/json')] start_response(internal_server_error.status, headers) yield format_error_to_json(internal_server_error, request=request)
Set log with small message
Set log with small message
Python
mit
hugobranquinho/ines
--- +++ @@ -7,6 +7,7 @@ from pyramid.httpexceptions import HTTPInternalServerError from pyramid.interfaces import IRequestFactory +from ines.convert import force_string from ines.middlewares import Middleware from ines.utils import format_error_to_json @@ -26,19 +27,25 @@ try: for chunk in self.application(environ, start_response): yield chunk - except (BaseException, Exception): + except (BaseException, Exception) as error: type_, value, tb = sys.exc_info() - error = ''.join(format_exception(type_, value, tb)) + message = ''.join(format_exception(type_, value, tb)) # Save / log error request = self.request_factory(environ) request.registry = self.config.registry try: - message = error.split()[-1] - getattr(request.api, self.api_name).log_critical('internal_server_error', message) + small_message = '%s: %s' % (error.__class__.__name__, force_string(error)) except (BaseException, Exception): - print error + small_message = error + + try: + getattr(request.api, self.api_name).log_critical( + 'internal_server_error', + str(small_message)) + except (BaseException, Exception): + print message internal_server_error = HTTPInternalServerError() headers = [('Content-type', 'application/json')]
47d9217b6ee9837987d25d77cc6e3c750766ed90
tests/test_formats.py
tests/test_formats.py
from contextlib import contextmanager from tempfile import TemporaryDirectory from django.core.management import call_command from django.test import TestCase from django_archive import archivers class FormatsTestCase(TestCase): """ Test that the archive command works with all available formats """ _FORMATS = ( archivers.TARBALL, archivers.TARBALL_GZ, archivers.TARBALL_BZ2, archivers.TARBALL_XZ, archivers.ZIP, ) @contextmanager def _wrap_in_temp_dir(self): with TemporaryDirectory() as directory: yield self.settings(ARCHIVE_DIRECTORY=directory) def test_archive(self): """ Test each format """ for fmt in self._FORMATS: with self.subTest(fmt=fmt): with self._wrap_in_temp_dir(): with self.settings(ARCHIVE_FORMAT=fmt): call_command('archive')
from contextlib import contextmanager from tempfile import TemporaryDirectory from django.core.management import call_command from django.test import TestCase from django_archive import archivers class FormatsTestCase(TestCase): """ Test that the archive command works with all available formats """ _FORMATS = ( archivers.TARBALL, archivers.TARBALL_GZ, archivers.TARBALL_BZ2, archivers.TARBALL_XZ, archivers.ZIP, ) @contextmanager def _wrap_in_temp_dir(self): with TemporaryDirectory() as directory: with self.settings(ARCHIVE_DIRECTORY=directory): yield None def test_archive(self): """ Test each format """ for fmt in self._FORMATS: with self.subTest(fmt=fmt): with self._wrap_in_temp_dir(): with self.settings(ARCHIVE_FORMAT=fmt): call_command('archive')
Fix bug in temporary directory generation.
Fix bug in temporary directory generation.
Python
mit
nathan-osman/django-archive,nathan-osman/django-archive
--- +++ @@ -23,7 +23,8 @@ @contextmanager def _wrap_in_temp_dir(self): with TemporaryDirectory() as directory: - yield self.settings(ARCHIVE_DIRECTORY=directory) + with self.settings(ARCHIVE_DIRECTORY=directory): + yield None def test_archive(self): """
4ec8a5b5880f7e5300d71c34f5b293ea5993f5b2
tests/test_storage.py
tests/test_storage.py
import os import json import pytest def test_add_single(identity_fixures, identity_store): for d in identity_fixures: identity = identity_store.add_identity(d) for key, val in d.items(): assert getattr(identity, key) == val def test_add_multiple(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) assert len(identity_store.identities) == len(identity_fixures) def test_id_validation(identity_fixures, identity_store): from awsident.storage import IdentityExists identity_store.add_identities(*identity_fixures) with pytest.raises(IdentityExists): identity_store.add_identity(identity_fixures[0]) identity = identity_store.identities.values()[0] original_id = identity.id identity.access_key_id = 'ichanged' assert 'ichanged' in identity_store.keys() assert original_id not in identity_store.keys() def test_serialization(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) # data should have been saved at this point so clear and reload it identity_store.identities.clear() identity_store.load_from_config() for data in identity_fixures: identity = identity_store.get(data['access_key_id']) for key, val in data.items(): assert getattr(identity, key) == val
import os import json import pytest def test_add_single(identity_fixures, identity_store): for d in identity_fixures: identity = identity_store.add_identity(d) for key, val in d.items(): assert getattr(identity, key) == val def test_add_multiple(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) assert len(identity_store.identities) == len(identity_fixures) def test_id_validation(identity_fixures, identity_store): from awsident.storage import IdentityExists identity_store.add_identities(*identity_fixures) with pytest.raises(IdentityExists): identity_store.add_identity(identity_fixures[0]) identity = list(identity_store.values())[0] original_id = identity.id identity.access_key_id = 'ichanged' assert 'ichanged' in identity_store.keys() assert original_id not in identity_store.keys() def test_serialization(identity_fixures, identity_store): identity_store.add_identities(*identity_fixures) # data should have been saved at this point so clear and reload it identity_store.identities.clear() identity_store.load_from_config() for data in identity_fixures: identity = identity_store.get(data['access_key_id']) for key, val in data.items(): assert getattr(identity, key) == val
Convert dict view to list for Py3
Convert dict view to list for Py3
Python
mit
nocarryr/AWS-Identity-Manager
--- +++ @@ -19,7 +19,7 @@ identity_store.add_identities(*identity_fixures) with pytest.raises(IdentityExists): identity_store.add_identity(identity_fixures[0]) - identity = identity_store.identities.values()[0] + identity = list(identity_store.values())[0] original_id = identity.id identity.access_key_id = 'ichanged' assert 'ichanged' in identity_store.keys()
0fbffce39b7e0209d04e26bd43009c2e6e5e0c46
testsuite/settings.py
testsuite/settings.py
from pathlib import Path from hoover.site.settings.common import * INSTALLED_APPS = INSTALLED_APPS + [ 'hoover.contrib.twofactor', 'django_otp', 'django_otp.plugins.otp_totp', ] MIDDLEWARE = MIDDLEWARE + [ 'django_otp.middleware.OTPMiddleware', 'hoover.contrib.twofactor.middleware.AutoLogout', 'hoover.contrib.twofactor.middleware.RequireAuth', ] testsuite_dir = Path(__file__).absolute().parent del HOOVER_ELASTICSEARCH_URL SECRET_KEY = 'testing secret key' HOOVER_UPLOADS_ROOT = str(testsuite_dir / 'uploads') HOOVER_UI_ROOT = str(testsuite_dir / 'mock_ui') HOOVER_BASE_URL = 'http://testserver' HOOVER_RATELIMIT_USER = (30, 60) # 30 per minute HOOVER_TWOFACTOR_RATELIMIT = (3, 60) # 3 per minute from hoover.site.settings.testing_local import *
from pathlib import Path from hoover.site.settings.common import * INSTALLED_APPS = INSTALLED_APPS + [ 'hoover.contrib.twofactor', 'django_otp', 'django_otp.plugins.otp_totp', ] MIDDLEWARE = MIDDLEWARE + [ 'django_otp.middleware.OTPMiddleware', 'hoover.contrib.twofactor.middleware.AutoLogout', 'hoover.contrib.twofactor.middleware.RequireAuth', ] testsuite_dir = Path(__file__).absolute().parent SECRET_KEY = 'testing secret key' HOOVER_UPLOADS_ROOT = str(testsuite_dir / 'uploads') HOOVER_UI_ROOT = str(testsuite_dir / 'mock_ui') HOOVER_BASE_URL = 'http://testserver' HOOVER_RATELIMIT_USER = (30, 60) # 30 per minute HOOVER_TWOFACTOR_RATELIMIT = (3, 60) # 3 per minute DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'search', 'USER': 'search', 'HOST': 'search-pg', 'PORT': 5432, }, } HOOVER_ELASTICSEARCH_URL = 'http://search-es:9200'
Remove some indirection, set db password
Remove some indirection, set db password
Python
mit
hoover/search,hoover/search,hoover/search
--- +++ @@ -15,7 +15,6 @@ testsuite_dir = Path(__file__).absolute().parent -del HOOVER_ELASTICSEARCH_URL SECRET_KEY = 'testing secret key' HOOVER_UPLOADS_ROOT = str(testsuite_dir / 'uploads') HOOVER_UI_ROOT = str(testsuite_dir / 'mock_ui') @@ -23,4 +22,14 @@ HOOVER_RATELIMIT_USER = (30, 60) # 30 per minute HOOVER_TWOFACTOR_RATELIMIT = (3, 60) # 3 per minute -from hoover.site.settings.testing_local import * +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': 'search', + 'USER': 'search', + 'HOST': 'search-pg', + 'PORT': 5432, + }, +} + +HOOVER_ELASTICSEARCH_URL = 'http://search-es:9200'
8b25f5606b160422f6eb698f4edae8cb5013a310
dsub/_dsub_version.py
dsub/_dsub_version.py
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.2.6'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.3.0.dev0'
Update dsub version to 0.3.0.dev0
Update dsub version to 0.3.0.dev0 PiperOrigin-RevId: 241419925
Python
apache-2.0
DataBiosphere/dsub,DataBiosphere/dsub
--- +++ @@ -26,4 +26,4 @@ 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ -DSUB_VERSION = '0.2.6' +DSUB_VERSION = '0.3.0.dev0'
ce05a68965a252a1756d6eac64bf319ef17ed158
packages/python/plotly/plotly/io/_utils.py
packages/python/plotly/plotly/io/_utils.py
from __future__ import absolute_import import plotly import plotly.graph_objs as go def validate_coerce_fig_to_dict(fig, validate, clone=True): from plotly.basedatatypes import BaseFigure if isinstance(fig, BaseFigure): fig_dict = fig.to_dict(clone=clone) elif isinstance(fig, dict): if validate: # This will raise an exception if fig is not a valid plotly figure fig_dict = plotly.graph_objs.Figure(fig).to_plotly_json() else: fig_dict = fig else: raise ValueError( """ The fig parameter must be a dict or Figure. Received value of type {typ}: {v}""".format( typ=type(fig), v=fig ) ) return fig_dict def validate_coerce_output_type(output_type): if output_type == "Figure" or output_type == go.Figure: cls = go.Figure elif output_type == "FigureWidget" or ( hasattr(go, "FigureWidget") and output_type == go.FigureWidget ): cls = go.FigureWidget else: raise ValueError( """ Invalid output type: {output_type} Must be one of: 'Figure', 'FigureWidget'""" ) return cls
from __future__ import absolute_import import plotly import plotly.graph_objs as go def validate_coerce_fig_to_dict(fig, validate, clone=True): from plotly.basedatatypes import BaseFigure if isinstance(fig, BaseFigure): fig_dict = fig.to_dict(clone=clone) elif isinstance(fig, dict): if validate: # This will raise an exception if fig is not a valid plotly figure fig_dict = plotly.graph_objs.Figure(fig).to_plotly_json() else: fig_dict = fig elif hasattr(fig, "to_plotly_json"): fig_dict = fig.to_plotly_json() else: raise ValueError( """ The fig parameter must be a dict or Figure. Received value of type {typ}: {v}""".format( typ=type(fig), v=fig ) ) return fig_dict def validate_coerce_output_type(output_type): if output_type == "Figure" or output_type == go.Figure: cls = go.Figure elif output_type == "FigureWidget" or ( hasattr(go, "FigureWidget") and output_type == go.FigureWidget ): cls = go.FigureWidget else: raise ValueError( """ Invalid output type: {output_type} Must be one of: 'Figure', 'FigureWidget'""" ) return cls
Handle Dash objects in to_json
Handle Dash objects in to_json
Python
mit
plotly/plotly.py,plotly/plotly.py,plotly/plotly.py
--- +++ @@ -15,6 +15,8 @@ fig_dict = plotly.graph_objs.Figure(fig).to_plotly_json() else: fig_dict = fig + elif hasattr(fig, "to_plotly_json"): + fig_dict = fig.to_plotly_json() else: raise ValueError( """
65e12efb52e9eef330ab8f7a9f50a8f255fb4aae
JasmineCoffeeScriptDetectFileType.py
JasmineCoffeeScriptDetectFileType.py
import sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "Jasmine CoffeeScript", "jasmine-coffeescript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax)
import sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "Jasmine CoffeeScript", "Jasmine CoffeeScript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax)
Adjust syntax detector to account for new ST3 default package name
Adjust syntax detector to account for new ST3 default package name
Python
mit
integrum/sublime-text-jasmine-coffeescript
--- +++ @@ -11,7 +11,7 @@ name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): - set_syntax(view, "Jasmine CoffeeScript", "jasmine-coffeescript/Syntaxes") + set_syntax(view, "Jasmine CoffeeScript", "Jasmine CoffeeScript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None:
510ea7c6971ede66206cfb5d24b16a38f18ffee1
mzalendo/odekro/management/commands/add_mps.py
mzalendo/odekro/management/commands/add_mps.py
from django.core.management.base import BaseCommand, CommandError from odekro import data class Command(BaseCommand): """Read in an info page file and either create or update existing info""" help = 'Add MPs data' args = '<file>' def handle(self, *args, **options): # file = open(args[]) if len(args) != 1: raise CommandError path = args[0] content = open(path, 'r').read() data.add_mps_from_json(content)
from django.core.management.base import BaseCommand, CommandError from odekro import data class Command(BaseCommand): """Read in mps data and either create or update existing info""" help = 'Add MPs data' args = '<file>' def handle(self, *args, **options): # file = open(args[]) if len(args) != 1: raise CommandError path = args[0] content = open(path, 'r').read() data.add_mps_from_json(content)
Update a docstring to match the upstream odekro branch
Update a docstring to match the upstream odekro branch
Python
agpl-3.0
mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola
--- +++ @@ -4,7 +4,7 @@ class Command(BaseCommand): - """Read in an info page file and either create or update existing info""" + """Read in mps data and either create or update existing info""" help = 'Add MPs data' args = '<file>'
b5f7cf1a83d24a36def961f62556f26442d9f5ca
buckets/test/urls.py
buckets/test/urls.py
from django.conf.urls import include, url from buckets.test import views urlpatterns = [ url(r'^', include('buckets.urls')), url(r'^media/s3/uploads$', views.fake_s3_upload, name='fake_s3_upload'), ]
from django.conf.urls import include, url from buckets.test import views urlpatterns = [ url(r'^', include('buckets.urls')), url(r'^media/s3/uploads/$', views.fake_s3_upload, name='fake_s3_upload'), ]
Add trailing slash to fake_s3_upload url
Add trailing slash to fake_s3_upload url
Python
agpl-3.0
Cadasta/django-buckets,Cadasta/django-buckets,Cadasta/django-buckets
--- +++ @@ -3,5 +3,5 @@ urlpatterns = [ url(r'^', include('buckets.urls')), - url(r'^media/s3/uploads$', views.fake_s3_upload, name='fake_s3_upload'), + url(r'^media/s3/uploads/$', views.fake_s3_upload, name='fake_s3_upload'), ]
a376d66b4d58e22f35ad4f43e8b6f2ad775d68a8
vaux/api/downloads.py
vaux/api/downloads.py
from flask.ext import restful from . import database from flask import abort, send_file from werkzeug import secure_filename import os class DownloadInstance(restful.Resource): def get(self, id): document = database.get_document(id) if document is None: abort(404) return send_file(document['path'])
from flask.ext import restful from . import database from flask import abort, send_file import mimetypes class DownloadInstance(restful.Resource): def get(self, id): document = database.get_document(id) if document is None: abort(404) mt = mimetypes.guess_type(document['path'])[0] return send_file(document['path'], as_attachment=True, attachment_filename=document['name'], mimetype=mt)
Make sure we give people a download with the actual name of the file
Make sure we give people a download with the actual name of the file
Python
mit
VauxIo/core
--- +++ @@ -1,8 +1,7 @@ from flask.ext import restful from . import database from flask import abort, send_file -from werkzeug import secure_filename -import os +import mimetypes class DownloadInstance(restful.Resource): @@ -10,5 +9,8 @@ document = database.get_document(id) if document is None: abort(404) - return send_file(document['path']) - + mt = mimetypes.guess_type(document['path'])[0] + return send_file(document['path'], + as_attachment=True, + attachment_filename=document['name'], + mimetype=mt)
deac9119d4d03434a2d610920a431127927ac56a
netdisco/discoverables/belkin_wemo.py
netdisco/discoverables/belkin_wemo.py
""" Discovers Belkin Wemo devices. """ from . import SSDPDiscoverable class Discoverable(SSDPDiscoverable): """ Adds support for discovering Belkin WeMo platform devices. """ def info_from_entry(self, entry): """ Returns most important info from a uPnP entry. """ device = entry.description.find('device') return (device.find('friendlyName').text, device.find('modelName').text, entry.values['location']) def get_entries(self): """ Returns all Belkin Wemo entries. """ return self.find_by_st('urn:Belkin:service:manufacture:1')
""" Discovers Belkin Wemo devices. """ from . import SSDPDiscoverable class Discoverable(SSDPDiscoverable): """ Adds support for discovering Belkin WeMo platform devices. """ def info_from_entry(self, entry): """ Returns most important info from a uPnP entry. """ device = entry.description.find('device') return (device.find('friendlyName').text, device.find('modelName').text, entry.values['location']) def get_entries(self): """ Returns all Belkin Wemo entries. """ return self.find_by_device_description( {'manufacturer': 'Belkin International Inc.'})
Update discovery method for Wemo devices
Update discovery method for Wemo devices
Python
mit
sfam/netdisco,toddeye/netdisco,rohitranjan1991/netdisco,tomduijf/netdisco,brburns/netdisco,balloob/netdisco
--- +++ @@ -16,4 +16,5 @@ def get_entries(self): """ Returns all Belkin Wemo entries. """ - return self.find_by_st('urn:Belkin:service:manufacture:1') + return self.find_by_device_description( + {'manufacturer': 'Belkin International Inc.'})
e2c4529fc35c07721f1ed70ae2bf88538a67677b
slave/skia_slave_scripts/compare_gms.py
slave/skia_slave_scripts/compare_gms.py
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Compare the generated GM images to the baselines """ # System-level imports import os import sys from build_step import BuildStep, BuildStepWarning from utils import misc import run_gm class CompareGMs(BuildStep): def _Run(self): json_summary_path = misc.GetAbsPath(os.path.join( self._gm_actual_dir, run_gm.JSON_SUMMARY_FILENAME)) # Temporary list of builders who are allowed to fail this step without the # bot turning red. may_fail_with_warning = [ 'Test-Ubuntu12-ShuttleA-ATI5770-x86-Release', 'Test-Ubuntu12-ShuttleA-ATI5770-x86-Release-Trybot', ] # This import must happen after BuildStep.__init__ because it requires that # CWD is in PYTHONPATH, and BuildStep.__init__ may change the CWD. from gm import display_json_results if not display_json_results.Display(json_summary_path): if self._builder_name in may_fail_with_warning: raise BuildStepWarning('Expectations mismatch in %s!' % json_summary_path) else: raise Exception('Expectations mismatch in %s!' % json_summary_path) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(CompareGMs))
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Compare the generated GM images to the baselines """ # System-level imports import os import sys from build_step import BuildStep, BuildStepWarning from utils import misc import run_gm class CompareGMs(BuildStep): def _Run(self): json_summary_path = misc.GetAbsPath(os.path.join( self._gm_actual_dir, run_gm.JSON_SUMMARY_FILENAME)) # Temporary list of builders who are allowed to fail this step without the # bot turning red. may_fail_with_warning = [] # This import must happen after BuildStep.__init__ because it requires that # CWD is in PYTHONPATH, and BuildStep.__init__ may change the CWD. from gm import display_json_results if not display_json_results.Display(json_summary_path): if self._builder_name in may_fail_with_warning: raise BuildStepWarning('Expectations mismatch in %s!' % json_summary_path) else: raise Exception('Expectations mismatch in %s!' % json_summary_path) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(CompareGMs))
Remove Ubuntu12 32 from may_fail_with_warning
Remove Ubuntu12 32 from may_fail_with_warning It's empty now. TODO: Remove the functionality once we're sure we don't need it. R=robertphillips@google.com Review URL: https://codereview.chromium.org/23545022 git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@11055 2bbb7eff-a529-9590-31e7-b0007b416f81
Python
bsd-3-clause
Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot
--- +++ @@ -20,10 +20,7 @@ # Temporary list of builders who are allowed to fail this step without the # bot turning red. - may_fail_with_warning = [ - 'Test-Ubuntu12-ShuttleA-ATI5770-x86-Release', - 'Test-Ubuntu12-ShuttleA-ATI5770-x86-Release-Trybot', - ] + may_fail_with_warning = [] # This import must happen after BuildStep.__init__ because it requires that # CWD is in PYTHONPATH, and BuildStep.__init__ may change the CWD. from gm import display_json_results
53764e4ce0f82dc0706a9fd64877ccda5e97c32f
compd-score-match.py
compd-score-match.py
#!/usr/bin/env python import os import sys import yaml import score def usage(): print "Usage: score-match.py MATCH_NUMBER" print " Scores the match file at matches/MATCH_NUMBER.yaml" print " Outputs scoring format suitable for piping at compd" if len(sys.argv) is not 2: usage() exit(1) match_num = sys.argv[1] match_file = "matches/{0}.yaml".format(match_num) if not os.path.exists(match_file): print "Match file '{0}' doesn't exist. Have you created it?".format(match_file) usage() exit(2) scores = yaml.load(open(match_file).read()) scorer = score.StrangeGameScorer(scores) scorer.compute_cell_winners() for tla in scores.keys(): this_score = scorer.compute_game_score(tla) print 'set-score {0} {1} {2}'.format(match_num, tla, this_score) print 'calc-league-points {0}'.format(match_num)
#!/usr/bin/env python import os import sys import yaml import score MATCH_ID = 'match-{0}' def usage(): print "Usage: score-match.py MATCH_NUMBER" print " Scores the match file at matches/MATCH_NUMBER.yaml" print " Outputs scoring format suitable for piping at compd" if len(sys.argv) is not 2: usage() exit(1) match_num = sys.argv[1] match_file = "matches/{0}.yaml".format(match_num) if not os.path.exists(match_file): print "Match file '{0}' doesn't exist. Have you created it?".format(match_file) usage() exit(2) scores = yaml.load(open(match_file).read()) scorer = score.StrangeGameScorer(scores) scorer.compute_cell_winners() match_id = MATCH_ID.format(match_num) for tla in scores.keys(): this_score = scorer.compute_game_score(tla) print 'set-score {0} {1} {2}'.format(match_id, tla, this_score) print 'calc-league-points {0}'.format(match_id)
Update match-id to equal that used in compd.
Update match-id to equal that used in compd.
Python
mit
samphippen/scoring_2013,samphippen/scoring_2013
--- +++ @@ -5,6 +5,8 @@ import yaml import score + +MATCH_ID = 'match-{0}' def usage(): print "Usage: score-match.py MATCH_NUMBER" @@ -28,7 +30,9 @@ scorer = score.StrangeGameScorer(scores) scorer.compute_cell_winners() +match_id = MATCH_ID.format(match_num) + for tla in scores.keys(): this_score = scorer.compute_game_score(tla) - print 'set-score {0} {1} {2}'.format(match_num, tla, this_score) -print 'calc-league-points {0}'.format(match_num) + print 'set-score {0} {1} {2}'.format(match_id, tla, this_score) +print 'calc-league-points {0}'.format(match_id)