commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
38cd50805e080f6613d7e1d5867a84952ec88580
flask_resty/related.py
flask_resty/related.py
from .exceptions import ApiError # ----------------------------------------------------------------------------- class Related(object): def __init__(self, item_class=None, **kwargs): self._item_class = item_class self._view_classes = kwargs def resolve_related(self, data): for field_name, view_class in self._view_classes.items(): value = data.get(field_name, None) if value is None: # If this field were required or non-nullable, the deserializer # would already have raised an exception. continue try: resolved = self.resolve_field(value, view_class) except ApiError as e: pointer = '/data/{}'.format(field_name) raise e.update({'source': {'pointer': pointer}}) data[field_name] = resolved if self._item_class: return self._item_class(**data) return data def resolve_field(self, value, view_class): # marshmallow always uses lists here. many = isinstance(value, list) if many and not value: # As a tiny optimization, there's no need to resolve an empty list. return value if isinstance(view_class, Related): # This is not actually a view class. resolver = view_class.resolve_related else: resolver = view_class().resolve_related_item if many: return [resolver(item) for item in value] return resolver(value)
from .exceptions import ApiError # ----------------------------------------------------------------------------- class Related(object): def __init__(self, item_class=None, **kwargs): self._item_class = item_class self._resolvers = kwargs def resolve_related(self, data): for field_name, resolver in self._resolvers.items(): value = data.get(field_name, None) if value is None: # If this field were required or non-nullable, the deserializer # would already have raised an exception. continue try: resolved = self.resolve_field(value, resolver) except ApiError as e: pointer = '/data/{}'.format(field_name) raise e.update({'source': {'pointer': pointer}}) data[field_name] = resolved if self._item_class: return self._item_class(**data) return data def resolve_field(self, value, resolver): # marshmallow always uses lists here. many = isinstance(value, list) if many and not value: # As a tiny optimization, there's no need to resolve an empty list. return value if isinstance(resolver, Related): resolve_item = resolver.resolve_related else: resolve_item = resolver().resolve_related_item if many: return [resolve_item(item) for item in value] return resolve_item(value)
Fix variable names in Related
Fix variable names in Related
Python
mit
taion/flask-jsonapiview,4Catalyzer/flask-jsonapiview,4Catalyzer/flask-resty
from .exceptions import ApiError # ----------------------------------------------------------------------------- class Related(object): def __init__(self, item_class=None, **kwargs): self._item_class = item_class - self._view_classes = kwargs + self._resolvers = kwargs def resolve_related(self, data): - for field_name, view_class in self._view_classes.items(): + for field_name, resolver in self._resolvers.items(): value = data.get(field_name, None) if value is None: # If this field were required or non-nullable, the deserializer # would already have raised an exception. continue try: - resolved = self.resolve_field(value, view_class) + resolved = self.resolve_field(value, resolver) except ApiError as e: pointer = '/data/{}'.format(field_name) raise e.update({'source': {'pointer': pointer}}) data[field_name] = resolved if self._item_class: return self._item_class(**data) return data - def resolve_field(self, value, view_class): + def resolve_field(self, value, resolver): # marshmallow always uses lists here. many = isinstance(value, list) if many and not value: # As a tiny optimization, there's no need to resolve an empty list. return value - if isinstance(view_class, Related): + if isinstance(resolver, Related): + resolve_item = resolver.resolve_related - # This is not actually a view class. - resolver = view_class.resolve_related else: - resolver = view_class().resolve_related_item + resolve_item = resolver().resolve_related_item if many: - return [resolver(item) for item in value] + return [resolve_item(item) for item in value] - return resolver(value) + return resolve_item(value)
Fix variable names in Related
## Code Before: from .exceptions import ApiError # ----------------------------------------------------------------------------- class Related(object): def __init__(self, item_class=None, **kwargs): self._item_class = item_class self._view_classes = kwargs def resolve_related(self, data): for field_name, view_class in self._view_classes.items(): value = data.get(field_name, None) if value is None: # If this field were required or non-nullable, the deserializer # would already have raised an exception. continue try: resolved = self.resolve_field(value, view_class) except ApiError as e: pointer = '/data/{}'.format(field_name) raise e.update({'source': {'pointer': pointer}}) data[field_name] = resolved if self._item_class: return self._item_class(**data) return data def resolve_field(self, value, view_class): # marshmallow always uses lists here. many = isinstance(value, list) if many and not value: # As a tiny optimization, there's no need to resolve an empty list. return value if isinstance(view_class, Related): # This is not actually a view class. resolver = view_class.resolve_related else: resolver = view_class().resolve_related_item if many: return [resolver(item) for item in value] return resolver(value) ## Instruction: Fix variable names in Related ## Code After: from .exceptions import ApiError # ----------------------------------------------------------------------------- class Related(object): def __init__(self, item_class=None, **kwargs): self._item_class = item_class self._resolvers = kwargs def resolve_related(self, data): for field_name, resolver in self._resolvers.items(): value = data.get(field_name, None) if value is None: # If this field were required or non-nullable, the deserializer # would already have raised an exception. continue try: resolved = self.resolve_field(value, resolver) except ApiError as e: pointer = '/data/{}'.format(field_name) raise e.update({'source': {'pointer': pointer}}) data[field_name] = resolved if self._item_class: return self._item_class(**data) return data def resolve_field(self, value, resolver): # marshmallow always uses lists here. many = isinstance(value, list) if many and not value: # As a tiny optimization, there's no need to resolve an empty list. return value if isinstance(resolver, Related): resolve_item = resolver.resolve_related else: resolve_item = resolver().resolve_related_item if many: return [resolve_item(item) for item in value] return resolve_item(value)
8cdbbb52ebe161b0b7fea342e8a3d197ec290ab1
satnogsclient/settings.py
satnogsclient/settings.py
from os import environ DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', None) ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', None) DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', None) OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', None)
from os import environ DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', 'rtl_fm') ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', 'oggenc') DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', 'multimon-ng') OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', '/tmp')
Add default commands for encoding/decoding/demodulation.
Add default commands for encoding/decoding/demodulation.
Python
agpl-3.0
adamkalis/satnogs-client,adamkalis/satnogs-client,cshields/satnogs-client,cshields/satnogs-client
from os import environ - DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', None) + DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', 'rtl_fm') - ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', None) + ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', 'oggenc') - DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', None) + DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', 'multimon-ng') - OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', None) + OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', '/tmp')
Add default commands for encoding/decoding/demodulation.
## Code Before: from os import environ DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', None) ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', None) DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', None) OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', None) ## Instruction: Add default commands for encoding/decoding/demodulation. ## Code After: from os import environ DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', 'rtl_fm') ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', 'oggenc') DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', 'multimon-ng') OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', '/tmp')
3335c8c9ce8419d9d1d1034903687aa02983280d
tests/rules_tests/NoRuleSpecifiedTest.py
tests/rules_tests/NoRuleSpecifiedTest.py
from unittest import main, TestCase from grammpy import Rule class NoRuleSpecifiedTest(TestCase): pass if __name__ == '__main__': main()
from unittest import main, TestCase from grammpy import Rule from grammpy.exceptions import RuleNotDefinedException class NoRuleSpecifiedTest(TestCase): def test_noRule(self): class tmp(Rule): x = 5 with self.assertRaises(RuleNotDefinedException): x = tmp.rules with self.assertRaises(RuleNotDefinedException): x = tmp.rule with self.assertRaises(RuleNotDefinedException): x = tmp.left with self.assertRaises(RuleNotDefinedException): x = tmp.right with self.assertRaises(RuleNotDefinedException): x = tmp.fromSymbol with self.assertRaises(RuleNotDefinedException): x = tmp.toSymbol if __name__ == '__main__': main()
Add tests when no rules is specified
Add tests when no rules is specified
Python
mit
PatrikValkovic/grammpy
from unittest import main, TestCase from grammpy import Rule + from grammpy.exceptions import RuleNotDefinedException class NoRuleSpecifiedTest(TestCase): - pass + def test_noRule(self): + class tmp(Rule): + x = 5 + with self.assertRaises(RuleNotDefinedException): + x = tmp.rules + with self.assertRaises(RuleNotDefinedException): + x = tmp.rule + with self.assertRaises(RuleNotDefinedException): + x = tmp.left + with self.assertRaises(RuleNotDefinedException): + x = tmp.right + with self.assertRaises(RuleNotDefinedException): + x = tmp.fromSymbol + with self.assertRaises(RuleNotDefinedException): + x = tmp.toSymbol if __name__ == '__main__': main() +
Add tests when no rules is specified
## Code Before: from unittest import main, TestCase from grammpy import Rule class NoRuleSpecifiedTest(TestCase): pass if __name__ == '__main__': main() ## Instruction: Add tests when no rules is specified ## Code After: from unittest import main, TestCase from grammpy import Rule from grammpy.exceptions import RuleNotDefinedException class NoRuleSpecifiedTest(TestCase): def test_noRule(self): class tmp(Rule): x = 5 with self.assertRaises(RuleNotDefinedException): x = tmp.rules with self.assertRaises(RuleNotDefinedException): x = tmp.rule with self.assertRaises(RuleNotDefinedException): x = tmp.left with self.assertRaises(RuleNotDefinedException): x = tmp.right with self.assertRaises(RuleNotDefinedException): x = tmp.fromSymbol with self.assertRaises(RuleNotDefinedException): x = tmp.toSymbol if __name__ == '__main__': main()
91a7e4ba30c2c455c58b7069015680b7af511cc4
tests/test_get_joke.py
tests/test_get_joke.py
def test_get_joke(): from pyjokes import get_joke for i in range(10): assert get_joke() languages = ['eng', 'de', 'spa'] categories = ['neutral', 'explicit', 'all'] for lang in languages: for cat in categories: for i in range(10): assert get_joke(cat, lang)
import pytest from pyjokes import get_joke from pyjokes.pyjokes import LanguageNotFoundError, CategoryNotFoundError def test_get_joke(): assert get_joke() languages = ['en', 'de', 'es'] categories = ['neutral', 'explicit', 'all'] for lang in languages: assert get_joke(language=lang) for cat in categories: assert get_joke(category=cat) def test_get_joke_raises(): assert pytest.raises(LanguageNotFoundError, get_joke, language='eu') assert pytest.raises(LanguageNotFoundError, get_joke, language='tr') assert pytest.raises(CategoryNotFoundError, get_joke, category='123')
Simplify get_joke test, add raise checks
Simplify get_joke test, add raise checks
Python
bsd-3-clause
borjaayerdi/pyjokes,trojjer/pyjokes,martinohanlon/pyjokes,bennuttall/pyjokes,ElectronicsGeek/pyjokes,pyjokes/pyjokes,gmarkall/pyjokes
+ + import pytest + from pyjokes import get_joke + from pyjokes.pyjokes import LanguageNotFoundError, CategoryNotFoundError def test_get_joke(): - from pyjokes import get_joke + assert get_joke() - for i in range(10): - assert get_joke() - - languages = ['eng', 'de', 'spa'] + languages = ['en', 'de', 'es'] categories = ['neutral', 'explicit', 'all'] for lang in languages: + assert get_joke(language=lang) + - for cat in categories: + for cat in categories: - for i in range(10): - assert get_joke(cat, lang) + assert get_joke(category=cat) + + + def test_get_joke_raises(): + assert pytest.raises(LanguageNotFoundError, get_joke, language='eu') + + assert pytest.raises(LanguageNotFoundError, get_joke, language='tr') + + assert pytest.raises(CategoryNotFoundError, get_joke, category='123')
Simplify get_joke test, add raise checks
## Code Before: def test_get_joke(): from pyjokes import get_joke for i in range(10): assert get_joke() languages = ['eng', 'de', 'spa'] categories = ['neutral', 'explicit', 'all'] for lang in languages: for cat in categories: for i in range(10): assert get_joke(cat, lang) ## Instruction: Simplify get_joke test, add raise checks ## Code After: import pytest from pyjokes import get_joke from pyjokes.pyjokes import LanguageNotFoundError, CategoryNotFoundError def test_get_joke(): assert get_joke() languages = ['en', 'de', 'es'] categories = ['neutral', 'explicit', 'all'] for lang in languages: assert get_joke(language=lang) for cat in categories: assert get_joke(category=cat) def test_get_joke_raises(): assert pytest.raises(LanguageNotFoundError, get_joke, language='eu') assert pytest.raises(LanguageNotFoundError, get_joke, language='tr') assert pytest.raises(CategoryNotFoundError, get_joke, category='123')
67d067fe499ba2ec78d34083640a4bfe9835d62b
tests/test_sequence.py
tests/test_sequence.py
from unittest import TestCase from prudent.sequence import Sequence class SequenceTest(TestCase): def setUp(self): self.seq = Sequence([1, 2, 3]) def test_getitem(self): assert self.seq[0] == 1 self.seq[2] assert self.seq[2] == 3 def test_len(self): assert len(self.seq) == 0 self.seq[2] assert len(self.seq) == 3 def test_iter(self): for _ in range(2): assert list(self.seq) == [1, 2, 3]
from unittest import TestCase from prudent.sequence import Sequence class SequenceTest(TestCase): def setUp(self): self.seq = Sequence([1, 2, 3]) def test_getitem(self): assert self.seq[0] == 1 assert self.seq[2] == 3 def test_getitem_raises_indexerror(self): self.assertRaises(IndexError, lambda: self.seq[3]) def test_len_returns_current_size(self): assert len(self.seq) == 0 self.seq[2] assert len(self.seq) == 3 def test_iter_preserves_elems(self): for _ in range(2): assert list(self.seq) == [1, 2, 3]
Test that IndexError is raised when appropriate
Test that IndexError is raised when appropriate
Python
mit
eugene-eeo/prudent
from unittest import TestCase from prudent.sequence import Sequence class SequenceTest(TestCase): def setUp(self): self.seq = Sequence([1, 2, 3]) def test_getitem(self): assert self.seq[0] == 1 - self.seq[2] assert self.seq[2] == 3 - def test_len(self): + def test_getitem_raises_indexerror(self): + self.assertRaises(IndexError, lambda: self.seq[3]) + + def test_len_returns_current_size(self): assert len(self.seq) == 0 self.seq[2] assert len(self.seq) == 3 - def test_iter(self): + def test_iter_preserves_elems(self): for _ in range(2): assert list(self.seq) == [1, 2, 3]
Test that IndexError is raised when appropriate
## Code Before: from unittest import TestCase from prudent.sequence import Sequence class SequenceTest(TestCase): def setUp(self): self.seq = Sequence([1, 2, 3]) def test_getitem(self): assert self.seq[0] == 1 self.seq[2] assert self.seq[2] == 3 def test_len(self): assert len(self.seq) == 0 self.seq[2] assert len(self.seq) == 3 def test_iter(self): for _ in range(2): assert list(self.seq) == [1, 2, 3] ## Instruction: Test that IndexError is raised when appropriate ## Code After: from unittest import TestCase from prudent.sequence import Sequence class SequenceTest(TestCase): def setUp(self): self.seq = Sequence([1, 2, 3]) def test_getitem(self): assert self.seq[0] == 1 assert self.seq[2] == 3 def test_getitem_raises_indexerror(self): self.assertRaises(IndexError, lambda: self.seq[3]) def test_len_returns_current_size(self): assert len(self.seq) == 0 self.seq[2] assert len(self.seq) == 3 def test_iter_preserves_elems(self): for _ in range(2): assert list(self.seq) == [1, 2, 3]
caeb76cbcb6cdd49138e41f57144573598b722ba
source/clique/__init__.py
source/clique/__init__.py
from ._version import __version__
import re from collections import defaultdict from ._version import __version__ from .collection import Collection from .error import CollectionError #: Pattern for matching an index with optional padding. DIGITS_PATTERN = '(?P<index>(?P<padding>0*)\d+)' _DIGITS_REGEX = re.compile(DIGITS_PATTERN) #: Common patterns that can be passed to :py:func:`~clique.assemble`. PATTERNS = { 'frames': '\.{0}\.\D+\d?$'.format(DIGITS_PATTERN), 'versions': 'v{0}'.format(DIGITS_PATTERN) } def assemble(iterable, patterns=None, minimum_items=2): '''Assemble items in *iterable* into discreet collections. *patterns* may be specified as a list of regular expressions to limit the returned collection possibilities. Use this when interested in collections that only match specific patterns. Each pattern must contain the expression from :py:data:`DIGITS_PATTERN` exactly once. A selection of common expressions are available in :py:data:`PATTERNS`. .. note:: If a pattern is supplied as a string it will be automatically compiled to a regular expression for convenience. When *patterns* is not specified, collections are formed by examining all possible groupings of the items in *iterable* based around common numerical components. *minimum_items* dictates the minimum number of items a collection must have in order to be included in the result. The default is 2, filtering out single item collections. Return list of assembled :py:class:`~clique.collection.Collection` instances. ''' collection_map = defaultdict(set) collections = [] # Compile patterns. compiled_patterns = [] if patterns is not None: if not patterns: return collections for pattern in patterns: if isinstance(pattern, basestring): compiled_patterns.append(re.compile(pattern)) else: compiled_patterns.append(pattern) else: compiled_patterns.append(_DIGITS_REGEX) # Process iterable. for item in iterable: for pattern in compiled_patterns: for match in pattern.finditer(item): index = match.group('index') head = item[:match.start('index')] tail = item[match.end('index'):] padding = match.group('padding') if padding: padding = len(index) else: padding = 0 key = (head, tail, padding) collection_map[key].add(int(index)) # Form collections, filtering out those that do not have at least # as many indexes as minimum_items for (head, tail, padding), indexes in collection_map.items(): if len(indexes) >= minimum_items: collections.append( Collection(head, tail, padding, indexes) ) return collections
Add top level function to help assemble collections from arbitrary items.
Add top level function to help assemble collections from arbitrary items.
Python
apache-2.0
4degrees/clique
+ + import re + from collections import defaultdict from ._version import __version__ + from .collection import Collection + from .error import CollectionError + #: Pattern for matching an index with optional padding. + DIGITS_PATTERN = '(?P<index>(?P<padding>0*)\d+)' + + _DIGITS_REGEX = re.compile(DIGITS_PATTERN) + + #: Common patterns that can be passed to :py:func:`~clique.assemble`. + PATTERNS = { + 'frames': '\.{0}\.\D+\d?$'.format(DIGITS_PATTERN), + 'versions': 'v{0}'.format(DIGITS_PATTERN) + } + + + def assemble(iterable, patterns=None, minimum_items=2): + '''Assemble items in *iterable* into discreet collections. + + *patterns* may be specified as a list of regular expressions to limit + the returned collection possibilities. Use this when interested in + collections that only match specific patterns. Each pattern must contain + the expression from :py:data:`DIGITS_PATTERN` exactly once. + + A selection of common expressions are available in :py:data:`PATTERNS`. + + .. note:: + + If a pattern is supplied as a string it will be automatically compiled + to a regular expression for convenience. + + When *patterns* is not specified, collections are formed by examining all + possible groupings of the items in *iterable* based around common numerical + components. + + *minimum_items* dictates the minimum number of items a collection must have + in order to be included in the result. The default is 2, filtering out + single item collections. + + Return list of assembled :py:class:`~clique.collection.Collection` + instances. + + ''' + collection_map = defaultdict(set) + collections = [] + + # Compile patterns. + compiled_patterns = [] + + if patterns is not None: + if not patterns: + return collections + + for pattern in patterns: + if isinstance(pattern, basestring): + compiled_patterns.append(re.compile(pattern)) + else: + compiled_patterns.append(pattern) + + else: + compiled_patterns.append(_DIGITS_REGEX) + + # Process iterable. + for item in iterable: + for pattern in compiled_patterns: + for match in pattern.finditer(item): + index = match.group('index') + + head = item[:match.start('index')] + tail = item[match.end('index'):] + + padding = match.group('padding') + if padding: + padding = len(index) + else: + padding = 0 + + key = (head, tail, padding) + collection_map[key].add(int(index)) + + # Form collections, filtering out those that do not have at least + # as many indexes as minimum_items + for (head, tail, padding), indexes in collection_map.items(): + if len(indexes) >= minimum_items: + collections.append( + Collection(head, tail, padding, indexes) + ) + + return collections + +
Add top level function to help assemble collections from arbitrary items.
## Code Before: from ._version import __version__ ## Instruction: Add top level function to help assemble collections from arbitrary items. ## Code After: import re from collections import defaultdict from ._version import __version__ from .collection import Collection from .error import CollectionError #: Pattern for matching an index with optional padding. DIGITS_PATTERN = '(?P<index>(?P<padding>0*)\d+)' _DIGITS_REGEX = re.compile(DIGITS_PATTERN) #: Common patterns that can be passed to :py:func:`~clique.assemble`. PATTERNS = { 'frames': '\.{0}\.\D+\d?$'.format(DIGITS_PATTERN), 'versions': 'v{0}'.format(DIGITS_PATTERN) } def assemble(iterable, patterns=None, minimum_items=2): '''Assemble items in *iterable* into discreet collections. *patterns* may be specified as a list of regular expressions to limit the returned collection possibilities. Use this when interested in collections that only match specific patterns. Each pattern must contain the expression from :py:data:`DIGITS_PATTERN` exactly once. A selection of common expressions are available in :py:data:`PATTERNS`. .. note:: If a pattern is supplied as a string it will be automatically compiled to a regular expression for convenience. When *patterns* is not specified, collections are formed by examining all possible groupings of the items in *iterable* based around common numerical components. *minimum_items* dictates the minimum number of items a collection must have in order to be included in the result. The default is 2, filtering out single item collections. Return list of assembled :py:class:`~clique.collection.Collection` instances. ''' collection_map = defaultdict(set) collections = [] # Compile patterns. compiled_patterns = [] if patterns is not None: if not patterns: return collections for pattern in patterns: if isinstance(pattern, basestring): compiled_patterns.append(re.compile(pattern)) else: compiled_patterns.append(pattern) else: compiled_patterns.append(_DIGITS_REGEX) # Process iterable. for item in iterable: for pattern in compiled_patterns: for match in pattern.finditer(item): index = match.group('index') head = item[:match.start('index')] tail = item[match.end('index'):] padding = match.group('padding') if padding: padding = len(index) else: padding = 0 key = (head, tail, padding) collection_map[key].add(int(index)) # Form collections, filtering out those that do not have at least # as many indexes as minimum_items for (head, tail, padding), indexes in collection_map.items(): if len(indexes) >= minimum_items: collections.append( Collection(head, tail, padding, indexes) ) return collections
21b97ceea5b2e667940ddd45682313261eba845b
discode_server/notify.py
discode_server/notify.py
import json from discode_server import db from discode_server import fragments connected = set() notified = set() async def feed(request, ws): global connected connected.add(ws) print("Open WebSockets: ", len(connected)) try: while True: if not ws.open: return async with request.app.config.DB.acquire() as conn: await conn.execute(f"LISTEN channel") msg = await conn.connection.notifies.get() if not ws.open: return fingerprint = ws.remote_address, msg.payload if fingerprint in notified: continue notified.add(fingerprint) paste_id, lineno, comment_id = msg.payload.split(',') paste = await db.get_paste(conn, int(paste_id)) html = fragments.comment_row(lineno, paste.comments[int(lineno)]) data = json.dumps({ "html": html, "lineno": lineno, "paste_id": paste.id, "comment_id": comment_id, }) await ws.send(data) finally: connected.remove(ws) print("Open WebSockets: ", len(connected))
import asyncio import json from discode_server import db from discode_server import fragments connected = set() notified = set() async def feed(request, ws): global connected connected.add(ws) print("Open WebSockets: ", len(connected)) try: while True: if not ws.open: return async with request.app.config.DB.acquire() as conn: await conn.execute(f"LISTEN channel") try: msg = await asyncio.wait_for( conn.connection.notifies.get(), 1) except asyncio.TimeoutError: continue if not ws.open: return fingerprint = ws.remote_address, msg.payload if fingerprint in notified: continue notified.add(fingerprint) paste_id, lineno, comment_id = msg.payload.split(',') paste = await db.get_paste(conn, int(paste_id)) html = fragments.comment_row(lineno, paste.comments[int(lineno)]) data = json.dumps({ "html": html, "lineno": lineno, "paste_id": paste.id, "comment_id": comment_id, }) await ws.send(data) finally: connected.remove(ws) print("Open WebSockets: ", len(connected))
Add the asyncio wait_for back in
Add the asyncio wait_for back in
Python
bsd-2-clause
d0ugal/discode-server,d0ugal/discode-server,d0ugal/discode-server
+ import asyncio import json from discode_server import db from discode_server import fragments connected = set() notified = set() async def feed(request, ws): global connected connected.add(ws) print("Open WebSockets: ", len(connected)) try: while True: if not ws.open: return async with request.app.config.DB.acquire() as conn: await conn.execute(f"LISTEN channel") + try: + msg = await asyncio.wait_for( - msg = await conn.connection.notifies.get() + conn.connection.notifies.get(), 1) + except asyncio.TimeoutError: + continue if not ws.open: return fingerprint = ws.remote_address, msg.payload if fingerprint in notified: continue notified.add(fingerprint) paste_id, lineno, comment_id = msg.payload.split(',') paste = await db.get_paste(conn, int(paste_id)) html = fragments.comment_row(lineno, paste.comments[int(lineno)]) data = json.dumps({ "html": html, "lineno": lineno, "paste_id": paste.id, "comment_id": comment_id, }) await ws.send(data) finally: connected.remove(ws) print("Open WebSockets: ", len(connected))
Add the asyncio wait_for back in
## Code Before: import json from discode_server import db from discode_server import fragments connected = set() notified = set() async def feed(request, ws): global connected connected.add(ws) print("Open WebSockets: ", len(connected)) try: while True: if not ws.open: return async with request.app.config.DB.acquire() as conn: await conn.execute(f"LISTEN channel") msg = await conn.connection.notifies.get() if not ws.open: return fingerprint = ws.remote_address, msg.payload if fingerprint in notified: continue notified.add(fingerprint) paste_id, lineno, comment_id = msg.payload.split(',') paste = await db.get_paste(conn, int(paste_id)) html = fragments.comment_row(lineno, paste.comments[int(lineno)]) data = json.dumps({ "html": html, "lineno": lineno, "paste_id": paste.id, "comment_id": comment_id, }) await ws.send(data) finally: connected.remove(ws) print("Open WebSockets: ", len(connected)) ## Instruction: Add the asyncio wait_for back in ## Code After: import asyncio import json from discode_server import db from discode_server import fragments connected = set() notified = set() async def feed(request, ws): global connected connected.add(ws) print("Open WebSockets: ", len(connected)) try: while True: if not ws.open: return async with request.app.config.DB.acquire() as conn: await conn.execute(f"LISTEN channel") try: msg = await asyncio.wait_for( conn.connection.notifies.get(), 1) except asyncio.TimeoutError: continue if not ws.open: return fingerprint = ws.remote_address, msg.payload if fingerprint in notified: continue notified.add(fingerprint) paste_id, lineno, comment_id = msg.payload.split(',') paste = await db.get_paste(conn, int(paste_id)) html = fragments.comment_row(lineno, paste.comments[int(lineno)]) data = json.dumps({ "html": html, "lineno": lineno, "paste_id": paste.id, "comment_id": comment_id, }) await ws.send(data) finally: connected.remove(ws) print("Open WebSockets: ", len(connected))
c3d03629734abfead5ae1eae83d1b6dcec792b45
iconizer/django_in_iconizer/django_server.py
iconizer/django_in_iconizer/django_server.py
import os class DjangoServer(object): default_django_manage_script = "manage.py" def __init__(self, django_manage_script=None): super(DjangoServer, self).__init__() if django_manage_script is None: self.django_manage_script = self.default_django_manage_script else: self.django_manage_script = django_manage_script def get_task_descriptor(self, task_name, param_list=[]): task_name_and_param = [self.django_manage_script, task_name] task_name_and_param.extend(param_list) return {task_name: task_name_and_param} # noinspection PyMethodMayBeStatic def get_cmd_str(self, cmd_name, param_list=[]): return "python %s %s" % (self.django_manage_script, cmd_name) def execute_cmd(self, django_cmd): os.system(self.get_cmd_str(django_cmd))
import os class DjangoServer(object): default_django_manage_script = "manage.py" def __init__(self, django_manage_script=None): super(DjangoServer, self).__init__() if django_manage_script is None: self.django_manage_script = self.default_django_manage_script else: self.django_manage_script = django_manage_script self.django_manage_script = os.environ.get("MANAGE_PY", self.django_manage_script) def get_task_descriptor(self, task_name, param_list=[]): task_name_and_param = [self.django_manage_script, task_name] task_name_and_param.extend(param_list) return {task_name: task_name_and_param} # noinspection PyMethodMayBeStatic def get_cmd_str(self, cmd_name, param_list=[]): return "python %s %s" % (self.django_manage_script, cmd_name) def execute_cmd(self, django_cmd): os.system(self.get_cmd_str(django_cmd))
Enable specify command line processor.
Enable specify command line processor.
Python
bsd-3-clause
weijia/iconizer
import os class DjangoServer(object): default_django_manage_script = "manage.py" def __init__(self, django_manage_script=None): super(DjangoServer, self).__init__() if django_manage_script is None: self.django_manage_script = self.default_django_manage_script else: self.django_manage_script = django_manage_script + self.django_manage_script = os.environ.get("MANAGE_PY", self.django_manage_script) def get_task_descriptor(self, task_name, param_list=[]): task_name_and_param = [self.django_manage_script, task_name] task_name_and_param.extend(param_list) return {task_name: task_name_and_param} # noinspection PyMethodMayBeStatic def get_cmd_str(self, cmd_name, param_list=[]): return "python %s %s" % (self.django_manage_script, cmd_name) def execute_cmd(self, django_cmd): os.system(self.get_cmd_str(django_cmd))
Enable specify command line processor.
## Code Before: import os class DjangoServer(object): default_django_manage_script = "manage.py" def __init__(self, django_manage_script=None): super(DjangoServer, self).__init__() if django_manage_script is None: self.django_manage_script = self.default_django_manage_script else: self.django_manage_script = django_manage_script def get_task_descriptor(self, task_name, param_list=[]): task_name_and_param = [self.django_manage_script, task_name] task_name_and_param.extend(param_list) return {task_name: task_name_and_param} # noinspection PyMethodMayBeStatic def get_cmd_str(self, cmd_name, param_list=[]): return "python %s %s" % (self.django_manage_script, cmd_name) def execute_cmd(self, django_cmd): os.system(self.get_cmd_str(django_cmd)) ## Instruction: Enable specify command line processor. ## Code After: import os class DjangoServer(object): default_django_manage_script = "manage.py" def __init__(self, django_manage_script=None): super(DjangoServer, self).__init__() if django_manage_script is None: self.django_manage_script = self.default_django_manage_script else: self.django_manage_script = django_manage_script self.django_manage_script = os.environ.get("MANAGE_PY", self.django_manage_script) def get_task_descriptor(self, task_name, param_list=[]): task_name_and_param = [self.django_manage_script, task_name] task_name_and_param.extend(param_list) return {task_name: task_name_and_param} # noinspection PyMethodMayBeStatic def get_cmd_str(self, cmd_name, param_list=[]): return "python %s %s" % (self.django_manage_script, cmd_name) def execute_cmd(self, django_cmd): os.system(self.get_cmd_str(django_cmd))
fce890ce9046dd055f219ac880ae9734f334f534
greenlight/harness/arguments.py
greenlight/harness/arguments.py
from marionette import BaseMarionetteOptions from greenlight import tests class ReleaseTestParser(BaseMarionetteOptions): def parse_args(self, *args, **kwargs): options, test_files = BaseMarionetteOptions.parse_args(self, *args, **kwargs) if not test_files: test_files = [tests.manifest] return (options, test_files)
from marionette import BaseMarionetteOptions from greenlight import tests class ReleaseTestParser(BaseMarionetteOptions): def parse_args(self, *args, **kwargs): options, test_files = BaseMarionetteOptions.parse_args(self, *args, **kwargs) if not any([(k.startswith('log_') and v is not None and '-' in v) for (k, v) in vars(options).items()]): options.log_mach = '-' if not test_files: test_files = [tests.manifest] return (options, test_files)
Make colored terminal output the default log formatter.
Make colored terminal output the default log formatter.
Python
mpl-2.0
myrdd/firefox-ui-tests,gbrmachado/firefox-ui-tests,utvar/firefox-ui-tests,chmanchester/firefox-ui-tests,armenzg/firefox-ui-tests,whimboo/firefox-ui-tests,myrdd/firefox-ui-tests,gbrmachado/firefox-ui-tests,sr-murthy/firefox-ui-tests,armenzg/firefox-ui-tests,Motwani/firefox-ui-tests,galgeek/firefox-ui-tests,armenzg/firefox-ui-tests,sr-murthy/firefox-ui-tests,sr-murthy/firefox-ui-tests,galgeek/firefox-ui-tests,myrdd/firefox-ui-tests,utvar/firefox-ui-tests,galgeek/firefox-ui-tests,whimboo/firefox-ui-tests,whimboo/firefox-ui-tests,Motwani/firefox-ui-tests,chmanchester/firefox-ui-tests
from marionette import BaseMarionetteOptions from greenlight import tests class ReleaseTestParser(BaseMarionetteOptions): def parse_args(self, *args, **kwargs): options, test_files = BaseMarionetteOptions.parse_args(self, *args, **kwargs) + + if not any([(k.startswith('log_') and v is not None and '-' in v) + for (k, v) in vars(options).items()]): + options.log_mach = '-' + if not test_files: test_files = [tests.manifest] return (options, test_files)
Make colored terminal output the default log formatter.
## Code Before: from marionette import BaseMarionetteOptions from greenlight import tests class ReleaseTestParser(BaseMarionetteOptions): def parse_args(self, *args, **kwargs): options, test_files = BaseMarionetteOptions.parse_args(self, *args, **kwargs) if not test_files: test_files = [tests.manifest] return (options, test_files) ## Instruction: Make colored terminal output the default log formatter. ## Code After: from marionette import BaseMarionetteOptions from greenlight import tests class ReleaseTestParser(BaseMarionetteOptions): def parse_args(self, *args, **kwargs): options, test_files = BaseMarionetteOptions.parse_args(self, *args, **kwargs) if not any([(k.startswith('log_') and v is not None and '-' in v) for (k, v) in vars(options).items()]): options.log_mach = '-' if not test_files: test_files = [tests.manifest] return (options, test_files)
f684692a013e80d0c4d07b1c0eba204bd94d2314
config.py
config.py
HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. ALLOW_UPDATE_WITHOUT_OLD = False
HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. # This WILL cause problems such as mapgen, mods and privilege information missing from the list ALLOW_UPDATE_WITHOUT_OLD = False
Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems
Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems
Python
lgpl-2.1
minetest/master-server,minetest/master-server,minetest/master-server
HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. + # This WILL cause problems such as mapgen, mods and privilege information missing from the list ALLOW_UPDATE_WITHOUT_OLD = False
Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems
## Code Before: HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. ALLOW_UPDATE_WITHOUT_OLD = False ## Instruction: Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems ## Code After: HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. # This WILL cause problems such as mapgen, mods and privilege information missing from the list ALLOW_UPDATE_WITHOUT_OLD = False
63e09b77e3b00a7483249417020fb093f98773a9
infrastructure/tests/helpers.py
infrastructure/tests/helpers.py
from datetime import datetime from django.contrib.staticfiles.testing import LiveServerTestCase from selenium import webdriver from selenium.webdriver import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait class BaseSeleniumTestCase(LiveServerTestCase): def setUp(self): super(BaseSeleniumTestCase, self).setUp() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("headless") chrome_options.add_argument("--no-sandbox") d = DesiredCapabilities.CHROME d["loggingPrefs"] = {"browser": "ALL"} self.selenium = webdriver.Chrome( chrome_options=chrome_options, desired_capabilities=d ) self.selenium.implicitly_wait(10) self.wait = WebDriverWait(self.selenium, 5) self.addCleanup(self.selenium.quit) def wait_until_text_in(self, selector, text): self.wait.until( EC.text_to_be_present_in_element((By.CSS_SELECTOR, selector), text) )
from datetime import datetime from django.contrib.staticfiles.testing import LiveServerTestCase from selenium import webdriver from selenium.webdriver import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait import logging logger = logging.Logger(__name__) class BaseSeleniumTestCase(LiveServerTestCase): def setUp(self): super(BaseSeleniumTestCase, self).setUp() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("headless") chrome_options.add_argument("--no-sandbox") d = DesiredCapabilities.CHROME d["loggingPrefs"] = {"browser": "ALL"} self.selenium = webdriver.Chrome( chrome_options=chrome_options, desired_capabilities=d ) self.selenium.implicitly_wait(10) self.wait = WebDriverWait(self.selenium, 5) self.addCleanup(self.selenium.quit) def wait_until_text_in(self, selector, text): if self.wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, selector), text)): pass else: text_content = self.selenium.find_elements_by_css_selector(selector)[0].text logger.error("Element contents: %s" % text_content)
Add logging to selector testing
Add logging to selector testing
Python
mit
Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data
from datetime import datetime from django.contrib.staticfiles.testing import LiveServerTestCase from selenium import webdriver from selenium.webdriver import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait + import logging + logger = logging.Logger(__name__) class BaseSeleniumTestCase(LiveServerTestCase): def setUp(self): super(BaseSeleniumTestCase, self).setUp() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("headless") chrome_options.add_argument("--no-sandbox") d = DesiredCapabilities.CHROME d["loggingPrefs"] = {"browser": "ALL"} self.selenium = webdriver.Chrome( chrome_options=chrome_options, desired_capabilities=d ) self.selenium.implicitly_wait(10) self.wait = WebDriverWait(self.selenium, 5) self.addCleanup(self.selenium.quit) def wait_until_text_in(self, selector, text): - self.wait.until( - EC.text_to_be_present_in_element((By.CSS_SELECTOR, selector), text) + if self.wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, selector), text)): - ) + pass + else: + text_content = self.selenium.find_elements_by_css_selector(selector)[0].text + logger.error("Element contents: %s" % text_content)
Add logging to selector testing
## Code Before: from datetime import datetime from django.contrib.staticfiles.testing import LiveServerTestCase from selenium import webdriver from selenium.webdriver import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait class BaseSeleniumTestCase(LiveServerTestCase): def setUp(self): super(BaseSeleniumTestCase, self).setUp() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("headless") chrome_options.add_argument("--no-sandbox") d = DesiredCapabilities.CHROME d["loggingPrefs"] = {"browser": "ALL"} self.selenium = webdriver.Chrome( chrome_options=chrome_options, desired_capabilities=d ) self.selenium.implicitly_wait(10) self.wait = WebDriverWait(self.selenium, 5) self.addCleanup(self.selenium.quit) def wait_until_text_in(self, selector, text): self.wait.until( EC.text_to_be_present_in_element((By.CSS_SELECTOR, selector), text) ) ## Instruction: Add logging to selector testing ## Code After: from datetime import datetime from django.contrib.staticfiles.testing import LiveServerTestCase from selenium import webdriver from selenium.webdriver import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait import logging logger = logging.Logger(__name__) class BaseSeleniumTestCase(LiveServerTestCase): def setUp(self): super(BaseSeleniumTestCase, self).setUp() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("headless") chrome_options.add_argument("--no-sandbox") d = DesiredCapabilities.CHROME d["loggingPrefs"] = {"browser": "ALL"} self.selenium = webdriver.Chrome( chrome_options=chrome_options, desired_capabilities=d ) self.selenium.implicitly_wait(10) self.wait = WebDriverWait(self.selenium, 5) self.addCleanup(self.selenium.quit) def wait_until_text_in(self, selector, text): if self.wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, selector), text)): pass else: text_content = self.selenium.find_elements_by_css_selector(selector)[0].text logger.error("Element contents: %s" % text_content)
d07b6483d110eb4c51f7c631f888d1bf30eacc1c
destroyer-runner.py
destroyer-runner.py
"""destroyer-runner.py - Run the main application""" import sys import subprocess if __name__ == '__main__': subprocess.call(['python', './destroyer/destroyer.py'] + [str(arg) for arg in sys.argv[1:]])
"""destroyer-runner.py - Run the main application""" from destroyer.destroyer import main if __name__ == '__main__': main()
Update with working code to run destroyer
Update with working code to run destroyer
Python
mit
jaredmichaelsmith/destroyer
"""destroyer-runner.py - Run the main application""" + from destroyer.destroyer import main - import sys - import subprocess if __name__ == '__main__': - subprocess.call(['python', './destroyer/destroyer.py'] + [str(arg) for arg in sys.argv[1:]]) + main()
Update with working code to run destroyer
## Code Before: """destroyer-runner.py - Run the main application""" import sys import subprocess if __name__ == '__main__': subprocess.call(['python', './destroyer/destroyer.py'] + [str(arg) for arg in sys.argv[1:]]) ## Instruction: Update with working code to run destroyer ## Code After: """destroyer-runner.py - Run the main application""" from destroyer.destroyer import main if __name__ == '__main__': main()
261c294690427b57d111c777cdc4d13b9c84f9d2
cloudkittydashboard/dashboards/admin/modules/forms.py
cloudkittydashboard/dashboards/admin/modules/forms.py
import logging from django.utils.translation import ugettext_lazy as _ from horizon import forms from cloudkittydashboard.api import cloudkitty as api LOG = logging.getLogger(__name__) class EditPriorityForm(forms.SelfHandlingForm): priority = forms.IntegerField(label=_("Priority"), required=True) def handle(self, request, data): ck_client = api.cloudkittyclient(request) return ck_client.modules.update( module_id=self.initial["module_id"], priority=data["priority"] )
from django.utils.translation import ugettext_lazy as _ from horizon import forms from cloudkittydashboard.api import cloudkitty as api class EditPriorityForm(forms.SelfHandlingForm): priority = forms.IntegerField(label=_("Priority"), required=True) def handle(self, request, data): ck_client = api.cloudkittyclient(request) return ck_client.modules.update( module_id=self.initial["module_id"], priority=data["priority"] )
Delete the unused LOG code
Delete the unused LOG code Change-Id: Ief253cdd226f8c2688429b0ff00785151a99759b
Python
apache-2.0
stackforge/cloudkitty-dashboard,openstack/cloudkitty-dashboard,openstack/cloudkitty-dashboard,openstack/cloudkitty-dashboard,stackforge/cloudkitty-dashboard,stackforge/cloudkitty-dashboard
- - import logging from django.utils.translation import ugettext_lazy as _ from horizon import forms from cloudkittydashboard.api import cloudkitty as api - - LOG = logging.getLogger(__name__) class EditPriorityForm(forms.SelfHandlingForm): priority = forms.IntegerField(label=_("Priority"), required=True) def handle(self, request, data): ck_client = api.cloudkittyclient(request) return ck_client.modules.update( module_id=self.initial["module_id"], priority=data["priority"] )
Delete the unused LOG code
## Code Before: import logging from django.utils.translation import ugettext_lazy as _ from horizon import forms from cloudkittydashboard.api import cloudkitty as api LOG = logging.getLogger(__name__) class EditPriorityForm(forms.SelfHandlingForm): priority = forms.IntegerField(label=_("Priority"), required=True) def handle(self, request, data): ck_client = api.cloudkittyclient(request) return ck_client.modules.update( module_id=self.initial["module_id"], priority=data["priority"] ) ## Instruction: Delete the unused LOG code ## Code After: from django.utils.translation import ugettext_lazy as _ from horizon import forms from cloudkittydashboard.api import cloudkitty as api class EditPriorityForm(forms.SelfHandlingForm): priority = forms.IntegerField(label=_("Priority"), required=True) def handle(self, request, data): ck_client = api.cloudkittyclient(request) return ck_client.modules.update( module_id=self.initial["module_id"], priority=data["priority"] )
316323387c508c88595f205182ea2436c271621d
src/highdicom/uid.py
src/highdicom/uid.py
import logging import pydicom logger = logging.getLogger(__name__) class UID(pydicom.uid.UID): """Unique DICOM identifier with a highdicom-specific UID prefix.""" def __new__(cls: type) -> str: prefix = '1.2.826.0.1.3680043.10.511.3.' identifier = pydicom.uid.generate_uid(prefix=prefix) return super().__new__(cls, identifier)
import logging from typing import Type, TypeVar import pydicom logger = logging.getLogger(__name__) T = TypeVar('T', bound='UID') class UID(pydicom.uid.UID): """Unique DICOM identifier with a highdicom-specific UID prefix.""" def __new__(cls: Type[T]) -> T: prefix = '1.2.826.0.1.3680043.10.511.3.' identifier = pydicom.uid.generate_uid(prefix=prefix) return super().__new__(cls, identifier)
Fix typing for UID class
Fix typing for UID class
Python
mit
MGHComputationalPathology/highdicom
import logging + from typing import Type, TypeVar import pydicom logger = logging.getLogger(__name__) + T = TypeVar('T', bound='UID') + + class UID(pydicom.uid.UID): """Unique DICOM identifier with a highdicom-specific UID prefix.""" - def __new__(cls: type) -> str: + def __new__(cls: Type[T]) -> T: prefix = '1.2.826.0.1.3680043.10.511.3.' identifier = pydicom.uid.generate_uid(prefix=prefix) return super().__new__(cls, identifier)
Fix typing for UID class
## Code Before: import logging import pydicom logger = logging.getLogger(__name__) class UID(pydicom.uid.UID): """Unique DICOM identifier with a highdicom-specific UID prefix.""" def __new__(cls: type) -> str: prefix = '1.2.826.0.1.3680043.10.511.3.' identifier = pydicom.uid.generate_uid(prefix=prefix) return super().__new__(cls, identifier) ## Instruction: Fix typing for UID class ## Code After: import logging from typing import Type, TypeVar import pydicom logger = logging.getLogger(__name__) T = TypeVar('T', bound='UID') class UID(pydicom.uid.UID): """Unique DICOM identifier with a highdicom-specific UID prefix.""" def __new__(cls: Type[T]) -> T: prefix = '1.2.826.0.1.3680043.10.511.3.' identifier = pydicom.uid.generate_uid(prefix=prefix) return super().__new__(cls, identifier)
ee53ec51d98802bf0bc55e70c39cc0918f2bb274
icekit/plugins/blog_post/content_plugins.py
icekit/plugins/blog_post/content_plugins.py
from django.apps import apps from django.conf import settings from django.db.models.loading import get_model from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool default_blog_model = 'blog_tools.BlogPost' icekit_blog_model = getattr(settings, 'ICEKIT_BLOG_MODEL', default_blog_model) BLOG_MODEL = apps.get_model(*icekit_blog_model.rsplit('.', 1)) if icekit_blog_model != default_blog_model: @plugin_pool.register class BlogPostPlugin(ContentPlugin): model = get_model(getattr(settings, 'ICEKIT_BLOG_CONTENT_ITEM', 'blog_post.PostItem')) category = _('Blog') render_template = 'icekit/plugins/post/default.html' raw_id_fields = ['post', ]
from django.apps import apps from django.conf import settings from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool default_blog_model = 'blog_tools.BlogPost' icekit_blog_model = getattr(settings, 'ICEKIT_BLOG_MODEL', default_blog_model) BLOG_MODEL = apps.get_model(*icekit_blog_model.rsplit('.', 1)) if icekit_blog_model != default_blog_model: @plugin_pool.register class BlogPostPlugin(ContentPlugin): model = apps.get_model(getattr(settings, 'ICEKIT_BLOG_CONTENT_ITEM', 'blog_post.BlogPostItem')) category = _('Blog') render_template = 'icekit/plugins/post/default.html' raw_id_fields = ['post', ]
Update Blog model and content item matching
Update Blog model and content item matching
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
from django.apps import apps from django.conf import settings - from django.db.models.loading import get_model from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool default_blog_model = 'blog_tools.BlogPost' icekit_blog_model = getattr(settings, 'ICEKIT_BLOG_MODEL', default_blog_model) BLOG_MODEL = apps.get_model(*icekit_blog_model.rsplit('.', 1)) if icekit_blog_model != default_blog_model: @plugin_pool.register class BlogPostPlugin(ContentPlugin): - model = get_model(getattr(settings, 'ICEKIT_BLOG_CONTENT_ITEM', 'blog_post.PostItem')) + model = apps.get_model(getattr(settings, 'ICEKIT_BLOG_CONTENT_ITEM', 'blog_post.BlogPostItem')) category = _('Blog') render_template = 'icekit/plugins/post/default.html' raw_id_fields = ['post', ]
Update Blog model and content item matching
## Code Before: from django.apps import apps from django.conf import settings from django.db.models.loading import get_model from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool default_blog_model = 'blog_tools.BlogPost' icekit_blog_model = getattr(settings, 'ICEKIT_BLOG_MODEL', default_blog_model) BLOG_MODEL = apps.get_model(*icekit_blog_model.rsplit('.', 1)) if icekit_blog_model != default_blog_model: @plugin_pool.register class BlogPostPlugin(ContentPlugin): model = get_model(getattr(settings, 'ICEKIT_BLOG_CONTENT_ITEM', 'blog_post.PostItem')) category = _('Blog') render_template = 'icekit/plugins/post/default.html' raw_id_fields = ['post', ] ## Instruction: Update Blog model and content item matching ## Code After: from django.apps import apps from django.conf import settings from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool default_blog_model = 'blog_tools.BlogPost' icekit_blog_model = getattr(settings, 'ICEKIT_BLOG_MODEL', default_blog_model) BLOG_MODEL = apps.get_model(*icekit_blog_model.rsplit('.', 1)) if icekit_blog_model != default_blog_model: @plugin_pool.register class BlogPostPlugin(ContentPlugin): model = apps.get_model(getattr(settings, 'ICEKIT_BLOG_CONTENT_ITEM', 'blog_post.BlogPostItem')) category = _('Blog') render_template = 'icekit/plugins/post/default.html' raw_id_fields = ['post', ]
c7143cd725fc829c33ad9f9150e5975deb7be93a
irctest/optional_extensions.py
irctest/optional_extensions.py
import unittest import operator import itertools class OptionalExtensionNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported extension: {}'.format(self.args[0]) class OptionalSaslMechanismNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported SASL mechanism: {}'.format(self.args[0]) class OptionalityReportingTextTestRunner(unittest.TextTestRunner): def run(self, test): result = super().run(test) if result.skipped: print() print('Some tests were skipped because the following optional' 'specifications/mechanisms are not supported:') msg_to_tests = itertools.groupby(result.skipped, key=operator.itemgetter(1)) for (msg, tests) in msg_to_tests: print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests))) return result
import unittest import operator import itertools class NotImplementedByController(unittest.SkipTest): def __str__(self): return 'Not implemented by controller: {}'.format(self.args[0]) class OptionalExtensionNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported extension: {}'.format(self.args[0]) class OptionalSaslMechanismNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported SASL mechanism: {}'.format(self.args[0]) class OptionalityReportingTextTestRunner(unittest.TextTestRunner): def run(self, test): result = super().run(test) if result.skipped: print() print('Some tests were skipped because the following optional' 'specifications/mechanisms are not supported:') msg_to_tests = itertools.groupby(result.skipped, key=operator.itemgetter(1)) for (msg, tests) in sorted(msg_to_tests): print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests))) return result
Add an exception to tell a controller does not implement something.
Add an exception to tell a controller does not implement something.
Python
mit
ProgVal/irctest
import unittest import operator import itertools + + class NotImplementedByController(unittest.SkipTest): + def __str__(self): + return 'Not implemented by controller: {}'.format(self.args[0]) class OptionalExtensionNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported extension: {}'.format(self.args[0]) class OptionalSaslMechanismNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported SASL mechanism: {}'.format(self.args[0]) class OptionalityReportingTextTestRunner(unittest.TextTestRunner): def run(self, test): result = super().run(test) if result.skipped: print() print('Some tests were skipped because the following optional' 'specifications/mechanisms are not supported:') msg_to_tests = itertools.groupby(result.skipped, key=operator.itemgetter(1)) - for (msg, tests) in msg_to_tests: + for (msg, tests) in sorted(msg_to_tests): print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests))) return result
Add an exception to tell a controller does not implement something.
## Code Before: import unittest import operator import itertools class OptionalExtensionNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported extension: {}'.format(self.args[0]) class OptionalSaslMechanismNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported SASL mechanism: {}'.format(self.args[0]) class OptionalityReportingTextTestRunner(unittest.TextTestRunner): def run(self, test): result = super().run(test) if result.skipped: print() print('Some tests were skipped because the following optional' 'specifications/mechanisms are not supported:') msg_to_tests = itertools.groupby(result.skipped, key=operator.itemgetter(1)) for (msg, tests) in msg_to_tests: print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests))) return result ## Instruction: Add an exception to tell a controller does not implement something. ## Code After: import unittest import operator import itertools class NotImplementedByController(unittest.SkipTest): def __str__(self): return 'Not implemented by controller: {}'.format(self.args[0]) class OptionalExtensionNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported extension: {}'.format(self.args[0]) class OptionalSaslMechanismNotSupported(unittest.SkipTest): def __str__(self): return 'Unsupported SASL mechanism: {}'.format(self.args[0]) class OptionalityReportingTextTestRunner(unittest.TextTestRunner): def run(self, test): result = super().run(test) if result.skipped: print() print('Some tests were skipped because the following optional' 'specifications/mechanisms are not supported:') msg_to_tests = itertools.groupby(result.skipped, key=operator.itemgetter(1)) for (msg, tests) in sorted(msg_to_tests): print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests))) return result
a0ce4d366681f2f62f232f4f952ac18df07667d4
ideascube/conf/idb_fra_cultura.py
ideascube/conf/idb_fra_cultura.py
"""Ideaxbox Cultura, France""" from .idb import * # noqa from django.utils.translation import ugettext_lazy as _ IDEASCUBE_NAME = u"Cultura" IDEASCUBE_PLACE_NAME = _("city") COUNTRIES_FIRST = ['FR'] TIME_ZONE = None LANGUAGE_CODE = 'fr' LOAN_DURATION = 14 MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender'] USER_FORM_FIELDS = ( (_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa ) HOME_CARDS = HOME_CARDS + [ { 'id': 'cpassorcier', }, { 'id': 'wikisource', }, { 'id': 'software', }, { 'id': 'ted', }, { 'id': 'ubuntudoc', }, ]
"""Ideaxbox Cultura, France""" from .idb import * # noqa from django.utils.translation import ugettext_lazy as _ IDEASCUBE_NAME = u"Cultura" IDEASCUBE_PLACE_NAME = _("city") COUNTRIES_FIRST = ['FR'] TIME_ZONE = None LANGUAGE_CODE = 'fr' LOAN_DURATION = 14 MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender'] USER_FORM_FIELDS = ( (_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa ) HOME_CARDS = HOME_CARDS + [ { 'id': 'cpassorcier', }, { 'id': 'wikisource', }, { 'id': 'ted', }, { 'id': 'ubuntudoc', }, ]
Remove "software" card from Cultura conf
Remove "software" card from Cultura conf
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
"""Ideaxbox Cultura, France""" from .idb import * # noqa from django.utils.translation import ugettext_lazy as _ IDEASCUBE_NAME = u"Cultura" IDEASCUBE_PLACE_NAME = _("city") COUNTRIES_FIRST = ['FR'] TIME_ZONE = None LANGUAGE_CODE = 'fr' LOAN_DURATION = 14 MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender'] USER_FORM_FIELDS = ( (_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa ) HOME_CARDS = HOME_CARDS + [ { 'id': 'cpassorcier', }, { 'id': 'wikisource', }, { - 'id': 'software', - }, - { 'id': 'ted', }, { 'id': 'ubuntudoc', }, ]
Remove "software" card from Cultura conf
## Code Before: """Ideaxbox Cultura, France""" from .idb import * # noqa from django.utils.translation import ugettext_lazy as _ IDEASCUBE_NAME = u"Cultura" IDEASCUBE_PLACE_NAME = _("city") COUNTRIES_FIRST = ['FR'] TIME_ZONE = None LANGUAGE_CODE = 'fr' LOAN_DURATION = 14 MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender'] USER_FORM_FIELDS = ( (_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa ) HOME_CARDS = HOME_CARDS + [ { 'id': 'cpassorcier', }, { 'id': 'wikisource', }, { 'id': 'software', }, { 'id': 'ted', }, { 'id': 'ubuntudoc', }, ] ## Instruction: Remove "software" card from Cultura conf ## Code After: """Ideaxbox Cultura, France""" from .idb import * # noqa from django.utils.translation import ugettext_lazy as _ IDEASCUBE_NAME = u"Cultura" IDEASCUBE_PLACE_NAME = _("city") COUNTRIES_FIRST = ['FR'] TIME_ZONE = None LANGUAGE_CODE = 'fr' LOAN_DURATION = 14 MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender'] USER_FORM_FIELDS = ( (_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa ) HOME_CARDS = HOME_CARDS + [ { 'id': 'cpassorcier', }, { 'id': 'wikisource', }, { 'id': 'ted', }, { 'id': 'ubuntudoc', }, ]
a977908efcc176e1e5adbd82843033805953c6cb
tools/reago/format_reago_input_files.py
tools/reago/format_reago_input_files.py
import sys import os import argparse import re reago_dir = '/tools/rna_manipulation/reago/reago/' def add_read_pair_num(input_filepath, output_filepath, read_pair_num): to_add = '.' + str(read_pair_num) with open(input_filepath,'r') as input_file: with open(output_filepath,'w') as output_file: for line in input_file: if line[0] == '>': split_line = line.split() seq_id = split_line[0] if seq_id.rfind(to_add) != (len(seq_id)-len(to_add)): split_line[0] = seq_id + to_add output_file.write(' '.join(split_line) + '\n') else: output_file.write(line) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--r1_sequence_file', required=True) parser.add_argument('--r2_sequence_file', required=True) args = parser.parse_args() add_read_pair_num(args.r1_input_sequence_file, args.r1_input_sequence_file, 1) add_read_pair_num(args.r2_input_sequence_file, args.r2_input_sequence_file, 2)
import sys import os import argparse import re reago_dir = '/tools/rna_manipulation/reago/reago/' def add_read_pair_num(input_filepath, output_filepath, read_pair_num): to_add = '.' + str(read_pair_num) with open(input_filepath,'r') as input_file: with open(output_filepath,'w') as output_file: for line in input_file: if line[0] == '>': split_line = line.split() seq_id = split_line[0] if seq_id.rfind(to_add) != (len(seq_id)-len(to_add)): split_line[0] = seq_id + to_add output_file.write(' '.join(split_line) + '\n') else: output_file.write(line) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--r1_sequence_file', required=True) parser.add_argument('--r2_sequence_file', required=True) args = parser.parse_args() add_read_pair_num(args.r1_sequence_file, args.r1_sequence_file, 1) add_read_pair_num(args.r2_sequence_file, args.r2_sequence_file, 2)
Correct argument name in script to format reago input file
Correct argument name in script to format reago input file
Python
apache-2.0
ASaiM/galaxytools,ASaiM/galaxytools
import sys import os import argparse import re reago_dir = '/tools/rna_manipulation/reago/reago/' def add_read_pair_num(input_filepath, output_filepath, read_pair_num): to_add = '.' + str(read_pair_num) with open(input_filepath,'r') as input_file: with open(output_filepath,'w') as output_file: for line in input_file: if line[0] == '>': split_line = line.split() seq_id = split_line[0] if seq_id.rfind(to_add) != (len(seq_id)-len(to_add)): split_line[0] = seq_id + to_add output_file.write(' '.join(split_line) + '\n') else: output_file.write(line) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--r1_sequence_file', required=True) parser.add_argument('--r2_sequence_file', required=True) args = parser.parse_args() - add_read_pair_num(args.r1_input_sequence_file, args.r1_input_sequence_file, 1) - add_read_pair_num(args.r2_input_sequence_file, args.r2_input_sequence_file, 2) + add_read_pair_num(args.r1_sequence_file, args.r1_sequence_file, 1) + add_read_pair_num(args.r2_sequence_file, args.r2_sequence_file, 2)
Correct argument name in script to format reago input file
## Code Before: import sys import os import argparse import re reago_dir = '/tools/rna_manipulation/reago/reago/' def add_read_pair_num(input_filepath, output_filepath, read_pair_num): to_add = '.' + str(read_pair_num) with open(input_filepath,'r') as input_file: with open(output_filepath,'w') as output_file: for line in input_file: if line[0] == '>': split_line = line.split() seq_id = split_line[0] if seq_id.rfind(to_add) != (len(seq_id)-len(to_add)): split_line[0] = seq_id + to_add output_file.write(' '.join(split_line) + '\n') else: output_file.write(line) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--r1_sequence_file', required=True) parser.add_argument('--r2_sequence_file', required=True) args = parser.parse_args() add_read_pair_num(args.r1_input_sequence_file, args.r1_input_sequence_file, 1) add_read_pair_num(args.r2_input_sequence_file, args.r2_input_sequence_file, 2) ## Instruction: Correct argument name in script to format reago input file ## Code After: import sys import os import argparse import re reago_dir = '/tools/rna_manipulation/reago/reago/' def add_read_pair_num(input_filepath, output_filepath, read_pair_num): to_add = '.' + str(read_pair_num) with open(input_filepath,'r') as input_file: with open(output_filepath,'w') as output_file: for line in input_file: if line[0] == '>': split_line = line.split() seq_id = split_line[0] if seq_id.rfind(to_add) != (len(seq_id)-len(to_add)): split_line[0] = seq_id + to_add output_file.write(' '.join(split_line) + '\n') else: output_file.write(line) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--r1_sequence_file', required=True) parser.add_argument('--r2_sequence_file', required=True) args = parser.parse_args() add_read_pair_num(args.r1_sequence_file, args.r1_sequence_file, 1) add_read_pair_num(args.r2_sequence_file, args.r2_sequence_file, 2)
2015233d252e625419485c269f1f70a7e0edada8
skmisc/__init__.py
skmisc/__init__.py
from ._version import get_versions __version__ = get_versions()['version'] del get_versions __all__ = ['__version__'] # We first need to detect if we're being called as part of the skmisc # setup procedure itself in a reliable manner. try: __SKMISC_SETUP__ except NameError: __SKMISC_SETUP__ = False if __SKMISC_SETUP__: import sys as _sys _sys.stderr.write('Running from skmisc source directory.\n') del _sys else: from skmisc.__config__ import show as show_config # noqa: F401 # try: # from skmisc.__config__ import show as show_config # noqa: F401 # except ImportError: # msg = """Error importing skmisc: you cannot import skmisc while # being in skmisc source directory; please exit the skmisc source # tree first, and relaunch your python intepreter.""" # raise ImportError(msg) __all__.append('show_config') def test(args=None, plugins=None): """ Run tests """ # The doctests are not run when called from an installed # package since the pytest.ini is not included in the # package. import os try: import pytest except ImportError: msg = "To run the tests, you must install pytest" raise ImportError(msg) path = os.path.realpath(__file__) if args is None: args = [path] else: args.append(path) return pytest.main(args=args, plugins=plugins)
from ._version import get_versions __version__ = get_versions()['version'] del get_versions __all__ = ['__version__'] # We first need to detect if we're being called as part of the skmisc # setup procedure itself in a reliable manner. try: __SKMISC_SETUP__ except NameError: __SKMISC_SETUP__ = False if __SKMISC_SETUP__: import sys as _sys _sys.stderr.write('Running from skmisc source directory.\n') del _sys else: try: from skmisc.__config__ import show as show_config # noqa: F401 except ImportError as err: msg = """Error importing skmisc: you cannot import skmisc while being in skmisc source directory; please exit the skmisc source tree first, and relaunch your python intepreter.""" raise ImportError('\n\n'.join([err.message, msg])) __all__.append('show_config') def test(args=None, plugins=None): """ Run tests """ # The doctests are not run when called from an installed # package since the pytest.ini is not included in the # package. import os try: import pytest except ImportError: msg = "To run the tests, you must install pytest" raise ImportError(msg) path = os.path.dirname(os.path.realpath(__file__)) if args is None: args = [path] else: args.append(path) return pytest.main(args=args, plugins=plugins)
Fix pytest path to root of package
Fix pytest path to root of package Instead of the package init file.
Python
bsd-3-clause
has2k1/onelib,has2k1/onelib,has2k1/onelib
from ._version import get_versions __version__ = get_versions()['version'] del get_versions __all__ = ['__version__'] # We first need to detect if we're being called as part of the skmisc # setup procedure itself in a reliable manner. try: __SKMISC_SETUP__ except NameError: __SKMISC_SETUP__ = False if __SKMISC_SETUP__: import sys as _sys _sys.stderr.write('Running from skmisc source directory.\n') del _sys else: - from skmisc.__config__ import show as show_config # noqa: F401 - # try: + try: - # from skmisc.__config__ import show as show_config # noqa: F401 + from skmisc.__config__ import show as show_config # noqa: F401 - # except ImportError: + except ImportError as err: - # msg = """Error importing skmisc: you cannot import skmisc while + msg = """Error importing skmisc: you cannot import skmisc while - # being in skmisc source directory; please exit the skmisc source + being in skmisc source directory; please exit the skmisc source - # tree first, and relaunch your python intepreter.""" + tree first, and relaunch your python intepreter.""" - # raise ImportError(msg) + raise ImportError('\n\n'.join([err.message, msg])) __all__.append('show_config') def test(args=None, plugins=None): """ Run tests """ # The doctests are not run when called from an installed # package since the pytest.ini is not included in the # package. import os try: import pytest except ImportError: msg = "To run the tests, you must install pytest" raise ImportError(msg) - path = os.path.realpath(__file__) + path = os.path.dirname(os.path.realpath(__file__)) if args is None: args = [path] else: args.append(path) return pytest.main(args=args, plugins=plugins)
Fix pytest path to root of package
## Code Before: from ._version import get_versions __version__ = get_versions()['version'] del get_versions __all__ = ['__version__'] # We first need to detect if we're being called as part of the skmisc # setup procedure itself in a reliable manner. try: __SKMISC_SETUP__ except NameError: __SKMISC_SETUP__ = False if __SKMISC_SETUP__: import sys as _sys _sys.stderr.write('Running from skmisc source directory.\n') del _sys else: from skmisc.__config__ import show as show_config # noqa: F401 # try: # from skmisc.__config__ import show as show_config # noqa: F401 # except ImportError: # msg = """Error importing skmisc: you cannot import skmisc while # being in skmisc source directory; please exit the skmisc source # tree first, and relaunch your python intepreter.""" # raise ImportError(msg) __all__.append('show_config') def test(args=None, plugins=None): """ Run tests """ # The doctests are not run when called from an installed # package since the pytest.ini is not included in the # package. import os try: import pytest except ImportError: msg = "To run the tests, you must install pytest" raise ImportError(msg) path = os.path.realpath(__file__) if args is None: args = [path] else: args.append(path) return pytest.main(args=args, plugins=plugins) ## Instruction: Fix pytest path to root of package ## Code After: from ._version import get_versions __version__ = get_versions()['version'] del get_versions __all__ = ['__version__'] # We first need to detect if we're being called as part of the skmisc # setup procedure itself in a reliable manner. try: __SKMISC_SETUP__ except NameError: __SKMISC_SETUP__ = False if __SKMISC_SETUP__: import sys as _sys _sys.stderr.write('Running from skmisc source directory.\n') del _sys else: try: from skmisc.__config__ import show as show_config # noqa: F401 except ImportError as err: msg = """Error importing skmisc: you cannot import skmisc while being in skmisc source directory; please exit the skmisc source tree first, and relaunch your python intepreter.""" raise ImportError('\n\n'.join([err.message, msg])) __all__.append('show_config') def test(args=None, plugins=None): """ Run tests """ # The doctests are not run when called from an installed # package since the pytest.ini is not included in the # package. import os try: import pytest except ImportError: msg = "To run the tests, you must install pytest" raise ImportError(msg) path = os.path.dirname(os.path.realpath(__file__)) if args is None: args = [path] else: args.append(path) return pytest.main(args=args, plugins=plugins)
8187591a0f8255487f4b16b653ba5070bfffe739
specs/test_diff.py
specs/test_diff.py
''' This is an example of a python test that compares a diff function (in this case a hardcoded one that doesn't work) to the reference JSON to check compliance. ''' from nose.tools import eq_ import json def diff(before, after): return [] def test_diffs(): test_cases = json.load(open('test_cases.json')) for test_case in test_cases: result = diff(test_case['before'], test_case['after']) eq_(result, test_case['diff'])
''' This is an example of a python test that compares a diff function (in this case a hardcoded one that doesn't work) to the reference JSON to check compliance. ''' from nose.tools import eq_ import json def diff(before, after): return [] def test_diffs(): test_cases = json.load(open('test_cases_simple.json')) for test_case in test_cases: result = diff(test_case['before'], test_case['after']) eq_(result, test_case['diff']) def test_diffs_cells(): test_cases = json.load(open('test_cases_cells.json')) for test_case in test_cases: result = diff(test_case['before'], test_case['after']) eq_(result, test_case['diff'])
Add code to specs example test
Add code to specs example test
Python
mit
tarmstrong/nbdiff,tarmstrong/nbdiff,tarmstrong/nbdiff,tarmstrong/nbdiff
''' This is an example of a python test that compares a diff function (in this case a hardcoded one that doesn't work) to the reference JSON to check compliance. ''' from nose.tools import eq_ import json def diff(before, after): return [] + def test_diffs(): - test_cases = json.load(open('test_cases.json')) + test_cases = json.load(open('test_cases_simple.json')) for test_case in test_cases: result = diff(test_case['before'], test_case['after']) eq_(result, test_case['diff']) + + def test_diffs_cells(): + test_cases = json.load(open('test_cases_cells.json')) + for test_case in test_cases: + result = diff(test_case['before'], test_case['after']) + eq_(result, test_case['diff']) +
Add code to specs example test
## Code Before: ''' This is an example of a python test that compares a diff function (in this case a hardcoded one that doesn't work) to the reference JSON to check compliance. ''' from nose.tools import eq_ import json def diff(before, after): return [] def test_diffs(): test_cases = json.load(open('test_cases.json')) for test_case in test_cases: result = diff(test_case['before'], test_case['after']) eq_(result, test_case['diff']) ## Instruction: Add code to specs example test ## Code After: ''' This is an example of a python test that compares a diff function (in this case a hardcoded one that doesn't work) to the reference JSON to check compliance. ''' from nose.tools import eq_ import json def diff(before, after): return [] def test_diffs(): test_cases = json.load(open('test_cases_simple.json')) for test_case in test_cases: result = diff(test_case['before'], test_case['after']) eq_(result, test_case['diff']) def test_diffs_cells(): test_cases = json.load(open('test_cases_cells.json')) for test_case in test_cases: result = diff(test_case['before'], test_case['after']) eq_(result, test_case['diff'])
05151bb3ccd018b37097ddf5288e9984f5b45716
ci/management/commands/cancel_old_jobs.py
ci/management/commands/cancel_old_jobs.py
from __future__ import unicode_literals, absolute_import from django.core.management.base import BaseCommand from ci import models, views, TimeUtils from datetime import timedelta class Command(BaseCommand): help = 'Cancel old Civet jobs. When a specific civet client is no longer running, it can leave jobs lying around that other clients have to ignore.' def add_arguments(self, parser): parser.add_argument('--dryrun', default=False, action='store_true', help="Don't make any changes, just report what would have happened") parser.add_argument('--days', required=True, type=int, help="Cancel jobs older than this many days") def handle(self, *args, **options): dryrun = options["dryrun"] days = options["days"] d = TimeUtils.get_local_time() - timedelta(days=days) jobs = models.Job.objects.filter(active=True, ready=True, status=models.JobStatus.NOT_STARTED, created__lt=d) count = jobs.count() prefix = "" if dryrun: prefix = "DRY RUN: " for job in jobs.all(): self.stdout.write("%sCancel job %s: %s: %s" % (prefix, job.pk, job, job.created)) if not dryrun: views.set_job_canceled(job, "Civet client hasn't run this job in too long a time") job.event.set_complete_if_done() if count == 0: self.stdout.write("No jobs to cancel")
from __future__ import unicode_literals, absolute_import from django.core.management.base import BaseCommand from ci import models, views, TimeUtils from datetime import timedelta class Command(BaseCommand): help = 'Cancel old Civet jobs. When a specific civet client is no longer running, it can leave jobs lying around that other clients have to ignore.' def add_arguments(self, parser): parser.add_argument('--dryrun', default=False, action='store_true', help="Don't make any changes, just report what would have happened") parser.add_argument('--days', required=True, type=int, help="Cancel jobs older than this many days") def handle(self, *args, **options): dryrun = options["dryrun"] days = options["days"] d = TimeUtils.get_local_time() - timedelta(days=days) jobs = models.Job.objects.filter(active=True, ready=True, status=models.JobStatus.NOT_STARTED, created__lt=d) count = jobs.count() prefix = "" if dryrun: prefix = "DRY RUN: " for job in jobs.all(): self.stdout.write("%sCancel job %s: %s: %s" % (prefix, job.pk, job, job.created)) if not dryrun: views.set_job_canceled(job, "Canceled due to civet client not running this job in too long a time") job.event.set_complete_if_done() if count == 0: self.stdout.write("No jobs to cancel")
Update cancel old job message
Update cancel old job message
Python
apache-2.0
idaholab/civet,brianmoose/civet,idaholab/civet,brianmoose/civet,brianmoose/civet,idaholab/civet,idaholab/civet,brianmoose/civet
from __future__ import unicode_literals, absolute_import from django.core.management.base import BaseCommand from ci import models, views, TimeUtils from datetime import timedelta class Command(BaseCommand): help = 'Cancel old Civet jobs. When a specific civet client is no longer running, it can leave jobs lying around that other clients have to ignore.' def add_arguments(self, parser): parser.add_argument('--dryrun', default=False, action='store_true', help="Don't make any changes, just report what would have happened") parser.add_argument('--days', required=True, type=int, help="Cancel jobs older than this many days") def handle(self, *args, **options): dryrun = options["dryrun"] days = options["days"] d = TimeUtils.get_local_time() - timedelta(days=days) jobs = models.Job.objects.filter(active=True, ready=True, status=models.JobStatus.NOT_STARTED, created__lt=d) count = jobs.count() prefix = "" if dryrun: prefix = "DRY RUN: " for job in jobs.all(): self.stdout.write("%sCancel job %s: %s: %s" % (prefix, job.pk, job, job.created)) if not dryrun: - views.set_job_canceled(job, "Civet client hasn't run this job in too long a time") + views.set_job_canceled(job, "Canceled due to civet client not running this job in too long a time") job.event.set_complete_if_done() if count == 0: self.stdout.write("No jobs to cancel")
Update cancel old job message
## Code Before: from __future__ import unicode_literals, absolute_import from django.core.management.base import BaseCommand from ci import models, views, TimeUtils from datetime import timedelta class Command(BaseCommand): help = 'Cancel old Civet jobs. When a specific civet client is no longer running, it can leave jobs lying around that other clients have to ignore.' def add_arguments(self, parser): parser.add_argument('--dryrun', default=False, action='store_true', help="Don't make any changes, just report what would have happened") parser.add_argument('--days', required=True, type=int, help="Cancel jobs older than this many days") def handle(self, *args, **options): dryrun = options["dryrun"] days = options["days"] d = TimeUtils.get_local_time() - timedelta(days=days) jobs = models.Job.objects.filter(active=True, ready=True, status=models.JobStatus.NOT_STARTED, created__lt=d) count = jobs.count() prefix = "" if dryrun: prefix = "DRY RUN: " for job in jobs.all(): self.stdout.write("%sCancel job %s: %s: %s" % (prefix, job.pk, job, job.created)) if not dryrun: views.set_job_canceled(job, "Civet client hasn't run this job in too long a time") job.event.set_complete_if_done() if count == 0: self.stdout.write("No jobs to cancel") ## Instruction: Update cancel old job message ## Code After: from __future__ import unicode_literals, absolute_import from django.core.management.base import BaseCommand from ci import models, views, TimeUtils from datetime import timedelta class Command(BaseCommand): help = 'Cancel old Civet jobs. When a specific civet client is no longer running, it can leave jobs lying around that other clients have to ignore.' def add_arguments(self, parser): parser.add_argument('--dryrun', default=False, action='store_true', help="Don't make any changes, just report what would have happened") parser.add_argument('--days', required=True, type=int, help="Cancel jobs older than this many days") def handle(self, *args, **options): dryrun = options["dryrun"] days = options["days"] d = TimeUtils.get_local_time() - timedelta(days=days) jobs = models.Job.objects.filter(active=True, ready=True, status=models.JobStatus.NOT_STARTED, created__lt=d) count = jobs.count() prefix = "" if dryrun: prefix = "DRY RUN: " for job in jobs.all(): self.stdout.write("%sCancel job %s: %s: %s" % (prefix, job.pk, job, job.created)) if not dryrun: views.set_job_canceled(job, "Canceled due to civet client not running this job in too long a time") job.event.set_complete_if_done() if count == 0: self.stdout.write("No jobs to cancel")
aef51ce5ece86d054f76d86dafca9667f88d3b1a
ccui/testexecution/templatetags/results.py
ccui/testexecution/templatetags/results.py
from django import template from django.core.urlresolvers import reverse from ..models import TestCycle, TestRun, TestRunIncludedTestCase register = template.Library() @register.filter def results_detail_url(obj): if isinstance(obj, TestCycle): return reverse("results_testruns") + "?testCycle=%s" % obj.id elif isinstance(obj, TestRun): return reverse("results_testcases") + "?testRun=%s" % obj.id elif isinstance(obj, TestRunIncludedTestCase): return reverse("results_testcase_detail", kwargs={"itc_id": obj.id}) return ""
from django import template from django.core.urlresolvers import reverse from ..models import TestCycle, TestRun, TestRunIncludedTestCase register = template.Library() @register.filter def results_detail_url(obj): if isinstance(obj, TestCycle): return reverse("results_testruns") + "?filter-testCycle=%s" % obj.id elif isinstance(obj, TestRun): return reverse("results_testcases") + "?filter-testRun=%s" % obj.id elif isinstance(obj, TestRunIncludedTestCase): return reverse("results_testcase_detail", kwargs={"itc_id": obj.id}) return ""
Fix result status chiclet links for new-style filter querystrings.
Fix result status chiclet links for new-style filter querystrings.
Python
bsd-2-clause
shinglyu/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,mccarrmb/moztrap,mozilla/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,mozilla/moztrap,bobsilverberg/moztrap,mozilla/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mozilla/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mozilla/moztrap
from django import template from django.core.urlresolvers import reverse from ..models import TestCycle, TestRun, TestRunIncludedTestCase register = template.Library() @register.filter def results_detail_url(obj): if isinstance(obj, TestCycle): - return reverse("results_testruns") + "?testCycle=%s" % obj.id + return reverse("results_testruns") + "?filter-testCycle=%s" % obj.id elif isinstance(obj, TestRun): - return reverse("results_testcases") + "?testRun=%s" % obj.id + return reverse("results_testcases") + "?filter-testRun=%s" % obj.id elif isinstance(obj, TestRunIncludedTestCase): return reverse("results_testcase_detail", kwargs={"itc_id": obj.id}) return ""
Fix result status chiclet links for new-style filter querystrings.
## Code Before: from django import template from django.core.urlresolvers import reverse from ..models import TestCycle, TestRun, TestRunIncludedTestCase register = template.Library() @register.filter def results_detail_url(obj): if isinstance(obj, TestCycle): return reverse("results_testruns") + "?testCycle=%s" % obj.id elif isinstance(obj, TestRun): return reverse("results_testcases") + "?testRun=%s" % obj.id elif isinstance(obj, TestRunIncludedTestCase): return reverse("results_testcase_detail", kwargs={"itc_id": obj.id}) return "" ## Instruction: Fix result status chiclet links for new-style filter querystrings. ## Code After: from django import template from django.core.urlresolvers import reverse from ..models import TestCycle, TestRun, TestRunIncludedTestCase register = template.Library() @register.filter def results_detail_url(obj): if isinstance(obj, TestCycle): return reverse("results_testruns") + "?filter-testCycle=%s" % obj.id elif isinstance(obj, TestRun): return reverse("results_testcases") + "?filter-testRun=%s" % obj.id elif isinstance(obj, TestRunIncludedTestCase): return reverse("results_testcase_detail", kwargs={"itc_id": obj.id}) return ""
17ddcb1b6c293197834b3154830b9521769d76fb
linter.py
linter.py
"""This module exports the Hlint plugin class.""" from SublimeLinter.lint import Linter class Hlint(Linter): """Provides an interface to hlint.""" syntax = ('haskell', 'haskell-sublimehaskell', 'literate haskell') cmd = 'hlint' regex = ( r'^.+:(?P<line>\d+):' '(?P<col>\d+):\s*' '(?:(?P<error>Error)|(?P<warning>Warning)):\s*' '(?P<message>.+)$' ) multiline = True tempfile_suffix = { 'haskell': 'hs', 'haskell-sublimehaskell': 'hs', 'literate haskell': 'lhs' }
"""This module exports the Hlint plugin class.""" from SublimeLinter.lint import Linter class Hlint(Linter): """Provides an interface to hlint.""" defaults = { 'selector': 'source.haskell' } cmd = 'hlint' regex = ( r'^.+:(?P<line>\d+):' '(?P<col>\d+):\s*' '(?:(?P<error>Error)|(?P<warning>Warning)):\s*' '(?P<message>.+)$' ) multiline = True tempfile_suffix = 'hs'
Update to new `defaults` configuration
Update to new `defaults` configuration
Python
mit
SublimeLinter/SublimeLinter-hlint
"""This module exports the Hlint plugin class.""" from SublimeLinter.lint import Linter class Hlint(Linter): """Provides an interface to hlint.""" - syntax = ('haskell', 'haskell-sublimehaskell', 'literate haskell') + defaults = { + 'selector': 'source.haskell' + } cmd = 'hlint' regex = ( r'^.+:(?P<line>\d+):' '(?P<col>\d+):\s*' '(?:(?P<error>Error)|(?P<warning>Warning)):\s*' '(?P<message>.+)$' ) multiline = True - tempfile_suffix = { + tempfile_suffix = 'hs' - 'haskell': 'hs', - 'haskell-sublimehaskell': 'hs', - 'literate haskell': 'lhs' - }
Update to new `defaults` configuration
## Code Before: """This module exports the Hlint plugin class.""" from SublimeLinter.lint import Linter class Hlint(Linter): """Provides an interface to hlint.""" syntax = ('haskell', 'haskell-sublimehaskell', 'literate haskell') cmd = 'hlint' regex = ( r'^.+:(?P<line>\d+):' '(?P<col>\d+):\s*' '(?:(?P<error>Error)|(?P<warning>Warning)):\s*' '(?P<message>.+)$' ) multiline = True tempfile_suffix = { 'haskell': 'hs', 'haskell-sublimehaskell': 'hs', 'literate haskell': 'lhs' } ## Instruction: Update to new `defaults` configuration ## Code After: """This module exports the Hlint plugin class.""" from SublimeLinter.lint import Linter class Hlint(Linter): """Provides an interface to hlint.""" defaults = { 'selector': 'source.haskell' } cmd = 'hlint' regex = ( r'^.+:(?P<line>\d+):' '(?P<col>\d+):\s*' '(?:(?P<error>Error)|(?P<warning>Warning)):\s*' '(?P<message>.+)$' ) multiline = True tempfile_suffix = 'hs'
2bab1888b43a9c232b37cc26c37df992ea5df2c5
project/apps/api/signals.py
project/apps/api/signals.py
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from .models import ( Performance, Session, ) @receiver(post_save, sender=Performance) def performance_post_save(sender, instance=None, created=False, raw=False, **kwargs): """Create sentinels.""" if not raw: if created: s = 1 while s <= instance.round.num_songs: song = instance.songs.create( performance=instance, num=s, ) s += 1 judges = instance.round.session.judges.filter( category__in=[ instance.round.session.judges.model.CATEGORY.music, instance.round.session.judges.model.CATEGORY.presentation, instance.round.session.judges.model.CATEGORY.singing, ] ) for judge in judges: judge.scores.create( judge=judge, song=song, category=judge.category, kind=judge.kind, ) @receiver(post_save, sender=Session) def session_post_save(sender, instance=None, created=False, raw=False, **kwargs): """Create sentinels.""" if not raw: if created: i = 1 while i <= instance.num_rounds: instance.rounds.create( num=i, kind=(instance.num_rounds - i) + 1, ) i += 1
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from .models import ( Performance, Session, ) @receiver(post_save, sender=Session) def session_post_save(sender, instance=None, created=False, raw=False, **kwargs): """Create sentinels.""" if not raw: if created: i = 1 while i <= instance.num_rounds: instance.rounds.create( num=i, kind=(instance.num_rounds - i) + 1, ) i += 1 @receiver(post_save, sender=Performance) def performance_post_save(sender, instance=None, created=False, raw=False, **kwargs): """Create sentinels.""" if not raw: if created: s = 1 while s <= instance.round.num_songs: song = instance.songs.create( performance=instance, num=s, ) s += 1 judges = instance.round.session.judges.filter( category__in=[ instance.round.session.judges.model.CATEGORY.music, instance.round.session.judges.model.CATEGORY.presentation, instance.round.session.judges.model.CATEGORY.singing, ] ) for judge in judges: judge.scores.create( judge=judge, song=song, category=judge.category, kind=judge.kind, )
Create sentinel rounds on Session creation
Create sentinel rounds on Session creation
Python
bsd-2-clause
barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from .models import ( Performance, Session, ) + + + @receiver(post_save, sender=Session) + def session_post_save(sender, instance=None, created=False, raw=False, **kwargs): + """Create sentinels.""" + if not raw: + if created: + i = 1 + while i <= instance.num_rounds: + instance.rounds.create( + num=i, + kind=(instance.num_rounds - i) + 1, + ) + i += 1 @receiver(post_save, sender=Performance) def performance_post_save(sender, instance=None, created=False, raw=False, **kwargs): """Create sentinels.""" if not raw: if created: s = 1 while s <= instance.round.num_songs: song = instance.songs.create( performance=instance, num=s, ) s += 1 judges = instance.round.session.judges.filter( category__in=[ instance.round.session.judges.model.CATEGORY.music, instance.round.session.judges.model.CATEGORY.presentation, instance.round.session.judges.model.CATEGORY.singing, ] ) for judge in judges: judge.scores.create( judge=judge, song=song, category=judge.category, kind=judge.kind, ) - - @receiver(post_save, sender=Session) - def session_post_save(sender, instance=None, created=False, raw=False, **kwargs): - """Create sentinels.""" - if not raw: - if created: - i = 1 - while i <= instance.num_rounds: - instance.rounds.create( - num=i, - kind=(instance.num_rounds - i) + 1, - ) - i += 1 -
Create sentinel rounds on Session creation
## Code Before: from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from .models import ( Performance, Session, ) @receiver(post_save, sender=Performance) def performance_post_save(sender, instance=None, created=False, raw=False, **kwargs): """Create sentinels.""" if not raw: if created: s = 1 while s <= instance.round.num_songs: song = instance.songs.create( performance=instance, num=s, ) s += 1 judges = instance.round.session.judges.filter( category__in=[ instance.round.session.judges.model.CATEGORY.music, instance.round.session.judges.model.CATEGORY.presentation, instance.round.session.judges.model.CATEGORY.singing, ] ) for judge in judges: judge.scores.create( judge=judge, song=song, category=judge.category, kind=judge.kind, ) @receiver(post_save, sender=Session) def session_post_save(sender, instance=None, created=False, raw=False, **kwargs): """Create sentinels.""" if not raw: if created: i = 1 while i <= instance.num_rounds: instance.rounds.create( num=i, kind=(instance.num_rounds - i) + 1, ) i += 1 ## Instruction: Create sentinel rounds on Session creation ## Code After: from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from .models import ( Performance, Session, ) @receiver(post_save, sender=Session) def session_post_save(sender, instance=None, created=False, raw=False, **kwargs): """Create sentinels.""" if not raw: if created: i = 1 while i <= instance.num_rounds: instance.rounds.create( num=i, kind=(instance.num_rounds - i) + 1, ) i += 1 @receiver(post_save, sender=Performance) def performance_post_save(sender, instance=None, created=False, raw=False, **kwargs): """Create sentinels.""" if not raw: if created: s = 1 while s <= instance.round.num_songs: song = instance.songs.create( performance=instance, num=s, ) s += 1 judges = instance.round.session.judges.filter( category__in=[ instance.round.session.judges.model.CATEGORY.music, instance.round.session.judges.model.CATEGORY.presentation, instance.round.session.judges.model.CATEGORY.singing, ] ) for judge in judges: judge.scores.create( judge=judge, song=song, category=judge.category, kind=judge.kind, )
375b26fbb6e5ba043a1017e28027241c12374207
napalm_logs/transport/zeromq.py
napalm_logs/transport/zeromq.py
''' ZeroMQ transport for napalm-logs. ''' from __future__ import absolute_import from __future__ import unicode_literals # Import stdlib import json # Import third party libs import zmq # Import napalm-logs pkgs from napalm_logs.transport.base import TransportBase class ZMQTransport(TransportBase): ''' ZMQ transport class. ''' def __init__(self, addr, port): self.addr = addr self.port = port def start(self): self.context = zmq.Context() self.socket = self.context.socket(zmq.PUB) self.socket.bind('tcp://{addr}:{port}'.format( addr=self.addr, port=self.port) ) def serialise(self, obj): return json.dumps(obj) def publish(self, obj): self.socket.send( self.serialise(obj) ) def tear_down(self): if hasattr(self, 'socket'): self.socket.close() if hasattr(self, 'context'): self.context.term()
''' ZeroMQ transport for napalm-logs. ''' from __future__ import absolute_import from __future__ import unicode_literals # Import stdlib import json import logging # Import third party libs import zmq # Import napalm-logs pkgs from napalm_logs.exceptions import BindException from napalm_logs.transport.base import TransportBase log = logging.getLogger(__name__) class ZMQTransport(TransportBase): ''' ZMQ transport class. ''' def __init__(self, addr, port): self.addr = addr self.port = port def start(self): self.context = zmq.Context() self.socket = self.context.socket(zmq.PUB) try: self.socket.bind('tcp://{addr}:{port}'.format( addr=self.addr, port=self.port) ) except zmq.error.ZMQError as err: log.error(err, exc_info=True) raise BindException(err) def serialise(self, obj): return json.dumps(obj) def publish(self, obj): self.socket.send( self.serialise(obj) ) def tear_down(self): if hasattr(self, 'socket'): self.socket.close() if hasattr(self, 'context'): self.context.term()
Raise bind exception and log
Raise bind exception and log
Python
apache-2.0
napalm-automation/napalm-logs,napalm-automation/napalm-logs
''' ZeroMQ transport for napalm-logs. ''' from __future__ import absolute_import from __future__ import unicode_literals # Import stdlib import json + import logging # Import third party libs import zmq # Import napalm-logs pkgs + from napalm_logs.exceptions import BindException from napalm_logs.transport.base import TransportBase + + log = logging.getLogger(__name__) class ZMQTransport(TransportBase): ''' ZMQ transport class. ''' def __init__(self, addr, port): self.addr = addr self.port = port def start(self): self.context = zmq.Context() self.socket = self.context.socket(zmq.PUB) + try: - self.socket.bind('tcp://{addr}:{port}'.format( + self.socket.bind('tcp://{addr}:{port}'.format( - addr=self.addr, + addr=self.addr, - port=self.port) + port=self.port) - ) + ) + except zmq.error.ZMQError as err: + log.error(err, exc_info=True) + raise BindException(err) def serialise(self, obj): return json.dumps(obj) def publish(self, obj): self.socket.send( self.serialise(obj) ) def tear_down(self): if hasattr(self, 'socket'): self.socket.close() if hasattr(self, 'context'): self.context.term()
Raise bind exception and log
## Code Before: ''' ZeroMQ transport for napalm-logs. ''' from __future__ import absolute_import from __future__ import unicode_literals # Import stdlib import json # Import third party libs import zmq # Import napalm-logs pkgs from napalm_logs.transport.base import TransportBase class ZMQTransport(TransportBase): ''' ZMQ transport class. ''' def __init__(self, addr, port): self.addr = addr self.port = port def start(self): self.context = zmq.Context() self.socket = self.context.socket(zmq.PUB) self.socket.bind('tcp://{addr}:{port}'.format( addr=self.addr, port=self.port) ) def serialise(self, obj): return json.dumps(obj) def publish(self, obj): self.socket.send( self.serialise(obj) ) def tear_down(self): if hasattr(self, 'socket'): self.socket.close() if hasattr(self, 'context'): self.context.term() ## Instruction: Raise bind exception and log ## Code After: ''' ZeroMQ transport for napalm-logs. ''' from __future__ import absolute_import from __future__ import unicode_literals # Import stdlib import json import logging # Import third party libs import zmq # Import napalm-logs pkgs from napalm_logs.exceptions import BindException from napalm_logs.transport.base import TransportBase log = logging.getLogger(__name__) class ZMQTransport(TransportBase): ''' ZMQ transport class. ''' def __init__(self, addr, port): self.addr = addr self.port = port def start(self): self.context = zmq.Context() self.socket = self.context.socket(zmq.PUB) try: self.socket.bind('tcp://{addr}:{port}'.format( addr=self.addr, port=self.port) ) except zmq.error.ZMQError as err: log.error(err, exc_info=True) raise BindException(err) def serialise(self, obj): return json.dumps(obj) def publish(self, obj): self.socket.send( self.serialise(obj) ) def tear_down(self): if hasattr(self, 'socket'): self.socket.close() if hasattr(self, 'context'): self.context.term()
0df35e81754f703d1a8164cf0ea5169a53355185
code/python/knub/thesis/word2vec_gaussian_lda_preprocessing.py
code/python/knub/thesis/word2vec_gaussian_lda_preprocessing.py
import argparse import logging import os from gensim.models import Word2Vec logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) if __name__ == "__main__": parser = argparse.ArgumentParser("Prepare model for Gaussian LDA") parser.add_argument("--topic_model", type=str) parser.add_argument("--embedding_model", type=str) args = parser.parse_args() word2vec = Word2Vec.load_word2vec_format(args.embedding_model, binary=True) embedding_name = os.path.basename(args.embedding_model) with open(args.topic_model + "." + embedding_name + ".gaussian-lda", "w") as output: with open(args.topic_model + ".restricted.alphabet", "r") as f: for line in f: word = line.split("#")[0] output.write(word + " ") output.write(" ".join(word2vec[word])) output.write("\n")
import argparse from codecs import open import logging import os from gensim.models import Word2Vec logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) if __name__ == "__main__": parser = argparse.ArgumentParser("Prepare model for Gaussian LDA") parser.add_argument("--topic-model", type=str) parser.add_argument("--embedding-model", type=str) args = parser.parse_args() word2vec = Word2Vec.load_word2vec_format(args.embedding_model, binary=True) embedding_name = os.path.basename(args.embedding_model) with open(args.topic_model + "." + embedding_name + ".gaussian-lda", "w", encoding="utf-8") as output: with open(args.topic_model + "." + embedding_name + ".restricted.alphabet", "r", encoding="utf-8") as f: for line in f: word = line.split("#")[0] output.write(word + " ") output.write(" ".join(map(str, word2vec[word]))) output.write("\n")
Fix parameter parsing in gaussian lda preprocessing.
Fix parameter parsing in gaussian lda preprocessing.
Python
apache-2.0
knub/master-thesis,knub/master-thesis,knub/master-thesis,knub/master-thesis
import argparse + from codecs import open import logging import os from gensim.models import Word2Vec logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) if __name__ == "__main__": parser = argparse.ArgumentParser("Prepare model for Gaussian LDA") - parser.add_argument("--topic_model", type=str) + parser.add_argument("--topic-model", type=str) - parser.add_argument("--embedding_model", type=str) + parser.add_argument("--embedding-model", type=str) args = parser.parse_args() word2vec = Word2Vec.load_word2vec_format(args.embedding_model, binary=True) embedding_name = os.path.basename(args.embedding_model) - with open(args.topic_model + "." + embedding_name + ".gaussian-lda", "w") as output: + with open(args.topic_model + "." + embedding_name + ".gaussian-lda", "w", encoding="utf-8") as output: - with open(args.topic_model + ".restricted.alphabet", "r") as f: + with open(args.topic_model + "." + embedding_name + ".restricted.alphabet", "r", encoding="utf-8") as f: for line in f: word = line.split("#")[0] output.write(word + " ") - output.write(" ".join(word2vec[word])) + output.write(" ".join(map(str, word2vec[word]))) output.write("\n")
Fix parameter parsing in gaussian lda preprocessing.
## Code Before: import argparse import logging import os from gensim.models import Word2Vec logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) if __name__ == "__main__": parser = argparse.ArgumentParser("Prepare model for Gaussian LDA") parser.add_argument("--topic_model", type=str) parser.add_argument("--embedding_model", type=str) args = parser.parse_args() word2vec = Word2Vec.load_word2vec_format(args.embedding_model, binary=True) embedding_name = os.path.basename(args.embedding_model) with open(args.topic_model + "." + embedding_name + ".gaussian-lda", "w") as output: with open(args.topic_model + ".restricted.alphabet", "r") as f: for line in f: word = line.split("#")[0] output.write(word + " ") output.write(" ".join(word2vec[word])) output.write("\n") ## Instruction: Fix parameter parsing in gaussian lda preprocessing. ## Code After: import argparse from codecs import open import logging import os from gensim.models import Word2Vec logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) if __name__ == "__main__": parser = argparse.ArgumentParser("Prepare model for Gaussian LDA") parser.add_argument("--topic-model", type=str) parser.add_argument("--embedding-model", type=str) args = parser.parse_args() word2vec = Word2Vec.load_word2vec_format(args.embedding_model, binary=True) embedding_name = os.path.basename(args.embedding_model) with open(args.topic_model + "." + embedding_name + ".gaussian-lda", "w", encoding="utf-8") as output: with open(args.topic_model + "." + embedding_name + ".restricted.alphabet", "r", encoding="utf-8") as f: for line in f: word = line.split("#")[0] output.write(word + " ") output.write(" ".join(map(str, word2vec[word]))) output.write("\n")
ce0be23f554eb9949a3769da1e4a3d3d51b546f1
src/server/datab.py
src/server/datab.py
''' Database module. Get the database, convert it to the built-in data structure and hold a link to it. The module should be initialized before any other modules except mailer and log. Design: Heranort ''' ''' Connect to the database. ''' def connect_to_datab(): pass ''' Get raw data of the database. ''' def datab_get_raw_data(): pass ''' Process the raw data. ''' def datab_process_data(): pass ''' Preserve the processed data into somewhere. ''' def datab_preserve_data(): pass ''' Check wether the history is modified. If so, emit warning. ''' def check_health(): pass
''' Database module. Get the database, convert it to the built-in data structure and hold a link to it. The module should be initialized before any other modules except mailer and log. Design: Heranort ''' import sqlite3, os ''' Connect to the database. ''' def connect_to_datab(): path = os.getcwd() pparent_path = os.path.dirname(os.path.dirname(path)) #get the root dir # print(pparent_path) sql = sqlite3.connect(pparent_path + '\data\data.db') return sql ''' Get raw data of the database. ''' def datab_get_raw_data(sql): cur = sql.cursor() cur.execute('select * from flight') #fetch the raw data of flight raw_data_flight = cur.fetchall() cur.execute('select * from train') #fetch the raw data of train raw_data_train = cur.fetchall() cur.execute('select * from highway') #fetch the raw data of highway raw_data_bus = cur.fetchall() return (raw_data_flight, raw_data_train, raw_data_bus) ''' Process the raw data. ''' def datab_process_data(raw_data_flight, raw_data_train, raw_data_bus): data_price = [[-1 for i in range(10)] for i in range(10)] data_instance = [[-1 for i in range(10)] for i in range(10)] data_time = [[-1 for i in range(10)] for i in range(10)] for element in raw_data_bus: pass ''' Preserve the processed data into somewhere. ''' def datab_preserve_data(): pass ''' Check wether the history is modified. If so, emit warning. ''' def check_health(): pass if(__name__ == '__main__'): sql = connect_to_datab() (raw_data_flight, raw_data_train, raw_data_bus) = datab_get_raw_data(sql) datab_process_data(raw_data_flight, raw_data_train, raw_data_bus)
Add function of data connection
Add function of data connection
Python
mit
niwtr/map-walker
''' Database module. Get the database, convert it to the built-in data structure and hold a link to it. The module should be initialized before any other modules except mailer and log. Design: Heranort ''' + import sqlite3, os + + ''' Connect to the database. ''' def connect_to_datab(): - pass + path = os.getcwd() + pparent_path = os.path.dirname(os.path.dirname(path)) #get the root dir + # print(pparent_path) + sql = sqlite3.connect(pparent_path + '\data\data.db') + return sql ''' Get raw data of the database. ''' - def datab_get_raw_data(): + def datab_get_raw_data(sql): - pass + cur = sql.cursor() + cur.execute('select * from flight') #fetch the raw data of flight + raw_data_flight = cur.fetchall() + cur.execute('select * from train') #fetch the raw data of train + raw_data_train = cur.fetchall() + cur.execute('select * from highway') #fetch the raw data of highway + raw_data_bus = cur.fetchall() + return (raw_data_flight, raw_data_train, raw_data_bus) + ''' Process the raw data. ''' - def datab_process_data(): + def datab_process_data(raw_data_flight, raw_data_train, raw_data_bus): + data_price = [[-1 for i in range(10)] for i in range(10)] + data_instance = [[-1 for i in range(10)] for i in range(10)] + data_time = [[-1 for i in range(10)] for i in range(10)] + for element in raw_data_bus: - pass + pass ''' Preserve the processed data into somewhere. ''' def datab_preserve_data(): pass ''' Check wether the history is modified. If so, emit warning. ''' def check_health(): pass + if(__name__ == '__main__'): + sql = connect_to_datab() + (raw_data_flight, raw_data_train, raw_data_bus) = datab_get_raw_data(sql) + datab_process_data(raw_data_flight, raw_data_train, raw_data_bus)
Add function of data connection
## Code Before: ''' Database module. Get the database, convert it to the built-in data structure and hold a link to it. The module should be initialized before any other modules except mailer and log. Design: Heranort ''' ''' Connect to the database. ''' def connect_to_datab(): pass ''' Get raw data of the database. ''' def datab_get_raw_data(): pass ''' Process the raw data. ''' def datab_process_data(): pass ''' Preserve the processed data into somewhere. ''' def datab_preserve_data(): pass ''' Check wether the history is modified. If so, emit warning. ''' def check_health(): pass ## Instruction: Add function of data connection ## Code After: ''' Database module. Get the database, convert it to the built-in data structure and hold a link to it. The module should be initialized before any other modules except mailer and log. Design: Heranort ''' import sqlite3, os ''' Connect to the database. ''' def connect_to_datab(): path = os.getcwd() pparent_path = os.path.dirname(os.path.dirname(path)) #get the root dir # print(pparent_path) sql = sqlite3.connect(pparent_path + '\data\data.db') return sql ''' Get raw data of the database. ''' def datab_get_raw_data(sql): cur = sql.cursor() cur.execute('select * from flight') #fetch the raw data of flight raw_data_flight = cur.fetchall() cur.execute('select * from train') #fetch the raw data of train raw_data_train = cur.fetchall() cur.execute('select * from highway') #fetch the raw data of highway raw_data_bus = cur.fetchall() return (raw_data_flight, raw_data_train, raw_data_bus) ''' Process the raw data. ''' def datab_process_data(raw_data_flight, raw_data_train, raw_data_bus): data_price = [[-1 for i in range(10)] for i in range(10)] data_instance = [[-1 for i in range(10)] for i in range(10)] data_time = [[-1 for i in range(10)] for i in range(10)] for element in raw_data_bus: pass ''' Preserve the processed data into somewhere. ''' def datab_preserve_data(): pass ''' Check wether the history is modified. If so, emit warning. ''' def check_health(): pass if(__name__ == '__main__'): sql = connect_to_datab() (raw_data_flight, raw_data_train, raw_data_bus) = datab_get_raw_data(sql) datab_process_data(raw_data_flight, raw_data_train, raw_data_bus)
5d3d47e0fae9ddb9f445972e5186429163aabf40
statirator/core/management/commands/init.py
statirator/core/management/commands/init.py
import os from optparse import make_option from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Init the static site project" args = '[directory]' option_list = ( make_option( '--title', '-t', dest='title', default='Default site', help='Site title [Default: "%defaults"]'), make_option( '--domain', '-d', dest='domain', default='example.com', help='Domain name [Default: "%default"]'), make_option( '--languages', '-l', dest='languages', default=['he', 'en'], action='append', help='Supported languages. [Default: "%default"]') ) + BaseCommand.option_list def handle(self, directory, **options): from django.conf.global_settings import LANGUAGES extra = { 'build': 'build', 'default_lang': options['languages'][0], 'languages': [l for l in LANGUAGES if l[0] in options["languages"]], 'extensions': ('py', ), 'files': (), 'template': os.path.abspath( os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, 'project_template')), } extra.update(options) from django.core.management import call_command call_command('startproject', 'conf', directory, **extra)
import os import logging from django.core.management.base import BaseCommand from optparse import make_option class Command(BaseCommand): help = "Init the static site project" args = '[directory]' option_list = ( make_option( '--title', '-t', dest='title', default='Default site', help='Site title [Default: "%defaults"]'), make_option( '--domain', '-d', dest='domain', default='example.com', help='Domain name [Default: "%default"]'), make_option( '--languages', '-l', dest='languages', default=['he', 'en'], action='append', help='Supported languages. [Default: "%default"]') ) + BaseCommand.option_list def handle(self, directory, **options): logging.info("Initializing project structure in %s", directory) os.makedirs(directory) from django.conf.global_settings import LANGUAGES extra = { 'build': 'build', 'default_lang': options['languages'][0], 'languages': [l for l in LANGUAGES if l[0] in options["languages"]], 'extensions': ('py', ), 'files': (), 'template': os.path.abspath( os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, 'project_template')), } extra.update(options) from django.core.management import call_command call_command('startproject', 'conf', directory, **extra)
Create the directory before calling the startprojcet command
Create the directory before calling the startprojcet command
Python
mit
MeirKriheli/statirator,MeirKriheli/statirator,MeirKriheli/statirator
import os + import logging + from django.core.management.base import BaseCommand from optparse import make_option - from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Init the static site project" args = '[directory]' option_list = ( make_option( '--title', '-t', dest='title', default='Default site', help='Site title [Default: "%defaults"]'), make_option( '--domain', '-d', dest='domain', default='example.com', help='Domain name [Default: "%default"]'), make_option( '--languages', '-l', dest='languages', default=['he', 'en'], action='append', help='Supported languages. [Default: "%default"]') ) + BaseCommand.option_list def handle(self, directory, **options): + logging.info("Initializing project structure in %s", directory) + os.makedirs(directory) + from django.conf.global_settings import LANGUAGES extra = { 'build': 'build', 'default_lang': options['languages'][0], 'languages': [l for l in LANGUAGES if l[0] in options["languages"]], 'extensions': ('py', ), 'files': (), 'template': os.path.abspath( os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, 'project_template')), } extra.update(options) from django.core.management import call_command call_command('startproject', 'conf', directory, **extra)
Create the directory before calling the startprojcet command
## Code Before: import os from optparse import make_option from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Init the static site project" args = '[directory]' option_list = ( make_option( '--title', '-t', dest='title', default='Default site', help='Site title [Default: "%defaults"]'), make_option( '--domain', '-d', dest='domain', default='example.com', help='Domain name [Default: "%default"]'), make_option( '--languages', '-l', dest='languages', default=['he', 'en'], action='append', help='Supported languages. [Default: "%default"]') ) + BaseCommand.option_list def handle(self, directory, **options): from django.conf.global_settings import LANGUAGES extra = { 'build': 'build', 'default_lang': options['languages'][0], 'languages': [l for l in LANGUAGES if l[0] in options["languages"]], 'extensions': ('py', ), 'files': (), 'template': os.path.abspath( os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, 'project_template')), } extra.update(options) from django.core.management import call_command call_command('startproject', 'conf', directory, **extra) ## Instruction: Create the directory before calling the startprojcet command ## Code After: import os import logging from django.core.management.base import BaseCommand from optparse import make_option class Command(BaseCommand): help = "Init the static site project" args = '[directory]' option_list = ( make_option( '--title', '-t', dest='title', default='Default site', help='Site title [Default: "%defaults"]'), make_option( '--domain', '-d', dest='domain', default='example.com', help='Domain name [Default: "%default"]'), make_option( '--languages', '-l', dest='languages', default=['he', 'en'], action='append', help='Supported languages. [Default: "%default"]') ) + BaseCommand.option_list def handle(self, directory, **options): logging.info("Initializing project structure in %s", directory) os.makedirs(directory) from django.conf.global_settings import LANGUAGES extra = { 'build': 'build', 'default_lang': options['languages'][0], 'languages': [l for l in LANGUAGES if l[0] in options["languages"]], 'extensions': ('py', ), 'files': (), 'template': os.path.abspath( os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, 'project_template')), } extra.update(options) from django.core.management import call_command call_command('startproject', 'conf', directory, **extra)
2d584531d043804f3dcf3acf132cb60b463e4c1a
azdweb/markdown_serv.py
azdweb/markdown_serv.py
import os from flask import request, render_template from azdweb import app from azdweb.util import gh_markdown root_path = os.path.abspath("markdown") # {filename: (mtime, contents)} cache = {} def load(filename): with open(filename) as file: return gh_markdown.markdown(file.read()) def load_cached(filename): mtime = os.path.getmtime(filename) if filename in cache: old_mtime, contents = cache[filename] if mtime != old_mtime: contents = load(filename) cache[filename] = (mtime, contents) else: contents = load(filename) cache[filename] = (mtime, contents) return contents @app.route("/md/<page>") def serve_markdown(page): filename = os.path.join(root_path, "{}.md".format(page)) if not os.path.exists(filename): return render_template("markdown-404.html", page=page) return render_template("markdown.html", page=page, content=load_cached(filename))
import codecs import os from flask import render_template from azdweb import app from azdweb.util import gh_markdown root_path = os.path.abspath("markdown") # {filename: (mtime, contents)} cache = {} def load(filename): with codecs.open(filename, encoding="utf-8") as file: return gh_markdown.markdown(file.read()) def load_cached(filename): mtime = os.path.getmtime(filename) if filename in cache: old_mtime, contents = cache[filename] if mtime != old_mtime: contents = load(filename) cache[filename] = (mtime, contents) else: contents = load(filename) cache[filename] = (mtime, contents) return contents @app.route("/md", defaults={"page": "index"}) @app.route("/md/<path:page>") def serve_markdown(page): if "." in page: return render_template("markdown-404.html", page=page) if page.endswith("/"): page += "index" filename = os.path.join(root_path, "{}.md".format(page)) if not os.path.exists(filename): return render_template("markdown-404.html", page=page) sidebar = os.path.join(os.path.dirname(filename), "sidebar.md") if os.path.exists(sidebar): sidebar_content = load_cached(sidebar) else: sidebar_content = "" return render_template("markdown.html", title=page, content=load_cached(filename), sidebar=sidebar_content) @app.route("/sw", defaults={"page": "index"}) @app.route("/sw/<path:page>") def skywars_alias(page): return serve_markdown("skywars/{}".format(page))
Add support for a sidebar, and also add a /sw/ alias for /md/skywars/
Add support for a sidebar, and also add a /sw/ alias for /md/skywars/
Python
apache-2.0
daboross/dabo.guru,daboross/dabo.guru,daboross/dabo.guru,daboross/dabo.guru
+ import codecs import os - from flask import request, render_template + from flask import render_template from azdweb import app from azdweb.util import gh_markdown root_path = os.path.abspath("markdown") # {filename: (mtime, contents)} cache = {} def load(filename): - with open(filename) as file: + with codecs.open(filename, encoding="utf-8") as file: return gh_markdown.markdown(file.read()) def load_cached(filename): mtime = os.path.getmtime(filename) if filename in cache: old_mtime, contents = cache[filename] if mtime != old_mtime: contents = load(filename) cache[filename] = (mtime, contents) else: contents = load(filename) cache[filename] = (mtime, contents) return contents + @app.route("/md", defaults={"page": "index"}) - @app.route("/md/<page>") + @app.route("/md/<path:page>") def serve_markdown(page): + if "." in page: + return render_template("markdown-404.html", page=page) + if page.endswith("/"): + page += "index" filename = os.path.join(root_path, "{}.md".format(page)) if not os.path.exists(filename): return render_template("markdown-404.html", page=page) + sidebar = os.path.join(os.path.dirname(filename), "sidebar.md") + if os.path.exists(sidebar): + sidebar_content = load_cached(sidebar) + else: + sidebar_content = "" - return render_template("markdown.html", page=page, content=load_cached(filename)) + return render_template("markdown.html", title=page, content=load_cached(filename), sidebar=sidebar_content) + + + @app.route("/sw", defaults={"page": "index"}) + @app.route("/sw/<path:page>") + def skywars_alias(page): + return serve_markdown("skywars/{}".format(page)) +
Add support for a sidebar, and also add a /sw/ alias for /md/skywars/
## Code Before: import os from flask import request, render_template from azdweb import app from azdweb.util import gh_markdown root_path = os.path.abspath("markdown") # {filename: (mtime, contents)} cache = {} def load(filename): with open(filename) as file: return gh_markdown.markdown(file.read()) def load_cached(filename): mtime = os.path.getmtime(filename) if filename in cache: old_mtime, contents = cache[filename] if mtime != old_mtime: contents = load(filename) cache[filename] = (mtime, contents) else: contents = load(filename) cache[filename] = (mtime, contents) return contents @app.route("/md/<page>") def serve_markdown(page): filename = os.path.join(root_path, "{}.md".format(page)) if not os.path.exists(filename): return render_template("markdown-404.html", page=page) return render_template("markdown.html", page=page, content=load_cached(filename)) ## Instruction: Add support for a sidebar, and also add a /sw/ alias for /md/skywars/ ## Code After: import codecs import os from flask import render_template from azdweb import app from azdweb.util import gh_markdown root_path = os.path.abspath("markdown") # {filename: (mtime, contents)} cache = {} def load(filename): with codecs.open(filename, encoding="utf-8") as file: return gh_markdown.markdown(file.read()) def load_cached(filename): mtime = os.path.getmtime(filename) if filename in cache: old_mtime, contents = cache[filename] if mtime != old_mtime: contents = load(filename) cache[filename] = (mtime, contents) else: contents = load(filename) cache[filename] = (mtime, contents) return contents @app.route("/md", defaults={"page": "index"}) @app.route("/md/<path:page>") def serve_markdown(page): if "." in page: return render_template("markdown-404.html", page=page) if page.endswith("/"): page += "index" filename = os.path.join(root_path, "{}.md".format(page)) if not os.path.exists(filename): return render_template("markdown-404.html", page=page) sidebar = os.path.join(os.path.dirname(filename), "sidebar.md") if os.path.exists(sidebar): sidebar_content = load_cached(sidebar) else: sidebar_content = "" return render_template("markdown.html", title=page, content=load_cached(filename), sidebar=sidebar_content) @app.route("/sw", defaults={"page": "index"}) @app.route("/sw/<path:page>") def skywars_alias(page): return serve_markdown("skywars/{}".format(page))
14fb663019038b80d42f212e0ad8169cd0d37e84
neutron_lib/exceptions/address_group.py
neutron_lib/exceptions/address_group.py
from neutron_lib._i18n import _ from neutron_lib import exceptions class AddressGroupNotFound(exceptions.NotFound): message = _("Address group %(address_group_id)s could not be found.") class AddressesNotFound(exceptions.NotFound): message = _("Addresses %(addresses)s not found in the address group " "%(address_group_id)s.") class AddressesAlreadyExist(exceptions.BadRequest): message = _("Addresses %(addresses)s already exist in the " "address group %(address_group_id)s.")
from neutron_lib._i18n import _ from neutron_lib import exceptions class AddressGroupNotFound(exceptions.NotFound): message = _("Address group %(address_group_id)s could not be found.") class AddressGroupInUse(exceptions.InUse): message = _("Address group %(address_group_id)s is in use on one or more " "security group rules.") class AddressesNotFound(exceptions.NotFound): message = _("Addresses %(addresses)s not found in the address group " "%(address_group_id)s.") class AddressesAlreadyExist(exceptions.BadRequest): message = _("Addresses %(addresses)s already exist in the " "address group %(address_group_id)s.")
Add address group in use exception
Add address group in use exception Related change: https://review.opendev.org/#/c/751110/ Change-Id: I2a9872890ca4d5e59a9e266c1dcacd3488a3265c
Python
apache-2.0
openstack/neutron-lib,openstack/neutron-lib,openstack/neutron-lib,openstack/neutron-lib
from neutron_lib._i18n import _ from neutron_lib import exceptions class AddressGroupNotFound(exceptions.NotFound): message = _("Address group %(address_group_id)s could not be found.") + + + class AddressGroupInUse(exceptions.InUse): + message = _("Address group %(address_group_id)s is in use on one or more " + "security group rules.") class AddressesNotFound(exceptions.NotFound): message = _("Addresses %(addresses)s not found in the address group " "%(address_group_id)s.") class AddressesAlreadyExist(exceptions.BadRequest): message = _("Addresses %(addresses)s already exist in the " "address group %(address_group_id)s.")
Add address group in use exception
## Code Before: from neutron_lib._i18n import _ from neutron_lib import exceptions class AddressGroupNotFound(exceptions.NotFound): message = _("Address group %(address_group_id)s could not be found.") class AddressesNotFound(exceptions.NotFound): message = _("Addresses %(addresses)s not found in the address group " "%(address_group_id)s.") class AddressesAlreadyExist(exceptions.BadRequest): message = _("Addresses %(addresses)s already exist in the " "address group %(address_group_id)s.") ## Instruction: Add address group in use exception ## Code After: from neutron_lib._i18n import _ from neutron_lib import exceptions class AddressGroupNotFound(exceptions.NotFound): message = _("Address group %(address_group_id)s could not be found.") class AddressGroupInUse(exceptions.InUse): message = _("Address group %(address_group_id)s is in use on one or more " "security group rules.") class AddressesNotFound(exceptions.NotFound): message = _("Addresses %(addresses)s not found in the address group " "%(address_group_id)s.") class AddressesAlreadyExist(exceptions.BadRequest): message = _("Addresses %(addresses)s already exist in the " "address group %(address_group_id)s.")
14d51aa701dcc8d1d3f026af947c935abb0eabe3
examples/rune.py
examples/rune.py
import cassiopeia as cass from cassiopeia.core import Summoner def test_cass(): name = "Kalturi" runes = cass.get_runes() for rune in runes: if rune.tier == 3: print(rune.name) if __name__ == "__main__": test_cass()
import cassiopeia as cass def print_t3_runes(): for rune in cass.get_runes(): if rune.tier == 3: print(rune.name) if __name__ == "__main__": print_t3_runes()
Change function name, remove unneeded summoner name
Change function name, remove unneeded summoner name
Python
mit
robrua/cassiopeia,10se1ucgo/cassiopeia,meraki-analytics/cassiopeia
import cassiopeia as cass - from cassiopeia.core import Summoner - def test_cass(): - name = "Kalturi" + def print_t3_runes(): - runes = cass.get_runes() + for rune in cass.get_runes(): - for rune in runes: if rune.tier == 3: print(rune.name) if __name__ == "__main__": - test_cass() + print_t3_runes()
Change function name, remove unneeded summoner name
## Code Before: import cassiopeia as cass from cassiopeia.core import Summoner def test_cass(): name = "Kalturi" runes = cass.get_runes() for rune in runes: if rune.tier == 3: print(rune.name) if __name__ == "__main__": test_cass() ## Instruction: Change function name, remove unneeded summoner name ## Code After: import cassiopeia as cass def print_t3_runes(): for rune in cass.get_runes(): if rune.tier == 3: print(rune.name) if __name__ == "__main__": print_t3_runes()
d72df78e0dea27ae93bde52e43cec360a963b32c
openprescribing/frontend/management/commands/delete_measure.py
openprescribing/frontend/management/commands/delete_measure.py
from django.conf import settings from django.core.management import BaseCommand, CommandError from frontend.models import Measure class Command(BaseCommand): def handle(self, measure_id, **options): if not measure_id.startswith(settings.MEASURE_PREVIEW_PREFIX): raise CommandError( f"Not deleting '{measure_id}' because it doesn't look like a preview " f"measure (it doesn't start with '{settings.MEASURE_PREVIEW_PREFIX}')" ) try: measure = Measure.objects.get(id=measure_id) except Measure.DoesNotExist: raise CommandError(f"No measure with ID '{measure_id}'") # The ON DELETE CASCADE configuration ensures that all MeasureValues are deleted # as well measure.delete() self.stdout.write(f"Deleted measure '{measure_id}'") def add_arguments(self, parser): parser.add_argument("measure_id")
from django.conf import settings from django.core.management import BaseCommand, CommandError from frontend.models import Measure from gcutils.bigquery import Client class Command(BaseCommand): def handle(self, measure_id, **options): if not measure_id.startswith(settings.MEASURE_PREVIEW_PREFIX): raise CommandError( f"Not deleting '{measure_id}' because it doesn't look like a preview " f"measure (it doesn't start with '{settings.MEASURE_PREVIEW_PREFIX}')" ) try: measure = Measure.objects.get(id=measure_id) except Measure.DoesNotExist: raise CommandError(f"No measure with ID '{measure_id}'") delete_from_bigquery(measure_id) # The ON DELETE CASCADE configuration ensures that all MeasureValues are deleted # as well measure.delete() self.stdout.write(f"Deleted measure '{measure_id}'") def add_arguments(self, parser): parser.add_argument("measure_id") def delete_from_bigquery(measure_id): # Dataset name from `import_measures.MeasureCalculation.get_table()` client = Client("measures") # Table naming convention from `import_measures.MeasureCalculation.table_name()` table_suffix = f"_data_{measure_id}" tables_to_delete = [ table for table in client.list_tables() if table.table_id.endswith(table_suffix) ] for table in tables_to_delete: client.delete_table(table.table_id)
Delete measures from BigQuery as well
Delete measures from BigQuery as well
Python
mit
ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc
from django.conf import settings from django.core.management import BaseCommand, CommandError from frontend.models import Measure + from gcutils.bigquery import Client class Command(BaseCommand): def handle(self, measure_id, **options): if not measure_id.startswith(settings.MEASURE_PREVIEW_PREFIX): raise CommandError( f"Not deleting '{measure_id}' because it doesn't look like a preview " f"measure (it doesn't start with '{settings.MEASURE_PREVIEW_PREFIX}')" ) try: measure = Measure.objects.get(id=measure_id) except Measure.DoesNotExist: raise CommandError(f"No measure with ID '{measure_id}'") + delete_from_bigquery(measure_id) # The ON DELETE CASCADE configuration ensures that all MeasureValues are deleted # as well measure.delete() self.stdout.write(f"Deleted measure '{measure_id}'") def add_arguments(self, parser): parser.add_argument("measure_id") + + def delete_from_bigquery(measure_id): + # Dataset name from `import_measures.MeasureCalculation.get_table()` + client = Client("measures") + # Table naming convention from `import_measures.MeasureCalculation.table_name()` + table_suffix = f"_data_{measure_id}" + + tables_to_delete = [ + table for table in client.list_tables() if table.table_id.endswith(table_suffix) + ] + for table in tables_to_delete: + client.delete_table(table.table_id) +
Delete measures from BigQuery as well
## Code Before: from django.conf import settings from django.core.management import BaseCommand, CommandError from frontend.models import Measure class Command(BaseCommand): def handle(self, measure_id, **options): if not measure_id.startswith(settings.MEASURE_PREVIEW_PREFIX): raise CommandError( f"Not deleting '{measure_id}' because it doesn't look like a preview " f"measure (it doesn't start with '{settings.MEASURE_PREVIEW_PREFIX}')" ) try: measure = Measure.objects.get(id=measure_id) except Measure.DoesNotExist: raise CommandError(f"No measure with ID '{measure_id}'") # The ON DELETE CASCADE configuration ensures that all MeasureValues are deleted # as well measure.delete() self.stdout.write(f"Deleted measure '{measure_id}'") def add_arguments(self, parser): parser.add_argument("measure_id") ## Instruction: Delete measures from BigQuery as well ## Code After: from django.conf import settings from django.core.management import BaseCommand, CommandError from frontend.models import Measure from gcutils.bigquery import Client class Command(BaseCommand): def handle(self, measure_id, **options): if not measure_id.startswith(settings.MEASURE_PREVIEW_PREFIX): raise CommandError( f"Not deleting '{measure_id}' because it doesn't look like a preview " f"measure (it doesn't start with '{settings.MEASURE_PREVIEW_PREFIX}')" ) try: measure = Measure.objects.get(id=measure_id) except Measure.DoesNotExist: raise CommandError(f"No measure with ID '{measure_id}'") delete_from_bigquery(measure_id) # The ON DELETE CASCADE configuration ensures that all MeasureValues are deleted # as well measure.delete() self.stdout.write(f"Deleted measure '{measure_id}'") def add_arguments(self, parser): parser.add_argument("measure_id") def delete_from_bigquery(measure_id): # Dataset name from `import_measures.MeasureCalculation.get_table()` client = Client("measures") # Table naming convention from `import_measures.MeasureCalculation.table_name()` table_suffix = f"_data_{measure_id}" tables_to_delete = [ table for table in client.list_tables() if table.table_id.endswith(table_suffix) ] for table in tables_to_delete: client.delete_table(table.table_id)
fa191537e15dd0729deb94aaa91dbb7fa9295e04
mathdeck/loadproblem.py
mathdeck/loadproblem.py
import os import sys # Load problem file as def load_file_as_module(file): """ Load problem file as a module. :param file: The full path to the problem file returns a module represented by the problem file """ # Create a new module to hold the seed variable so # the loaded module can reference the seed variable if sys.version_info[0] == 2: import imp problem_module = imp.load_source('prob_module',file) if sys.version_info[0] == 3: import importlib.machinery problem_module = importlib.machinery \ .SourceFileLoader("prob_module",file) \ .load_module() try: problem_module.answers except AttributeError: raise AttributeError('Problem file has no \'answers\' attribute') return problem_module
import os import sys # Load problem file as def load_file_as_module(file_path): """ Load problem file as a module. :param file: The full path to the problem file returns a module represented by the problem file """ # Create a new module to hold the seed variable so # the loaded module can reference the seed variable if sys.version_info[0] == 2: import imp problem_module = imp.load_source('prob_mod_pkg',file_path) if sys.version_info[0] == 3: import importlib.machinery problem_module = importlib.machinery \ .SourceFileLoader('prob_mod_pkg',file_path) \ .load_module() try: problem_module.answers except AttributeError: raise AttributeError('Problem file has no \'answers\' attribute') return problem_module
Change package name in loadmodule call
Change package name in loadmodule call Not much reason to do this. It just happened.
Python
apache-2.0
patrickspencer/mathdeck,patrickspencer/mathdeck
import os import sys # Load problem file as - def load_file_as_module(file): + def load_file_as_module(file_path): """ Load problem file as a module. :param file: The full path to the problem file returns a module represented by the problem file """ # Create a new module to hold the seed variable so # the loaded module can reference the seed variable if sys.version_info[0] == 2: import imp - problem_module = imp.load_source('prob_module',file) + problem_module = imp.load_source('prob_mod_pkg',file_path) if sys.version_info[0] == 3: import importlib.machinery problem_module = importlib.machinery \ - .SourceFileLoader("prob_module",file) \ + .SourceFileLoader('prob_mod_pkg',file_path) \ .load_module() try: problem_module.answers except AttributeError: raise AttributeError('Problem file has no \'answers\' attribute') return problem_module
Change package name in loadmodule call
## Code Before: import os import sys # Load problem file as def load_file_as_module(file): """ Load problem file as a module. :param file: The full path to the problem file returns a module represented by the problem file """ # Create a new module to hold the seed variable so # the loaded module can reference the seed variable if sys.version_info[0] == 2: import imp problem_module = imp.load_source('prob_module',file) if sys.version_info[0] == 3: import importlib.machinery problem_module = importlib.machinery \ .SourceFileLoader("prob_module",file) \ .load_module() try: problem_module.answers except AttributeError: raise AttributeError('Problem file has no \'answers\' attribute') return problem_module ## Instruction: Change package name in loadmodule call ## Code After: import os import sys # Load problem file as def load_file_as_module(file_path): """ Load problem file as a module. :param file: The full path to the problem file returns a module represented by the problem file """ # Create a new module to hold the seed variable so # the loaded module can reference the seed variable if sys.version_info[0] == 2: import imp problem_module = imp.load_source('prob_mod_pkg',file_path) if sys.version_info[0] == 3: import importlib.machinery problem_module = importlib.machinery \ .SourceFileLoader('prob_mod_pkg',file_path) \ .load_module() try: problem_module.answers except AttributeError: raise AttributeError('Problem file has no \'answers\' attribute') return problem_module
6db8a9e779031ae97977a49e4edd11d42fb6389d
samples/04_markdown_parse/epub2markdown.py
samples/04_markdown_parse/epub2markdown.py
import sys import subprocess import os import os.path from ebooklib import epub # This is just a basic example which can easily break in real world. if __name__ == '__main__': # read epub book = epub.read_epub(sys.argv[1]) # get base filename from the epub base_name = os.path.basename(os.path.splitext(sys.argv[1])[0]) for item in book.items: # convert into markdown if this is html if isinstance(item, epub.EpubHtml): proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE ) content, error = proc.communicate(item.content) file_name = os.path.splitext(item.file_name)[0]+'.md' else: file_name = item.file_name content = item.content # create needed directories dir_name = '%s/%s' % (base_name, os.path.dirname(file_name)) if not os.path.exists(dir_name): os.makedirs(dir_name) print '>> ', file_name # write content to file f = open('%s/%s' % (base_name, file_name), 'w') f.write(content) f.close()
import os.path import subprocess import sys from ebooklib import epub # This is just a basic example which can easily break in real world. if __name__ == '__main__': # read epub book = epub.read_epub(sys.argv[1]) # get base filename from the epub base_name = os.path.basename(os.path.splitext(sys.argv[1])[0]) for item in book.items: # convert into markdown if this is html if isinstance(item, epub.EpubHtml): proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) content, error = proc.communicate(item.content) file_name = os.path.splitext(item.file_name)[0] + '.md' else: file_name = item.file_name content = item.content # create needed directories dir_name = '{0}/{1}'.format(base_name, os.path.dirname(file_name)) if not os.path.exists(dir_name): os.makedirs(dir_name) print('>> {0}'.format(file_name)) # write content to file with open('{0}/{1}'.format(base_name, file_name), 'w') as f: f.write(content)
Make `samples/04_markdown_parse` Python 2+3 compatible
Make `samples/04_markdown_parse` Python 2+3 compatible
Python
agpl-3.0
booktype/ebooklib,aerkalov/ebooklib
- + import os.path + import subprocess import sys - import subprocess - import os - import os.path from ebooklib import epub # This is just a basic example which can easily break in real world. if __name__ == '__main__': # read epub book = epub.read_epub(sys.argv[1]) # get base filename from the epub base_name = os.path.basename(os.path.splitext(sys.argv[1])[0]) for item in book.items: # convert into markdown if this is html if isinstance(item, epub.EpubHtml): proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'], stdin=subprocess.PIPE, - stdout=subprocess.PIPE + stdout=subprocess.PIPE) - ) content, error = proc.communicate(item.content) - file_name = os.path.splitext(item.file_name)[0]+'.md' + file_name = os.path.splitext(item.file_name)[0] + '.md' else: file_name = item.file_name content = item.content # create needed directories - dir_name = '%s/%s' % (base_name, os.path.dirname(file_name)) + dir_name = '{0}/{1}'.format(base_name, os.path.dirname(file_name)) if not os.path.exists(dir_name): os.makedirs(dir_name) - print '>> ', file_name + print('>> {0}'.format(file_name)) # write content to file - f = open('%s/%s' % (base_name, file_name), 'w') + with open('{0}/{1}'.format(base_name, file_name), 'w') as f: - f.write(content) + f.write(content) - f.close() -
Make `samples/04_markdown_parse` Python 2+3 compatible
## Code Before: import sys import subprocess import os import os.path from ebooklib import epub # This is just a basic example which can easily break in real world. if __name__ == '__main__': # read epub book = epub.read_epub(sys.argv[1]) # get base filename from the epub base_name = os.path.basename(os.path.splitext(sys.argv[1])[0]) for item in book.items: # convert into markdown if this is html if isinstance(item, epub.EpubHtml): proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE ) content, error = proc.communicate(item.content) file_name = os.path.splitext(item.file_name)[0]+'.md' else: file_name = item.file_name content = item.content # create needed directories dir_name = '%s/%s' % (base_name, os.path.dirname(file_name)) if not os.path.exists(dir_name): os.makedirs(dir_name) print '>> ', file_name # write content to file f = open('%s/%s' % (base_name, file_name), 'w') f.write(content) f.close() ## Instruction: Make `samples/04_markdown_parse` Python 2+3 compatible ## Code After: import os.path import subprocess import sys from ebooklib import epub # This is just a basic example which can easily break in real world. if __name__ == '__main__': # read epub book = epub.read_epub(sys.argv[1]) # get base filename from the epub base_name = os.path.basename(os.path.splitext(sys.argv[1])[0]) for item in book.items: # convert into markdown if this is html if isinstance(item, epub.EpubHtml): proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) content, error = proc.communicate(item.content) file_name = os.path.splitext(item.file_name)[0] + '.md' else: file_name = item.file_name content = item.content # create needed directories dir_name = '{0}/{1}'.format(base_name, os.path.dirname(file_name)) if not os.path.exists(dir_name): os.makedirs(dir_name) print('>> {0}'.format(file_name)) # write content to file with open('{0}/{1}'.format(base_name, file_name), 'w') as f: f.write(content)
82696dd76351f8d0bb4fcfe9f173ada652947acc
whacked4/whacked4/ui/dialogs/errordialog.py
whacked4/whacked4/ui/dialogs/errordialog.py
from whacked4.ui import windows import wx class ErrorDialog(windows.ErrorDialogBase): def __init__(self, parent): windows.ErrorDialogBase.__init__(self, parent) wx.EndBusyCursor() def set_log(self, log_file): """ Shows the log file's contents in the report field. """ log_file.flush() log_file.seek(0) self.Report.ChangeValue(log_file.read()) def copy(self, event): self.Report.SelectAll() self.Report.Copy() self.Report.SetSelection(-1, -1) def close(self, event): self.Hide()
from whacked4.ui import windows import wx class ErrorDialog(windows.ErrorDialogBase): def __init__(self, parent): windows.ErrorDialogBase.__init__(self, parent) if wx.IsBusy() == True: wx.EndBusyCursor() def set_log(self, log_file): """ Shows the log file's contents in the report field. """ log_file.flush() log_file.seek(0) self.Report.ChangeValue(log_file.read()) def copy(self, event): self.Report.SelectAll() self.Report.Copy() self.Report.SetSelection(-1, -1) def close(self, event): self.Hide()
Fix exceptions not displaying if a busy cursor was set.
Fix exceptions not displaying if a busy cursor was set.
Python
bsd-2-clause
GitExl/WhackEd4,GitExl/WhackEd4
from whacked4.ui import windows import wx class ErrorDialog(windows.ErrorDialogBase): def __init__(self, parent): windows.ErrorDialogBase.__init__(self, parent) + if wx.IsBusy() == True: - wx.EndBusyCursor() + wx.EndBusyCursor() def set_log(self, log_file): """ Shows the log file's contents in the report field. """ log_file.flush() log_file.seek(0) self.Report.ChangeValue(log_file.read()) def copy(self, event): self.Report.SelectAll() self.Report.Copy() self.Report.SetSelection(-1, -1) def close(self, event): self.Hide()
Fix exceptions not displaying if a busy cursor was set.
## Code Before: from whacked4.ui import windows import wx class ErrorDialog(windows.ErrorDialogBase): def __init__(self, parent): windows.ErrorDialogBase.__init__(self, parent) wx.EndBusyCursor() def set_log(self, log_file): """ Shows the log file's contents in the report field. """ log_file.flush() log_file.seek(0) self.Report.ChangeValue(log_file.read()) def copy(self, event): self.Report.SelectAll() self.Report.Copy() self.Report.SetSelection(-1, -1) def close(self, event): self.Hide() ## Instruction: Fix exceptions not displaying if a busy cursor was set. ## Code After: from whacked4.ui import windows import wx class ErrorDialog(windows.ErrorDialogBase): def __init__(self, parent): windows.ErrorDialogBase.__init__(self, parent) if wx.IsBusy() == True: wx.EndBusyCursor() def set_log(self, log_file): """ Shows the log file's contents in the report field. """ log_file.flush() log_file.seek(0) self.Report.ChangeValue(log_file.read()) def copy(self, event): self.Report.SelectAll() self.Report.Copy() self.Report.SetSelection(-1, -1) def close(self, event): self.Hide()
2575946f1b05ac1601a00f8936ab3a701b05bc7e
tests/test_utils.py
tests/test_utils.py
import unittest from utils import TextLoader import numpy as np class TestUtilsMethods(unittest.TestCase): def setUp(self): self.data_loader = TextLoader("tests/test_data", batch_size=2, seq_length=5) def test_init(self): print (self.data_loader.vocab) print (self.data_loader.tensor) print (self.data_loader.vocab_size) def test_build_vocab(self): sentences = ["I", "love", "cat", "cat"] vocab, vocab_inv = self.data_loader.build_vocab(sentences) print (vocab, vocab_inv) # Must include I, love, and cat self.assertItemsEqual(vocab, ["I", "love", "cat"]) self.assertDictEqual(vocab, {'I': 0, 'love': 2, 'cat': 1}) self.assertItemsEqual(vocab_inv, ["I", "love", "cat"]) def test_batch_vocab(self): print (np.array(self.data_loader.x_batches).shape) self.assertItemsEqual(self.data_loader.x_batches[0][0][1:], self.data_loader.y_batches[0][0][:-1]) self.assertItemsEqual(self.data_loader.x_batches[0][1][1:], self.data_loader.y_batches[0][1][:-1]) if __name__ == '__main__': unittest.main()
import unittest from utils import TextLoader import numpy as np from collections import Counter class TestUtilsMethods(unittest.TestCase): def setUp(self): self.data_loader = TextLoader("tests/test_data", batch_size=2, seq_length=5) def test_init(self): print (self.data_loader.vocab) print (self.data_loader.tensor) print (self.data_loader.vocab_size) def test_build_vocab(self): sentences = ["I", "love", "cat", "cat"] vocab, vocab_inv = self.data_loader.build_vocab(sentences) print (vocab, vocab_inv) # Must include I, love, and cat self.assertEqual(Counter(list(vocab)), Counter(list(["I", "love", "cat"]))) self.assertDictEqual(vocab, {'I': 0, 'love': 2, 'cat': 1}) self.assertEqual(Counter(list(vocab_inv)), Counter(list(["I", "love", "cat"]))) def test_batch_vocab(self): print (np.array(self.data_loader.x_batches).shape) self.assertEqual(Counter(list(self.data_loader.x_batches[0][0][1:])), Counter(list(self.data_loader.y_batches[0][0][:-1]))) self.assertEqual(Counter(list(self.data_loader.x_batches[0][1][1:])), Counter(list(self.data_loader.y_batches[0][1][:-1]))) if __name__ == '__main__': unittest.main()
Generalize method names to be compatible with Python 2.7 and 3.4
Generalize method names to be compatible with Python 2.7 and 3.4
Python
mit
hunkim/word-rnn-tensorflow,bahmanh/word-rnn-tensorflow
import unittest from utils import TextLoader import numpy as np + from collections import Counter class TestUtilsMethods(unittest.TestCase): def setUp(self): self.data_loader = TextLoader("tests/test_data", batch_size=2, seq_length=5) def test_init(self): print (self.data_loader.vocab) print (self.data_loader.tensor) print (self.data_loader.vocab_size) def test_build_vocab(self): sentences = ["I", "love", "cat", "cat"] vocab, vocab_inv = self.data_loader.build_vocab(sentences) print (vocab, vocab_inv) # Must include I, love, and cat - self.assertItemsEqual(vocab, ["I", "love", "cat"]) + self.assertEqual(Counter(list(vocab)), Counter(list(["I", "love", "cat"]))) self.assertDictEqual(vocab, {'I': 0, 'love': 2, 'cat': 1}) - self.assertItemsEqual(vocab_inv, ["I", "love", "cat"]) + self.assertEqual(Counter(list(vocab_inv)), Counter(list(["I", "love", "cat"]))) def test_batch_vocab(self): print (np.array(self.data_loader.x_batches).shape) - self.assertItemsEqual(self.data_loader.x_batches[0][0][1:], + self.assertEqual(Counter(list(self.data_loader.x_batches[0][0][1:])), - self.data_loader.y_batches[0][0][:-1]) + Counter(list(self.data_loader.y_batches[0][0][:-1]))) - self.assertItemsEqual(self.data_loader.x_batches[0][1][1:], + self.assertEqual(Counter(list(self.data_loader.x_batches[0][1][1:])), - self.data_loader.y_batches[0][1][:-1]) + Counter(list(self.data_loader.y_batches[0][1][:-1]))) if __name__ == '__main__': unittest.main() +
Generalize method names to be compatible with Python 2.7 and 3.4
## Code Before: import unittest from utils import TextLoader import numpy as np class TestUtilsMethods(unittest.TestCase): def setUp(self): self.data_loader = TextLoader("tests/test_data", batch_size=2, seq_length=5) def test_init(self): print (self.data_loader.vocab) print (self.data_loader.tensor) print (self.data_loader.vocab_size) def test_build_vocab(self): sentences = ["I", "love", "cat", "cat"] vocab, vocab_inv = self.data_loader.build_vocab(sentences) print (vocab, vocab_inv) # Must include I, love, and cat self.assertItemsEqual(vocab, ["I", "love", "cat"]) self.assertDictEqual(vocab, {'I': 0, 'love': 2, 'cat': 1}) self.assertItemsEqual(vocab_inv, ["I", "love", "cat"]) def test_batch_vocab(self): print (np.array(self.data_loader.x_batches).shape) self.assertItemsEqual(self.data_loader.x_batches[0][0][1:], self.data_loader.y_batches[0][0][:-1]) self.assertItemsEqual(self.data_loader.x_batches[0][1][1:], self.data_loader.y_batches[0][1][:-1]) if __name__ == '__main__': unittest.main() ## Instruction: Generalize method names to be compatible with Python 2.7 and 3.4 ## Code After: import unittest from utils import TextLoader import numpy as np from collections import Counter class TestUtilsMethods(unittest.TestCase): def setUp(self): self.data_loader = TextLoader("tests/test_data", batch_size=2, seq_length=5) def test_init(self): print (self.data_loader.vocab) print (self.data_loader.tensor) print (self.data_loader.vocab_size) def test_build_vocab(self): sentences = ["I", "love", "cat", "cat"] vocab, vocab_inv = self.data_loader.build_vocab(sentences) print (vocab, vocab_inv) # Must include I, love, and cat self.assertEqual(Counter(list(vocab)), Counter(list(["I", "love", "cat"]))) self.assertDictEqual(vocab, {'I': 0, 'love': 2, 'cat': 1}) self.assertEqual(Counter(list(vocab_inv)), Counter(list(["I", "love", "cat"]))) def test_batch_vocab(self): print (np.array(self.data_loader.x_batches).shape) self.assertEqual(Counter(list(self.data_loader.x_batches[0][0][1:])), Counter(list(self.data_loader.y_batches[0][0][:-1]))) self.assertEqual(Counter(list(self.data_loader.x_batches[0][1][1:])), Counter(list(self.data_loader.y_batches[0][1][:-1]))) if __name__ == '__main__': unittest.main()
a92118d7ee6acde57ab9853186c43a5c6748e8a6
tracpro/__init__.py
tracpro/__init__.py
from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app # noqa __version__ = "1.0.0"
from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app # noqa VERSION = (1, 0, 0, "dev") def get_version(version): assert len(version) == 4, "Version must be formatted as (major, minor, micro, state)" major, minor, micro, state = version assert isinstance(major, int), "Major version must be an integer." assert isinstance(minor, int), "Minor version must be an integer." assert isinstance(micro, int), "Micro version must be an integer." assert state in ('final', 'dev'), "State must be either final or dev." if state == 'final': return "{}.{}.{}".format(major, minor, micro) else: return "{}.{}.{}.{}".format(major, minor, micro, state) __version__ = get_version(VERSION)
Use tuple to represent version
Use tuple to represent version
Python
bsd-3-clause
rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro,rapidpro/tracpro
from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app # noqa - __version__ = "1.0.0" + VERSION = (1, 0, 0, "dev") + + def get_version(version): + assert len(version) == 4, "Version must be formatted as (major, minor, micro, state)" + + major, minor, micro, state = version + + assert isinstance(major, int), "Major version must be an integer." + assert isinstance(minor, int), "Minor version must be an integer." + assert isinstance(micro, int), "Micro version must be an integer." + assert state in ('final', 'dev'), "State must be either final or dev." + + if state == 'final': + return "{}.{}.{}".format(major, minor, micro) + else: + return "{}.{}.{}.{}".format(major, minor, micro, state) + + + __version__ = get_version(VERSION) +
Use tuple to represent version
## Code Before: from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app # noqa __version__ = "1.0.0" ## Instruction: Use tuple to represent version ## Code After: from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app # noqa VERSION = (1, 0, 0, "dev") def get_version(version): assert len(version) == 4, "Version must be formatted as (major, minor, micro, state)" major, minor, micro, state = version assert isinstance(major, int), "Major version must be an integer." assert isinstance(minor, int), "Minor version must be an integer." assert isinstance(micro, int), "Micro version must be an integer." assert state in ('final', 'dev'), "State must be either final or dev." if state == 'final': return "{}.{}.{}".format(major, minor, micro) else: return "{}.{}.{}.{}".format(major, minor, micro, state) __version__ = get_version(VERSION)
532b0809b040318abbb8e62848f18ad0cdf72547
src/workspace/workspace_managers.py
src/workspace/workspace_managers.py
from workspace.models import GroupPublishedWorkspace, PublishedWorkSpace, WorkSpace def ref_from_workspace(workspace): if isinstance(workspace, WorkSpace): return 'group/' + str(workspace.id) elif isinstance(workspace, PublishedWorkSpace): return 'group_published/' + str(workspace.id) class OrganizationWorkspaceManager: def get_id(self): return 'ezweb_organizations' def update_base_workspaces(self, user, current_workspace_refs): workspaces_to_remove = current_workspace_refs[:] workspaces_to_add = [] user_groups = user.groups.all() # workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces = [workspace for sublist in [WorkSpace.objects.filter(targetOrganizations=org) for org in user_groups] for workspace in sublist] # published workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces += [relation.workspace for sublist in [GroupPublishedWorkspace.objects.filter(group=group) for group in user_groups] for relation in sublist] workspaces = set(workspaces) for workspace in workspaces: ref = ref_from_workspace(workspace) if ref not in current_workspace_refs: workspaces_to_add.append((ref, workspace)) else: workspaces_to_remove.remove(ref) return (workspaces_to_remove, workspaces_to_add)
from workspace.models import GroupPublishedWorkspace, PublishedWorkSpace, WorkSpace def ref_from_workspace(workspace): if isinstance(workspace, WorkSpace): return 'group/' + str(workspace.id) elif isinstance(workspace, PublishedWorkSpace): return 'group_published/' + str(workspace.id) class OrganizationWorkspaceManager: def get_id(self): return 'ezweb_organizations' def update_base_workspaces(self, user, current_workspace_refs): workspaces_to_remove = current_workspace_refs[:] workspaces_to_add = [] user_groups = user.groups.all() # workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces = [workspace for sublist in [WorkSpace.objects.filter(targetOrganizations=org) for org in user_groups] for workspace in sublist] # published workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces += [relation.workspace for sublist in [GroupPublishedWorkspace.objects.filter(group=group) for group in user_groups] for relation in sublist] workspaces = set(workspaces) for workspace in workspaces: if workspace.creator == user: # Ignore workspaces created by the user continue ref = ref_from_workspace(workspace) if ref not in current_workspace_refs: workspaces_to_add.append((ref, workspace)) else: workspaces_to_remove.remove(ref) return (workspaces_to_remove, workspaces_to_add)
Make OrganizationWorkspaceManager ignore the original workspace when sharing workspaces with groups
Make OrganizationWorkspaceManager ignore the original workspace when sharing workspaces with groups
Python
agpl-3.0
rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud
from workspace.models import GroupPublishedWorkspace, PublishedWorkSpace, WorkSpace def ref_from_workspace(workspace): if isinstance(workspace, WorkSpace): return 'group/' + str(workspace.id) elif isinstance(workspace, PublishedWorkSpace): return 'group_published/' + str(workspace.id) class OrganizationWorkspaceManager: def get_id(self): return 'ezweb_organizations' def update_base_workspaces(self, user, current_workspace_refs): workspaces_to_remove = current_workspace_refs[:] workspaces_to_add = [] user_groups = user.groups.all() # workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces = [workspace for sublist in [WorkSpace.objects.filter(targetOrganizations=org) for org in user_groups] for workspace in sublist] # published workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces += [relation.workspace for sublist in [GroupPublishedWorkspace.objects.filter(group=group) for group in user_groups] for relation in sublist] workspaces = set(workspaces) for workspace in workspaces: + if workspace.creator == user: + # Ignore workspaces created by the user + continue + ref = ref_from_workspace(workspace) if ref not in current_workspace_refs: workspaces_to_add.append((ref, workspace)) else: workspaces_to_remove.remove(ref) return (workspaces_to_remove, workspaces_to_add)
Make OrganizationWorkspaceManager ignore the original workspace when sharing workspaces with groups
## Code Before: from workspace.models import GroupPublishedWorkspace, PublishedWorkSpace, WorkSpace def ref_from_workspace(workspace): if isinstance(workspace, WorkSpace): return 'group/' + str(workspace.id) elif isinstance(workspace, PublishedWorkSpace): return 'group_published/' + str(workspace.id) class OrganizationWorkspaceManager: def get_id(self): return 'ezweb_organizations' def update_base_workspaces(self, user, current_workspace_refs): workspaces_to_remove = current_workspace_refs[:] workspaces_to_add = [] user_groups = user.groups.all() # workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces = [workspace for sublist in [WorkSpace.objects.filter(targetOrganizations=org) for org in user_groups] for workspace in sublist] # published workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces += [relation.workspace for sublist in [GroupPublishedWorkspace.objects.filter(group=group) for group in user_groups] for relation in sublist] workspaces = set(workspaces) for workspace in workspaces: ref = ref_from_workspace(workspace) if ref not in current_workspace_refs: workspaces_to_add.append((ref, workspace)) else: workspaces_to_remove.remove(ref) return (workspaces_to_remove, workspaces_to_add) ## Instruction: Make OrganizationWorkspaceManager ignore the original workspace when sharing workspaces with groups ## Code After: from workspace.models import GroupPublishedWorkspace, PublishedWorkSpace, WorkSpace def ref_from_workspace(workspace): if isinstance(workspace, WorkSpace): return 'group/' + str(workspace.id) elif isinstance(workspace, PublishedWorkSpace): return 'group_published/' + str(workspace.id) class OrganizationWorkspaceManager: def get_id(self): return 'ezweb_organizations' def update_base_workspaces(self, user, current_workspace_refs): workspaces_to_remove = current_workspace_refs[:] workspaces_to_add = [] user_groups = user.groups.all() # workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces = [workspace for sublist in [WorkSpace.objects.filter(targetOrganizations=org) for org in user_groups] for workspace in sublist] # published workspaces assigned to the user's groups # the compression list outside the inside compression list is for flattening # the inside list workspaces += [relation.workspace for sublist in [GroupPublishedWorkspace.objects.filter(group=group) for group in user_groups] for relation in sublist] workspaces = set(workspaces) for workspace in workspaces: if workspace.creator == user: # Ignore workspaces created by the user continue ref = ref_from_workspace(workspace) if ref not in current_workspace_refs: workspaces_to_add.append((ref, workspace)) else: workspaces_to_remove.remove(ref) return (workspaces_to_remove, workspaces_to_add)
06e7cf66d37a34a33349e47c374e733b1f3006be
test/functional/feature_shutdown.py
test/functional/feature_shutdown.py
"""Test bitcoind shutdown.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, get_rpc_proxy from threading import Thread def test_long_call(node): block = node.waitfornewblock() assert_equal(block['height'], 0) class ShutdownTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir) Thread(target=test_long_call, args=(node,)).start() # wait 1 second to ensure event loop waits for current connections to close self.stop_node(0, wait=1000) if __name__ == '__main__': ShutdownTest().main()
"""Test bitcoind shutdown.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, get_rpc_proxy, wait_until from threading import Thread def test_long_call(node): block = node.waitfornewblock() assert_equal(block['height'], 0) class ShutdownTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir) # Force connection establishment by executing a dummy command. node.getblockcount() Thread(target=test_long_call, args=(node,)).start() # Wait until the server is executing the above `waitfornewblock`. wait_until(lambda: len(self.nodes[0].getrpcinfo()['active_commands']) == 2) # Wait 1 second after requesting shutdown but not before the `stop` call # finishes. This is to ensure event loop waits for current connections # to close. self.stop_node(0, wait=1000) if __name__ == '__main__': ShutdownTest().main()
Remove race between connecting and shutdown on separate connections
qa: Remove race between connecting and shutdown on separate connections
Python
mit
chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin
"""Test bitcoind shutdown.""" from test_framework.test_framework import BitcoinTestFramework - from test_framework.util import assert_equal, get_rpc_proxy + from test_framework.util import assert_equal, get_rpc_proxy, wait_until from threading import Thread def test_long_call(node): block = node.waitfornewblock() assert_equal(block['height'], 0) class ShutdownTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir) + # Force connection establishment by executing a dummy command. + node.getblockcount() Thread(target=test_long_call, args=(node,)).start() + # Wait until the server is executing the above `waitfornewblock`. + wait_until(lambda: len(self.nodes[0].getrpcinfo()['active_commands']) == 2) + # Wait 1 second after requesting shutdown but not before the `stop` call - # wait 1 second to ensure event loop waits for current connections to close + # finishes. This is to ensure event loop waits for current connections + # to close. self.stop_node(0, wait=1000) if __name__ == '__main__': ShutdownTest().main()
Remove race between connecting and shutdown on separate connections
## Code Before: """Test bitcoind shutdown.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, get_rpc_proxy from threading import Thread def test_long_call(node): block = node.waitfornewblock() assert_equal(block['height'], 0) class ShutdownTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir) Thread(target=test_long_call, args=(node,)).start() # wait 1 second to ensure event loop waits for current connections to close self.stop_node(0, wait=1000) if __name__ == '__main__': ShutdownTest().main() ## Instruction: Remove race between connecting and shutdown on separate connections ## Code After: """Test bitcoind shutdown.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, get_rpc_proxy, wait_until from threading import Thread def test_long_call(node): block = node.waitfornewblock() assert_equal(block['height'], 0) class ShutdownTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir) # Force connection establishment by executing a dummy command. node.getblockcount() Thread(target=test_long_call, args=(node,)).start() # Wait until the server is executing the above `waitfornewblock`. wait_until(lambda: len(self.nodes[0].getrpcinfo()['active_commands']) == 2) # Wait 1 second after requesting shutdown but not before the `stop` call # finishes. This is to ensure event loop waits for current connections # to close. self.stop_node(0, wait=1000) if __name__ == '__main__': ShutdownTest().main()
d73872b8bcc6c7c32fa10d4a8ffdd77fe568a954
pyautotest/cli.py
pyautotest/cli.py
import logging import os import signal import time from optparse import OptionParser from watchdog.observers import Observer from pyautotest.observers import Notifier, ChangeHandler # Configure logging logging.basicConfig(format='%(asctime)s (%(name)s) [%(levelname)s]: %(message)s', datefmt='%m-%d-%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger('pyautotest') def main(): parser = OptionParser("usage: %prog [options]") parser.set_defaults(loglevel="INFO") parser.add_option("-l", "--log-level", action="store", dest="loglevel") (options, args) = parser.parse_args() # Handle options logger.setLevel(getattr(logging, options.loglevel.upper(), None)) while True: event_handler = ChangeHandler() event_handler.run_tests() observer = Observer() observer.schedule(event_handler, os.getcwd(), recursive=True) # Avoid child zombie processes signal.signal(signal.SIGCHLD, signal.SIG_IGN) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == "__main__": main()
import argparse import logging import os import signal import time from watchdog.observers import Observer from pyautotest.observers import Notifier, ChangeHandler # Configure logging logging.basicConfig(format='%(asctime)s (%(name)s) [%(levelname)s]: %(message)s', datefmt='%m-%d-%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger('pyautotest') def main(): parser = argparse.ArgumentParser(description="Continuously run unit tests when changes detected") parser.add_argument('-l', '--log-level', metavar='L', default='INFO', dest='loglevel', action='store', help='set logger level') args = parser.parse_args() # Handle options logger.setLevel(getattr(logging, args.loglevel.upper(), None)) while True: event_handler = ChangeHandler() event_handler.run_tests() observer = Observer() observer.schedule(event_handler, os.getcwd(), recursive=True) # Avoid child zombie processes signal.signal(signal.SIGCHLD, signal.SIG_IGN) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == "__main__": main()
Switch from optparase to argparse
Switch from optparase to argparse
Python
mit
ascarter/pyautotest
+ import argparse import logging import os import signal import time - from optparse import OptionParser from watchdog.observers import Observer from pyautotest.observers import Notifier, ChangeHandler # Configure logging logging.basicConfig(format='%(asctime)s (%(name)s) [%(levelname)s]: %(message)s', datefmt='%m-%d-%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger('pyautotest') def main(): - parser = OptionParser("usage: %prog [options]") - parser.set_defaults(loglevel="INFO") - parser.add_option("-l", "--log-level", action="store", dest="loglevel") + parser = argparse.ArgumentParser(description="Continuously run unit tests when changes detected") + parser.add_argument('-l', '--log-level', + metavar='L', + default='INFO', + dest='loglevel', + action='store', + help='set logger level') - (options, args) = parser.parse_args() + args = parser.parse_args() # Handle options - logger.setLevel(getattr(logging, options.loglevel.upper(), None)) + logger.setLevel(getattr(logging, args.loglevel.upper(), None)) while True: event_handler = ChangeHandler() event_handler.run_tests() observer = Observer() observer.schedule(event_handler, os.getcwd(), recursive=True) # Avoid child zombie processes signal.signal(signal.SIGCHLD, signal.SIG_IGN) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == "__main__": main()
Switch from optparase to argparse
## Code Before: import logging import os import signal import time from optparse import OptionParser from watchdog.observers import Observer from pyautotest.observers import Notifier, ChangeHandler # Configure logging logging.basicConfig(format='%(asctime)s (%(name)s) [%(levelname)s]: %(message)s', datefmt='%m-%d-%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger('pyautotest') def main(): parser = OptionParser("usage: %prog [options]") parser.set_defaults(loglevel="INFO") parser.add_option("-l", "--log-level", action="store", dest="loglevel") (options, args) = parser.parse_args() # Handle options logger.setLevel(getattr(logging, options.loglevel.upper(), None)) while True: event_handler = ChangeHandler() event_handler.run_tests() observer = Observer() observer.schedule(event_handler, os.getcwd(), recursive=True) # Avoid child zombie processes signal.signal(signal.SIGCHLD, signal.SIG_IGN) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == "__main__": main() ## Instruction: Switch from optparase to argparse ## Code After: import argparse import logging import os import signal import time from watchdog.observers import Observer from pyautotest.observers import Notifier, ChangeHandler # Configure logging logging.basicConfig(format='%(asctime)s (%(name)s) [%(levelname)s]: %(message)s', datefmt='%m-%d-%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger('pyautotest') def main(): parser = argparse.ArgumentParser(description="Continuously run unit tests when changes detected") parser.add_argument('-l', '--log-level', metavar='L', default='INFO', dest='loglevel', action='store', help='set logger level') args = parser.parse_args() # Handle options logger.setLevel(getattr(logging, args.loglevel.upper(), None)) while True: event_handler = ChangeHandler() event_handler.run_tests() observer = Observer() observer.schedule(event_handler, os.getcwd(), recursive=True) # Avoid child zombie processes signal.signal(signal.SIGCHLD, signal.SIG_IGN) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == "__main__": main()
5e30bd1ae8218a6ad5a2582c15aed99258994d83
tests/tests/test_swappable_model.py
tests/tests/test_swappable_model.py
from django.test import TestCase
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, modify_settings from boardinghouse.schema import get_schema_model class TestSwappableModel(TestCase): @modify_settings() def test_schema_model_app_not_found(self): settings.BOARDINGHOUSE_SCHEMA_MODEL = 'foo.bar' with self.assertRaises(ImproperlyConfigured): get_schema_model() @modify_settings() def test_schema_model_model_not_found(self): settings.BOARDINGHOUSE_SCHEMA_MODEL = 'boardinghouse.NotSchemaModel' with self.assertRaises(ImproperlyConfigured): get_schema_model() @modify_settings() def test_invalid_schema_model_string(self): settings.BOARDINGHOUSE_SCHEMA_MODEL = 'foo__bar' with self.assertRaises(ImproperlyConfigured): get_schema_model()
Write tests for swappable model.
Write tests for swappable model. Resolves #28, #36. --HG-- branch : fix-swappable-model
Python
bsd-3-clause
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
+ from django.conf import settings + from django.core.exceptions import ImproperlyConfigured - from django.test import TestCase + from django.test import TestCase, modify_settings + + from boardinghouse.schema import get_schema_model + + + class TestSwappableModel(TestCase): + + @modify_settings() + def test_schema_model_app_not_found(self): + settings.BOARDINGHOUSE_SCHEMA_MODEL = 'foo.bar' + with self.assertRaises(ImproperlyConfigured): + get_schema_model() + + @modify_settings() + def test_schema_model_model_not_found(self): + settings.BOARDINGHOUSE_SCHEMA_MODEL = 'boardinghouse.NotSchemaModel' + with self.assertRaises(ImproperlyConfigured): + get_schema_model() + + @modify_settings() + def test_invalid_schema_model_string(self): + settings.BOARDINGHOUSE_SCHEMA_MODEL = 'foo__bar' + with self.assertRaises(ImproperlyConfigured): + get_schema_model() +
Write tests for swappable model.
## Code Before: from django.test import TestCase ## Instruction: Write tests for swappable model. ## Code After: from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, modify_settings from boardinghouse.schema import get_schema_model class TestSwappableModel(TestCase): @modify_settings() def test_schema_model_app_not_found(self): settings.BOARDINGHOUSE_SCHEMA_MODEL = 'foo.bar' with self.assertRaises(ImproperlyConfigured): get_schema_model() @modify_settings() def test_schema_model_model_not_found(self): settings.BOARDINGHOUSE_SCHEMA_MODEL = 'boardinghouse.NotSchemaModel' with self.assertRaises(ImproperlyConfigured): get_schema_model() @modify_settings() def test_invalid_schema_model_string(self): settings.BOARDINGHOUSE_SCHEMA_MODEL = 'foo__bar' with self.assertRaises(ImproperlyConfigured): get_schema_model()
1b1652053213f3939b50b2ac66a775cd5d4beed9
openpnm/__init__.py
openpnm/__init__.py
from .__version__ import __version__ from . import utils from . import core from . import network from . import geometry from . import phases from . import physics from . import models from . import solvers from . import integrators from . import algorithms from . import materials from . import topotools from . import io from . import metrics from .utils import Workspace, Project import numpy as _np _np.seterr(divide='ignore', invalid='ignore')
from .__version__ import __version__ from . import utils from . import core from . import network from . import geometry from . import phases from . import physics from . import models from . import algorithms from . import solvers from . import integrators from . import materials from . import topotools from . import io from . import metrics from .utils import Workspace, Project import numpy as _np _np.seterr(divide='ignore', invalid='ignore')
Fix import order to avoid circular import
Fix import order to avoid circular import
Python
mit
PMEAL/OpenPNM
from .__version__ import __version__ from . import utils from . import core from . import network from . import geometry from . import phases from . import physics from . import models + from . import algorithms from . import solvers from . import integrators - from . import algorithms from . import materials from . import topotools from . import io from . import metrics from .utils import Workspace, Project import numpy as _np _np.seterr(divide='ignore', invalid='ignore')
Fix import order to avoid circular import
## Code Before: from .__version__ import __version__ from . import utils from . import core from . import network from . import geometry from . import phases from . import physics from . import models from . import solvers from . import integrators from . import algorithms from . import materials from . import topotools from . import io from . import metrics from .utils import Workspace, Project import numpy as _np _np.seterr(divide='ignore', invalid='ignore') ## Instruction: Fix import order to avoid circular import ## Code After: from .__version__ import __version__ from . import utils from . import core from . import network from . import geometry from . import phases from . import physics from . import models from . import algorithms from . import solvers from . import integrators from . import materials from . import topotools from . import io from . import metrics from .utils import Workspace, Project import numpy as _np _np.seterr(divide='ignore', invalid='ignore')
32bf828445ed897609b908dff435191287f922f4
bookie/views/stats.py
bookie/views/stats.py
"""Basic views with no home""" import logging from pyramid.view import view_config from bookie.bcelery import tasks from bookie.models import BmarkMgr from bookie.models.auth import ActivationMgr from bookie.models.auth import UserMgr LOG = logging.getLogger(__name__) @view_config( route_name="dashboard", renderer="/stats/dashboard.mako") def dashboard(request): """A public dashboard of the system """ res = tasks.count_total.delay() # Generate some user data and stats user_count = UserMgr.count() pending_activations = ActivationMgr.count() # Generate some bookmark data. bookmark_count = BmarkMgr.count() unique_url_count = BmarkMgr.count(distinct=True) users_with_bookmarks = BmarkMgr.count(distinct_users=True) return { 'bookmark_data': { 'count': bookmark_count, 'unique_count': unique_url_count, }, 'user_data': { 'count': user_count, 'activations': pending_activations, 'with_bookmarks': users_with_bookmarks, } }
"""Basic views with no home""" import logging from pyramid.view import view_config from bookie.models import BmarkMgr from bookie.models.auth import ActivationMgr from bookie.models.auth import UserMgr LOG = logging.getLogger(__name__) @view_config( route_name="dashboard", renderer="/stats/dashboard.mako") def dashboard(request): """A public dashboard of the system """ # Generate some user data and stats user_count = UserMgr.count() pending_activations = ActivationMgr.count() # Generate some bookmark data. bookmark_count = BmarkMgr.count() unique_url_count = BmarkMgr.count(distinct=True) users_with_bookmarks = BmarkMgr.count(distinct_users=True) return { 'bookmark_data': { 'count': bookmark_count, 'unique_count': unique_url_count, }, 'user_data': { 'count': user_count, 'activations': pending_activations, 'with_bookmarks': users_with_bookmarks, } }
Clean up old code no longer used
Clean up old code no longer used
Python
agpl-3.0
adamlincoln/Bookie,charany1/Bookie,GreenLunar/Bookie,charany1/Bookie,skmezanul/Bookie,charany1/Bookie,adamlincoln/Bookie,GreenLunar/Bookie,pombredanne/Bookie,wangjun/Bookie,bookieio/Bookie,skmezanul/Bookie,pombredanne/Bookie,bookieio/Bookie,GreenLunar/Bookie,pombredanne/Bookie,teodesson/Bookie,skmezanul/Bookie,bookieio/Bookie,teodesson/Bookie,wangjun/Bookie,adamlincoln/Bookie,teodesson/Bookie,skmezanul/Bookie,wangjun/Bookie,GreenLunar/Bookie,teodesson/Bookie,adamlincoln/Bookie,bookieio/Bookie,wangjun/Bookie
"""Basic views with no home""" import logging from pyramid.view import view_config - from bookie.bcelery import tasks from bookie.models import BmarkMgr from bookie.models.auth import ActivationMgr from bookie.models.auth import UserMgr LOG = logging.getLogger(__name__) @view_config( route_name="dashboard", renderer="/stats/dashboard.mako") def dashboard(request): """A public dashboard of the system """ - res = tasks.count_total.delay() - # Generate some user data and stats user_count = UserMgr.count() pending_activations = ActivationMgr.count() # Generate some bookmark data. bookmark_count = BmarkMgr.count() unique_url_count = BmarkMgr.count(distinct=True) users_with_bookmarks = BmarkMgr.count(distinct_users=True) return { 'bookmark_data': { 'count': bookmark_count, 'unique_count': unique_url_count, }, 'user_data': { 'count': user_count, 'activations': pending_activations, 'with_bookmarks': users_with_bookmarks, } }
Clean up old code no longer used
## Code Before: """Basic views with no home""" import logging from pyramid.view import view_config from bookie.bcelery import tasks from bookie.models import BmarkMgr from bookie.models.auth import ActivationMgr from bookie.models.auth import UserMgr LOG = logging.getLogger(__name__) @view_config( route_name="dashboard", renderer="/stats/dashboard.mako") def dashboard(request): """A public dashboard of the system """ res = tasks.count_total.delay() # Generate some user data and stats user_count = UserMgr.count() pending_activations = ActivationMgr.count() # Generate some bookmark data. bookmark_count = BmarkMgr.count() unique_url_count = BmarkMgr.count(distinct=True) users_with_bookmarks = BmarkMgr.count(distinct_users=True) return { 'bookmark_data': { 'count': bookmark_count, 'unique_count': unique_url_count, }, 'user_data': { 'count': user_count, 'activations': pending_activations, 'with_bookmarks': users_with_bookmarks, } } ## Instruction: Clean up old code no longer used ## Code After: """Basic views with no home""" import logging from pyramid.view import view_config from bookie.models import BmarkMgr from bookie.models.auth import ActivationMgr from bookie.models.auth import UserMgr LOG = logging.getLogger(__name__) @view_config( route_name="dashboard", renderer="/stats/dashboard.mako") def dashboard(request): """A public dashboard of the system """ # Generate some user data and stats user_count = UserMgr.count() pending_activations = ActivationMgr.count() # Generate some bookmark data. bookmark_count = BmarkMgr.count() unique_url_count = BmarkMgr.count(distinct=True) users_with_bookmarks = BmarkMgr.count(distinct_users=True) return { 'bookmark_data': { 'count': bookmark_count, 'unique_count': unique_url_count, }, 'user_data': { 'count': user_count, 'activations': pending_activations, 'with_bookmarks': users_with_bookmarks, } }
c5a2c7e802d89ea17a7f0fd1a9194eaab8eaf61d
wcontrol/src/main.py
wcontrol/src/main.py
from flask import Flask app = Flask(__name__) app.config.from_object("config")
import os from flask import Flask app = Flask(__name__) app.config.from_object(os.environ.get("WCONTROL_CONF"))
Use a env var to get config
Use a env var to get config
Python
mit
pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control
+ import os from flask import Flask app = Flask(__name__) - app.config.from_object("config") + app.config.from_object(os.environ.get("WCONTROL_CONF"))
Use a env var to get config
## Code Before: from flask import Flask app = Flask(__name__) app.config.from_object("config") ## Instruction: Use a env var to get config ## Code After: import os from flask import Flask app = Flask(__name__) app.config.from_object(os.environ.get("WCONTROL_CONF"))
98dfc5569fb1ae58905f8b6a36deeda324dcdd7b
cronos/teilar/models.py
cronos/teilar/models.py
from django.db import models class Departments(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Department name", max_length = 200) class Teachers(models.Model): urlid = models.CharField("URL ID", max_length = 30, unique = True) name = models.CharField("Teacher name", max_length = 100) email = models.EmailField("Teacher's mail", null = True) department = models.CharField("Teacher's department", max_length = 100, null = True) def __unicode__(self): return self.name
from django.db import models class Departments(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Department name", max_length = 200) deprecated = models.BooleanField(default = False) def __unicode__(self): return self.name class Teachers(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Teacher name", max_length = 100) email = models.EmailField("Teacher's mail", null = True) department = models.CharField("Teacher's department", max_length = 100, null = True) deprecated = models.BooleanField(default = False) def __unicode__(self): return self.name
Add deprecated flag for teachers and departments
Add deprecated flag for teachers and departments
Python
agpl-3.0
LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr
from django.db import models class Departments(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Department name", max_length = 200) + deprecated = models.BooleanField(default = False) - - class Teachers(models.Model): - urlid = models.CharField("URL ID", max_length = 30, unique = True) - name = models.CharField("Teacher name", max_length = 100) - email = models.EmailField("Teacher's mail", null = True) - department = models.CharField("Teacher's department", max_length = 100, null = True) def __unicode__(self): return self.name + class Teachers(models.Model): + urlid = models.IntegerField(unique = True) + name = models.CharField("Teacher name", max_length = 100) + email = models.EmailField("Teacher's mail", null = True) + department = models.CharField("Teacher's department", max_length = 100, null = True) + deprecated = models.BooleanField(default = False) + + def __unicode__(self): + return self.name +
Add deprecated flag for teachers and departments
## Code Before: from django.db import models class Departments(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Department name", max_length = 200) class Teachers(models.Model): urlid = models.CharField("URL ID", max_length = 30, unique = True) name = models.CharField("Teacher name", max_length = 100) email = models.EmailField("Teacher's mail", null = True) department = models.CharField("Teacher's department", max_length = 100, null = True) def __unicode__(self): return self.name ## Instruction: Add deprecated flag for teachers and departments ## Code After: from django.db import models class Departments(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Department name", max_length = 200) deprecated = models.BooleanField(default = False) def __unicode__(self): return self.name class Teachers(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Teacher name", max_length = 100) email = models.EmailField("Teacher's mail", null = True) department = models.CharField("Teacher's department", max_length = 100, null = True) deprecated = models.BooleanField(default = False) def __unicode__(self): return self.name
2ac94aa922dbf2d07039bc6545e7b1d31c5c9e4e
src/cclib/progress/__init__.py
src/cclib/progress/__init__.py
__revision__ = "$Revision$" from textprogress import TextProgress try: import qt except ImportError: pass # import QtProgress will cause an error else: from qtprogress import QtProgress
__revision__ = "$Revision$" from textprogress import TextProgress import sys if 'qt' in sys.modules.keys(): from qtprogress import QtProgress
Check to see if qt is loaded; if so, export QtProgress class
Check to see if qt is loaded; if so, export QtProgress class
Python
lgpl-2.1
Clyde-fare/cclib,Schamnad/cclib,jchodera/cclib,ghutchis/cclib,gaursagar/cclib,berquist/cclib,andersx/cclib,ben-albrecht/cclib,Schamnad/cclib,cclib/cclib,ATenderholt/cclib,cclib/cclib,langner/cclib,berquist/cclib,Clyde-fare/cclib,langner/cclib,ben-albrecht/cclib,ATenderholt/cclib,ghutchis/cclib,jchodera/cclib,andersx/cclib,cclib/cclib,langner/cclib,berquist/cclib,gaursagar/cclib
__revision__ = "$Revision$" from textprogress import TextProgress + import sys + + if 'qt' in sys.modules.keys(): - try: - import qt - except ImportError: - pass # import QtProgress will cause an error - else: from qtprogress import QtProgress
Check to see if qt is loaded; if so, export QtProgress class
## Code Before: __revision__ = "$Revision$" from textprogress import TextProgress try: import qt except ImportError: pass # import QtProgress will cause an error else: from qtprogress import QtProgress ## Instruction: Check to see if qt is loaded; if so, export QtProgress class ## Code After: __revision__ = "$Revision$" from textprogress import TextProgress import sys if 'qt' in sys.modules.keys(): from qtprogress import QtProgress
e621b9f03b19e38dc6754dd1a4cb7b172e4891e7
tests/test_extended_tests.py
tests/test_extended_tests.py
import pytest import glob from html2kirby import HTML2Kirby files = [] for f in glob.glob("extended_tests/*.html"): html = f txt = f.replace(".html", ".txt") files.append((html, txt)) @pytest.mark.parametrize("html,kirby", files) def test_file(html, kirby): formatter = HTML2Kirby() with open(html, 'r') as html_file: formatter.feed(html_file.read()) with open(kirby, 'r') as kirby_file: expected_result = kirby_file.read() assert formatter.markdown.strip() == expected_result.strip()
import pytest import glob import os from html2kirby import HTML2Kirby files = [] path = os.path.dirname(os.path.abspath(__file__)) extended_tests_path = os.path.join(path, "extended_tests/*.html") for f in glob.glob(extended_tests_path): html = f txt = f.replace(".html", ".txt") files.append((html, txt)) @pytest.mark.parametrize("html,kirby", files) def test_file(html, kirby): formatter = HTML2Kirby() with open(html, 'r') as html_file: formatter.feed(html_file.read()) with open(kirby, 'r') as kirby_file: expected_result = kirby_file.read() assert formatter.markdown.strip() == expected_result.strip()
Fix the extended test search
Fix the extended test search
Python
mit
liip/html2kirby,liip/html2kirby
import pytest import glob + import os from html2kirby import HTML2Kirby files = [] + path = os.path.dirname(os.path.abspath(__file__)) + + extended_tests_path = os.path.join(path, "extended_tests/*.html") + - for f in glob.glob("extended_tests/*.html"): + for f in glob.glob(extended_tests_path): html = f txt = f.replace(".html", ".txt") files.append((html, txt)) @pytest.mark.parametrize("html,kirby", files) def test_file(html, kirby): formatter = HTML2Kirby() with open(html, 'r') as html_file: formatter.feed(html_file.read()) with open(kirby, 'r') as kirby_file: expected_result = kirby_file.read() assert formatter.markdown.strip() == expected_result.strip()
Fix the extended test search
## Code Before: import pytest import glob from html2kirby import HTML2Kirby files = [] for f in glob.glob("extended_tests/*.html"): html = f txt = f.replace(".html", ".txt") files.append((html, txt)) @pytest.mark.parametrize("html,kirby", files) def test_file(html, kirby): formatter = HTML2Kirby() with open(html, 'r') as html_file: formatter.feed(html_file.read()) with open(kirby, 'r') as kirby_file: expected_result = kirby_file.read() assert formatter.markdown.strip() == expected_result.strip() ## Instruction: Fix the extended test search ## Code After: import pytest import glob import os from html2kirby import HTML2Kirby files = [] path = os.path.dirname(os.path.abspath(__file__)) extended_tests_path = os.path.join(path, "extended_tests/*.html") for f in glob.glob(extended_tests_path): html = f txt = f.replace(".html", ".txt") files.append((html, txt)) @pytest.mark.parametrize("html,kirby", files) def test_file(html, kirby): formatter = HTML2Kirby() with open(html, 'r') as html_file: formatter.feed(html_file.read()) with open(kirby, 'r') as kirby_file: expected_result = kirby_file.read() assert formatter.markdown.strip() == expected_result.strip()
603aacd06b99326d7dbab28e750b34589c51fa05
tests/test_postgresqlgate.py
tests/test_postgresqlgate.py
from unittest.mock import MagicMock, mock_open, patch import smdba.postgresqlgate class TestPgGt: """ Test suite for base gate. """ @patch("os.path.exists", MagicMock(side_effect=[True, False, False])) @patch("smdba.postgresqlgate.open", new_callable=mock_open, read_data="key=value") def test_get_scenario_template(self, mck): """ Gets scenario template. :return: """ pgt = smdba.postgresqlgate.PgSQLGate({}) template = pgt.get_scenario_template(target="psql") assert template == "cat - << EOF | /usr/bin/psql -t --pset footer=off\n@scenario\nEOF"
from unittest.mock import MagicMock, mock_open, patch import smdba.postgresqlgate class TestPgGt: """ Test suite for base gate. """ @patch("os.path.exists", MagicMock(side_effect=[True, False, False])) @patch("smdba.postgresqlgate.open", new_callable=mock_open, read_data="key=value") def test_get_scenario_template(self, mck): """ Gets scenario template. :return: """ pgt = smdba.postgresqlgate.PgSQLGate({}) template = pgt.get_scenario_template(target="psql") assert template == "cat - << EOF | /usr/bin/psql -t --pset footer=off\n@scenario\nEOF" @patch("os.path.exists", MagicMock(side_effect=[True, False, False])) @patch("smdba.postgresqlgate.open", new_callable=mock_open, read_data="key=value") def test_call_scenario(self, mck): """ Calls database scenario. :return: """ pgt = smdba.postgresqlgate.PgSQLGate({}) pgt.get_scn = MagicMock() pgt.get_scn().read = MagicMock(return_value="SELECT pg_reload_conf();") pgt.syscall = MagicMock() pgt.call_scenario("pg-reload-conf.scn", target="psql") expectations = [ ( ('sudo', '-u', 'postgres', '/bin/bash'), {'input': 'cat - << EOF | /usr/bin/psql -t --pset footer=off\nSELECT pg_reload_conf();\nEOF'} ) ] for call in pgt.syscall.call_args_list: args, kw = call exp_args, exp_kw = next(iter(expectations)) expectations.pop(0) assert args == exp_args assert "input" in kw assert "input" in exp_kw assert kw["input"] == exp_kw["input"] assert not expectations
Add unit test for database scenario call
Add unit test for database scenario call
Python
mit
SUSE/smdba,SUSE/smdba
from unittest.mock import MagicMock, mock_open, patch import smdba.postgresqlgate class TestPgGt: """ Test suite for base gate. """ @patch("os.path.exists", MagicMock(side_effect=[True, False, False])) @patch("smdba.postgresqlgate.open", new_callable=mock_open, read_data="key=value") def test_get_scenario_template(self, mck): """ Gets scenario template. :return: """ pgt = smdba.postgresqlgate.PgSQLGate({}) template = pgt.get_scenario_template(target="psql") assert template == "cat - << EOF | /usr/bin/psql -t --pset footer=off\n@scenario\nEOF" + @patch("os.path.exists", MagicMock(side_effect=[True, False, False])) + @patch("smdba.postgresqlgate.open", new_callable=mock_open, + read_data="key=value") + def test_call_scenario(self, mck): + """ + Calls database scenario. + + :return: + """ + pgt = smdba.postgresqlgate.PgSQLGate({}) + pgt.get_scn = MagicMock() + pgt.get_scn().read = MagicMock(return_value="SELECT pg_reload_conf();") + pgt.syscall = MagicMock() + + pgt.call_scenario("pg-reload-conf.scn", target="psql") + + expectations = [ + ( + ('sudo', '-u', 'postgres', '/bin/bash'), + {'input': 'cat - << EOF | /usr/bin/psql -t --pset footer=off\nSELECT pg_reload_conf();\nEOF'} + ) + ] + + for call in pgt.syscall.call_args_list: + args, kw = call + exp_args, exp_kw = next(iter(expectations)) + expectations.pop(0) + + assert args == exp_args + assert "input" in kw + assert "input" in exp_kw + assert kw["input"] == exp_kw["input"] + + assert not expectations +
Add unit test for database scenario call
## Code Before: from unittest.mock import MagicMock, mock_open, patch import smdba.postgresqlgate class TestPgGt: """ Test suite for base gate. """ @patch("os.path.exists", MagicMock(side_effect=[True, False, False])) @patch("smdba.postgresqlgate.open", new_callable=mock_open, read_data="key=value") def test_get_scenario_template(self, mck): """ Gets scenario template. :return: """ pgt = smdba.postgresqlgate.PgSQLGate({}) template = pgt.get_scenario_template(target="psql") assert template == "cat - << EOF | /usr/bin/psql -t --pset footer=off\n@scenario\nEOF" ## Instruction: Add unit test for database scenario call ## Code After: from unittest.mock import MagicMock, mock_open, patch import smdba.postgresqlgate class TestPgGt: """ Test suite for base gate. """ @patch("os.path.exists", MagicMock(side_effect=[True, False, False])) @patch("smdba.postgresqlgate.open", new_callable=mock_open, read_data="key=value") def test_get_scenario_template(self, mck): """ Gets scenario template. :return: """ pgt = smdba.postgresqlgate.PgSQLGate({}) template = pgt.get_scenario_template(target="psql") assert template == "cat - << EOF | /usr/bin/psql -t --pset footer=off\n@scenario\nEOF" @patch("os.path.exists", MagicMock(side_effect=[True, False, False])) @patch("smdba.postgresqlgate.open", new_callable=mock_open, read_data="key=value") def test_call_scenario(self, mck): """ Calls database scenario. :return: """ pgt = smdba.postgresqlgate.PgSQLGate({}) pgt.get_scn = MagicMock() pgt.get_scn().read = MagicMock(return_value="SELECT pg_reload_conf();") pgt.syscall = MagicMock() pgt.call_scenario("pg-reload-conf.scn", target="psql") expectations = [ ( ('sudo', '-u', 'postgres', '/bin/bash'), {'input': 'cat - << EOF | /usr/bin/psql -t --pset footer=off\nSELECT pg_reload_conf();\nEOF'} ) ] for call in pgt.syscall.call_args_list: args, kw = call exp_args, exp_kw = next(iter(expectations)) expectations.pop(0) assert args == exp_args assert "input" in kw assert "input" in exp_kw assert kw["input"] == exp_kw["input"] assert not expectations
2a0b1d070996bfb3d950d4fae70b264ddabc7d2f
sheldon/config.py
sheldon/config.py
import os class Config: def __init__(self, prefix='SHELDON_'): """ Load config from environment variables. :param prefix: string, all needed environment variables starts from it. Default - 'SHELDON_'. So, environment variables will be looking like: 'SHELDON_BOT_NAME', 'SHELDON_TWITTER_KEY' :return: """ # Bot config variables self.variables = {} for variable in os.environ: if variable.startswith(prefix): self.variables[variable] = os.environ[variable] def get(self, variable, default_value): """ :param variable: string, needed variable :param default_value: string, value that returns if variable is not set :return: """ if variable not in self.variables: return default_value return self.variables[variable]
import os class Config: def __init__(self, prefix='SHELDON_'): """ Load config from environment variables. :param prefix: string, all needed environment variables starts from it. Default - 'SHELDON_'. So, environment variables will be looking like: 'SHELDON_BOT_NAME', 'SHELDON_TWITTER_KEY' :return: """ # Bot config variables self.variables = {} for variable in os.environ: if variable.startswith(prefix): self.variables[variable] = os.environ[variable] def get(self, variable, default_value): """ Get variable value from environment :param variable: string, needed variable :param default_value: string, value that returns if variable is not set :return: variable value """ if variable not in self.variables: return default_value return self.variables[variable] def get_installed_plugins(self): """ Return list of installed plugins from installed_plugins.txt :return: list of strings with names of plugins """ plugins_file = open('installed_plugins.txt') return plugins_file.readlines()
Add function for getting installed plugins
Add function for getting installed plugins
Python
mit
lises/sheldon
import os class Config: def __init__(self, prefix='SHELDON_'): """ Load config from environment variables. :param prefix: string, all needed environment variables starts from it. Default - 'SHELDON_'. So, environment variables will be looking like: 'SHELDON_BOT_NAME', 'SHELDON_TWITTER_KEY' :return: """ # Bot config variables self.variables = {} for variable in os.environ: if variable.startswith(prefix): self.variables[variable] = os.environ[variable] def get(self, variable, default_value): """ + Get variable value from environment :param variable: string, needed variable :param default_value: string, value that returns if variable is not set - :return: + :return: variable value """ if variable not in self.variables: return default_value return self.variables[variable] + def get_installed_plugins(self): + """ + Return list of installed plugins from installed_plugins.txt + :return: list of strings with names of plugins + """ + plugins_file = open('installed_plugins.txt') + return plugins_file.readlines() +
Add function for getting installed plugins
## Code Before: import os class Config: def __init__(self, prefix='SHELDON_'): """ Load config from environment variables. :param prefix: string, all needed environment variables starts from it. Default - 'SHELDON_'. So, environment variables will be looking like: 'SHELDON_BOT_NAME', 'SHELDON_TWITTER_KEY' :return: """ # Bot config variables self.variables = {} for variable in os.environ: if variable.startswith(prefix): self.variables[variable] = os.environ[variable] def get(self, variable, default_value): """ :param variable: string, needed variable :param default_value: string, value that returns if variable is not set :return: """ if variable not in self.variables: return default_value return self.variables[variable] ## Instruction: Add function for getting installed plugins ## Code After: import os class Config: def __init__(self, prefix='SHELDON_'): """ Load config from environment variables. :param prefix: string, all needed environment variables starts from it. Default - 'SHELDON_'. So, environment variables will be looking like: 'SHELDON_BOT_NAME', 'SHELDON_TWITTER_KEY' :return: """ # Bot config variables self.variables = {} for variable in os.environ: if variable.startswith(prefix): self.variables[variable] = os.environ[variable] def get(self, variable, default_value): """ Get variable value from environment :param variable: string, needed variable :param default_value: string, value that returns if variable is not set :return: variable value """ if variable not in self.variables: return default_value return self.variables[variable] def get_installed_plugins(self): """ Return list of installed plugins from installed_plugins.txt :return: list of strings with names of plugins """ plugins_file = open('installed_plugins.txt') return plugins_file.readlines()
2f8ae4d29bd95c298209a0cb93b5354c00186d6b
trackpy/C_fallback_python.py
trackpy/C_fallback_python.py
try: from _Cfilters import nullify_secondary_maxima except ImportError: import numpy as np # Because of the way C imports work, nullify_secondary_maxima # is *called*, as in nullify_secondary_maxima(). # For the pure Python variant, we do not want to call the function, # so we make nullify_secondary_maxima a wrapper than returns # the pure Python function that does the actual filtering. def _filter(a): target = a.size // 2 + 1 target_val = a[target] if np.any(a[:target] > target_val): return 0 if np.any(a[target + 1:] >= target_val): return 0 return target def nullify_secondary_maxima(): return _filter
try: from _Cfilters import nullify_secondary_maxima except ImportError: import numpy as np # Because of the way C imports work, nullify_secondary_maxima # is *called*, as in nullify_secondary_maxima(). # For the pure Python variant, we do not want to call the function, # so we make nullify_secondary_maxima a wrapper than returns # the pure Python function that does the actual filtering. def _filter(a): target = a.size // 2 target_val = a[target] if target_val == 0: return 0 # speedup trivial case if np.any(a[:target] > target_val): return 0 if np.any(a[target + 1:] >= target_val): return 0 return target_val def nullify_secondary_maxima(): return _filter
Fix and speedup pure-Python fallback for C filter.
BUG/PERF: Fix and speedup pure-Python fallback for C filter.
Python
bsd-3-clause
daniorerio/trackpy,daniorerio/trackpy
try: from _Cfilters import nullify_secondary_maxima except ImportError: import numpy as np # Because of the way C imports work, nullify_secondary_maxima # is *called*, as in nullify_secondary_maxima(). # For the pure Python variant, we do not want to call the function, # so we make nullify_secondary_maxima a wrapper than returns # the pure Python function that does the actual filtering. def _filter(a): - target = a.size // 2 + 1 + target = a.size // 2 target_val = a[target] + if target_val == 0: + return 0 # speedup trivial case if np.any(a[:target] > target_val): return 0 if np.any(a[target + 1:] >= target_val): return 0 - return target + return target_val def nullify_secondary_maxima(): return _filter
Fix and speedup pure-Python fallback for C filter.
## Code Before: try: from _Cfilters import nullify_secondary_maxima except ImportError: import numpy as np # Because of the way C imports work, nullify_secondary_maxima # is *called*, as in nullify_secondary_maxima(). # For the pure Python variant, we do not want to call the function, # so we make nullify_secondary_maxima a wrapper than returns # the pure Python function that does the actual filtering. def _filter(a): target = a.size // 2 + 1 target_val = a[target] if np.any(a[:target] > target_val): return 0 if np.any(a[target + 1:] >= target_val): return 0 return target def nullify_secondary_maxima(): return _filter ## Instruction: Fix and speedup pure-Python fallback for C filter. ## Code After: try: from _Cfilters import nullify_secondary_maxima except ImportError: import numpy as np # Because of the way C imports work, nullify_secondary_maxima # is *called*, as in nullify_secondary_maxima(). # For the pure Python variant, we do not want to call the function, # so we make nullify_secondary_maxima a wrapper than returns # the pure Python function that does the actual filtering. def _filter(a): target = a.size // 2 target_val = a[target] if target_val == 0: return 0 # speedup trivial case if np.any(a[:target] > target_val): return 0 if np.any(a[target + 1:] >= target_val): return 0 return target_val def nullify_secondary_maxima(): return _filter
0003ef7fe3d59c4bda034dee334d45b6d7a2622d
pyvm_test.py
pyvm_test.py
import pyvm import unittest class PyVMTest(unittest.TestCase): def setUp(self): self.vm = pyvm.PythonVM() def test_load_const_num(self): self.assertEqual( 10, self.vm.eval('10') ) def test_load_const_str(self): self.assertEqual( "hoge", self.vm.eval('"hoge"') ) if __name__ == '__main__': unittest.main()
import pyvm import unittest class PyVMTest(unittest.TestCase): def setUp(self): self.vm = pyvm.PythonVM() def test_load_const_num(self): self.assertEqual( 10, self.vm.eval('10') ) def test_load_const_num_float(self): self.assertEqual( 10.55, self.vm.eval('10.55') ) def test_load_const_str(self): self.assertEqual( "hoge", self.vm.eval('"hoge"') ) if __name__ == '__main__': unittest.main()
Add test of storing float
Add test of storing float
Python
mit
utgwkk/tiny-python-vm
import pyvm import unittest class PyVMTest(unittest.TestCase): def setUp(self): self.vm = pyvm.PythonVM() def test_load_const_num(self): self.assertEqual( 10, self.vm.eval('10') ) + def test_load_const_num_float(self): + self.assertEqual( + 10.55, + self.vm.eval('10.55') + ) + def test_load_const_str(self): self.assertEqual( "hoge", self.vm.eval('"hoge"') ) if __name__ == '__main__': unittest.main()
Add test of storing float
## Code Before: import pyvm import unittest class PyVMTest(unittest.TestCase): def setUp(self): self.vm = pyvm.PythonVM() def test_load_const_num(self): self.assertEqual( 10, self.vm.eval('10') ) def test_load_const_str(self): self.assertEqual( "hoge", self.vm.eval('"hoge"') ) if __name__ == '__main__': unittest.main() ## Instruction: Add test of storing float ## Code After: import pyvm import unittest class PyVMTest(unittest.TestCase): def setUp(self): self.vm = pyvm.PythonVM() def test_load_const_num(self): self.assertEqual( 10, self.vm.eval('10') ) def test_load_const_num_float(self): self.assertEqual( 10.55, self.vm.eval('10.55') ) def test_load_const_str(self): self.assertEqual( "hoge", self.vm.eval('"hoge"') ) if __name__ == '__main__': unittest.main()
66ba9aa2172fbed67b67a06acb331d449d32a33c
tests/services/shop/conftest.py
tests/services/shop/conftest.py
import pytest from byceps.services.shop.cart.models import Cart from byceps.services.shop.sequence import service as sequence_service from byceps.services.shop.shop import service as shop_service from testfixtures.shop_order import create_orderer from tests.helpers import create_user_with_detail @pytest.fixture def shop(email_config): return shop_service.create_shop('shop-01', 'Some Shop', email_config.id) @pytest.fixture def orderer(normal_user): user = create_user_with_detail('Besteller') return create_orderer(user) @pytest.fixture def empty_cart() -> Cart: return Cart() @pytest.fixture def order_number_sequence(shop) -> None: sequence_service.create_order_number_sequence(shop.id, 'order-')
import pytest from byceps.services.shop.cart.models import Cart from byceps.services.shop.sequence import service as sequence_service from byceps.services.shop.shop import service as shop_service from testfixtures.shop_order import create_orderer from tests.helpers import create_user_with_detail @pytest.fixture def shop(email_config): return shop_service.create_shop('shop-01', 'Some Shop', email_config.id) @pytest.fixture def orderer(): user = create_user_with_detail('Besteller') return create_orderer(user) @pytest.fixture def empty_cart() -> Cart: return Cart() @pytest.fixture def order_number_sequence(shop) -> None: sequence_service.create_order_number_sequence(shop.id, 'order-')
Remove unused fixture from orderer
Remove unused fixture from orderer
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
import pytest from byceps.services.shop.cart.models import Cart from byceps.services.shop.sequence import service as sequence_service from byceps.services.shop.shop import service as shop_service from testfixtures.shop_order import create_orderer from tests.helpers import create_user_with_detail @pytest.fixture def shop(email_config): return shop_service.create_shop('shop-01', 'Some Shop', email_config.id) @pytest.fixture - def orderer(normal_user): + def orderer(): user = create_user_with_detail('Besteller') return create_orderer(user) @pytest.fixture def empty_cart() -> Cart: return Cart() @pytest.fixture def order_number_sequence(shop) -> None: sequence_service.create_order_number_sequence(shop.id, 'order-')
Remove unused fixture from orderer
## Code Before: import pytest from byceps.services.shop.cart.models import Cart from byceps.services.shop.sequence import service as sequence_service from byceps.services.shop.shop import service as shop_service from testfixtures.shop_order import create_orderer from tests.helpers import create_user_with_detail @pytest.fixture def shop(email_config): return shop_service.create_shop('shop-01', 'Some Shop', email_config.id) @pytest.fixture def orderer(normal_user): user = create_user_with_detail('Besteller') return create_orderer(user) @pytest.fixture def empty_cart() -> Cart: return Cart() @pytest.fixture def order_number_sequence(shop) -> None: sequence_service.create_order_number_sequence(shop.id, 'order-') ## Instruction: Remove unused fixture from orderer ## Code After: import pytest from byceps.services.shop.cart.models import Cart from byceps.services.shop.sequence import service as sequence_service from byceps.services.shop.shop import service as shop_service from testfixtures.shop_order import create_orderer from tests.helpers import create_user_with_detail @pytest.fixture def shop(email_config): return shop_service.create_shop('shop-01', 'Some Shop', email_config.id) @pytest.fixture def orderer(): user = create_user_with_detail('Besteller') return create_orderer(user) @pytest.fixture def empty_cart() -> Cart: return Cart() @pytest.fixture def order_number_sequence(shop) -> None: sequence_service.create_order_number_sequence(shop.id, 'order-')
2e897f7dce89d4b52c3507c62e7120ee238b713c
database/database_setup.py
database/database_setup.py
from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from sqlalchemy import create_engine from models.base import Base from models.user import User from models.store import Store from models.product import Product engine = create_engine('sqlite:///productcatalog.db') Base.metadata.create_all(engine)
from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from sqlalchemy import create_engine from models.base import Base from models.user import User from models.store import Store from models.product import Product engine = create_engine('postgresql://catalog:catalog123!@localhost:8000/catalog') Base.metadata.create_all(engine)
Connect database engine to postgresql
feat: Connect database engine to postgresql
Python
mit
caasted/aws-flask-catalog-app,caasted/aws-flask-catalog-app
from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from sqlalchemy import create_engine from models.base import Base from models.user import User from models.store import Store from models.product import Product - engine = create_engine('sqlite:///productcatalog.db') + engine = create_engine('postgresql://catalog:catalog123!@localhost:8000/catalog') Base.metadata.create_all(engine)
Connect database engine to postgresql
## Code Before: from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from sqlalchemy import create_engine from models.base import Base from models.user import User from models.store import Store from models.product import Product engine = create_engine('sqlite:///productcatalog.db') Base.metadata.create_all(engine) ## Instruction: Connect database engine to postgresql ## Code After: from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from sqlalchemy import create_engine from models.base import Base from models.user import User from models.store import Store from models.product import Product engine = create_engine('postgresql://catalog:catalog123!@localhost:8000/catalog') Base.metadata.create_all(engine)
a8c8b136f081e3a2c7f1fd1f833a85288a358e42
vumi_http_retry/workers/api/validate.py
vumi_http_retry/workers/api/validate.py
import json from functools import wraps from twisted.web import http from jsonschema import Draft4Validator from vumi_http_retry.workers.api.utils import response def validate(*validators): def validator(fn): @wraps(fn) def wrapper(api, req, *a, **kw): errors = [] for v in validators: errors.extend(v(req, *a, **kw) or []) if not errors: return fn(api, req, *a, **kw) else: return response(req, {'errors': errors}, code=http.BAD_REQUEST) return wrapper return validator def has_header(name): def validator(req): if not req.requestHeaders.hasHeader(name): return [{ 'type': 'header_missing', 'message': "Header '%s' is missing" % (name,) }] else: return [] return validator def body_schema(schema): json_validator = Draft4Validator(schema) def validator(req, body): return [{ 'type': 'invalid_body', 'message': e.message } for e in json_validator.iter_errors(body)] return validator
import json from functools import wraps from twisted.web import http from jsonschema import Draft4Validator from vumi_http_retry.workers.api.utils import response def validate(*validators): def validator(fn): @wraps(fn) def wrapper(api, req, *a, **kw): errors = [] for v in validators: errors.extend(v(req, *a, **kw) or []) if not errors: return fn(api, req, *a, **kw) else: return response(req, {'errors': errors}, code=http.BAD_REQUEST) return wrapper return validator def has_header(name): def validator(req, *a, **kw): if not req.requestHeaders.hasHeader(name): return [{ 'type': 'header_missing', 'message': "Header '%s' is missing" % (name,) }] else: return [] return validator def body_schema(schema): json_validator = Draft4Validator(schema) def validator(req, body, *a, **kw): return [{ 'type': 'invalid_body', 'message': e.message } for e in json_validator.iter_errors(body)] return validator
Change validators to allow additional arguments to be given to the functions they are wrapping
Change validators to allow additional arguments to be given to the functions they are wrapping
Python
bsd-3-clause
praekelt/vumi-http-retry-api,praekelt/vumi-http-retry-api
import json from functools import wraps from twisted.web import http from jsonschema import Draft4Validator from vumi_http_retry.workers.api.utils import response def validate(*validators): def validator(fn): @wraps(fn) def wrapper(api, req, *a, **kw): errors = [] for v in validators: errors.extend(v(req, *a, **kw) or []) if not errors: return fn(api, req, *a, **kw) else: return response(req, {'errors': errors}, code=http.BAD_REQUEST) return wrapper return validator def has_header(name): - def validator(req): + def validator(req, *a, **kw): if not req.requestHeaders.hasHeader(name): return [{ 'type': 'header_missing', 'message': "Header '%s' is missing" % (name,) }] else: return [] return validator def body_schema(schema): json_validator = Draft4Validator(schema) - def validator(req, body): + def validator(req, body, *a, **kw): return [{ 'type': 'invalid_body', 'message': e.message } for e in json_validator.iter_errors(body)] return validator
Change validators to allow additional arguments to be given to the functions they are wrapping
## Code Before: import json from functools import wraps from twisted.web import http from jsonschema import Draft4Validator from vumi_http_retry.workers.api.utils import response def validate(*validators): def validator(fn): @wraps(fn) def wrapper(api, req, *a, **kw): errors = [] for v in validators: errors.extend(v(req, *a, **kw) or []) if not errors: return fn(api, req, *a, **kw) else: return response(req, {'errors': errors}, code=http.BAD_REQUEST) return wrapper return validator def has_header(name): def validator(req): if not req.requestHeaders.hasHeader(name): return [{ 'type': 'header_missing', 'message': "Header '%s' is missing" % (name,) }] else: return [] return validator def body_schema(schema): json_validator = Draft4Validator(schema) def validator(req, body): return [{ 'type': 'invalid_body', 'message': e.message } for e in json_validator.iter_errors(body)] return validator ## Instruction: Change validators to allow additional arguments to be given to the functions they are wrapping ## Code After: import json from functools import wraps from twisted.web import http from jsonschema import Draft4Validator from vumi_http_retry.workers.api.utils import response def validate(*validators): def validator(fn): @wraps(fn) def wrapper(api, req, *a, **kw): errors = [] for v in validators: errors.extend(v(req, *a, **kw) or []) if not errors: return fn(api, req, *a, **kw) else: return response(req, {'errors': errors}, code=http.BAD_REQUEST) return wrapper return validator def has_header(name): def validator(req, *a, **kw): if not req.requestHeaders.hasHeader(name): return [{ 'type': 'header_missing', 'message': "Header '%s' is missing" % (name,) }] else: return [] return validator def body_schema(schema): json_validator = Draft4Validator(schema) def validator(req, body, *a, **kw): return [{ 'type': 'invalid_body', 'message': e.message } for e in json_validator.iter_errors(body)] return validator
6f8b5950a85c79ed33c1d00a35a1def2efc7bff5
tests/conftest.py
tests/conftest.py
from factories import post_factory, post
from factories import post_factory, post import os import sys root = os.path.join(os.path.dirname(__file__)) package = os.path.join(root, '..') sys.path.insert(0, os.path.abspath(package))
Make the tests run just via py.test
Make the tests run just via py.test
Python
mit
kalasjocke/hyp
from factories import post_factory, post + import os + import sys + + root = os.path.join(os.path.dirname(__file__)) + package = os.path.join(root, '..') + sys.path.insert(0, os.path.abspath(package)) +
Make the tests run just via py.test
## Code Before: from factories import post_factory, post ## Instruction: Make the tests run just via py.test ## Code After: from factories import post_factory, post import os import sys root = os.path.join(os.path.dirname(__file__)) package = os.path.join(root, '..') sys.path.insert(0, os.path.abspath(package))
39c777d6fc5555534628113190bb543c6225c07e
uncurl/bin.py
uncurl/bin.py
from __future__ import print_function import sys from .api import parse def main(): result = parse(sys.argv[1]) print(result)
from __future__ import print_function import sys from .api import parse def main(): if sys.stdin.isatty(): result = parse(sys.argv[1]) else: result = parse(sys.stdin.read()) print(result)
Read from stdin if available.
Read from stdin if available.
Python
apache-2.0
weinerjm/uncurl,spulec/uncurl
from __future__ import print_function import sys from .api import parse def main(): + if sys.stdin.isatty(): - result = parse(sys.argv[1]) + result = parse(sys.argv[1]) + else: + result = parse(sys.stdin.read()) print(result)
Read from stdin if available.
## Code Before: from __future__ import print_function import sys from .api import parse def main(): result = parse(sys.argv[1]) print(result) ## Instruction: Read from stdin if available. ## Code After: from __future__ import print_function import sys from .api import parse def main(): if sys.stdin.isatty(): result = parse(sys.argv[1]) else: result = parse(sys.stdin.read()) print(result)
899f28e2cd7dbeb6227e8c56eef541cce1a424f4
alertaclient/commands/cmd_heartbeat.py
alertaclient/commands/cmd_heartbeat.py
import os import platform import sys import click prog = os.path.basename(sys.argv[0]) @click.command('heartbeat', short_help='Send a heartbeat') @click.option('--origin', default='{}/{}'.format(prog, platform.uname()[1])) @click.option('--tag', '-T', 'tags', multiple=True) @click.option('--timeout', metavar='EXPIRES', help='Seconds before heartbeat is stale') @click.option('--delete', '-D', metavar='ID', help='Delete hearbeat') @click.pass_obj def cli(obj, origin, tags, timeout, delete): """Send or delete a heartbeat.""" client = obj['client'] if delete: if origin or tags or timeout: raise click.UsageError('Option "--delete" is mutually exclusive.') client.delete_heartbeat(delete) else: try: heartbeat = client.heartbeat(origin=origin, tags=tags, timeout=timeout) except Exception as e: click.echo('ERROR: {}'.format(e)) sys.exit(1) click.echo(heartbeat.id)
import os import platform import sys import click prog = os.path.basename(sys.argv[0]) @click.command('heartbeat', short_help='Send a heartbeat') @click.option('--origin', default='{}/{}'.format(prog, platform.uname()[1])) @click.option('--tag', '-T', 'tags', multiple=True) @click.option('--timeout', metavar='EXPIRES', type=int, help='Seconds before heartbeat is stale') @click.option('--delete', '-D', metavar='ID', help='Delete hearbeat') @click.pass_obj def cli(obj, origin, tags, timeout, delete): """Send or delete a heartbeat.""" client = obj['client'] if delete: if origin or tags or timeout: raise click.UsageError('Option "--delete" is mutually exclusive.') client.delete_heartbeat(delete) else: try: heartbeat = client.heartbeat(origin=origin, tags=tags, timeout=timeout) except Exception as e: click.echo('ERROR: {}'.format(e)) sys.exit(1) click.echo(heartbeat.id)
Add check that heartbeat timeout is integer
Add check that heartbeat timeout is integer
Python
apache-2.0
alerta/python-alerta-client,alerta/python-alerta-client,alerta/python-alerta
import os import platform import sys import click prog = os.path.basename(sys.argv[0]) @click.command('heartbeat', short_help='Send a heartbeat') @click.option('--origin', default='{}/{}'.format(prog, platform.uname()[1])) @click.option('--tag', '-T', 'tags', multiple=True) - @click.option('--timeout', metavar='EXPIRES', help='Seconds before heartbeat is stale') + @click.option('--timeout', metavar='EXPIRES', type=int, help='Seconds before heartbeat is stale') @click.option('--delete', '-D', metavar='ID', help='Delete hearbeat') @click.pass_obj def cli(obj, origin, tags, timeout, delete): """Send or delete a heartbeat.""" client = obj['client'] if delete: if origin or tags or timeout: raise click.UsageError('Option "--delete" is mutually exclusive.') client.delete_heartbeat(delete) else: try: heartbeat = client.heartbeat(origin=origin, tags=tags, timeout=timeout) except Exception as e: click.echo('ERROR: {}'.format(e)) sys.exit(1) click.echo(heartbeat.id)
Add check that heartbeat timeout is integer
## Code Before: import os import platform import sys import click prog = os.path.basename(sys.argv[0]) @click.command('heartbeat', short_help='Send a heartbeat') @click.option('--origin', default='{}/{}'.format(prog, platform.uname()[1])) @click.option('--tag', '-T', 'tags', multiple=True) @click.option('--timeout', metavar='EXPIRES', help='Seconds before heartbeat is stale') @click.option('--delete', '-D', metavar='ID', help='Delete hearbeat') @click.pass_obj def cli(obj, origin, tags, timeout, delete): """Send or delete a heartbeat.""" client = obj['client'] if delete: if origin or tags or timeout: raise click.UsageError('Option "--delete" is mutually exclusive.') client.delete_heartbeat(delete) else: try: heartbeat = client.heartbeat(origin=origin, tags=tags, timeout=timeout) except Exception as e: click.echo('ERROR: {}'.format(e)) sys.exit(1) click.echo(heartbeat.id) ## Instruction: Add check that heartbeat timeout is integer ## Code After: import os import platform import sys import click prog = os.path.basename(sys.argv[0]) @click.command('heartbeat', short_help='Send a heartbeat') @click.option('--origin', default='{}/{}'.format(prog, platform.uname()[1])) @click.option('--tag', '-T', 'tags', multiple=True) @click.option('--timeout', metavar='EXPIRES', type=int, help='Seconds before heartbeat is stale') @click.option('--delete', '-D', metavar='ID', help='Delete hearbeat') @click.pass_obj def cli(obj, origin, tags, timeout, delete): """Send or delete a heartbeat.""" client = obj['client'] if delete: if origin or tags or timeout: raise click.UsageError('Option "--delete" is mutually exclusive.') client.delete_heartbeat(delete) else: try: heartbeat = client.heartbeat(origin=origin, tags=tags, timeout=timeout) except Exception as e: click.echo('ERROR: {}'.format(e)) sys.exit(1) click.echo(heartbeat.id)
ee8cb600c772e4a0f795a0fe00b1e612cb8a8e37
dirmuncher.py
dirmuncher.py
import os class Dirmuncher: def __init__(self, directory): self.directory = directory def directoryListing(self): for dirname, dirnames, filenames in os.walk(self.directory): # Subdirectories for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # Filenames for filename in filenames: print(os.path.join(dirname, filename)) if __name__ == "__main__": muncher = Dirmuncher('movies') muncher.directoryListing()
import os class Dirmuncher: def __init__(self, directory): self.directory = directory def getFiles(self): result = {} for dirname, dirnames, filenames in os.walk(self.directory): # Subdirectories for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # Filenames for filename in filenames: print(os.path.join(dirname, filename)) result[dirname] = filenames return result if __name__ == "__main__": muncher = Dirmuncher('movies') print(muncher.getFiles())
Sort files into dict with dir as key
[py] Sort files into dict with dir as key
Python
mit
claudemuller/masfir
import os class Dirmuncher: def __init__(self, directory): self.directory = directory - def directoryListing(self): + def getFiles(self): + result = {} + for dirname, dirnames, filenames in os.walk(self.directory): # Subdirectories for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # Filenames for filename in filenames: print(os.path.join(dirname, filename)) + result[dirname] = filenames + + return result + + if __name__ == "__main__": muncher = Dirmuncher('movies') - muncher.directoryListing() + print(muncher.getFiles())
Sort files into dict with dir as key
## Code Before: import os class Dirmuncher: def __init__(self, directory): self.directory = directory def directoryListing(self): for dirname, dirnames, filenames in os.walk(self.directory): # Subdirectories for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # Filenames for filename in filenames: print(os.path.join(dirname, filename)) if __name__ == "__main__": muncher = Dirmuncher('movies') muncher.directoryListing() ## Instruction: Sort files into dict with dir as key ## Code After: import os class Dirmuncher: def __init__(self, directory): self.directory = directory def getFiles(self): result = {} for dirname, dirnames, filenames in os.walk(self.directory): # Subdirectories for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # Filenames for filename in filenames: print(os.path.join(dirname, filename)) result[dirname] = filenames return result if __name__ == "__main__": muncher = Dirmuncher('movies') print(muncher.getFiles())
a5f60d664e7758b113abc31b405657952dd5eccd
tests/conftest.py
tests/conftest.py
import os import pytest from pywatson.watson import Watson @pytest.fixture def config(): """Get Watson configuration from the environment :return: dict with keys 'url', 'username', and 'password' """ try: return { 'url': os.environ['WATSON_URL'], 'username': os.environ['WATSON_USERNAME'], 'password': os.environ['WATSON_PASSWORD'] } except KeyError as err: raise Exception('You must set the environment variable {}'.format(err.args[0])) @pytest.fixture def watson(config): return Watson(url=config['url'], username=config['username'], password=config['password'])
import json import os import pytest from pywatson.watson import Watson @pytest.fixture def config(): """Get Watson configuration from the environment :return: dict with keys 'url', 'username', and 'password' """ try: return { 'url': os.environ['WATSON_URL'], 'username': os.environ['WATSON_USERNAME'], 'password': os.environ['WATSON_PASSWORD'] } except KeyError as err: raise Exception('You must set the environment variable {}'.format(err.args[0])) @pytest.fixture def watson(config): return Watson(url=config['url'], username=config['username'], password=config['password']) @pytest.fixture def questions(): qs = [] for root, dirs, files in os.walk('tests/json/questions'): for filename in files: filepath = os.path.join(root, filename) try: qs.append(json.load(open(filepath))) except ValueError: raise ValueError('Expected {} to contain valid JSON'.format(filepath)) return qs
Implement test data JSON loader
Implement test data JSON loader
Python
mit
sherlocke/pywatson
+ import json import os import pytest from pywatson.watson import Watson @pytest.fixture def config(): """Get Watson configuration from the environment :return: dict with keys 'url', 'username', and 'password' """ try: return { 'url': os.environ['WATSON_URL'], 'username': os.environ['WATSON_USERNAME'], 'password': os.environ['WATSON_PASSWORD'] } except KeyError as err: raise Exception('You must set the environment variable {}'.format(err.args[0])) @pytest.fixture def watson(config): return Watson(url=config['url'], username=config['username'], password=config['password']) + + @pytest.fixture + def questions(): + qs = [] + + for root, dirs, files in os.walk('tests/json/questions'): + for filename in files: + filepath = os.path.join(root, filename) + try: + qs.append(json.load(open(filepath))) + except ValueError: + raise ValueError('Expected {} to contain valid JSON'.format(filepath)) + + return qs +
Implement test data JSON loader
## Code Before: import os import pytest from pywatson.watson import Watson @pytest.fixture def config(): """Get Watson configuration from the environment :return: dict with keys 'url', 'username', and 'password' """ try: return { 'url': os.environ['WATSON_URL'], 'username': os.environ['WATSON_USERNAME'], 'password': os.environ['WATSON_PASSWORD'] } except KeyError as err: raise Exception('You must set the environment variable {}'.format(err.args[0])) @pytest.fixture def watson(config): return Watson(url=config['url'], username=config['username'], password=config['password']) ## Instruction: Implement test data JSON loader ## Code After: import json import os import pytest from pywatson.watson import Watson @pytest.fixture def config(): """Get Watson configuration from the environment :return: dict with keys 'url', 'username', and 'password' """ try: return { 'url': os.environ['WATSON_URL'], 'username': os.environ['WATSON_USERNAME'], 'password': os.environ['WATSON_PASSWORD'] } except KeyError as err: raise Exception('You must set the environment variable {}'.format(err.args[0])) @pytest.fixture def watson(config): return Watson(url=config['url'], username=config['username'], password=config['password']) @pytest.fixture def questions(): qs = [] for root, dirs, files in os.walk('tests/json/questions'): for filename in files: filepath = os.path.join(root, filename) try: qs.append(json.load(open(filepath))) except ValueError: raise ValueError('Expected {} to contain valid JSON'.format(filepath)) return qs
904db705daf24d68fcc9ac6010b55b93c7dc4544
txircd/modules/core/accounts.py
txircd/modules/core/accounts.py
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): return [ ("usercansetmetadata", 10, self.denyMetadataSet) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None accounts = Accounts()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements # Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html irc.RPL_LOGGEDIN = "900" irc.RPL_LOGGEDOUT = "901" class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): return [ ("usercansetmetadata", 10, self.denyMetadataSet), ("usermetadataupdate", 10, self.sendLoginNumeric) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer): if key == "account": if value is None: user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out") else: user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value)) accounts = Accounts()
Add automatic sending of 900/901 numerics for account status
Add automatic sending of 900/901 numerics for account status
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd
from twisted.plugin import IPlugin + from twisted.words.protocols import irc from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements + + # Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html + irc.RPL_LOGGEDIN = "900" + irc.RPL_LOGGEDOUT = "901" class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): - return [ ("usercansetmetadata", 10, self.denyMetadataSet) ] + return [ ("usercansetmetadata", 10, self.denyMetadataSet), + ("usermetadataupdate", 10, self.sendLoginNumeric) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None + + def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer): + if key == "account": + if value is None: + user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out") + else: + user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value)) accounts = Accounts()
Add automatic sending of 900/901 numerics for account status
## Code Before: from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): return [ ("usercansetmetadata", 10, self.denyMetadataSet) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None accounts = Accounts() ## Instruction: Add automatic sending of 900/901 numerics for account status ## Code After: from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements # Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html irc.RPL_LOGGEDIN = "900" irc.RPL_LOGGEDOUT = "901" class Accounts(ModuleData): implements(IPlugin, IModuleData) name = "Accounts" core = True def actions(self): return [ ("usercansetmetadata", 10, self.denyMetadataSet), ("usermetadataupdate", 10, self.sendLoginNumeric) ] def denyMetadataSet(self, key): if ircLower(key) == "account": return False return None def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer): if key == "account": if value is None: user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out") else: user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value)) accounts = Accounts()
ecc56eec0ebee4a93d5052280ae5d8c649e1e6da
tests/test_api.py
tests/test_api.py
from nose.tools import eq_ import mock from lcp import api @mock.patch('lcp.api.requests.request') def _assert_calls_requests_with_url(original_url, expected_url, request_mock): api.Client('BASE_URL').request('METHOD', original_url) expected_headers = {'Content-Type': 'application/json'} eq_(request_mock.call_args_list, [ mock.call('METHOD', expected_url, data='{}', headers=expected_headers)]) def test_request_does_not_alter_absolute_urls(): for absolute_url in [ 'http://www.points.com', 'https://www.points.com', ]: yield _assert_calls_requests_with_url, absolute_url, absolute_url def test_request_adds_base_url_to_relative_urls(): for absolute_url in [ 'some/relative/path/', '/some/absolute/path', ]: yield _assert_calls_requests_with_url, absolute_url, 'BASE_URL' + absolute_url
from nose.tools import eq_ import mock from lcp import api class TestApiClient(object): def setup(self): self.client = api.Client('BASE_URL') def test_request_does_not_alter_absolute_urls(self): for absolute_url in [ 'http://www.points.com', 'https://www.points.com', ]: yield self._assert_calls_requests_with_url, absolute_url, absolute_url def test_request_adds_base_url_to_relative_urls(self): for absolute_url in [ 'some/relative/path/', '/some/absolute/path', ]: yield self._assert_calls_requests_with_url, absolute_url, 'BASE_URL' + absolute_url @mock.patch('lcp.api.requests.request') def _assert_calls_requests_with_url(self, original_url, expected_url, request_mock): self.client.request('METHOD', original_url) expected_headers = {'Content-Type': 'application/json'} eq_(request_mock.call_args_list, [ mock.call('METHOD', expected_url, data='{}', headers=expected_headers)])
Refactor api test to setup test client in setup +review PLAT-127 DCORE-1109
Refactor api test to setup test client in setup +review PLAT-127 DCORE-1109
Python
bsd-3-clause
bradsokol/PyLCP,Points/PyLCP,bradsokol/PyLCP,Points/PyLCP
from nose.tools import eq_ import mock from lcp import api + class TestApiClient(object): + def setup(self): + self.client = api.Client('BASE_URL') - @mock.patch('lcp.api.requests.request') - def _assert_calls_requests_with_url(original_url, expected_url, request_mock): - api.Client('BASE_URL').request('METHOD', original_url) - expected_headers = {'Content-Type': 'application/json'} - eq_(request_mock.call_args_list, [ - mock.call('METHOD', expected_url, data='{}', headers=expected_headers)]) + def test_request_does_not_alter_absolute_urls(self): + for absolute_url in [ + 'http://www.points.com', + 'https://www.points.com', + ]: + yield self._assert_calls_requests_with_url, absolute_url, absolute_url - def test_request_does_not_alter_absolute_urls(): + def test_request_adds_base_url_to_relative_urls(self): - for absolute_url in [ + for absolute_url in [ - 'http://www.points.com', - 'https://www.points.com', + 'some/relative/path/', + '/some/absolute/path', - ]: + ]: - yield _assert_calls_requests_with_url, absolute_url, absolute_url + yield self._assert_calls_requests_with_url, absolute_url, 'BASE_URL' + absolute_url + @mock.patch('lcp.api.requests.request') + def _assert_calls_requests_with_url(self, original_url, expected_url, request_mock): + self.client.request('METHOD', original_url) + expected_headers = {'Content-Type': 'application/json'} + eq_(request_mock.call_args_list, [ + mock.call('METHOD', expected_url, data='{}', headers=expected_headers)]) - def test_request_adds_base_url_to_relative_urls(): - for absolute_url in [ - 'some/relative/path/', - '/some/absolute/path', - ]: - yield _assert_calls_requests_with_url, absolute_url, 'BASE_URL' + absolute_url -
Refactor api test to setup test client in setup +review PLAT-127 DCORE-1109
## Code Before: from nose.tools import eq_ import mock from lcp import api @mock.patch('lcp.api.requests.request') def _assert_calls_requests_with_url(original_url, expected_url, request_mock): api.Client('BASE_URL').request('METHOD', original_url) expected_headers = {'Content-Type': 'application/json'} eq_(request_mock.call_args_list, [ mock.call('METHOD', expected_url, data='{}', headers=expected_headers)]) def test_request_does_not_alter_absolute_urls(): for absolute_url in [ 'http://www.points.com', 'https://www.points.com', ]: yield _assert_calls_requests_with_url, absolute_url, absolute_url def test_request_adds_base_url_to_relative_urls(): for absolute_url in [ 'some/relative/path/', '/some/absolute/path', ]: yield _assert_calls_requests_with_url, absolute_url, 'BASE_URL' + absolute_url ## Instruction: Refactor api test to setup test client in setup +review PLAT-127 DCORE-1109 ## Code After: from nose.tools import eq_ import mock from lcp import api class TestApiClient(object): def setup(self): self.client = api.Client('BASE_URL') def test_request_does_not_alter_absolute_urls(self): for absolute_url in [ 'http://www.points.com', 'https://www.points.com', ]: yield self._assert_calls_requests_with_url, absolute_url, absolute_url def test_request_adds_base_url_to_relative_urls(self): for absolute_url in [ 'some/relative/path/', '/some/absolute/path', ]: yield self._assert_calls_requests_with_url, absolute_url, 'BASE_URL' + absolute_url @mock.patch('lcp.api.requests.request') def _assert_calls_requests_with_url(self, original_url, expected_url, request_mock): self.client.request('METHOD', original_url) expected_headers = {'Content-Type': 'application/json'} eq_(request_mock.call_args_list, [ mock.call('METHOD', expected_url, data='{}', headers=expected_headers)])
7bdfb1ef77d23bc868434e8d74d6184dd68c0a6e
tests/test_api.py
tests/test_api.py
from unittest import TestCase import inspect from pycurlbrowser.backend import * from pycurlbrowser import Browser def is_http_backend_derived(t): if t is HttpBackend: return False try: return HttpBackend in inspect.getmro(t) except AttributeError: return False def derived_types(): return [t for t in globals().values() if is_http_backend_derived(t)] class ApiTests(TestCase): def test_go(self): comp = inspect.getargspec(HttpBackend.go) for t in derived_types(): self.assertEqual(comp, inspect.getargspec(t.go), "Type %(t)s does not adhere to the spec %(s)s" % dict(t=t, s=comp)) def test_properties(self): comp = set(dir(HttpBackend)) for t in derived_types(): self.assertEqual(comp - set(dir(t)), set()) def test_properties_overriden(self): comp = dir(HttpBackend) for t in derived_types(): o = t() for p in comp: try: getattr(o, p) except NotImplementedError: raise NotImplementedError("Property '%(p)s' is not overriden for type %(t)s" % (dict(p=p, t=t))) except: pass
from unittest import TestCase import inspect from pycurlbrowser.backend import * from pycurlbrowser import Browser def is_http_backend_derived(t): if t is HttpBackend: return False try: return HttpBackend in inspect.getmro(t) except AttributeError: return False def derived_types(): return [t for t in globals().values() if is_http_backend_derived(t)] class ApiTests(TestCase): def test_go(self): def just_args(s): return dict(args=s.args, varargs=s.varargs) comp = just_args(inspect.getargspec(HttpBackend.go)) for t in derived_types(): sig = just_args(inspect.getargspec(t.go)) self.assertEqual(comp, sig, "Type %(t)s does not adhere to the spec %(spec)s with signature %(sig)s" % dict(t=t, spec=comp, sig=sig)) def test_properties(self): comp = set(dir(HttpBackend)) for t in derived_types(): self.assertEqual(comp - set(dir(t)), set()) def test_properties_overriden(self): comp = dir(HttpBackend) for t in derived_types(): o = t() for p in comp: try: getattr(o, p) except NotImplementedError: raise NotImplementedError("Property '%(p)s' is not overriden for type %(t)s" % (dict(p=p, t=t))) except: pass
Improve API test by only comparing args and varargs.
Improve API test by only comparing args and varargs.
Python
agpl-3.0
ahri/pycurlbrowser
from unittest import TestCase import inspect from pycurlbrowser.backend import * from pycurlbrowser import Browser def is_http_backend_derived(t): if t is HttpBackend: return False try: return HttpBackend in inspect.getmro(t) except AttributeError: return False def derived_types(): return [t for t in globals().values() if is_http_backend_derived(t)] class ApiTests(TestCase): def test_go(self): + def just_args(s): + return dict(args=s.args, varargs=s.varargs) + - comp = inspect.getargspec(HttpBackend.go) + comp = just_args(inspect.getargspec(HttpBackend.go)) for t in derived_types(): + sig = just_args(inspect.getargspec(t.go)) - self.assertEqual(comp, inspect.getargspec(t.go), "Type %(t)s does not adhere to the spec %(s)s" % dict(t=t, s=comp)) + self.assertEqual(comp, sig, "Type %(t)s does not adhere to the spec %(spec)s with signature %(sig)s" % dict(t=t, spec=comp, sig=sig)) def test_properties(self): comp = set(dir(HttpBackend)) for t in derived_types(): self.assertEqual(comp - set(dir(t)), set()) def test_properties_overriden(self): comp = dir(HttpBackend) for t in derived_types(): o = t() for p in comp: try: getattr(o, p) except NotImplementedError: raise NotImplementedError("Property '%(p)s' is not overriden for type %(t)s" % (dict(p=p, t=t))) except: pass
Improve API test by only comparing args and varargs.
## Code Before: from unittest import TestCase import inspect from pycurlbrowser.backend import * from pycurlbrowser import Browser def is_http_backend_derived(t): if t is HttpBackend: return False try: return HttpBackend in inspect.getmro(t) except AttributeError: return False def derived_types(): return [t for t in globals().values() if is_http_backend_derived(t)] class ApiTests(TestCase): def test_go(self): comp = inspect.getargspec(HttpBackend.go) for t in derived_types(): self.assertEqual(comp, inspect.getargspec(t.go), "Type %(t)s does not adhere to the spec %(s)s" % dict(t=t, s=comp)) def test_properties(self): comp = set(dir(HttpBackend)) for t in derived_types(): self.assertEqual(comp - set(dir(t)), set()) def test_properties_overriden(self): comp = dir(HttpBackend) for t in derived_types(): o = t() for p in comp: try: getattr(o, p) except NotImplementedError: raise NotImplementedError("Property '%(p)s' is not overriden for type %(t)s" % (dict(p=p, t=t))) except: pass ## Instruction: Improve API test by only comparing args and varargs. ## Code After: from unittest import TestCase import inspect from pycurlbrowser.backend import * from pycurlbrowser import Browser def is_http_backend_derived(t): if t is HttpBackend: return False try: return HttpBackend in inspect.getmro(t) except AttributeError: return False def derived_types(): return [t for t in globals().values() if is_http_backend_derived(t)] class ApiTests(TestCase): def test_go(self): def just_args(s): return dict(args=s.args, varargs=s.varargs) comp = just_args(inspect.getargspec(HttpBackend.go)) for t in derived_types(): sig = just_args(inspect.getargspec(t.go)) self.assertEqual(comp, sig, "Type %(t)s does not adhere to the spec %(spec)s with signature %(sig)s" % dict(t=t, spec=comp, sig=sig)) def test_properties(self): comp = set(dir(HttpBackend)) for t in derived_types(): self.assertEqual(comp - set(dir(t)), set()) def test_properties_overriden(self): comp = dir(HttpBackend) for t in derived_types(): o = t() for p in comp: try: getattr(o, p) except NotImplementedError: raise NotImplementedError("Property '%(p)s' is not overriden for type %(t)s" % (dict(p=p, t=t))) except: pass
1d4777f810388ee87cceb01c2b53367723fb3a71
PyFBA/cmd/__init__.py
PyFBA/cmd/__init__.py
from .citation import cite_me_please from .fluxes import measure_fluxes from .gapfill_from_roles import gapfill_from_roles from .assigned_functions_to_reactions import to_reactions from .fba_from_reactions import run_the_fba from .gapfill_from_reactions_multiple_conditions import gapfill_multiple_media from .media import list_media # Don't forget to add the imports here so that you can import * __all__ = [ 'cite_me_please', 'measure_fluxes', 'gapfill_from_roles', 'to_reactions', 'run_the_fba', 'gapfill_multiple_media', 'list_media' ]
from .citation import cite_me_please from .fluxes import measure_fluxes from .gapfill_from_roles import gapfill_from_roles from .assigned_functions_to_reactions import to_reactions from .fba_from_reactions import run_the_fba from .gapfill_from_reactions_multiple_conditions import gapfill_multiple_media from .media import list_media from .reactions_to_roles import convert_reactions_to_roles # Don't forget to add the imports here so that you can import * __all__ = [ 'cite_me_please', 'measure_fluxes', 'gapfill_from_roles', 'to_reactions', 'run_the_fba', 'gapfill_multiple_media', 'list_media', 'convert_reactions_to_roles' ]
Add a function to retrieve roles from reactions
Add a function to retrieve roles from reactions
Python
mit
linsalrob/PyFBA
from .citation import cite_me_please from .fluxes import measure_fluxes from .gapfill_from_roles import gapfill_from_roles from .assigned_functions_to_reactions import to_reactions from .fba_from_reactions import run_the_fba from .gapfill_from_reactions_multiple_conditions import gapfill_multiple_media from .media import list_media + from .reactions_to_roles import convert_reactions_to_roles # Don't forget to add the imports here so that you can import * __all__ = [ 'cite_me_please', 'measure_fluxes', 'gapfill_from_roles', 'to_reactions', 'run_the_fba', 'gapfill_multiple_media', - 'list_media' + 'list_media', 'convert_reactions_to_roles' ]
Add a function to retrieve roles from reactions
## Code Before: from .citation import cite_me_please from .fluxes import measure_fluxes from .gapfill_from_roles import gapfill_from_roles from .assigned_functions_to_reactions import to_reactions from .fba_from_reactions import run_the_fba from .gapfill_from_reactions_multiple_conditions import gapfill_multiple_media from .media import list_media # Don't forget to add the imports here so that you can import * __all__ = [ 'cite_me_please', 'measure_fluxes', 'gapfill_from_roles', 'to_reactions', 'run_the_fba', 'gapfill_multiple_media', 'list_media' ] ## Instruction: Add a function to retrieve roles from reactions ## Code After: from .citation import cite_me_please from .fluxes import measure_fluxes from .gapfill_from_roles import gapfill_from_roles from .assigned_functions_to_reactions import to_reactions from .fba_from_reactions import run_the_fba from .gapfill_from_reactions_multiple_conditions import gapfill_multiple_media from .media import list_media from .reactions_to_roles import convert_reactions_to_roles # Don't forget to add the imports here so that you can import * __all__ = [ 'cite_me_please', 'measure_fluxes', 'gapfill_from_roles', 'to_reactions', 'run_the_fba', 'gapfill_multiple_media', 'list_media', 'convert_reactions_to_roles' ]
6fd7f3cb01f621d2ea79e15188f8000c7b6fa361
tools/add_feed.py
tools/add_feed.py
import os from urllib.parse import urlencode, quote from autobit import Client def add_rarbg_feed(client, name, directory, filter_kwargs): url = 'http://localhost:5555/{}?{}'.format( quote(name), urlencode(filter_kwargs) ) return client.add_feed(name, url, directory) def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) name = input('name> ') directory = input('directory> ') os.makedirs(directory, exist_ok=True) if input('rarbg[yn]> ') == 'n': client.add_feed( name, input('url> '), directory ) else: add_rarbg_feed( client, name, directory, eval(input('filter dict> ')) ) if __name__ == '__main__': main()
import os from autobit import Client def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) client.get_torrents() name = input('name> ') directory = input('directory> ') os.makedirs(directory, exist_ok=True) client.add_feed( name, input('url> '), directory ) if __name__ == '__main__': main()
Remove code specific to my system
Remove code specific to my system
Python
mit
Mause/autobit
import os - from urllib.parse import urlencode, quote from autobit import Client - def add_rarbg_feed(client, name, directory, filter_kwargs): - url = 'http://localhost:5555/{}?{}'.format( - quote(name), - urlencode(filter_kwargs) - ) - - return client.add_feed(name, url, directory) - - def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) + client.get_torrents() name = input('name> ') directory = input('directory> ') os.makedirs(directory, exist_ok=True) - if input('rarbg[yn]> ') == 'n': - client.add_feed( + client.add_feed( - name, + name, - input('url> '), + input('url> '), - directory + directory + ) - ) - else: - add_rarbg_feed( - client, - name, - directory, - eval(input('filter dict> ')) - ) if __name__ == '__main__': main()
Remove code specific to my system
## Code Before: import os from urllib.parse import urlencode, quote from autobit import Client def add_rarbg_feed(client, name, directory, filter_kwargs): url = 'http://localhost:5555/{}?{}'.format( quote(name), urlencode(filter_kwargs) ) return client.add_feed(name, url, directory) def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) name = input('name> ') directory = input('directory> ') os.makedirs(directory, exist_ok=True) if input('rarbg[yn]> ') == 'n': client.add_feed( name, input('url> '), directory ) else: add_rarbg_feed( client, name, directory, eval(input('filter dict> ')) ) if __name__ == '__main__': main() ## Instruction: Remove code specific to my system ## Code After: import os from autobit import Client def main(): client = Client('http://localhost:8081/gui/', auth=('admin', '20133')) client.get_torrents() name = input('name> ') directory = input('directory> ') os.makedirs(directory, exist_ok=True) client.add_feed( name, input('url> '), directory ) if __name__ == '__main__': main()
894203d67e88e8bac8ec4f8948d940789387b648
tests/data/questions.py
tests/data/questions.py
QUESTIONS = [ { 'questionText': 'What is the Labour Code?' }, { 'questionText': 'When can a union start a strike?' } ]
QUESTIONS = [ { 'questionText': 'What is the Labour Code?' }, { 'questionText': 'When can a union start a strike?', 'items': 0, 'evidenceRequest': { 'items': 0, 'profile': '' }, 'answerAssertion': '', 'category': '', 'context': '', 'formattedAnswer': '', 'passthru': '', 'synonyms': '', 'lat': '', 'filters': [ { 'filterType': '', 'filterName': '', 'values': '' } ] } ]
Add all blank parameters to sample question
Add all blank parameters to sample question
Python
mit
sherlocke/pywatson
QUESTIONS = [ { 'questionText': 'What is the Labour Code?' }, { - 'questionText': 'When can a union start a strike?' + 'questionText': 'When can a union start a strike?', + 'items': 0, + 'evidenceRequest': { + 'items': 0, + 'profile': '' + }, + 'answerAssertion': '', + 'category': '', + 'context': '', + 'formattedAnswer': '', + 'passthru': '', + 'synonyms': '', + 'lat': '', + 'filters': [ + { + 'filterType': '', + 'filterName': '', + 'values': '' + } + ] } ]
Add all blank parameters to sample question
## Code Before: QUESTIONS = [ { 'questionText': 'What is the Labour Code?' }, { 'questionText': 'When can a union start a strike?' } ] ## Instruction: Add all blank parameters to sample question ## Code After: QUESTIONS = [ { 'questionText': 'What is the Labour Code?' }, { 'questionText': 'When can a union start a strike?', 'items': 0, 'evidenceRequest': { 'items': 0, 'profile': '' }, 'answerAssertion': '', 'category': '', 'context': '', 'formattedAnswer': '', 'passthru': '', 'synonyms': '', 'lat': '', 'filters': [ { 'filterType': '', 'filterName': '', 'values': '' } ] } ]
111d0bd356c18d0c028c73cd8c84c9d3e3ae591c
astropy/io/misc/asdf/tags/tests/helpers.py
astropy/io/misc/asdf/tags/tests/helpers.py
import os import urllib.parse import yaml import numpy as np def run_schema_example_test(organization, standard, name, version, check_func=None): import asdf from asdf.tests import helpers from asdf.types import format_tag from asdf.resolver import default_resolver tag = format_tag(organization, standard, version, name) schema_path = urllib.parse.urlparse(default_resolver(tag)).path with open(schema_path, 'rb') as ff: schema = yaml.load(ff) examples = [] for node in asdf.treeutil.iter_tree(schema): if (isinstance(node, dict) and 'examples' in node and isinstance(node['examples'], list)): for desc, example in node['examples']: examples.append(example) for example in examples: buff = helpers.yaml_to_asdf('example: ' + example.strip()) ff = asdf.AsdfFile(uri=schema_path) # Add some dummy blocks so that the ndarray examples work for i in range(3): b = asdf.block.Block(np.zeros((1024*1024*8), dtype=np.uint8)) b._used = True ff.blocks.add(b) ff._open_impl(ff, buff, mode='r') if check_func: check_func(ff)
import os import urllib.parse import urllib.request import yaml import numpy as np def run_schema_example_test(organization, standard, name, version, check_func=None): import asdf from asdf.tests import helpers from asdf.types import format_tag from asdf.resolver import default_tag_to_url_mapping from asdf.schema import load_schema tag = format_tag(organization, standard, version, name) uri = asdf.resolver.default_tag_to_url_mapping(tag) r = asdf.AsdfFile().resolver examples = [] schema = load_schema(uri, resolver=r) for node in asdf.treeutil.iter_tree(schema): if (isinstance(node, dict) and 'examples' in node and isinstance(node['examples'], list)): for desc, example in node['examples']: examples.append(example) for example in examples: buff = helpers.yaml_to_asdf('example: ' + example.strip()) ff = asdf.AsdfFile(uri=uri) # Add some dummy blocks so that the ndarray examples work for i in range(3): b = asdf.block.Block(np.zeros((1024*1024*8), dtype=np.uint8)) b._used = True ff.blocks.add(b) ff._open_impl(ff, buff, mode='r') if check_func: check_func(ff)
Fix ASDF tag test helper to load schemas correctly
Fix ASDF tag test helper to load schemas correctly
Python
bsd-3-clause
pllim/astropy,astropy/astropy,lpsinger/astropy,larrybradley/astropy,StuartLittlefair/astropy,mhvk/astropy,pllim/astropy,MSeifert04/astropy,saimn/astropy,dhomeier/astropy,lpsinger/astropy,pllim/astropy,stargaser/astropy,larrybradley/astropy,larrybradley/astropy,bsipocz/astropy,StuartLittlefair/astropy,astropy/astropy,dhomeier/astropy,bsipocz/astropy,pllim/astropy,astropy/astropy,mhvk/astropy,MSeifert04/astropy,StuartLittlefair/astropy,aleksandr-bakanov/astropy,bsipocz/astropy,lpsinger/astropy,mhvk/astropy,astropy/astropy,StuartLittlefair/astropy,larrybradley/astropy,aleksandr-bakanov/astropy,MSeifert04/astropy,saimn/astropy,stargaser/astropy,aleksandr-bakanov/astropy,lpsinger/astropy,dhomeier/astropy,astropy/astropy,dhomeier/astropy,pllim/astropy,StuartLittlefair/astropy,larrybradley/astropy,bsipocz/astropy,stargaser/astropy,mhvk/astropy,stargaser/astropy,aleksandr-bakanov/astropy,lpsinger/astropy,saimn/astropy,dhomeier/astropy,saimn/astropy,mhvk/astropy,saimn/astropy,MSeifert04/astropy
import os import urllib.parse + import urllib.request import yaml import numpy as np def run_schema_example_test(organization, standard, name, version, check_func=None): import asdf from asdf.tests import helpers from asdf.types import format_tag - from asdf.resolver import default_resolver + from asdf.resolver import default_tag_to_url_mapping + from asdf.schema import load_schema tag = format_tag(organization, standard, version, name) + uri = asdf.resolver.default_tag_to_url_mapping(tag) + r = asdf.AsdfFile().resolver - schema_path = urllib.parse.urlparse(default_resolver(tag)).path - - with open(schema_path, 'rb') as ff: - schema = yaml.load(ff) examples = [] + schema = load_schema(uri, resolver=r) for node in asdf.treeutil.iter_tree(schema): if (isinstance(node, dict) and 'examples' in node and isinstance(node['examples'], list)): for desc, example in node['examples']: examples.append(example) for example in examples: buff = helpers.yaml_to_asdf('example: ' + example.strip()) - ff = asdf.AsdfFile(uri=schema_path) + ff = asdf.AsdfFile(uri=uri) # Add some dummy blocks so that the ndarray examples work for i in range(3): b = asdf.block.Block(np.zeros((1024*1024*8), dtype=np.uint8)) b._used = True ff.blocks.add(b) ff._open_impl(ff, buff, mode='r') if check_func: check_func(ff)
Fix ASDF tag test helper to load schemas correctly
## Code Before: import os import urllib.parse import yaml import numpy as np def run_schema_example_test(organization, standard, name, version, check_func=None): import asdf from asdf.tests import helpers from asdf.types import format_tag from asdf.resolver import default_resolver tag = format_tag(organization, standard, version, name) schema_path = urllib.parse.urlparse(default_resolver(tag)).path with open(schema_path, 'rb') as ff: schema = yaml.load(ff) examples = [] for node in asdf.treeutil.iter_tree(schema): if (isinstance(node, dict) and 'examples' in node and isinstance(node['examples'], list)): for desc, example in node['examples']: examples.append(example) for example in examples: buff = helpers.yaml_to_asdf('example: ' + example.strip()) ff = asdf.AsdfFile(uri=schema_path) # Add some dummy blocks so that the ndarray examples work for i in range(3): b = asdf.block.Block(np.zeros((1024*1024*8), dtype=np.uint8)) b._used = True ff.blocks.add(b) ff._open_impl(ff, buff, mode='r') if check_func: check_func(ff) ## Instruction: Fix ASDF tag test helper to load schemas correctly ## Code After: import os import urllib.parse import urllib.request import yaml import numpy as np def run_schema_example_test(organization, standard, name, version, check_func=None): import asdf from asdf.tests import helpers from asdf.types import format_tag from asdf.resolver import default_tag_to_url_mapping from asdf.schema import load_schema tag = format_tag(organization, standard, version, name) uri = asdf.resolver.default_tag_to_url_mapping(tag) r = asdf.AsdfFile().resolver examples = [] schema = load_schema(uri, resolver=r) for node in asdf.treeutil.iter_tree(schema): if (isinstance(node, dict) and 'examples' in node and isinstance(node['examples'], list)): for desc, example in node['examples']: examples.append(example) for example in examples: buff = helpers.yaml_to_asdf('example: ' + example.strip()) ff = asdf.AsdfFile(uri=uri) # Add some dummy blocks so that the ndarray examples work for i in range(3): b = asdf.block.Block(np.zeros((1024*1024*8), dtype=np.uint8)) b._used = True ff.blocks.add(b) ff._open_impl(ff, buff, mode='r') if check_func: check_func(ff)
80c4b0fe0a654ef4ec56faac73af993408b846f1
test_client.py
test_client.py
from client import client import pytest def test_string_input(): assert client("String") == "You sent: String" def test_int_input(): assert client(42) == "You sent: 42" def test_empty_input(): with pytest.raises(TypeError): client() def test_over32_input(): assert client("A long message that will be over 32 bits but here's a few more")\ == "You sent: A long message that will be over 32 bits but here's a few more"
from client import client import pytest def test_response_ok(): msg = "GET /path/to/myindex.html HTTP/1.1\r\nHost: localhost:50000\r\n" result = "HTTP/1.1 200 OK\r\n" con_type = "Content-Type: text/plain\r\n" body = "Content length: {}".format(21) # Length of message from file name to end of line result = "{}{}{}".format(result, con_type, body) assert client(msg) == result
Add first test for a good response
Add first test for a good response
Python
mit
nbeck90/network_tools
from client import client import pytest - def test_string_input(): - assert client("String") == "You sent: String" + def test_response_ok(): + msg = "GET /path/to/myindex.html HTTP/1.1\r\nHost: localhost:50000\r\n" + result = "HTTP/1.1 200 OK\r\n" + con_type = "Content-Type: text/plain\r\n" + body = "Content length: {}".format(21) + # Length of message from file name to end of line + result = "{}{}{}".format(result, con_type, body) + assert client(msg) == result - - def test_int_input(): - assert client(42) == "You sent: 42" - - - def test_empty_input(): - with pytest.raises(TypeError): - client() - - - def test_over32_input(): - assert client("A long message that will be over 32 bits but here's a few more")\ - == "You sent: A long message that will be over 32 bits but here's a few more" -
Add first test for a good response
## Code Before: from client import client import pytest def test_string_input(): assert client("String") == "You sent: String" def test_int_input(): assert client(42) == "You sent: 42" def test_empty_input(): with pytest.raises(TypeError): client() def test_over32_input(): assert client("A long message that will be over 32 bits but here's a few more")\ == "You sent: A long message that will be over 32 bits but here's a few more" ## Instruction: Add first test for a good response ## Code After: from client import client import pytest def test_response_ok(): msg = "GET /path/to/myindex.html HTTP/1.1\r\nHost: localhost:50000\r\n" result = "HTTP/1.1 200 OK\r\n" con_type = "Content-Type: text/plain\r\n" body = "Content length: {}".format(21) # Length of message from file name to end of line result = "{}{}{}".format(result, con_type, body) assert client(msg) == result
f275c8cc020119b52ed01bc6b56946279853d854
src/mmw/apps/bigcz/clients/cuahsi/details.py
src/mmw/apps/bigcz/clients/cuahsi/details.py
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from datetime import date, timedelta from rest_framework.exceptions import ValidationError DATE_FORMAT = '%m/%d/%Y' def details(wsdl, site): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_site_info(wsdl, site) def values(wsdl, site, variable, from_date=None, to_date=None): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not variable: raise ValidationError({ 'error': 'Required argument: variable'}) if not to_date: # Set to default value of today to_date = date.today().strftime(DATE_FORMAT) if not from_date: # Set to default value of one week ago from_date = (date.today() - timedelta(days=7)).strftime(DATE_FORMAT) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_values(wsdl, site, variable, from_date, to_date)
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from datetime import date, timedelta from rest_framework.exceptions import ValidationError DATE_FORMAT = '%m/%d/%Y' def details(wsdl, site): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_site_info(wsdl, site, None) def values(wsdl, site, variable, from_date=None, to_date=None): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not variable: raise ValidationError({ 'error': 'Required argument: variable'}) if not to_date: # Set to default value of today to_date = date.today().strftime(DATE_FORMAT) if not from_date: # Set to default value of one week ago from_date = (date.today() - timedelta(days=7)).strftime(DATE_FORMAT) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_values(wsdl, site, variable, from_date, to_date, None)
Stop ulmo caching for suds-jurko compliance
Stop ulmo caching for suds-jurko compliance Previously we were using ulmo with suds-jurko 0.6, which is the current latest release, but it is 4 years old. Most recent work on suds-jurko has been done on the development branch, including optimizations to memory use (which we need). Unfortunately, the development branch also includes some breaking changes, including one which "cleans up" the caching module: https://bitbucket.org/jurko/suds/commits/6b24afe3206fc648605cc8d19f7c58c605d9df5f?at=default This change renames .setduration() to .__set_duration(), which is called by ulmo here: https://github.com/emiliom/ulmo/blob/90dbfe31f38a72ea4cee9a52e572cfa8f8484adc/ulmo/cuahsi/wof/core.py#L290 By explicitly setting the caching to None, we ensure that line isn't executed and those errors don't crop up. The performance improvements we get from using the development branch of suds-jurko outweigh the benefits of caching for one day, since it is unlikely we will be accessing the exact same content repeatedly.
Python
apache-2.0
WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from datetime import date, timedelta from rest_framework.exceptions import ValidationError DATE_FORMAT = '%m/%d/%Y' def details(wsdl, site): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof - return wof.get_site_info(wsdl, site) + return wof.get_site_info(wsdl, site, None) def values(wsdl, site, variable, from_date=None, to_date=None): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not variable: raise ValidationError({ 'error': 'Required argument: variable'}) if not to_date: # Set to default value of today to_date = date.today().strftime(DATE_FORMAT) if not from_date: # Set to default value of one week ago from_date = (date.today() - timedelta(days=7)).strftime(DATE_FORMAT) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof - return wof.get_values(wsdl, site, variable, from_date, to_date) + return wof.get_values(wsdl, site, variable, from_date, to_date, None)
Stop ulmo caching for suds-jurko compliance
## Code Before: from __future__ import print_function from __future__ import unicode_literals from __future__ import division from datetime import date, timedelta from rest_framework.exceptions import ValidationError DATE_FORMAT = '%m/%d/%Y' def details(wsdl, site): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_site_info(wsdl, site) def values(wsdl, site, variable, from_date=None, to_date=None): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not variable: raise ValidationError({ 'error': 'Required argument: variable'}) if not to_date: # Set to default value of today to_date = date.today().strftime(DATE_FORMAT) if not from_date: # Set to default value of one week ago from_date = (date.today() - timedelta(days=7)).strftime(DATE_FORMAT) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_values(wsdl, site, variable, from_date, to_date) ## Instruction: Stop ulmo caching for suds-jurko compliance ## Code After: from __future__ import print_function from __future__ import unicode_literals from __future__ import division from datetime import date, timedelta from rest_framework.exceptions import ValidationError DATE_FORMAT = '%m/%d/%Y' def details(wsdl, site): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_site_info(wsdl, site, None) def values(wsdl, site, variable, from_date=None, to_date=None): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not variable: raise ValidationError({ 'error': 'Required argument: variable'}) if not to_date: # Set to default value of today to_date = date.today().strftime(DATE_FORMAT) if not from_date: # Set to default value of one week ago from_date = (date.today() - timedelta(days=7)).strftime(DATE_FORMAT) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_values(wsdl, site, variable, from_date, to_date, None)
366316b0ea20ae178670581b61c52c481682d2b0
cosmic_ray/operators/exception_replacer.py
cosmic_ray/operators/exception_replacer.py
import ast import builtins from .operator import Operator class OutOfNoWhereException(Exception): pass setattr(builtins, OutOfNoWhereException.__name__, OutOfNoWhereException) class ExceptionReplacer(Operator): """An operator that modifies exception handlers.""" def visit_ExceptHandler(self, node): # noqa return self.visit_mutation_site(node) def mutate(self, node, _): """Modify the exception handler with another exception type.""" except_id = OutOfNoWhereException.__name__ except_type = ast.Name(id=except_id, ctx=ast.Load()) new_node = ast.ExceptHandler(type=except_type, name=node.name, body=node.body) return new_node
import ast import builtins from .operator import Operator class CosmicRayTestingException(Exception): pass setattr(builtins, CosmicRayTestingException.__name__, CosmicRayTestingException) class ExceptionReplacer(Operator): """An operator that modifies exception handlers.""" def visit_ExceptHandler(self, node): # noqa return self.visit_mutation_site(node) def mutate(self, node, _): """Modify the exception handler with another exception type.""" except_id = CosmicRayTestingException.__name__ except_type = ast.Name(id=except_id, ctx=ast.Load()) new_node = ast.ExceptHandler(type=except_type, name=node.name, body=node.body) return new_node
Change exception name to CosmicRayTestingException
Change exception name to CosmicRayTestingException
Python
mit
sixty-north/cosmic-ray
import ast import builtins from .operator import Operator - class OutOfNoWhereException(Exception): + class CosmicRayTestingException(Exception): pass - setattr(builtins, OutOfNoWhereException.__name__, OutOfNoWhereException) + setattr(builtins, CosmicRayTestingException.__name__, CosmicRayTestingException) class ExceptionReplacer(Operator): """An operator that modifies exception handlers.""" def visit_ExceptHandler(self, node): # noqa return self.visit_mutation_site(node) def mutate(self, node, _): """Modify the exception handler with another exception type.""" - except_id = OutOfNoWhereException.__name__ + except_id = CosmicRayTestingException.__name__ except_type = ast.Name(id=except_id, ctx=ast.Load()) new_node = ast.ExceptHandler(type=except_type, name=node.name, body=node.body) return new_node
Change exception name to CosmicRayTestingException
## Code Before: import ast import builtins from .operator import Operator class OutOfNoWhereException(Exception): pass setattr(builtins, OutOfNoWhereException.__name__, OutOfNoWhereException) class ExceptionReplacer(Operator): """An operator that modifies exception handlers.""" def visit_ExceptHandler(self, node): # noqa return self.visit_mutation_site(node) def mutate(self, node, _): """Modify the exception handler with another exception type.""" except_id = OutOfNoWhereException.__name__ except_type = ast.Name(id=except_id, ctx=ast.Load()) new_node = ast.ExceptHandler(type=except_type, name=node.name, body=node.body) return new_node ## Instruction: Change exception name to CosmicRayTestingException ## Code After: import ast import builtins from .operator import Operator class CosmicRayTestingException(Exception): pass setattr(builtins, CosmicRayTestingException.__name__, CosmicRayTestingException) class ExceptionReplacer(Operator): """An operator that modifies exception handlers.""" def visit_ExceptHandler(self, node): # noqa return self.visit_mutation_site(node) def mutate(self, node, _): """Modify the exception handler with another exception type.""" except_id = CosmicRayTestingException.__name__ except_type = ast.Name(id=except_id, ctx=ast.Load()) new_node = ast.ExceptHandler(type=except_type, name=node.name, body=node.body) return new_node
132309e91cc7e951d4a7f326d9e374dc8943f2f3
tests/core/providers/test_testrpc_provider.py
tests/core/providers/test_testrpc_provider.py
import pytest from web3.manager import ( RequestManager, ) from web3.providers.tester import ( TestRPCProvider, is_testrpc_available, ) from web3.utils.compat import socket def get_open_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) s.listen(1) port = s.getsockname()[1] s.close() return port @pytest.mark.skipif(not is_testrpc_available, reason="`eth-testrpc` is not installed") def test_making_provider_request(): from testrpc.rpc import RPCMethods provider = TestRPCProvider(port=get_open_port()) rm = RequestManager(None, provider) response = rm.request_blocking(method="web3_clientVersion", params=[]) assert response == RPCMethods.web3_clientVersion()
import pytest from web3.manager import ( RequestManager, ) from web3.providers.tester import ( TestRPCProvider as TheTestRPCProvider, is_testrpc_available, ) from web3.utils.compat import socket def get_open_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) s.listen(1) port = s.getsockname()[1] s.close() return port @pytest.mark.skipif(not is_testrpc_available, reason="`eth-testrpc` is not installed") def test_making_provider_request(): from testrpc.rpc import RPCMethods provider = TheTestRPCProvider(port=get_open_port()) rm = RequestManager(None, provider) response = rm.request_blocking(method="web3_clientVersion", params=[]) assert response == RPCMethods.web3_clientVersion()
Resolve pytest warning about TestRPCProvider
Resolve pytest warning about TestRPCProvider
Python
mit
pipermerriam/web3.py
import pytest from web3.manager import ( RequestManager, ) from web3.providers.tester import ( - TestRPCProvider, + TestRPCProvider as TheTestRPCProvider, is_testrpc_available, ) from web3.utils.compat import socket def get_open_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) s.listen(1) port = s.getsockname()[1] s.close() return port @pytest.mark.skipif(not is_testrpc_available, reason="`eth-testrpc` is not installed") def test_making_provider_request(): from testrpc.rpc import RPCMethods - provider = TestRPCProvider(port=get_open_port()) + provider = TheTestRPCProvider(port=get_open_port()) rm = RequestManager(None, provider) response = rm.request_blocking(method="web3_clientVersion", params=[]) assert response == RPCMethods.web3_clientVersion()
Resolve pytest warning about TestRPCProvider
## Code Before: import pytest from web3.manager import ( RequestManager, ) from web3.providers.tester import ( TestRPCProvider, is_testrpc_available, ) from web3.utils.compat import socket def get_open_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) s.listen(1) port = s.getsockname()[1] s.close() return port @pytest.mark.skipif(not is_testrpc_available, reason="`eth-testrpc` is not installed") def test_making_provider_request(): from testrpc.rpc import RPCMethods provider = TestRPCProvider(port=get_open_port()) rm = RequestManager(None, provider) response = rm.request_blocking(method="web3_clientVersion", params=[]) assert response == RPCMethods.web3_clientVersion() ## Instruction: Resolve pytest warning about TestRPCProvider ## Code After: import pytest from web3.manager import ( RequestManager, ) from web3.providers.tester import ( TestRPCProvider as TheTestRPCProvider, is_testrpc_available, ) from web3.utils.compat import socket def get_open_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) s.listen(1) port = s.getsockname()[1] s.close() return port @pytest.mark.skipif(not is_testrpc_available, reason="`eth-testrpc` is not installed") def test_making_provider_request(): from testrpc.rpc import RPCMethods provider = TheTestRPCProvider(port=get_open_port()) rm = RequestManager(None, provider) response = rm.request_blocking(method="web3_clientVersion", params=[]) assert response == RPCMethods.web3_clientVersion()
17e26fa55e70de657d52e340cb6b66691310a663
bettertexts/forms.py
bettertexts/forms.py
from django_comments.forms import CommentForm from django import forms from django.utils.translation import ugettext_lazy as _ from bettertexts.models import TextComment class TextCommentForm(CommentForm): def __init__(self, *args, **kwargs): super(TextCommentForm, self).__init__(*args, **kwargs) self.fields['name'].label = _("Name") self.fields['name'].required = True self.fields['email'].label = _("Email address") self.fields['email'].required = True self.fields['comment'].label = _('Comment') self.fields['comment'].required = True self.fields['url'].widget = forms.HiddenInput() inform = forms.BooleanField(required=False, label=_('Keep me informed'), widget=forms.CheckboxInput) involved = forms.BooleanField(required=False, label=_('Keep me involved'), widget=forms.CheckboxInput) class Meta: fields = ['name', 'email', 'inform', 'comment'] def get_comment_model(self): """ override to provide a custom comment model. """ return TextComment def get_comment_create_data(self): """ Override to add inform field """ data = super(TextCommentForm, self).get_comment_create_data() data.update({'inform': True}) return data
from django_comments.forms import CommentForm from django import forms from django.utils.translation import ugettext_lazy as _ from bettertexts.models import TextComment class TextCommentForm(CommentForm): def __init__(self, *args, **kwargs): super(TextCommentForm, self).__init__(*args, **kwargs) self.fields['name'].label = _("Name") self.fields['name'].required = True self.fields['email'].label = _("Email address") self.fields['email'].required = True self.fields['comment'].label = _('Comment') self.fields['comment'].required = True self.fields['url'].widget = forms.HiddenInput() inform = forms.BooleanField(required=False, label=_('Keep me informed'), widget=forms.CheckboxInput) involved = forms.BooleanField(required=False, label=_('Keep me involved'), widget=forms.CheckboxInput) class Meta: fields = ['name', 'email', 'inform', 'comment'] def get_comment_model(self): """ override to provide a custom comment model. """ return TextComment def get_comment_create_data(self): """ Override to add inform and involved field """ data = super(TextCommentForm, self).get_comment_create_data() data.update({'inform': self.cleaned_data["inform"], 'involved': self.cleaned_data["involved"]}) return data
Fix checkboxes inform and involved
CL011: Fix checkboxes inform and involved
Python
mit
citizenline/citizenline,citizenline/citizenline,citizenline/citizenline,citizenline/citizenline
from django_comments.forms import CommentForm from django import forms from django.utils.translation import ugettext_lazy as _ from bettertexts.models import TextComment class TextCommentForm(CommentForm): def __init__(self, *args, **kwargs): super(TextCommentForm, self).__init__(*args, **kwargs) self.fields['name'].label = _("Name") self.fields['name'].required = True self.fields['email'].label = _("Email address") self.fields['email'].required = True self.fields['comment'].label = _('Comment') self.fields['comment'].required = True self.fields['url'].widget = forms.HiddenInput() inform = forms.BooleanField(required=False, label=_('Keep me informed'), widget=forms.CheckboxInput) involved = forms.BooleanField(required=False, label=_('Keep me involved'), widget=forms.CheckboxInput) class Meta: fields = ['name', 'email', 'inform', 'comment'] def get_comment_model(self): """ override to provide a custom comment model. """ return TextComment def get_comment_create_data(self): """ - Override to add inform field + Override to add inform and involved field """ data = super(TextCommentForm, self).get_comment_create_data() - data.update({'inform': True}) + data.update({'inform': self.cleaned_data["inform"], + 'involved': self.cleaned_data["involved"]}) return data
Fix checkboxes inform and involved
## Code Before: from django_comments.forms import CommentForm from django import forms from django.utils.translation import ugettext_lazy as _ from bettertexts.models import TextComment class TextCommentForm(CommentForm): def __init__(self, *args, **kwargs): super(TextCommentForm, self).__init__(*args, **kwargs) self.fields['name'].label = _("Name") self.fields['name'].required = True self.fields['email'].label = _("Email address") self.fields['email'].required = True self.fields['comment'].label = _('Comment') self.fields['comment'].required = True self.fields['url'].widget = forms.HiddenInput() inform = forms.BooleanField(required=False, label=_('Keep me informed'), widget=forms.CheckboxInput) involved = forms.BooleanField(required=False, label=_('Keep me involved'), widget=forms.CheckboxInput) class Meta: fields = ['name', 'email', 'inform', 'comment'] def get_comment_model(self): """ override to provide a custom comment model. """ return TextComment def get_comment_create_data(self): """ Override to add inform field """ data = super(TextCommentForm, self).get_comment_create_data() data.update({'inform': True}) return data ## Instruction: Fix checkboxes inform and involved ## Code After: from django_comments.forms import CommentForm from django import forms from django.utils.translation import ugettext_lazy as _ from bettertexts.models import TextComment class TextCommentForm(CommentForm): def __init__(self, *args, **kwargs): super(TextCommentForm, self).__init__(*args, **kwargs) self.fields['name'].label = _("Name") self.fields['name'].required = True self.fields['email'].label = _("Email address") self.fields['email'].required = True self.fields['comment'].label = _('Comment') self.fields['comment'].required = True self.fields['url'].widget = forms.HiddenInput() inform = forms.BooleanField(required=False, label=_('Keep me informed'), widget=forms.CheckboxInput) involved = forms.BooleanField(required=False, label=_('Keep me involved'), widget=forms.CheckboxInput) class Meta: fields = ['name', 'email', 'inform', 'comment'] def get_comment_model(self): """ override to provide a custom comment model. """ return TextComment def get_comment_create_data(self): """ Override to add inform and involved field """ data = super(TextCommentForm, self).get_comment_create_data() data.update({'inform': self.cleaned_data["inform"], 'involved': self.cleaned_data["involved"]}) return data
ee66811628ea81e0540816e012c71d90457cc933
test/utils/filesystem/name_sanitizer_spec.py
test/utils/filesystem/name_sanitizer_spec.py
from tempfile import TemporaryDirectory from expects import expect from hypothesis import given, assume, example from hypothesis.strategies import text, characters from mamba import description, it from pathlib import Path from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \ invalid_filename_chars from test_utils.matchers import contain_any with description("AnkiDeckNameSanitizer"): with it("should remove all bad characters from the string"): expect(sanitize_anki_deck_name(invalid_filename_chars)) \ .not_to(contain_any(*invalid_filename_chars)) with it("should be possible to create a file name from a random sanitized string"): @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=254, min_size=1)) @example("line\n another one") def can_create(potential_name): assume(potential_name not in ('.', '..')) with TemporaryDirectory() as dir_name: Path(dir_name).joinpath(sanitize_anki_deck_name(potential_name)).mkdir() can_create()
from tempfile import TemporaryDirectory from expects import expect from hypothesis import given, assume, example from hypothesis.strategies import text, characters from mamba import description, it from pathlib import Path from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \ invalid_filename_chars from test_utils.matchers import contain_any size_limit = 255 def byte_length_size(sample): return len(bytes(sample, "utf-8")) <= size_limit with description("AnkiDeckNameSanitizer"): with it("should remove all bad characters from the string"): expect(sanitize_anki_deck_name(invalid_filename_chars)) \ .not_to(contain_any(*invalid_filename_chars)) with it("should be possible to create a file name from a random sanitized string"): @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=size_limit, min_size=1) .filter(byte_length_size)) @example("line\n another one") def can_create(potential_name): assume(potential_name not in ('.', '..')) with TemporaryDirectory() as dir_name: Path(dir_name).joinpath(sanitize_anki_deck_name(potential_name)).mkdir() can_create()
Add explicit example filtering based on the byte length of the content
Add explicit example filtering based on the byte length of the content
Python
mit
Stvad/CrowdAnki,Stvad/CrowdAnki,Stvad/CrowdAnki
from tempfile import TemporaryDirectory from expects import expect from hypothesis import given, assume, example from hypothesis.strategies import text, characters from mamba import description, it from pathlib import Path from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \ invalid_filename_chars from test_utils.matchers import contain_any + size_limit = 255 + + + def byte_length_size(sample): + return len(bytes(sample, "utf-8")) <= size_limit + + with description("AnkiDeckNameSanitizer"): with it("should remove all bad characters from the string"): expect(sanitize_anki_deck_name(invalid_filename_chars)) \ .not_to(contain_any(*invalid_filename_chars)) with it("should be possible to create a file name from a random sanitized string"): - @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=254, min_size=1)) + @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=size_limit, min_size=1) + .filter(byte_length_size)) @example("line\n another one") def can_create(potential_name): assume(potential_name not in ('.', '..')) with TemporaryDirectory() as dir_name: Path(dir_name).joinpath(sanitize_anki_deck_name(potential_name)).mkdir() can_create()
Add explicit example filtering based on the byte length of the content
## Code Before: from tempfile import TemporaryDirectory from expects import expect from hypothesis import given, assume, example from hypothesis.strategies import text, characters from mamba import description, it from pathlib import Path from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \ invalid_filename_chars from test_utils.matchers import contain_any with description("AnkiDeckNameSanitizer"): with it("should remove all bad characters from the string"): expect(sanitize_anki_deck_name(invalid_filename_chars)) \ .not_to(contain_any(*invalid_filename_chars)) with it("should be possible to create a file name from a random sanitized string"): @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=254, min_size=1)) @example("line\n another one") def can_create(potential_name): assume(potential_name not in ('.', '..')) with TemporaryDirectory() as dir_name: Path(dir_name).joinpath(sanitize_anki_deck_name(potential_name)).mkdir() can_create() ## Instruction: Add explicit example filtering based on the byte length of the content ## Code After: from tempfile import TemporaryDirectory from expects import expect from hypothesis import given, assume, example from hypothesis.strategies import text, characters from mamba import description, it from pathlib import Path from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \ invalid_filename_chars from test_utils.matchers import contain_any size_limit = 255 def byte_length_size(sample): return len(bytes(sample, "utf-8")) <= size_limit with description("AnkiDeckNameSanitizer"): with it("should remove all bad characters from the string"): expect(sanitize_anki_deck_name(invalid_filename_chars)) \ .not_to(contain_any(*invalid_filename_chars)) with it("should be possible to create a file name from a random sanitized string"): @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=size_limit, min_size=1) .filter(byte_length_size)) @example("line\n another one") def can_create(potential_name): assume(potential_name not in ('.', '..')) with TemporaryDirectory() as dir_name: Path(dir_name).joinpath(sanitize_anki_deck_name(potential_name)).mkdir() can_create()
729d3160f974c521ab6605c02cf64861be0fb6ab
fri/utils.py
fri/utils.py
import numpy as np def distance(u, v): """ Distance measure custom made for feature comparison. Parameters ---------- u: first feature v: second feature Returns ------- """ u = np.asarray(u) v = np.asarray(v) # Euclidean differences diff = (u - v) ** 2 # Nullify pairwise contribution diff[u == 0] = 0 diff[v == 0] = 0 return np.sqrt(np.sum(diff))
import numpy as np def distance(u, v): """ Distance measure custom made for feature comparison. Parameters ---------- u: first feature v: second feature Returns ------- """ u = np.asarray(u) v = np.asarray(v) # Euclidean differences diff = (u - v) ** 2 # Nullify pairwise contribution diff[u == 0] = 0 diff[v == 0] = 0 return np.sqrt(np.sum(diff)) def permutate_feature_in_data(data, feature_i, random_state): X, y = data X_copy = np.copy(X) # Permute selected feature permutated_feature = random_state.permutation(X_copy[:, feature_i]) # Add permutation back to dataset X_copy[:, feature_i] = permutated_feature return X_copy, y
Revert removal of necessary function
Revert removal of necessary function
Python
mit
lpfann/fri
import numpy as np def distance(u, v): """ Distance measure custom made for feature comparison. Parameters ---------- u: first feature v: second feature Returns ------- """ u = np.asarray(u) v = np.asarray(v) # Euclidean differences diff = (u - v) ** 2 # Nullify pairwise contribution diff[u == 0] = 0 diff[v == 0] = 0 return np.sqrt(np.sum(diff)) + + def permutate_feature_in_data(data, feature_i, random_state): + X, y = data + X_copy = np.copy(X) + # Permute selected feature + permutated_feature = random_state.permutation(X_copy[:, feature_i]) + # Add permutation back to dataset + X_copy[:, feature_i] = permutated_feature + return X_copy, y +
Revert removal of necessary function
## Code Before: import numpy as np def distance(u, v): """ Distance measure custom made for feature comparison. Parameters ---------- u: first feature v: second feature Returns ------- """ u = np.asarray(u) v = np.asarray(v) # Euclidean differences diff = (u - v) ** 2 # Nullify pairwise contribution diff[u == 0] = 0 diff[v == 0] = 0 return np.sqrt(np.sum(diff)) ## Instruction: Revert removal of necessary function ## Code After: import numpy as np def distance(u, v): """ Distance measure custom made for feature comparison. Parameters ---------- u: first feature v: second feature Returns ------- """ u = np.asarray(u) v = np.asarray(v) # Euclidean differences diff = (u - v) ** 2 # Nullify pairwise contribution diff[u == 0] = 0 diff[v == 0] = 0 return np.sqrt(np.sum(diff)) def permutate_feature_in_data(data, feature_i, random_state): X, y = data X_copy = np.copy(X) # Permute selected feature permutated_feature = random_state.permutation(X_copy[:, feature_i]) # Add permutation back to dataset X_copy[:, feature_i] = permutated_feature return X_copy, y
02522262692554a499d7c0fbc8f2efe4361023f1
bmi_ilamb/__init__.py
bmi_ilamb/__init__.py
import os from .bmi_ilamb import BmiIlamb __all__ = ['BmiIlamb'] __version__ = 0.1 package_dir = os.path.dirname(__file__) data_dir = os.path.join(package_dir, 'data')
import os from .bmi_ilamb import BmiIlamb from .config import Configuration __all__ = ['BmiIlamb', 'Configuration'] __version__ = 0.1 package_dir = os.path.dirname(__file__) data_dir = os.path.join(package_dir, 'data')
Add Configuration to package definition
Add Configuration to package definition
Python
mit
permamodel/bmi-ilamb
import os from .bmi_ilamb import BmiIlamb + from .config import Configuration - __all__ = ['BmiIlamb'] + __all__ = ['BmiIlamb', 'Configuration'] __version__ = 0.1 package_dir = os.path.dirname(__file__) data_dir = os.path.join(package_dir, 'data')
Add Configuration to package definition
## Code Before: import os from .bmi_ilamb import BmiIlamb __all__ = ['BmiIlamb'] __version__ = 0.1 package_dir = os.path.dirname(__file__) data_dir = os.path.join(package_dir, 'data') ## Instruction: Add Configuration to package definition ## Code After: import os from .bmi_ilamb import BmiIlamb from .config import Configuration __all__ = ['BmiIlamb', 'Configuration'] __version__ = 0.1 package_dir = os.path.dirname(__file__) data_dir = os.path.join(package_dir, 'data')
af2687703bc13eeabfe715e35988ad8c54ce9117
builds/format_json.py
builds/format_json.py
import json import os import subprocess import sys def find_json_files(): for root, _, filenames in os.walk('.'): if any( d in root for d in ['/WIP', '/.terraform', '/target'] ): continue for f in filenames: if f.lower().endswith('.json'): yield os.path.join(root, f) if __name__ == '__main__': bad_files = [] for f in find_json_files(): f_contents = open(f).read() try: data = json.loads(f_contents) except ValueError as err: print(f'[ERROR] {f} - Invalid JSON? {err}') bad_files.append(f) continue json_str = json.dumps(f_contents, indent=2, sort_keys=True) if json_str == f_contents: print(f'[OK] {f}') else: open(f, 'w').write(json_str) print(f'[FIXED] {f}') if bad_files: print('') print('Errors in the following files:') for f in bad_files: print(f'- {f}') sys.exit(1) else: sys.exit(0)
import json import os import subprocess import sys def find_json_files(): for root, _, filenames in os.walk('.'): if any( d in root for d in ['/WIP', '/.terraform', '/target'] ): continue for f in filenames: if f.lower().endswith('.json'): yield os.path.join(root, f) if __name__ == '__main__': bad_files = [] for f in find_json_files(): f_contents = open(f).read() try: data = json.loads(f_contents) except ValueError as err: print(f'[ERROR] {f} - Invalid JSON? {err}') bad_files.append(f) continue json_str = json.dumps(data, indent=2) + '\n' if json_str == f_contents: print(f'[OK] {f}') else: open(f, 'w').write(json_str) print(f'[FIXED] {f}') if bad_files: print('') print('Errors in the following files:') for f in bad_files: print(f'- {f}') sys.exit(1) else: sys.exit(0)
Tweak the JSON we export
Tweak the JSON we export
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
import json import os import subprocess import sys def find_json_files(): for root, _, filenames in os.walk('.'): if any( d in root for d in ['/WIP', '/.terraform', '/target'] ): continue for f in filenames: if f.lower().endswith('.json'): yield os.path.join(root, f) if __name__ == '__main__': bad_files = [] for f in find_json_files(): f_contents = open(f).read() try: data = json.loads(f_contents) except ValueError as err: print(f'[ERROR] {f} - Invalid JSON? {err}') bad_files.append(f) continue - json_str = json.dumps(f_contents, indent=2, sort_keys=True) + json_str = json.dumps(data, indent=2) + '\n' if json_str == f_contents: print(f'[OK] {f}') else: open(f, 'w').write(json_str) print(f'[FIXED] {f}') if bad_files: print('') print('Errors in the following files:') for f in bad_files: print(f'- {f}') sys.exit(1) else: sys.exit(0)
Tweak the JSON we export
## Code Before: import json import os import subprocess import sys def find_json_files(): for root, _, filenames in os.walk('.'): if any( d in root for d in ['/WIP', '/.terraform', '/target'] ): continue for f in filenames: if f.lower().endswith('.json'): yield os.path.join(root, f) if __name__ == '__main__': bad_files = [] for f in find_json_files(): f_contents = open(f).read() try: data = json.loads(f_contents) except ValueError as err: print(f'[ERROR] {f} - Invalid JSON? {err}') bad_files.append(f) continue json_str = json.dumps(f_contents, indent=2, sort_keys=True) if json_str == f_contents: print(f'[OK] {f}') else: open(f, 'w').write(json_str) print(f'[FIXED] {f}') if bad_files: print('') print('Errors in the following files:') for f in bad_files: print(f'- {f}') sys.exit(1) else: sys.exit(0) ## Instruction: Tweak the JSON we export ## Code After: import json import os import subprocess import sys def find_json_files(): for root, _, filenames in os.walk('.'): if any( d in root for d in ['/WIP', '/.terraform', '/target'] ): continue for f in filenames: if f.lower().endswith('.json'): yield os.path.join(root, f) if __name__ == '__main__': bad_files = [] for f in find_json_files(): f_contents = open(f).read() try: data = json.loads(f_contents) except ValueError as err: print(f'[ERROR] {f} - Invalid JSON? {err}') bad_files.append(f) continue json_str = json.dumps(data, indent=2) + '\n' if json_str == f_contents: print(f'[OK] {f}') else: open(f, 'w').write(json_str) print(f'[FIXED] {f}') if bad_files: print('') print('Errors in the following files:') for f in bad_files: print(f'- {f}') sys.exit(1) else: sys.exit(0)
0b5cc3f4702081eb565ef83c3175efc4e8b30e75
circuits/node/node.py
circuits/node/node.py
from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs['channel'] if 'channel' in kwargs else \ '%s_client_%s' % (self.channel, name) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
Fix channel definition in add method
Fix channel definition in add method
Python
mit
eriol/circuits,eriol/circuits,treemo/circuits,nizox/circuits,eriol/circuits,treemo/circuits,treemo/circuits
from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): + channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) - channel = kwargs['channel'] if 'channel' in kwargs else \ - '%s_client_%s' % (self.channel, name) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
Fix channel definition in add method
## Code Before: from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs['channel'] if 'channel' in kwargs else \ '%s_client_%s' % (self.channel, name) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e) ## Instruction: Fix channel definition in add method ## Code After: from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
3234d929d22d7504d89753ce6351d0efe1bfa8ac
whitepy/lexer.py
whitepy/lexer.py
from .lexerconstants import * from .ws_token import Tokeniser class Lexer(object): def __init__(self, line): self.line = line self.pos = 0 self.tokens = [] def _get_int(self): token = Tokeniser() if self.line[-1] == '\n': const = 'INT' token.scan(self.line, self.pos, const) else: # TODO: Add error handling for invalid integer pass return token def _get_token(self, const): token = Tokeniser() token.scan(self.line, self.pos, const) return token def get_all_tokens(self): while self.pos < len(self.line): const = IMP_CONST if self.pos is 0 else eval( "{}_CONST".format(self.tokens[0].type)) token = self._get_token(const) self.tokens.append(token) self.pos = self.pos + len(token.value) if token.type == 'PUSH': self.tokens.append(self._get_int()) self.pos = len(self.line)
from .lexerconstants import * from .ws_token import Tokeniser class IntError(ValueError): '''Exception when invalid integer is found''' class Lexer(object): def __init__(self, line): self.line = line self.pos = 0 self.tokens = [] def _get_int(self): token = Tokeniser() if self.line[-1] == '\n': const = 'INT' token.scan(self.line, self.pos, const) else: raise IntError return token def _get_token(self, const): token = Tokeniser() token.scan(self.line, self.pos, const) return token def get_all_tokens(self): while self.pos < len(self.line): const = IMP_CONST if self.pos is 0 else eval( "{}_CONST".format(self.tokens[0].type)) token = self._get_token(const) self.tokens.append(token) self.pos = self.pos + len(token.value) if token.type == 'PUSH': self.tokens.append(self._get_int()) self.pos = len(self.line)
Add Execption for invalid Integer
Add Execption for invalid Integer Exception class created for invalid integer and raise it if a bad integer is found
Python
apache-2.0
yasn77/whitepy
from .lexerconstants import * from .ws_token import Tokeniser + + + class IntError(ValueError): + '''Exception when invalid integer is found''' class Lexer(object): def __init__(self, line): self.line = line self.pos = 0 self.tokens = [] def _get_int(self): token = Tokeniser() if self.line[-1] == '\n': const = 'INT' token.scan(self.line, self.pos, const) else: + raise IntError - # TODO: Add error handling for invalid integer - pass return token def _get_token(self, const): token = Tokeniser() token.scan(self.line, self.pos, const) return token def get_all_tokens(self): while self.pos < len(self.line): const = IMP_CONST if self.pos is 0 else eval( "{}_CONST".format(self.tokens[0].type)) token = self._get_token(const) self.tokens.append(token) self.pos = self.pos + len(token.value) if token.type == 'PUSH': self.tokens.append(self._get_int()) self.pos = len(self.line)
Add Execption for invalid Integer
## Code Before: from .lexerconstants import * from .ws_token import Tokeniser class Lexer(object): def __init__(self, line): self.line = line self.pos = 0 self.tokens = [] def _get_int(self): token = Tokeniser() if self.line[-1] == '\n': const = 'INT' token.scan(self.line, self.pos, const) else: # TODO: Add error handling for invalid integer pass return token def _get_token(self, const): token = Tokeniser() token.scan(self.line, self.pos, const) return token def get_all_tokens(self): while self.pos < len(self.line): const = IMP_CONST if self.pos is 0 else eval( "{}_CONST".format(self.tokens[0].type)) token = self._get_token(const) self.tokens.append(token) self.pos = self.pos + len(token.value) if token.type == 'PUSH': self.tokens.append(self._get_int()) self.pos = len(self.line) ## Instruction: Add Execption for invalid Integer ## Code After: from .lexerconstants import * from .ws_token import Tokeniser class IntError(ValueError): '''Exception when invalid integer is found''' class Lexer(object): def __init__(self, line): self.line = line self.pos = 0 self.tokens = [] def _get_int(self): token = Tokeniser() if self.line[-1] == '\n': const = 'INT' token.scan(self.line, self.pos, const) else: raise IntError return token def _get_token(self, const): token = Tokeniser() token.scan(self.line, self.pos, const) return token def get_all_tokens(self): while self.pos < len(self.line): const = IMP_CONST if self.pos is 0 else eval( "{}_CONST".format(self.tokens[0].type)) token = self._get_token(const) self.tokens.append(token) self.pos = self.pos + len(token.value) if token.type == 'PUSH': self.tokens.append(self._get_int()) self.pos = len(self.line)
9d0ea4eaf8269350fabc3415545bebf4da4137a7
source/segue/backend/processor/background.py
source/segue/backend/processor/background.py
import multiprocessing from .base import Processor class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' process = multiprocessing.Process(target=command, args=args, kwargs=kw) process.start() process.join()
import multiprocessing from .base import Processor class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' if args is None: args = () if kw is None: kw = {} process = multiprocessing.Process(target=command, args=args, kwargs=kw) process.start() process.join()
Fix passing invalid None to multiprocessing Process class.
Fix passing invalid None to multiprocessing Process class.
Python
apache-2.0
4degrees/segue
import multiprocessing from .base import Processor class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' + if args is None: + args = () + + if kw is None: + kw = {} + process = multiprocessing.Process(target=command, args=args, kwargs=kw) process.start() process.join()
Fix passing invalid None to multiprocessing Process class.
## Code Before: import multiprocessing from .base import Processor class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' process = multiprocessing.Process(target=command, args=args, kwargs=kw) process.start() process.join() ## Instruction: Fix passing invalid None to multiprocessing Process class. ## Code After: import multiprocessing from .base import Processor class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' if args is None: args = () if kw is None: kw = {} process = multiprocessing.Process(target=command, args=args, kwargs=kw) process.start() process.join()
cb1af2160952c7065e236d2cd544f46e5b252e92
account_partner_account_summary/__openerp__.py
account_partner_account_summary/__openerp__.py
{ 'name': 'Partner Account Summary', 'version': '1.0', 'description': """Partner Account Summary""", 'category': 'Aeroo Reporting', 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'depends': [ 'sale', 'report_aeroo', ], 'data': [ 'wizard/account_summary_wizard_view.xml', 'report/account_summary_report.xml'], 'demo': [ ], 'test': [ ], 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
{ 'name': 'Partner Account Summary', 'version': '1.0', 'description': """Partner Account Summary""", 'category': 'Aeroo Reporting', 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'depends': [ 'sale', 'report_aeroo', 'l10n_ar_invoice', ], 'data': [ 'wizard/account_summary_wizard_view.xml', 'report/account_summary_report.xml'], 'demo': [ ], 'test': [ ], 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
ADD dependency of l10n_ar_invoice for account summary
ADD dependency of l10n_ar_invoice for account summary
Python
agpl-3.0
maljac/odoo-addons,adhoc-dev/odoo-addons,syci/ingadhoc-odoo-addons,dvitme/odoo-addons,ingadhoc/account-payment,jorsea/odoo-addons,ingadhoc/stock,jorsea/odoo-addons,ingadhoc/account-financial-tools,sysadminmatmoz/ingadhoc,levkar/odoo-addons,syci/ingadhoc-odoo-addons,ingadhoc/partner,ingadhoc/product,ClearCorp/account-financial-tools,ingadhoc/sale,levkar/odoo-addons,levkar/odoo-addons,jorsea/odoo-addons,syci/ingadhoc-odoo-addons,HBEE/odoo-addons,levkar/odoo-addons,ingadhoc/account-invoicing,ingadhoc/sale,ingadhoc/product,ingadhoc/odoo-addons,ingadhoc/odoo-addons,adhoc-dev/account-financial-tools,dvitme/odoo-addons,maljac/odoo-addons,ingadhoc/sale,ingadhoc/odoo-addons,bmya/odoo-addons,bmya/odoo-addons,sysadminmatmoz/ingadhoc,bmya/odoo-addons,HBEE/odoo-addons,HBEE/odoo-addons,sysadminmatmoz/ingadhoc,ClearCorp/account-financial-tools,dvitme/odoo-addons,adhoc-dev/odoo-addons,adhoc-dev/account-financial-tools,ingadhoc/account-analytic,maljac/odoo-addons,adhoc-dev/odoo-addons,ingadhoc/sale
{ 'name': 'Partner Account Summary', 'version': '1.0', 'description': """Partner Account Summary""", 'category': 'Aeroo Reporting', 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'depends': [ 'sale', 'report_aeroo', + 'l10n_ar_invoice', ], 'data': [ 'wizard/account_summary_wizard_view.xml', 'report/account_summary_report.xml'], 'demo': [ ], 'test': [ ], 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
ADD dependency of l10n_ar_invoice for account summary
## Code Before: { 'name': 'Partner Account Summary', 'version': '1.0', 'description': """Partner Account Summary""", 'category': 'Aeroo Reporting', 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'depends': [ 'sale', 'report_aeroo', ], 'data': [ 'wizard/account_summary_wizard_view.xml', 'report/account_summary_report.xml'], 'demo': [ ], 'test': [ ], 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: ## Instruction: ADD dependency of l10n_ar_invoice for account summary ## Code After: { 'name': 'Partner Account Summary', 'version': '1.0', 'description': """Partner Account Summary""", 'category': 'Aeroo Reporting', 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'depends': [ 'sale', 'report_aeroo', 'l10n_ar_invoice', ], 'data': [ 'wizard/account_summary_wizard_view.xml', 'report/account_summary_report.xml'], 'demo': [ ], 'test': [ ], 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
517d25cf79c4d04661309ab7b3ab0638a2f968ee
api/docbleach/utils/__init__.py
api/docbleach/utils/__init__.py
import os import random import string def secure_uuid(): """ Strength: 6*3 random characters from a list of 62, approx. 64^18 possible strings, or 2^100. Should be enough to prevent a successful bruteforce, as download links are only valid for 3 hours :return: """ return id_generator() + "-" + id_generator() + "-" + id_generator() def id_generator(size=6, chars=string.ascii_letters + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def static(*args): return os.path.join('static', *args)
import os import string from random import SystemRandom cryptogen = SystemRandom() def secure_uuid(): """ Strength: 6*3 random characters from a list of 62, approx. 64^18 possible strings, or 2^100. Should be enough to prevent a successful bruteforce, as download links are only valid for 3 hours :return: """ return id_generator() + "-" + id_generator() + "-" + id_generator() def id_generator(size=6, chars=string.ascii_letters + string.digits): return ''.join(cryptogen.choice(chars) for _ in range(size)) def static(*args): return os.path.join('static', *args)
Use SystemRandom to generate security-viable randomness
Use SystemRandom to generate security-viable randomness
Python
mit
docbleach/DocBleach-Web,docbleach/DocBleach-Web,docbleach/DocBleach-Web,docbleach/DocBleach-Web
import os - import random import string + from random import SystemRandom + + cryptogen = SystemRandom() def secure_uuid(): """ Strength: 6*3 random characters from a list of 62, approx. 64^18 possible strings, or 2^100. Should be enough to prevent a successful bruteforce, as download links are only valid for 3 hours :return: """ return id_generator() + "-" + id_generator() + "-" + id_generator() def id_generator(size=6, chars=string.ascii_letters + string.digits): - return ''.join(random.choice(chars) for _ in range(size)) + return ''.join(cryptogen.choice(chars) for _ in range(size)) def static(*args): return os.path.join('static', *args)
Use SystemRandom to generate security-viable randomness
## Code Before: import os import random import string def secure_uuid(): """ Strength: 6*3 random characters from a list of 62, approx. 64^18 possible strings, or 2^100. Should be enough to prevent a successful bruteforce, as download links are only valid for 3 hours :return: """ return id_generator() + "-" + id_generator() + "-" + id_generator() def id_generator(size=6, chars=string.ascii_letters + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def static(*args): return os.path.join('static', *args) ## Instruction: Use SystemRandom to generate security-viable randomness ## Code After: import os import string from random import SystemRandom cryptogen = SystemRandom() def secure_uuid(): """ Strength: 6*3 random characters from a list of 62, approx. 64^18 possible strings, or 2^100. Should be enough to prevent a successful bruteforce, as download links are only valid for 3 hours :return: """ return id_generator() + "-" + id_generator() + "-" + id_generator() def id_generator(size=6, chars=string.ascii_letters + string.digits): return ''.join(cryptogen.choice(chars) for _ in range(size)) def static(*args): return os.path.join('static', *args)
a4df3f966e232e8327522a3db32870f5dcea0c03
cartridge/shop/middleware.py
cartridge/shop/middleware.py
from mezzanine.conf import settings from cartridge.shop.models import Cart class ShopMiddleware(object): def __init__(self): old = ("SHOP_SSL_ENABLED", "SHOP_FORCE_HOST", "SHOP_FORCE_SSL_VIEWS") for name in old: try: getattr(settings, name) except AttributeError: pass else: import warnings warnings.warn("The settings %s are deprecated; " "use SSL_ENABLED, SSL_FORCE_HOST and " "SSL_FORCE_URL_PREFIXES, and add " "mezzanine.core.middleware.SSLRedirectMiddleware to " "MIDDLEWARE_CLASSES." % ", ".join(old)) break def process_request(self, request): """ Adds cart and wishlist attributes to the current request. """ request.cart = Cart.objects.from_request(request) wishlist = request.COOKIES.get("wishlist", "").split(",") if not wishlist[0]: wishlist = [] request.wishlist = wishlist
from mezzanine.conf import settings from cartridge.shop.models import Cart class SSLRedirect(object): def __init__(self): old = ("SHOP_SSL_ENABLED", "SHOP_FORCE_HOST", "SHOP_FORCE_SSL_VIEWS") for name in old: try: getattr(settings, name) except AttributeError: pass else: import warnings warnings.warn("The settings %s are deprecated; " "use SSL_ENABLED, SSL_FORCE_HOST and " "SSL_FORCE_URL_PREFIXES, and add " "mezzanine.core.middleware.SSLRedirectMiddleware to " "MIDDLEWARE_CLASSES." % ", ".join(old)) break class ShopMiddleware(SSLRedirect): """ Adds cart and wishlist attributes to the current request. """ def process_request(self, request): request.cart = Cart.objects.from_request(request) wishlist = request.COOKIES.get("wishlist", "").split(",") if not wishlist[0]: wishlist = [] request.wishlist = wishlist
Add deprecated fallback for SSLMiddleware.
Add deprecated fallback for SSLMiddleware.
Python
bsd-2-clause
traxxas/cartridge,traxxas/cartridge,Parisson/cartridge,Kniyl/cartridge,syaiful6/cartridge,jaywink/cartridge-reservable,wbtuomela/cartridge,syaiful6/cartridge,ryneeverett/cartridge,wbtuomela/cartridge,dsanders11/cartridge,wbtuomela/cartridge,dsanders11/cartridge,wyzex/cartridge,jaywink/cartridge-reservable,Parisson/cartridge,viaregio/cartridge,ryneeverett/cartridge,jaywink/cartridge-reservable,Kniyl/cartridge,traxxas/cartridge,wyzex/cartridge,wyzex/cartridge,stephenmcd/cartridge,Parisson/cartridge,dsanders11/cartridge,stephenmcd/cartridge,ryneeverett/cartridge,viaregio/cartridge,stephenmcd/cartridge,syaiful6/cartridge,Kniyl/cartridge
from mezzanine.conf import settings from cartridge.shop.models import Cart - class ShopMiddleware(object): + class SSLRedirect(object): def __init__(self): old = ("SHOP_SSL_ENABLED", "SHOP_FORCE_HOST", "SHOP_FORCE_SSL_VIEWS") for name in old: try: getattr(settings, name) except AttributeError: pass else: import warnings warnings.warn("The settings %s are deprecated; " "use SSL_ENABLED, SSL_FORCE_HOST and " "SSL_FORCE_URL_PREFIXES, and add " "mezzanine.core.middleware.SSLRedirectMiddleware to " "MIDDLEWARE_CLASSES." % ", ".join(old)) break + + class ShopMiddleware(SSLRedirect): + """ + Adds cart and wishlist attributes to the current request. + """ def process_request(self, request): - """ - Adds cart and wishlist attributes to the current request. - """ request.cart = Cart.objects.from_request(request) wishlist = request.COOKIES.get("wishlist", "").split(",") if not wishlist[0]: wishlist = [] request.wishlist = wishlist
Add deprecated fallback for SSLMiddleware.
## Code Before: from mezzanine.conf import settings from cartridge.shop.models import Cart class ShopMiddleware(object): def __init__(self): old = ("SHOP_SSL_ENABLED", "SHOP_FORCE_HOST", "SHOP_FORCE_SSL_VIEWS") for name in old: try: getattr(settings, name) except AttributeError: pass else: import warnings warnings.warn("The settings %s are deprecated; " "use SSL_ENABLED, SSL_FORCE_HOST and " "SSL_FORCE_URL_PREFIXES, and add " "mezzanine.core.middleware.SSLRedirectMiddleware to " "MIDDLEWARE_CLASSES." % ", ".join(old)) break def process_request(self, request): """ Adds cart and wishlist attributes to the current request. """ request.cart = Cart.objects.from_request(request) wishlist = request.COOKIES.get("wishlist", "").split(",") if not wishlist[0]: wishlist = [] request.wishlist = wishlist ## Instruction: Add deprecated fallback for SSLMiddleware. ## Code After: from mezzanine.conf import settings from cartridge.shop.models import Cart class SSLRedirect(object): def __init__(self): old = ("SHOP_SSL_ENABLED", "SHOP_FORCE_HOST", "SHOP_FORCE_SSL_VIEWS") for name in old: try: getattr(settings, name) except AttributeError: pass else: import warnings warnings.warn("The settings %s are deprecated; " "use SSL_ENABLED, SSL_FORCE_HOST and " "SSL_FORCE_URL_PREFIXES, and add " "mezzanine.core.middleware.SSLRedirectMiddleware to " "MIDDLEWARE_CLASSES." % ", ".join(old)) break class ShopMiddleware(SSLRedirect): """ Adds cart and wishlist attributes to the current request. """ def process_request(self, request): request.cart = Cart.objects.from_request(request) wishlist = request.COOKIES.get("wishlist", "").split(",") if not wishlist[0]: wishlist = [] request.wishlist = wishlist
47f495e7e5b8fa06991e0c263bc9239818dd5b4f
airpy/list.py
airpy/list.py
import os import airpy def airlist(): installed_docs = os.listdir(airpy.data_directory) for dir in installed_docs: print(dir, end= ' ') print(end = '\n')
from __future__ import print_function import os import airpy def airlist(): installed_docs = os.listdir(airpy.data_directory) for dir in installed_docs: print(dir, end= ' ') print(end = '\n')
Add a Backwards compatibility for python 2.7 by adding a __future__ import
Add a Backwards compatibility for python 2.7 by adding a __future__ import
Python
mit
kevinaloys/airpy
+ from __future__ import print_function import os import airpy + def airlist(): installed_docs = os.listdir(airpy.data_directory) for dir in installed_docs: print(dir, end= ' ') print(end = '\n') +
Add a Backwards compatibility for python 2.7 by adding a __future__ import
## Code Before: import os import airpy def airlist(): installed_docs = os.listdir(airpy.data_directory) for dir in installed_docs: print(dir, end= ' ') print(end = '\n') ## Instruction: Add a Backwards compatibility for python 2.7 by adding a __future__ import ## Code After: from __future__ import print_function import os import airpy def airlist(): installed_docs = os.listdir(airpy.data_directory) for dir in installed_docs: print(dir, end= ' ') print(end = '\n')
9011b359bdf164994734f8d6890a2d5acb5fa865
project_euler/solutions/problem_32.py
project_euler/solutions/problem_32.py
from itertools import permutations def solve() -> int: pandigital = [] for permutation in permutations(range(1, 10)): result = int(''.join(str(digit) for digit in permutation[:4])) for i in range(1, 4): left = int(''.join(str(digit) for digit in permutation[4:4 + i])) right = int(''.join(str(digit) for digit in permutation[4 + i:])) if left * right == result: pandigital.append(result) return sum(set(pandigital))
from itertools import permutations from ..library.base import list_to_number def solve() -> int: pandigital = [] for permutation in permutations(range(1, 10)): result = list_to_number(permutation[:4]) for i in range(1, 4): left = list_to_number(permutation[4:4 + i]) right = list_to_number(permutation[4 + i:]) if left * right == result: pandigital.append(result) return sum(set(pandigital))
Replace joins with list_to_number in 32
Replace joins with list_to_number in 32
Python
mit
cryvate/project-euler,cryvate/project-euler
from itertools import permutations + + from ..library.base import list_to_number def solve() -> int: pandigital = [] for permutation in permutations(range(1, 10)): - result = int(''.join(str(digit) for digit in permutation[:4])) + result = list_to_number(permutation[:4]) for i in range(1, 4): - left = int(''.join(str(digit) for digit in permutation[4:4 + i])) - right = int(''.join(str(digit) for digit in permutation[4 + i:])) + left = list_to_number(permutation[4:4 + i]) + right = list_to_number(permutation[4 + i:]) if left * right == result: pandigital.append(result) return sum(set(pandigital))
Replace joins with list_to_number in 32
## Code Before: from itertools import permutations def solve() -> int: pandigital = [] for permutation in permutations(range(1, 10)): result = int(''.join(str(digit) for digit in permutation[:4])) for i in range(1, 4): left = int(''.join(str(digit) for digit in permutation[4:4 + i])) right = int(''.join(str(digit) for digit in permutation[4 + i:])) if left * right == result: pandigital.append(result) return sum(set(pandigital)) ## Instruction: Replace joins with list_to_number in 32 ## Code After: from itertools import permutations from ..library.base import list_to_number def solve() -> int: pandigital = [] for permutation in permutations(range(1, 10)): result = list_to_number(permutation[:4]) for i in range(1, 4): left = list_to_number(permutation[4:4 + i]) right = list_to_number(permutation[4 + i:]) if left * right == result: pandigital.append(result) return sum(set(pandigital))
a3c582df681aae77034e2db08999c89866cd6470
utilities.py
utilities.py
import collections def each(function, iterable): for item in iterable: function(item) def each_unpack(function, iterable): for item in iterable: function(*item) def minmax(*args): min = None max = None for x in args: if max < x: max = x if x > min: min = x return min, max def map_inplace(function, list, depth=0): if depth <= 0: list[:] = map(function, list) else: for item in list: map_inplace(function, item, depth - 1) def count_if(function, iterable): count = 0 for item in iterable: if function(item): count += 1 return count def teemap(iterable, *functions): map(lambda item: (f(item) for f in functions), iterable) class ProbabilityDistribution(collections.defaultdict): """"Holds a probability distribution and can compute the distance to other dists""" def __init__(self): collections.defaultdict.__init__(self, int) def get(self, k, d = 0): return dict.get(self, k, d) def distance_to(self, compare_to): key_set = self.viewkeys() | compare_to.viewkeys() currentEMD = 0 lastEMD = 0 totaldistance = 0 for key in key_set: lastEMD = currentEMD currentEMD = (self.get(key, 0) + lastEMD) - compare_to.get(key, 0) totaldistance += math.fabs(currentEMD) return totaldistance
import collections def each(function, iterable): for item in iterable: function(item) def each_unpack(function, iterable): for item in iterable: function(*item) def minmax(*args): min = None max = None for x in args: if max < x: max = x if x > min: min = x return min, max def map_inplace(function, list, depth=0): if depth <= 0: list[:] = map(function, list) else: for item in list: map_inplace(function, item, depth - 1) def count_if(function, iterable): count = 0 for item in iterable: if function(item): count += 1 return count def teemap(iterable, *functions): map(lambda item: (f(item) for f in functions), iterable) class ProbabilityDistribution(collections.defaultdict): """"Holds a probability distribution and can compute the distance to other dists""" def __init__(self): collections.defaultdict.__init__(self, int) def get(self, k, d = 0): return dict.get(self, k, d) def distance_to(self, compare_to): return sum( (abs(self.get(bin) - compare_to.get(bin)) for bin in self.viewkeys() | compare_to.viewkeys()), 0)
Refactor earth mover's distance implementation
Refactor earth mover's distance implementation
Python
mit
davidfoerster/schema-matching
import collections def each(function, iterable): for item in iterable: function(item) def each_unpack(function, iterable): for item in iterable: function(*item) def minmax(*args): min = None max = None for x in args: if max < x: max = x if x > min: min = x return min, max def map_inplace(function, list, depth=0): if depth <= 0: list[:] = map(function, list) else: for item in list: map_inplace(function, item, depth - 1) def count_if(function, iterable): count = 0 for item in iterable: if function(item): count += 1 return count def teemap(iterable, *functions): map(lambda item: (f(item) for f in functions), iterable) class ProbabilityDistribution(collections.defaultdict): """"Holds a probability distribution and can compute the distance to other dists""" def __init__(self): collections.defaultdict.__init__(self, int) def get(self, k, d = 0): return dict.get(self, k, d) def distance_to(self, compare_to): + return sum( + (abs(self.get(bin) - compare_to.get(bin)) - key_set = self.viewkeys() | compare_to.viewkeys() + for bin in self.viewkeys() | compare_to.viewkeys()), + 0) - currentEMD = 0 - lastEMD = 0 - totaldistance = 0 - - for key in key_set: - lastEMD = currentEMD - currentEMD = (self.get(key, 0) + lastEMD) - compare_to.get(key, 0) - totaldistance += math.fabs(currentEMD) - - return totaldistance
Refactor earth mover's distance implementation
## Code Before: import collections def each(function, iterable): for item in iterable: function(item) def each_unpack(function, iterable): for item in iterable: function(*item) def minmax(*args): min = None max = None for x in args: if max < x: max = x if x > min: min = x return min, max def map_inplace(function, list, depth=0): if depth <= 0: list[:] = map(function, list) else: for item in list: map_inplace(function, item, depth - 1) def count_if(function, iterable): count = 0 for item in iterable: if function(item): count += 1 return count def teemap(iterable, *functions): map(lambda item: (f(item) for f in functions), iterable) class ProbabilityDistribution(collections.defaultdict): """"Holds a probability distribution and can compute the distance to other dists""" def __init__(self): collections.defaultdict.__init__(self, int) def get(self, k, d = 0): return dict.get(self, k, d) def distance_to(self, compare_to): key_set = self.viewkeys() | compare_to.viewkeys() currentEMD = 0 lastEMD = 0 totaldistance = 0 for key in key_set: lastEMD = currentEMD currentEMD = (self.get(key, 0) + lastEMD) - compare_to.get(key, 0) totaldistance += math.fabs(currentEMD) return totaldistance ## Instruction: Refactor earth mover's distance implementation ## Code After: import collections def each(function, iterable): for item in iterable: function(item) def each_unpack(function, iterable): for item in iterable: function(*item) def minmax(*args): min = None max = None for x in args: if max < x: max = x if x > min: min = x return min, max def map_inplace(function, list, depth=0): if depth <= 0: list[:] = map(function, list) else: for item in list: map_inplace(function, item, depth - 1) def count_if(function, iterable): count = 0 for item in iterable: if function(item): count += 1 return count def teemap(iterable, *functions): map(lambda item: (f(item) for f in functions), iterable) class ProbabilityDistribution(collections.defaultdict): """"Holds a probability distribution and can compute the distance to other dists""" def __init__(self): collections.defaultdict.__init__(self, int) def get(self, k, d = 0): return dict.get(self, k, d) def distance_to(self, compare_to): return sum( (abs(self.get(bin) - compare_to.get(bin)) for bin in self.viewkeys() | compare_to.viewkeys()), 0)
0d2079b1dcb97708dc55c32d9e2c1a0f12595875
salt/runners/launchd.py
salt/runners/launchd.py
''' Manage launchd plist files ''' # Import python libs import os import sys def write_launchd_plist(program): ''' Write a launchd plist for managing salt-master or salt-minion CLI Example: .. code-block:: bash salt-run launchd.write_launchd_plist salt-master ''' plist_sample_text = """ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>org.saltstack.{program}</string> <key>ProgramArguments</key> <array> <string>{python}</string> <string>{script}</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> """.strip() supported_programs = ['salt-master', 'salt-minion'] if program not in supported_programs: sys.stderr.write("Supported programs: %r\n" % supported_programs) sys.exit(-1) sys.stdout.write( plist_sample_text.format( program=program, python=sys.executable, script=os.path.join(os.path.dirname(sys.executable), program) ) )
''' Manage launchd plist files ''' # Import python libs import os import sys def write_launchd_plist(program): ''' Write a launchd plist for managing salt-master or salt-minion CLI Example: .. code-block:: bash salt-run launchd.write_launchd_plist salt-master ''' plist_sample_text = ''' <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>org.saltstack.{program}</string> <key>ProgramArguments</key> <array> <string>{python}</string> <string>{script}</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> '''.strip() supported_programs = ['salt-master', 'salt-minion'] if program not in supported_programs: sys.stderr.write('Supported programs: {0!r}\n'.format(supported_programs)) sys.exit(-1) sys.stdout.write( plist_sample_text.format( program=program, python=sys.executable, script=os.path.join(os.path.dirname(sys.executable), program) ) )
Replace string substitution with string formatting
Replace string substitution with string formatting
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' Manage launchd plist files ''' # Import python libs import os import sys def write_launchd_plist(program): ''' Write a launchd plist for managing salt-master or salt-minion CLI Example: .. code-block:: bash salt-run launchd.write_launchd_plist salt-master ''' - plist_sample_text = """ + plist_sample_text = ''' <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>org.saltstack.{program}</string> <key>ProgramArguments</key> <array> <string>{python}</string> <string>{script}</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> - """.strip() + '''.strip() supported_programs = ['salt-master', 'salt-minion'] if program not in supported_programs: - sys.stderr.write("Supported programs: %r\n" % supported_programs) + sys.stderr.write('Supported programs: {0!r}\n'.format(supported_programs)) sys.exit(-1) sys.stdout.write( plist_sample_text.format( program=program, python=sys.executable, script=os.path.join(os.path.dirname(sys.executable), program) ) )
Replace string substitution with string formatting
## Code Before: ''' Manage launchd plist files ''' # Import python libs import os import sys def write_launchd_plist(program): ''' Write a launchd plist for managing salt-master or salt-minion CLI Example: .. code-block:: bash salt-run launchd.write_launchd_plist salt-master ''' plist_sample_text = """ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>org.saltstack.{program}</string> <key>ProgramArguments</key> <array> <string>{python}</string> <string>{script}</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> """.strip() supported_programs = ['salt-master', 'salt-minion'] if program not in supported_programs: sys.stderr.write("Supported programs: %r\n" % supported_programs) sys.exit(-1) sys.stdout.write( plist_sample_text.format( program=program, python=sys.executable, script=os.path.join(os.path.dirname(sys.executable), program) ) ) ## Instruction: Replace string substitution with string formatting ## Code After: ''' Manage launchd plist files ''' # Import python libs import os import sys def write_launchd_plist(program): ''' Write a launchd plist for managing salt-master or salt-minion CLI Example: .. code-block:: bash salt-run launchd.write_launchd_plist salt-master ''' plist_sample_text = ''' <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>org.saltstack.{program}</string> <key>ProgramArguments</key> <array> <string>{python}</string> <string>{script}</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> '''.strip() supported_programs = ['salt-master', 'salt-minion'] if program not in supported_programs: sys.stderr.write('Supported programs: {0!r}\n'.format(supported_programs)) sys.exit(-1) sys.stdout.write( plist_sample_text.format( program=program, python=sys.executable, script=os.path.join(os.path.dirname(sys.executable), program) ) )
69e760e4a571d16e75f30f1e97ea1a917445f333
recipes/recipe_modules/gitiles/__init__.py
recipes/recipe_modules/gitiles/__init__.py
DEPS = [ 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/python', 'recipe_engine/raw_io', 'url', ]
DEPS = [ 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/python', 'recipe_engine/raw_io', 'recipe_engine/url', ]
Switch to recipe engine "url" module.
Switch to recipe engine "url" module. BUG=None TEST=expectations R=40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org Change-Id: I43a65405c957cb6dddd64f61846b926d81046752 Reviewed-on: https://chromium-review.googlesource.com/505278 Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org> Commit-Queue: Daniel Jacques <8400006a9338a0893dca0101ad49838955bd6b2c@chromium.org>
Python
bsd-3-clause
CoherentLabs/depot_tools,CoherentLabs/depot_tools
DEPS = [ 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/python', 'recipe_engine/raw_io', - 'url', + 'recipe_engine/url', ]
Switch to recipe engine "url" module.
## Code Before: DEPS = [ 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/python', 'recipe_engine/raw_io', 'url', ] ## Instruction: Switch to recipe engine "url" module. ## Code After: DEPS = [ 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/python', 'recipe_engine/raw_io', 'recipe_engine/url', ]
394954fc80230e01112166db4fe133c107febead
gitautodeploy/parsers/common.py
gitautodeploy/parsers/common.py
class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue if repo_config['url'] == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs
class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue if repo_config.get('repo', repo_config.get('url')) == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs
Allow more than one GitHub repo from the same user
Allow more than one GitHub repo from the same user GitHub does not allow the same SSH key to be used for multiple repositories on the same server belonging to the same user, see: http://snipe.net/2013/04/multiple-github-deploy-keys-single-server The fix there doesn't work because the "url" field is used both to get the repo and to identify it when a push comes in. Using a local SSH name for the repo works for getting the repo but then the name in the push doesn't match. This patch adds a 'repo' option that that can be set to the name of the repo as given in the push. If 'repo' is not set the behaviour is unchanged. Example: "url": "git@repo-a-shortname/somerepo.git" "repo": "git@github.com/somerepo.git"
Python
mit
evoja/docker-Github-Gitlab-Auto-Deploy,evoja/docker-Github-Gitlab-Auto-Deploy
class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue - if repo_config['url'] == url: + if repo_config.get('repo', repo_config.get('url')) == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs +
Allow more than one GitHub repo from the same user
## Code Before: class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue if repo_config['url'] == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs ## Instruction: Allow more than one GitHub repo from the same user ## Code After: class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue if repo_config.get('repo', repo_config.get('url')) == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs
bb9d1255548b46dc2ba7a85e26606b7dd4c926f3
examples/greeting.py
examples/greeting.py
from pyparsing import Word, alphas # define grammar greet = Word( alphas ) + "," + Word( alphas ) + "!" # input string hello = "Hello, World!" # parse input string print(hello, "->", greet.parseString( hello ))
import pyparsing as pp # define grammar greet = pp.Word(pp.alphas) + "," + pp.Word(pp.alphas) + pp.oneOf("! ? .") # input string hello = "Hello, World!" # parse input string print(hello, "->", greet.parseString( hello )) # parse a bunch of input strings greet.runTests("""\ Hello, World! Ahoy, Matey! Howdy, Pardner! Morning, Neighbor! """)
Update original "Hello, World!" parser to latest coding, plus runTests
Update original "Hello, World!" parser to latest coding, plus runTests
Python
mit
pyparsing/pyparsing,pyparsing/pyparsing
+ import pyparsing as pp - from pyparsing import Word, alphas - - # define grammar - greet = Word( alphas ) + "," + Word( alphas ) + "!" - - # input string - hello = "Hello, World!" - - # parse input string - print(hello, "->", greet.parseString( hello )) + # define grammar + greet = pp.Word(pp.alphas) + "," + pp.Word(pp.alphas) + pp.oneOf("! ? .") + + # input string + hello = "Hello, World!" + + # parse input string + print(hello, "->", greet.parseString( hello )) + + # parse a bunch of input strings + greet.runTests("""\ + Hello, World! + Ahoy, Matey! + Howdy, Pardner! + Morning, Neighbor! + """)
Update original "Hello, World!" parser to latest coding, plus runTests
## Code Before: from pyparsing import Word, alphas # define grammar greet = Word( alphas ) + "," + Word( alphas ) + "!" # input string hello = "Hello, World!" # parse input string print(hello, "->", greet.parseString( hello )) ## Instruction: Update original "Hello, World!" parser to latest coding, plus runTests ## Code After: import pyparsing as pp # define grammar greet = pp.Word(pp.alphas) + "," + pp.Word(pp.alphas) + pp.oneOf("! ? .") # input string hello = "Hello, World!" # parse input string print(hello, "->", greet.parseString( hello )) # parse a bunch of input strings greet.runTests("""\ Hello, World! Ahoy, Matey! Howdy, Pardner! Morning, Neighbor! """)
bc6c3834cd8383f7e1f9e109f0413bb6015a92bf
go/scheduler/views.py
go/scheduler/views.py
import datetime from django.views.generic import ListView from go.scheduler.models import Task class SchedulerListView(ListView): paginate_by = 12 context_object_name = 'tasks' template = 'scheduler/task_list.html' def get_queryset(self): now = datetime.datetime.utcnow() return Task.objects.filter( account_id=self.request.user_api.user_account_key ).order_by('-scheduled_for')
from django.views.generic import ListView from go.scheduler.models import Task class SchedulerListView(ListView): paginate_by = 12 context_object_name = 'tasks' template = 'scheduler/task_list.html' def get_queryset(self): return Task.objects.filter( account_id=self.request.user_api.user_account_key ).order_by('-scheduled_for')
Remove unneeded datetime from view
Remove unneeded datetime from view
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
- import datetime from django.views.generic import ListView from go.scheduler.models import Task class SchedulerListView(ListView): paginate_by = 12 context_object_name = 'tasks' template = 'scheduler/task_list.html' def get_queryset(self): - now = datetime.datetime.utcnow() return Task.objects.filter( account_id=self.request.user_api.user_account_key ).order_by('-scheduled_for')
Remove unneeded datetime from view
## Code Before: import datetime from django.views.generic import ListView from go.scheduler.models import Task class SchedulerListView(ListView): paginate_by = 12 context_object_name = 'tasks' template = 'scheduler/task_list.html' def get_queryset(self): now = datetime.datetime.utcnow() return Task.objects.filter( account_id=self.request.user_api.user_account_key ).order_by('-scheduled_for') ## Instruction: Remove unneeded datetime from view ## Code After: from django.views.generic import ListView from go.scheduler.models import Task class SchedulerListView(ListView): paginate_by = 12 context_object_name = 'tasks' template = 'scheduler/task_list.html' def get_queryset(self): return Task.objects.filter( account_id=self.request.user_api.user_account_key ).order_by('-scheduled_for')
ebfaf30fca157e83ea9e4bf33173221fc9525caf
demo/examples/employees/forms.py
demo/examples/employees/forms.py
from datetime import date from django import forms from django.utils import timezone from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): salary = forms.IntegerField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, )
from django import forms from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): salary = forms.IntegerField(max_value=1000000) def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, )
Fix emplorrs demo salary db error
Fix emplorrs demo salary db error
Python
bsd-3-clause
viewflow/django-material,viewflow/django-material,viewflow/django-material
- from datetime import date - from django import forms - from django.utils import timezone from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): - salary = forms.IntegerField() + salary = forms.IntegerField(max_value=1000000) def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, )
Fix emplorrs demo salary db error
## Code Before: from datetime import date from django import forms from django.utils import timezone from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): salary = forms.IntegerField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, ) ## Instruction: Fix emplorrs demo salary db error ## Code After: from django import forms from .models import Employee, DeptManager, Title, Salary class ChangeManagerForm(forms.Form): manager = forms.ModelChoiceField(queryset=Employee.objects.all()[:100]) def __init__(self, *args, **kwargs): self.department = kwargs.pop('department') super(ChangeManagerForm, self).__init__(*args, **kwargs) def save(self): new_manager = self.cleaned_data['manager'] DeptManager.objects.filter( department=self.department ).set( department=self.department, employee=new_manager ) class ChangeTitleForm(forms.Form): position = forms.CharField() def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeTitleForm, self).__init__(*args, **kwargs) def save(self): new_title = self.cleaned_data['position'] Title.objects.filter( employee=self.employee, ).set( employee=self.employee, title=new_title ) class ChangeSalaryForm(forms.Form): salary = forms.IntegerField(max_value=1000000) def __init__(self, *args, **kwargs): self.employee = kwargs.pop('employee') super(ChangeSalaryForm, self).__init__(*args, **kwargs) def save(self): new_salary = self.cleaned_data['salary'] Salary.objects.filter( employee=self.employee, ).set( employee=self.employee, salary=new_salary, )
a473b2cb9af95c1296ecae4d2138142f2be397ee
examples/variants.py
examples/variants.py
from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script()
from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap c.unihan.add_extension('cihai.unihan.UnihanVariants', namespace='variants') print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script()
Add variant extension in example script
Add variant extension in example script
Python
mit
cihai/cihai,cihai/cihai-python,cihai/cihai
from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap + c.unihan.add_extension('cihai.unihan.UnihanVariants', namespace='variants') + print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script()
Add variant extension in example script
## Code Before: from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script() ## Instruction: Add variant extension in example script ## Code After: from __future__ import print_function, unicode_literals from cihai.bootstrap import bootstrap_unihan from cihai.core import Cihai def variant_list(unihan, field): for char in unihan.with_fields(field): print("Character: {}".format(char.char)) for var in char.untagged_vars(field): print(var) def script(unihan_options={}): """Wrapped so we can test in tests/test_examples.py""" print("This example prints variant character data.") c = Cihai() c.add_dataset('cihai.unihan.Unihan', namespace='unihan') if not c.sql.is_bootstrapped: # download and install Unihan to db bootstrap_unihan(c.sql.metadata, options=unihan_options) c.sql.reflect_db() # automap new table created during bootstrap c.unihan.add_extension('cihai.unihan.UnihanVariants', namespace='variants') print("## ZVariants") variant_list(c.unihan, "kZVariant") print("## kSemanticVariant") variant_list(c.unihan, "kSemanticVariant") print("## kSpecializedSemanticVariant") variant_list(c.unihan, "kSpecializedSemanticVariant") if __name__ == '__main__': script()
7f974b87c278ef009535271461b5e49686057a9a
avatar/management/commands/rebuild_avatars.py
avatar/management/commands/rebuild_avatars.py
from django.core.management.base import NoArgsCommand from avatar.conf import settings from avatar.models import Avatar class Command(NoArgsCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") def handle_noargs(self, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size)
from django.core.management.base import BaseCommand from avatar.conf import settings from avatar.models import Avatar class Command(BaseCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") def handle(self, *args, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size)
Fix for django >= 1.10
Fix for django >= 1.10 The class django.core.management.NoArgsCommand is removed.
Python
bsd-3-clause
grantmcconnaughey/django-avatar,jezdez/django-avatar,grantmcconnaughey/django-avatar,ad-m/django-avatar,ad-m/django-avatar,jezdez/django-avatar
- from django.core.management.base import NoArgsCommand + from django.core.management.base import BaseCommand from avatar.conf import settings from avatar.models import Avatar - class Command(NoArgsCommand): + class Command(BaseCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") - def handle_noargs(self, **options): + def handle(self, *args, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size)
Fix for django >= 1.10
## Code Before: from django.core.management.base import NoArgsCommand from avatar.conf import settings from avatar.models import Avatar class Command(NoArgsCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") def handle_noargs(self, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size) ## Instruction: Fix for django >= 1.10 ## Code After: from django.core.management.base import BaseCommand from avatar.conf import settings from avatar.models import Avatar class Command(BaseCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") def handle(self, *args, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size)
eb1fdf3419bdfd1d5920d73a877f707162b783b0
cfgrib/__init__.py
cfgrib/__init__.py
__version__ = "0.9.9.2.dev0" # cfgrib core API depends on the ECMWF ecCodes C-library only from .cfmessage import CfMessage from .dataset import ( Dataset, DatasetBuildError, open_container, open_file, open_fileindex, open_from_index, ) from .messages import FileStream, Message # NOTE: xarray is not a hard dependency, but let's provide helpers if it is available. try: from .xarray_store import open_dataset, open_datasets except ImportError: pass
__version__ = "0.9.9.2.dev0" # cfgrib core API depends on the ECMWF ecCodes C-library only from .cfmessage import CfMessage from .dataset import Dataset, DatasetBuildError, open_container, open_file, open_from_index from .messages import FileStream, Message # NOTE: xarray is not a hard dependency, but let's provide helpers if it is available. try: from .xarray_store import open_dataset, open_datasets except ImportError: pass
Drop unused and dangerous entrypoint `open_fileindex`
Drop unused and dangerous entrypoint `open_fileindex`
Python
apache-2.0
ecmwf/cfgrib
__version__ = "0.9.9.2.dev0" # cfgrib core API depends on the ECMWF ecCodes C-library only from .cfmessage import CfMessage + from .dataset import Dataset, DatasetBuildError, open_container, open_file, open_from_index - from .dataset import ( - Dataset, - DatasetBuildError, - open_container, - open_file, - open_fileindex, - open_from_index, - ) from .messages import FileStream, Message # NOTE: xarray is not a hard dependency, but let's provide helpers if it is available. try: from .xarray_store import open_dataset, open_datasets except ImportError: pass
Drop unused and dangerous entrypoint `open_fileindex`
## Code Before: __version__ = "0.9.9.2.dev0" # cfgrib core API depends on the ECMWF ecCodes C-library only from .cfmessage import CfMessage from .dataset import ( Dataset, DatasetBuildError, open_container, open_file, open_fileindex, open_from_index, ) from .messages import FileStream, Message # NOTE: xarray is not a hard dependency, but let's provide helpers if it is available. try: from .xarray_store import open_dataset, open_datasets except ImportError: pass ## Instruction: Drop unused and dangerous entrypoint `open_fileindex` ## Code After: __version__ = "0.9.9.2.dev0" # cfgrib core API depends on the ECMWF ecCodes C-library only from .cfmessage import CfMessage from .dataset import Dataset, DatasetBuildError, open_container, open_file, open_from_index from .messages import FileStream, Message # NOTE: xarray is not a hard dependency, but let's provide helpers if it is available. try: from .xarray_store import open_dataset, open_datasets except ImportError: pass
e3548d62aa67472f291f6d3c0c8beca9813d6032
gym/envs/toy_text/discrete.py
gym/envs/toy_text/discrete.py
from gym import Env from gym import spaces import numpy as np def categorical_sample(prob_n): """ Sample from categorical distribution Each row specifies class probabilities """ prob_n = np.asarray(prob_n) csprob_n = np.cumsum(prob_n) return (csprob_n > np.random.rand()).argmax() class DiscreteEnv(Env): """ Has the following members - nS: number of states - nA: number of actions - P: transitions (*) - isd: initial state distribution (**) (*) dictionary dict of dicts of lists, where P[s][a] == [(probability, nextstate, reward, done), ...] (**) list or array of length nS """ def __init__(self, nS, nA, P, isd): self.action_space = spaces.Discrete(nA) self.observation_space = spaces.Discrete(nS) self.nA = nA self.P = P self.isd = isd self.lastaction=None # for rendering @property def nS(self): return self.observation_space.n def _reset(self): self.s = categorical_sample(self.isd) return self.s def _step(self, a): transitions = self.P[self.s][a] i = categorical_sample([t[0] for t in transitions]) p, s, r, d= transitions[i] self.s = s self.lastaction=a return (s, r, d, {"prob" : p})
from gym import Env from gym import spaces import numpy as np def categorical_sample(prob_n): """ Sample from categorical distribution Each row specifies class probabilities """ prob_n = np.asarray(prob_n) csprob_n = np.cumsum(prob_n) return (csprob_n > np.random.rand()).argmax() class DiscreteEnv(Env): """ Has the following members - nS: number of states - nA: number of actions - P: transitions (*) - isd: initial state distribution (**) (*) dictionary dict of dicts of lists, where P[s][a] == [(probability, nextstate, reward, done), ...] (**) list or array of length nS """ def __init__(self, nS, nA, P, isd): self.action_space = spaces.Discrete(nA) self.observation_space = spaces.Discrete(nS) self.nA = nA self.P = P self.isd = isd self.lastaction=None # for rendering self._reset() @property def nS(self): return self.observation_space.n def _reset(self): self.s = categorical_sample(self.isd) return self.s def _step(self, a): transitions = self.P[self.s][a] i = categorical_sample([t[0] for t in transitions]) p, s, r, d= transitions[i] self.s = s self.lastaction=a return (s, r, d, {"prob" : p})
Make it possible to step() in a newly created env, rather than throwing AttributeError
Make it possible to step() in a newly created env, rather than throwing AttributeError
Python
mit
d1hotpep/openai_gym,Farama-Foundation/Gymnasium,dianchen96/gym,machinaut/gym,dianchen96/gym,d1hotpep/openai_gym,machinaut/gym,Farama-Foundation/Gymnasium
from gym import Env from gym import spaces import numpy as np def categorical_sample(prob_n): """ Sample from categorical distribution Each row specifies class probabilities """ prob_n = np.asarray(prob_n) csprob_n = np.cumsum(prob_n) return (csprob_n > np.random.rand()).argmax() class DiscreteEnv(Env): """ Has the following members - nS: number of states - nA: number of actions - P: transitions (*) - isd: initial state distribution (**) (*) dictionary dict of dicts of lists, where P[s][a] == [(probability, nextstate, reward, done), ...] (**) list or array of length nS """ def __init__(self, nS, nA, P, isd): self.action_space = spaces.Discrete(nA) self.observation_space = spaces.Discrete(nS) self.nA = nA self.P = P self.isd = isd self.lastaction=None # for rendering + self._reset() @property def nS(self): return self.observation_space.n def _reset(self): self.s = categorical_sample(self.isd) return self.s def _step(self, a): transitions = self.P[self.s][a] i = categorical_sample([t[0] for t in transitions]) p, s, r, d= transitions[i] self.s = s self.lastaction=a return (s, r, d, {"prob" : p})
Make it possible to step() in a newly created env, rather than throwing AttributeError
## Code Before: from gym import Env from gym import spaces import numpy as np def categorical_sample(prob_n): """ Sample from categorical distribution Each row specifies class probabilities """ prob_n = np.asarray(prob_n) csprob_n = np.cumsum(prob_n) return (csprob_n > np.random.rand()).argmax() class DiscreteEnv(Env): """ Has the following members - nS: number of states - nA: number of actions - P: transitions (*) - isd: initial state distribution (**) (*) dictionary dict of dicts of lists, where P[s][a] == [(probability, nextstate, reward, done), ...] (**) list or array of length nS """ def __init__(self, nS, nA, P, isd): self.action_space = spaces.Discrete(nA) self.observation_space = spaces.Discrete(nS) self.nA = nA self.P = P self.isd = isd self.lastaction=None # for rendering @property def nS(self): return self.observation_space.n def _reset(self): self.s = categorical_sample(self.isd) return self.s def _step(self, a): transitions = self.P[self.s][a] i = categorical_sample([t[0] for t in transitions]) p, s, r, d= transitions[i] self.s = s self.lastaction=a return (s, r, d, {"prob" : p}) ## Instruction: Make it possible to step() in a newly created env, rather than throwing AttributeError ## Code After: from gym import Env from gym import spaces import numpy as np def categorical_sample(prob_n): """ Sample from categorical distribution Each row specifies class probabilities """ prob_n = np.asarray(prob_n) csprob_n = np.cumsum(prob_n) return (csprob_n > np.random.rand()).argmax() class DiscreteEnv(Env): """ Has the following members - nS: number of states - nA: number of actions - P: transitions (*) - isd: initial state distribution (**) (*) dictionary dict of dicts of lists, where P[s][a] == [(probability, nextstate, reward, done), ...] (**) list or array of length nS """ def __init__(self, nS, nA, P, isd): self.action_space = spaces.Discrete(nA) self.observation_space = spaces.Discrete(nS) self.nA = nA self.P = P self.isd = isd self.lastaction=None # for rendering self._reset() @property def nS(self): return self.observation_space.n def _reset(self): self.s = categorical_sample(self.isd) return self.s def _step(self, a): transitions = self.P[self.s][a] i = categorical_sample([t[0] for t in transitions]) p, s, r, d= transitions[i] self.s = s self.lastaction=a return (s, r, d, {"prob" : p})
91e916cb67867db9ce835be28b31904e6efda832
spacy/tests/regression/test_issue1727.py
spacy/tests/regression/test_issue1727.py
from __future__ import unicode_literals import numpy from ...pipeline import Tagger from ...vectors import Vectors from ...vocab import Vocab from ..util import make_tempdir def test_issue1727(): data = numpy.ones((3, 300), dtype='f') keys = [u'I', u'am', u'Matt'] vectors = Vectors(data=data, keys=keys) tagger = Tagger(Vocab()) tagger.add_label('PRP') tagger.begin_training() assert tagger.cfg.get('pretrained_dims', 0) == 0 tagger.vocab.vectors = vectors with make_tempdir() as path: tagger.to_disk(path) tagger = Tagger(Vocab()).from_disk(path) assert tagger.cfg.get('pretrained_dims', 0) == 0
'''Test that models with no pretrained vectors can be deserialized correctly after vectors are added.''' from __future__ import unicode_literals import numpy from ...pipeline import Tagger from ...vectors import Vectors from ...vocab import Vocab from ..util import make_tempdir def test_issue1727(): data = numpy.ones((3, 300), dtype='f') keys = [u'I', u'am', u'Matt'] vectors = Vectors(data=data, keys=keys) tagger = Tagger(Vocab()) tagger.add_label('PRP') tagger.begin_training() assert tagger.cfg.get('pretrained_dims', 0) == 0 tagger.vocab.vectors = vectors with make_tempdir() as path: tagger.to_disk(path) tagger = Tagger(Vocab()).from_disk(path) assert tagger.cfg.get('pretrained_dims', 0) == 0
Add comment to new test
Add comment to new test
Python
mit
aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy
+ '''Test that models with no pretrained vectors can be deserialized correctly + after vectors are added.''' from __future__ import unicode_literals import numpy from ...pipeline import Tagger from ...vectors import Vectors from ...vocab import Vocab from ..util import make_tempdir def test_issue1727(): data = numpy.ones((3, 300), dtype='f') keys = [u'I', u'am', u'Matt'] vectors = Vectors(data=data, keys=keys) tagger = Tagger(Vocab()) tagger.add_label('PRP') tagger.begin_training() assert tagger.cfg.get('pretrained_dims', 0) == 0 tagger.vocab.vectors = vectors with make_tempdir() as path: tagger.to_disk(path) tagger = Tagger(Vocab()).from_disk(path) assert tagger.cfg.get('pretrained_dims', 0) == 0
Add comment to new test
## Code Before: from __future__ import unicode_literals import numpy from ...pipeline import Tagger from ...vectors import Vectors from ...vocab import Vocab from ..util import make_tempdir def test_issue1727(): data = numpy.ones((3, 300), dtype='f') keys = [u'I', u'am', u'Matt'] vectors = Vectors(data=data, keys=keys) tagger = Tagger(Vocab()) tagger.add_label('PRP') tagger.begin_training() assert tagger.cfg.get('pretrained_dims', 0) == 0 tagger.vocab.vectors = vectors with make_tempdir() as path: tagger.to_disk(path) tagger = Tagger(Vocab()).from_disk(path) assert tagger.cfg.get('pretrained_dims', 0) == 0 ## Instruction: Add comment to new test ## Code After: '''Test that models with no pretrained vectors can be deserialized correctly after vectors are added.''' from __future__ import unicode_literals import numpy from ...pipeline import Tagger from ...vectors import Vectors from ...vocab import Vocab from ..util import make_tempdir def test_issue1727(): data = numpy.ones((3, 300), dtype='f') keys = [u'I', u'am', u'Matt'] vectors = Vectors(data=data, keys=keys) tagger = Tagger(Vocab()) tagger.add_label('PRP') tagger.begin_training() assert tagger.cfg.get('pretrained_dims', 0) == 0 tagger.vocab.vectors = vectors with make_tempdir() as path: tagger.to_disk(path) tagger = Tagger(Vocab()).from_disk(path) assert tagger.cfg.get('pretrained_dims', 0) == 0
9df00bbfa829006396c2a6718e4540410b27c4c6
kolibri/tasks/apps.py
kolibri/tasks/apps.py
from __future__ import absolute_import, print_function, unicode_literals from django.apps import AppConfig class KolibriTasksConfig(AppConfig): name = 'kolibri.tasks' label = 'kolibritasks' verbose_name = 'Kolibri Tasks' def ready(self): pass
from __future__ import absolute_import, print_function, unicode_literals from django.apps import AppConfig class KolibriTasksConfig(AppConfig): name = 'kolibri.tasks' label = 'kolibritasks' verbose_name = 'Kolibri Tasks' def ready(self): from kolibri.tasks.api import client client.clear(force=True)
Clear the job queue upon kolibri initialization.
Clear the job queue upon kolibri initialization.
Python
mit
MingDai/kolibri,mrpau/kolibri,benjaoming/kolibri,DXCanas/kolibri,lyw07/kolibri,learningequality/kolibri,rtibbles/kolibri,mrpau/kolibri,mrpau/kolibri,rtibbles/kolibri,DXCanas/kolibri,indirectlylit/kolibri,MingDai/kolibri,lyw07/kolibri,mrpau/kolibri,christianmemije/kolibri,DXCanas/kolibri,learningequality/kolibri,jonboiser/kolibri,christianmemije/kolibri,christianmemije/kolibri,lyw07/kolibri,lyw07/kolibri,benjaoming/kolibri,jonboiser/kolibri,jonboiser/kolibri,indirectlylit/kolibri,christianmemije/kolibri,benjaoming/kolibri,learningequality/kolibri,rtibbles/kolibri,learningequality/kolibri,benjaoming/kolibri,MingDai/kolibri,indirectlylit/kolibri,MingDai/kolibri,indirectlylit/kolibri,rtibbles/kolibri,jonboiser/kolibri,DXCanas/kolibri
from __future__ import absolute_import, print_function, unicode_literals from django.apps import AppConfig class KolibriTasksConfig(AppConfig): name = 'kolibri.tasks' label = 'kolibritasks' verbose_name = 'Kolibri Tasks' def ready(self): - pass + from kolibri.tasks.api import client + client.clear(force=True)
Clear the job queue upon kolibri initialization.
## Code Before: from __future__ import absolute_import, print_function, unicode_literals from django.apps import AppConfig class KolibriTasksConfig(AppConfig): name = 'kolibri.tasks' label = 'kolibritasks' verbose_name = 'Kolibri Tasks' def ready(self): pass ## Instruction: Clear the job queue upon kolibri initialization. ## Code After: from __future__ import absolute_import, print_function, unicode_literals from django.apps import AppConfig class KolibriTasksConfig(AppConfig): name = 'kolibri.tasks' label = 'kolibritasks' verbose_name = 'Kolibri Tasks' def ready(self): from kolibri.tasks.api import client client.clear(force=True)
959897478bbda18f02aa6e38f2ebdd837581f1f0
tests/test_sct_verify_signature.py
tests/test_sct_verify_signature.py
from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb').read() signature = open(flo('{basedir}/signature.der'), 'rb').read() pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read() got_verified, got_output, got_cmd_res = \ verify_signature(signature_input, signature, pubkey) assert got_verified is True assert got_output == 'Verified OK\n' assert got_cmd_res.exitcode == 0 signature_input = b'some invalid signature input' got_verified, got_output, got_cmd_res = \ verify_signature(signature_input, signature, pubkey) assert got_verified is False assert got_output == 'Verification Failure\n' assert got_cmd_res.exitcode == 1
from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb').read() signature = open(flo('{basedir}/signature.der'), 'rb').read() pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read() assert verify_signature(signature_input, signature, pubkey) is True signature_input = b'some invalid signature input' assert verify_signature(signature_input, signature, pubkey) is False
Fix test for changed SctVerificationResult
Fix test for changed SctVerificationResult
Python
mit
theno/ctutlz,theno/ctutlz
from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb').read() signature = open(flo('{basedir}/signature.der'), 'rb').read() pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read() - got_verified, got_output, got_cmd_res = \ - verify_signature(signature_input, signature, pubkey) + assert verify_signature(signature_input, signature, pubkey) is True - - assert got_verified is True - assert got_output == 'Verified OK\n' - assert got_cmd_res.exitcode == 0 signature_input = b'some invalid signature input' - got_verified, got_output, got_cmd_res = \ - verify_signature(signature_input, signature, pubkey) + assert verify_signature(signature_input, signature, pubkey) is False - assert got_verified is False - assert got_output == 'Verification Failure\n' - assert got_cmd_res.exitcode == 1 -
Fix test for changed SctVerificationResult
## Code Before: from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb').read() signature = open(flo('{basedir}/signature.der'), 'rb').read() pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read() got_verified, got_output, got_cmd_res = \ verify_signature(signature_input, signature, pubkey) assert got_verified is True assert got_output == 'Verified OK\n' assert got_cmd_res.exitcode == 0 signature_input = b'some invalid signature input' got_verified, got_output, got_cmd_res = \ verify_signature(signature_input, signature, pubkey) assert got_verified is False assert got_output == 'Verification Failure\n' assert got_cmd_res.exitcode == 1 ## Instruction: Fix test for changed SctVerificationResult ## Code After: from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb').read() signature = open(flo('{basedir}/signature.der'), 'rb').read() pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read() assert verify_signature(signature_input, signature, pubkey) is True signature_input = b'some invalid signature input' assert verify_signature(signature_input, signature, pubkey) is False
a378649f85f0bc55060ad0238e426f587bc2ff1a
core/exceptions.py
core/exceptions.py
class InvalidMembership(Exception): """ The membership provided is not valid """ pass class SourceNotFound(Exception): """ InstanceSource doesn't have an associated source. """ pass class RequestLimitExceeded(Exception): """ A limit was exceeded for the specific request """ pass class ProviderLimitExceeded(Exception): """ A limit was exceeded for the specific provider """ pass class ProviderNotActive(Exception): """ The provider that was requested is not active """ def __init__(self, provider, *args, **kwargs): self.message = "Cannot create driver on an inactive provider:%s" \ % (provider,) pass
class InvalidMembership(Exception): """ The membership provided is not valid """ pass class SourceNotFound(Exception): """ InstanceSource doesn't have an associated source. """ pass class RequestLimitExceeded(Exception): """ A limit was exceeded for the specific request """ pass class ProviderLimitExceeded(Exception): """ A limit was exceeded for the specific provider """ pass class ProviderNotActive(Exception): """ The provider that was requested is not active """ def __init__(self, provider, *args, **kwargs): self.message = "Cannot create driver on an inactive provider: %s" \ % (provider.location,) pass
Send location only when printing exception (Avoid leaking ID/UUID)
Send location only when printing exception (Avoid leaking ID/UUID)
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
class InvalidMembership(Exception): """ The membership provided is not valid """ pass class SourceNotFound(Exception): """ InstanceSource doesn't have an associated source. """ pass class RequestLimitExceeded(Exception): """ A limit was exceeded for the specific request """ pass class ProviderLimitExceeded(Exception): """ A limit was exceeded for the specific provider """ pass class ProviderNotActive(Exception): """ The provider that was requested is not active """ def __init__(self, provider, *args, **kwargs): - self.message = "Cannot create driver on an inactive provider:%s" \ + self.message = "Cannot create driver on an inactive provider: %s" \ - % (provider,) + % (provider.location,) pass
Send location only when printing exception (Avoid leaking ID/UUID)
## Code Before: class InvalidMembership(Exception): """ The membership provided is not valid """ pass class SourceNotFound(Exception): """ InstanceSource doesn't have an associated source. """ pass class RequestLimitExceeded(Exception): """ A limit was exceeded for the specific request """ pass class ProviderLimitExceeded(Exception): """ A limit was exceeded for the specific provider """ pass class ProviderNotActive(Exception): """ The provider that was requested is not active """ def __init__(self, provider, *args, **kwargs): self.message = "Cannot create driver on an inactive provider:%s" \ % (provider,) pass ## Instruction: Send location only when printing exception (Avoid leaking ID/UUID) ## Code After: class InvalidMembership(Exception): """ The membership provided is not valid """ pass class SourceNotFound(Exception): """ InstanceSource doesn't have an associated source. """ pass class RequestLimitExceeded(Exception): """ A limit was exceeded for the specific request """ pass class ProviderLimitExceeded(Exception): """ A limit was exceeded for the specific provider """ pass class ProviderNotActive(Exception): """ The provider that was requested is not active """ def __init__(self, provider, *args, **kwargs): self.message = "Cannot create driver on an inactive provider: %s" \ % (provider.location,) pass
99e9ef79178d6e2dffd8ec7ed12b3edbd8b7d0f1
longclaw/longclawbasket/views.py
longclaw/longclawbasket/views.py
from django.shortcuts import render from django.views.generic import ListView from longclaw.longclawbasket.models import BasketItem from longclaw.longclawbasket import utils class BasketView(ListView): model = BasketItem template_name = "longclawbasket/basket.html" def get_context_data(self, **kwargs): items, _ = utils.get_basket_items(self.request) return {"basket": items}
from django.shortcuts import render from django.views.generic import ListView from longclaw.longclawbasket.models import BasketItem from longclaw.longclawbasket import utils class BasketView(ListView): model = BasketItem template_name = "longclawbasket/basket.html" def get_context_data(self, **kwargs): items, _ = utils.get_basket_items(self.request) total_price = sum(item.total() for item in items) return {"basket": items, "total_price": total_price}
Add basket total to context
Add basket total to context
Python
mit
JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw
from django.shortcuts import render from django.views.generic import ListView from longclaw.longclawbasket.models import BasketItem from longclaw.longclawbasket import utils class BasketView(ListView): model = BasketItem template_name = "longclawbasket/basket.html" def get_context_data(self, **kwargs): items, _ = utils.get_basket_items(self.request) - return {"basket": items} + total_price = sum(item.total() for item in items) + return {"basket": items, "total_price": total_price}
Add basket total to context
## Code Before: from django.shortcuts import render from django.views.generic import ListView from longclaw.longclawbasket.models import BasketItem from longclaw.longclawbasket import utils class BasketView(ListView): model = BasketItem template_name = "longclawbasket/basket.html" def get_context_data(self, **kwargs): items, _ = utils.get_basket_items(self.request) return {"basket": items} ## Instruction: Add basket total to context ## Code After: from django.shortcuts import render from django.views.generic import ListView from longclaw.longclawbasket.models import BasketItem from longclaw.longclawbasket import utils class BasketView(ListView): model = BasketItem template_name = "longclawbasket/basket.html" def get_context_data(self, **kwargs): items, _ = utils.get_basket_items(self.request) total_price = sum(item.total() for item in items) return {"basket": items, "total_price": total_price}
6cfc94d8a03439c55808090aa5e3a4f35c288887
menpodetect/tests/opencv_test.py
menpodetect/tests/opencv_test.py
from menpodetect.opencv import (load_opencv_frontal_face_detector, load_opencv_eye_detector) import menpo.io as mio takeo = mio.import_builtin_asset.takeo_ppm() def test_frontal_face_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4 def test_frontal_face_detector_min_neighbors(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy, min_neighbours=100) assert len(pcs) == 0 assert takeo_copy.n_channels == 3 def test_eye_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_eye_detector() pcs = opencv_detector(takeo_copy, min_size=(5, 5)) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4
from numpy.testing import assert_allclose from menpodetect.opencv import (load_opencv_frontal_face_detector, load_opencv_eye_detector) import menpo.io as mio takeo = mio.import_builtin_asset.takeo_ppm() def test_frontal_face_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4 def test_frontal_face_detector_min_neighbors(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy, min_neighbours=100) assert len(pcs) == 0 assert takeo_copy.n_channels == 3 def test_eye_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_eye_detector() pcs = opencv_detector(takeo_copy, min_size=(5, 5)) assert_allclose(len(pcs), 1) assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4
Use assert_allclose so we can see the appveyor failure
Use assert_allclose so we can see the appveyor failure
Python
bsd-3-clause
yuxiang-zhou/menpodetect,jabooth/menpodetect,yuxiang-zhou/menpodetect,jabooth/menpodetect
+ from numpy.testing import assert_allclose from menpodetect.opencv import (load_opencv_frontal_face_detector, load_opencv_eye_detector) import menpo.io as mio takeo = mio.import_builtin_asset.takeo_ppm() def test_frontal_face_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4 def test_frontal_face_detector_min_neighbors(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy, min_neighbours=100) assert len(pcs) == 0 assert takeo_copy.n_channels == 3 def test_eye_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_eye_detector() pcs = opencv_detector(takeo_copy, min_size=(5, 5)) - assert len(pcs) == 1 + assert_allclose(len(pcs), 1) assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4
Use assert_allclose so we can see the appveyor failure
## Code Before: from menpodetect.opencv import (load_opencv_frontal_face_detector, load_opencv_eye_detector) import menpo.io as mio takeo = mio.import_builtin_asset.takeo_ppm() def test_frontal_face_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4 def test_frontal_face_detector_min_neighbors(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy, min_neighbours=100) assert len(pcs) == 0 assert takeo_copy.n_channels == 3 def test_eye_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_eye_detector() pcs = opencv_detector(takeo_copy, min_size=(5, 5)) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4 ## Instruction: Use assert_allclose so we can see the appveyor failure ## Code After: from numpy.testing import assert_allclose from menpodetect.opencv import (load_opencv_frontal_face_detector, load_opencv_eye_detector) import menpo.io as mio takeo = mio.import_builtin_asset.takeo_ppm() def test_frontal_face_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy) assert len(pcs) == 1 assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4 def test_frontal_face_detector_min_neighbors(): takeo_copy = takeo.copy() opencv_detector = load_opencv_frontal_face_detector() pcs = opencv_detector(takeo_copy, min_neighbours=100) assert len(pcs) == 0 assert takeo_copy.n_channels == 3 def test_eye_detector(): takeo_copy = takeo.copy() opencv_detector = load_opencv_eye_detector() pcs = opencv_detector(takeo_copy, min_size=(5, 5)) assert_allclose(len(pcs), 1) assert takeo_copy.n_channels == 3 assert takeo_copy.landmarks['opencv_0'][None].n_points == 4