commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
ab2d1296dd189016daa8012fc80d821d1b71486c
telephony/radio_station.py
telephony/radio_station.py
import time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return def stop(self): self.call_handler.stop() self.__program_handler.stop() pass def __init__(self, station, db, logger): self.logger = logger self.db = db self.station = station self.__program_handler = ProgramHandler(self) self.call_handler = CallHandler(self) self.__community_handler = CommunityMenu(self) self.logger.info("Starting up station {0}".format(self.station.name)) return
import time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return def stop(self): self.call_handler.stop() self.__program_handler.stop() pass def __init__(self, station, db, logger): self.logger = logger self.db = db self.station = station self.id = station.id self.__program_handler = ProgramHandler(self) self.call_handler = CallHandler(self) self.__community_handler = CommunityMenu(self) self.logger.info("Starting up station {0}".format(self.station.name)) return
Fix no id property for RadioStation
Fix no id property for RadioStation
Python
agpl-3.0
rootio/rootio_web,rootio/rootio_web,rootio/rootio_web,rootio/rootio_web
import time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return def stop(self): self.call_handler.stop() self.__program_handler.stop() pass def __init__(self, station, db, logger): self.logger = logger self.db = db self.station = station self.__program_handler = ProgramHandler(self) self.call_handler = CallHandler(self) self.__community_handler = CommunityMenu(self) self.logger.info("Starting up station {0}".format(self.station.name)) return Fix no id property for RadioStation
import time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return def stop(self): self.call_handler.stop() self.__program_handler.stop() pass def __init__(self, station, db, logger): self.logger = logger self.db = db self.station = station self.id = station.id self.__program_handler = ProgramHandler(self) self.call_handler = CallHandler(self) self.__community_handler = CommunityMenu(self) self.logger.info("Starting up station {0}".format(self.station.name)) return
<commit_before>import time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return def stop(self): self.call_handler.stop() self.__program_handler.stop() pass def __init__(self, station, db, logger): self.logger = logger self.db = db self.station = station self.__program_handler = ProgramHandler(self) self.call_handler = CallHandler(self) self.__community_handler = CommunityMenu(self) self.logger.info("Starting up station {0}".format(self.station.name)) return <commit_msg>Fix no id property for RadioStation<commit_after>
import time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return def stop(self): self.call_handler.stop() self.__program_handler.stop() pass def __init__(self, station, db, logger): self.logger = logger self.db = db self.station = station self.id = station.id self.__program_handler = ProgramHandler(self) self.call_handler = CallHandler(self) self.__community_handler = CommunityMenu(self) self.logger.info("Starting up station {0}".format(self.station.name)) return
import time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return def stop(self): self.call_handler.stop() self.__program_handler.stop() pass def __init__(self, station, db, logger): self.logger = logger self.db = db self.station = station self.__program_handler = ProgramHandler(self) self.call_handler = CallHandler(self) self.__community_handler = CommunityMenu(self) self.logger.info("Starting up station {0}".format(self.station.name)) return Fix no id property for RadioStationimport time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return def stop(self): self.call_handler.stop() self.__program_handler.stop() pass def __init__(self, station, db, logger): self.logger = logger self.db = db self.station = station self.id = station.id self.__program_handler = ProgramHandler(self) self.call_handler = CallHandler(self) self.__community_handler = CommunityMenu(self) self.logger.info("Starting up station {0}".format(self.station.name)) return
<commit_before>import time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return def stop(self): self.call_handler.stop() self.__program_handler.stop() pass def __init__(self, station, db, logger): self.logger = logger self.db = db self.station = station self.__program_handler = ProgramHandler(self) self.call_handler = CallHandler(self) self.__community_handler = CommunityMenu(self) self.logger.info("Starting up station {0}".format(self.station.name)) return <commit_msg>Fix no id property for RadioStation<commit_after>import time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return def stop(self): self.call_handler.stop() self.__program_handler.stop() pass def __init__(self, station, db, logger): self.logger = logger self.db = db self.station = station self.id = station.id self.__program_handler = ProgramHandler(self) self.call_handler = CallHandler(self) self.__community_handler = CommunityMenu(self) self.logger.info("Starting up station {0}".format(self.station.name)) return
ff564c646cedf7f8129fb4ce3d6736424252f8a6
pundler/config.py
pundler/config.py
# coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: self.pyfile = os.path.join(os.getcwd(), 'Pyfile') self._check_file(self.pyfile) self.data = yaml.load(open(self.pyfile).read()) self.environment = environment @property def packages(self): if self.environment not in self.data: raise EnvironmentNotFound( 'not environment({}) in config file Pyfile'.format( self.environment)) return [ Package(name, config) for name, config in self.data[self.environment].iteritems() ] def _check_file(self, filepath): if not os.path.exists(filepath): raise FileNotFound('config file({}) not found.'.format(filepath))
# coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: self.pyfile = os.path.join(os.getcwd(), 'Pyfile') self._check_file(self.pyfile) self.data = yaml.load(open(self.pyfile).read()) self.environment = environment @property def packages(self): if self.environment not in self.data: raise EnvironmentNotFound( 'not environment({}) in config file Pyfile'.format( self.environment)) return [ Package(name, config) for name, config in self.data[self.environment].items() ] def _check_file(self, filepath): if not os.path.exists(filepath): raise FileNotFound('config file({}) not found.'.format(filepath))
Fix iteritems isn't a method name in Py3
Fix iteritems isn't a method name in Py3
Python
mit
hirokazumiyaji/pundler
# coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: self.pyfile = os.path.join(os.getcwd(), 'Pyfile') self._check_file(self.pyfile) self.data = yaml.load(open(self.pyfile).read()) self.environment = environment @property def packages(self): if self.environment not in self.data: raise EnvironmentNotFound( 'not environment({}) in config file Pyfile'.format( self.environment)) return [ Package(name, config) for name, config in self.data[self.environment].iteritems() ] def _check_file(self, filepath): if not os.path.exists(filepath): raise FileNotFound('config file({}) not found.'.format(filepath)) Fix iteritems isn't a method name in Py3
# coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: self.pyfile = os.path.join(os.getcwd(), 'Pyfile') self._check_file(self.pyfile) self.data = yaml.load(open(self.pyfile).read()) self.environment = environment @property def packages(self): if self.environment not in self.data: raise EnvironmentNotFound( 'not environment({}) in config file Pyfile'.format( self.environment)) return [ Package(name, config) for name, config in self.data[self.environment].items() ] def _check_file(self, filepath): if not os.path.exists(filepath): raise FileNotFound('config file({}) not found.'.format(filepath))
<commit_before># coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: self.pyfile = os.path.join(os.getcwd(), 'Pyfile') self._check_file(self.pyfile) self.data = yaml.load(open(self.pyfile).read()) self.environment = environment @property def packages(self): if self.environment not in self.data: raise EnvironmentNotFound( 'not environment({}) in config file Pyfile'.format( self.environment)) return [ Package(name, config) for name, config in self.data[self.environment].iteritems() ] def _check_file(self, filepath): if not os.path.exists(filepath): raise FileNotFound('config file({}) not found.'.format(filepath)) <commit_msg>Fix iteritems isn't a method name in Py3<commit_after>
# coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: self.pyfile = os.path.join(os.getcwd(), 'Pyfile') self._check_file(self.pyfile) self.data = yaml.load(open(self.pyfile).read()) self.environment = environment @property def packages(self): if self.environment not in self.data: raise EnvironmentNotFound( 'not environment({}) in config file Pyfile'.format( self.environment)) return [ Package(name, config) for name, config in self.data[self.environment].items() ] def _check_file(self, filepath): if not os.path.exists(filepath): raise FileNotFound('config file({}) not found.'.format(filepath))
# coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: self.pyfile = os.path.join(os.getcwd(), 'Pyfile') self._check_file(self.pyfile) self.data = yaml.load(open(self.pyfile).read()) self.environment = environment @property def packages(self): if self.environment not in self.data: raise EnvironmentNotFound( 'not environment({}) in config file Pyfile'.format( self.environment)) return [ Package(name, config) for name, config in self.data[self.environment].iteritems() ] def _check_file(self, filepath): if not os.path.exists(filepath): raise FileNotFound('config file({}) not found.'.format(filepath)) Fix iteritems isn't a method name in Py3# coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: self.pyfile = os.path.join(os.getcwd(), 'Pyfile') self._check_file(self.pyfile) self.data = yaml.load(open(self.pyfile).read()) self.environment = environment @property def packages(self): if self.environment not in self.data: raise EnvironmentNotFound( 'not environment({}) in config file Pyfile'.format( self.environment)) return [ Package(name, config) for name, config in self.data[self.environment].items() ] def _check_file(self, filepath): if not os.path.exists(filepath): raise FileNotFound('config file({}) not found.'.format(filepath))
<commit_before># coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: self.pyfile = os.path.join(os.getcwd(), 'Pyfile') self._check_file(self.pyfile) self.data = yaml.load(open(self.pyfile).read()) self.environment = environment @property def packages(self): if self.environment not in self.data: raise EnvironmentNotFound( 'not environment({}) in config file Pyfile'.format( self.environment)) return [ Package(name, config) for name, config in self.data[self.environment].iteritems() ] def _check_file(self, filepath): if not os.path.exists(filepath): raise FileNotFound('config file({}) not found.'.format(filepath)) <commit_msg>Fix iteritems isn't a method name in Py3<commit_after># coding: utf-8 from __future__ import absolute_import import os import yaml from .exceptions import EnvironmentNotFound, FileNotFound from .package import Package class Config(object): def __init__(self, pyfile=None, environment='development'): if pyfile: self.pyfile = pyfile else: self.pyfile = os.path.join(os.getcwd(), 'Pyfile') self._check_file(self.pyfile) self.data = yaml.load(open(self.pyfile).read()) self.environment = environment @property def packages(self): if self.environment not in self.data: raise EnvironmentNotFound( 'not environment({}) in config file Pyfile'.format( self.environment)) return [ Package(name, config) for name, config in self.data[self.environment].items() ] def _check_file(self, filepath): if not os.path.exists(filepath): raise FileNotFound('config file({}) not found.'.format(filepath))
18374ff4e3906f704276bb0a7b5a5feae50875a2
aspy/yaml/__init__.py
aspy/yaml/__init__.py
from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(yaml.loader.Loader): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: OrderedDict(loader.construct_pairs(node)), ) class OrderedDumper(yaml.dumper.SafeDumper): pass OrderedDumper.add_representer( OrderedDict, lambda dumper, data: dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), ), ) def ordered_load(stream): """yaml.load which respects order for dictionaries in the yaml file. :param stream: string or streamlike object. """ return yaml.load(stream, Loader=OrderedLoader) def ordered_dump(obj, **kwargs): """yaml.dump which respects order for dictionaries in the yaml object. :param obj: Yaml dumpable object """ return yaml.dump(obj, Dumper=OrderedDumper, **kwargs)
from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(getattr(yaml, 'CSafeLoader', yaml.SafeLoader)): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: OrderedDict(loader.construct_pairs(node)), ) class OrderedDumper(getattr(yaml, 'CSafeDumper', yaml.SafeDumper)): pass OrderedDumper.add_representer( OrderedDict, lambda dumper, data: dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), ), ) def ordered_load(stream): """yaml.load which respects order for dictionaries in the yaml file. :param stream: string or streamlike object. """ return yaml.load(stream, Loader=OrderedLoader) def ordered_dump(obj, **kwargs): """yaml.dump which respects order for dictionaries in the yaml object. :param obj: Yaml dumpable object """ return yaml.dump(obj, Dumper=OrderedDumper, **kwargs)
Use the C Loader/Dumper when available
Use the C Loader/Dumper when available
Python
mit
asottile/aspy.yaml
from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(yaml.loader.Loader): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: OrderedDict(loader.construct_pairs(node)), ) class OrderedDumper(yaml.dumper.SafeDumper): pass OrderedDumper.add_representer( OrderedDict, lambda dumper, data: dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), ), ) def ordered_load(stream): """yaml.load which respects order for dictionaries in the yaml file. :param stream: string or streamlike object. """ return yaml.load(stream, Loader=OrderedLoader) def ordered_dump(obj, **kwargs): """yaml.dump which respects order for dictionaries in the yaml object. :param obj: Yaml dumpable object """ return yaml.dump(obj, Dumper=OrderedDumper, **kwargs) Use the C Loader/Dumper when available
from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(getattr(yaml, 'CSafeLoader', yaml.SafeLoader)): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: OrderedDict(loader.construct_pairs(node)), ) class OrderedDumper(getattr(yaml, 'CSafeDumper', yaml.SafeDumper)): pass OrderedDumper.add_representer( OrderedDict, lambda dumper, data: dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), ), ) def ordered_load(stream): """yaml.load which respects order for dictionaries in the yaml file. :param stream: string or streamlike object. """ return yaml.load(stream, Loader=OrderedLoader) def ordered_dump(obj, **kwargs): """yaml.dump which respects order for dictionaries in the yaml object. :param obj: Yaml dumpable object """ return yaml.dump(obj, Dumper=OrderedDumper, **kwargs)
<commit_before>from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(yaml.loader.Loader): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: OrderedDict(loader.construct_pairs(node)), ) class OrderedDumper(yaml.dumper.SafeDumper): pass OrderedDumper.add_representer( OrderedDict, lambda dumper, data: dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), ), ) def ordered_load(stream): """yaml.load which respects order for dictionaries in the yaml file. :param stream: string or streamlike object. """ return yaml.load(stream, Loader=OrderedLoader) def ordered_dump(obj, **kwargs): """yaml.dump which respects order for dictionaries in the yaml object. :param obj: Yaml dumpable object """ return yaml.dump(obj, Dumper=OrderedDumper, **kwargs) <commit_msg>Use the C Loader/Dumper when available<commit_after>
from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(getattr(yaml, 'CSafeLoader', yaml.SafeLoader)): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: OrderedDict(loader.construct_pairs(node)), ) class OrderedDumper(getattr(yaml, 'CSafeDumper', yaml.SafeDumper)): pass OrderedDumper.add_representer( OrderedDict, lambda dumper, data: dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), ), ) def ordered_load(stream): """yaml.load which respects order for dictionaries in the yaml file. :param stream: string or streamlike object. """ return yaml.load(stream, Loader=OrderedLoader) def ordered_dump(obj, **kwargs): """yaml.dump which respects order for dictionaries in the yaml object. :param obj: Yaml dumpable object """ return yaml.dump(obj, Dumper=OrderedDumper, **kwargs)
from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(yaml.loader.Loader): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: OrderedDict(loader.construct_pairs(node)), ) class OrderedDumper(yaml.dumper.SafeDumper): pass OrderedDumper.add_representer( OrderedDict, lambda dumper, data: dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), ), ) def ordered_load(stream): """yaml.load which respects order for dictionaries in the yaml file. :param stream: string or streamlike object. """ return yaml.load(stream, Loader=OrderedLoader) def ordered_dump(obj, **kwargs): """yaml.dump which respects order for dictionaries in the yaml object. :param obj: Yaml dumpable object """ return yaml.dump(obj, Dumper=OrderedDumper, **kwargs) Use the C Loader/Dumper when availablefrom __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(getattr(yaml, 'CSafeLoader', yaml.SafeLoader)): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: OrderedDict(loader.construct_pairs(node)), ) class OrderedDumper(getattr(yaml, 'CSafeDumper', yaml.SafeDumper)): pass OrderedDumper.add_representer( OrderedDict, lambda dumper, data: dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), ), ) def ordered_load(stream): """yaml.load which respects order for dictionaries in the yaml file. :param stream: string or streamlike object. """ return yaml.load(stream, Loader=OrderedLoader) def ordered_dump(obj, **kwargs): """yaml.dump which respects order for dictionaries in the yaml object. :param obj: Yaml dumpable object """ return yaml.dump(obj, Dumper=OrderedDumper, **kwargs)
<commit_before>from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(yaml.loader.Loader): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: OrderedDict(loader.construct_pairs(node)), ) class OrderedDumper(yaml.dumper.SafeDumper): pass OrderedDumper.add_representer( OrderedDict, lambda dumper, data: dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), ), ) def ordered_load(stream): """yaml.load which respects order for dictionaries in the yaml file. :param stream: string or streamlike object. """ return yaml.load(stream, Loader=OrderedLoader) def ordered_dump(obj, **kwargs): """yaml.dump which respects order for dictionaries in the yaml object. :param obj: Yaml dumpable object """ return yaml.dump(obj, Dumper=OrderedDumper, **kwargs) <commit_msg>Use the C Loader/Dumper when available<commit_after>from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(getattr(yaml, 'CSafeLoader', yaml.SafeLoader)): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: OrderedDict(loader.construct_pairs(node)), ) class OrderedDumper(getattr(yaml, 'CSafeDumper', yaml.SafeDumper)): pass OrderedDumper.add_representer( OrderedDict, lambda dumper, data: dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), ), ) def ordered_load(stream): """yaml.load which respects order for dictionaries in the yaml file. :param stream: string or streamlike object. """ return yaml.load(stream, Loader=OrderedLoader) def ordered_dump(obj, **kwargs): """yaml.dump which respects order for dictionaries in the yaml object. :param obj: Yaml dumpable object """ return yaml.dump(obj, Dumper=OrderedDumper, **kwargs)
942b5603da12f43395c0fba35ffd34a31462a023
schedule.py
schedule.py
#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")"
#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")" # The uninterpreted function that's going to become our scheduler. Takes a # 4 bit round, 4 bit match, 2 bit slot, returns a team. print "" print "(declare-fun sparticus ((_ BitVec 4) (_ BitVec 4) (_ BitVec 2)) TEAM)" print ""
Define an uninterpreted scheduling function
Define an uninterpreted scheduling function
Python
bsd-2-clause
jmorse/numbness
#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")" Define an uninterpreted scheduling function
#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")" # The uninterpreted function that's going to become our scheduler. Takes a # 4 bit round, 4 bit match, 2 bit slot, returns a team. print "" print "(declare-fun sparticus ((_ BitVec 4) (_ BitVec 4) (_ BitVec 2)) TEAM)" print ""
<commit_before>#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")" <commit_msg>Define an uninterpreted scheduling function<commit_after>
#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")" # The uninterpreted function that's going to become our scheduler. Takes a # 4 bit round, 4 bit match, 2 bit slot, returns a team. print "" print "(declare-fun sparticus ((_ BitVec 4) (_ BitVec 4) (_ BitVec 2)) TEAM)" print ""
#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")" Define an uninterpreted scheduling function#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")" # The uninterpreted function that's going to become our scheduler. Takes a # 4 bit round, 4 bit match, 2 bit slot, returns a team. print "" print "(declare-fun sparticus ((_ BitVec 4) (_ BitVec 4) (_ BitVec 2)) TEAM)" print ""
<commit_before>#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")" <commit_msg>Define an uninterpreted scheduling function<commit_after>#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")" # The uninterpreted function that's going to become our scheduler. Takes a # 4 bit round, 4 bit match, 2 bit slot, returns a team. print "" print "(declare-fun sparticus ((_ BitVec 4) (_ BitVec 4) (_ BitVec 2)) TEAM)" print ""
5a6b903fc0a309d61e02d020f46ebf2d6c482ed3
tests/factory_tests/test_images.py
tests/factory_tests/test_images.py
from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() file = FileFactory.build().file assert isinstance(file, File) assert isinstance(file.file, BufferedReader) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): file = images.uploadable_file() assert isinstance(file, BufferedReader)
from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images # In Python 2 Django's File wraps the builtin `file`, but that doesn't exist in Python 3. try: FILE_TYPE = file except NameError: FILE_TYPE = BufferedReader def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() built_file = FileFactory.build().file assert isinstance(built_file, File) assert isinstance(built_file.file, FILE_TYPE) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): built_file = images.uploadable_file() assert isinstance(built_file, FILE_TYPE)
Fix the file type asserts on Python 2 (I hope).
Fix the file type asserts on Python 2 (I hope).
Python
bsd-2-clause
incuna/incuna-test-utils,incuna/incuna-test-utils
from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() file = FileFactory.build().file assert isinstance(file, File) assert isinstance(file.file, BufferedReader) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): file = images.uploadable_file() assert isinstance(file, BufferedReader) Fix the file type asserts on Python 2 (I hope).
from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images # In Python 2 Django's File wraps the builtin `file`, but that doesn't exist in Python 3. try: FILE_TYPE = file except NameError: FILE_TYPE = BufferedReader def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() built_file = FileFactory.build().file assert isinstance(built_file, File) assert isinstance(built_file.file, FILE_TYPE) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): built_file = images.uploadable_file() assert isinstance(built_file, FILE_TYPE)
<commit_before>from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() file = FileFactory.build().file assert isinstance(file, File) assert isinstance(file.file, BufferedReader) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): file = images.uploadable_file() assert isinstance(file, BufferedReader) <commit_msg>Fix the file type asserts on Python 2 (I hope).<commit_after>
from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images # In Python 2 Django's File wraps the builtin `file`, but that doesn't exist in Python 3. try: FILE_TYPE = file except NameError: FILE_TYPE = BufferedReader def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() built_file = FileFactory.build().file assert isinstance(built_file, File) assert isinstance(built_file.file, FILE_TYPE) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): built_file = images.uploadable_file() assert isinstance(built_file, FILE_TYPE)
from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() file = FileFactory.build().file assert isinstance(file, File) assert isinstance(file.file, BufferedReader) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): file = images.uploadable_file() assert isinstance(file, BufferedReader) Fix the file type asserts on Python 2 (I hope).from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images # In Python 2 Django's File wraps the builtin `file`, but that doesn't exist in Python 3. try: FILE_TYPE = file except NameError: FILE_TYPE = BufferedReader def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() built_file = FileFactory.build().file assert isinstance(built_file, File) assert isinstance(built_file.file, FILE_TYPE) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): built_file = images.uploadable_file() assert isinstance(built_file, FILE_TYPE)
<commit_before>from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() file = FileFactory.build().file assert isinstance(file, File) assert isinstance(file.file, BufferedReader) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): file = images.uploadable_file() assert isinstance(file, BufferedReader) <commit_msg>Fix the file type asserts on Python 2 (I hope).<commit_after>from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images # In Python 2 Django's File wraps the builtin `file`, but that doesn't exist in Python 3. try: FILE_TYPE = file except NameError: FILE_TYPE = BufferedReader def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() built_file = FileFactory.build().file assert isinstance(built_file, File) assert isinstance(built_file.file, FILE_TYPE) def test_simple_png_file_field(): class FileFactory(factory.StubFactory): image = images.SimplePngFileField() image = FileFactory.build().image assert isinstance(image, BytesIO) def test_uploadable_file(): built_file = images.uploadable_file() assert isinstance(built_file, FILE_TYPE)
6423bb87a392bf6f8abd3b04a0a1bab3181542a0
run_time/src/gae_server/font_mapper.py
run_time/src/gae_server/font_mapper.py
""" Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path
""" Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' elif fontname[0:8] == 'NotoSans': family_dir = 'NotoSans/' elif fontname[0:5] == 'Arimo': family_dir = 'Arimo/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path
Add support for NotoSans and Arimo.
Add support for NotoSans and Arimo.
Python
apache-2.0
googlefonts/TachyFont,googlei18n/TachyFont,moyogo/tachyfont,googlei18n/TachyFont,moyogo/tachyfont,bstell/TachyFont,bstell/TachyFont,bstell/TachyFont,moyogo/tachyfont,googlefonts/TachyFont,googlei18n/TachyFont,googlei18n/TachyFont,googlei18n/TachyFont,moyogo/tachyfont,googlefonts/TachyFont,bstell/TachyFont,googlefonts/TachyFont,moyogo/tachyfont,bstell/TachyFont,googlefonts/TachyFont
""" Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path Add support for NotoSans and Arimo.
""" Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' elif fontname[0:8] == 'NotoSans': family_dir = 'NotoSans/' elif fontname[0:5] == 'Arimo': family_dir = 'Arimo/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path
<commit_before>""" Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path <commit_msg>Add support for NotoSans and Arimo.<commit_after>
""" Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' elif fontname[0:8] == 'NotoSans': family_dir = 'NotoSans/' elif fontname[0:5] == 'Arimo': family_dir = 'Arimo/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path
""" Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path Add support for NotoSans and Arimo.""" Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' elif fontname[0:8] == 'NotoSans': family_dir = 'NotoSans/' elif fontname[0:5] == 'Arimo': family_dir = 'Arimo/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path
<commit_before>""" Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path <commit_msg>Add support for NotoSans and Arimo.<commit_after>""" Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' elif fontname[0:8] == 'NotoSans': family_dir = 'NotoSans/' elif fontname[0:5] == 'Arimo': family_dir = 'Arimo/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path
691ccb9e99240f36ab954974e1ecbdea61c4c7b6
datagroupings/templatetags/key.py
datagroupings/templatetags/key.py
import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='minval') def minval(d, key_name): if d is not None: if d.get(key_name) is not None: minval = json.loads(d.get(key_name)).get('minval') if minval is not None: return minval return '' @register.filter(name='maxval') def maxval(d, key_name): if d is not None: if d.get(key_name) is not None: maxval = json.loads(d.get(key_name)).get('maxval') if maxval is not None: return maxval return ''
import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='minval') def minval(d, key_name): if d is not None: if d.get(key_name) is not None: minval = json.loads(d.get(key_name)).get('minval') if minval is not None: return minval return '' @register.filter(name='maxval') def maxval(d, key_name): if d is not None: if d.get(key_name) is not None: maxval = json.loads(d.get(key_name)).get('maxval') if maxval is not None: return maxval return ''
Fix TemplateTag issue with filters
Fix TemplateTag issue with filters
Python
apache-2.0
nagyistoce/geokey,nagyistoce/geokey,nagyistoce/geokey
import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='minval') def minval(d, key_name): if d is not None: if d.get(key_name) is not None: minval = json.loads(d.get(key_name)).get('minval') if minval is not None: return minval return '' @register.filter(name='maxval') def maxval(d, key_name): if d is not None: if d.get(key_name) is not None: maxval = json.loads(d.get(key_name)).get('maxval') if maxval is not None: return maxval return '' Fix TemplateTag issue with filters
import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='minval') def minval(d, key_name): if d is not None: if d.get(key_name) is not None: minval = json.loads(d.get(key_name)).get('minval') if minval is not None: return minval return '' @register.filter(name='maxval') def maxval(d, key_name): if d is not None: if d.get(key_name) is not None: maxval = json.loads(d.get(key_name)).get('maxval') if maxval is not None: return maxval return ''
<commit_before>import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='minval') def minval(d, key_name): if d is not None: if d.get(key_name) is not None: minval = json.loads(d.get(key_name)).get('minval') if minval is not None: return minval return '' @register.filter(name='maxval') def maxval(d, key_name): if d is not None: if d.get(key_name) is not None: maxval = json.loads(d.get(key_name)).get('maxval') if maxval is not None: return maxval return '' <commit_msg>Fix TemplateTag issue with filters<commit_after>
import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='minval') def minval(d, key_name): if d is not None: if d.get(key_name) is not None: minval = json.loads(d.get(key_name)).get('minval') if minval is not None: return minval return '' @register.filter(name='maxval') def maxval(d, key_name): if d is not None: if d.get(key_name) is not None: maxval = json.loads(d.get(key_name)).get('maxval') if maxval is not None: return maxval return ''
import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='minval') def minval(d, key_name): if d is not None: if d.get(key_name) is not None: minval = json.loads(d.get(key_name)).get('minval') if minval is not None: return minval return '' @register.filter(name='maxval') def maxval(d, key_name): if d is not None: if d.get(key_name) is not None: maxval = json.loads(d.get(key_name)).get('maxval') if maxval is not None: return maxval return '' Fix TemplateTag issue with filtersimport json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='minval') def minval(d, key_name): if d is not None: if d.get(key_name) is not None: minval = json.loads(d.get(key_name)).get('minval') if minval is not None: return minval return '' @register.filter(name='maxval') def maxval(d, key_name): if d is not None: if d.get(key_name) is not None: maxval = json.loads(d.get(key_name)).get('maxval') if maxval is not None: return maxval return ''
<commit_before>import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='minval') def minval(d, key_name): if d is not None: if d.get(key_name) is not None: minval = json.loads(d.get(key_name)).get('minval') if minval is not None: return minval return '' @register.filter(name='maxval') def maxval(d, key_name): if d is not None: if d.get(key_name) is not None: maxval = json.loads(d.get(key_name)).get('maxval') if maxval is not None: return maxval return '' <commit_msg>Fix TemplateTag issue with filters<commit_after>import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='minval') def minval(d, key_name): if d is not None: if d.get(key_name) is not None: minval = json.loads(d.get(key_name)).get('minval') if minval is not None: return minval return '' @register.filter(name='maxval') def maxval(d, key_name): if d is not None: if d.get(key_name) is not None: maxval = json.loads(d.get(key_name)).get('maxval') if maxval is not None: return maxval return ''
8119e33a6074df2140ee9f20011495ac754c4d34
newsApp/notifierBase.py
newsApp/notifierBase.py
import os import logging from datetime import datetime from pytz import timezone logger = logging.getLogger('notifierTwitter') class NotifierBase: def __init__(self): self.domainName = os.environ['DOMAIN'] def isNightTime(self, locale): # for now we only have cities in india india_tz = timezone('Asia/Kolkata') hour = datetime.now(india_tz).hour return hour >= 2 and hour < 7
import os import logging from datetime import datetime from pytz import timezone logger = logging.getLogger('notifierTwitter') class NotifierBase: def __init__(self): self.domainName = os.environ['DOMAIN'] def isNightTime(self, locale): # for now we only have cities in india india_tz = timezone('Asia/Kolkata') hour = datetime.now(india_tz).hour return hour >= 2 and hour < 9
Allow tweets only from 9am
Allow tweets only from 9am
Python
mit
adityabansal/newsAroundMe,adityabansal/newsAroundMe,adityabansal/newsAroundMe
import os import logging from datetime import datetime from pytz import timezone logger = logging.getLogger('notifierTwitter') class NotifierBase: def __init__(self): self.domainName = os.environ['DOMAIN'] def isNightTime(self, locale): # for now we only have cities in india india_tz = timezone('Asia/Kolkata') hour = datetime.now(india_tz).hour return hour >= 2 and hour < 7Allow tweets only from 9am
import os import logging from datetime import datetime from pytz import timezone logger = logging.getLogger('notifierTwitter') class NotifierBase: def __init__(self): self.domainName = os.environ['DOMAIN'] def isNightTime(self, locale): # for now we only have cities in india india_tz = timezone('Asia/Kolkata') hour = datetime.now(india_tz).hour return hour >= 2 and hour < 9
<commit_before>import os import logging from datetime import datetime from pytz import timezone logger = logging.getLogger('notifierTwitter') class NotifierBase: def __init__(self): self.domainName = os.environ['DOMAIN'] def isNightTime(self, locale): # for now we only have cities in india india_tz = timezone('Asia/Kolkata') hour = datetime.now(india_tz).hour return hour >= 2 and hour < 7<commit_msg>Allow tweets only from 9am<commit_after>
import os import logging from datetime import datetime from pytz import timezone logger = logging.getLogger('notifierTwitter') class NotifierBase: def __init__(self): self.domainName = os.environ['DOMAIN'] def isNightTime(self, locale): # for now we only have cities in india india_tz = timezone('Asia/Kolkata') hour = datetime.now(india_tz).hour return hour >= 2 and hour < 9
import os import logging from datetime import datetime from pytz import timezone logger = logging.getLogger('notifierTwitter') class NotifierBase: def __init__(self): self.domainName = os.environ['DOMAIN'] def isNightTime(self, locale): # for now we only have cities in india india_tz = timezone('Asia/Kolkata') hour = datetime.now(india_tz).hour return hour >= 2 and hour < 7Allow tweets only from 9amimport os import logging from datetime import datetime from pytz import timezone logger = logging.getLogger('notifierTwitter') class NotifierBase: def __init__(self): self.domainName = os.environ['DOMAIN'] def isNightTime(self, locale): # for now we only have cities in india india_tz = timezone('Asia/Kolkata') hour = datetime.now(india_tz).hour return hour >= 2 and hour < 9
<commit_before>import os import logging from datetime import datetime from pytz import timezone logger = logging.getLogger('notifierTwitter') class NotifierBase: def __init__(self): self.domainName = os.environ['DOMAIN'] def isNightTime(self, locale): # for now we only have cities in india india_tz = timezone('Asia/Kolkata') hour = datetime.now(india_tz).hour return hour >= 2 and hour < 7<commit_msg>Allow tweets only from 9am<commit_after>import os import logging from datetime import datetime from pytz import timezone logger = logging.getLogger('notifierTwitter') class NotifierBase: def __init__(self): self.domainName = os.environ['DOMAIN'] def isNightTime(self, locale): # for now we only have cities in india india_tz = timezone('Asia/Kolkata') hour = datetime.now(india_tz).hour return hour >= 2 and hour < 9
a7aa0fb21a04b6c6b8e1548f17064462e07e2d74
punic/errors.py
punic/errors.py
from __future__ import division, absolute_import, print_function import contextlib from punic.logger import logger class RepositoryNotClonedError(Exception): pass class CartfileNotFound(Exception): def __init__(self, path): self.path = path class PunicRepresentableError(Exception): pass class NoSuchRevision(Exception): def __init__(self, repository, revision): self.repository = repository self.revision = revision @contextlib.contextmanager def error_handling(): try: yield except RepositoryNotClonedError: logger.error('Error: No locally cloned repository found. Did you neglect to run `punic checkout` first?') exit(-1) except CartfileNotFound as e: logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path)) exit(-1) except NoSuchRevision as e: logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository)) logger.error( 'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`') exit(-1) except PunicRepresentableError as e: logger.error(e.message) exit(-1) except: raise
from __future__ import division, absolute_import, print_function import contextlib from punic.logger import logger class RepositoryNotClonedError(Exception): pass class CartfileNotFound(Exception): def __init__(self, path): self.path = path class PunicRepresentableError(Exception): pass class NoSuchRevision(Exception): def __init__(self, repository, revision): self.repository = repository self.revision = revision @contextlib.contextmanager def error_handling(): try: yield except RepositoryNotClonedError: logger.error('Error: No locally cloned repository found. Did you neglect to run `punic fetch` first?') exit(-1) except CartfileNotFound as e: logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path)) exit(-1) except NoSuchRevision as e: logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository)) logger.error( 'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`') exit(-1) except PunicRepresentableError as e: logger.error(e.message) exit(-1) except: raise
Fix suggested solution for failure to clone.
Fix suggested solution for failure to clone.
Python
mit
schwa/punic
from __future__ import division, absolute_import, print_function import contextlib from punic.logger import logger class RepositoryNotClonedError(Exception): pass class CartfileNotFound(Exception): def __init__(self, path): self.path = path class PunicRepresentableError(Exception): pass class NoSuchRevision(Exception): def __init__(self, repository, revision): self.repository = repository self.revision = revision @contextlib.contextmanager def error_handling(): try: yield except RepositoryNotClonedError: logger.error('Error: No locally cloned repository found. Did you neglect to run `punic checkout` first?') exit(-1) except CartfileNotFound as e: logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path)) exit(-1) except NoSuchRevision as e: logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository)) logger.error( 'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`') exit(-1) except PunicRepresentableError as e: logger.error(e.message) exit(-1) except: raiseFix suggested solution for failure to clone.
from __future__ import division, absolute_import, print_function import contextlib from punic.logger import logger class RepositoryNotClonedError(Exception): pass class CartfileNotFound(Exception): def __init__(self, path): self.path = path class PunicRepresentableError(Exception): pass class NoSuchRevision(Exception): def __init__(self, repository, revision): self.repository = repository self.revision = revision @contextlib.contextmanager def error_handling(): try: yield except RepositoryNotClonedError: logger.error('Error: No locally cloned repository found. Did you neglect to run `punic fetch` first?') exit(-1) except CartfileNotFound as e: logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path)) exit(-1) except NoSuchRevision as e: logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository)) logger.error( 'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`') exit(-1) except PunicRepresentableError as e: logger.error(e.message) exit(-1) except: raise
<commit_before>from __future__ import division, absolute_import, print_function import contextlib from punic.logger import logger class RepositoryNotClonedError(Exception): pass class CartfileNotFound(Exception): def __init__(self, path): self.path = path class PunicRepresentableError(Exception): pass class NoSuchRevision(Exception): def __init__(self, repository, revision): self.repository = repository self.revision = revision @contextlib.contextmanager def error_handling(): try: yield except RepositoryNotClonedError: logger.error('Error: No locally cloned repository found. Did you neglect to run `punic checkout` first?') exit(-1) except CartfileNotFound as e: logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path)) exit(-1) except NoSuchRevision as e: logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository)) logger.error( 'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`') exit(-1) except PunicRepresentableError as e: logger.error(e.message) exit(-1) except: raise<commit_msg>Fix suggested solution for failure to clone.<commit_after>
from __future__ import division, absolute_import, print_function import contextlib from punic.logger import logger class RepositoryNotClonedError(Exception): pass class CartfileNotFound(Exception): def __init__(self, path): self.path = path class PunicRepresentableError(Exception): pass class NoSuchRevision(Exception): def __init__(self, repository, revision): self.repository = repository self.revision = revision @contextlib.contextmanager def error_handling(): try: yield except RepositoryNotClonedError: logger.error('Error: No locally cloned repository found. Did you neglect to run `punic fetch` first?') exit(-1) except CartfileNotFound as e: logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path)) exit(-1) except NoSuchRevision as e: logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository)) logger.error( 'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`') exit(-1) except PunicRepresentableError as e: logger.error(e.message) exit(-1) except: raise
from __future__ import division, absolute_import, print_function import contextlib from punic.logger import logger class RepositoryNotClonedError(Exception): pass class CartfileNotFound(Exception): def __init__(self, path): self.path = path class PunicRepresentableError(Exception): pass class NoSuchRevision(Exception): def __init__(self, repository, revision): self.repository = repository self.revision = revision @contextlib.contextmanager def error_handling(): try: yield except RepositoryNotClonedError: logger.error('Error: No locally cloned repository found. Did you neglect to run `punic checkout` first?') exit(-1) except CartfileNotFound as e: logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path)) exit(-1) except NoSuchRevision as e: logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository)) logger.error( 'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`') exit(-1) except PunicRepresentableError as e: logger.error(e.message) exit(-1) except: raiseFix suggested solution for failure to clone.from __future__ import division, absolute_import, print_function import contextlib from punic.logger import logger class RepositoryNotClonedError(Exception): pass class CartfileNotFound(Exception): def __init__(self, path): self.path = path class PunicRepresentableError(Exception): pass class NoSuchRevision(Exception): def __init__(self, repository, revision): self.repository = repository self.revision = revision @contextlib.contextmanager def error_handling(): try: yield except RepositoryNotClonedError: logger.error('Error: No locally cloned repository found. Did you neglect to run `punic fetch` first?') exit(-1) except CartfileNotFound as e: logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path)) exit(-1) except NoSuchRevision as e: logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository)) logger.error( 'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`') exit(-1) except PunicRepresentableError as e: logger.error(e.message) exit(-1) except: raise
<commit_before>from __future__ import division, absolute_import, print_function import contextlib from punic.logger import logger class RepositoryNotClonedError(Exception): pass class CartfileNotFound(Exception): def __init__(self, path): self.path = path class PunicRepresentableError(Exception): pass class NoSuchRevision(Exception): def __init__(self, repository, revision): self.repository = repository self.revision = revision @contextlib.contextmanager def error_handling(): try: yield except RepositoryNotClonedError: logger.error('Error: No locally cloned repository found. Did you neglect to run `punic checkout` first?') exit(-1) except CartfileNotFound as e: logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path)) exit(-1) except NoSuchRevision as e: logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository)) logger.error( 'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`') exit(-1) except PunicRepresentableError as e: logger.error(e.message) exit(-1) except: raise<commit_msg>Fix suggested solution for failure to clone.<commit_after>from __future__ import division, absolute_import, print_function import contextlib from punic.logger import logger class RepositoryNotClonedError(Exception): pass class CartfileNotFound(Exception): def __init__(self, path): self.path = path class PunicRepresentableError(Exception): pass class NoSuchRevision(Exception): def __init__(self, repository, revision): self.repository = repository self.revision = revision @contextlib.contextmanager def error_handling(): try: yield except RepositoryNotClonedError: logger.error('Error: No locally cloned repository found. Did you neglect to run `punic fetch` first?') exit(-1) except CartfileNotFound as e: logger.error('<err>Error</err>: No Cartfile found at path: <ref>{}</ref>'.format(e.path)) exit(-1) except NoSuchRevision as e: logger.error('<err>Error</err>: No such revision {} found in repository {}'.format(e.revision, e.repository)) logger.error( 'Are you sure you are using the latest bits? Try an explicit `punic fetch` or use `punic bootstrap` instead of `punic build`') exit(-1) except PunicRepresentableError as e: logger.error(e.message) exit(-1) except: raise
1e84e4f8cadd6f776bde4b64839a7e919cb95228
website/addons/s3/tests/factories.py
website/addons/s3/tests/factories.py
# -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket'
# -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): class Meta: model = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): class Meta: model = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket'
Use newer factory-boy Meta syntax for s3
Use newer factory-boy Meta syntax for s3
Python
apache-2.0
mluke93/osf.io,mattclark/osf.io,abought/osf.io,adlius/osf.io,laurenrevere/osf.io,kch8qx/osf.io,RomanZWang/osf.io,chrisseto/osf.io,asanfilippo7/osf.io,hmoco/osf.io,caseyrollins/osf.io,rdhyee/osf.io,brianjgeiger/osf.io,zamattiac/osf.io,alexschiller/osf.io,kch8qx/osf.io,mfraezz/osf.io,alexschiller/osf.io,pattisdr/osf.io,SSJohns/osf.io,leb2dg/osf.io,acshi/osf.io,RomanZWang/osf.io,chennan47/osf.io,emetsger/osf.io,sloria/osf.io,hmoco/osf.io,zachjanicki/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,emetsger/osf.io,kch8qx/osf.io,icereval/osf.io,samchrisinger/osf.io,Nesiehr/osf.io,CenterForOpenScience/osf.io,RomanZWang/osf.io,cslzchen/osf.io,amyshi188/osf.io,mluo613/osf.io,cwisecarver/osf.io,samchrisinger/osf.io,acshi/osf.io,saradbowman/osf.io,DanielSBrown/osf.io,chennan47/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,leb2dg/osf.io,chrisseto/osf.io,leb2dg/osf.io,emetsger/osf.io,rdhyee/osf.io,amyshi188/osf.io,samchrisinger/osf.io,acshi/osf.io,icereval/osf.io,rdhyee/osf.io,alexschiller/osf.io,hmoco/osf.io,Johnetordoff/osf.io,wearpants/osf.io,jnayak1/osf.io,kch8qx/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,mluke93/osf.io,kwierman/osf.io,brianjgeiger/osf.io,amyshi188/osf.io,zamattiac/osf.io,aaxelb/osf.io,binoculars/osf.io,mattclark/osf.io,mfraezz/osf.io,samchrisinger/osf.io,TomHeatwole/osf.io,RomanZWang/osf.io,cwisecarver/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,DanielSBrown/osf.io,laurenrevere/osf.io,TomBaxter/osf.io,Nesiehr/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,Nesiehr/osf.io,kch8qx/osf.io,cslzchen/osf.io,alexschiller/osf.io,SSJohns/osf.io,doublebits/osf.io,leb2dg/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,adlius/osf.io,sloria/osf.io,erinspace/osf.io,zachjanicki/osf.io,caneruguz/osf.io,TomHeatwole/osf.io,crcresearch/osf.io,amyshi188/osf.io,kwierman/osf.io,baylee-d/osf.io,wearpants/osf.io,abought/osf.io,sloria/osf.io,abought/osf.io,doublebits/osf.io,TomBaxter/osf.io,abought/osf.io,monikagrabowska/osf.io,chrisseto/osf.io,baylee-d/osf.io,kwierman/osf.io,DanielSBrown/osf.io,SSJohns/osf.io,binoculars/osf.io,crcresearch/osf.io,HalcyonChimera/osf.io,zamattiac/osf.io,mattclark/osf.io,erinspace/osf.io,DanielSBrown/osf.io,felliott/osf.io,HalcyonChimera/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,TomHeatwole/osf.io,emetsger/osf.io,mluke93/osf.io,acshi/osf.io,aaxelb/osf.io,crcresearch/osf.io,TomHeatwole/osf.io,mluo613/osf.io,hmoco/osf.io,Johnetordoff/osf.io,jnayak1/osf.io,caneruguz/osf.io,asanfilippo7/osf.io,zachjanicki/osf.io,mluo613/osf.io,zachjanicki/osf.io,icereval/osf.io,erinspace/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,baylee-d/osf.io,cwisecarver/osf.io,alexschiller/osf.io,zamattiac/osf.io,felliott/osf.io,mfraezz/osf.io,rdhyee/osf.io,acshi/osf.io,HalcyonChimera/osf.io,kwierman/osf.io,RomanZWang/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,adlius/osf.io,pattisdr/osf.io,wearpants/osf.io,adlius/osf.io,aaxelb/osf.io,mluo613/osf.io,felliott/osf.io,chennan47/osf.io,asanfilippo7/osf.io,chrisseto/osf.io,doublebits/osf.io,cwisecarver/osf.io,doublebits/osf.io,laurenrevere/osf.io,jnayak1/osf.io,SSJohns/osf.io,TomBaxter/osf.io,aaxelb/osf.io,mluke93/osf.io,caseyrollins/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,doublebits/osf.io,mfraezz/osf.io,wearpants/osf.io,mluo613/osf.io
# -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket' Use newer factory-boy Meta syntax for s3
# -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): class Meta: model = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): class Meta: model = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket'
<commit_before># -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket' <commit_msg>Use newer factory-boy Meta syntax for s3<commit_after>
# -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): class Meta: model = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): class Meta: model = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket'
# -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket' Use newer factory-boy Meta syntax for s3# -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): class Meta: model = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): class Meta: model = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket'
<commit_before># -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket' <commit_msg>Use newer factory-boy Meta syntax for s3<commit_after># -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): class Meta: model = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): class Meta: model = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket'
d314504621b3b0d36d8248a4ef36d089cd593108
153957_theme/theme.py
153957_theme/theme.py
"""Use the 153957-theme as theme for the gallery""" from pathlib import Path from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def register(settings): signals.gallery_initialized.connect(theme)
"""Use the 153957-theme as theme for the gallery""" from pathlib import Path from shutil import rmtree from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def remove_leaflet(gallery): """Remove Leaflet which is part of the default static files in sigal, but not used by this theme""" leafet_path = Path(gallery.settings['destination']) / 'static/leaflet' rmtree(leafet_path) def register(settings): signals.gallery_initialized.connect(theme) signals.gallery_build.connect(remove_leaflet)
Remove leaflet static files included by default by sigal
Remove leaflet static files included by default by sigal Leaflet is not used by this theme, those static files are unnecessary.
Python
mit
153957/153957-theme,153957/153957-theme
"""Use the 153957-theme as theme for the gallery""" from pathlib import Path from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def register(settings): signals.gallery_initialized.connect(theme) Remove leaflet static files included by default by sigal Leaflet is not used by this theme, those static files are unnecessary.
"""Use the 153957-theme as theme for the gallery""" from pathlib import Path from shutil import rmtree from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def remove_leaflet(gallery): """Remove Leaflet which is part of the default static files in sigal, but not used by this theme""" leafet_path = Path(gallery.settings['destination']) / 'static/leaflet' rmtree(leafet_path) def register(settings): signals.gallery_initialized.connect(theme) signals.gallery_build.connect(remove_leaflet)
<commit_before>"""Use the 153957-theme as theme for the gallery""" from pathlib import Path from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def register(settings): signals.gallery_initialized.connect(theme) <commit_msg>Remove leaflet static files included by default by sigal Leaflet is not used by this theme, those static files are unnecessary.<commit_after>
"""Use the 153957-theme as theme for the gallery""" from pathlib import Path from shutil import rmtree from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def remove_leaflet(gallery): """Remove Leaflet which is part of the default static files in sigal, but not used by this theme""" leafet_path = Path(gallery.settings['destination']) / 'static/leaflet' rmtree(leafet_path) def register(settings): signals.gallery_initialized.connect(theme) signals.gallery_build.connect(remove_leaflet)
"""Use the 153957-theme as theme for the gallery""" from pathlib import Path from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def register(settings): signals.gallery_initialized.connect(theme) Remove leaflet static files included by default by sigal Leaflet is not used by this theme, those static files are unnecessary."""Use the 153957-theme as theme for the gallery""" from pathlib import Path from shutil import rmtree from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def remove_leaflet(gallery): """Remove Leaflet which is part of the default static files in sigal, but not used by this theme""" leafet_path = Path(gallery.settings['destination']) / 'static/leaflet' rmtree(leafet_path) def register(settings): signals.gallery_initialized.connect(theme) signals.gallery_build.connect(remove_leaflet)
<commit_before>"""Use the 153957-theme as theme for the gallery""" from pathlib import Path from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def register(settings): signals.gallery_initialized.connect(theme) <commit_msg>Remove leaflet static files included by default by sigal Leaflet is not used by this theme, those static files are unnecessary.<commit_after>"""Use the 153957-theme as theme for the gallery""" from pathlib import Path from shutil import rmtree from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def remove_leaflet(gallery): """Remove Leaflet which is part of the default static files in sigal, but not used by this theme""" leafet_path = Path(gallery.settings['destination']) / 'static/leaflet' rmtree(leafet_path) def register(settings): signals.gallery_initialized.connect(theme) signals.gallery_build.connect(remove_leaflet)
3bb79d53e71d3d3b6d22a6958e39e102917e1161
environment_tools/config.py
environment_tools/config.py
# -*- coding: utf-8 -*- import json import os import networkx as nx DATA_DIRECTORY = '/nail/etc/services' def _read_data_json(filename): path = os.path.join(DATA_DIRECTORY, filename) with open(path) as f: return json.load(f) def _convert_mapping_to_graph(dict_mapping): """ Converts the dictionary datacenter layout to a networkx.DiGraph object :param dict_mapping: A dict read out of the location_mapping datafile :returns: A :class:`networkx.DiGraph` object that is a graph representation of the provided mapping. Edges flow from the highest level of the hierarhcy to the lowest level of the hierarchy :rtype: :class:`networkx.DiGraph` """ graph = nx.DiGraph() # Recursively walk the DAG, adding edges as we go # to the closed graph object def _visit(root, subdict): edges = [(root, key) for key in subdict] graph.add_edges_from(edges) for key, value in subdict.items(): _visit(key, value) # We don't have a "root" node at the top of the DAG, # so this just kicks off the recursive process for key, value in dict_mapping.items(): _visit(key, value) return graph
# -*- coding: utf-8 -*- import json import os import networkx as nx DATA_DIRECTORY = '/etc/yelp_location' OVERRIDE_DATA_DIRECTORY = '/nail/etc/services' # FIXME - we're moving from distributing location information # via our configs system to via just baking the package # into AMIs, but to do that we want to be able to read # both whilst we transition - with the existing mechanism # taking preference def _read_data_json(filename): path = os.path.join(OVERRIDE_DATA_DIRECTORY, filename) if not os.path.isfile(path): path = os.path.join(DATA_DIRECTORY, filename) with open(path) as f: return json.load(f) def _convert_mapping_to_graph(dict_mapping): """ Converts the dictionary datacenter layout to a networkx.DiGraph object :param dict_mapping: A dict read out of the location_mapping datafile :returns: A :class:`networkx.DiGraph` object that is a graph representation of the provided mapping. Edges flow from the highest level of the hierarhcy to the lowest level of the hierarchy :rtype: :class:`networkx.DiGraph` """ graph = nx.DiGraph() # Recursively walk the DAG, adding edges as we go # to the closed graph object def _visit(root, subdict): edges = [(root, key) for key in subdict] graph.add_edges_from(edges) for key, value in subdict.items(): _visit(key, value) # We don't have a "root" node at the top of the DAG, # so this just kicks off the recursive process for key, value in dict_mapping.items(): _visit(key, value) return graph
Support a different path to /nail/etc/services
Support a different path to /nail/etc/services This will allow us to distribute location mapping info via an alternate mechanism to yelpsoa-configs, as I want to use IP mapping information in preference to DNS to produce the habitat etc mapping for a machine, and I don't want to make every machine depend on yelpsoa-configs. location-mapping actually changes so infrequently that demanding new AMIs before we can launch hosts in a newly mapped location just doesn't feel like it's a big deal.
Python
apache-2.0
Yelp/environment_tools
# -*- coding: utf-8 -*- import json import os import networkx as nx DATA_DIRECTORY = '/nail/etc/services' def _read_data_json(filename): path = os.path.join(DATA_DIRECTORY, filename) with open(path) as f: return json.load(f) def _convert_mapping_to_graph(dict_mapping): """ Converts the dictionary datacenter layout to a networkx.DiGraph object :param dict_mapping: A dict read out of the location_mapping datafile :returns: A :class:`networkx.DiGraph` object that is a graph representation of the provided mapping. Edges flow from the highest level of the hierarhcy to the lowest level of the hierarchy :rtype: :class:`networkx.DiGraph` """ graph = nx.DiGraph() # Recursively walk the DAG, adding edges as we go # to the closed graph object def _visit(root, subdict): edges = [(root, key) for key in subdict] graph.add_edges_from(edges) for key, value in subdict.items(): _visit(key, value) # We don't have a "root" node at the top of the DAG, # so this just kicks off the recursive process for key, value in dict_mapping.items(): _visit(key, value) return graph Support a different path to /nail/etc/services This will allow us to distribute location mapping info via an alternate mechanism to yelpsoa-configs, as I want to use IP mapping information in preference to DNS to produce the habitat etc mapping for a machine, and I don't want to make every machine depend on yelpsoa-configs. location-mapping actually changes so infrequently that demanding new AMIs before we can launch hosts in a newly mapped location just doesn't feel like it's a big deal.
# -*- coding: utf-8 -*- import json import os import networkx as nx DATA_DIRECTORY = '/etc/yelp_location' OVERRIDE_DATA_DIRECTORY = '/nail/etc/services' # FIXME - we're moving from distributing location information # via our configs system to via just baking the package # into AMIs, but to do that we want to be able to read # both whilst we transition - with the existing mechanism # taking preference def _read_data_json(filename): path = os.path.join(OVERRIDE_DATA_DIRECTORY, filename) if not os.path.isfile(path): path = os.path.join(DATA_DIRECTORY, filename) with open(path) as f: return json.load(f) def _convert_mapping_to_graph(dict_mapping): """ Converts the dictionary datacenter layout to a networkx.DiGraph object :param dict_mapping: A dict read out of the location_mapping datafile :returns: A :class:`networkx.DiGraph` object that is a graph representation of the provided mapping. Edges flow from the highest level of the hierarhcy to the lowest level of the hierarchy :rtype: :class:`networkx.DiGraph` """ graph = nx.DiGraph() # Recursively walk the DAG, adding edges as we go # to the closed graph object def _visit(root, subdict): edges = [(root, key) for key in subdict] graph.add_edges_from(edges) for key, value in subdict.items(): _visit(key, value) # We don't have a "root" node at the top of the DAG, # so this just kicks off the recursive process for key, value in dict_mapping.items(): _visit(key, value) return graph
<commit_before># -*- coding: utf-8 -*- import json import os import networkx as nx DATA_DIRECTORY = '/nail/etc/services' def _read_data_json(filename): path = os.path.join(DATA_DIRECTORY, filename) with open(path) as f: return json.load(f) def _convert_mapping_to_graph(dict_mapping): """ Converts the dictionary datacenter layout to a networkx.DiGraph object :param dict_mapping: A dict read out of the location_mapping datafile :returns: A :class:`networkx.DiGraph` object that is a graph representation of the provided mapping. Edges flow from the highest level of the hierarhcy to the lowest level of the hierarchy :rtype: :class:`networkx.DiGraph` """ graph = nx.DiGraph() # Recursively walk the DAG, adding edges as we go # to the closed graph object def _visit(root, subdict): edges = [(root, key) for key in subdict] graph.add_edges_from(edges) for key, value in subdict.items(): _visit(key, value) # We don't have a "root" node at the top of the DAG, # so this just kicks off the recursive process for key, value in dict_mapping.items(): _visit(key, value) return graph <commit_msg>Support a different path to /nail/etc/services This will allow us to distribute location mapping info via an alternate mechanism to yelpsoa-configs, as I want to use IP mapping information in preference to DNS to produce the habitat etc mapping for a machine, and I don't want to make every machine depend on yelpsoa-configs. location-mapping actually changes so infrequently that demanding new AMIs before we can launch hosts in a newly mapped location just doesn't feel like it's a big deal.<commit_after>
# -*- coding: utf-8 -*- import json import os import networkx as nx DATA_DIRECTORY = '/etc/yelp_location' OVERRIDE_DATA_DIRECTORY = '/nail/etc/services' # FIXME - we're moving from distributing location information # via our configs system to via just baking the package # into AMIs, but to do that we want to be able to read # both whilst we transition - with the existing mechanism # taking preference def _read_data_json(filename): path = os.path.join(OVERRIDE_DATA_DIRECTORY, filename) if not os.path.isfile(path): path = os.path.join(DATA_DIRECTORY, filename) with open(path) as f: return json.load(f) def _convert_mapping_to_graph(dict_mapping): """ Converts the dictionary datacenter layout to a networkx.DiGraph object :param dict_mapping: A dict read out of the location_mapping datafile :returns: A :class:`networkx.DiGraph` object that is a graph representation of the provided mapping. Edges flow from the highest level of the hierarhcy to the lowest level of the hierarchy :rtype: :class:`networkx.DiGraph` """ graph = nx.DiGraph() # Recursively walk the DAG, adding edges as we go # to the closed graph object def _visit(root, subdict): edges = [(root, key) for key in subdict] graph.add_edges_from(edges) for key, value in subdict.items(): _visit(key, value) # We don't have a "root" node at the top of the DAG, # so this just kicks off the recursive process for key, value in dict_mapping.items(): _visit(key, value) return graph
# -*- coding: utf-8 -*- import json import os import networkx as nx DATA_DIRECTORY = '/nail/etc/services' def _read_data_json(filename): path = os.path.join(DATA_DIRECTORY, filename) with open(path) as f: return json.load(f) def _convert_mapping_to_graph(dict_mapping): """ Converts the dictionary datacenter layout to a networkx.DiGraph object :param dict_mapping: A dict read out of the location_mapping datafile :returns: A :class:`networkx.DiGraph` object that is a graph representation of the provided mapping. Edges flow from the highest level of the hierarhcy to the lowest level of the hierarchy :rtype: :class:`networkx.DiGraph` """ graph = nx.DiGraph() # Recursively walk the DAG, adding edges as we go # to the closed graph object def _visit(root, subdict): edges = [(root, key) for key in subdict] graph.add_edges_from(edges) for key, value in subdict.items(): _visit(key, value) # We don't have a "root" node at the top of the DAG, # so this just kicks off the recursive process for key, value in dict_mapping.items(): _visit(key, value) return graph Support a different path to /nail/etc/services This will allow us to distribute location mapping info via an alternate mechanism to yelpsoa-configs, as I want to use IP mapping information in preference to DNS to produce the habitat etc mapping for a machine, and I don't want to make every machine depend on yelpsoa-configs. location-mapping actually changes so infrequently that demanding new AMIs before we can launch hosts in a newly mapped location just doesn't feel like it's a big deal.# -*- coding: utf-8 -*- import json import os import networkx as nx DATA_DIRECTORY = '/etc/yelp_location' OVERRIDE_DATA_DIRECTORY = '/nail/etc/services' # FIXME - we're moving from distributing location information # via our configs system to via just baking the package # into AMIs, but to do that we want to be able to read # both whilst we transition - with the existing mechanism # taking preference def _read_data_json(filename): path = os.path.join(OVERRIDE_DATA_DIRECTORY, filename) if not os.path.isfile(path): path = os.path.join(DATA_DIRECTORY, filename) with open(path) as f: return json.load(f) def _convert_mapping_to_graph(dict_mapping): """ Converts the dictionary datacenter layout to a networkx.DiGraph object :param dict_mapping: A dict read out of the location_mapping datafile :returns: A :class:`networkx.DiGraph` object that is a graph representation of the provided mapping. Edges flow from the highest level of the hierarhcy to the lowest level of the hierarchy :rtype: :class:`networkx.DiGraph` """ graph = nx.DiGraph() # Recursively walk the DAG, adding edges as we go # to the closed graph object def _visit(root, subdict): edges = [(root, key) for key in subdict] graph.add_edges_from(edges) for key, value in subdict.items(): _visit(key, value) # We don't have a "root" node at the top of the DAG, # so this just kicks off the recursive process for key, value in dict_mapping.items(): _visit(key, value) return graph
<commit_before># -*- coding: utf-8 -*- import json import os import networkx as nx DATA_DIRECTORY = '/nail/etc/services' def _read_data_json(filename): path = os.path.join(DATA_DIRECTORY, filename) with open(path) as f: return json.load(f) def _convert_mapping_to_graph(dict_mapping): """ Converts the dictionary datacenter layout to a networkx.DiGraph object :param dict_mapping: A dict read out of the location_mapping datafile :returns: A :class:`networkx.DiGraph` object that is a graph representation of the provided mapping. Edges flow from the highest level of the hierarhcy to the lowest level of the hierarchy :rtype: :class:`networkx.DiGraph` """ graph = nx.DiGraph() # Recursively walk the DAG, adding edges as we go # to the closed graph object def _visit(root, subdict): edges = [(root, key) for key in subdict] graph.add_edges_from(edges) for key, value in subdict.items(): _visit(key, value) # We don't have a "root" node at the top of the DAG, # so this just kicks off the recursive process for key, value in dict_mapping.items(): _visit(key, value) return graph <commit_msg>Support a different path to /nail/etc/services This will allow us to distribute location mapping info via an alternate mechanism to yelpsoa-configs, as I want to use IP mapping information in preference to DNS to produce the habitat etc mapping for a machine, and I don't want to make every machine depend on yelpsoa-configs. location-mapping actually changes so infrequently that demanding new AMIs before we can launch hosts in a newly mapped location just doesn't feel like it's a big deal.<commit_after># -*- coding: utf-8 -*- import json import os import networkx as nx DATA_DIRECTORY = '/etc/yelp_location' OVERRIDE_DATA_DIRECTORY = '/nail/etc/services' # FIXME - we're moving from distributing location information # via our configs system to via just baking the package # into AMIs, but to do that we want to be able to read # both whilst we transition - with the existing mechanism # taking preference def _read_data_json(filename): path = os.path.join(OVERRIDE_DATA_DIRECTORY, filename) if not os.path.isfile(path): path = os.path.join(DATA_DIRECTORY, filename) with open(path) as f: return json.load(f) def _convert_mapping_to_graph(dict_mapping): """ Converts the dictionary datacenter layout to a networkx.DiGraph object :param dict_mapping: A dict read out of the location_mapping datafile :returns: A :class:`networkx.DiGraph` object that is a graph representation of the provided mapping. Edges flow from the highest level of the hierarhcy to the lowest level of the hierarchy :rtype: :class:`networkx.DiGraph` """ graph = nx.DiGraph() # Recursively walk the DAG, adding edges as we go # to the closed graph object def _visit(root, subdict): edges = [(root, key) for key in subdict] graph.add_edges_from(edges) for key, value in subdict.items(): _visit(key, value) # We don't have a "root" node at the top of the DAG, # so this just kicks off the recursive process for key, value in dict_mapping.items(): _visit(key, value) return graph
57ca59e225119a031dee6b0c10a27c43a41f56ce
settings.py
settings.py
# ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
# ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTPORT = 1300 ZONEENDPORT = 1400 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
Add a zone port range.
Add a zone port range.
Python
agpl-3.0
cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO
# ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS Add a zone port range.
# ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTPORT = 1300 ZONEENDPORT = 1400 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
<commit_before># ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS <commit_msg>Add a zone port range.<commit_after>
# ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTPORT = 1300 ZONEENDPORT = 1400 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
# ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS Add a zone port range.# ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTPORT = 1300 ZONEENDPORT = 1400 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
<commit_before># ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS <commit_msg>Add a zone port range.<commit_after># ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTPORT = 1300 ZONEENDPORT = 1400 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
402cf0192a7c90ced34acd7bdf1a93c487389a1f
python/setup.py
python/setup.py
from setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copy(SO_PATH, os.path.join(PIP_DIR, 'storehouse')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*' + EXT, ] }, license='Apache 2.0' )
from setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copyfile( SO_PATH, os.path.join(PIP_DIR, 'storehouse', 'libstorehouse.so')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*.so', ] }, license='Apache 2.0' )
Rename extension to .so so python can import
Rename extension to .so so python can import
Python
apache-2.0
scanner-research/storehouse,apoms/storehouse,scanner-research/storehouse,scanner-research/storehouse
from setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copy(SO_PATH, os.path.join(PIP_DIR, 'storehouse')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*' + EXT, ] }, license='Apache 2.0' ) Rename extension to .so so python can import
from setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copyfile( SO_PATH, os.path.join(PIP_DIR, 'storehouse', 'libstorehouse.so')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*.so', ] }, license='Apache 2.0' )
<commit_before>from setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copy(SO_PATH, os.path.join(PIP_DIR, 'storehouse')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*' + EXT, ] }, license='Apache 2.0' ) <commit_msg>Rename extension to .so so python can import<commit_after>
from setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copyfile( SO_PATH, os.path.join(PIP_DIR, 'storehouse', 'libstorehouse.so')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*.so', ] }, license='Apache 2.0' )
from setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copy(SO_PATH, os.path.join(PIP_DIR, 'storehouse')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*' + EXT, ] }, license='Apache 2.0' ) Rename extension to .so so python can importfrom setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copyfile( SO_PATH, os.path.join(PIP_DIR, 'storehouse', 'libstorehouse.so')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*.so', ] }, license='Apache 2.0' )
<commit_before>from setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copy(SO_PATH, os.path.join(PIP_DIR, 'storehouse')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*' + EXT, ] }, license='Apache 2.0' ) <commit_msg>Rename extension to .so so python can import<commit_after>from setuptools import setup import os import shutil from sys import platform if platform == 'linux' or platform == 'linux2': EXT = '.so' else: EXT = '.dylib' SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) STOREHOUSE_DIR = '.' BUILD_DIR = os.path.join(STOREHOUSE_DIR, 'build') PIP_DIR = os.path.join(BUILD_DIR, 'pip') SO_PATH = os.path.join(BUILD_DIR, 'libstorehouse' + EXT) shutil.rmtree(PIP_DIR, ignore_errors=True) shutil.copytree(SCRIPT_DIR, PIP_DIR) shutil.copyfile( SO_PATH, os.path.join(PIP_DIR, 'storehouse', 'libstorehouse.so')) setup( name='storehouse', version='0.4.1', url='https://github.com/scanner-research/storehouse', author='Alex Poms and Will Crichton', author_email='wcrichto@cs.stanford.edu', package_dir={'': PIP_DIR}, packages=['storehouse'], package_data={ 'storehouse': [ '*.so', ] }, license='Apache 2.0' )
a8a5fa7327e11964f130c8590994dd000c1f7e06
qiime_studio/server.py
qiime_studio/server.py
import webbrowser from flask import Flask, jsonify from gevent.pywsgi import WSGIServer from qiime_studio.api.security import make_url from qiime_studio.api.v1 import v1 from qiime_studio.static import static_files studio = Flask('qiime_studio') studio.register_blueprint(v1, url_prefix='/api/0.0.1') studio.debug = True @studio.route("/api/", methods=['GET']) def available_api(): return jsonify(available=["/api/0.0.1/"]) @studio.route("/", methods=['GET']) def hello(): return "Hello World!" def start_server(port, domain, in_dev, run_local, skip_open): host = "%s:%d/api/" % (domain, port) ihost = "qiime.studio/" if run_local: ihost = "%s:%d" % (domain, port) studio.register_blueprint(static_files) elif in_dev: ihost = "localhost:4242" url = make_url(host, ihost) print("Your QIIME Studio server is starting.") print("Please visit the following URL to access:\n") print(url) if not skip_open: webbrowser.open(url) WSGIServer((domain, port), studio).serve_forever()
import webbrowser from flask import Flask, jsonify from gevent.pywsgi import WSGIServer from qiime_studio.api.security import make_url from qiime_studio.api.cors import add_cors_headers from qiime_studio.api.v1 import v1 from qiime_studio.static import static_files studio = Flask('qiime_studio') studio.register_blueprint(v1, url_prefix='/api/0.0.1') studio.debug = True studio.after_request(add_cors_headers) @studio.route("/api/", methods=['GET']) def available_api(): return jsonify(available=["/api/0.0.1/"]) @studio.route("/", methods=['GET']) def hello(): return "Hello World!" def start_server(port, domain, in_dev, run_local, skip_open): host = "%s:%d/api/" % (domain, port) ihost = "qiime.studio/" if run_local: ihost = "%s:%d" % (domain, port) studio.register_blueprint(static_files) elif in_dev: ihost = "localhost:4242" url = make_url(host, ihost) print("Your QIIME Studio server is starting.") print("Please visit the following URL to access:\n") print(url) if not skip_open: webbrowser.open(url) WSGIServer((domain, port), studio).serve_forever()
Add CORS headers to main studio Flask application, to allow initial API version request
Add CORS headers to main studio Flask application, to allow initial API version request Remove before_request from main application
Python
bsd-3-clause
qiime2/qiime-studio,qiime2/qiime-studio,jakereps/qiime-studio,jakereps/qiime-studio-frontend,qiime2/qiime-studio-frontend,jakereps/qiime-studio,jakereps/qiime-studio,jakereps/qiime-studio-frontend,qiime2/qiime-studio-frontend,qiime2/qiime-studio
import webbrowser from flask import Flask, jsonify from gevent.pywsgi import WSGIServer from qiime_studio.api.security import make_url from qiime_studio.api.v1 import v1 from qiime_studio.static import static_files studio = Flask('qiime_studio') studio.register_blueprint(v1, url_prefix='/api/0.0.1') studio.debug = True @studio.route("/api/", methods=['GET']) def available_api(): return jsonify(available=["/api/0.0.1/"]) @studio.route("/", methods=['GET']) def hello(): return "Hello World!" def start_server(port, domain, in_dev, run_local, skip_open): host = "%s:%d/api/" % (domain, port) ihost = "qiime.studio/" if run_local: ihost = "%s:%d" % (domain, port) studio.register_blueprint(static_files) elif in_dev: ihost = "localhost:4242" url = make_url(host, ihost) print("Your QIIME Studio server is starting.") print("Please visit the following URL to access:\n") print(url) if not skip_open: webbrowser.open(url) WSGIServer((domain, port), studio).serve_forever() Add CORS headers to main studio Flask application, to allow initial API version request Remove before_request from main application
import webbrowser from flask import Flask, jsonify from gevent.pywsgi import WSGIServer from qiime_studio.api.security import make_url from qiime_studio.api.cors import add_cors_headers from qiime_studio.api.v1 import v1 from qiime_studio.static import static_files studio = Flask('qiime_studio') studio.register_blueprint(v1, url_prefix='/api/0.0.1') studio.debug = True studio.after_request(add_cors_headers) @studio.route("/api/", methods=['GET']) def available_api(): return jsonify(available=["/api/0.0.1/"]) @studio.route("/", methods=['GET']) def hello(): return "Hello World!" def start_server(port, domain, in_dev, run_local, skip_open): host = "%s:%d/api/" % (domain, port) ihost = "qiime.studio/" if run_local: ihost = "%s:%d" % (domain, port) studio.register_blueprint(static_files) elif in_dev: ihost = "localhost:4242" url = make_url(host, ihost) print("Your QIIME Studio server is starting.") print("Please visit the following URL to access:\n") print(url) if not skip_open: webbrowser.open(url) WSGIServer((domain, port), studio).serve_forever()
<commit_before>import webbrowser from flask import Flask, jsonify from gevent.pywsgi import WSGIServer from qiime_studio.api.security import make_url from qiime_studio.api.v1 import v1 from qiime_studio.static import static_files studio = Flask('qiime_studio') studio.register_blueprint(v1, url_prefix='/api/0.0.1') studio.debug = True @studio.route("/api/", methods=['GET']) def available_api(): return jsonify(available=["/api/0.0.1/"]) @studio.route("/", methods=['GET']) def hello(): return "Hello World!" def start_server(port, domain, in_dev, run_local, skip_open): host = "%s:%d/api/" % (domain, port) ihost = "qiime.studio/" if run_local: ihost = "%s:%d" % (domain, port) studio.register_blueprint(static_files) elif in_dev: ihost = "localhost:4242" url = make_url(host, ihost) print("Your QIIME Studio server is starting.") print("Please visit the following URL to access:\n") print(url) if not skip_open: webbrowser.open(url) WSGIServer((domain, port), studio).serve_forever() <commit_msg>Add CORS headers to main studio Flask application, to allow initial API version request Remove before_request from main application<commit_after>
import webbrowser from flask import Flask, jsonify from gevent.pywsgi import WSGIServer from qiime_studio.api.security import make_url from qiime_studio.api.cors import add_cors_headers from qiime_studio.api.v1 import v1 from qiime_studio.static import static_files studio = Flask('qiime_studio') studio.register_blueprint(v1, url_prefix='/api/0.0.1') studio.debug = True studio.after_request(add_cors_headers) @studio.route("/api/", methods=['GET']) def available_api(): return jsonify(available=["/api/0.0.1/"]) @studio.route("/", methods=['GET']) def hello(): return "Hello World!" def start_server(port, domain, in_dev, run_local, skip_open): host = "%s:%d/api/" % (domain, port) ihost = "qiime.studio/" if run_local: ihost = "%s:%d" % (domain, port) studio.register_blueprint(static_files) elif in_dev: ihost = "localhost:4242" url = make_url(host, ihost) print("Your QIIME Studio server is starting.") print("Please visit the following URL to access:\n") print(url) if not skip_open: webbrowser.open(url) WSGIServer((domain, port), studio).serve_forever()
import webbrowser from flask import Flask, jsonify from gevent.pywsgi import WSGIServer from qiime_studio.api.security import make_url from qiime_studio.api.v1 import v1 from qiime_studio.static import static_files studio = Flask('qiime_studio') studio.register_blueprint(v1, url_prefix='/api/0.0.1') studio.debug = True @studio.route("/api/", methods=['GET']) def available_api(): return jsonify(available=["/api/0.0.1/"]) @studio.route("/", methods=['GET']) def hello(): return "Hello World!" def start_server(port, domain, in_dev, run_local, skip_open): host = "%s:%d/api/" % (domain, port) ihost = "qiime.studio/" if run_local: ihost = "%s:%d" % (domain, port) studio.register_blueprint(static_files) elif in_dev: ihost = "localhost:4242" url = make_url(host, ihost) print("Your QIIME Studio server is starting.") print("Please visit the following URL to access:\n") print(url) if not skip_open: webbrowser.open(url) WSGIServer((domain, port), studio).serve_forever() Add CORS headers to main studio Flask application, to allow initial API version request Remove before_request from main applicationimport webbrowser from flask import Flask, jsonify from gevent.pywsgi import WSGIServer from qiime_studio.api.security import make_url from qiime_studio.api.cors import add_cors_headers from qiime_studio.api.v1 import v1 from qiime_studio.static import static_files studio = Flask('qiime_studio') studio.register_blueprint(v1, url_prefix='/api/0.0.1') studio.debug = True studio.after_request(add_cors_headers) @studio.route("/api/", methods=['GET']) def available_api(): return jsonify(available=["/api/0.0.1/"]) @studio.route("/", methods=['GET']) def hello(): return "Hello World!" def start_server(port, domain, in_dev, run_local, skip_open): host = "%s:%d/api/" % (domain, port) ihost = "qiime.studio/" if run_local: ihost = "%s:%d" % (domain, port) studio.register_blueprint(static_files) elif in_dev: ihost = "localhost:4242" url = make_url(host, ihost) print("Your QIIME Studio server is starting.") print("Please visit the following URL to access:\n") print(url) if not skip_open: webbrowser.open(url) WSGIServer((domain, port), studio).serve_forever()
<commit_before>import webbrowser from flask import Flask, jsonify from gevent.pywsgi import WSGIServer from qiime_studio.api.security import make_url from qiime_studio.api.v1 import v1 from qiime_studio.static import static_files studio = Flask('qiime_studio') studio.register_blueprint(v1, url_prefix='/api/0.0.1') studio.debug = True @studio.route("/api/", methods=['GET']) def available_api(): return jsonify(available=["/api/0.0.1/"]) @studio.route("/", methods=['GET']) def hello(): return "Hello World!" def start_server(port, domain, in_dev, run_local, skip_open): host = "%s:%d/api/" % (domain, port) ihost = "qiime.studio/" if run_local: ihost = "%s:%d" % (domain, port) studio.register_blueprint(static_files) elif in_dev: ihost = "localhost:4242" url = make_url(host, ihost) print("Your QIIME Studio server is starting.") print("Please visit the following URL to access:\n") print(url) if not skip_open: webbrowser.open(url) WSGIServer((domain, port), studio).serve_forever() <commit_msg>Add CORS headers to main studio Flask application, to allow initial API version request Remove before_request from main application<commit_after>import webbrowser from flask import Flask, jsonify from gevent.pywsgi import WSGIServer from qiime_studio.api.security import make_url from qiime_studio.api.cors import add_cors_headers from qiime_studio.api.v1 import v1 from qiime_studio.static import static_files studio = Flask('qiime_studio') studio.register_blueprint(v1, url_prefix='/api/0.0.1') studio.debug = True studio.after_request(add_cors_headers) @studio.route("/api/", methods=['GET']) def available_api(): return jsonify(available=["/api/0.0.1/"]) @studio.route("/", methods=['GET']) def hello(): return "Hello World!" def start_server(port, domain, in_dev, run_local, skip_open): host = "%s:%d/api/" % (domain, port) ihost = "qiime.studio/" if run_local: ihost = "%s:%d" % (domain, port) studio.register_blueprint(static_files) elif in_dev: ihost = "localhost:4242" url = make_url(host, ihost) print("Your QIIME Studio server is starting.") print("Please visit the following URL to access:\n") print(url) if not skip_open: webbrowser.open(url) WSGIServer((domain, port), studio).serve_forever()
2a6e7ffdfcaa916557da2e65ad23d3789d430dbd
doc/examples/plot_rag_draw.py
doc/examples/plot_rag_draw.py
""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with cubehelix colormap") cmap = plt.get_cmap('cubehelix') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show()
""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with viridis colormap") cmap = plt.get_cmap('viridis') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show()
Replace cubehelix with the viridis colormap in the RAG drawing example
Replace cubehelix with the viridis colormap in the RAG drawing example
Python
bsd-3-clause
rjeli/scikit-image,paalge/scikit-image,oew1v07/scikit-image,ClinicalGraphics/scikit-image,WarrenWeckesser/scikits-image,vighneshbirodkar/scikit-image,emon10005/scikit-image,rjeli/scikit-image,Midafi/scikit-image,blink1073/scikit-image,rjeli/scikit-image,youprofit/scikit-image,jwiggins/scikit-image,ajaybhat/scikit-image,keflavich/scikit-image,pratapvardhan/scikit-image,ofgulban/scikit-image,oew1v07/scikit-image,paalge/scikit-image,vighneshbirodkar/scikit-image,Hiyorimi/scikit-image,Midafi/scikit-image,ajaybhat/scikit-image,jwiggins/scikit-image,youprofit/scikit-image,WarrenWeckesser/scikits-image,chriscrosscutler/scikit-image,ClinicalGraphics/scikit-image,juliusbierk/scikit-image,emon10005/scikit-image,juliusbierk/scikit-image,Hiyorimi/scikit-image,chriscrosscutler/scikit-image,ofgulban/scikit-image,pratapvardhan/scikit-image,paalge/scikit-image,blink1073/scikit-image,vighneshbirodkar/scikit-image,keflavich/scikit-image,ofgulban/scikit-image
""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with cubehelix colormap") cmap = plt.get_cmap('cubehelix') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show() Replace cubehelix with the viridis colormap in the RAG drawing example
""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with viridis colormap") cmap = plt.get_cmap('viridis') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show()
<commit_before>""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with cubehelix colormap") cmap = plt.get_cmap('cubehelix') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show() <commit_msg>Replace cubehelix with the viridis colormap in the RAG drawing example<commit_after>
""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with viridis colormap") cmap = plt.get_cmap('viridis') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show()
""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with cubehelix colormap") cmap = plt.get_cmap('cubehelix') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show() Replace cubehelix with the viridis colormap in the RAG drawing example""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with viridis colormap") cmap = plt.get_cmap('viridis') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show()
<commit_before>""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with cubehelix colormap") cmap = plt.get_cmap('cubehelix') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show() <commit_msg>Replace cubehelix with the viridis colormap in the RAG drawing example<commit_after>""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with viridis colormap") cmap = plt.get_cmap('viridis') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show()
7c33ff3ff94b933fe9e5c8b53fa08041ef8ee404
runserver.py
runserver.py
from geomancer import create_app app = create_app() if __name__ == "__main__": app.run(debug=True)
from geomancer import create_app app = create_app() if __name__ == "__main__": import sys try: port = int(sys.argv[1]) except IndexError: port = 5000 app.run(debug=True, port=port)
Make it so we can choose port
Make it so we can choose port
Python
mit
associatedpress/geomancer,associatedpress/geomancer,datamade/geomancer,associatedpress/geomancer,datamade/geomancer,datamade/geomancer
from geomancer import create_app app = create_app() if __name__ == "__main__": app.run(debug=True) Make it so we can choose port
from geomancer import create_app app = create_app() if __name__ == "__main__": import sys try: port = int(sys.argv[1]) except IndexError: port = 5000 app.run(debug=True, port=port)
<commit_before>from geomancer import create_app app = create_app() if __name__ == "__main__": app.run(debug=True) <commit_msg>Make it so we can choose port<commit_after>
from geomancer import create_app app = create_app() if __name__ == "__main__": import sys try: port = int(sys.argv[1]) except IndexError: port = 5000 app.run(debug=True, port=port)
from geomancer import create_app app = create_app() if __name__ == "__main__": app.run(debug=True) Make it so we can choose portfrom geomancer import create_app app = create_app() if __name__ == "__main__": import sys try: port = int(sys.argv[1]) except IndexError: port = 5000 app.run(debug=True, port=port)
<commit_before>from geomancer import create_app app = create_app() if __name__ == "__main__": app.run(debug=True) <commit_msg>Make it so we can choose port<commit_after>from geomancer import create_app app = create_app() if __name__ == "__main__": import sys try: port = int(sys.argv[1]) except IndexError: port = 5000 app.run(debug=True, port=port)
38bc8c8599d4165485ada8ca0b55dafd547385c4
runserver.py
runserver.py
import sys from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi if __name__ == '__main__': conf_file, options = parse_options() sys.exit(run_wsgi(conf_file, 'proxy-server', **options))
import sys from optparse import OptionParser from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi def run_objgraph(types): import objgraph import os import random objgraph.show_most_common_types(limit=50, shortnames=False) for type_ in types: count = objgraph.count(type_) print '%s objects: %d' % (type_, count) if count: objgraph.show_backrefs( random.choice(objgraph.by_type(type_)), max_depth=20, filename='/tmp/backrefs_%s_%d.dot' % (type_, os.getpid())) if __name__ == '__main__': parser = OptionParser(usage="%prog CONFIG [options]") parser.add_option('--objgraph', action='store_true', help=('Run objgraph, show most common ' 'types before exiting')) parser.add_option('--show-backrefs', action='append', default=list(), help=('Draw backreference graph for one randomly ' 'chosen object of that type. Can be used ' 'multiple times.')) conf_file, options = parse_options(parser) res = run_wsgi(conf_file, 'proxy-server', **options) if options.get('objgraph'): run_objgraph(options.get('show_backrefs', list())) sys.exit(res)
Allow to run objgraph before exiting
Allow to run objgraph before exiting Use "--objgraph" to show most common types. Add "--show-backrefs <some type>" do draw a graph of backreferences.
Python
apache-2.0
open-io/oio-swift,open-io/oio-swift
import sys from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi if __name__ == '__main__': conf_file, options = parse_options() sys.exit(run_wsgi(conf_file, 'proxy-server', **options)) Allow to run objgraph before exiting Use "--objgraph" to show most common types. Add "--show-backrefs <some type>" do draw a graph of backreferences.
import sys from optparse import OptionParser from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi def run_objgraph(types): import objgraph import os import random objgraph.show_most_common_types(limit=50, shortnames=False) for type_ in types: count = objgraph.count(type_) print '%s objects: %d' % (type_, count) if count: objgraph.show_backrefs( random.choice(objgraph.by_type(type_)), max_depth=20, filename='/tmp/backrefs_%s_%d.dot' % (type_, os.getpid())) if __name__ == '__main__': parser = OptionParser(usage="%prog CONFIG [options]") parser.add_option('--objgraph', action='store_true', help=('Run objgraph, show most common ' 'types before exiting')) parser.add_option('--show-backrefs', action='append', default=list(), help=('Draw backreference graph for one randomly ' 'chosen object of that type. Can be used ' 'multiple times.')) conf_file, options = parse_options(parser) res = run_wsgi(conf_file, 'proxy-server', **options) if options.get('objgraph'): run_objgraph(options.get('show_backrefs', list())) sys.exit(res)
<commit_before>import sys from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi if __name__ == '__main__': conf_file, options = parse_options() sys.exit(run_wsgi(conf_file, 'proxy-server', **options)) <commit_msg>Allow to run objgraph before exiting Use "--objgraph" to show most common types. Add "--show-backrefs <some type>" do draw a graph of backreferences.<commit_after>
import sys from optparse import OptionParser from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi def run_objgraph(types): import objgraph import os import random objgraph.show_most_common_types(limit=50, shortnames=False) for type_ in types: count = objgraph.count(type_) print '%s objects: %d' % (type_, count) if count: objgraph.show_backrefs( random.choice(objgraph.by_type(type_)), max_depth=20, filename='/tmp/backrefs_%s_%d.dot' % (type_, os.getpid())) if __name__ == '__main__': parser = OptionParser(usage="%prog CONFIG [options]") parser.add_option('--objgraph', action='store_true', help=('Run objgraph, show most common ' 'types before exiting')) parser.add_option('--show-backrefs', action='append', default=list(), help=('Draw backreference graph for one randomly ' 'chosen object of that type. Can be used ' 'multiple times.')) conf_file, options = parse_options(parser) res = run_wsgi(conf_file, 'proxy-server', **options) if options.get('objgraph'): run_objgraph(options.get('show_backrefs', list())) sys.exit(res)
import sys from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi if __name__ == '__main__': conf_file, options = parse_options() sys.exit(run_wsgi(conf_file, 'proxy-server', **options)) Allow to run objgraph before exiting Use "--objgraph" to show most common types. Add "--show-backrefs <some type>" do draw a graph of backreferences.import sys from optparse import OptionParser from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi def run_objgraph(types): import objgraph import os import random objgraph.show_most_common_types(limit=50, shortnames=False) for type_ in types: count = objgraph.count(type_) print '%s objects: %d' % (type_, count) if count: objgraph.show_backrefs( random.choice(objgraph.by_type(type_)), max_depth=20, filename='/tmp/backrefs_%s_%d.dot' % (type_, os.getpid())) if __name__ == '__main__': parser = OptionParser(usage="%prog CONFIG [options]") parser.add_option('--objgraph', action='store_true', help=('Run objgraph, show most common ' 'types before exiting')) parser.add_option('--show-backrefs', action='append', default=list(), help=('Draw backreference graph for one randomly ' 'chosen object of that type. Can be used ' 'multiple times.')) conf_file, options = parse_options(parser) res = run_wsgi(conf_file, 'proxy-server', **options) if options.get('objgraph'): run_objgraph(options.get('show_backrefs', list())) sys.exit(res)
<commit_before>import sys from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi if __name__ == '__main__': conf_file, options = parse_options() sys.exit(run_wsgi(conf_file, 'proxy-server', **options)) <commit_msg>Allow to run objgraph before exiting Use "--objgraph" to show most common types. Add "--show-backrefs <some type>" do draw a graph of backreferences.<commit_after>import sys from optparse import OptionParser from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi def run_objgraph(types): import objgraph import os import random objgraph.show_most_common_types(limit=50, shortnames=False) for type_ in types: count = objgraph.count(type_) print '%s objects: %d' % (type_, count) if count: objgraph.show_backrefs( random.choice(objgraph.by_type(type_)), max_depth=20, filename='/tmp/backrefs_%s_%d.dot' % (type_, os.getpid())) if __name__ == '__main__': parser = OptionParser(usage="%prog CONFIG [options]") parser.add_option('--objgraph', action='store_true', help=('Run objgraph, show most common ' 'types before exiting')) parser.add_option('--show-backrefs', action='append', default=list(), help=('Draw backreference graph for one randomly ' 'chosen object of that type. Can be used ' 'multiple times.')) conf_file, options = parse_options(parser) res = run_wsgi(conf_file, 'proxy-server', **options) if options.get('objgraph'): run_objgraph(options.get('show_backrefs', list())) sys.exit(res)
2280d17fc2c6c144c1490617811b4665d5d41545
tests/unit/test_context.py
tests/unit/test_context.py
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack.common import context from openstack.common import test class ContextTest(test.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted)
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslotest import base as test_base from openstack.common import context class ContextTest(test_base.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted)
Use oslotest instead of common test module
Use oslotest instead of common test module Module openstack.common.test is obsolete, so we should use oslotest library instead of it. Modified tests and common database code, new requirement added. Change-Id: I853e548f11a4c3785eaf75124510a6d789536634
Python
apache-2.0
varunarya10/oslo.context,JioCloud/oslo.context,dims/oslo.context,citrix-openstack-build/oslo.context,openstack/oslo.context,yanheven/oslo.middleware
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack.common import context from openstack.common import test class ContextTest(test.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted) Use oslotest instead of common test module Module openstack.common.test is obsolete, so we should use oslotest library instead of it. Modified tests and common database code, new requirement added. Change-Id: I853e548f11a4c3785eaf75124510a6d789536634
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslotest import base as test_base from openstack.common import context class ContextTest(test_base.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted)
<commit_before># Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack.common import context from openstack.common import test class ContextTest(test.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted) <commit_msg>Use oslotest instead of common test module Module openstack.common.test is obsolete, so we should use oslotest library instead of it. Modified tests and common database code, new requirement added. Change-Id: I853e548f11a4c3785eaf75124510a6d789536634<commit_after>
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslotest import base as test_base from openstack.common import context class ContextTest(test_base.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted)
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack.common import context from openstack.common import test class ContextTest(test.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted) Use oslotest instead of common test module Module openstack.common.test is obsolete, so we should use oslotest library instead of it. Modified tests and common database code, new requirement added. Change-Id: I853e548f11a4c3785eaf75124510a6d789536634# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslotest import base as test_base from openstack.common import context class ContextTest(test_base.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted)
<commit_before># Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack.common import context from openstack.common import test class ContextTest(test.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted) <commit_msg>Use oslotest instead of common test module Module openstack.common.test is obsolete, so we should use oslotest library instead of it. Modified tests and common database code, new requirement added. Change-Id: I853e548f11a4c3785eaf75124510a6d789536634<commit_after># Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslotest import base as test_base from openstack.common import context class ContextTest(test_base.BaseTestCase): def test_context(self): ctx = context.RequestContext() self.assertTrue(ctx) def test_admin_context_show_deleted_flag_default(self): ctx = context.get_admin_context() self.assertFalse(ctx.show_deleted)
03f3ee254c2a1c4ebd91728263b66ff29e8b4f78
defenses/torch/audio/input_tranformation/resampling.py
defenses/torch/audio/input_tranformation/resampling.py
import torchaudio import librosa # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1)
import torchaudio import librosa # There exist a limitation of this defense that it may lead to the problem of aliasing, and we can use the narrowband sample rate # rather than downsampling followed by upsampling. # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1)
Add limitation of this defence in the comment
Add limitation of this defence in the comment
Python
mit
cleverhans-lab/cleverhans,cleverhans-lab/cleverhans,cleverhans-lab/cleverhans
import torchaudio import librosa # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1) Add limitation of this defence in the comment
import torchaudio import librosa # There exist a limitation of this defense that it may lead to the problem of aliasing, and we can use the narrowband sample rate # rather than downsampling followed by upsampling. # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1)
<commit_before>import torchaudio import librosa # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1) <commit_msg>Add limitation of this defence in the comment<commit_after>
import torchaudio import librosa # There exist a limitation of this defense that it may lead to the problem of aliasing, and we can use the narrowband sample rate # rather than downsampling followed by upsampling. # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1)
import torchaudio import librosa # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1) Add limitation of this defence in the commentimport torchaudio import librosa # There exist a limitation of this defense that it may lead to the problem of aliasing, and we can use the narrowband sample rate # rather than downsampling followed by upsampling. # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1)
<commit_before>import torchaudio import librosa # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1) <commit_msg>Add limitation of this defence in the comment<commit_after>import torchaudio import librosa # There exist a limitation of this defense that it may lead to the problem of aliasing, and we can use the narrowband sample rate # rather than downsampling followed by upsampling. # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack. # resample the audio files to 8kHz from 16kHz sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation") audio_resample_1 = sample(audio_data) # resample the audio back to 16kHz sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation") # Give audio_resample_2 as input to the asr model audio_resample_2 = sample(audio_resample_1)
a93635977bbdbe8d0ebfbc054b068c7e5fae7e9c
runners/serializers.py
runners/serializers.py
from rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'path') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions')
from rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'url') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions')
Fix url field for runner version serializer
Fix url field for runner version serializer
Python
agpl-3.0
lutris/website,lutris/website,Turupawn/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,Turupawn/website
from rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'path') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions') Fix url field for runner version serializer
from rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'url') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions')
<commit_before>from rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'path') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions') <commit_msg>Fix url field for runner version serializer<commit_after>
from rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'url') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions')
from rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'path') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions') Fix url field for runner version serializerfrom rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'url') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions')
<commit_before>from rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'path') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions') <commit_msg>Fix url field for runner version serializer<commit_after>from rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'url') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions')
1f3dc9aee3a73582c75ac14ef079f2cf970537e6
service_config.py
service_config.py
# This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encrypt session keys SECRET_KEY = os.urandom(24) # The URI of the database #SQLALCHEMY_DATABASE_URI = "mysql://pegasus:secret@127.0.0.1:3306/pegasus_service" SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/.pegasus/workflow.db' % os.getenv('HOME')
# This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encrypt session keys SECRET_KEY = os.urandom(24) # The URI of the database #SQLALCHEMY_DATABASE_URI = "mysql://pegasus:secret@127.0.0.1:3306/pegasus_service" SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/.pegasus/workflow.db' % os.getenv('HOME') # Set to True to log SQL queries #SQLALCHEMY_ECHO = False # Set to change the SQLAlchemy connection pool size #SQLALCHEMY_POOL_SIZE = 5 # Set to change the connection timeout (in seconds) #SQLALCHEMY_POOL_TIMEOUT = 10 # Set to change how long connections remain before being recycled (in seconds) # Default is 2 hours for MySQL #SQLALCHEMY_POOL_RECYCLE = 2 * 60 * 60
Update configuration options for Flask-SQLAlchemy
Update configuration options for Flask-SQLAlchemy
Python
apache-2.0
pegasus-isi/pegasus-service,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus-service,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus-service,pegasus-isi/pegasus
# This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encrypt session keys SECRET_KEY = os.urandom(24) # The URI of the database #SQLALCHEMY_DATABASE_URI = "mysql://pegasus:secret@127.0.0.1:3306/pegasus_service" SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/.pegasus/workflow.db' % os.getenv('HOME') Update configuration options for Flask-SQLAlchemy
# This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encrypt session keys SECRET_KEY = os.urandom(24) # The URI of the database #SQLALCHEMY_DATABASE_URI = "mysql://pegasus:secret@127.0.0.1:3306/pegasus_service" SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/.pegasus/workflow.db' % os.getenv('HOME') # Set to True to log SQL queries #SQLALCHEMY_ECHO = False # Set to change the SQLAlchemy connection pool size #SQLALCHEMY_POOL_SIZE = 5 # Set to change the connection timeout (in seconds) #SQLALCHEMY_POOL_TIMEOUT = 10 # Set to change how long connections remain before being recycled (in seconds) # Default is 2 hours for MySQL #SQLALCHEMY_POOL_RECYCLE = 2 * 60 * 60
<commit_before># This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encrypt session keys SECRET_KEY = os.urandom(24) # The URI of the database #SQLALCHEMY_DATABASE_URI = "mysql://pegasus:secret@127.0.0.1:3306/pegasus_service" SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/.pegasus/workflow.db' % os.getenv('HOME') <commit_msg>Update configuration options for Flask-SQLAlchemy<commit_after>
# This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encrypt session keys SECRET_KEY = os.urandom(24) # The URI of the database #SQLALCHEMY_DATABASE_URI = "mysql://pegasus:secret@127.0.0.1:3306/pegasus_service" SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/.pegasus/workflow.db' % os.getenv('HOME') # Set to True to log SQL queries #SQLALCHEMY_ECHO = False # Set to change the SQLAlchemy connection pool size #SQLALCHEMY_POOL_SIZE = 5 # Set to change the connection timeout (in seconds) #SQLALCHEMY_POOL_TIMEOUT = 10 # Set to change how long connections remain before being recycled (in seconds) # Default is 2 hours for MySQL #SQLALCHEMY_POOL_RECYCLE = 2 * 60 * 60
# This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encrypt session keys SECRET_KEY = os.urandom(24) # The URI of the database #SQLALCHEMY_DATABASE_URI = "mysql://pegasus:secret@127.0.0.1:3306/pegasus_service" SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/.pegasus/workflow.db' % os.getenv('HOME') Update configuration options for Flask-SQLAlchemy# This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encrypt session keys SECRET_KEY = os.urandom(24) # The URI of the database #SQLALCHEMY_DATABASE_URI = "mysql://pegasus:secret@127.0.0.1:3306/pegasus_service" SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/.pegasus/workflow.db' % os.getenv('HOME') # Set to True to log SQL queries #SQLALCHEMY_ECHO = False # Set to change the SQLAlchemy connection pool size #SQLALCHEMY_POOL_SIZE = 5 # Set to change the connection timeout (in seconds) #SQLALCHEMY_POOL_TIMEOUT = 10 # Set to change how long connections remain before being recycled (in seconds) # Default is 2 hours for MySQL #SQLALCHEMY_POOL_RECYCLE = 2 * 60 * 60
<commit_before># This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encrypt session keys SECRET_KEY = os.urandom(24) # The URI of the database #SQLALCHEMY_DATABASE_URI = "mysql://pegasus:secret@127.0.0.1:3306/pegasus_service" SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/.pegasus/workflow.db' % os.getenv('HOME') <commit_msg>Update configuration options for Flask-SQLAlchemy<commit_after># This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encrypt session keys SECRET_KEY = os.urandom(24) # The URI of the database #SQLALCHEMY_DATABASE_URI = "mysql://pegasus:secret@127.0.0.1:3306/pegasus_service" SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/.pegasus/workflow.db' % os.getenv('HOME') # Set to True to log SQL queries #SQLALCHEMY_ECHO = False # Set to change the SQLAlchemy connection pool size #SQLALCHEMY_POOL_SIZE = 5 # Set to change the connection timeout (in seconds) #SQLALCHEMY_POOL_TIMEOUT = 10 # Set to change how long connections remain before being recycled (in seconds) # Default is 2 hours for MySQL #SQLALCHEMY_POOL_RECYCLE = 2 * 60 * 60
3929484162d4fde2b71100a1d0b6265f40499b59
plugins/anime_planet.py
plugins/anime_planet.py
from motobot import command @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For channel rules, please go to http://bit.ly/1aRaMhh"
from motobot import command from requests import get from bs4 import BeautifulSoup @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For channel rules, please go to http://bit.ly/1aRaMhh" #@command('anime') def anime_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_media(' '.join(args[1:]), 'anime') else: return "Please supply a search term." #@command('manga') def manga_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_media(' '.join(args[1:]), 'manga') else: return "Please supply a search term." #@command('user') def user_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_users(' '.join(args[1:])) else: return "Please supply a search term." def search_media(term, type): base_url = 'http://www.anime-planet.com' url = base_url + '/' + type + '/all?name=' + term.replace(' ', '%20') response = get(url) if response.url != url: return response.url else: bs = BeautifulSoup(response.text) if bs.find('div', {'class': 'error'}, recursive=True): return "No results found." else: result = bs.find('li', {'class': 'entry'}, recursive=True) return "Search result: " + base_url + result.find('a')['href'] def search_users(user): base_url = 'http://www.anime-planet.com' url = base_url + '/users/' + user.lower() response = get(url) if response.url != url: return "No users found with name '{}'.".format(user) else: return "Search result: " + response.url
Add search functions (currently disabled)
Add search functions (currently disabled)
Python
mit
Motoko11/MotoBot
from motobot import command @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For channel rules, please go to http://bit.ly/1aRaMhh" Add search functions (currently disabled)
from motobot import command from requests import get from bs4 import BeautifulSoup @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For channel rules, please go to http://bit.ly/1aRaMhh" #@command('anime') def anime_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_media(' '.join(args[1:]), 'anime') else: return "Please supply a search term." #@command('manga') def manga_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_media(' '.join(args[1:]), 'manga') else: return "Please supply a search term." #@command('user') def user_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_users(' '.join(args[1:])) else: return "Please supply a search term." def search_media(term, type): base_url = 'http://www.anime-planet.com' url = base_url + '/' + type + '/all?name=' + term.replace(' ', '%20') response = get(url) if response.url != url: return response.url else: bs = BeautifulSoup(response.text) if bs.find('div', {'class': 'error'}, recursive=True): return "No results found." else: result = bs.find('li', {'class': 'entry'}, recursive=True) return "Search result: " + base_url + result.find('a')['href'] def search_users(user): base_url = 'http://www.anime-planet.com' url = base_url + '/users/' + user.lower() response = get(url) if response.url != url: return "No users found with name '{}'.".format(user) else: return "Search result: " + response.url
<commit_before>from motobot import command @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For channel rules, please go to http://bit.ly/1aRaMhh" <commit_msg>Add search functions (currently disabled)<commit_after>
from motobot import command from requests import get from bs4 import BeautifulSoup @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For channel rules, please go to http://bit.ly/1aRaMhh" #@command('anime') def anime_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_media(' '.join(args[1:]), 'anime') else: return "Please supply a search term." #@command('manga') def manga_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_media(' '.join(args[1:]), 'manga') else: return "Please supply a search term." #@command('user') def user_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_users(' '.join(args[1:])) else: return "Please supply a search term." def search_media(term, type): base_url = 'http://www.anime-planet.com' url = base_url + '/' + type + '/all?name=' + term.replace(' ', '%20') response = get(url) if response.url != url: return response.url else: bs = BeautifulSoup(response.text) if bs.find('div', {'class': 'error'}, recursive=True): return "No results found." else: result = bs.find('li', {'class': 'entry'}, recursive=True) return "Search result: " + base_url + result.find('a')['href'] def search_users(user): base_url = 'http://www.anime-planet.com' url = base_url + '/users/' + user.lower() response = get(url) if response.url != url: return "No users found with name '{}'.".format(user) else: return "Search result: " + response.url
from motobot import command @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For channel rules, please go to http://bit.ly/1aRaMhh" Add search functions (currently disabled)from motobot import command from requests import get from bs4 import BeautifulSoup @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For channel rules, please go to http://bit.ly/1aRaMhh" #@command('anime') def anime_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_media(' '.join(args[1:]), 'anime') else: return "Please supply a search term." #@command('manga') def manga_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_media(' '.join(args[1:]), 'manga') else: return "Please supply a search term." #@command('user') def user_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_users(' '.join(args[1:])) else: return "Please supply a search term." def search_media(term, type): base_url = 'http://www.anime-planet.com' url = base_url + '/' + type + '/all?name=' + term.replace(' ', '%20') response = get(url) if response.url != url: return response.url else: bs = BeautifulSoup(response.text) if bs.find('div', {'class': 'error'}, recursive=True): return "No results found." else: result = bs.find('li', {'class': 'entry'}, recursive=True) return "Search result: " + base_url + result.find('a')['href'] def search_users(user): base_url = 'http://www.anime-planet.com' url = base_url + '/users/' + user.lower() response = get(url) if response.url != url: return "No users found with name '{}'.".format(user) else: return "Search result: " + response.url
<commit_before>from motobot import command @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For channel rules, please go to http://bit.ly/1aRaMhh" <commit_msg>Add search functions (currently disabled)<commit_after>from motobot import command from requests import get from bs4 import BeautifulSoup @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For channel rules, please go to http://bit.ly/1aRaMhh" #@command('anime') def anime_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_media(' '.join(args[1:]), 'anime') else: return "Please supply a search term." #@command('manga') def manga_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_media(' '.join(args[1:]), 'manga') else: return "Please supply a search term." #@command('user') def user_search_command(message, database): args = message.message.split(' ') if len(args) > 1: return search_users(' '.join(args[1:])) else: return "Please supply a search term." def search_media(term, type): base_url = 'http://www.anime-planet.com' url = base_url + '/' + type + '/all?name=' + term.replace(' ', '%20') response = get(url) if response.url != url: return response.url else: bs = BeautifulSoup(response.text) if bs.find('div', {'class': 'error'}, recursive=True): return "No results found." else: result = bs.find('li', {'class': 'entry'}, recursive=True) return "Search result: " + base_url + result.find('a')['href'] def search_users(user): base_url = 'http://www.anime-planet.com' url = base_url + '/users/' + user.lower() response = get(url) if response.url != url: return "No users found with name '{}'.".format(user) else: return "Search result: " + response.url
6ab6d1ddfd0a8a94956223014af634e4768f57bd
vdirsyncer/utils/compat.py
vdirsyncer/utils/compat.py
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if PY2: # pragma: no cover import urlparse from urllib import \ quote as urlquote, \ unquote as urlunquote text_type = unicode # flake8: noqa iteritems = lambda x: x.iteritems() itervalues = lambda x: x.itervalues() else: # pragma: no cover import urllib.parse as urlparse urlquote = urlparse.quote urlunquote = urlparse.unquote text_type = str iteritems = lambda x: x.items() itervalues = lambda x: x.values() def with_metaclass(meta, *bases): '''Original code from six, by Benjamin Peterson.''' class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if sys.version_info < (3, 3) and sys.version_info[:2] != (2, 7): raise RuntimeError( 'vdirsyncer only works on Python versions 2.7.x and 3.3+' ) if PY2: # pragma: no cover import urlparse from urllib import \ quote as urlquote, \ unquote as urlunquote text_type = unicode # flake8: noqa iteritems = lambda x: x.iteritems() itervalues = lambda x: x.itervalues() else: # pragma: no cover import urllib.parse as urlparse urlquote = urlparse.quote urlunquote = urlparse.unquote text_type = str iteritems = lambda x: x.items() itervalues = lambda x: x.values() def with_metaclass(meta, *bases): '''Original code from six, by Benjamin Peterson.''' class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
Check Python version at runtime
Check Python version at runtime
Python
mit
hobarrera/vdirsyncer,tribut/vdirsyncer,credativUK/vdirsyncer,untitaker/vdirsyncer,hobarrera/vdirsyncer,tribut/vdirsyncer,untitaker/vdirsyncer,credativUK/vdirsyncer,untitaker/vdirsyncer
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if PY2: # pragma: no cover import urlparse from urllib import \ quote as urlquote, \ unquote as urlunquote text_type = unicode # flake8: noqa iteritems = lambda x: x.iteritems() itervalues = lambda x: x.itervalues() else: # pragma: no cover import urllib.parse as urlparse urlquote = urlparse.quote urlunquote = urlparse.unquote text_type = str iteritems = lambda x: x.items() itervalues = lambda x: x.values() def with_metaclass(meta, *bases): '''Original code from six, by Benjamin Peterson.''' class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) Check Python version at runtime
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if sys.version_info < (3, 3) and sys.version_info[:2] != (2, 7): raise RuntimeError( 'vdirsyncer only works on Python versions 2.7.x and 3.3+' ) if PY2: # pragma: no cover import urlparse from urllib import \ quote as urlquote, \ unquote as urlunquote text_type = unicode # flake8: noqa iteritems = lambda x: x.iteritems() itervalues = lambda x: x.itervalues() else: # pragma: no cover import urllib.parse as urlparse urlquote = urlparse.quote urlunquote = urlparse.unquote text_type = str iteritems = lambda x: x.items() itervalues = lambda x: x.values() def with_metaclass(meta, *bases): '''Original code from six, by Benjamin Peterson.''' class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
<commit_before># -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if PY2: # pragma: no cover import urlparse from urllib import \ quote as urlquote, \ unquote as urlunquote text_type = unicode # flake8: noqa iteritems = lambda x: x.iteritems() itervalues = lambda x: x.itervalues() else: # pragma: no cover import urllib.parse as urlparse urlquote = urlparse.quote urlunquote = urlparse.unquote text_type = str iteritems = lambda x: x.items() itervalues = lambda x: x.values() def with_metaclass(meta, *bases): '''Original code from six, by Benjamin Peterson.''' class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) <commit_msg>Check Python version at runtime<commit_after>
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if sys.version_info < (3, 3) and sys.version_info[:2] != (2, 7): raise RuntimeError( 'vdirsyncer only works on Python versions 2.7.x and 3.3+' ) if PY2: # pragma: no cover import urlparse from urllib import \ quote as urlquote, \ unquote as urlunquote text_type = unicode # flake8: noqa iteritems = lambda x: x.iteritems() itervalues = lambda x: x.itervalues() else: # pragma: no cover import urllib.parse as urlparse urlquote = urlparse.quote urlunquote = urlparse.unquote text_type = str iteritems = lambda x: x.items() itervalues = lambda x: x.values() def with_metaclass(meta, *bases): '''Original code from six, by Benjamin Peterson.''' class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if PY2: # pragma: no cover import urlparse from urllib import \ quote as urlquote, \ unquote as urlunquote text_type = unicode # flake8: noqa iteritems = lambda x: x.iteritems() itervalues = lambda x: x.itervalues() else: # pragma: no cover import urllib.parse as urlparse urlquote = urlparse.quote urlunquote = urlparse.unquote text_type = str iteritems = lambda x: x.items() itervalues = lambda x: x.values() def with_metaclass(meta, *bases): '''Original code from six, by Benjamin Peterson.''' class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) Check Python version at runtime# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if sys.version_info < (3, 3) and sys.version_info[:2] != (2, 7): raise RuntimeError( 'vdirsyncer only works on Python versions 2.7.x and 3.3+' ) if PY2: # pragma: no cover import urlparse from urllib import \ quote as urlquote, \ unquote as urlunquote text_type = unicode # flake8: noqa iteritems = lambda x: x.iteritems() itervalues = lambda x: x.itervalues() else: # pragma: no cover import urllib.parse as urlparse urlquote = urlparse.quote urlunquote = urlparse.unquote text_type = str iteritems = lambda x: x.items() itervalues = lambda x: x.values() def with_metaclass(meta, *bases): '''Original code from six, by Benjamin Peterson.''' class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
<commit_before># -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if PY2: # pragma: no cover import urlparse from urllib import \ quote as urlquote, \ unquote as urlunquote text_type = unicode # flake8: noqa iteritems = lambda x: x.iteritems() itervalues = lambda x: x.itervalues() else: # pragma: no cover import urllib.parse as urlparse urlquote = urlparse.quote urlunquote = urlparse.unquote text_type = str iteritems = lambda x: x.items() itervalues = lambda x: x.values() def with_metaclass(meta, *bases): '''Original code from six, by Benjamin Peterson.''' class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) <commit_msg>Check Python version at runtime<commit_after># -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if sys.version_info < (3, 3) and sys.version_info[:2] != (2, 7): raise RuntimeError( 'vdirsyncer only works on Python versions 2.7.x and 3.3+' ) if PY2: # pragma: no cover import urlparse from urllib import \ quote as urlquote, \ unquote as urlunquote text_type = unicode # flake8: noqa iteritems = lambda x: x.iteritems() itervalues = lambda x: x.itervalues() else: # pragma: no cover import urllib.parse as urlparse urlquote = urlparse.quote urlunquote = urlparse.unquote text_type = str iteritems = lambda x: x.items() itervalues = lambda x: x.values() def with_metaclass(meta, *bases): '''Original code from six, by Benjamin Peterson.''' class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
ecbbc523ab3349a3f05403c06106b41562f9ca03
fireplace/cards/game/all.py
fireplace/cards/game/all.py
# The Coin class GAME_005: def play(self): self.controller.temp_mana += 1
""" GAME set and other special cards """ from ..utils import * # The Coin class GAME_005: play = ManaThisTurn(CONTROLLER, 1)
Use ManaThisTurn action for The Coin
Use ManaThisTurn action for The Coin
Python
agpl-3.0
butozerca/fireplace,smallnamespace/fireplace,Meerkov/fireplace,amw2104/fireplace,Ragowit/fireplace,amw2104/fireplace,NightKev/fireplace,liujimj/fireplace,butozerca/fireplace,Meerkov/fireplace,smallnamespace/fireplace,jleclanche/fireplace,oftc-ftw/fireplace,beheh/fireplace,Ragowit/fireplace,liujimj/fireplace,oftc-ftw/fireplace
# The Coin class GAME_005: def play(self): self.controller.temp_mana += 1 Use ManaThisTurn action for The Coin
""" GAME set and other special cards """ from ..utils import * # The Coin class GAME_005: play = ManaThisTurn(CONTROLLER, 1)
<commit_before># The Coin class GAME_005: def play(self): self.controller.temp_mana += 1 <commit_msg>Use ManaThisTurn action for The Coin<commit_after>
""" GAME set and other special cards """ from ..utils import * # The Coin class GAME_005: play = ManaThisTurn(CONTROLLER, 1)
# The Coin class GAME_005: def play(self): self.controller.temp_mana += 1 Use ManaThisTurn action for The Coin""" GAME set and other special cards """ from ..utils import * # The Coin class GAME_005: play = ManaThisTurn(CONTROLLER, 1)
<commit_before># The Coin class GAME_005: def play(self): self.controller.temp_mana += 1 <commit_msg>Use ManaThisTurn action for The Coin<commit_after>""" GAME set and other special cards """ from ..utils import * # The Coin class GAME_005: play = ManaThisTurn(CONTROLLER, 1)
b40bec85439f8b45f338b848b118ee11aec52377
examples/flask_alchemy/demoapp.py
examples/flask_alchemy/demoapp.py
# -*- coding: utf-8 -*- # Copyright: See the LICENSE file. from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username class UserLog(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('logs', lazy='dynamic')) def __init__(self, message, user): self.message = message self.user = user def __repr__(self): return '<Log for %r: %s>' % (self.user, self.message)
# -*- coding: utf-8 -*- # Copyright: See the LICENSE file. from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username class UserLog(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('logs', lazy='dynamic')) def __init__(self, message, user): self.message = message self.user = user def __repr__(self): return '<Log for %r: %s>' % (self.user, self.message)
Adjust to Flask>=1.0 extension nanespace
examples: Adjust to Flask>=1.0 extension nanespace Previous versions of Flask installed extensions under `flask.ext`; that is no longer the case.
Python
mit
FactoryBoy/factory_boy,rbarrois/factory_boy
# -*- coding: utf-8 -*- # Copyright: See the LICENSE file. from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username class UserLog(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('logs', lazy='dynamic')) def __init__(self, message, user): self.message = message self.user = user def __repr__(self): return '<Log for %r: %s>' % (self.user, self.message) examples: Adjust to Flask>=1.0 extension nanespace Previous versions of Flask installed extensions under `flask.ext`; that is no longer the case.
# -*- coding: utf-8 -*- # Copyright: See the LICENSE file. from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username class UserLog(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('logs', lazy='dynamic')) def __init__(self, message, user): self.message = message self.user = user def __repr__(self): return '<Log for %r: %s>' % (self.user, self.message)
<commit_before># -*- coding: utf-8 -*- # Copyright: See the LICENSE file. from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username class UserLog(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('logs', lazy='dynamic')) def __init__(self, message, user): self.message = message self.user = user def __repr__(self): return '<Log for %r: %s>' % (self.user, self.message) <commit_msg>examples: Adjust to Flask>=1.0 extension nanespace Previous versions of Flask installed extensions under `flask.ext`; that is no longer the case.<commit_after>
# -*- coding: utf-8 -*- # Copyright: See the LICENSE file. from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username class UserLog(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('logs', lazy='dynamic')) def __init__(self, message, user): self.message = message self.user = user def __repr__(self): return '<Log for %r: %s>' % (self.user, self.message)
# -*- coding: utf-8 -*- # Copyright: See the LICENSE file. from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username class UserLog(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('logs', lazy='dynamic')) def __init__(self, message, user): self.message = message self.user = user def __repr__(self): return '<Log for %r: %s>' % (self.user, self.message) examples: Adjust to Flask>=1.0 extension nanespace Previous versions of Flask installed extensions under `flask.ext`; that is no longer the case.# -*- coding: utf-8 -*- # Copyright: See the LICENSE file. from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username class UserLog(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('logs', lazy='dynamic')) def __init__(self, message, user): self.message = message self.user = user def __repr__(self): return '<Log for %r: %s>' % (self.user, self.message)
<commit_before># -*- coding: utf-8 -*- # Copyright: See the LICENSE file. from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username class UserLog(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('logs', lazy='dynamic')) def __init__(self, message, user): self.message = message self.user = user def __repr__(self): return '<Log for %r: %s>' % (self.user, self.message) <commit_msg>examples: Adjust to Flask>=1.0 extension nanespace Previous versions of Flask installed extensions under `flask.ext`; that is no longer the case.<commit_after># -*- coding: utf-8 -*- # Copyright: See the LICENSE file. from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username class UserLog(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('logs', lazy='dynamic')) def __init__(self, message, user): self.message = message self.user = user def __repr__(self): return '<Log for %r: %s>' % (self.user, self.message)
c22554f7979d07be881db5cb27c249581f99ce5a
nflpool/data/secret-config.py
nflpool/data/secret-config.py
from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = ''
from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = '' msf_api = 'YOUR API KEY' msf_v2pw = 'MYSPORTSFEEDS'
Add the MSF API key and password fields
Add the MSF API key and password fields
Python
mit
prcutler/nflpool,prcutler/nflpool
from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = '' Add the MSF API key and password fields
from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = '' msf_api = 'YOUR API KEY' msf_v2pw = 'MYSPORTSFEEDS'
<commit_before>from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = '' <commit_msg>Add the MSF API key and password fields<commit_after>
from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = '' msf_api = 'YOUR API KEY' msf_v2pw = 'MYSPORTSFEEDS'
from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = '' Add the MSF API key and password fieldsfrom nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = '' msf_api = 'YOUR API KEY' msf_v2pw = 'MYSPORTSFEEDS'
<commit_before>from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = '' <commit_msg>Add the MSF API key and password fields<commit_after>from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = '' msf_api = 'YOUR API KEY' msf_v2pw = 'MYSPORTSFEEDS'
7e2c31d748b458b96b0d31c40868e538727862eb
Lib/hotshot/stones.py
Lib/hotshot/stones.py
import errno import hotshot import hotshot.stats import os import sys import test.pystone if sys.argv[1:]: logfile = sys.argv[1] else: import tempfile logf = tempfile.NamedTemporaryFile() logfile = logf.name p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise
import errno import hotshot import hotshot.stats import os import sys import test.pystone def main(logfile): p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise if __name__ == '__main__': if sys.argv[1:]: main(sys.argv[1]) else: import tempfile main(tempfile.NamedTemporaryFile().name)
Move testing code into "if __name__ == '__main__'" so it's not run on import.
Move testing code into "if __name__ == '__main__'" so it's not run on import.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
import errno import hotshot import hotshot.stats import os import sys import test.pystone if sys.argv[1:]: logfile = sys.argv[1] else: import tempfile logf = tempfile.NamedTemporaryFile() logfile = logf.name p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise Move testing code into "if __name__ == '__main__'" so it's not run on import.
import errno import hotshot import hotshot.stats import os import sys import test.pystone def main(logfile): p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise if __name__ == '__main__': if sys.argv[1:]: main(sys.argv[1]) else: import tempfile main(tempfile.NamedTemporaryFile().name)
<commit_before>import errno import hotshot import hotshot.stats import os import sys import test.pystone if sys.argv[1:]: logfile = sys.argv[1] else: import tempfile logf = tempfile.NamedTemporaryFile() logfile = logf.name p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise <commit_msg>Move testing code into "if __name__ == '__main__'" so it's not run on import.<commit_after>
import errno import hotshot import hotshot.stats import os import sys import test.pystone def main(logfile): p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise if __name__ == '__main__': if sys.argv[1:]: main(sys.argv[1]) else: import tempfile main(tempfile.NamedTemporaryFile().name)
import errno import hotshot import hotshot.stats import os import sys import test.pystone if sys.argv[1:]: logfile = sys.argv[1] else: import tempfile logf = tempfile.NamedTemporaryFile() logfile = logf.name p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise Move testing code into "if __name__ == '__main__'" so it's not run on import.import errno import hotshot import hotshot.stats import os import sys import test.pystone def main(logfile): p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise if __name__ == '__main__': if sys.argv[1:]: main(sys.argv[1]) else: import tempfile main(tempfile.NamedTemporaryFile().name)
<commit_before>import errno import hotshot import hotshot.stats import os import sys import test.pystone if sys.argv[1:]: logfile = sys.argv[1] else: import tempfile logf = tempfile.NamedTemporaryFile() logfile = logf.name p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise <commit_msg>Move testing code into "if __name__ == '__main__'" so it's not run on import.<commit_after>import errno import hotshot import hotshot.stats import os import sys import test.pystone def main(logfile): p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('time', 'calls') try: stats.print_stats(20) except IOError, e: if e.errno != errno.EPIPE: raise if __name__ == '__main__': if sys.argv[1:]: main(sys.argv[1]) else: import tempfile main(tempfile.NamedTemporaryFile().name)
dc56d2634f05ec57ba594c5c70193d2b113c53e5
Mathematics/Fundamentals/jim-and-the-jokes.py
Mathematics/Fundamentals/jim-and-the-jokes.py
# Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m return result n = int(raw_input()) decimals = [0]*37 # 37 = 12*3 + 1 = max(base(i,j)) for 1<=i<=12 (months) and 1<=j<=31 (days) for i in range(n): m,d = [int(j) for j in raw_input().split()] x = base(m,d) result = 0 if(x != -1): result += decimals[x] decimals[x] += 1 print result
# Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m return result n = int(raw_input()) decimals = [0]*38 # 37 = 12*3 + 1 = max(base(i,j)) for 1<=i<=12 (months) and 1<=j<=31 (days) for i in range(n): m,d = [int(j) for j in raw_input().split()] x = base(m,d) #print 'x = ' + str(x) if(x != -1): decimals[x] += 1 answer = 0 for j in decimals: # Note that the following if-else is necessary in order # to deal with large integers if j%2 == 0: answer += (j/2)*(j-1) else: answer += ((j-1)/2)*j print answer
Fix code to deal with large numbers
Fix code to deal with large numbers
Python
mit
ugaliguy/HackerRank,ugaliguy/HackerRank,ugaliguy/HackerRank
# Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m return result n = int(raw_input()) decimals = [0]*37 # 37 = 12*3 + 1 = max(base(i,j)) for 1<=i<=12 (months) and 1<=j<=31 (days) for i in range(n): m,d = [int(j) for j in raw_input().split()] x = base(m,d) result = 0 if(x != -1): result += decimals[x] decimals[x] += 1 print resultFix code to deal with large numbers
# Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m return result n = int(raw_input()) decimals = [0]*38 # 37 = 12*3 + 1 = max(base(i,j)) for 1<=i<=12 (months) and 1<=j<=31 (days) for i in range(n): m,d = [int(j) for j in raw_input().split()] x = base(m,d) #print 'x = ' + str(x) if(x != -1): decimals[x] += 1 answer = 0 for j in decimals: # Note that the following if-else is necessary in order # to deal with large integers if j%2 == 0: answer += (j/2)*(j-1) else: answer += ((j-1)/2)*j print answer
<commit_before># Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m return result n = int(raw_input()) decimals = [0]*37 # 37 = 12*3 + 1 = max(base(i,j)) for 1<=i<=12 (months) and 1<=j<=31 (days) for i in range(n): m,d = [int(j) for j in raw_input().split()] x = base(m,d) result = 0 if(x != -1): result += decimals[x] decimals[x] += 1 print result<commit_msg>Fix code to deal with large numbers<commit_after>
# Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m return result n = int(raw_input()) decimals = [0]*38 # 37 = 12*3 + 1 = max(base(i,j)) for 1<=i<=12 (months) and 1<=j<=31 (days) for i in range(n): m,d = [int(j) for j in raw_input().split()] x = base(m,d) #print 'x = ' + str(x) if(x != -1): decimals[x] += 1 answer = 0 for j in decimals: # Note that the following if-else is necessary in order # to deal with large integers if j%2 == 0: answer += (j/2)*(j-1) else: answer += ((j-1)/2)*j print answer
# Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m return result n = int(raw_input()) decimals = [0]*37 # 37 = 12*3 + 1 = max(base(i,j)) for 1<=i<=12 (months) and 1<=j<=31 (days) for i in range(n): m,d = [int(j) for j in raw_input().split()] x = base(m,d) result = 0 if(x != -1): result += decimals[x] decimals[x] += 1 print resultFix code to deal with large numbers# Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m return result n = int(raw_input()) decimals = [0]*38 # 37 = 12*3 + 1 = max(base(i,j)) for 1<=i<=12 (months) and 1<=j<=31 (days) for i in range(n): m,d = [int(j) for j in raw_input().split()] x = base(m,d) #print 'x = ' + str(x) if(x != -1): decimals[x] += 1 answer = 0 for j in decimals: # Note that the following if-else is necessary in order # to deal with large integers if j%2 == 0: answer += (j/2)*(j-1) else: answer += ((j-1)/2)*j print answer
<commit_before># Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m return result n = int(raw_input()) decimals = [0]*37 # 37 = 12*3 + 1 = max(base(i,j)) for 1<=i<=12 (months) and 1<=j<=31 (days) for i in range(n): m,d = [int(j) for j in raw_input().split()] x = base(m,d) result = 0 if(x != -1): result += decimals[x] decimals[x] += 1 print result<commit_msg>Fix code to deal with large numbers<commit_after># Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m return result n = int(raw_input()) decimals = [0]*38 # 37 = 12*3 + 1 = max(base(i,j)) for 1<=i<=12 (months) and 1<=j<=31 (days) for i in range(n): m,d = [int(j) for j in raw_input().split()] x = base(m,d) #print 'x = ' + str(x) if(x != -1): decimals[x] += 1 answer = 0 for j in decimals: # Note that the following if-else is necessary in order # to deal with large integers if j%2 == 0: answer += (j/2)*(j-1) else: answer += ((j-1)/2)*j print answer
c4e0bc68db9e0e897c51181e5dd23370a7a08734
pypocketexplore/jobs.py
pypocketexplore/jobs.py
from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() data = req.get('http://localhost:5000/api/topic/{}'.format(topic)).json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res else: raise Exception if __name__ == '__main__': extract_topic_items('finance')
from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() resp = req.get('http://localhost:5000/api/topic/{}'.format(topic))\ data = resp.json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res elif resp.ok and not items: return else: raise Exception if __name__ == '__main__': extract_topic_items('finance')
Handle topics with zero elements
Handle topics with zero elements
Python
mit
Florents-Tselai/PyPocketExplore
from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() data = req.get('http://localhost:5000/api/topic/{}'.format(topic)).json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res else: raise Exception if __name__ == '__main__': extract_topic_items('finance') Handle topics with zero elements
from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() resp = req.get('http://localhost:5000/api/topic/{}'.format(topic))\ data = resp.json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res elif resp.ok and not items: return else: raise Exception if __name__ == '__main__': extract_topic_items('finance')
<commit_before>from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() data = req.get('http://localhost:5000/api/topic/{}'.format(topic)).json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res else: raise Exception if __name__ == '__main__': extract_topic_items('finance') <commit_msg>Handle topics with zero elements<commit_after>
from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() resp = req.get('http://localhost:5000/api/topic/{}'.format(topic))\ data = resp.json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res elif resp.ok and not items: return else: raise Exception if __name__ == '__main__': extract_topic_items('finance')
from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() data = req.get('http://localhost:5000/api/topic/{}'.format(topic)).json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res else: raise Exception if __name__ == '__main__': extract_topic_items('finance') Handle topics with zero elementsfrom datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() resp = req.get('http://localhost:5000/api/topic/{}'.format(topic))\ data = resp.json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res elif resp.ok and not items: return else: raise Exception if __name__ == '__main__': extract_topic_items('finance')
<commit_before>from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() data = req.get('http://localhost:5000/api/topic/{}'.format(topic)).json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res else: raise Exception if __name__ == '__main__': extract_topic_items('finance') <commit_msg>Handle topics with zero elements<commit_after>from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() resp = req.get('http://localhost:5000/api/topic/{}'.format(topic))\ data = resp.json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res elif resp.ok and not items: return else: raise Exception if __name__ == '__main__': extract_topic_items('finance')
771c3bead487aa989dd19558bc2a4107abc29b6b
webapp/apps/staff/views.py
webapp/apps/staff/views.py
from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): # messages = "User with that email already exists" pass else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = "User created" else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'users/new.html', { 'form': form, # 'messages': messages })
from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): messages.add_message(request, messages.ERROR, 'Username with\ that email already exists') else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = "User created" messages.add_message(request, messages.SUCCESS, 'User create!.') else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'staff/users/new.jinja', { 'form': form, })
Add more msgs for staff/user/new view
Add more msgs for staff/user/new view
Python
apache-2.0
patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass,patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass,patrickspencer/compass,patrickspencer/compass,patrickspencer/compass
from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): # messages = "User with that email already exists" pass else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = "User created" else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'users/new.html', { 'form': form, # 'messages': messages }) Add more msgs for staff/user/new view
from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): messages.add_message(request, messages.ERROR, 'Username with\ that email already exists') else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = "User created" messages.add_message(request, messages.SUCCESS, 'User create!.') else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'staff/users/new.jinja', { 'form': form, })
<commit_before>from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): # messages = "User with that email already exists" pass else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = "User created" else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'users/new.html', { 'form': form, # 'messages': messages }) <commit_msg>Add more msgs for staff/user/new view<commit_after>
from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): messages.add_message(request, messages.ERROR, 'Username with\ that email already exists') else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = "User created" messages.add_message(request, messages.SUCCESS, 'User create!.') else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'staff/users/new.jinja', { 'form': form, })
from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): # messages = "User with that email already exists" pass else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = "User created" else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'users/new.html', { 'form': form, # 'messages': messages }) Add more msgs for staff/user/new viewfrom django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): messages.add_message(request, messages.ERROR, 'Username with\ that email already exists') else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = "User created" messages.add_message(request, messages.SUCCESS, 'User create!.') else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'staff/users/new.jinja', { 'form': form, })
<commit_before>from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): # messages = "User with that email already exists" pass else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = "User created" else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'users/new.html', { 'form': form, # 'messages': messages }) <commit_msg>Add more msgs for staff/user/new view<commit_after>from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if User.objects.filter(email=email).exists(): messages.add_message(request, messages.ERROR, 'Username with\ that email already exists') else: User.objects.create_user( username = form.cleaned_data['username'], email = email, password = form.cleaned_data['password'], last_name = form.cleaned_data['last_name'], first_name = form.cleaned_data['first_name'] ) # messages = "User created" messages.add_message(request, messages.SUCCESS, 'User create!.') else: form = NewUserForm() messages.add_message(request, messages.INFO, 'This is a message!.') return render(request, 'staff/users/new.jinja', { 'form': form, })
3544f211913ba67f0bd7e433c23d2e5b22bba719
lightcurve_pipeline/database/reset_database.py
lightcurve_pipeline/database/reset_database.py
#! /usr/bin/env python """ Reset all tables in the database. """ from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTINGS['db_connection_string']) prompt += 'Do you wish to proceed? (y/n)' response = raw_input(prompt) if response.lower() == 'y': print 'Resetting database' base.metadata.drop_all() base.metadata.create_all()
#! /usr/bin/env python """ Reset all tables in the database. """ from __future__ import print_function from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTINGS['db_connection_string']) prompt += 'Do you wish to proceed? (y/n)' response = raw_input(prompt) if response.lower() == 'y': print('Resetting database') base.metadata.drop_all() base.metadata.create_all()
Change the print statement to use __future__.
Change the print statement to use __future__.
Python
bsd-3-clause
justincely/lightcurve_pipeline
#! /usr/bin/env python """ Reset all tables in the database. """ from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTINGS['db_connection_string']) prompt += 'Do you wish to proceed? (y/n)' response = raw_input(prompt) if response.lower() == 'y': print 'Resetting database' base.metadata.drop_all() base.metadata.create_all() Change the print statement to use __future__.
#! /usr/bin/env python """ Reset all tables in the database. """ from __future__ import print_function from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTINGS['db_connection_string']) prompt += 'Do you wish to proceed? (y/n)' response = raw_input(prompt) if response.lower() == 'y': print('Resetting database') base.metadata.drop_all() base.metadata.create_all()
<commit_before>#! /usr/bin/env python """ Reset all tables in the database. """ from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTINGS['db_connection_string']) prompt += 'Do you wish to proceed? (y/n)' response = raw_input(prompt) if response.lower() == 'y': print 'Resetting database' base.metadata.drop_all() base.metadata.create_all() <commit_msg>Change the print statement to use __future__.<commit_after>
#! /usr/bin/env python """ Reset all tables in the database. """ from __future__ import print_function from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTINGS['db_connection_string']) prompt += 'Do you wish to proceed? (y/n)' response = raw_input(prompt) if response.lower() == 'y': print('Resetting database') base.metadata.drop_all() base.metadata.create_all()
#! /usr/bin/env python """ Reset all tables in the database. """ from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTINGS['db_connection_string']) prompt += 'Do you wish to proceed? (y/n)' response = raw_input(prompt) if response.lower() == 'y': print 'Resetting database' base.metadata.drop_all() base.metadata.create_all() Change the print statement to use __future__.#! /usr/bin/env python """ Reset all tables in the database. """ from __future__ import print_function from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTINGS['db_connection_string']) prompt += 'Do you wish to proceed? (y/n)' response = raw_input(prompt) if response.lower() == 'y': print('Resetting database') base.metadata.drop_all() base.metadata.create_all()
<commit_before>#! /usr/bin/env python """ Reset all tables in the database. """ from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTINGS['db_connection_string']) prompt += 'Do you wish to proceed? (y/n)' response = raw_input(prompt) if response.lower() == 'y': print 'Resetting database' base.metadata.drop_all() base.metadata.create_all() <commit_msg>Change the print statement to use __future__.<commit_after>#! /usr/bin/env python """ Reset all tables in the database. """ from __future__ import print_function from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTINGS['db_connection_string']) prompt += 'Do you wish to proceed? (y/n)' response = raw_input(prompt) if response.lower() == 'y': print('Resetting database') base.metadata.drop_all() base.metadata.create_all()
62ebb94f09ea2dee3276041bd471502d57078650
mcrouter/test/test_mcrouter_to_mcrouter_tko.py
mcrouter/test/test_mcrouter_to_mcrouter_tko.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors'] def setUp(self): self.underlying_mcr = self.add_mcrouter(self.config, extra_args=self.extra_args, bg_mcrouter=True) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) stats = self.underlying_mcr.stats("suspect_servers") print(stats) self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0])) stats = mcr.stats("suspect_servers") self.assertEqual(0, len(stats))
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re import time from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors'] def setUp(self): self.underlying_mcr = self.add_mcrouter(self.config, extra_args=self.extra_args, bg_mcrouter=True) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) retries = 10 while self.underlying_mcr.stats()['cmd_delete_count'] != 1 and retries > 0: retries = retries - 1 time.sleep(1) stats = self.underlying_mcr.stats("suspect_servers") print(stats) self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0])) stats = mcr.stats("suspect_servers") self.assertEqual(0, len(stats))
Fix flaky mcrouter tko tests
Fix flaky mcrouter tko tests Summary: As above Reviewed By: edenzik Differential Revision: D25722019 fbshipit-source-id: 06ff9200e99f3580db25fef9ca5ab167c50b97ed
Python
mit
facebook/mcrouter,facebook/mcrouter,facebook/mcrouter,facebook/mcrouter
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors'] def setUp(self): self.underlying_mcr = self.add_mcrouter(self.config, extra_args=self.extra_args, bg_mcrouter=True) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) stats = self.underlying_mcr.stats("suspect_servers") print(stats) self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0])) stats = mcr.stats("suspect_servers") self.assertEqual(0, len(stats)) Fix flaky mcrouter tko tests Summary: As above Reviewed By: edenzik Differential Revision: D25722019 fbshipit-source-id: 06ff9200e99f3580db25fef9ca5ab167c50b97ed
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re import time from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors'] def setUp(self): self.underlying_mcr = self.add_mcrouter(self.config, extra_args=self.extra_args, bg_mcrouter=True) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) retries = 10 while self.underlying_mcr.stats()['cmd_delete_count'] != 1 and retries > 0: retries = retries - 1 time.sleep(1) stats = self.underlying_mcr.stats("suspect_servers") print(stats) self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0])) stats = mcr.stats("suspect_servers") self.assertEqual(0, len(stats))
<commit_before>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors'] def setUp(self): self.underlying_mcr = self.add_mcrouter(self.config, extra_args=self.extra_args, bg_mcrouter=True) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) stats = self.underlying_mcr.stats("suspect_servers") print(stats) self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0])) stats = mcr.stats("suspect_servers") self.assertEqual(0, len(stats)) <commit_msg>Fix flaky mcrouter tko tests Summary: As above Reviewed By: edenzik Differential Revision: D25722019 fbshipit-source-id: 06ff9200e99f3580db25fef9ca5ab167c50b97ed<commit_after>
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re import time from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors'] def setUp(self): self.underlying_mcr = self.add_mcrouter(self.config, extra_args=self.extra_args, bg_mcrouter=True) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) retries = 10 while self.underlying_mcr.stats()['cmd_delete_count'] != 1 and retries > 0: retries = retries - 1 time.sleep(1) stats = self.underlying_mcr.stats("suspect_servers") print(stats) self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0])) stats = mcr.stats("suspect_servers") self.assertEqual(0, len(stats))
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors'] def setUp(self): self.underlying_mcr = self.add_mcrouter(self.config, extra_args=self.extra_args, bg_mcrouter=True) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) stats = self.underlying_mcr.stats("suspect_servers") print(stats) self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0])) stats = mcr.stats("suspect_servers") self.assertEqual(0, len(stats)) Fix flaky mcrouter tko tests Summary: As above Reviewed By: edenzik Differential Revision: D25722019 fbshipit-source-id: 06ff9200e99f3580db25fef9ca5ab167c50b97ed#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re import time from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors'] def setUp(self): self.underlying_mcr = self.add_mcrouter(self.config, extra_args=self.extra_args, bg_mcrouter=True) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) retries = 10 while self.underlying_mcr.stats()['cmd_delete_count'] != 1 and retries > 0: retries = retries - 1 time.sleep(1) stats = self.underlying_mcr.stats("suspect_servers") print(stats) self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0])) stats = mcr.stats("suspect_servers") self.assertEqual(0, len(stats))
<commit_before>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors'] def setUp(self): self.underlying_mcr = self.add_mcrouter(self.config, extra_args=self.extra_args, bg_mcrouter=True) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) stats = self.underlying_mcr.stats("suspect_servers") print(stats) self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0])) stats = mcr.stats("suspect_servers") self.assertEqual(0, len(stats)) <commit_msg>Fix flaky mcrouter tko tests Summary: As above Reviewed By: edenzik Differential Revision: D25722019 fbshipit-source-id: 06ff9200e99f3580db25fef9ca5ab167c50b97ed<commit_after>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re import time from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors'] def setUp(self): self.underlying_mcr = self.add_mcrouter(self.config, extra_args=self.extra_args, bg_mcrouter=True) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) retries = 10 while self.underlying_mcr.stats()['cmd_delete_count'] != 1 and retries > 0: retries = retries - 1 time.sleep(1) stats = self.underlying_mcr.stats("suspect_servers") print(stats) self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0])) stats = mcr.stats("suspect_servers") self.assertEqual(0, len(stats))
5fdd28a4707c8dcc9fe9ef3607742e6856725288
examples/connect4/connect4.py
examples/connect4/connect4.py
class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n ' or ' ' for piece_column in self.pieces: try: output += str(piece_column[5 - i]) + ' ' except IndexError: output += ' ' return output def start(): pass
class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n|' or '|' for piece_column in self.pieces: try: output += piece_column[5 - i] and 'X|' or 'O|' except IndexError: output += ' |' output += '\n 0 1 2 3 4 5 6 ' return output def start(): pass
Make Connect4's __str__ more readable
Make Connect4's __str__ more readable
Python
mit
tysonzero/py-ann
class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n ' or ' ' for piece_column in self.pieces: try: output += str(piece_column[5 - i]) + ' ' except IndexError: output += ' ' return output def start(): pass Make Connect4's __str__ more readable
class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n|' or '|' for piece_column in self.pieces: try: output += piece_column[5 - i] and 'X|' or 'O|' except IndexError: output += ' |' output += '\n 0 1 2 3 4 5 6 ' return output def start(): pass
<commit_before>class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n ' or ' ' for piece_column in self.pieces: try: output += str(piece_column[5 - i]) + ' ' except IndexError: output += ' ' return output def start(): pass <commit_msg>Make Connect4's __str__ more readable<commit_after>
class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n|' or '|' for piece_column in self.pieces: try: output += piece_column[5 - i] and 'X|' or 'O|' except IndexError: output += ' |' output += '\n 0 1 2 3 4 5 6 ' return output def start(): pass
class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n ' or ' ' for piece_column in self.pieces: try: output += str(piece_column[5 - i]) + ' ' except IndexError: output += ' ' return output def start(): pass Make Connect4's __str__ more readableclass Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n|' or '|' for piece_column in self.pieces: try: output += piece_column[5 - i] and 'X|' or 'O|' except IndexError: output += ' |' output += '\n 0 1 2 3 4 5 6 ' return output def start(): pass
<commit_before>class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n ' or ' ' for piece_column in self.pieces: try: output += str(piece_column[5 - i]) + ' ' except IndexError: output += ' ' return output def start(): pass <commit_msg>Make Connect4's __str__ more readable<commit_after>class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n|' or '|' for piece_column in self.pieces: try: output += piece_column[5 - i] and 'X|' or 'O|' except IndexError: output += ' |' output += '\n 0 1 2 3 4 5 6 ' return output def start(): pass
90ee1f19ad1b99c3960f5b4917d6801cd4d4d607
paypal_registration/models.py
paypal_registration/models.py
from django.db import models # Create your models here.
from django.db import models from registration.models import RegistrationProfile class PaypalRegistrationProfile(RegistrationProfile): paid = models.BooleanField(default=False)
Make a bit more sensible model.
Make a bit more sensible model.
Python
bsd-3-clause
buchuki/django-registration-paypal
from django.db import models # Create your models here. Make a bit more sensible model.
from django.db import models from registration.models import RegistrationProfile class PaypalRegistrationProfile(RegistrationProfile): paid = models.BooleanField(default=False)
<commit_before>from django.db import models # Create your models here. <commit_msg>Make a bit more sensible model.<commit_after>
from django.db import models from registration.models import RegistrationProfile class PaypalRegistrationProfile(RegistrationProfile): paid = models.BooleanField(default=False)
from django.db import models # Create your models here. Make a bit more sensible model.from django.db import models from registration.models import RegistrationProfile class PaypalRegistrationProfile(RegistrationProfile): paid = models.BooleanField(default=False)
<commit_before>from django.db import models # Create your models here. <commit_msg>Make a bit more sensible model.<commit_after>from django.db import models from registration.models import RegistrationProfile class PaypalRegistrationProfile(RegistrationProfile): paid = models.BooleanField(default=False)
4c6c0561743c03ac70d82fc0e7af1a3a135b7c84
test/test_pipeline/components/regression/test_liblinear_svr.py
test/test_pipeline/components/regression/test_liblinear_svr.py
import unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(LibLinear_SVR, dataset='boston') self.assertAlmostEqual(0.67714499792824023, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions))
import unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(LibLinear_SVR, dataset='boston') # Lenient test because of travis-ci which gets quite different # results here! self.assertAlmostEqual(0.68, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions), places=2)
FIX numerical issues in test on travis-ci
FIX numerical issues in test on travis-ci
Python
bsd-3-clause
automl/auto-sklearn,automl/auto-sklearn
import unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(LibLinear_SVR, dataset='boston') self.assertAlmostEqual(0.67714499792824023, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) FIX numerical issues in test on travis-ci
import unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(LibLinear_SVR, dataset='boston') # Lenient test because of travis-ci which gets quite different # results here! self.assertAlmostEqual(0.68, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions), places=2)
<commit_before>import unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(LibLinear_SVR, dataset='boston') self.assertAlmostEqual(0.67714499792824023, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) <commit_msg>FIX numerical issues in test on travis-ci<commit_after>
import unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(LibLinear_SVR, dataset='boston') # Lenient test because of travis-ci which gets quite different # results here! self.assertAlmostEqual(0.68, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions), places=2)
import unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(LibLinear_SVR, dataset='boston') self.assertAlmostEqual(0.67714499792824023, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) FIX numerical issues in test on travis-ciimport unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(LibLinear_SVR, dataset='boston') # Lenient test because of travis-ci which gets quite different # results here! self.assertAlmostEqual(0.68, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions), places=2)
<commit_before>import unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(LibLinear_SVR, dataset='boston') self.assertAlmostEqual(0.67714499792824023, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions)) <commit_msg>FIX numerical issues in test on travis-ci<commit_after>import unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): predictions, targets = _test_regressor(LibLinear_SVR, dataset='boston') # Lenient test because of travis-ci which gets quite different # results here! self.assertAlmostEqual(0.68, sklearn.metrics.r2_score(y_true=targets, y_pred=predictions), places=2)
1dc7383a2f51c225f0138792eff6d35dc35dac8c
infinite_memcached/tests.py
infinite_memcached/tests.py
import time from django.test import TestCase from infinite_memcached.cache import MemcachedCache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = MemcachedCache( server="127.0.0.1:11211", params={}, ) self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days))
import time from django.test import TestCase from django.core.cache import get_cache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = get_cache('infinite_memcached.cache.MemcachedCache', LOCATION='127.0.0.1:11211') self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days))
Load the backend with get_cache
Load the backend with get_cache
Python
bsd-3-clause
edavis/django-infinite-memcached,edavis/django-infinite-memcached
import time from django.test import TestCase from infinite_memcached.cache import MemcachedCache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = MemcachedCache( server="127.0.0.1:11211", params={}, ) self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days)) Load the backend with get_cache
import time from django.test import TestCase from django.core.cache import get_cache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = get_cache('infinite_memcached.cache.MemcachedCache', LOCATION='127.0.0.1:11211') self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days))
<commit_before>import time from django.test import TestCase from infinite_memcached.cache import MemcachedCache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = MemcachedCache( server="127.0.0.1:11211", params={}, ) self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days)) <commit_msg>Load the backend with get_cache<commit_after>
import time from django.test import TestCase from django.core.cache import get_cache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = get_cache('infinite_memcached.cache.MemcachedCache', LOCATION='127.0.0.1:11211') self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days))
import time from django.test import TestCase from infinite_memcached.cache import MemcachedCache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = MemcachedCache( server="127.0.0.1:11211", params={}, ) self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days)) Load the backend with get_cacheimport time from django.test import TestCase from django.core.cache import get_cache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = get_cache('infinite_memcached.cache.MemcachedCache', LOCATION='127.0.0.1:11211') self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days))
<commit_before>import time from django.test import TestCase from infinite_memcached.cache import MemcachedCache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = MemcachedCache( server="127.0.0.1:11211", params={}, ) self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days)) <commit_msg>Load the backend with get_cache<commit_after>import time from django.test import TestCase from django.core.cache import get_cache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = get_cache('infinite_memcached.cache.MemcachedCache', LOCATION='127.0.0.1:11211') self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days))
86091dedfe1fc9ececb5c9e36a79866660525e90
ckanext/ckanext-apicatalog_routes/ckanext/apicatalog_routes/tests/test_plugin.py
ckanext/ckanext-apicatalog_routes/ckanext/apicatalog_routes/tests/test_plugin.py
"""Tests for plugin.py.""" def test_plugin(): pass
"""Tests for plugin.py.""" import pytest from ckan.tests import factories import ckan.tests.helpers as helpers from ckan.plugins.toolkit import NotAuthorized @pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes') @pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context') class Apicatalog_Routes_Tests(): def non_sysadmins_should_not_be_able_to_delete_subsystems(self): user = factories.User() org_users = [{"name": user["name"], "capacity": "admin"}] org = factories.Organization(users=org_users) subsystem = factories.Dataset( owner_org=org["id"] ) context = {'ignore_auth': False, 'user': user['name']} with pytest.raises(NotAuthorized): helpers.call_action('package_delete', context, name=subsystem['name'])
Add test for deleting subsystem as normal user
Add test for deleting subsystem as normal user
Python
mit
vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog
"""Tests for plugin.py.""" def test_plugin(): pass Add test for deleting subsystem as normal user
"""Tests for plugin.py.""" import pytest from ckan.tests import factories import ckan.tests.helpers as helpers from ckan.plugins.toolkit import NotAuthorized @pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes') @pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context') class Apicatalog_Routes_Tests(): def non_sysadmins_should_not_be_able_to_delete_subsystems(self): user = factories.User() org_users = [{"name": user["name"], "capacity": "admin"}] org = factories.Organization(users=org_users) subsystem = factories.Dataset( owner_org=org["id"] ) context = {'ignore_auth': False, 'user': user['name']} with pytest.raises(NotAuthorized): helpers.call_action('package_delete', context, name=subsystem['name'])
<commit_before>"""Tests for plugin.py.""" def test_plugin(): pass <commit_msg>Add test for deleting subsystem as normal user<commit_after>
"""Tests for plugin.py.""" import pytest from ckan.tests import factories import ckan.tests.helpers as helpers from ckan.plugins.toolkit import NotAuthorized @pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes') @pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context') class Apicatalog_Routes_Tests(): def non_sysadmins_should_not_be_able_to_delete_subsystems(self): user = factories.User() org_users = [{"name": user["name"], "capacity": "admin"}] org = factories.Organization(users=org_users) subsystem = factories.Dataset( owner_org=org["id"] ) context = {'ignore_auth': False, 'user': user['name']} with pytest.raises(NotAuthorized): helpers.call_action('package_delete', context, name=subsystem['name'])
"""Tests for plugin.py.""" def test_plugin(): pass Add test for deleting subsystem as normal user"""Tests for plugin.py.""" import pytest from ckan.tests import factories import ckan.tests.helpers as helpers from ckan.plugins.toolkit import NotAuthorized @pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes') @pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context') class Apicatalog_Routes_Tests(): def non_sysadmins_should_not_be_able_to_delete_subsystems(self): user = factories.User() org_users = [{"name": user["name"], "capacity": "admin"}] org = factories.Organization(users=org_users) subsystem = factories.Dataset( owner_org=org["id"] ) context = {'ignore_auth': False, 'user': user['name']} with pytest.raises(NotAuthorized): helpers.call_action('package_delete', context, name=subsystem['name'])
<commit_before>"""Tests for plugin.py.""" def test_plugin(): pass <commit_msg>Add test for deleting subsystem as normal user<commit_after>"""Tests for plugin.py.""" import pytest from ckan.tests import factories import ckan.tests.helpers as helpers from ckan.plugins.toolkit import NotAuthorized @pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes') @pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context') class Apicatalog_Routes_Tests(): def non_sysadmins_should_not_be_able_to_delete_subsystems(self): user = factories.User() org_users = [{"name": user["name"], "capacity": "admin"}] org = factories.Organization(users=org_users) subsystem = factories.Dataset( owner_org=org["id"] ) context = {'ignore_auth': False, 'user': user['name']} with pytest.raises(NotAuthorized): helpers.call_action('package_delete', context, name=subsystem['name'])
d921858302f8bba715a7f4e63eaec68dfe04927a
app/grandchallenge/workstations/context_processors.py
app/grandchallenge/workstations/context_processors.py
from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) return {"workstation_session": s}
from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None try: if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) except AttributeError: # No user pass return {"workstation_session": s}
Handle no user at all
Handle no user at all
Python
apache-2.0
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) return {"workstation_session": s} Handle no user at all
from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None try: if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) except AttributeError: # No user pass return {"workstation_session": s}
<commit_before>from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) return {"workstation_session": s} <commit_msg>Handle no user at all<commit_after>
from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None try: if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) except AttributeError: # No user pass return {"workstation_session": s}
from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) return {"workstation_session": s} Handle no user at allfrom grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None try: if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) except AttributeError: # No user pass return {"workstation_session": s}
<commit_before>from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) return {"workstation_session": s} <commit_msg>Handle no user at all<commit_after>from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None try: if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) except AttributeError: # No user pass return {"workstation_session": s}
76dff207a128cb9230d8dceea24d0fb8e174ac3d
exporter/settings.py
exporter/settings.py
# Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils')
# Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils', 'sjevents')
Add sjevents to modules exported.
Add sjevents to modules exported.
Python
lgpl-2.1
SmartJog/webengine,SmartJog/webengine
# Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils') Add sjevents to modules exported.
# Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils', 'sjevents')
<commit_before># Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils') <commit_msg>Add sjevents to modules exported.<commit_after>
# Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils', 'sjevents')
# Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils') Add sjevents to modules exported.# Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils', 'sjevents')
<commit_before># Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils') <commit_msg>Add sjevents to modules exported.<commit_after># Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils', 'sjevents')
907169a645cd779de1a382dc09765a04c0217206
dyngraph/exporter.py
dyngraph/exporter.py
from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] if xmin <= 0: xmin = 0 if xmax >= datalen: xmax = datalen self.xmax, self.xmin = int(xmax), int(xmin) def tocsv(self, filename): self.updaterange() data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax] data.to_csv(filename, index = False)
from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] if xmin <= 0: xmin = 0 if xmax >= datalen: xmax = datalen self.xmax, self.xmin = int(xmax), int(xmin) def tocsv(self, filename): self.updaterange() data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax] datanona = data.dropna(how = 'all', subset = self.plotinfo.yfields) datanona.to_csv(filename, index = False)
Remove NA values from export.
Remove NA values from export.
Python
isc
jaj42/GraPhysio,jaj42/dyngraph,jaj42/GraPhysio
from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] if xmin <= 0: xmin = 0 if xmax >= datalen: xmax = datalen self.xmax, self.xmin = int(xmax), int(xmin) def tocsv(self, filename): self.updaterange() data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax] data.to_csv(filename, index = False) Remove NA values from export.
from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] if xmin <= 0: xmin = 0 if xmax >= datalen: xmax = datalen self.xmax, self.xmin = int(xmax), int(xmin) def tocsv(self, filename): self.updaterange() data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax] datanona = data.dropna(how = 'all', subset = self.plotinfo.yfields) datanona.to_csv(filename, index = False)
<commit_before>from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] if xmin <= 0: xmin = 0 if xmax >= datalen: xmax = datalen self.xmax, self.xmin = int(xmax), int(xmin) def tocsv(self, filename): self.updaterange() data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax] data.to_csv(filename, index = False) <commit_msg>Remove NA values from export.<commit_after>
from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] if xmin <= 0: xmin = 0 if xmax >= datalen: xmax = datalen self.xmax, self.xmin = int(xmax), int(xmin) def tocsv(self, filename): self.updaterange() data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax] datanona = data.dropna(how = 'all', subset = self.plotinfo.yfields) datanona.to_csv(filename, index = False)
from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] if xmin <= 0: xmin = 0 if xmax >= datalen: xmax = datalen self.xmax, self.xmin = int(xmax), int(xmin) def tocsv(self, filename): self.updaterange() data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax] data.to_csv(filename, index = False) Remove NA values from export.from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] if xmin <= 0: xmin = 0 if xmax >= datalen: xmax = datalen self.xmax, self.xmin = int(xmax), int(xmin) def tocsv(self, filename): self.updaterange() data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax] datanona = data.dropna(how = 'all', subset = self.plotinfo.yfields) datanona.to_csv(filename, index = False)
<commit_before>from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] if xmin <= 0: xmin = 0 if xmax >= datalen: xmax = datalen self.xmax, self.xmin = int(xmax), int(xmin) def tocsv(self, filename): self.updaterange() data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax] data.to_csv(filename, index = False) <commit_msg>Remove NA values from export.<commit_after>from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] if xmin <= 0: xmin = 0 if xmax >= datalen: xmax = datalen self.xmax, self.xmin = int(xmax), int(xmin) def tocsv(self, filename): self.updaterange() data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax] datanona = data.dropna(how = 'all', subset = self.plotinfo.yfields) datanona.to_csv(filename, index = False)
355205554a7b95ae81fe7fc04fa65c3a850b3c47
Tools/ecl_ekf/batch_process_logdata_ekf.py
Tools/ecl_ekf/batch_process_logdata_ekf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py "+ulog_directory+"/"+file)
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py '{}'".format(os.path.join(ulog_directory, file)))
Use format to properly format file for process_logdata_parser.py
Use format to properly format file for process_logdata_parser.py
Python
bsd-3-clause
acfloria/Firmware,mje-nz/PX4-Firmware,dagar/Firmware,dagar/Firmware,krbeverx/Firmware,mje-nz/PX4-Firmware,mje-nz/PX4-Firmware,PX4/Firmware,mcgill-robotics/Firmware,jlecoeur/Firmware,krbeverx/Firmware,dagar/Firmware,krbeverx/Firmware,Aerotenna/Firmware,Aerotenna/Firmware,dagar/Firmware,acfloria/Firmware,acfloria/Firmware,acfloria/Firmware,jlecoeur/Firmware,mje-nz/PX4-Firmware,jlecoeur/Firmware,PX4/Firmware,dagar/Firmware,jlecoeur/Firmware,Aerotenna/Firmware,acfloria/Firmware,dagar/Firmware,Aerotenna/Firmware,jlecoeur/Firmware,mje-nz/PX4-Firmware,mcgill-robotics/Firmware,krbeverx/Firmware,Aerotenna/Firmware,krbeverx/Firmware,mcgill-robotics/Firmware,mje-nz/PX4-Firmware,acfloria/Firmware,PX4/Firmware,mcgill-robotics/Firmware,jlecoeur/Firmware,PX4/Firmware,jlecoeur/Firmware,acfloria/Firmware,krbeverx/Firmware,PX4/Firmware,jlecoeur/Firmware,mje-nz/PX4-Firmware,Aerotenna/Firmware,mcgill-robotics/Firmware,mcgill-robotics/Firmware,krbeverx/Firmware,mcgill-robotics/Firmware,PX4/Firmware,PX4/Firmware,Aerotenna/Firmware,dagar/Firmware
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py "+ulog_directory+"/"+file) Use format to properly format file for process_logdata_parser.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py '{}'".format(os.path.join(ulog_directory, file)))
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py "+ulog_directory+"/"+file) <commit_msg>Use format to properly format file for process_logdata_parser.py<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py '{}'".format(os.path.join(ulog_directory, file)))
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py "+ulog_directory+"/"+file) Use format to properly format file for process_logdata_parser.py#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py '{}'".format(os.path.join(ulog_directory, file)))
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py "+ulog_directory+"/"+file) <commit_msg>Use format to properly format file for process_logdata_parser.py<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified directory') parser.add_argument("directory_path") def is_valid_directory(parser, arg): if os.path.isdir(arg): # Directory exists so return the directory return arg else: parser.error('The directory {} does not exist'.format(arg)) args = parser.parse_args() ulog_directory = args.directory_path print("\n"+"analysing all .ulog files in "+ulog_directory) # Run the analysis script on all the log files found in the specified directory for file in os.listdir(ulog_directory): if file.endswith(".ulg"): print("\n"+"loading "+file+" for analysis") os.system("python process_logdata_ekf.py '{}'".format(os.path.join(ulog_directory, file)))
2a731fba72268c9a07d81c591be608f2292b06cb
byceps/blueprints/core_admin/views.py
byceps/blueprints/core_admin/views.py
# -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand.models import Brand blueprint = create_blueprint('core_admin', __name__) @blueprint.app_context_processor def inject_brands(): return { 'all_brands': Brand.query.all(), }
# -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand import service as brand_service blueprint = create_blueprint('core_admin', __name__) @blueprint.app_context_processor def inject_brands(): brands = brand_service.get_brands() return { 'all_brands': brands, }
Move database query assembly and execution from view functions to services ('core_admin' blueprint)
Move database query assembly and execution from view functions to services ('core_admin' blueprint)
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps
# -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand.models import Brand blueprint = create_blueprint('core_admin', __name__) @blueprint.app_context_processor def inject_brands(): return { 'all_brands': Brand.query.all(), } Move database query assembly and execution from view functions to services ('core_admin' blueprint)
# -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand import service as brand_service blueprint = create_blueprint('core_admin', __name__) @blueprint.app_context_processor def inject_brands(): brands = brand_service.get_brands() return { 'all_brands': brands, }
<commit_before># -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand.models import Brand blueprint = create_blueprint('core_admin', __name__) @blueprint.app_context_processor def inject_brands(): return { 'all_brands': Brand.query.all(), } <commit_msg>Move database query assembly and execution from view functions to services ('core_admin' blueprint)<commit_after>
# -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand import service as brand_service blueprint = create_blueprint('core_admin', __name__) @blueprint.app_context_processor def inject_brands(): brands = brand_service.get_brands() return { 'all_brands': brands, }
# -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand.models import Brand blueprint = create_blueprint('core_admin', __name__) @blueprint.app_context_processor def inject_brands(): return { 'all_brands': Brand.query.all(), } Move database query assembly and execution from view functions to services ('core_admin' blueprint)# -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand import service as brand_service blueprint = create_blueprint('core_admin', __name__) @blueprint.app_context_processor def inject_brands(): brands = brand_service.get_brands() return { 'all_brands': brands, }
<commit_before># -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand.models import Brand blueprint = create_blueprint('core_admin', __name__) @blueprint.app_context_processor def inject_brands(): return { 'all_brands': Brand.query.all(), } <commit_msg>Move database query assembly and execution from view functions to services ('core_admin' blueprint)<commit_after># -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand import service as brand_service blueprint = create_blueprint('core_admin', __name__) @blueprint.app_context_processor def inject_brands(): brands = brand_service.get_brands() return { 'all_brands': brands, }
d882e6f707455113c133c843e40852acdf343e1a
dodo_commands/extra/git_commands/git-create-branch.py
dodo_commands/extra/git_commands/git-create-branch.py
# noqa from dodo_commands.defaults.commands.standard_commands import DodoCommand from dodo_commands import call_command from plumbum import local from plumbum.cmd import git class Command(DodoCommand): # noqa help = "" decorators = [] def add_arguments_imp(self, parser): # noqa parser.add_argument('branch') def handle_imp(self, branch, **kwargs): # noqa src_dir = self.get_config("/ROOT/src_dir") with local.cwd(src_dir): has_local_changes = git("diff") if has_local_changes: self.runcmd( ["git", "stash", "save", "create_branch_" + branch], cwd=src_dir) self.runcmd(["git", "checkout", "dev"], cwd=src_dir) self.runcmd(["git", "pull"], cwd=src_dir) self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir) with local.cwd(src_dir): call_command("gitsplit", "--move", "HEAD") if has_local_changes: self.runcmd(["git", "stash", "pop"], cwd=src_dir)
# noqa from dodo_commands.default_commands.standard_commands import DodoCommand from dodo_commands import call_command from plumbum import local from plumbum.cmd import git class Command(DodoCommand): # noqa help = "" decorators = [] def add_arguments_imp(self, parser): # noqa parser.add_argument('branch') def handle_imp(self, branch, **kwargs): # noqa src_dir = self.get_config("/ROOT/src_dir") with local.cwd(src_dir): has_local_changes = git("diff") if has_local_changes: self.runcmd( ["git", "stash", "save", "create_branch_" + branch], cwd=src_dir) self.runcmd(["git", "checkout", "dev"], cwd=src_dir) self.runcmd(["git", "pull"], cwd=src_dir) self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir) with local.cwd(src_dir): call_command("gitsplit", "--move", "HEAD") if has_local_changes: self.runcmd(["git", "stash", "pop"], cwd=src_dir)
Fix import path to default_commands
Fix import path to default_commands
Python
mit
mnieber/dodo_commands
# noqa from dodo_commands.defaults.commands.standard_commands import DodoCommand from dodo_commands import call_command from plumbum import local from plumbum.cmd import git class Command(DodoCommand): # noqa help = "" decorators = [] def add_arguments_imp(self, parser): # noqa parser.add_argument('branch') def handle_imp(self, branch, **kwargs): # noqa src_dir = self.get_config("/ROOT/src_dir") with local.cwd(src_dir): has_local_changes = git("diff") if has_local_changes: self.runcmd( ["git", "stash", "save", "create_branch_" + branch], cwd=src_dir) self.runcmd(["git", "checkout", "dev"], cwd=src_dir) self.runcmd(["git", "pull"], cwd=src_dir) self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir) with local.cwd(src_dir): call_command("gitsplit", "--move", "HEAD") if has_local_changes: self.runcmd(["git", "stash", "pop"], cwd=src_dir) Fix import path to default_commands
# noqa from dodo_commands.default_commands.standard_commands import DodoCommand from dodo_commands import call_command from plumbum import local from plumbum.cmd import git class Command(DodoCommand): # noqa help = "" decorators = [] def add_arguments_imp(self, parser): # noqa parser.add_argument('branch') def handle_imp(self, branch, **kwargs): # noqa src_dir = self.get_config("/ROOT/src_dir") with local.cwd(src_dir): has_local_changes = git("diff") if has_local_changes: self.runcmd( ["git", "stash", "save", "create_branch_" + branch], cwd=src_dir) self.runcmd(["git", "checkout", "dev"], cwd=src_dir) self.runcmd(["git", "pull"], cwd=src_dir) self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir) with local.cwd(src_dir): call_command("gitsplit", "--move", "HEAD") if has_local_changes: self.runcmd(["git", "stash", "pop"], cwd=src_dir)
<commit_before># noqa from dodo_commands.defaults.commands.standard_commands import DodoCommand from dodo_commands import call_command from plumbum import local from plumbum.cmd import git class Command(DodoCommand): # noqa help = "" decorators = [] def add_arguments_imp(self, parser): # noqa parser.add_argument('branch') def handle_imp(self, branch, **kwargs): # noqa src_dir = self.get_config("/ROOT/src_dir") with local.cwd(src_dir): has_local_changes = git("diff") if has_local_changes: self.runcmd( ["git", "stash", "save", "create_branch_" + branch], cwd=src_dir) self.runcmd(["git", "checkout", "dev"], cwd=src_dir) self.runcmd(["git", "pull"], cwd=src_dir) self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir) with local.cwd(src_dir): call_command("gitsplit", "--move", "HEAD") if has_local_changes: self.runcmd(["git", "stash", "pop"], cwd=src_dir) <commit_msg>Fix import path to default_commands<commit_after>
# noqa from dodo_commands.default_commands.standard_commands import DodoCommand from dodo_commands import call_command from plumbum import local from plumbum.cmd import git class Command(DodoCommand): # noqa help = "" decorators = [] def add_arguments_imp(self, parser): # noqa parser.add_argument('branch') def handle_imp(self, branch, **kwargs): # noqa src_dir = self.get_config("/ROOT/src_dir") with local.cwd(src_dir): has_local_changes = git("diff") if has_local_changes: self.runcmd( ["git", "stash", "save", "create_branch_" + branch], cwd=src_dir) self.runcmd(["git", "checkout", "dev"], cwd=src_dir) self.runcmd(["git", "pull"], cwd=src_dir) self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir) with local.cwd(src_dir): call_command("gitsplit", "--move", "HEAD") if has_local_changes: self.runcmd(["git", "stash", "pop"], cwd=src_dir)
# noqa from dodo_commands.defaults.commands.standard_commands import DodoCommand from dodo_commands import call_command from plumbum import local from plumbum.cmd import git class Command(DodoCommand): # noqa help = "" decorators = [] def add_arguments_imp(self, parser): # noqa parser.add_argument('branch') def handle_imp(self, branch, **kwargs): # noqa src_dir = self.get_config("/ROOT/src_dir") with local.cwd(src_dir): has_local_changes = git("diff") if has_local_changes: self.runcmd( ["git", "stash", "save", "create_branch_" + branch], cwd=src_dir) self.runcmd(["git", "checkout", "dev"], cwd=src_dir) self.runcmd(["git", "pull"], cwd=src_dir) self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir) with local.cwd(src_dir): call_command("gitsplit", "--move", "HEAD") if has_local_changes: self.runcmd(["git", "stash", "pop"], cwd=src_dir) Fix import path to default_commands# noqa from dodo_commands.default_commands.standard_commands import DodoCommand from dodo_commands import call_command from plumbum import local from plumbum.cmd import git class Command(DodoCommand): # noqa help = "" decorators = [] def add_arguments_imp(self, parser): # noqa parser.add_argument('branch') def handle_imp(self, branch, **kwargs): # noqa src_dir = self.get_config("/ROOT/src_dir") with local.cwd(src_dir): has_local_changes = git("diff") if has_local_changes: self.runcmd( ["git", "stash", "save", "create_branch_" + branch], cwd=src_dir) self.runcmd(["git", "checkout", "dev"], cwd=src_dir) self.runcmd(["git", "pull"], cwd=src_dir) self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir) with local.cwd(src_dir): call_command("gitsplit", "--move", "HEAD") if has_local_changes: self.runcmd(["git", "stash", "pop"], cwd=src_dir)
<commit_before># noqa from dodo_commands.defaults.commands.standard_commands import DodoCommand from dodo_commands import call_command from plumbum import local from plumbum.cmd import git class Command(DodoCommand): # noqa help = "" decorators = [] def add_arguments_imp(self, parser): # noqa parser.add_argument('branch') def handle_imp(self, branch, **kwargs): # noqa src_dir = self.get_config("/ROOT/src_dir") with local.cwd(src_dir): has_local_changes = git("diff") if has_local_changes: self.runcmd( ["git", "stash", "save", "create_branch_" + branch], cwd=src_dir) self.runcmd(["git", "checkout", "dev"], cwd=src_dir) self.runcmd(["git", "pull"], cwd=src_dir) self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir) with local.cwd(src_dir): call_command("gitsplit", "--move", "HEAD") if has_local_changes: self.runcmd(["git", "stash", "pop"], cwd=src_dir) <commit_msg>Fix import path to default_commands<commit_after># noqa from dodo_commands.default_commands.standard_commands import DodoCommand from dodo_commands import call_command from plumbum import local from plumbum.cmd import git class Command(DodoCommand): # noqa help = "" decorators = [] def add_arguments_imp(self, parser): # noqa parser.add_argument('branch') def handle_imp(self, branch, **kwargs): # noqa src_dir = self.get_config("/ROOT/src_dir") with local.cwd(src_dir): has_local_changes = git("diff") if has_local_changes: self.runcmd( ["git", "stash", "save", "create_branch_" + branch], cwd=src_dir) self.runcmd(["git", "checkout", "dev"], cwd=src_dir) self.runcmd(["git", "pull"], cwd=src_dir) self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir) with local.cwd(src_dir): call_command("gitsplit", "--move", "HEAD") if has_local_changes: self.runcmd(["git", "stash", "pop"], cwd=src_dir)
c5ef250240cbaa894ee84615c5d07a383bd16962
fluent_contents/plugins/oembeditem/content_plugins.py
fluent_contents/plugins/oembeditem/content_plugins.py
""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ return ["fluent_contents/plugins/oembed/{type}.html".format(type=instance.type or 'default'), self.render_template]
""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem import re re_safe = re.compile(r'[^\w_-]') @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ safe_filename = re_safe.sub('', instance.type or 'default') return [ "fluent_contents/plugins/oembed/{type}.html".format(type=safe_filename), self.render_template ]
Make sure the OEmbed type can never be used to control filenames.
Make sure the OEmbed type can never be used to control filenames. Minor risk, as it's still a template path, but better be safe then sorry.
Python
apache-2.0
pombredanne/django-fluent-contents,edoburu/django-fluent-contents,jpotterm/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,ixc/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,pombredanne/django-fluent-contents,ixc/django-fluent-contents,django-fluent/django-fluent-contents,django-fluent/django-fluent-contents,edoburu/django-fluent-contents,jpotterm/django-fluent-contents
""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ return ["fluent_contents/plugins/oembed/{type}.html".format(type=instance.type or 'default'), self.render_template] Make sure the OEmbed type can never be used to control filenames. Minor risk, as it's still a template path, but better be safe then sorry.
""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem import re re_safe = re.compile(r'[^\w_-]') @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ safe_filename = re_safe.sub('', instance.type or 'default') return [ "fluent_contents/plugins/oembed/{type}.html".format(type=safe_filename), self.render_template ]
<commit_before>""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ return ["fluent_contents/plugins/oembed/{type}.html".format(type=instance.type or 'default'), self.render_template] <commit_msg>Make sure the OEmbed type can never be used to control filenames. Minor risk, as it's still a template path, but better be safe then sorry.<commit_after>
""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem import re re_safe = re.compile(r'[^\w_-]') @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ safe_filename = re_safe.sub('', instance.type or 'default') return [ "fluent_contents/plugins/oembed/{type}.html".format(type=safe_filename), self.render_template ]
""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ return ["fluent_contents/plugins/oembed/{type}.html".format(type=instance.type or 'default'), self.render_template] Make sure the OEmbed type can never be used to control filenames. Minor risk, as it's still a template path, but better be safe then sorry.""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem import re re_safe = re.compile(r'[^\w_-]') @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ safe_filename = re_safe.sub('', instance.type or 'default') return [ "fluent_contents/plugins/oembed/{type}.html".format(type=safe_filename), self.render_template ]
<commit_before>""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ return ["fluent_contents/plugins/oembed/{type}.html".format(type=instance.type or 'default'), self.render_template] <commit_msg>Make sure the OEmbed type can never be used to control filenames. Minor risk, as it's still a template path, but better be safe then sorry.<commit_after>""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem import re re_safe = re.compile(r'[^\w_-]') @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ safe_filename = re_safe.sub('', instance.type or 'default') return [ "fluent_contents/plugins/oembed/{type}.html".format(type=safe_filename), self.render_template ]
a78bc9909780e8621216b11855e23998a169e8af
test_core.py
test_core.py
#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ # # # # # # # > . . \ # # . # . . # # . o . . # # . \ . / # # # # # # # """) game.start() print "hit <enter> to render next; ^C to abort" status = core.Game.STATUS_ON while status == core.Game.STATUS_ON: print utils.dump_game_to_string(game) status = game.step() raw_input() print utils.dump_game_to_string(game) print "game status: %s" % game.get_status()
#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ # # # # # # # > . . \ # # . # . . # # o / + . # # . \ . / # # # # # # # """) game.start() print "hit <enter> to render next; ^C to abort" status = core.Game.STATUS_ON while status == core.Game.STATUS_ON: print utils.dump_game_to_string(game) status = game.step() raw_input() print utils.dump_game_to_string(game) print "game status: %s" % game.get_status()
Put both victory exit and defeat trap on a map
test: Put both victory exit and defeat trap on a map
Python
mit
vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah
#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ # # # # # # # > . . \ # # . # . . # # . o . . # # . \ . / # # # # # # # """) game.start() print "hit <enter> to render next; ^C to abort" status = core.Game.STATUS_ON while status == core.Game.STATUS_ON: print utils.dump_game_to_string(game) status = game.step() raw_input() print utils.dump_game_to_string(game) print "game status: %s" % game.get_status() test: Put both victory exit and defeat trap on a map
#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ # # # # # # # > . . \ # # . # . . # # o / + . # # . \ . / # # # # # # # """) game.start() print "hit <enter> to render next; ^C to abort" status = core.Game.STATUS_ON while status == core.Game.STATUS_ON: print utils.dump_game_to_string(game) status = game.step() raw_input() print utils.dump_game_to_string(game) print "game status: %s" % game.get_status()
<commit_before>#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ # # # # # # # > . . \ # # . # . . # # . o . . # # . \ . / # # # # # # # """) game.start() print "hit <enter> to render next; ^C to abort" status = core.Game.STATUS_ON while status == core.Game.STATUS_ON: print utils.dump_game_to_string(game) status = game.step() raw_input() print utils.dump_game_to_string(game) print "game status: %s" % game.get_status() <commit_msg>test: Put both victory exit and defeat trap on a map<commit_after>
#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ # # # # # # # > . . \ # # . # . . # # o / + . # # . \ . / # # # # # # # """) game.start() print "hit <enter> to render next; ^C to abort" status = core.Game.STATUS_ON while status == core.Game.STATUS_ON: print utils.dump_game_to_string(game) status = game.step() raw_input() print utils.dump_game_to_string(game) print "game status: %s" % game.get_status()
#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ # # # # # # # > . . \ # # . # . . # # . o . . # # . \ . / # # # # # # # """) game.start() print "hit <enter> to render next; ^C to abort" status = core.Game.STATUS_ON while status == core.Game.STATUS_ON: print utils.dump_game_to_string(game) status = game.step() raw_input() print utils.dump_game_to_string(game) print "game status: %s" % game.get_status() test: Put both victory exit and defeat trap on a map#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ # # # # # # # > . . \ # # . # . . # # o / + . # # . \ . / # # # # # # # """) game.start() print "hit <enter> to render next; ^C to abort" status = core.Game.STATUS_ON while status == core.Game.STATUS_ON: print utils.dump_game_to_string(game) status = game.step() raw_input() print utils.dump_game_to_string(game) print "game status: %s" % game.get_status()
<commit_before>#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ # # # # # # # > . . \ # # . # . . # # . o . . # # . \ . / # # # # # # # """) game.start() print "hit <enter> to render next; ^C to abort" status = core.Game.STATUS_ON while status == core.Game.STATUS_ON: print utils.dump_game_to_string(game) status = game.step() raw_input() print utils.dump_game_to_string(game) print "game status: %s" % game.get_status() <commit_msg>test: Put both victory exit and defeat trap on a map<commit_after>#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ # # # # # # # > . . \ # # . # . . # # o / + . # # . \ . / # # # # # # # """) game.start() print "hit <enter> to render next; ^C to abort" status = core.Game.STATUS_ON while status == core.Game.STATUS_ON: print utils.dump_game_to_string(game) status = game.step() raw_input() print utils.dump_game_to_string(game) print "game status: %s" % game.get_status()
0a28636f2ddd1a088556adeca8767abde1bcc34d
src/webassets/__init__.py
src/webassets/__init__.py
__version__ = (0, 10, 1) # Make a couple frequently used things available right here. from .bundle import Bundle from .env import Environment
__version__ = (0, 11, 'dev') # Make a couple frequently used things available right here. from .bundle import Bundle from .env import Environment
Change version number to dev again.
Change version number to dev again.
Python
bsd-2-clause
wijerasa/webassets,glorpen/webassets,john2x/webassets,heynemann/webassets,glorpen/webassets,aconrad/webassets,aconrad/webassets,florianjacob/webassets,heynemann/webassets,heynemann/webassets,glorpen/webassets,scorphus/webassets,JDeuce/webassets,scorphus/webassets,john2x/webassets,aconrad/webassets,JDeuce/webassets,florianjacob/webassets,wijerasa/webassets
__version__ = (0, 10, 1) # Make a couple frequently used things available right here. from .bundle import Bundle from .env import Environment Change version number to dev again.
__version__ = (0, 11, 'dev') # Make a couple frequently used things available right here. from .bundle import Bundle from .env import Environment
<commit_before>__version__ = (0, 10, 1) # Make a couple frequently used things available right here. from .bundle import Bundle from .env import Environment <commit_msg>Change version number to dev again.<commit_after>
__version__ = (0, 11, 'dev') # Make a couple frequently used things available right here. from .bundle import Bundle from .env import Environment
__version__ = (0, 10, 1) # Make a couple frequently used things available right here. from .bundle import Bundle from .env import Environment Change version number to dev again.__version__ = (0, 11, 'dev') # Make a couple frequently used things available right here. from .bundle import Bundle from .env import Environment
<commit_before>__version__ = (0, 10, 1) # Make a couple frequently used things available right here. from .bundle import Bundle from .env import Environment <commit_msg>Change version number to dev again.<commit_after>__version__ = (0, 11, 'dev') # Make a couple frequently used things available right here. from .bundle import Bundle from .env import Environment
1569da946dbe3010984b90f83382c31750551935
testapp/settings.py
testapp/settings.py
# CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160'
# CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160' CQLENGINE_DEFAULT_KEYSPACE = 'flask_cqlengine'
Add setting for CQLENGINE_DEFAULT_KEYSPACE to test app
Add setting for CQLENGINE_DEFAULT_KEYSPACE to test app
Python
apache-2.0
chillinc/Flask-CQLEngine
# CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160' Add setting for CQLENGINE_DEFAULT_KEYSPACE to test app
# CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160' CQLENGINE_DEFAULT_KEYSPACE = 'flask_cqlengine'
<commit_before># CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160' <commit_msg>Add setting for CQLENGINE_DEFAULT_KEYSPACE to test app<commit_after>
# CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160' CQLENGINE_DEFAULT_KEYSPACE = 'flask_cqlengine'
# CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160' Add setting for CQLENGINE_DEFAULT_KEYSPACE to test app# CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160' CQLENGINE_DEFAULT_KEYSPACE = 'flask_cqlengine'
<commit_before># CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160' <commit_msg>Add setting for CQLENGINE_DEFAULT_KEYSPACE to test app<commit_after># CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160' CQLENGINE_DEFAULT_KEYSPACE = 'flask_cqlengine'
dbe40d21d6f38cbb0827eeaaaaab425dd9b724ca
tasks/__init__.py
tasks/__init__.py
from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ ]) selftest_task_queue.conf.update(**queue_conf)
from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ "tasks.message_tasks" ]) selftest_task_queue.conf.update(**queue_conf)
Add tasks to list of mq tasks
Add tasks to list of mq tasks
Python
apache-2.0
BishopFox/SpoofcheckSelfTest,BishopFox/SpoofcheckSelfTest,BishopFox/SpoofcheckSelfTest
from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ ]) selftest_task_queue.conf.update(**queue_conf)Add tasks to list of mq tasks
from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ "tasks.message_tasks" ]) selftest_task_queue.conf.update(**queue_conf)
<commit_before>from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ ]) selftest_task_queue.conf.update(**queue_conf)<commit_msg>Add tasks to list of mq tasks<commit_after>
from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ "tasks.message_tasks" ]) selftest_task_queue.conf.update(**queue_conf)
from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ ]) selftest_task_queue.conf.update(**queue_conf)Add tasks to list of mq tasksfrom celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ "tasks.message_tasks" ]) selftest_task_queue.conf.update(**queue_conf)
<commit_before>from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ ]) selftest_task_queue.conf.update(**queue_conf)<commit_msg>Add tasks to list of mq tasks<commit_after>from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ "tasks.message_tasks" ]) selftest_task_queue.conf.update(**queue_conf)
e38859cacd02553761593719db8420c4bb6c005f
srttools/core/__init__.py
srttools/core/__init__.py
import warnings DEFAULT_MPL_BACKEND = 'TkAgg' try: import matplotlib # This is necessary. Random backends might respond incorrectly. matplotlib.use(DEFAULT_MPL_BACKEND) HAS_MPL = True except ImportError: HAS_MPL = False try: import statsmodels.api as sm version = [int(i) for i in sm.version.version.split('.')] # Minimum version 0.8.0 if version < (0, 8, 0): warnings.warn("Please update statsmodels") raise ImportError HAS_STATSM = True except ImportError: HAS_STATSM = False try: from numba import jit, vectorize except ImportError: warnings.warn("Numba not installed. Faking it") def jit(fun): return fun def vectorize(*args, **kwargs): return jit
import warnings DEFAULT_MPL_BACKEND = 'TkAgg' try: import matplotlib # This is necessary. Random backends might respond incorrectly. matplotlib.use(DEFAULT_MPL_BACKEND) HAS_MPL = True except ImportError: HAS_MPL = False try: import statsmodels.api as sm version = [int(i) for i in sm.version.version.split('.')] # Minimum version 0.8.0 if version < [0, 8, 0]: warnings.warn("Please update statsmodels") raise ImportError HAS_STATSM = True except ImportError: HAS_STATSM = False try: from numba import jit, vectorize except ImportError: warnings.warn("Numba not installed. Faking it") def jit(fun): return fun def vectorize(*args, **kwargs): return jit
Fix bug with comparison of lists and tuples
Fix bug with comparison of lists and tuples
Python
bsd-3-clause
matteobachetti/srt-single-dish-tools
import warnings DEFAULT_MPL_BACKEND = 'TkAgg' try: import matplotlib # This is necessary. Random backends might respond incorrectly. matplotlib.use(DEFAULT_MPL_BACKEND) HAS_MPL = True except ImportError: HAS_MPL = False try: import statsmodels.api as sm version = [int(i) for i in sm.version.version.split('.')] # Minimum version 0.8.0 if version < (0, 8, 0): warnings.warn("Please update statsmodels") raise ImportError HAS_STATSM = True except ImportError: HAS_STATSM = False try: from numba import jit, vectorize except ImportError: warnings.warn("Numba not installed. Faking it") def jit(fun): return fun def vectorize(*args, **kwargs): return jit Fix bug with comparison of lists and tuples
import warnings DEFAULT_MPL_BACKEND = 'TkAgg' try: import matplotlib # This is necessary. Random backends might respond incorrectly. matplotlib.use(DEFAULT_MPL_BACKEND) HAS_MPL = True except ImportError: HAS_MPL = False try: import statsmodels.api as sm version = [int(i) for i in sm.version.version.split('.')] # Minimum version 0.8.0 if version < [0, 8, 0]: warnings.warn("Please update statsmodels") raise ImportError HAS_STATSM = True except ImportError: HAS_STATSM = False try: from numba import jit, vectorize except ImportError: warnings.warn("Numba not installed. Faking it") def jit(fun): return fun def vectorize(*args, **kwargs): return jit
<commit_before>import warnings DEFAULT_MPL_BACKEND = 'TkAgg' try: import matplotlib # This is necessary. Random backends might respond incorrectly. matplotlib.use(DEFAULT_MPL_BACKEND) HAS_MPL = True except ImportError: HAS_MPL = False try: import statsmodels.api as sm version = [int(i) for i in sm.version.version.split('.')] # Minimum version 0.8.0 if version < (0, 8, 0): warnings.warn("Please update statsmodels") raise ImportError HAS_STATSM = True except ImportError: HAS_STATSM = False try: from numba import jit, vectorize except ImportError: warnings.warn("Numba not installed. Faking it") def jit(fun): return fun def vectorize(*args, **kwargs): return jit <commit_msg>Fix bug with comparison of lists and tuples<commit_after>
import warnings DEFAULT_MPL_BACKEND = 'TkAgg' try: import matplotlib # This is necessary. Random backends might respond incorrectly. matplotlib.use(DEFAULT_MPL_BACKEND) HAS_MPL = True except ImportError: HAS_MPL = False try: import statsmodels.api as sm version = [int(i) for i in sm.version.version.split('.')] # Minimum version 0.8.0 if version < [0, 8, 0]: warnings.warn("Please update statsmodels") raise ImportError HAS_STATSM = True except ImportError: HAS_STATSM = False try: from numba import jit, vectorize except ImportError: warnings.warn("Numba not installed. Faking it") def jit(fun): return fun def vectorize(*args, **kwargs): return jit
import warnings DEFAULT_MPL_BACKEND = 'TkAgg' try: import matplotlib # This is necessary. Random backends might respond incorrectly. matplotlib.use(DEFAULT_MPL_BACKEND) HAS_MPL = True except ImportError: HAS_MPL = False try: import statsmodels.api as sm version = [int(i) for i in sm.version.version.split('.')] # Minimum version 0.8.0 if version < (0, 8, 0): warnings.warn("Please update statsmodels") raise ImportError HAS_STATSM = True except ImportError: HAS_STATSM = False try: from numba import jit, vectorize except ImportError: warnings.warn("Numba not installed. Faking it") def jit(fun): return fun def vectorize(*args, **kwargs): return jit Fix bug with comparison of lists and tuplesimport warnings DEFAULT_MPL_BACKEND = 'TkAgg' try: import matplotlib # This is necessary. Random backends might respond incorrectly. matplotlib.use(DEFAULT_MPL_BACKEND) HAS_MPL = True except ImportError: HAS_MPL = False try: import statsmodels.api as sm version = [int(i) for i in sm.version.version.split('.')] # Minimum version 0.8.0 if version < [0, 8, 0]: warnings.warn("Please update statsmodels") raise ImportError HAS_STATSM = True except ImportError: HAS_STATSM = False try: from numba import jit, vectorize except ImportError: warnings.warn("Numba not installed. Faking it") def jit(fun): return fun def vectorize(*args, **kwargs): return jit
<commit_before>import warnings DEFAULT_MPL_BACKEND = 'TkAgg' try: import matplotlib # This is necessary. Random backends might respond incorrectly. matplotlib.use(DEFAULT_MPL_BACKEND) HAS_MPL = True except ImportError: HAS_MPL = False try: import statsmodels.api as sm version = [int(i) for i in sm.version.version.split('.')] # Minimum version 0.8.0 if version < (0, 8, 0): warnings.warn("Please update statsmodels") raise ImportError HAS_STATSM = True except ImportError: HAS_STATSM = False try: from numba import jit, vectorize except ImportError: warnings.warn("Numba not installed. Faking it") def jit(fun): return fun def vectorize(*args, **kwargs): return jit <commit_msg>Fix bug with comparison of lists and tuples<commit_after>import warnings DEFAULT_MPL_BACKEND = 'TkAgg' try: import matplotlib # This is necessary. Random backends might respond incorrectly. matplotlib.use(DEFAULT_MPL_BACKEND) HAS_MPL = True except ImportError: HAS_MPL = False try: import statsmodels.api as sm version = [int(i) for i in sm.version.version.split('.')] # Minimum version 0.8.0 if version < [0, 8, 0]: warnings.warn("Please update statsmodels") raise ImportError HAS_STATSM = True except ImportError: HAS_STATSM = False try: from numba import jit, vectorize except ImportError: warnings.warn("Numba not installed. Faking it") def jit(fun): return fun def vectorize(*args, **kwargs): return jit
bf21ad33327129047d5e1d30b908c7a386da6d77
test_/models.py
test_/models.py
import uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
import uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): my_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
Change test to use a user model with name not id for pk
Change test to use a user model with name not id for pk
Python
mit
feffe/django-selenium-login,feffe/django-selenium-login
import uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Change test to use a user model with name not id for pk
import uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): my_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
<commit_before>import uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) <commit_msg>Change test to use a user model with name not id for pk<commit_after>
import uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): my_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
import uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Change test to use a user model with name not id for pkimport uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): my_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
<commit_before>import uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) <commit_msg>Change test to use a user model with name not id for pk<commit_after>import uuid from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): my_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
8a0953345279c40e3b3cf63a748e8ca7b3ad0199
test_urlconf.py
test_urlconf.py
from django.conf.urls import patterns, url, include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
Test urls - list of urls instead of patterns()
Test urls - list of urls instead of patterns()
Python
isc
yprez/django-logentry-admin,yprez/django-logentry-admin
from django.conf.urls import patterns, url, include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), ) Test urls - list of urls instead of patterns()
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
<commit_before>from django.conf.urls import patterns, url, include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), ) <commit_msg>Test urls - list of urls instead of patterns()<commit_after>
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
from django.conf.urls import patterns, url, include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), ) Test urls - list of urls instead of patterns()from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
<commit_before>from django.conf.urls import patterns, url, include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), ) <commit_msg>Test urls - list of urls instead of patterns()<commit_after>from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
7923baf30bcd41e17182599e46b4efd86f4eab49
tests/conftest.py
tests/conftest.py
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Set the matplotlib back end to a headless one before anything tries # to use matplotlib and get some other back end. import matplotlib matplotlib.use('pdf') import pytest def pytest_addoption(parser): parser.addoption('--integration', action='store_true', help='run integration tests')
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Set the matplotlib back end to a headless one before anything tries # to use matplotlib and get some other back end. import matplotlib matplotlib.use('pdf')
Stop making --integration an argument.
Stop making --integration an argument.
Python
apache-2.0
probcomp/cgpm,probcomp/cgpm
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Set the matplotlib back end to a headless one before anything tries # to use matplotlib and get some other back end. import matplotlib matplotlib.use('pdf') import pytest def pytest_addoption(parser): parser.addoption('--integration', action='store_true', help='run integration tests') Stop making --integration an argument.
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Set the matplotlib back end to a headless one before anything tries # to use matplotlib and get some other back end. import matplotlib matplotlib.use('pdf')
<commit_before># -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Set the matplotlib back end to a headless one before anything tries # to use matplotlib and get some other back end. import matplotlib matplotlib.use('pdf') import pytest def pytest_addoption(parser): parser.addoption('--integration', action='store_true', help='run integration tests') <commit_msg>Stop making --integration an argument.<commit_after>
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Set the matplotlib back end to a headless one before anything tries # to use matplotlib and get some other back end. import matplotlib matplotlib.use('pdf')
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Set the matplotlib back end to a headless one before anything tries # to use matplotlib and get some other back end. import matplotlib matplotlib.use('pdf') import pytest def pytest_addoption(parser): parser.addoption('--integration', action='store_true', help='run integration tests') Stop making --integration an argument.# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Set the matplotlib back end to a headless one before anything tries # to use matplotlib and get some other back end. import matplotlib matplotlib.use('pdf')
<commit_before># -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Set the matplotlib back end to a headless one before anything tries # to use matplotlib and get some other back end. import matplotlib matplotlib.use('pdf') import pytest def pytest_addoption(parser): parser.addoption('--integration', action='store_true', help='run integration tests') <commit_msg>Stop making --integration an argument.<commit_after># -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Set the matplotlib back end to a headless one before anything tries # to use matplotlib and get some other back end. import matplotlib matplotlib.use('pdf')
0b74a76899d4ece2b3d7a8559fdc58c312231174
tests/conftest.py
tests/conftest.py
"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in files: with open(file_) as source: yield source.read() def pytest_generate_tests(metafunc): # pylint: disable=C0111 if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames: metafunc.parametrize( DATA_FILES_FIXTURE_NAME, _load_files_contents(*TEST_DATA_FILES), ids=TEST_DATA_FILES, )
"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in files: with open(file_) as source: yield source.read() def pytest_generate_tests(metafunc): """All tests that take a fixture named ``data_file`` will be parameterized with all the testing data files. This means, the test can be made to work with a single test file as an input, but instead it will run once per every file present in the directory ``TEST_DATA_FILES_LOCATION``. """ if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames: metafunc.parametrize( DATA_FILES_FIXTURE_NAME, _load_files_contents(*TEST_DATA_FILES), ids=TEST_DATA_FILES, )
Add docstring explaining the parametrization of data files
Add docstring explaining the parametrization of data files
Python
mit
rmariano/compr,rmariano/compr
"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in files: with open(file_) as source: yield source.read() def pytest_generate_tests(metafunc): # pylint: disable=C0111 if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames: metafunc.parametrize( DATA_FILES_FIXTURE_NAME, _load_files_contents(*TEST_DATA_FILES), ids=TEST_DATA_FILES, ) Add docstring explaining the parametrization of data files
"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in files: with open(file_) as source: yield source.read() def pytest_generate_tests(metafunc): """All tests that take a fixture named ``data_file`` will be parameterized with all the testing data files. This means, the test can be made to work with a single test file as an input, but instead it will run once per every file present in the directory ``TEST_DATA_FILES_LOCATION``. """ if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames: metafunc.parametrize( DATA_FILES_FIXTURE_NAME, _load_files_contents(*TEST_DATA_FILES), ids=TEST_DATA_FILES, )
<commit_before>"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in files: with open(file_) as source: yield source.read() def pytest_generate_tests(metafunc): # pylint: disable=C0111 if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames: metafunc.parametrize( DATA_FILES_FIXTURE_NAME, _load_files_contents(*TEST_DATA_FILES), ids=TEST_DATA_FILES, ) <commit_msg>Add docstring explaining the parametrization of data files<commit_after>
"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in files: with open(file_) as source: yield source.read() def pytest_generate_tests(metafunc): """All tests that take a fixture named ``data_file`` will be parameterized with all the testing data files. This means, the test can be made to work with a single test file as an input, but instead it will run once per every file present in the directory ``TEST_DATA_FILES_LOCATION``. """ if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames: metafunc.parametrize( DATA_FILES_FIXTURE_NAME, _load_files_contents(*TEST_DATA_FILES), ids=TEST_DATA_FILES, )
"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in files: with open(file_) as source: yield source.read() def pytest_generate_tests(metafunc): # pylint: disable=C0111 if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames: metafunc.parametrize( DATA_FILES_FIXTURE_NAME, _load_files_contents(*TEST_DATA_FILES), ids=TEST_DATA_FILES, ) Add docstring explaining the parametrization of data files"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in files: with open(file_) as source: yield source.read() def pytest_generate_tests(metafunc): """All tests that take a fixture named ``data_file`` will be parameterized with all the testing data files. This means, the test can be made to work with a single test file as an input, but instead it will run once per every file present in the directory ``TEST_DATA_FILES_LOCATION``. """ if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames: metafunc.parametrize( DATA_FILES_FIXTURE_NAME, _load_files_contents(*TEST_DATA_FILES), ids=TEST_DATA_FILES, )
<commit_before>"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in files: with open(file_) as source: yield source.read() def pytest_generate_tests(metafunc): # pylint: disable=C0111 if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames: metafunc.parametrize( DATA_FILES_FIXTURE_NAME, _load_files_contents(*TEST_DATA_FILES), ids=TEST_DATA_FILES, ) <commit_msg>Add docstring explaining the parametrization of data files<commit_after>"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in files: with open(file_) as source: yield source.read() def pytest_generate_tests(metafunc): """All tests that take a fixture named ``data_file`` will be parameterized with all the testing data files. This means, the test can be made to work with a single test file as an input, but instead it will run once per every file present in the directory ``TEST_DATA_FILES_LOCATION``. """ if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames: metafunc.parametrize( DATA_FILES_FIXTURE_NAME, _load_files_contents(*TEST_DATA_FILES), ids=TEST_DATA_FILES, )
4165ca1eb5ea43c198c86c4dcf2cfbfe4a6b1c6c
run_tests.py
run_tests.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: $ ./run_tests.py -s -v normalize.test_foo """ import os import sys try: import nose except ImportError: recommend = ( "pip install nose" if "VIRTUAL_ENV" in os.environ else "sudo easy_install nose" ) sys.stderr.write( "Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n" .format(cmd=recommend) ) sys.exit(1) nose.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: $ ./run_tests.py -s -v normalize.test_foo """ import os import sys try: import nose except ImportError: recommend = ( "pip install nose unittest2 -r requirements.txt" if "VIRTUAL_ENV" in os.environ else "sudo easy_install nose unittest2 richenum" ) sys.stderr.write( "Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n" .format(cmd=recommend) ) sys.exit(1) args = [] if "distutils" in sys.modules else sys.argv[1:] nose.main(argv=['nosetests'] + args)
Make sure tests run on 'setup.py test'
Make sure tests run on 'setup.py test' Nose was parsing the argv passed to setup.py (oh, global variables). Assume that if 'distutils' are loaded then this is the case; and pass through argv if it isn't. Also, update the suggested commands for the extra requirements.
Python
mit
tomo-otsuka/normalize,hearsaycorp/normalize,samv/normalize
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: $ ./run_tests.py -s -v normalize.test_foo """ import os import sys try: import nose except ImportError: recommend = ( "pip install nose" if "VIRTUAL_ENV" in os.environ else "sudo easy_install nose" ) sys.stderr.write( "Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n" .format(cmd=recommend) ) sys.exit(1) nose.main() Make sure tests run on 'setup.py test' Nose was parsing the argv passed to setup.py (oh, global variables). Assume that if 'distutils' are loaded then this is the case; and pass through argv if it isn't. Also, update the suggested commands for the extra requirements.
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: $ ./run_tests.py -s -v normalize.test_foo """ import os import sys try: import nose except ImportError: recommend = ( "pip install nose unittest2 -r requirements.txt" if "VIRTUAL_ENV" in os.environ else "sudo easy_install nose unittest2 richenum" ) sys.stderr.write( "Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n" .format(cmd=recommend) ) sys.exit(1) args = [] if "distutils" in sys.modules else sys.argv[1:] nose.main(argv=['nosetests'] + args)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: $ ./run_tests.py -s -v normalize.test_foo """ import os import sys try: import nose except ImportError: recommend = ( "pip install nose" if "VIRTUAL_ENV" in os.environ else "sudo easy_install nose" ) sys.stderr.write( "Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n" .format(cmd=recommend) ) sys.exit(1) nose.main() <commit_msg>Make sure tests run on 'setup.py test' Nose was parsing the argv passed to setup.py (oh, global variables). Assume that if 'distutils' are loaded then this is the case; and pass through argv if it isn't. Also, update the suggested commands for the extra requirements.<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: $ ./run_tests.py -s -v normalize.test_foo """ import os import sys try: import nose except ImportError: recommend = ( "pip install nose unittest2 -r requirements.txt" if "VIRTUAL_ENV" in os.environ else "sudo easy_install nose unittest2 richenum" ) sys.stderr.write( "Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n" .format(cmd=recommend) ) sys.exit(1) args = [] if "distutils" in sys.modules else sys.argv[1:] nose.main(argv=['nosetests'] + args)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: $ ./run_tests.py -s -v normalize.test_foo """ import os import sys try: import nose except ImportError: recommend = ( "pip install nose" if "VIRTUAL_ENV" in os.environ else "sudo easy_install nose" ) sys.stderr.write( "Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n" .format(cmd=recommend) ) sys.exit(1) nose.main() Make sure tests run on 'setup.py test' Nose was parsing the argv passed to setup.py (oh, global variables). Assume that if 'distutils' are loaded then this is the case; and pass through argv if it isn't. Also, update the suggested commands for the extra requirements.#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: $ ./run_tests.py -s -v normalize.test_foo """ import os import sys try: import nose except ImportError: recommend = ( "pip install nose unittest2 -r requirements.txt" if "VIRTUAL_ENV" in os.environ else "sudo easy_install nose unittest2 richenum" ) sys.stderr.write( "Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n" .format(cmd=recommend) ) sys.exit(1) args = [] if "distutils" in sys.modules else sys.argv[1:] nose.main(argv=['nosetests'] + args)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: $ ./run_tests.py -s -v normalize.test_foo """ import os import sys try: import nose except ImportError: recommend = ( "pip install nose" if "VIRTUAL_ENV" in os.environ else "sudo easy_install nose" ) sys.stderr.write( "Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n" .format(cmd=recommend) ) sys.exit(1) nose.main() <commit_msg>Make sure tests run on 'setup.py test' Nose was parsing the argv passed to setup.py (oh, global variables). Assume that if 'distutils' are loaded then this is the case; and pass through argv if it isn't. Also, update the suggested commands for the extra requirements.<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: $ ./run_tests.py -s -v normalize.test_foo """ import os import sys try: import nose except ImportError: recommend = ( "pip install nose unittest2 -r requirements.txt" if "VIRTUAL_ENV" in os.environ else "sudo easy_install nose unittest2 richenum" ) sys.stderr.write( "Running the tests requires Nose. Try:\n\n{cmd}\n\nAborting.\n" .format(cmd=recommend) ) sys.exit(1) args = [] if "distutils" in sys.modules else sys.argv[1:] nose.main(argv=['nosetests'] + args)
0c21d60108d38f43d22aa03c882a62c93754d5da
tests/test_cli.py
tests/test_cli.py
from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path),)) == 0 assert file_path.read_text() == FORMATTED_MARKDOWN def test_invalid_file(): assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1 def test_check(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(FORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 0 def test_check__fail(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 1
from io import StringIO import sys from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path),)) == 0 assert file_path.read_text() == FORMATTED_MARKDOWN def test_invalid_file(): assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1 def test_check(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(FORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 0 def test_check__fail(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 1 def test_dash_stdin(capsys, monkeypatch): monkeypatch.setattr(sys, "stdin", StringIO(UNFORMATTED_MARKDOWN)) run(("-",)) captured = capsys.readouterr() assert captured.out == FORMATTED_MARKDOWN
Test read from stdin and write to stdout
Test read from stdin and write to stdout
Python
mit
executablebooks/mdformat
from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path),)) == 0 assert file_path.read_text() == FORMATTED_MARKDOWN def test_invalid_file(): assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1 def test_check(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(FORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 0 def test_check__fail(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 1 Test read from stdin and write to stdout
from io import StringIO import sys from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path),)) == 0 assert file_path.read_text() == FORMATTED_MARKDOWN def test_invalid_file(): assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1 def test_check(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(FORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 0 def test_check__fail(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 1 def test_dash_stdin(capsys, monkeypatch): monkeypatch.setattr(sys, "stdin", StringIO(UNFORMATTED_MARKDOWN)) run(("-",)) captured = capsys.readouterr() assert captured.out == FORMATTED_MARKDOWN
<commit_before>from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path),)) == 0 assert file_path.read_text() == FORMATTED_MARKDOWN def test_invalid_file(): assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1 def test_check(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(FORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 0 def test_check__fail(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 1 <commit_msg>Test read from stdin and write to stdout<commit_after>
from io import StringIO import sys from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path),)) == 0 assert file_path.read_text() == FORMATTED_MARKDOWN def test_invalid_file(): assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1 def test_check(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(FORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 0 def test_check__fail(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 1 def test_dash_stdin(capsys, monkeypatch): monkeypatch.setattr(sys, "stdin", StringIO(UNFORMATTED_MARKDOWN)) run(("-",)) captured = capsys.readouterr() assert captured.out == FORMATTED_MARKDOWN
from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path),)) == 0 assert file_path.read_text() == FORMATTED_MARKDOWN def test_invalid_file(): assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1 def test_check(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(FORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 0 def test_check__fail(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 1 Test read from stdin and write to stdoutfrom io import StringIO import sys from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path),)) == 0 assert file_path.read_text() == FORMATTED_MARKDOWN def test_invalid_file(): assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1 def test_check(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(FORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 0 def test_check__fail(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 1 def test_dash_stdin(capsys, monkeypatch): monkeypatch.setattr(sys, "stdin", StringIO(UNFORMATTED_MARKDOWN)) run(("-",)) captured = capsys.readouterr() assert captured.out == FORMATTED_MARKDOWN
<commit_before>from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path),)) == 0 assert file_path.read_text() == FORMATTED_MARKDOWN def test_invalid_file(): assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1 def test_check(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(FORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 0 def test_check__fail(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 1 <commit_msg>Test read from stdin and write to stdout<commit_after>from io import StringIO import sys from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path),)) == 0 assert file_path.read_text() == FORMATTED_MARKDOWN def test_invalid_file(): assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1 def test_check(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(FORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 0 def test_check__fail(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path), "--check")) == 1 def test_dash_stdin(capsys, monkeypatch): monkeypatch.setattr(sys, "stdin", StringIO(UNFORMATTED_MARKDOWN)) run(("-",)) captured = capsys.readouterr() assert captured.out == FORMATTED_MARKDOWN
bb7e01988a50131c4f9649d9142b1770cb9263e5
java/kotlin-extractor/kotlin_plugin_versions.py
java/kotlin-extractor/kotlin_plugin_versions.py
import re import subprocess many_versions = [ '1.4.32', '1.5.31', '1.6.0-RC2' ] def get_single_version(): versionOutput = subprocess.run(['kotlinc', '-version'], capture_output=True, text=True) m = re.match(r'.* kotlinc-jvm ([0-9]+\.[0-9]+\.)[0-9]+ .*', versionOutput.stderr) if m is None: raise Exception('Cannot detect version of kotlinc') prefix = m.group(1) for version in many_versions: if version.startswith(prefix): return version raise Exception('No suitable kotlinc version found for ' + prefix)
import re import subprocess many_versions = [ '1.4.32', '1.5.31', '1.6.10' ] def get_single_version(): versionOutput = subprocess.run(['kotlinc', '-version'], capture_output=True, text=True) m = re.match(r'.* kotlinc-jvm ([0-9]+\.[0-9]+\.)[0-9]+ .*', versionOutput.stderr) if m is None: raise Exception('Cannot detect version of kotlinc') prefix = m.group(1) for version in many_versions: if version.startswith(prefix): return version raise Exception('No suitable kotlinc version found for ' + prefix)
Change kotlin dependency version from 1.6.0-RC2 to 1.6.10
Change kotlin dependency version from 1.6.0-RC2 to 1.6.10
Python
mit
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
import re import subprocess many_versions = [ '1.4.32', '1.5.31', '1.6.0-RC2' ] def get_single_version(): versionOutput = subprocess.run(['kotlinc', '-version'], capture_output=True, text=True) m = re.match(r'.* kotlinc-jvm ([0-9]+\.[0-9]+\.)[0-9]+ .*', versionOutput.stderr) if m is None: raise Exception('Cannot detect version of kotlinc') prefix = m.group(1) for version in many_versions: if version.startswith(prefix): return version raise Exception('No suitable kotlinc version found for ' + prefix) Change kotlin dependency version from 1.6.0-RC2 to 1.6.10
import re import subprocess many_versions = [ '1.4.32', '1.5.31', '1.6.10' ] def get_single_version(): versionOutput = subprocess.run(['kotlinc', '-version'], capture_output=True, text=True) m = re.match(r'.* kotlinc-jvm ([0-9]+\.[0-9]+\.)[0-9]+ .*', versionOutput.stderr) if m is None: raise Exception('Cannot detect version of kotlinc') prefix = m.group(1) for version in many_versions: if version.startswith(prefix): return version raise Exception('No suitable kotlinc version found for ' + prefix)
<commit_before>import re import subprocess many_versions = [ '1.4.32', '1.5.31', '1.6.0-RC2' ] def get_single_version(): versionOutput = subprocess.run(['kotlinc', '-version'], capture_output=True, text=True) m = re.match(r'.* kotlinc-jvm ([0-9]+\.[0-9]+\.)[0-9]+ .*', versionOutput.stderr) if m is None: raise Exception('Cannot detect version of kotlinc') prefix = m.group(1) for version in many_versions: if version.startswith(prefix): return version raise Exception('No suitable kotlinc version found for ' + prefix) <commit_msg>Change kotlin dependency version from 1.6.0-RC2 to 1.6.10<commit_after>
import re import subprocess many_versions = [ '1.4.32', '1.5.31', '1.6.10' ] def get_single_version(): versionOutput = subprocess.run(['kotlinc', '-version'], capture_output=True, text=True) m = re.match(r'.* kotlinc-jvm ([0-9]+\.[0-9]+\.)[0-9]+ .*', versionOutput.stderr) if m is None: raise Exception('Cannot detect version of kotlinc') prefix = m.group(1) for version in many_versions: if version.startswith(prefix): return version raise Exception('No suitable kotlinc version found for ' + prefix)
import re import subprocess many_versions = [ '1.4.32', '1.5.31', '1.6.0-RC2' ] def get_single_version(): versionOutput = subprocess.run(['kotlinc', '-version'], capture_output=True, text=True) m = re.match(r'.* kotlinc-jvm ([0-9]+\.[0-9]+\.)[0-9]+ .*', versionOutput.stderr) if m is None: raise Exception('Cannot detect version of kotlinc') prefix = m.group(1) for version in many_versions: if version.startswith(prefix): return version raise Exception('No suitable kotlinc version found for ' + prefix) Change kotlin dependency version from 1.6.0-RC2 to 1.6.10import re import subprocess many_versions = [ '1.4.32', '1.5.31', '1.6.10' ] def get_single_version(): versionOutput = subprocess.run(['kotlinc', '-version'], capture_output=True, text=True) m = re.match(r'.* kotlinc-jvm ([0-9]+\.[0-9]+\.)[0-9]+ .*', versionOutput.stderr) if m is None: raise Exception('Cannot detect version of kotlinc') prefix = m.group(1) for version in many_versions: if version.startswith(prefix): return version raise Exception('No suitable kotlinc version found for ' + prefix)
<commit_before>import re import subprocess many_versions = [ '1.4.32', '1.5.31', '1.6.0-RC2' ] def get_single_version(): versionOutput = subprocess.run(['kotlinc', '-version'], capture_output=True, text=True) m = re.match(r'.* kotlinc-jvm ([0-9]+\.[0-9]+\.)[0-9]+ .*', versionOutput.stderr) if m is None: raise Exception('Cannot detect version of kotlinc') prefix = m.group(1) for version in many_versions: if version.startswith(prefix): return version raise Exception('No suitable kotlinc version found for ' + prefix) <commit_msg>Change kotlin dependency version from 1.6.0-RC2 to 1.6.10<commit_after>import re import subprocess many_versions = [ '1.4.32', '1.5.31', '1.6.10' ] def get_single_version(): versionOutput = subprocess.run(['kotlinc', '-version'], capture_output=True, text=True) m = re.match(r'.* kotlinc-jvm ([0-9]+\.[0-9]+\.)[0-9]+ .*', versionOutput.stderr) if m is None: raise Exception('Cannot detect version of kotlinc') prefix = m.group(1) for version in many_versions: if version.startswith(prefix): return version raise Exception('No suitable kotlinc version found for ' + prefix)
30ea5b30746f12feb7b5915bce180ff4934ae204
problem67.py
problem67.py
import math def blad(): ins = open( "triangles_18.txt", "r" ) arr = [] idx = 0 for line in ins: try: l = [int(x) for x in line.split()] if ( l[idx] < l[idx+1] ): idx += 1 except IndexError: pass arr.append(l[idx]) ins.close() print arr print sum(arr) #6580 # 3 # 7 4 # 2 4 6 # 8 5 9 3 def all(n): arr = [] for s in format(n, '100b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] #print idx try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**99 for i in xrange(n): print i, n sums.append(all(i)) print max(sums)
# Project Euler # problems 18 and 67 def generic(): data = [] ins = open( "triangles.txt", "r" ) for i,line in enumerate(ins): data.insert(0, [int(x) for x in line.split()] ) ins.close() for n,d in enumerate(data): if n == 0: pass else: data[n] = [ max(i+data[n-1][nn], i+data[n-1][nn+1]) for nn,i in enumerate(d) ] return data[n][0] def perm(n): arr = [] for s in format(n, '015b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**14 for i in xrange(n): sums.append(perm(i)) print "Problem 18:" ,max(sums) print "Problem 67:", generic()
Add proper solution for projects 18 and 67
Add proper solution for projects 18 and 67
Python
mit
jakubczaplicki/projecteuler,jakubczaplicki/projecteuler
import math def blad(): ins = open( "triangles_18.txt", "r" ) arr = [] idx = 0 for line in ins: try: l = [int(x) for x in line.split()] if ( l[idx] < l[idx+1] ): idx += 1 except IndexError: pass arr.append(l[idx]) ins.close() print arr print sum(arr) #6580 # 3 # 7 4 # 2 4 6 # 8 5 9 3 def all(n): arr = [] for s in format(n, '100b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] #print idx try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**99 for i in xrange(n): print i, n sums.append(all(i)) print max(sums)Add proper solution for projects 18 and 67
# Project Euler # problems 18 and 67 def generic(): data = [] ins = open( "triangles.txt", "r" ) for i,line in enumerate(ins): data.insert(0, [int(x) for x in line.split()] ) ins.close() for n,d in enumerate(data): if n == 0: pass else: data[n] = [ max(i+data[n-1][nn], i+data[n-1][nn+1]) for nn,i in enumerate(d) ] return data[n][0] def perm(n): arr = [] for s in format(n, '015b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**14 for i in xrange(n): sums.append(perm(i)) print "Problem 18:" ,max(sums) print "Problem 67:", generic()
<commit_before> import math def blad(): ins = open( "triangles_18.txt", "r" ) arr = [] idx = 0 for line in ins: try: l = [int(x) for x in line.split()] if ( l[idx] < l[idx+1] ): idx += 1 except IndexError: pass arr.append(l[idx]) ins.close() print arr print sum(arr) #6580 # 3 # 7 4 # 2 4 6 # 8 5 9 3 def all(n): arr = [] for s in format(n, '100b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] #print idx try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**99 for i in xrange(n): print i, n sums.append(all(i)) print max(sums)<commit_msg>Add proper solution for projects 18 and 67<commit_after>
# Project Euler # problems 18 and 67 def generic(): data = [] ins = open( "triangles.txt", "r" ) for i,line in enumerate(ins): data.insert(0, [int(x) for x in line.split()] ) ins.close() for n,d in enumerate(data): if n == 0: pass else: data[n] = [ max(i+data[n-1][nn], i+data[n-1][nn+1]) for nn,i in enumerate(d) ] return data[n][0] def perm(n): arr = [] for s in format(n, '015b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**14 for i in xrange(n): sums.append(perm(i)) print "Problem 18:" ,max(sums) print "Problem 67:", generic()
import math def blad(): ins = open( "triangles_18.txt", "r" ) arr = [] idx = 0 for line in ins: try: l = [int(x) for x in line.split()] if ( l[idx] < l[idx+1] ): idx += 1 except IndexError: pass arr.append(l[idx]) ins.close() print arr print sum(arr) #6580 # 3 # 7 4 # 2 4 6 # 8 5 9 3 def all(n): arr = [] for s in format(n, '100b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] #print idx try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**99 for i in xrange(n): print i, n sums.append(all(i)) print max(sums)Add proper solution for projects 18 and 67# Project Euler # problems 18 and 67 def generic(): data = [] ins = open( "triangles.txt", "r" ) for i,line in enumerate(ins): data.insert(0, [int(x) for x in line.split()] ) ins.close() for n,d in enumerate(data): if n == 0: pass else: data[n] = [ max(i+data[n-1][nn], i+data[n-1][nn+1]) for nn,i in enumerate(d) ] return data[n][0] def perm(n): arr = [] for s in format(n, '015b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**14 for i in xrange(n): sums.append(perm(i)) print "Problem 18:" ,max(sums) print "Problem 67:", generic()
<commit_before> import math def blad(): ins = open( "triangles_18.txt", "r" ) arr = [] idx = 0 for line in ins: try: l = [int(x) for x in line.split()] if ( l[idx] < l[idx+1] ): idx += 1 except IndexError: pass arr.append(l[idx]) ins.close() print arr print sum(arr) #6580 # 3 # 7 4 # 2 4 6 # 8 5 9 3 def all(n): arr = [] for s in format(n, '100b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] #print idx try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**99 for i in xrange(n): print i, n sums.append(all(i)) print max(sums)<commit_msg>Add proper solution for projects 18 and 67<commit_after># Project Euler # problems 18 and 67 def generic(): data = [] ins = open( "triangles.txt", "r" ) for i,line in enumerate(ins): data.insert(0, [int(x) for x in line.split()] ) ins.close() for n,d in enumerate(data): if n == 0: pass else: data[n] = [ max(i+data[n-1][nn], i+data[n-1][nn+1]) for nn,i in enumerate(d) ] return data[n][0] def perm(n): arr = [] for s in format(n, '015b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**14 for i in xrange(n): sums.append(perm(i)) print "Problem 18:" ,max(sums) print "Problem 67:", generic()
64745f9dc3e31d55c5b73457b719484384ba0d76
runserver.py
runserver.py
from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0')
from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0', port=8000)
Set default port to 8000
Set default port to 8000
Python
mit
nvlbg/gepify,nvlbg/gepify
from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0') Set default port to 8000
from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0', port=8000)
<commit_before>from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0') <commit_msg>Set default port to 8000<commit_after>
from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0', port=8000)
from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0') Set default port to 8000from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0', port=8000)
<commit_before>from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0') <commit_msg>Set default port to 8000<commit_after>from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0', port=8000)
20dbd80d0262869f3378597d7152dab7a6104de8
routes/__init__.py
routes/__init__.py
import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to
import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to __all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
Tweak for exporting the symbols
[svn] Tweak for exporting the symbols --HG-- branch : trunk
Python
mit
alex/routes,bbangert/routes,mikepk/routes,webknjaz/routes,mikepk/pybald-routes
import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to [svn] Tweak for exporting the symbols --HG-- branch : trunk
import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to __all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
<commit_before>import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to <commit_msg>[svn] Tweak for exporting the symbols --HG-- branch : trunk<commit_after>
import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to __all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to [svn] Tweak for exporting the symbols --HG-- branch : trunkimport threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to __all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
<commit_before>import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to <commit_msg>[svn] Tweak for exporting the symbols --HG-- branch : trunk<commit_after>import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to __all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
61ec5bdf739b0c7165c8aed85378e0b88c51e920
twango/manager.py
twango/manager.py
from django.db import models from twango.query import TwistedQuerySet class TwistedManager(models.Manager): queryset_class = TwistedQuerySet def get_query_set(self): return self.queryset_class(self.model, using=self._db)
from django.db import models from twango.query import TwistedQuerySet class TwistedManager(models.Manager): queryset_class = TwistedQuerySet def get_queryset(self): return self.queryset_class(self.model, using=self._db)
Fix for deprecation warning in django 1.7rc2
Fix for deprecation warning in django 1.7rc2
Python
mit
Bonus05/djangotworm,gdoermann/twango
from django.db import models from twango.query import TwistedQuerySet class TwistedManager(models.Manager): queryset_class = TwistedQuerySet def get_query_set(self): return self.queryset_class(self.model, using=self._db) Fix for deprecation warning in django 1.7rc2
from django.db import models from twango.query import TwistedQuerySet class TwistedManager(models.Manager): queryset_class = TwistedQuerySet def get_queryset(self): return self.queryset_class(self.model, using=self._db)
<commit_before>from django.db import models from twango.query import TwistedQuerySet class TwistedManager(models.Manager): queryset_class = TwistedQuerySet def get_query_set(self): return self.queryset_class(self.model, using=self._db) <commit_msg>Fix for deprecation warning in django 1.7rc2<commit_after>
from django.db import models from twango.query import TwistedQuerySet class TwistedManager(models.Manager): queryset_class = TwistedQuerySet def get_queryset(self): return self.queryset_class(self.model, using=self._db)
from django.db import models from twango.query import TwistedQuerySet class TwistedManager(models.Manager): queryset_class = TwistedQuerySet def get_query_set(self): return self.queryset_class(self.model, using=self._db) Fix for deprecation warning in django 1.7rc2from django.db import models from twango.query import TwistedQuerySet class TwistedManager(models.Manager): queryset_class = TwistedQuerySet def get_queryset(self): return self.queryset_class(self.model, using=self._db)
<commit_before>from django.db import models from twango.query import TwistedQuerySet class TwistedManager(models.Manager): queryset_class = TwistedQuerySet def get_query_set(self): return self.queryset_class(self.model, using=self._db) <commit_msg>Fix for deprecation warning in django 1.7rc2<commit_after>from django.db import models from twango.query import TwistedQuerySet class TwistedManager(models.Manager): queryset_class = TwistedQuerySet def get_queryset(self): return self.queryset_class(self.model, using=self._db)
1bb7ff80906058370839eb22ff2ebc67f11ad09e
django_auth_adfs/rest_framework.py
django_auth_adfs/rest_framework.py
import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthentication): """ ADFS access Token authentication """ www_authenticate_realm = 'api' def authenticate(self, request): """ Returns a `User` if a correct access token has been supplied in the Authorization header. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: msg = 'Invalid authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid authorization header. Access token should not contain spaces.' raise exceptions.AuthenticationFailed(msg) # Authenticate the user # The AdfsBackend authentication backend will notice the "access_token" parameter # and skip the request for an access token using the authorization code user = authenticate(access_token=auth[1]) if user is None: raise exceptions.AuthenticationFailed('Invalid access token.') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return user, auth[1] def authenticate_header(self, request): return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm
from __future__ import absolute_import import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthentication): """ ADFS access Token authentication """ www_authenticate_realm = 'api' def authenticate(self, request): """ Returns a `User` if a correct access token has been supplied in the Authorization header. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: msg = 'Invalid authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid authorization header. Access token should not contain spaces.' raise exceptions.AuthenticationFailed(msg) # Authenticate the user # The AdfsBackend authentication backend will notice the "access_token" parameter # and skip the request for an access token using the authorization code user = authenticate(access_token=auth[1]) if user is None: raise exceptions.AuthenticationFailed('Invalid access token.') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return user, auth[1] def authenticate_header(self, request): return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm
Make sure we don't have a import namespace clash with DRF
Make sure we don't have a import namespace clash with DRF For python 2.7 you need to add from __future__ import absolute_import
Python
bsd-2-clause
jobec/django-auth-adfs,jobec/django-auth-adfs
import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthentication): """ ADFS access Token authentication """ www_authenticate_realm = 'api' def authenticate(self, request): """ Returns a `User` if a correct access token has been supplied in the Authorization header. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: msg = 'Invalid authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid authorization header. Access token should not contain spaces.' raise exceptions.AuthenticationFailed(msg) # Authenticate the user # The AdfsBackend authentication backend will notice the "access_token" parameter # and skip the request for an access token using the authorization code user = authenticate(access_token=auth[1]) if user is None: raise exceptions.AuthenticationFailed('Invalid access token.') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return user, auth[1] def authenticate_header(self, request): return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm Make sure we don't have a import namespace clash with DRF For python 2.7 you need to add from __future__ import absolute_import
from __future__ import absolute_import import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthentication): """ ADFS access Token authentication """ www_authenticate_realm = 'api' def authenticate(self, request): """ Returns a `User` if a correct access token has been supplied in the Authorization header. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: msg = 'Invalid authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid authorization header. Access token should not contain spaces.' raise exceptions.AuthenticationFailed(msg) # Authenticate the user # The AdfsBackend authentication backend will notice the "access_token" parameter # and skip the request for an access token using the authorization code user = authenticate(access_token=auth[1]) if user is None: raise exceptions.AuthenticationFailed('Invalid access token.') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return user, auth[1] def authenticate_header(self, request): return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm
<commit_before>import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthentication): """ ADFS access Token authentication """ www_authenticate_realm = 'api' def authenticate(self, request): """ Returns a `User` if a correct access token has been supplied in the Authorization header. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: msg = 'Invalid authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid authorization header. Access token should not contain spaces.' raise exceptions.AuthenticationFailed(msg) # Authenticate the user # The AdfsBackend authentication backend will notice the "access_token" parameter # and skip the request for an access token using the authorization code user = authenticate(access_token=auth[1]) if user is None: raise exceptions.AuthenticationFailed('Invalid access token.') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return user, auth[1] def authenticate_header(self, request): return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm <commit_msg>Make sure we don't have a import namespace clash with DRF For python 2.7 you need to add from __future__ import absolute_import<commit_after>
from __future__ import absolute_import import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthentication): """ ADFS access Token authentication """ www_authenticate_realm = 'api' def authenticate(self, request): """ Returns a `User` if a correct access token has been supplied in the Authorization header. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: msg = 'Invalid authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid authorization header. Access token should not contain spaces.' raise exceptions.AuthenticationFailed(msg) # Authenticate the user # The AdfsBackend authentication backend will notice the "access_token" parameter # and skip the request for an access token using the authorization code user = authenticate(access_token=auth[1]) if user is None: raise exceptions.AuthenticationFailed('Invalid access token.') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return user, auth[1] def authenticate_header(self, request): return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm
import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthentication): """ ADFS access Token authentication """ www_authenticate_realm = 'api' def authenticate(self, request): """ Returns a `User` if a correct access token has been supplied in the Authorization header. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: msg = 'Invalid authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid authorization header. Access token should not contain spaces.' raise exceptions.AuthenticationFailed(msg) # Authenticate the user # The AdfsBackend authentication backend will notice the "access_token" parameter # and skip the request for an access token using the authorization code user = authenticate(access_token=auth[1]) if user is None: raise exceptions.AuthenticationFailed('Invalid access token.') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return user, auth[1] def authenticate_header(self, request): return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm Make sure we don't have a import namespace clash with DRF For python 2.7 you need to add from __future__ import absolute_importfrom __future__ import absolute_import import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthentication): """ ADFS access Token authentication """ www_authenticate_realm = 'api' def authenticate(self, request): """ Returns a `User` if a correct access token has been supplied in the Authorization header. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: msg = 'Invalid authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid authorization header. Access token should not contain spaces.' raise exceptions.AuthenticationFailed(msg) # Authenticate the user # The AdfsBackend authentication backend will notice the "access_token" parameter # and skip the request for an access token using the authorization code user = authenticate(access_token=auth[1]) if user is None: raise exceptions.AuthenticationFailed('Invalid access token.') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return user, auth[1] def authenticate_header(self, request): return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm
<commit_before>import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthentication): """ ADFS access Token authentication """ www_authenticate_realm = 'api' def authenticate(self, request): """ Returns a `User` if a correct access token has been supplied in the Authorization header. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: msg = 'Invalid authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid authorization header. Access token should not contain spaces.' raise exceptions.AuthenticationFailed(msg) # Authenticate the user # The AdfsBackend authentication backend will notice the "access_token" parameter # and skip the request for an access token using the authorization code user = authenticate(access_token=auth[1]) if user is None: raise exceptions.AuthenticationFailed('Invalid access token.') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return user, auth[1] def authenticate_header(self, request): return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm <commit_msg>Make sure we don't have a import namespace clash with DRF For python 2.7 you need to add from __future__ import absolute_import<commit_after>from __future__ import absolute_import import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthentication): """ ADFS access Token authentication """ www_authenticate_realm = 'api' def authenticate(self, request): """ Returns a `User` if a correct access token has been supplied in the Authorization header. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'bearer': return None if len(auth) == 1: msg = 'Invalid authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid authorization header. Access token should not contain spaces.' raise exceptions.AuthenticationFailed(msg) # Authenticate the user # The AdfsBackend authentication backend will notice the "access_token" parameter # and skip the request for an access token using the authorization code user = authenticate(access_token=auth[1]) if user is None: raise exceptions.AuthenticationFailed('Invalid access token.') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return user, auth[1] def authenticate_header(self, request): return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm
a67e45347f0119c4e1a3fb55b401a9acce939c7a
script/lib/util.py
script/lib/util.py
#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' return output_dir def get_configuration(target_arch): config = 'Release' if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']: config += '_x64' return config
#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' elif target_arch == 'arm': output_dir += '_arm' return output_dir def get_configuration(target_arch): config = 'Release' if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']: config += '_x64' return config
Fix output dir for arm target
Fix output dir for arm target
Python
mit
atom/libchromiumcontent,eric-seekas/libchromiumcontent,paulcbetts/libchromiumcontent,adamjgray/libchromiumcontent,synaptek/libchromiumcontent,atom/libchromiumcontent,electron/libchromiumcontent,bbondy/libchromiumcontent,hokein/libchromiumcontent,adamjgray/libchromiumcontent,synaptek/libchromiumcontent,hokein/libchromiumcontent,zhanggyb/libchromiumcontent,electron/libchromiumcontent,brave/libchromiumcontent,bbondy/libchromiumcontent,zhanggyb/libchromiumcontent,paulcbetts/libchromiumcontent,eric-seekas/libchromiumcontent,brave/libchromiumcontent
#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' return output_dir def get_configuration(target_arch): config = 'Release' if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']: config += '_x64' return config Fix output dir for arm target
#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' elif target_arch == 'arm': output_dir += '_arm' return output_dir def get_configuration(target_arch): config = 'Release' if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']: config += '_x64' return config
<commit_before>#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' return output_dir def get_configuration(target_arch): config = 'Release' if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']: config += '_x64' return config <commit_msg>Fix output dir for arm target<commit_after>
#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' elif target_arch == 'arm': output_dir += '_arm' return output_dir def get_configuration(target_arch): config = 'Release' if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']: config += '_x64' return config
#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' return output_dir def get_configuration(target_arch): config = 'Release' if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']: config += '_x64' return config Fix output dir for arm target#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' elif target_arch == 'arm': output_dir += '_arm' return output_dir def get_configuration(target_arch): config = 'Release' if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']: config += '_x64' return config
<commit_before>#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' return output_dir def get_configuration(target_arch): config = 'Release' if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']: config += '_x64' return config <commit_msg>Fix output dir for arm target<commit_after>#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' elif target_arch == 'arm': output_dir += '_arm' return output_dir def get_configuration(target_arch): config = 'Release' if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']: config += '_x64' return config
d27723ed3c3006a5bd9567e992c6d37a9ca0d159
run_tests.py
run_tests.py
#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description of # these options. try: import enaml.qt del enaml except ImportError: pass import nose from dataportal.testing.noseclasses import KnownFailure plugins = [KnownFailure] env = {"NOSE_WITH_COVERAGE": 1, 'NOSE_COVER_PACKAGE': ['dataportal', 'replay'], 'NOSE_COVER_HTML': 1} # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin with # a list. from nose.plugins import multiprocess multiprocess._instantiate_plugins = plugins def run(): nose.main(addplugins=[x() for x in plugins], env=env) if __name__ == '__main__': run()
#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description of # these options. try: import enaml.qt del enaml except ImportError: pass import nose from dataportal.testing.noseclasses import KnownFailure plugins = [KnownFailure] env = {"NOSE_WITH_COVERAGE": 1, 'NOSE_COVER_PACKAGE': ['dataportal'], 'NOSE_COVER_HTML': 1} # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin with # a list. from nose.plugins import multiprocess multiprocess._instantiate_plugins = plugins def run(): nose.main(addplugins=[x() for x in plugins], env=env) if __name__ == '__main__': run()
Remove coverage on replay; development is suspended.
MNT: Remove coverage on replay; development is suspended.
Python
bsd-3-clause
tacaswell/dataportal,danielballan/datamuxer,NSLS-II/dataportal,danielballan/dataportal,ericdill/databroker,NSLS-II/datamuxer,NSLS-II/dataportal,tacaswell/dataportal,ericdill/databroker,ericdill/datamuxer,danielballan/dataportal,danielballan/datamuxer,ericdill/datamuxer
#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description of # these options. try: import enaml.qt del enaml except ImportError: pass import nose from dataportal.testing.noseclasses import KnownFailure plugins = [KnownFailure] env = {"NOSE_WITH_COVERAGE": 1, 'NOSE_COVER_PACKAGE': ['dataportal', 'replay'], 'NOSE_COVER_HTML': 1} # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin with # a list. from nose.plugins import multiprocess multiprocess._instantiate_plugins = plugins def run(): nose.main(addplugins=[x() for x in plugins], env=env) if __name__ == '__main__': run() MNT: Remove coverage on replay; development is suspended.
#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description of # these options. try: import enaml.qt del enaml except ImportError: pass import nose from dataportal.testing.noseclasses import KnownFailure plugins = [KnownFailure] env = {"NOSE_WITH_COVERAGE": 1, 'NOSE_COVER_PACKAGE': ['dataportal'], 'NOSE_COVER_HTML': 1} # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin with # a list. from nose.plugins import multiprocess multiprocess._instantiate_plugins = plugins def run(): nose.main(addplugins=[x() for x in plugins], env=env) if __name__ == '__main__': run()
<commit_before>#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description of # these options. try: import enaml.qt del enaml except ImportError: pass import nose from dataportal.testing.noseclasses import KnownFailure plugins = [KnownFailure] env = {"NOSE_WITH_COVERAGE": 1, 'NOSE_COVER_PACKAGE': ['dataportal', 'replay'], 'NOSE_COVER_HTML': 1} # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin with # a list. from nose.plugins import multiprocess multiprocess._instantiate_plugins = plugins def run(): nose.main(addplugins=[x() for x in plugins], env=env) if __name__ == '__main__': run() <commit_msg>MNT: Remove coverage on replay; development is suspended.<commit_after>
#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description of # these options. try: import enaml.qt del enaml except ImportError: pass import nose from dataportal.testing.noseclasses import KnownFailure plugins = [KnownFailure] env = {"NOSE_WITH_COVERAGE": 1, 'NOSE_COVER_PACKAGE': ['dataportal'], 'NOSE_COVER_HTML': 1} # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin with # a list. from nose.plugins import multiprocess multiprocess._instantiate_plugins = plugins def run(): nose.main(addplugins=[x() for x in plugins], env=env) if __name__ == '__main__': run()
#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description of # these options. try: import enaml.qt del enaml except ImportError: pass import nose from dataportal.testing.noseclasses import KnownFailure plugins = [KnownFailure] env = {"NOSE_WITH_COVERAGE": 1, 'NOSE_COVER_PACKAGE': ['dataportal', 'replay'], 'NOSE_COVER_HTML': 1} # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin with # a list. from nose.plugins import multiprocess multiprocess._instantiate_plugins = plugins def run(): nose.main(addplugins=[x() for x in plugins], env=env) if __name__ == '__main__': run() MNT: Remove coverage on replay; development is suspended.#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description of # these options. try: import enaml.qt del enaml except ImportError: pass import nose from dataportal.testing.noseclasses import KnownFailure plugins = [KnownFailure] env = {"NOSE_WITH_COVERAGE": 1, 'NOSE_COVER_PACKAGE': ['dataportal'], 'NOSE_COVER_HTML': 1} # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin with # a list. from nose.plugins import multiprocess multiprocess._instantiate_plugins = plugins def run(): nose.main(addplugins=[x() for x in plugins], env=env) if __name__ == '__main__': run()
<commit_before>#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description of # these options. try: import enaml.qt del enaml except ImportError: pass import nose from dataportal.testing.noseclasses import KnownFailure plugins = [KnownFailure] env = {"NOSE_WITH_COVERAGE": 1, 'NOSE_COVER_PACKAGE': ['dataportal', 'replay'], 'NOSE_COVER_HTML': 1} # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin with # a list. from nose.plugins import multiprocess multiprocess._instantiate_plugins = plugins def run(): nose.main(addplugins=[x() for x in plugins], env=env) if __name__ == '__main__': run() <commit_msg>MNT: Remove coverage on replay; development is suspended.<commit_after>#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description of # these options. try: import enaml.qt del enaml except ImportError: pass import nose from dataportal.testing.noseclasses import KnownFailure plugins = [KnownFailure] env = {"NOSE_WITH_COVERAGE": 1, 'NOSE_COVER_PACKAGE': ['dataportal'], 'NOSE_COVER_HTML': 1} # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin with # a list. from nose.plugins import multiprocess multiprocess._instantiate_plugins = plugins def run(): nose.main(addplugins=[x() for x in plugins], env=env) if __name__ == '__main__': run()
f31fcceede055a7c2955066d1c2086cd8246e4f7
runserver.py
runserver.py
from mmmpaste import app app.run(debug = True)
import os from mmmpaste import app PORT = int(os.environ['PORT']) if 'PORT' in os.environ else 5000 app.run(debug = True, port = PORT)
Allow the port to overridden by and environment variable.
Allow the port to overridden by and environment variable.
Python
bsd-2-clause
ryanc/mmmpaste,ryanc/mmmpaste
from mmmpaste import app app.run(debug = True) Allow the port to overridden by and environment variable.
import os from mmmpaste import app PORT = int(os.environ['PORT']) if 'PORT' in os.environ else 5000 app.run(debug = True, port = PORT)
<commit_before>from mmmpaste import app app.run(debug = True) <commit_msg>Allow the port to overridden by and environment variable.<commit_after>
import os from mmmpaste import app PORT = int(os.environ['PORT']) if 'PORT' in os.environ else 5000 app.run(debug = True, port = PORT)
from mmmpaste import app app.run(debug = True) Allow the port to overridden by and environment variable.import os from mmmpaste import app PORT = int(os.environ['PORT']) if 'PORT' in os.environ else 5000 app.run(debug = True, port = PORT)
<commit_before>from mmmpaste import app app.run(debug = True) <commit_msg>Allow the port to overridden by and environment variable.<commit_after>import os from mmmpaste import app PORT = int(os.environ['PORT']) if 'PORT' in os.environ else 5000 app.run(debug = True, port = PORT)
9bb312c505c2749862372c0ff56ba47e087a9edc
searx/engines/semantic_scholar.py
searx/engines/semantic_scholar.py
# SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "performTitleMatch": True, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results
# SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results
Remove duplicated key from dict in Semantic Scholar
Remove duplicated key from dict in Semantic Scholar
Python
agpl-3.0
dalf/searx,dalf/searx,dalf/searx,dalf/searx
# SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "performTitleMatch": True, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results Remove duplicated key from dict in Semantic Scholar
# SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results
<commit_before># SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "performTitleMatch": True, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results <commit_msg>Remove duplicated key from dict in Semantic Scholar<commit_after>
# SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results
# SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "performTitleMatch": True, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results Remove duplicated key from dict in Semantic Scholar# SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results
<commit_before># SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "performTitleMatch": True, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results <commit_msg>Remove duplicated key from dict in Semantic Scholar<commit_after># SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/json' params['data'] = dumps({ "queryString": query, "page": params['pageno'], "pageSize": 10, "sort": "relevance", "useFallbackRankerService": False, "useFallbackSearchCluster": False, "getQuerySuggestions": False, "authors": [], "coAuthors": [], "venues": [], "performTitleMatch": True, }) return params def response(resp): res = loads(resp.text) results = [] for result in res['results']: results.append({ 'url': result['primaryPaperLink']['url'], 'title': result['title']['text'], 'content': result['paperAbstractTruncated'] }) return results
129081d873a4e812a32b126cd7738b72979a814f
softwareindex/handlers/coreapi.py
softwareindex/handlers/coreapi.py
import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' def getCOREMentions(identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score, 'mentions in Open Access articles (via http://core.ac.uk/)'
# This is a software index handler that gives a score based on the # number of mentions in open access articles. It uses the CORE # aggregator (http://core.ac.uk/) to search the full text of indexed # articles. # # Inputs: # - identifier (String) # # Outputs: # - score (Number) # - description (String) import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' class core_handler: def get_score(self, identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score def get_description(self): return 'mentions in Open Access articles (via http://core.ac.uk/)'
Convert into a class to match the other handlers.
Convert into a class to match the other handlers.
Python
bsd-3-clause
softwaresaved/softwareindex,softwaresaved/softwareindex
import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' def getCOREMentions(identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score, 'mentions in Open Access articles (via http://core.ac.uk/)' Convert into a class to match the other handlers.
# This is a software index handler that gives a score based on the # number of mentions in open access articles. It uses the CORE # aggregator (http://core.ac.uk/) to search the full text of indexed # articles. # # Inputs: # - identifier (String) # # Outputs: # - score (Number) # - description (String) import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' class core_handler: def get_score(self, identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score def get_description(self): return 'mentions in Open Access articles (via http://core.ac.uk/)'
<commit_before>import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' def getCOREMentions(identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score, 'mentions in Open Access articles (via http://core.ac.uk/)' <commit_msg>Convert into a class to match the other handlers.<commit_after>
# This is a software index handler that gives a score based on the # number of mentions in open access articles. It uses the CORE # aggregator (http://core.ac.uk/) to search the full text of indexed # articles. # # Inputs: # - identifier (String) # # Outputs: # - score (Number) # - description (String) import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' class core_handler: def get_score(self, identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score def get_description(self): return 'mentions in Open Access articles (via http://core.ac.uk/)'
import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' def getCOREMentions(identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score, 'mentions in Open Access articles (via http://core.ac.uk/)' Convert into a class to match the other handlers.# This is a software index handler that gives a score based on the # number of mentions in open access articles. It uses the CORE # aggregator (http://core.ac.uk/) to search the full text of indexed # articles. # # Inputs: # - identifier (String) # # Outputs: # - score (Number) # - description (String) import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' class core_handler: def get_score(self, identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score def get_description(self): return 'mentions in Open Access articles (via http://core.ac.uk/)'
<commit_before>import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' def getCOREMentions(identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score, 'mentions in Open Access articles (via http://core.ac.uk/)' <commit_msg>Convert into a class to match the other handlers.<commit_after># This is a software index handler that gives a score based on the # number of mentions in open access articles. It uses the CORE # aggregator (http://core.ac.uk/) to search the full text of indexed # articles. # # Inputs: # - identifier (String) # # Outputs: # - score (Number) # - description (String) import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' class core_handler: def get_score(self, identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score def get_description(self): return 'mentions in Open Access articles (via http://core.ac.uk/)'
1a0b0c8b5424c3cc1a944902281a6a02c75cc66c
voting-app/app.py
voting-app/app.py
from flask import Flask, render_template, request, make_response, g from redis import Redis import os import socket import random import json option_a = os.getenv('OPTION_A', "Cats") option_b = os.getenv('OPTION_B', "Dogs") hostname = socket.gethostname() app = Flask(__name__) def get_redis(): if not hasattr(g, 'redis'): g.redis = Redis(host="redis", db=0) return g.redis @app.route("/", methods=['POST','GET']) def hello(): voter_id = request.cookies.get('voter_id') if not voter_id: voter_id = hex(random.getrandbits(64))[2:-1] vote = None if request.method == 'POST': redis = get_redis() vote = request.form['vote'] data = json.dumps({'voter_id': voter_id, 'vote': vote}) redis.rpush('votes', data) resp = make_response(render_template( 'index.html', option_a=option_a, option_b=option_b, hostname=hostname, vote=vote, )) resp.set_cookie('voter_id', voter_id) return resp if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True, threaded=True)
from flask import Flask, render_template, request, make_response, g from redis import Redis import os import socket import random import json option_a = os.getenv('OPTION_A', "Cats") option_b = os.getenv('OPTION_B', "Dogs") hostname = socket.gethostname() app = Flask(__name__) def get_redis(): if not hasattr(g, 'redis'): g.redis = Redis(host="redis", db=0, socket_timeout=5) return g.redis @app.route("/", methods=['POST','GET']) def hello(): voter_id = request.cookies.get('voter_id') if not voter_id: voter_id = hex(random.getrandbits(64))[2:-1] vote = None if request.method == 'POST': redis = get_redis() vote = request.form['vote'] data = json.dumps({'voter_id': voter_id, 'vote': vote}) redis.rpush('votes', data) resp = make_response(render_template( 'index.html', option_a=option_a, option_b=option_b, hostname=hostname, vote=vote, )) resp.set_cookie('voter_id', voter_id) return resp if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True, threaded=True)
Set redis socket timeout to 5s
Set redis socket timeout to 5s
Python
apache-2.0
TeamHeqing/voting-app,reshma-k/example-voting-app,sergey-korolev/demo-app,sergey-korolev/demo-app,sergey-korolev/demo-app,sergey-korolev/demo-app,TeamHeqing/voting-app,reshma-k/example-voting-app,reshma-k/example-voting-app,chrisdias/example-voting-app,reshma-k/example-voting-app,chrisdias/example-voting-app,reshma-k/example-voting-app,sergey-korolev/demo-app,TeamHeqing/voting-app,chrisdias/example-voting-app,TeamHeqing/voting-app,chrisdias/example-voting-app,TeamHeqing/voting-app,chrisdias/example-voting-app,sergey-korolev/demo-app,reshma-k/example-voting-app
from flask import Flask, render_template, request, make_response, g from redis import Redis import os import socket import random import json option_a = os.getenv('OPTION_A', "Cats") option_b = os.getenv('OPTION_B', "Dogs") hostname = socket.gethostname() app = Flask(__name__) def get_redis(): if not hasattr(g, 'redis'): g.redis = Redis(host="redis", db=0) return g.redis @app.route("/", methods=['POST','GET']) def hello(): voter_id = request.cookies.get('voter_id') if not voter_id: voter_id = hex(random.getrandbits(64))[2:-1] vote = None if request.method == 'POST': redis = get_redis() vote = request.form['vote'] data = json.dumps({'voter_id': voter_id, 'vote': vote}) redis.rpush('votes', data) resp = make_response(render_template( 'index.html', option_a=option_a, option_b=option_b, hostname=hostname, vote=vote, )) resp.set_cookie('voter_id', voter_id) return resp if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True, threaded=True) Set redis socket timeout to 5s
from flask import Flask, render_template, request, make_response, g from redis import Redis import os import socket import random import json option_a = os.getenv('OPTION_A', "Cats") option_b = os.getenv('OPTION_B', "Dogs") hostname = socket.gethostname() app = Flask(__name__) def get_redis(): if not hasattr(g, 'redis'): g.redis = Redis(host="redis", db=0, socket_timeout=5) return g.redis @app.route("/", methods=['POST','GET']) def hello(): voter_id = request.cookies.get('voter_id') if not voter_id: voter_id = hex(random.getrandbits(64))[2:-1] vote = None if request.method == 'POST': redis = get_redis() vote = request.form['vote'] data = json.dumps({'voter_id': voter_id, 'vote': vote}) redis.rpush('votes', data) resp = make_response(render_template( 'index.html', option_a=option_a, option_b=option_b, hostname=hostname, vote=vote, )) resp.set_cookie('voter_id', voter_id) return resp if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True, threaded=True)
<commit_before>from flask import Flask, render_template, request, make_response, g from redis import Redis import os import socket import random import json option_a = os.getenv('OPTION_A', "Cats") option_b = os.getenv('OPTION_B', "Dogs") hostname = socket.gethostname() app = Flask(__name__) def get_redis(): if not hasattr(g, 'redis'): g.redis = Redis(host="redis", db=0) return g.redis @app.route("/", methods=['POST','GET']) def hello(): voter_id = request.cookies.get('voter_id') if not voter_id: voter_id = hex(random.getrandbits(64))[2:-1] vote = None if request.method == 'POST': redis = get_redis() vote = request.form['vote'] data = json.dumps({'voter_id': voter_id, 'vote': vote}) redis.rpush('votes', data) resp = make_response(render_template( 'index.html', option_a=option_a, option_b=option_b, hostname=hostname, vote=vote, )) resp.set_cookie('voter_id', voter_id) return resp if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True, threaded=True) <commit_msg>Set redis socket timeout to 5s<commit_after>
from flask import Flask, render_template, request, make_response, g from redis import Redis import os import socket import random import json option_a = os.getenv('OPTION_A', "Cats") option_b = os.getenv('OPTION_B', "Dogs") hostname = socket.gethostname() app = Flask(__name__) def get_redis(): if not hasattr(g, 'redis'): g.redis = Redis(host="redis", db=0, socket_timeout=5) return g.redis @app.route("/", methods=['POST','GET']) def hello(): voter_id = request.cookies.get('voter_id') if not voter_id: voter_id = hex(random.getrandbits(64))[2:-1] vote = None if request.method == 'POST': redis = get_redis() vote = request.form['vote'] data = json.dumps({'voter_id': voter_id, 'vote': vote}) redis.rpush('votes', data) resp = make_response(render_template( 'index.html', option_a=option_a, option_b=option_b, hostname=hostname, vote=vote, )) resp.set_cookie('voter_id', voter_id) return resp if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True, threaded=True)
from flask import Flask, render_template, request, make_response, g from redis import Redis import os import socket import random import json option_a = os.getenv('OPTION_A', "Cats") option_b = os.getenv('OPTION_B', "Dogs") hostname = socket.gethostname() app = Flask(__name__) def get_redis(): if not hasattr(g, 'redis'): g.redis = Redis(host="redis", db=0) return g.redis @app.route("/", methods=['POST','GET']) def hello(): voter_id = request.cookies.get('voter_id') if not voter_id: voter_id = hex(random.getrandbits(64))[2:-1] vote = None if request.method == 'POST': redis = get_redis() vote = request.form['vote'] data = json.dumps({'voter_id': voter_id, 'vote': vote}) redis.rpush('votes', data) resp = make_response(render_template( 'index.html', option_a=option_a, option_b=option_b, hostname=hostname, vote=vote, )) resp.set_cookie('voter_id', voter_id) return resp if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True, threaded=True) Set redis socket timeout to 5sfrom flask import Flask, render_template, request, make_response, g from redis import Redis import os import socket import random import json option_a = os.getenv('OPTION_A', "Cats") option_b = os.getenv('OPTION_B', "Dogs") hostname = socket.gethostname() app = Flask(__name__) def get_redis(): if not hasattr(g, 'redis'): g.redis = Redis(host="redis", db=0, socket_timeout=5) return g.redis @app.route("/", methods=['POST','GET']) def hello(): voter_id = request.cookies.get('voter_id') if not voter_id: voter_id = hex(random.getrandbits(64))[2:-1] vote = None if request.method == 'POST': redis = get_redis() vote = request.form['vote'] data = json.dumps({'voter_id': voter_id, 'vote': vote}) redis.rpush('votes', data) resp = make_response(render_template( 'index.html', option_a=option_a, option_b=option_b, hostname=hostname, vote=vote, )) resp.set_cookie('voter_id', voter_id) return resp if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True, threaded=True)
<commit_before>from flask import Flask, render_template, request, make_response, g from redis import Redis import os import socket import random import json option_a = os.getenv('OPTION_A', "Cats") option_b = os.getenv('OPTION_B', "Dogs") hostname = socket.gethostname() app = Flask(__name__) def get_redis(): if not hasattr(g, 'redis'): g.redis = Redis(host="redis", db=0) return g.redis @app.route("/", methods=['POST','GET']) def hello(): voter_id = request.cookies.get('voter_id') if not voter_id: voter_id = hex(random.getrandbits(64))[2:-1] vote = None if request.method == 'POST': redis = get_redis() vote = request.form['vote'] data = json.dumps({'voter_id': voter_id, 'vote': vote}) redis.rpush('votes', data) resp = make_response(render_template( 'index.html', option_a=option_a, option_b=option_b, hostname=hostname, vote=vote, )) resp.set_cookie('voter_id', voter_id) return resp if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True, threaded=True) <commit_msg>Set redis socket timeout to 5s<commit_after>from flask import Flask, render_template, request, make_response, g from redis import Redis import os import socket import random import json option_a = os.getenv('OPTION_A', "Cats") option_b = os.getenv('OPTION_B', "Dogs") hostname = socket.gethostname() app = Flask(__name__) def get_redis(): if not hasattr(g, 'redis'): g.redis = Redis(host="redis", db=0, socket_timeout=5) return g.redis @app.route("/", methods=['POST','GET']) def hello(): voter_id = request.cookies.get('voter_id') if not voter_id: voter_id = hex(random.getrandbits(64))[2:-1] vote = None if request.method == 'POST': redis = get_redis() vote = request.form['vote'] data = json.dumps({'voter_id': voter_id, 'vote': vote}) redis.rpush('votes', data) resp = make_response(render_template( 'index.html', option_a=option_a, option_b=option_b, hostname=hostname, vote=vote, )) resp.set_cookie('voter_id', voter_id) return resp if __name__ == "__main__": app.run(host='0.0.0.0', port=80, debug=True, threaded=True)
e3f846d99280ab24120f34d52308ab9040b5e31b
Gateway_v2/packet_tester.py
Gateway_v2/packet_tester.py
from xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(30) kill_flag.set()
from xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(60) kill_flag.set()
Change wait period from 30 seconds to 60 seconds
Change wait period from 30 seconds to 60 seconds
Python
mit
scel-hawaii/data-gateway,scel-hawaii/data-gateway
from xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(30) kill_flag.set() Change wait period from 30 seconds to 60 seconds
from xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(60) kill_flag.set()
<commit_before>from xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(30) kill_flag.set() <commit_msg>Change wait period from 30 seconds to 60 seconds<commit_after>
from xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(60) kill_flag.set()
from xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(30) kill_flag.set() Change wait period from 30 seconds to 60 secondsfrom xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(60) kill_flag.set()
<commit_before>from xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(30) kill_flag.set() <commit_msg>Change wait period from 30 seconds to 60 seconds<commit_after>from xbee import ZigBee import sys import serial import datetime import struct import collections import threading from decoder import Decoder from xbee_gateway import XBeeGateway decoder = Decoder() xbg = XBeeGateway() decoder.register_callback(decoder.print_dictionary) decoder.register_callback(decoder.write_to_file) #decoder.register_callback(decoder.write_to_db) xbg.register_callback(decoder.decode_data) port = raw_input("Please enter your serial port path/name: ") baud_rate = 9600 t_flag = threading.Event() kill_flag = threading.Event() while True: currentTime = datetime.datetime.now() # log start times to file fileName = 'reset_log.txt' with open(fileName, 'a') as logfile: logfile.write(str(currentTime)) logfile.write('\n') kill_flag.clear() t_flag.set() xbg.setup_xbee(port, baud_rate) newThread = threading.Thread(target=xbg.begin_test, args=(1,t_flag,kill_flag)) newThread.daemon = True newThread.start() while t_flag.is_set(): t_flag.clear() #sleep 30 seconds then check to see if we have received anything t_flag.wait(60) kill_flag.set()
98f0313e935db2491a615e868e3bd5da21769c03
gocd/api/pipeline.py
gocd/api/pipeline.py
from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or 0)) def release(self): return self._post('/releaseLock') unlock = release def pause(self, reason=''): return self._post('/pause', pauseCause=reason) def unpause(self): return self._post('/unpause') def status(self): return self._get('/status') def instance(self, counter): return self._get('/instance/{counter:d}'.format(counter=counter)) def schedule(self, **material_args): return self._post('/schedule', ok_status=202, **material_args) run = schedule
from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or 0)) def release(self): return self._post('/releaseLock') unlock = release def pause(self, reason=''): return self._post('/pause', pauseCause=reason) def unpause(self): return self._post('/unpause') def status(self): return self._get('/status') def instance(self, counter): return self._get('/instance/{counter:d}'.format(counter=counter)) def schedule(self, **material_args): return self._post('/schedule', ok_status=202, **material_args) run = schedule trigger = schedule
Add trigger as an alias for schedule
Add trigger as an alias for schedule "Have you triggered that pipeline" is a fairly common thing to say.
Python
mit
henriquegemignani/py-gocd,gaqzi/py-gocd
from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or 0)) def release(self): return self._post('/releaseLock') unlock = release def pause(self, reason=''): return self._post('/pause', pauseCause=reason) def unpause(self): return self._post('/unpause') def status(self): return self._get('/status') def instance(self, counter): return self._get('/instance/{counter:d}'.format(counter=counter)) def schedule(self, **material_args): return self._post('/schedule', ok_status=202, **material_args) run = schedule Add trigger as an alias for schedule "Have you triggered that pipeline" is a fairly common thing to say.
from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or 0)) def release(self): return self._post('/releaseLock') unlock = release def pause(self, reason=''): return self._post('/pause', pauseCause=reason) def unpause(self): return self._post('/unpause') def status(self): return self._get('/status') def instance(self, counter): return self._get('/instance/{counter:d}'.format(counter=counter)) def schedule(self, **material_args): return self._post('/schedule', ok_status=202, **material_args) run = schedule trigger = schedule
<commit_before>from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or 0)) def release(self): return self._post('/releaseLock') unlock = release def pause(self, reason=''): return self._post('/pause', pauseCause=reason) def unpause(self): return self._post('/unpause') def status(self): return self._get('/status') def instance(self, counter): return self._get('/instance/{counter:d}'.format(counter=counter)) def schedule(self, **material_args): return self._post('/schedule', ok_status=202, **material_args) run = schedule <commit_msg>Add trigger as an alias for schedule "Have you triggered that pipeline" is a fairly common thing to say.<commit_after>
from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or 0)) def release(self): return self._post('/releaseLock') unlock = release def pause(self, reason=''): return self._post('/pause', pauseCause=reason) def unpause(self): return self._post('/unpause') def status(self): return self._get('/status') def instance(self, counter): return self._get('/instance/{counter:d}'.format(counter=counter)) def schedule(self, **material_args): return self._post('/schedule', ok_status=202, **material_args) run = schedule trigger = schedule
from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or 0)) def release(self): return self._post('/releaseLock') unlock = release def pause(self, reason=''): return self._post('/pause', pauseCause=reason) def unpause(self): return self._post('/unpause') def status(self): return self._get('/status') def instance(self, counter): return self._get('/instance/{counter:d}'.format(counter=counter)) def schedule(self, **material_args): return self._post('/schedule', ok_status=202, **material_args) run = schedule Add trigger as an alias for schedule "Have you triggered that pipeline" is a fairly common thing to say.from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or 0)) def release(self): return self._post('/releaseLock') unlock = release def pause(self, reason=''): return self._post('/pause', pauseCause=reason) def unpause(self): return self._post('/unpause') def status(self): return self._get('/status') def instance(self, counter): return self._get('/instance/{counter:d}'.format(counter=counter)) def schedule(self, **material_args): return self._post('/schedule', ok_status=202, **material_args) run = schedule trigger = schedule
<commit_before>from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or 0)) def release(self): return self._post('/releaseLock') unlock = release def pause(self, reason=''): return self._post('/pause', pauseCause=reason) def unpause(self): return self._post('/unpause') def status(self): return self._get('/status') def instance(self, counter): return self._get('/instance/{counter:d}'.format(counter=counter)) def schedule(self, **material_args): return self._post('/schedule', ok_status=202, **material_args) run = schedule <commit_msg>Add trigger as an alias for schedule "Have you triggered that pipeline" is a fairly common thing to say.<commit_after>from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or 0)) def release(self): return self._post('/releaseLock') unlock = release def pause(self, reason=''): return self._post('/pause', pauseCause=reason) def unpause(self): return self._post('/unpause') def status(self): return self._get('/status') def instance(self, counter): return self._get('/instance/{counter:d}'.format(counter=counter)) def schedule(self, **material_args): return self._post('/schedule', ok_status=202, **material_args) run = schedule trigger = schedule
936302bf5db057a01644014aabc1357f925c6afa
mezzanine/accounts/models.py
mezzanine/accounts/models.py
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(user_model, instance, created, **kwargs): if created: try: get_profile_for_user(instance) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False)
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(**kwargs): if kwargs["created"]: try: get_profile_for_user(kwargs["instance"]) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False)
Fix user profile signal handler.
Fix user profile signal handler.
Python
bsd-2-clause
wbtuomela/mezzanine,Cicero-Zhao/mezzanine,gradel/mezzanine,christianwgd/mezzanine,eino-makitalo/mezzanine,frankier/mezzanine,jerivas/mezzanine,Cicero-Zhao/mezzanine,frankier/mezzanine,readevalprint/mezzanine,dsanders11/mezzanine,stephenmcd/mezzanine,frankier/mezzanine,eino-makitalo/mezzanine,ryneeverett/mezzanine,viaregio/mezzanine,wbtuomela/mezzanine,readevalprint/mezzanine,dsanders11/mezzanine,douglaskastle/mezzanine,ryneeverett/mezzanine,vladir/mezzanine,stephenmcd/mezzanine,douglaskastle/mezzanine,vladir/mezzanine,christianwgd/mezzanine,sjdines/mezzanine,sjuxax/mezzanine,jerivas/mezzanine,stephenmcd/mezzanine,sjdines/mezzanine,readevalprint/mezzanine,viaregio/mezzanine,gradel/mezzanine,eino-makitalo/mezzanine,gradel/mezzanine,spookylukey/mezzanine,ryneeverett/mezzanine,viaregio/mezzanine,sjuxax/mezzanine,vladir/mezzanine,molokov/mezzanine,dsanders11/mezzanine,jerivas/mezzanine,spookylukey/mezzanine,sjuxax/mezzanine,douglaskastle/mezzanine,christianwgd/mezzanine,molokov/mezzanine,sjdines/mezzanine,molokov/mezzanine,spookylukey/mezzanine,wbtuomela/mezzanine
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(user_model, instance, created, **kwargs): if created: try: get_profile_for_user(instance) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False) Fix user profile signal handler.
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(**kwargs): if kwargs["created"]: try: get_profile_for_user(kwargs["instance"]) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False)
<commit_before>from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(user_model, instance, created, **kwargs): if created: try: get_profile_for_user(instance) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False) <commit_msg>Fix user profile signal handler.<commit_after>
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(**kwargs): if kwargs["created"]: try: get_profile_for_user(kwargs["instance"]) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False)
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(user_model, instance, created, **kwargs): if created: try: get_profile_for_user(instance) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False) Fix user profile signal handler.from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(**kwargs): if kwargs["created"]: try: get_profile_for_user(kwargs["instance"]) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False)
<commit_before>from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(user_model, instance, created, **kwargs): if created: try: get_profile_for_user(instance) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False) <commit_msg>Fix user profile signal handler.<commit_after>from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(**kwargs): if kwargs["created"]: try: get_profile_for_user(kwargs["instance"]) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False)
148ebbb82f824a091ae439f49b543165878eeee4
cloudly/cache.py
cloudly/cache.py
import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else - look for an EC2 hosted server offering the service 'redis', else - use localhost, 127.0.0.1. """ service_ips = ec2.find_service_ip('redis') ip_address = (os.environ.get("REDIS_HOST") or service_ips[0] if service_ips else None or "127.0.0.1") redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku. 'redis://{}:6379'.format(ip_address)) log.info("Connecting to Redis server at {}".format(redis_url)) return pyredis.from_url(redis_url) redis = get_conn()
import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else - look for an EC2 hosted server offering the service 'redis', else - use localhost, 127.0.0.1. """ try: service_ips = ec2.find_service_ip('redis') except Exception, exception: log.warning(exception) service_ips = [] ip_address = (os.environ.get("REDIS_HOST") or service_ips[0] if service_ips else None or "127.0.0.1") redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku. 'redis://{}:6379'.format(ip_address)) log.info("Connecting to Redis server at {}".format(redis_url)) return pyredis.from_url(redis_url) redis = get_conn()
Fix missing auth handler when trying to access EC2.
Fix missing auth handler when trying to access EC2.
Python
mit
ooda/cloudly,ooda/cloudly
import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else - look for an EC2 hosted server offering the service 'redis', else - use localhost, 127.0.0.1. """ service_ips = ec2.find_service_ip('redis') ip_address = (os.environ.get("REDIS_HOST") or service_ips[0] if service_ips else None or "127.0.0.1") redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku. 'redis://{}:6379'.format(ip_address)) log.info("Connecting to Redis server at {}".format(redis_url)) return pyredis.from_url(redis_url) redis = get_conn() Fix missing auth handler when trying to access EC2.
import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else - look for an EC2 hosted server offering the service 'redis', else - use localhost, 127.0.0.1. """ try: service_ips = ec2.find_service_ip('redis') except Exception, exception: log.warning(exception) service_ips = [] ip_address = (os.environ.get("REDIS_HOST") or service_ips[0] if service_ips else None or "127.0.0.1") redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku. 'redis://{}:6379'.format(ip_address)) log.info("Connecting to Redis server at {}".format(redis_url)) return pyredis.from_url(redis_url) redis = get_conn()
<commit_before>import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else - look for an EC2 hosted server offering the service 'redis', else - use localhost, 127.0.0.1. """ service_ips = ec2.find_service_ip('redis') ip_address = (os.environ.get("REDIS_HOST") or service_ips[0] if service_ips else None or "127.0.0.1") redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku. 'redis://{}:6379'.format(ip_address)) log.info("Connecting to Redis server at {}".format(redis_url)) return pyredis.from_url(redis_url) redis = get_conn() <commit_msg>Fix missing auth handler when trying to access EC2.<commit_after>
import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else - look for an EC2 hosted server offering the service 'redis', else - use localhost, 127.0.0.1. """ try: service_ips = ec2.find_service_ip('redis') except Exception, exception: log.warning(exception) service_ips = [] ip_address = (os.environ.get("REDIS_HOST") or service_ips[0] if service_ips else None or "127.0.0.1") redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku. 'redis://{}:6379'.format(ip_address)) log.info("Connecting to Redis server at {}".format(redis_url)) return pyredis.from_url(redis_url) redis = get_conn()
import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else - look for an EC2 hosted server offering the service 'redis', else - use localhost, 127.0.0.1. """ service_ips = ec2.find_service_ip('redis') ip_address = (os.environ.get("REDIS_HOST") or service_ips[0] if service_ips else None or "127.0.0.1") redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku. 'redis://{}:6379'.format(ip_address)) log.info("Connecting to Redis server at {}".format(redis_url)) return pyredis.from_url(redis_url) redis = get_conn() Fix missing auth handler when trying to access EC2.import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else - look for an EC2 hosted server offering the service 'redis', else - use localhost, 127.0.0.1. """ try: service_ips = ec2.find_service_ip('redis') except Exception, exception: log.warning(exception) service_ips = [] ip_address = (os.environ.get("REDIS_HOST") or service_ips[0] if service_ips else None or "127.0.0.1") redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku. 'redis://{}:6379'.format(ip_address)) log.info("Connecting to Redis server at {}".format(redis_url)) return pyredis.from_url(redis_url) redis = get_conn()
<commit_before>import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else - look for an EC2 hosted server offering the service 'redis', else - use localhost, 127.0.0.1. """ service_ips = ec2.find_service_ip('redis') ip_address = (os.environ.get("REDIS_HOST") or service_ips[0] if service_ips else None or "127.0.0.1") redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku. 'redis://{}:6379'.format(ip_address)) log.info("Connecting to Redis server at {}".format(redis_url)) return pyredis.from_url(redis_url) redis = get_conn() <commit_msg>Fix missing auth handler when trying to access EC2.<commit_after>import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else - look for an EC2 hosted server offering the service 'redis', else - use localhost, 127.0.0.1. """ try: service_ips = ec2.find_service_ip('redis') except Exception, exception: log.warning(exception) service_ips = [] ip_address = (os.environ.get("REDIS_HOST") or service_ips[0] if service_ips else None or "127.0.0.1") redis_url = os.getenv('REDISTOGO_URL', # Set when on Heroku. 'redis://{}:6379'.format(ip_address)) log.info("Connecting to Redis server at {}".format(redis_url)) return pyredis.from_url(redis_url) redis = get_conn()
54121f2b82950868db596d75e37e12f4c10c3339
troposphere/ce.py
troposphere/ce.py
# Copyright (c) 2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject class CostCategory(AWSObject): resource_type = "AWS::CE::CostCategory" props = { 'Name': (basestring, True), 'Rules': (basestring, True), 'RuleVersion': (basestring, True), }
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 31.0.0 from . import AWSObject from . import AWSProperty from .validators import double class AnomalyMonitor(AWSObject): resource_type = "AWS::CE::AnomalyMonitor" props = { 'MonitorDimension': (basestring, False), 'MonitorName': (basestring, True), 'MonitorSpecification': (basestring, False), 'MonitorType': (basestring, True), } class Subscriber(AWSProperty): props = { 'Address': (basestring, True), 'Status': (basestring, False), 'Type': (basestring, True), } class AnomalySubscription(AWSObject): resource_type = "AWS::CE::AnomalySubscription" props = { 'Frequency': (basestring, True), 'MonitorArnList': ([basestring], True), 'Subscribers': ([Subscriber], True), 'SubscriptionName': (basestring, True), 'Threshold': (double, True), } class CostCategory(AWSObject): resource_type = "AWS::CE::CostCategory" props = { 'Name': (basestring, True), 'RuleVersion': (basestring, True), 'Rules': (basestring, True), }
Update CE per 2021-03-11 changes
Update CE per 2021-03-11 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
# Copyright (c) 2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject class CostCategory(AWSObject): resource_type = "AWS::CE::CostCategory" props = { 'Name': (basestring, True), 'Rules': (basestring, True), 'RuleVersion': (basestring, True), } Update CE per 2021-03-11 changes
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 31.0.0 from . import AWSObject from . import AWSProperty from .validators import double class AnomalyMonitor(AWSObject): resource_type = "AWS::CE::AnomalyMonitor" props = { 'MonitorDimension': (basestring, False), 'MonitorName': (basestring, True), 'MonitorSpecification': (basestring, False), 'MonitorType': (basestring, True), } class Subscriber(AWSProperty): props = { 'Address': (basestring, True), 'Status': (basestring, False), 'Type': (basestring, True), } class AnomalySubscription(AWSObject): resource_type = "AWS::CE::AnomalySubscription" props = { 'Frequency': (basestring, True), 'MonitorArnList': ([basestring], True), 'Subscribers': ([Subscriber], True), 'SubscriptionName': (basestring, True), 'Threshold': (double, True), } class CostCategory(AWSObject): resource_type = "AWS::CE::CostCategory" props = { 'Name': (basestring, True), 'RuleVersion': (basestring, True), 'Rules': (basestring, True), }
<commit_before># Copyright (c) 2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject class CostCategory(AWSObject): resource_type = "AWS::CE::CostCategory" props = { 'Name': (basestring, True), 'Rules': (basestring, True), 'RuleVersion': (basestring, True), } <commit_msg>Update CE per 2021-03-11 changes<commit_after>
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 31.0.0 from . import AWSObject from . import AWSProperty from .validators import double class AnomalyMonitor(AWSObject): resource_type = "AWS::CE::AnomalyMonitor" props = { 'MonitorDimension': (basestring, False), 'MonitorName': (basestring, True), 'MonitorSpecification': (basestring, False), 'MonitorType': (basestring, True), } class Subscriber(AWSProperty): props = { 'Address': (basestring, True), 'Status': (basestring, False), 'Type': (basestring, True), } class AnomalySubscription(AWSObject): resource_type = "AWS::CE::AnomalySubscription" props = { 'Frequency': (basestring, True), 'MonitorArnList': ([basestring], True), 'Subscribers': ([Subscriber], True), 'SubscriptionName': (basestring, True), 'Threshold': (double, True), } class CostCategory(AWSObject): resource_type = "AWS::CE::CostCategory" props = { 'Name': (basestring, True), 'RuleVersion': (basestring, True), 'Rules': (basestring, True), }
# Copyright (c) 2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject class CostCategory(AWSObject): resource_type = "AWS::CE::CostCategory" props = { 'Name': (basestring, True), 'Rules': (basestring, True), 'RuleVersion': (basestring, True), } Update CE per 2021-03-11 changes# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 31.0.0 from . import AWSObject from . import AWSProperty from .validators import double class AnomalyMonitor(AWSObject): resource_type = "AWS::CE::AnomalyMonitor" props = { 'MonitorDimension': (basestring, False), 'MonitorName': (basestring, True), 'MonitorSpecification': (basestring, False), 'MonitorType': (basestring, True), } class Subscriber(AWSProperty): props = { 'Address': (basestring, True), 'Status': (basestring, False), 'Type': (basestring, True), } class AnomalySubscription(AWSObject): resource_type = "AWS::CE::AnomalySubscription" props = { 'Frequency': (basestring, True), 'MonitorArnList': ([basestring], True), 'Subscribers': ([Subscriber], True), 'SubscriptionName': (basestring, True), 'Threshold': (double, True), } class CostCategory(AWSObject): resource_type = "AWS::CE::CostCategory" props = { 'Name': (basestring, True), 'RuleVersion': (basestring, True), 'Rules': (basestring, True), }
<commit_before># Copyright (c) 2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject class CostCategory(AWSObject): resource_type = "AWS::CE::CostCategory" props = { 'Name': (basestring, True), 'Rules': (basestring, True), 'RuleVersion': (basestring, True), } <commit_msg>Update CE per 2021-03-11 changes<commit_after># Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 31.0.0 from . import AWSObject from . import AWSProperty from .validators import double class AnomalyMonitor(AWSObject): resource_type = "AWS::CE::AnomalyMonitor" props = { 'MonitorDimension': (basestring, False), 'MonitorName': (basestring, True), 'MonitorSpecification': (basestring, False), 'MonitorType': (basestring, True), } class Subscriber(AWSProperty): props = { 'Address': (basestring, True), 'Status': (basestring, False), 'Type': (basestring, True), } class AnomalySubscription(AWSObject): resource_type = "AWS::CE::AnomalySubscription" props = { 'Frequency': (basestring, True), 'MonitorArnList': ([basestring], True), 'Subscribers': ([Subscriber], True), 'SubscriptionName': (basestring, True), 'Threshold': (double, True), } class CostCategory(AWSObject): resource_type = "AWS::CE::CostCategory" props = { 'Name': (basestring, True), 'RuleVersion': (basestring, True), 'Rules': (basestring, True), }
fedf54fba832fd073f1a984e48b4e76400018aa0
mamba/application_factory.py
mamba/application_factory.py
# -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() settings_.slow_test_threshold = self.arguments.slow settings_.enable_coverage = self.arguments.enable_coverage return settings_ def create_formatter(self): return formatters.DocumentationFormatter(self.create_settings()) def create_example_collector(self): return example_collector.ExampleCollector(self.arguments.specs) def create_reporter(self): return reporter.Reporter(self.create_formatter()) def create_runner(self): settings = self.create_settings() if settings.enable_coverage: return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter()) return runners.Runner(self.create_example_collector(), self.create_reporter())
# -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() settings_.slow_test_threshold = self.arguments.slow settings_.enable_code_coverage = self.arguments.enable_coverage return settings_ def create_formatter(self): return formatters.DocumentationFormatter(self.create_settings()) def create_example_collector(self): return example_collector.ExampleCollector(self.arguments.specs) def create_reporter(self): return reporter.Reporter(self.create_formatter()) def create_runner(self): settings = self.create_settings() if settings.enable_code_coverage: return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter()) return runners.Runner(self.create_example_collector(), self.create_reporter())
Fix the enable coverage issue
Fix the enable coverage issue
Python
mit
dex4er/mamba,alejandrodob/mamba,markng/mamba,eferro/mamba,angelsanz/mamba,nestorsalceda/mamba,jaimegildesagredo/mamba
# -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() settings_.slow_test_threshold = self.arguments.slow settings_.enable_coverage = self.arguments.enable_coverage return settings_ def create_formatter(self): return formatters.DocumentationFormatter(self.create_settings()) def create_example_collector(self): return example_collector.ExampleCollector(self.arguments.specs) def create_reporter(self): return reporter.Reporter(self.create_formatter()) def create_runner(self): settings = self.create_settings() if settings.enable_coverage: return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter()) return runners.Runner(self.create_example_collector(), self.create_reporter()) Fix the enable coverage issue
# -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() settings_.slow_test_threshold = self.arguments.slow settings_.enable_code_coverage = self.arguments.enable_coverage return settings_ def create_formatter(self): return formatters.DocumentationFormatter(self.create_settings()) def create_example_collector(self): return example_collector.ExampleCollector(self.arguments.specs) def create_reporter(self): return reporter.Reporter(self.create_formatter()) def create_runner(self): settings = self.create_settings() if settings.enable_code_coverage: return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter()) return runners.Runner(self.create_example_collector(), self.create_reporter())
<commit_before># -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() settings_.slow_test_threshold = self.arguments.slow settings_.enable_coverage = self.arguments.enable_coverage return settings_ def create_formatter(self): return formatters.DocumentationFormatter(self.create_settings()) def create_example_collector(self): return example_collector.ExampleCollector(self.arguments.specs) def create_reporter(self): return reporter.Reporter(self.create_formatter()) def create_runner(self): settings = self.create_settings() if settings.enable_coverage: return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter()) return runners.Runner(self.create_example_collector(), self.create_reporter()) <commit_msg>Fix the enable coverage issue<commit_after>
# -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() settings_.slow_test_threshold = self.arguments.slow settings_.enable_code_coverage = self.arguments.enable_coverage return settings_ def create_formatter(self): return formatters.DocumentationFormatter(self.create_settings()) def create_example_collector(self): return example_collector.ExampleCollector(self.arguments.specs) def create_reporter(self): return reporter.Reporter(self.create_formatter()) def create_runner(self): settings = self.create_settings() if settings.enable_code_coverage: return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter()) return runners.Runner(self.create_example_collector(), self.create_reporter())
# -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() settings_.slow_test_threshold = self.arguments.slow settings_.enable_coverage = self.arguments.enable_coverage return settings_ def create_formatter(self): return formatters.DocumentationFormatter(self.create_settings()) def create_example_collector(self): return example_collector.ExampleCollector(self.arguments.specs) def create_reporter(self): return reporter.Reporter(self.create_formatter()) def create_runner(self): settings = self.create_settings() if settings.enable_coverage: return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter()) return runners.Runner(self.create_example_collector(), self.create_reporter()) Fix the enable coverage issue# -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() settings_.slow_test_threshold = self.arguments.slow settings_.enable_code_coverage = self.arguments.enable_coverage return settings_ def create_formatter(self): return formatters.DocumentationFormatter(self.create_settings()) def create_example_collector(self): return example_collector.ExampleCollector(self.arguments.specs) def create_reporter(self): return reporter.Reporter(self.create_formatter()) def create_runner(self): settings = self.create_settings() if settings.enable_code_coverage: return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter()) return runners.Runner(self.create_example_collector(), self.create_reporter())
<commit_before># -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() settings_.slow_test_threshold = self.arguments.slow settings_.enable_coverage = self.arguments.enable_coverage return settings_ def create_formatter(self): return formatters.DocumentationFormatter(self.create_settings()) def create_example_collector(self): return example_collector.ExampleCollector(self.arguments.specs) def create_reporter(self): return reporter.Reporter(self.create_formatter()) def create_runner(self): settings = self.create_settings() if settings.enable_coverage: return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter()) return runners.Runner(self.create_example_collector(), self.create_reporter()) <commit_msg>Fix the enable coverage issue<commit_after># -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() settings_.slow_test_threshold = self.arguments.slow settings_.enable_code_coverage = self.arguments.enable_coverage return settings_ def create_formatter(self): return formatters.DocumentationFormatter(self.create_settings()) def create_example_collector(self): return example_collector.ExampleCollector(self.arguments.specs) def create_reporter(self): return reporter.Reporter(self.create_formatter()) def create_runner(self): settings = self.create_settings() if settings.enable_code_coverage: return runners.CodeCoverageRunner(self.create_example_collector(), self.create_reporter()) return runners.Runner(self.create_example_collector(), self.create_reporter())
f5ac1fa0738384fada4abb979ba25dddecc56372
compose/utils.py
compose/utils.py
import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True) h = hashlib.sha256() h.update(dump) return h.hexdigest()
import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True, separators=(',', ':')) h = hashlib.sha256() h.update(dump) return h.hexdigest()
Remove whitespace from json hash
Remove whitespace from json hash Reasoning: https://github.com/aanand/fig/commit/e5d8447f063498164f12567554a2eec16b4a3c88#commitcomment-11243708 Signed-off-by: Ben Firshman <73675debcd8a436be48ec22211dcf44fe0df0a64@firshman.co.uk>
Python
apache-2.0
alunduil/fig,danix800/docker.github.io,joaofnfernandes/docker.github.io,tiry/compose,mrfuxi/compose,mnowster/compose,talolard/compose,joaofnfernandes/docker.github.io,JimGalasyn/docker.github.io,bdwill/docker.github.io,jrabbit/compose,uvgroovy/compose,rgbkrk/compose,Chouser/compose,anweiss/docker.github.io,shin-/docker.github.io,BSWANG/denverdino.github.io,danix800/docker.github.io,Yelp/docker-compose,albers/compose,mindaugasrukas/compose,Katlean/fig,LuisBosquez/docker.github.io,troy0820/docker.github.io,mnuessler/compose,saada/compose,viranch/compose,runcom/compose,bbirand/compose,josephpage/compose,andrewgee/compose,aanand/fig,mdaue/compose,xydinesh/compose,docker-zh/docker.github.io,amitsaha/compose,marcusmartins/compose,mosquito/docker-compose,denverdino/docker.github.io,shin-/compose,jzwlqx/denverdino.github.io,sebglazebrook/compose,dopry/compose,VinceBarresi/compose,denverdino/denverdino.github.io,MSakamaki/compose,Yelp/docker-compose,sanscontext/docker.github.io,tpounds/compose,tiry/compose,philwrenn/compose,joaofnfernandes/docker.github.io,simonista/compose,tpounds/compose,runcom/compose,d2bit/compose,ekristen/compose,dockerhn/compose,genki/compose,ralphtheninja/compose,jonaseck2/compose,charleswhchan/compose,thaJeztah/compose,thaJeztah/docker.github.io,TheDataShed/compose,bobphill/compose,shin-/docker.github.io,browning/compose,thaJeztah/compose,dopry/compose,troy0820/docker.github.io,bbirand/compose,alexandrev/compose,danix800/docker.github.io,jessekl/compose,mchasal/compose,marcusmartins/compose,phiroict/docker,shubheksha/docker.github.io,docker/docker.github.io,phiroict/docker,michael-k/docker-compose,phiroict/docker,shin-/docker.github.io,iamluc/compose,dockerhn/compose,johnstep/docker.github.io,BSWANG/denverdino.github.io,cclauss/compose,artemkaint/compose,brunocascio/compose,schmunk42/compose,glogiotatidis/compose,unodba/compose,aduermael/docker.github.io,mindaugasrukas/compose,bsmr-docker/compose,iamluc/compose,denverdino/denverdino.github.io,JimGalasyn/docker.github.io,aduermael/docker.github.io,anweiss/docker.github.io,joeuo/docker.github.io,LuisBosquez/docker.github.io,shubheksha/docker.github.io,swoopla/compose,Chouser/compose,phiroict/docker,jzwlqx/denverdino.github.io,ggtools/compose,LuisBosquez/docker.github.io,sdurrheimer/compose,denverdino/denverdino.github.io,bsmr-docker/compose,jzwlqx/denverdino.github.io,goloveychuk/compose,unodba/compose,noironetworks/compose,KalleDK/compose,benhamill/compose,jgrowl/compose,twitherspoon/compose,londoncalling/docker.github.io,gdevillele/docker.github.io,BSWANG/denverdino.github.io,jonaseck2/compose,goloveychuk/compose,artemkaint/compose,browning/compose,danix800/docker.github.io,joeuo/docker.github.io,londoncalling/docker.github.io,rillig/docker.github.io,anweiss/docker.github.io,docker-zh/docker.github.io,au-phiware/compose,johnstep/docker.github.io,johnstep/docker.github.io,mark-adams/compose,denverdino/compose,gdevillele/docker.github.io,rillig/docker.github.io,KevinGreene/compose,johnstep/docker.github.io,twitherspoon/compose,jiekechoo/compose,ZJaffee/compose,amitsaha/compose,anweiss/docker.github.io,bfirsh/fig,rillig/docker.github.io,thieman/compose,mohitsoni/compose,menglingwei/denverdino.github.io,jessekl/compose,docker-zh/docker.github.io,alexisbellido/docker.github.io,philwrenn/compose,mosquito/docker-compose,docker-zh/docker.github.io,RobertNorthard/compose,funkyfuture/docker-compose,pspierce/compose,calou/compose,shubheksha/docker.github.io,johnstep/docker.github.io,DoubleMalt/compose,mbailey/compose,docker/docker.github.io,gdevillele/docker.github.io,JimGalasyn/docker.github.io,zhangspook/compose,andrewgee/compose,swoopla/compose,rstacruz/compose,joaofnfernandes/docker.github.io,moxiegirl/compose,brunocascio/compose,KevinGreene/compose,jzwlqx/denverdino.github.io,JimGalasyn/docker.github.io,shin-/docker.github.io,dilgerma/compose,sanscontext/docker.github.io,bdwill/docker.github.io,denverdino/docker.github.io,denverdino/denverdino.github.io,kojiromike/compose,au-phiware/compose,mark-adams/compose,thieman/compose,londoncalling/docker.github.io,thaJeztah/docker.github.io,docker/docker.github.io,anweiss/docker.github.io,saada/compose,alexandrev/compose,rstacruz/compose,docker/docker.github.io,mrfuxi/compose,vdemeester/compose,glogiotatidis/compose,lukemarsden/compose,troy0820/docker.github.io,gtrdotmcs/compose,feelobot/compose,vdemeester/compose,nhumrich/compose,ekristen/compose,troy0820/docker.github.io,mbailey/compose,vlajos/compose,KalleDK/compose,denverdino/compose,benhamill/compose,feelobot/compose,jorgeLuizChaves/compose,rgbkrk/compose,moxiegirl/compose,Dakno/compose,aanand/fig,shubheksha/docker.github.io,joeuo/docker.github.io,schmunk42/compose,lukemarsden/compose,xydinesh/compose,qzio/compose,denverdino/denverdino.github.io,DoubleMalt/compose,ionrock/compose,VinceBarresi/compose,tangkun75/compose,screwgoth/compose,sanscontext/docker.github.io,charleswhchan/compose,jeanpralo/compose,lmesz/compose,thaJeztah/docker.github.io,menglingwei/denverdino.github.io,sebglazebrook/compose,sanscontext/docker.github.io,uvgroovy/compose,MSakamaki/compose,mnuessler/compose,joeuo/docker.github.io,denverdino/docker.github.io,dnephin/compose,kojiromike/compose,bdwill/docker.github.io,aduermael/docker.github.io,gdevillele/docker.github.io,bfirsh/fig,ph-One/compose,londoncalling/docker.github.io,hoogenm/compose,mchasal/compose,ggtools/compose,dbdd4us/compose,josephpage/compose,funkyfuture/docker-compose,talolard/compose,bobphill/compose,pspierce/compose,JimGalasyn/docker.github.io,menglingwei/denverdino.github.io,jgrowl/compose,cgvarela/compose,denverdino/docker.github.io,mdaue/compose,phiroict/docker,rillig/docker.github.io,mohitsoni/compose,LuisBosquez/docker.github.io,zhangspook/compose,tangkun75/compose,jrabbit/compose,LuisBosquez/docker.github.io,lmesz/compose,TomasTomecek/compose,shin-/compose,thaJeztah/docker.github.io,dnephin/compose,ionrock/compose,kikkomep/compose,bdwill/docker.github.io,docker-zh/docker.github.io,prologic/compose,vlajos/compose,dbdd4us/compose,noironetworks/compose,screwgoth/compose,menglingwei/denverdino.github.io,kikkomep/compose,cclauss/compose,viranch/compose,denverdino/docker.github.io,ZJaffee/compose,simonista/compose,alexisbellido/docker.github.io,jeanpralo/compose,joeuo/docker.github.io,qzio/compose,alunduil/fig,nhumrich/compose,cgvarela/compose,aduermael/docker.github.io,ChrisChinchilla/compose,thaJeztah/docker.github.io,RobertNorthard/compose,docker/docker.github.io,shubheksha/docker.github.io,TheDataShed/compose,gtrdotmcs/compose,londoncalling/docker.github.io,joaofnfernandes/docker.github.io,BSWANG/denverdino.github.io,dilgerma/compose,GM-Alex/compose,bdwill/docker.github.io,TomasTomecek/compose,sanscontext/docker.github.io,jzwlqx/denverdino.github.io,mnowster/compose,calou/compose,menglingwei/denverdino.github.io,genki/compose,albers/compose,gdevillele/docker.github.io,alexisbellido/docker.github.io,alexisbellido/docker.github.io,michael-k/docker-compose,ChrisChinchilla/compose,GM-Alex/compose,alexisbellido/docker.github.io,prologic/compose,ralphtheninja/compose,Dakno/compose,jorgeLuizChaves/compose,sdurrheimer/compose,shin-/docker.github.io,ph-One/compose,jiekechoo/compose,BSWANG/denverdino.github.io,hoogenm/compose,Katlean/fig,j-fuentes/compose,j-fuentes/compose,d2bit/compose
import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True) h = hashlib.sha256() h.update(dump) return h.hexdigest() Remove whitespace from json hash Reasoning: https://github.com/aanand/fig/commit/e5d8447f063498164f12567554a2eec16b4a3c88#commitcomment-11243708 Signed-off-by: Ben Firshman <73675debcd8a436be48ec22211dcf44fe0df0a64@firshman.co.uk>
import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True, separators=(',', ':')) h = hashlib.sha256() h.update(dump) return h.hexdigest()
<commit_before>import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True) h = hashlib.sha256() h.update(dump) return h.hexdigest() <commit_msg>Remove whitespace from json hash Reasoning: https://github.com/aanand/fig/commit/e5d8447f063498164f12567554a2eec16b4a3c88#commitcomment-11243708 Signed-off-by: Ben Firshman <73675debcd8a436be48ec22211dcf44fe0df0a64@firshman.co.uk><commit_after>
import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True, separators=(',', ':')) h = hashlib.sha256() h.update(dump) return h.hexdigest()
import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True) h = hashlib.sha256() h.update(dump) return h.hexdigest() Remove whitespace from json hash Reasoning: https://github.com/aanand/fig/commit/e5d8447f063498164f12567554a2eec16b4a3c88#commitcomment-11243708 Signed-off-by: Ben Firshman <73675debcd8a436be48ec22211dcf44fe0df0a64@firshman.co.uk>import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True, separators=(',', ':')) h = hashlib.sha256() h.update(dump) return h.hexdigest()
<commit_before>import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True) h = hashlib.sha256() h.update(dump) return h.hexdigest() <commit_msg>Remove whitespace from json hash Reasoning: https://github.com/aanand/fig/commit/e5d8447f063498164f12567554a2eec16b4a3c88#commitcomment-11243708 Signed-off-by: Ben Firshman <73675debcd8a436be48ec22211dcf44fe0df0a64@firshman.co.uk><commit_after>import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True, separators=(',', ':')) h = hashlib.sha256() h.update(dump) return h.hexdigest()
e78ce4d29fda36bcd946e6c54a745761596ee7f1
spec/puzzle/examples/gph/a_basic_puzzle_spec.py
spec/puzzle/examples/gph/a_basic_puzzle_spec.py
from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', 'sept e nary +1', 'binary +1', None, 'qui nary +9', None, None, 'quaternary +12', None ]))
from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', None, # 'sept e nary +1' lost when Trie threshold was changed. 'binary +1', None, None, # 'qui nary +9' lost when Trie threshold was changed. None, None, 'quaternary +12', None ]))
Update test values. Trie no longer provides 2 of the answers.
Update test values. Trie no longer provides 2 of the answers.
Python
mit
PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge
from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', 'sept e nary +1', 'binary +1', None, 'qui nary +9', None, None, 'quaternary +12', None ])) Update test values. Trie no longer provides 2 of the answers.
from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', None, # 'sept e nary +1' lost when Trie threshold was changed. 'binary +1', None, None, # 'qui nary +9' lost when Trie threshold was changed. None, None, 'quaternary +12', None ]))
<commit_before>from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', 'sept e nary +1', 'binary +1', None, 'qui nary +9', None, None, 'quaternary +12', None ])) <commit_msg>Update test values. Trie no longer provides 2 of the answers.<commit_after>
from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', None, # 'sept e nary +1' lost when Trie threshold was changed. 'binary +1', None, None, # 'qui nary +9' lost when Trie threshold was changed. None, None, 'quaternary +12', None ]))
from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', 'sept e nary +1', 'binary +1', None, 'qui nary +9', None, None, 'quaternary +12', None ])) Update test values. Trie no longer provides 2 of the answers.from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', None, # 'sept e nary +1' lost when Trie threshold was changed. 'binary +1', None, None, # 'qui nary +9' lost when Trie threshold was changed. None, None, 'quaternary +12', None ]))
<commit_before>from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', 'sept e nary +1', 'binary +1', None, 'qui nary +9', None, None, 'quaternary +12', None ])) <commit_msg>Update test values. Trie no longer provides 2 of the answers.<commit_after>from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle.get() with after.all: prod_config.reset() warehouse.restore() with it('parses'): problems = self.subject.problems() expect(problems).to(have_len(len(a_basic_puzzle.SOURCE.split('\n')) - 2)) for problem in problems: expect(problem).to(be_a(number_problem.NumberProblem)) with it('solves first problem'): expect(self.subject.problem(0).solution).not_to(be_empty) with it('gets some solutions right'): solutions = self.subject.solutions() expect(solutions).to(equal([ 'decimal +25', 'octal +12', None, # 'sept e nary +1' lost when Trie threshold was changed. 'binary +1', None, None, # 'qui nary +9' lost when Trie threshold was changed. None, None, 'quaternary +12', None ]))
03a3f15daf7c90f8146987f09491c69b899a0130
corehq/apps/domainsync/management/commands/copy_utils.py
corehq/apps/domainsync/management/commands/copy_utils.py
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list of doc-ids from a remote postgres database to the locally configured one. """ # can make this more configurable or less hard coded eventually # also note that ordering here is important for foreign key dependencies postgres_models = [ (SQLProduct, 'product_id'), (StockReport, 'form_id'), (StockTransaction, 'case_id'), (DocDomainMapping, 'doc_id'), # StockState objects are "derived" and get created by StockTransaction post_save signal. # We may want to directly port these over in the future. # (StockState, 'case_id'), ] for model, doc_field in postgres_models: query_set = model.objects.using(remote_postgres_slug).filter( **{'{}__in'.format(doc_field): doc_ids} ) count = query_set.count() print "Copying {} models ({})".format(model.__name__, count) if not simulate: for i, item in enumerate(query_set): # this can cause primary key conflicts to overwrite local data I think. Oh well? item.save(using='default') print 'Synced {}/{} {}'.format(i + 1, count, model.__name__)
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct from phonelog.models import DeviceReportEntry def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list of doc-ids from a remote postgres database to the locally configured one. """ # can make this more configurable or less hard coded eventually # also note that ordering here is important for foreign key dependencies postgres_models = [ (SQLProduct, 'product_id'), (StockReport, 'form_id'), (StockTransaction, 'case_id'), (DocDomainMapping, 'doc_id'), # StockState objects are "derived" and get created by StockTransaction post_save signal. # We may want to directly port these over in the future. # (StockState, 'case_id'), (DeviceReportEntry, 'xform_id'), ] for model, doc_field in postgres_models: query_set = model.objects.using(remote_postgres_slug).filter( **{'{}__in'.format(doc_field): doc_ids} ) count = query_set.count() print "Copying {} models ({})".format(model.__name__, count) if not simulate: for i, item in enumerate(query_set): # this can cause primary key conflicts to overwrite local data I think. Oh well? item.save(using='default') print 'Synced {}/{} {}'.format(i + 1, count, model.__name__)
Add phonelog to postgres models copied by copy_domain
Add phonelog to postgres models copied by copy_domain
Python
bsd-3-clause
dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list of doc-ids from a remote postgres database to the locally configured one. """ # can make this more configurable or less hard coded eventually # also note that ordering here is important for foreign key dependencies postgres_models = [ (SQLProduct, 'product_id'), (StockReport, 'form_id'), (StockTransaction, 'case_id'), (DocDomainMapping, 'doc_id'), # StockState objects are "derived" and get created by StockTransaction post_save signal. # We may want to directly port these over in the future. # (StockState, 'case_id'), ] for model, doc_field in postgres_models: query_set = model.objects.using(remote_postgres_slug).filter( **{'{}__in'.format(doc_field): doc_ids} ) count = query_set.count() print "Copying {} models ({})".format(model.__name__, count) if not simulate: for i, item in enumerate(query_set): # this can cause primary key conflicts to overwrite local data I think. Oh well? item.save(using='default') print 'Synced {}/{} {}'.format(i + 1, count, model.__name__) Add phonelog to postgres models copied by copy_domain
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct from phonelog.models import DeviceReportEntry def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list of doc-ids from a remote postgres database to the locally configured one. """ # can make this more configurable or less hard coded eventually # also note that ordering here is important for foreign key dependencies postgres_models = [ (SQLProduct, 'product_id'), (StockReport, 'form_id'), (StockTransaction, 'case_id'), (DocDomainMapping, 'doc_id'), # StockState objects are "derived" and get created by StockTransaction post_save signal. # We may want to directly port these over in the future. # (StockState, 'case_id'), (DeviceReportEntry, 'xform_id'), ] for model, doc_field in postgres_models: query_set = model.objects.using(remote_postgres_slug).filter( **{'{}__in'.format(doc_field): doc_ids} ) count = query_set.count() print "Copying {} models ({})".format(model.__name__, count) if not simulate: for i, item in enumerate(query_set): # this can cause primary key conflicts to overwrite local data I think. Oh well? item.save(using='default') print 'Synced {}/{} {}'.format(i + 1, count, model.__name__)
<commit_before>from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list of doc-ids from a remote postgres database to the locally configured one. """ # can make this more configurable or less hard coded eventually # also note that ordering here is important for foreign key dependencies postgres_models = [ (SQLProduct, 'product_id'), (StockReport, 'form_id'), (StockTransaction, 'case_id'), (DocDomainMapping, 'doc_id'), # StockState objects are "derived" and get created by StockTransaction post_save signal. # We may want to directly port these over in the future. # (StockState, 'case_id'), ] for model, doc_field in postgres_models: query_set = model.objects.using(remote_postgres_slug).filter( **{'{}__in'.format(doc_field): doc_ids} ) count = query_set.count() print "Copying {} models ({})".format(model.__name__, count) if not simulate: for i, item in enumerate(query_set): # this can cause primary key conflicts to overwrite local data I think. Oh well? item.save(using='default') print 'Synced {}/{} {}'.format(i + 1, count, model.__name__) <commit_msg>Add phonelog to postgres models copied by copy_domain<commit_after>
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct from phonelog.models import DeviceReportEntry def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list of doc-ids from a remote postgres database to the locally configured one. """ # can make this more configurable or less hard coded eventually # also note that ordering here is important for foreign key dependencies postgres_models = [ (SQLProduct, 'product_id'), (StockReport, 'form_id'), (StockTransaction, 'case_id'), (DocDomainMapping, 'doc_id'), # StockState objects are "derived" and get created by StockTransaction post_save signal. # We may want to directly port these over in the future. # (StockState, 'case_id'), (DeviceReportEntry, 'xform_id'), ] for model, doc_field in postgres_models: query_set = model.objects.using(remote_postgres_slug).filter( **{'{}__in'.format(doc_field): doc_ids} ) count = query_set.count() print "Copying {} models ({})".format(model.__name__, count) if not simulate: for i, item in enumerate(query_set): # this can cause primary key conflicts to overwrite local data I think. Oh well? item.save(using='default') print 'Synced {}/{} {}'.format(i + 1, count, model.__name__)
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list of doc-ids from a remote postgres database to the locally configured one. """ # can make this more configurable or less hard coded eventually # also note that ordering here is important for foreign key dependencies postgres_models = [ (SQLProduct, 'product_id'), (StockReport, 'form_id'), (StockTransaction, 'case_id'), (DocDomainMapping, 'doc_id'), # StockState objects are "derived" and get created by StockTransaction post_save signal. # We may want to directly port these over in the future. # (StockState, 'case_id'), ] for model, doc_field in postgres_models: query_set = model.objects.using(remote_postgres_slug).filter( **{'{}__in'.format(doc_field): doc_ids} ) count = query_set.count() print "Copying {} models ({})".format(model.__name__, count) if not simulate: for i, item in enumerate(query_set): # this can cause primary key conflicts to overwrite local data I think. Oh well? item.save(using='default') print 'Synced {}/{} {}'.format(i + 1, count, model.__name__) Add phonelog to postgres models copied by copy_domainfrom casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct from phonelog.models import DeviceReportEntry def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list of doc-ids from a remote postgres database to the locally configured one. """ # can make this more configurable or less hard coded eventually # also note that ordering here is important for foreign key dependencies postgres_models = [ (SQLProduct, 'product_id'), (StockReport, 'form_id'), (StockTransaction, 'case_id'), (DocDomainMapping, 'doc_id'), # StockState objects are "derived" and get created by StockTransaction post_save signal. # We may want to directly port these over in the future. # (StockState, 'case_id'), (DeviceReportEntry, 'xform_id'), ] for model, doc_field in postgres_models: query_set = model.objects.using(remote_postgres_slug).filter( **{'{}__in'.format(doc_field): doc_ids} ) count = query_set.count() print "Copying {} models ({})".format(model.__name__, count) if not simulate: for i, item in enumerate(query_set): # this can cause primary key conflicts to overwrite local data I think. Oh well? item.save(using='default') print 'Synced {}/{} {}'.format(i + 1, count, model.__name__)
<commit_before>from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list of doc-ids from a remote postgres database to the locally configured one. """ # can make this more configurable or less hard coded eventually # also note that ordering here is important for foreign key dependencies postgres_models = [ (SQLProduct, 'product_id'), (StockReport, 'form_id'), (StockTransaction, 'case_id'), (DocDomainMapping, 'doc_id'), # StockState objects are "derived" and get created by StockTransaction post_save signal. # We may want to directly port these over in the future. # (StockState, 'case_id'), ] for model, doc_field in postgres_models: query_set = model.objects.using(remote_postgres_slug).filter( **{'{}__in'.format(doc_field): doc_ids} ) count = query_set.count() print "Copying {} models ({})".format(model.__name__, count) if not simulate: for i, item in enumerate(query_set): # this can cause primary key conflicts to overwrite local data I think. Oh well? item.save(using='default') print 'Synced {}/{} {}'.format(i + 1, count, model.__name__) <commit_msg>Add phonelog to postgres models copied by copy_domain<commit_after>from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct from phonelog.models import DeviceReportEntry def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list of doc-ids from a remote postgres database to the locally configured one. """ # can make this more configurable or less hard coded eventually # also note that ordering here is important for foreign key dependencies postgres_models = [ (SQLProduct, 'product_id'), (StockReport, 'form_id'), (StockTransaction, 'case_id'), (DocDomainMapping, 'doc_id'), # StockState objects are "derived" and get created by StockTransaction post_save signal. # We may want to directly port these over in the future. # (StockState, 'case_id'), (DeviceReportEntry, 'xform_id'), ] for model, doc_field in postgres_models: query_set = model.objects.using(remote_postgres_slug).filter( **{'{}__in'.format(doc_field): doc_ids} ) count = query_set.count() print "Copying {} models ({})".format(model.__name__, count) if not simulate: for i, item in enumerate(query_set): # this can cause primary key conflicts to overwrite local data I think. Oh well? item.save(using='default') print 'Synced {}/{} {}'.format(i + 1, count, model.__name__)
0c593f66c0b51903c38b76bf1163d716f59c56d8
FreeMemory.py
FreeMemory.py
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } with open("/proc/meminfo") as fd: for line in fd: if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
Fix to ensure we dont leave any open file handles laying around
Fix to ensure we dont leave any open file handles laying around
Python
apache-2.0
inbloom/server-density-plugins
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data Fix to ensure we dont leave any open file handles laying around
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } with open("/proc/meminfo") as fd: for line in fd: if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
<commit_before>/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data <commit_msg>Fix to ensure we dont leave any open file handles laying around<commit_after>
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } with open("/proc/meminfo") as fd: for line in fd: if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data Fix to ensure we dont leave any open file handles laying around/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } with open("/proc/meminfo") as fd: for line in fd: if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
<commit_before>/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data <commit_msg>Fix to ensure we dont leave any open file handles laying around<commit_after>/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } with open("/proc/meminfo") as fd: for line in fd: if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
0e2d792cfe8d7afff08e08f5eaecdc126c369f54
asyncio/compat.py
asyncio/compat.py
""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (bytes, bytearray, buffer) else: BYTES_TYPES = (bytes, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return bytes(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data
""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (str, bytearray, buffer) else: # Python 2.7 BYTES_TYPES = (str, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return str(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data
Use str type instead of bytes in Python 2
Use str type instead of bytes in Python 2
Python
apache-2.0
overcastcloud/trollius,overcastcloud/trollius,overcastcloud/trollius
""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (bytes, bytearray, buffer) else: BYTES_TYPES = (bytes, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return bytes(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data Use str type instead of bytes in Python 2
""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (str, bytearray, buffer) else: # Python 2.7 BYTES_TYPES = (str, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return str(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data
<commit_before>""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (bytes, bytearray, buffer) else: BYTES_TYPES = (bytes, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return bytes(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data <commit_msg>Use str type instead of bytes in Python 2<commit_after>
""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (str, bytearray, buffer) else: # Python 2.7 BYTES_TYPES = (str, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return str(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data
""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (bytes, bytearray, buffer) else: BYTES_TYPES = (bytes, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return bytes(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data Use str type instead of bytes in Python 2""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (str, bytearray, buffer) else: # Python 2.7 BYTES_TYPES = (str, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return str(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data
<commit_before>""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (bytes, bytearray, buffer) else: BYTES_TYPES = (bytes, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return bytes(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data <commit_msg>Use str type instead of bytes in Python 2<commit_after>""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (str, bytearray, buffer) else: # Python 2.7 BYTES_TYPES = (str, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return str(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data
0e0b33a88ee050d7c02c0ba292d56478ba99e75d
stag/base.py
stag/base.py
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] children = children[1:] else: self.attrs = attrs # Some helpers for the `class` attribute if 'classes' in attrs: attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c) elif 'class_' in attrs: attrs['class'] = attrs.pop('class_') self.children = [] self.add_children(children) def __call__(self, *children): self.add_children(children) return self def add_children(self, children): if self.self_closing and children: raise ValueError("Self-closing tags can't have children.") if children and isgenerator(children[0]): children = children[0] for child in children: if child is not None: if isinstance(child, list): self.add_children(child) else: self.children.append(child)
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] children = children[1:] else: self.attrs = attrs # Some helpers for the `class` attribute if 'classes' in attrs: attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c) elif 'class_' in attrs: attrs['class'] = attrs.pop('class_') self.children = [] self.add_children(children) def __call__(self, *children): self.add_children(children) return self def __repr__(self): attr_string = ''.join(' {}="{}"'.format(key, val) for key, val in self.attrs.items() if val) return '<{}{}>'.format(self.tag, attr_string) def add_children(self, children): if self.self_closing and children: raise ValueError("Self-closing tags can't have children.") if children and isgenerator(children[0]): children = children[0] for child in children: if child is not None: if isinstance(child, list): self.add_children(child) else: self.children.append(child)
Add __repr__ for elements for easier debugging
Add __repr__ for elements for easier debugging
Python
mit
russiancow/stag
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] children = children[1:] else: self.attrs = attrs # Some helpers for the `class` attribute if 'classes' in attrs: attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c) elif 'class_' in attrs: attrs['class'] = attrs.pop('class_') self.children = [] self.add_children(children) def __call__(self, *children): self.add_children(children) return self def add_children(self, children): if self.self_closing and children: raise ValueError("Self-closing tags can't have children.") if children and isgenerator(children[0]): children = children[0] for child in children: if child is not None: if isinstance(child, list): self.add_children(child) else: self.children.append(child) Add __repr__ for elements for easier debugging
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] children = children[1:] else: self.attrs = attrs # Some helpers for the `class` attribute if 'classes' in attrs: attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c) elif 'class_' in attrs: attrs['class'] = attrs.pop('class_') self.children = [] self.add_children(children) def __call__(self, *children): self.add_children(children) return self def __repr__(self): attr_string = ''.join(' {}="{}"'.format(key, val) for key, val in self.attrs.items() if val) return '<{}{}>'.format(self.tag, attr_string) def add_children(self, children): if self.self_closing and children: raise ValueError("Self-closing tags can't have children.") if children and isgenerator(children[0]): children = children[0] for child in children: if child is not None: if isinstance(child, list): self.add_children(child) else: self.children.append(child)
<commit_before>try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] children = children[1:] else: self.attrs = attrs # Some helpers for the `class` attribute if 'classes' in attrs: attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c) elif 'class_' in attrs: attrs['class'] = attrs.pop('class_') self.children = [] self.add_children(children) def __call__(self, *children): self.add_children(children) return self def add_children(self, children): if self.self_closing and children: raise ValueError("Self-closing tags can't have children.") if children and isgenerator(children[0]): children = children[0] for child in children: if child is not None: if isinstance(child, list): self.add_children(child) else: self.children.append(child) <commit_msg>Add __repr__ for elements for easier debugging<commit_after>
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] children = children[1:] else: self.attrs = attrs # Some helpers for the `class` attribute if 'classes' in attrs: attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c) elif 'class_' in attrs: attrs['class'] = attrs.pop('class_') self.children = [] self.add_children(children) def __call__(self, *children): self.add_children(children) return self def __repr__(self): attr_string = ''.join(' {}="{}"'.format(key, val) for key, val in self.attrs.items() if val) return '<{}{}>'.format(self.tag, attr_string) def add_children(self, children): if self.self_closing and children: raise ValueError("Self-closing tags can't have children.") if children and isgenerator(children[0]): children = children[0] for child in children: if child is not None: if isinstance(child, list): self.add_children(child) else: self.children.append(child)
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] children = children[1:] else: self.attrs = attrs # Some helpers for the `class` attribute if 'classes' in attrs: attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c) elif 'class_' in attrs: attrs['class'] = attrs.pop('class_') self.children = [] self.add_children(children) def __call__(self, *children): self.add_children(children) return self def add_children(self, children): if self.self_closing and children: raise ValueError("Self-closing tags can't have children.") if children and isgenerator(children[0]): children = children[0] for child in children: if child is not None: if isinstance(child, list): self.add_children(child) else: self.children.append(child) Add __repr__ for elements for easier debuggingtry: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] children = children[1:] else: self.attrs = attrs # Some helpers for the `class` attribute if 'classes' in attrs: attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c) elif 'class_' in attrs: attrs['class'] = attrs.pop('class_') self.children = [] self.add_children(children) def __call__(self, *children): self.add_children(children) return self def __repr__(self): attr_string = ''.join(' {}="{}"'.format(key, val) for key, val in self.attrs.items() if val) return '<{}{}>'.format(self.tag, attr_string) def add_children(self, children): if self.self_closing and children: raise ValueError("Self-closing tags can't have children.") if children and isgenerator(children[0]): children = children[0] for child in children: if child is not None: if isinstance(child, list): self.add_children(child) else: self.children.append(child)
<commit_before>try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] children = children[1:] else: self.attrs = attrs # Some helpers for the `class` attribute if 'classes' in attrs: attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c) elif 'class_' in attrs: attrs['class'] = attrs.pop('class_') self.children = [] self.add_children(children) def __call__(self, *children): self.add_children(children) return self def add_children(self, children): if self.self_closing and children: raise ValueError("Self-closing tags can't have children.") if children and isgenerator(children[0]): children = children[0] for child in children: if child is not None: if isinstance(child, list): self.add_children(child) else: self.children.append(child) <commit_msg>Add __repr__ for elements for easier debugging<commit_after>try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] children = children[1:] else: self.attrs = attrs # Some helpers for the `class` attribute if 'classes' in attrs: attrs['class'] = ' '.join(c for c in attrs.pop('classes') if c) elif 'class_' in attrs: attrs['class'] = attrs.pop('class_') self.children = [] self.add_children(children) def __call__(self, *children): self.add_children(children) return self def __repr__(self): attr_string = ''.join(' {}="{}"'.format(key, val) for key, val in self.attrs.items() if val) return '<{}{}>'.format(self.tag, attr_string) def add_children(self, children): if self.self_closing and children: raise ValueError("Self-closing tags can't have children.") if children and isgenerator(children[0]): children = children[0] for child in children: if child is not None: if isinstance(child, list): self.add_children(child) else: self.children.append(child)
7a6e8af11ac28cf10e5ce33637bc883324dde641
game/models.py
game/models.py
from django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en = models.CharField(null=False, blank=False, max_length=256) desc_ru = models.TextField(null=False, blank=False) desc_en = models.TextField(null=False, blank=False) writeup_ru = models.TextField(null=False, blank=False) writeup_en = models.TextField(null=False, blank=False) flag = models.CharField(max_length=1024) is_case_insensitive_check = models.BooleanField(default=False) is_trimmed_check = models.BooleanField(default=False) check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES) created_at = models.DateTimeField(null=False, blank=True) def save(self, *args, **kwargs): if self.pk is None: self.created_at = timezone.now() return super(Task, self).save(*args, **kwargs)
from django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en = models.CharField(null=False, blank=False, max_length=256) category = models.CharField(null=False, blank=False, max_length=256) cost = models.IntegerField(null=False, blank=False) desc_ru = models.TextField(null=False, blank=False) desc_en = models.TextField(null=False, blank=False) writeup_ru = models.TextField(null=False, blank=False) writeup_en = models.TextField(null=False, blank=False) flag = models.CharField(max_length=1024) is_case_insensitive_check = models.BooleanField(default=False) is_trimmed_check = models.BooleanField(default=False) check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES) created_at = models.DateTimeField(null=False, blank=True) def save(self, *args, **kwargs): if self.pk is None: self.created_at = timezone.now() return super(Task, self).save(*args, **kwargs)
Add new fields to the task model
Add new fields to the task model
Python
bsd-3-clause
stefantsov/blackbox3,stefantsov/blackbox3,stefantsov/blackbox3
from django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en = models.CharField(null=False, blank=False, max_length=256) desc_ru = models.TextField(null=False, blank=False) desc_en = models.TextField(null=False, blank=False) writeup_ru = models.TextField(null=False, blank=False) writeup_en = models.TextField(null=False, blank=False) flag = models.CharField(max_length=1024) is_case_insensitive_check = models.BooleanField(default=False) is_trimmed_check = models.BooleanField(default=False) check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES) created_at = models.DateTimeField(null=False, blank=True) def save(self, *args, **kwargs): if self.pk is None: self.created_at = timezone.now() return super(Task, self).save(*args, **kwargs) Add new fields to the task model
from django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en = models.CharField(null=False, blank=False, max_length=256) category = models.CharField(null=False, blank=False, max_length=256) cost = models.IntegerField(null=False, blank=False) desc_ru = models.TextField(null=False, blank=False) desc_en = models.TextField(null=False, blank=False) writeup_ru = models.TextField(null=False, blank=False) writeup_en = models.TextField(null=False, blank=False) flag = models.CharField(max_length=1024) is_case_insensitive_check = models.BooleanField(default=False) is_trimmed_check = models.BooleanField(default=False) check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES) created_at = models.DateTimeField(null=False, blank=True) def save(self, *args, **kwargs): if self.pk is None: self.created_at = timezone.now() return super(Task, self).save(*args, **kwargs)
<commit_before>from django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en = models.CharField(null=False, blank=False, max_length=256) desc_ru = models.TextField(null=False, blank=False) desc_en = models.TextField(null=False, blank=False) writeup_ru = models.TextField(null=False, blank=False) writeup_en = models.TextField(null=False, blank=False) flag = models.CharField(max_length=1024) is_case_insensitive_check = models.BooleanField(default=False) is_trimmed_check = models.BooleanField(default=False) check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES) created_at = models.DateTimeField(null=False, blank=True) def save(self, *args, **kwargs): if self.pk is None: self.created_at = timezone.now() return super(Task, self).save(*args, **kwargs) <commit_msg>Add new fields to the task model<commit_after>
from django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en = models.CharField(null=False, blank=False, max_length=256) category = models.CharField(null=False, blank=False, max_length=256) cost = models.IntegerField(null=False, blank=False) desc_ru = models.TextField(null=False, blank=False) desc_en = models.TextField(null=False, blank=False) writeup_ru = models.TextField(null=False, blank=False) writeup_en = models.TextField(null=False, blank=False) flag = models.CharField(max_length=1024) is_case_insensitive_check = models.BooleanField(default=False) is_trimmed_check = models.BooleanField(default=False) check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES) created_at = models.DateTimeField(null=False, blank=True) def save(self, *args, **kwargs): if self.pk is None: self.created_at = timezone.now() return super(Task, self).save(*args, **kwargs)
from django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en = models.CharField(null=False, blank=False, max_length=256) desc_ru = models.TextField(null=False, blank=False) desc_en = models.TextField(null=False, blank=False) writeup_ru = models.TextField(null=False, blank=False) writeup_en = models.TextField(null=False, blank=False) flag = models.CharField(max_length=1024) is_case_insensitive_check = models.BooleanField(default=False) is_trimmed_check = models.BooleanField(default=False) check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES) created_at = models.DateTimeField(null=False, blank=True) def save(self, *args, **kwargs): if self.pk is None: self.created_at = timezone.now() return super(Task, self).save(*args, **kwargs) Add new fields to the task modelfrom django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en = models.CharField(null=False, blank=False, max_length=256) category = models.CharField(null=False, blank=False, max_length=256) cost = models.IntegerField(null=False, blank=False) desc_ru = models.TextField(null=False, blank=False) desc_en = models.TextField(null=False, blank=False) writeup_ru = models.TextField(null=False, blank=False) writeup_en = models.TextField(null=False, blank=False) flag = models.CharField(max_length=1024) is_case_insensitive_check = models.BooleanField(default=False) is_trimmed_check = models.BooleanField(default=False) check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES) created_at = models.DateTimeField(null=False, blank=True) def save(self, *args, **kwargs): if self.pk is None: self.created_at = timezone.now() return super(Task, self).save(*args, **kwargs)
<commit_before>from django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en = models.CharField(null=False, blank=False, max_length=256) desc_ru = models.TextField(null=False, blank=False) desc_en = models.TextField(null=False, blank=False) writeup_ru = models.TextField(null=False, blank=False) writeup_en = models.TextField(null=False, blank=False) flag = models.CharField(max_length=1024) is_case_insensitive_check = models.BooleanField(default=False) is_trimmed_check = models.BooleanField(default=False) check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES) created_at = models.DateTimeField(null=False, blank=True) def save(self, *args, **kwargs): if self.pk is None: self.created_at = timezone.now() return super(Task, self).save(*args, **kwargs) <commit_msg>Add new fields to the task model<commit_after>from django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en = models.CharField(null=False, blank=False, max_length=256) category = models.CharField(null=False, blank=False, max_length=256) cost = models.IntegerField(null=False, blank=False) desc_ru = models.TextField(null=False, blank=False) desc_en = models.TextField(null=False, blank=False) writeup_ru = models.TextField(null=False, blank=False) writeup_en = models.TextField(null=False, blank=False) flag = models.CharField(max_length=1024) is_case_insensitive_check = models.BooleanField(default=False) is_trimmed_check = models.BooleanField(default=False) check = models.CharField(null=False, blank=False, max_length=2, choices=CHECK_CHOICES) created_at = models.DateTimeField(null=False, blank=True) def save(self, *args, **kwargs): if self.pk is None: self.created_at = timezone.now() return super(Task, self).save(*args, **kwargs)
ddae9e02ab2bc9099fcb215ba5803210767f72a5
common/lib/xmodule/xmodule/edxnotes_utils.py
common/lib/xmodule/xmodule/edxnotes_utils.py
""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "edxnotes" in sys.modules: from edxnotes.decorators import edxnotes as notes return notes(cls) else: return cls
""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "lms.djangoapps.edxnotes" in sys.modules: from lms.djangoapps.edxnotes.decorators import edxnotes as notes return notes(cls) else: return cls
Use fully-qualified edxnotes app name when checking if installed
Use fully-qualified edxnotes app name when checking if installed
Python
agpl-3.0
angelapper/edx-platform,stvstnfrd/edx-platform,arbrandes/edx-platform,arbrandes/edx-platform,edx/edx-platform,eduNEXT/edunext-platform,EDUlib/edx-platform,EDUlib/edx-platform,angelapper/edx-platform,edx/edx-platform,eduNEXT/edx-platform,angelapper/edx-platform,EDUlib/edx-platform,edx/edx-platform,stvstnfrd/edx-platform,eduNEXT/edx-platform,stvstnfrd/edx-platform,arbrandes/edx-platform,eduNEXT/edx-platform,angelapper/edx-platform,edx/edx-platform,EDUlib/edx-platform,eduNEXT/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,stvstnfrd/edx-platform,eduNEXT/edunext-platform,eduNEXT/edunext-platform
""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "edxnotes" in sys.modules: from edxnotes.decorators import edxnotes as notes return notes(cls) else: return cls Use fully-qualified edxnotes app name when checking if installed
""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "lms.djangoapps.edxnotes" in sys.modules: from lms.djangoapps.edxnotes.decorators import edxnotes as notes return notes(cls) else: return cls
<commit_before>""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "edxnotes" in sys.modules: from edxnotes.decorators import edxnotes as notes return notes(cls) else: return cls <commit_msg>Use fully-qualified edxnotes app name when checking if installed<commit_after>
""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "lms.djangoapps.edxnotes" in sys.modules: from lms.djangoapps.edxnotes.decorators import edxnotes as notes return notes(cls) else: return cls
""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "edxnotes" in sys.modules: from edxnotes.decorators import edxnotes as notes return notes(cls) else: return cls Use fully-qualified edxnotes app name when checking if installed""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "lms.djangoapps.edxnotes" in sys.modules: from lms.djangoapps.edxnotes.decorators import edxnotes as notes return notes(cls) else: return cls
<commit_before>""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "edxnotes" in sys.modules: from edxnotes.decorators import edxnotes as notes return notes(cls) else: return cls <commit_msg>Use fully-qualified edxnotes app name when checking if installed<commit_after>""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "lms.djangoapps.edxnotes" in sys.modules: from lms.djangoapps.edxnotes.decorators import edxnotes as notes return notes(cls) else: return cls
61b2266cbd70eacf1382f3a6c46dd16485e4f7e7
utils/exporter.py
utils/exporter.py
import plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs/' def export(fig, module, dates): graph_dir = '{}{}/'.format(_out_dir, str(module))[:-3] # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename=graph_dir + output_file_name(module, dates))
import plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs' def export(fig, module, dates): graph_dir = '{}/{}'.format(_out_dir, module[:-3]) # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename='{}/{}'.format(graph_dir, output_file_name(module, dates)))
Fix naming of output dir and file names
Fix naming of output dir and file names
Python
mit
f-jiang/sleep-pattern-grapher
import plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs/' def export(fig, module, dates): graph_dir = '{}{}/'.format(_out_dir, str(module))[:-3] # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename=graph_dir + output_file_name(module, dates)) Fix naming of output dir and file names
import plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs' def export(fig, module, dates): graph_dir = '{}/{}'.format(_out_dir, module[:-3]) # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename='{}/{}'.format(graph_dir, output_file_name(module, dates)))
<commit_before>import plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs/' def export(fig, module, dates): graph_dir = '{}{}/'.format(_out_dir, str(module))[:-3] # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename=graph_dir + output_file_name(module, dates)) <commit_msg>Fix naming of output dir and file names<commit_after>
import plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs' def export(fig, module, dates): graph_dir = '{}/{}'.format(_out_dir, module[:-3]) # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename='{}/{}'.format(graph_dir, output_file_name(module, dates)))
import plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs/' def export(fig, module, dates): graph_dir = '{}{}/'.format(_out_dir, str(module))[:-3] # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename=graph_dir + output_file_name(module, dates)) Fix naming of output dir and file namesimport plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs' def export(fig, module, dates): graph_dir = '{}/{}'.format(_out_dir, module[:-3]) # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename='{}/{}'.format(graph_dir, output_file_name(module, dates)))
<commit_before>import plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs/' def export(fig, module, dates): graph_dir = '{}{}/'.format(_out_dir, str(module))[:-3] # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename=graph_dir + output_file_name(module, dates)) <commit_msg>Fix naming of output dir and file names<commit_after>import plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs' def export(fig, module, dates): graph_dir = '{}/{}'.format(_out_dir, module[:-3]) # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename='{}/{}'.format(graph_dir, output_file_name(module, dates)))
9c7b617829a953c8e7a4b377f8da84f8de94c9bf
src/rgrep.py
src/rgrep.py
def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' else: if case == 'i': return pattern.lower() in text.lower() else: return pattern in text
def display_usage(): return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return display_usage() else: if case == 'i': pattern = pattern.lower() text = text.lower() return pattern in text
Refactor the case insensitive option
Refactor the case insensitive option
Python
bsd-2-clause
ambidextrousTx/RGrep-Python
def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' else: if case == 'i': return pattern.lower() in text.lower() else: return pattern in text Refactor the case insensitive option
def display_usage(): return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return display_usage() else: if case == 'i': pattern = pattern.lower() text = text.lower() return pattern in text
<commit_before>def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' else: if case == 'i': return pattern.lower() in text.lower() else: return pattern in text <commit_msg>Refactor the case insensitive option<commit_after>
def display_usage(): return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return display_usage() else: if case == 'i': pattern = pattern.lower() text = text.lower() return pattern in text
def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' else: if case == 'i': return pattern.lower() in text.lower() else: return pattern in text Refactor the case insensitive optiondef display_usage(): return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return display_usage() else: if case == 'i': pattern = pattern.lower() text = text.lower() return pattern in text
<commit_before>def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' else: if case == 'i': return pattern.lower() in text.lower() else: return pattern in text <commit_msg>Refactor the case insensitive option<commit_after>def display_usage(): return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return display_usage() else: if case == 'i': pattern = pattern.lower() text = text.lower() return pattern in text
894fb1d68e82679720ed0acb71d478a8a1ba525d
openchordcharts/views/api.py
openchordcharts/views/api.py
# -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): return [chart.to_json() for chart in model.Chart.find()]
# -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): title = request.GET.get('title') user = request.GET.get('user') spec = {} if title: spec['title'] = title if user: spec['user'] = user return [chart.to_json() for chart in model.Chart.find(spec)]
Add search by title and user for API.
Add search by title and user for API.
Python
agpl-3.0
openchordcharts/web-api,openchordcharts/openchordcharts-api
# -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): return [chart.to_json() for chart in model.Chart.find()] Add search by title and user for API.
# -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): title = request.GET.get('title') user = request.GET.get('user') spec = {} if title: spec['title'] = title if user: spec['user'] = user return [chart.to_json() for chart in model.Chart.find(spec)]
<commit_before># -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): return [chart.to_json() for chart in model.Chart.find()] <commit_msg>Add search by title and user for API.<commit_after>
# -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): title = request.GET.get('title') user = request.GET.get('user') spec = {} if title: spec['title'] = title if user: spec['user'] = user return [chart.to_json() for chart in model.Chart.find(spec)]
# -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): return [chart.to_json() for chart in model.Chart.find()] Add search by title and user for API.# -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): title = request.GET.get('title') user = request.GET.get('user') spec = {} if title: spec['title'] = title if user: spec['user'] = user return [chart.to_json() for chart in model.Chart.find(spec)]
<commit_before># -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): return [chart.to_json() for chart in model.Chart.find()] <commit_msg>Add search by title and user for API.<commit_after># -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): title = request.GET.get('title') user = request.GET.get('user') spec = {} if title: spec['title'] = title if user: spec['user'] = user return [chart.to_json() for chart in model.Chart.find(spec)]
2fabca2c3a358e5c744c85eeeefcc78be3537a57
Demo/sockets/unixserver.py
Demo/sockets/unixserver.py
# Echo server program using Unix sockets (handles one connection only) from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
# Echo server demo using Unix sockets (handles one connection only) # Piet van Oostrum from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
Add Piet van Oostrum's name to the comments.
Add Piet van Oostrum's name to the comments.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
# Echo server program using Unix sockets (handles one connection only) from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() Add Piet van Oostrum's name to the comments.
# Echo server demo using Unix sockets (handles one connection only) # Piet van Oostrum from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
<commit_before># Echo server program using Unix sockets (handles one connection only) from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() <commit_msg>Add Piet van Oostrum's name to the comments.<commit_after>
# Echo server demo using Unix sockets (handles one connection only) # Piet van Oostrum from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
# Echo server program using Unix sockets (handles one connection only) from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() Add Piet van Oostrum's name to the comments.# Echo server demo using Unix sockets (handles one connection only) # Piet van Oostrum from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
<commit_before># Echo server program using Unix sockets (handles one connection only) from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() <commit_msg>Add Piet van Oostrum's name to the comments.<commit_after># Echo server demo using Unix sockets (handles one connection only) # Piet van Oostrum from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
501ede985c034f4883ac93a38f8486af6fddf766
src/nodeconductor_saltstack/saltstack/perms.py
src/nodeconductor_saltstack/saltstack/perms.py
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole, ProjectGroupRole, ProjectRole PERMISSION_LOGICS = ( ('saltstack.SaltStackService', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), ('saltstack.SaltStackServiceProjectLink', FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'service__customer__roles__permission_group__user', 'project__project_groups__roles__permission_group__user', ], collaborators_filter=[ {'service__customer__roles__role_type': CustomerRole.OWNER}, {'project__project_groups__roles__role_type': ProjectGroupRole.MANAGER}, ], any_permission=True, )), ) property_permission_logic = FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'tenant__service_project_link__project__roles__permission_group__user', 'tenant__service_project_link__project__customer__roles__permission_group__user', ], collaborators_filter=[ {'tenant__service_project_link__project__roles__role_type': ProjectRole.ADMINISTRATOR}, {'tenant__service_project_link__project__customer__roles__role_type': CustomerRole.OWNER}, ], any_permission=True, )
from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('saltstack.SaltStackService', structure_perms.service_permission_logic), ('saltstack.SaltStackServiceProjectLink', structure_perms.service_project_link_permission_logic), ) property_permission_logic = structure_perms.property_permission_logic('tenant')
Make permissions declaration DRY (NC-1282)
Make permissions declaration DRY (NC-1282)
Python
mit
opennode/nodeconductor-saltstack
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole, ProjectGroupRole, ProjectRole PERMISSION_LOGICS = ( ('saltstack.SaltStackService', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), ('saltstack.SaltStackServiceProjectLink', FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'service__customer__roles__permission_group__user', 'project__project_groups__roles__permission_group__user', ], collaborators_filter=[ {'service__customer__roles__role_type': CustomerRole.OWNER}, {'project__project_groups__roles__role_type': ProjectGroupRole.MANAGER}, ], any_permission=True, )), ) property_permission_logic = FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'tenant__service_project_link__project__roles__permission_group__user', 'tenant__service_project_link__project__customer__roles__permission_group__user', ], collaborators_filter=[ {'tenant__service_project_link__project__roles__role_type': ProjectRole.ADMINISTRATOR}, {'tenant__service_project_link__project__customer__roles__role_type': CustomerRole.OWNER}, ], any_permission=True, ) Make permissions declaration DRY (NC-1282)
from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('saltstack.SaltStackService', structure_perms.service_permission_logic), ('saltstack.SaltStackServiceProjectLink', structure_perms.service_project_link_permission_logic), ) property_permission_logic = structure_perms.property_permission_logic('tenant')
<commit_before>from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole, ProjectGroupRole, ProjectRole PERMISSION_LOGICS = ( ('saltstack.SaltStackService', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), ('saltstack.SaltStackServiceProjectLink', FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'service__customer__roles__permission_group__user', 'project__project_groups__roles__permission_group__user', ], collaborators_filter=[ {'service__customer__roles__role_type': CustomerRole.OWNER}, {'project__project_groups__roles__role_type': ProjectGroupRole.MANAGER}, ], any_permission=True, )), ) property_permission_logic = FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'tenant__service_project_link__project__roles__permission_group__user', 'tenant__service_project_link__project__customer__roles__permission_group__user', ], collaborators_filter=[ {'tenant__service_project_link__project__roles__role_type': ProjectRole.ADMINISTRATOR}, {'tenant__service_project_link__project__customer__roles__role_type': CustomerRole.OWNER}, ], any_permission=True, ) <commit_msg>Make permissions declaration DRY (NC-1282)<commit_after>
from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('saltstack.SaltStackService', structure_perms.service_permission_logic), ('saltstack.SaltStackServiceProjectLink', structure_perms.service_project_link_permission_logic), ) property_permission_logic = structure_perms.property_permission_logic('tenant')
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole, ProjectGroupRole, ProjectRole PERMISSION_LOGICS = ( ('saltstack.SaltStackService', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), ('saltstack.SaltStackServiceProjectLink', FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'service__customer__roles__permission_group__user', 'project__project_groups__roles__permission_group__user', ], collaborators_filter=[ {'service__customer__roles__role_type': CustomerRole.OWNER}, {'project__project_groups__roles__role_type': ProjectGroupRole.MANAGER}, ], any_permission=True, )), ) property_permission_logic = FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'tenant__service_project_link__project__roles__permission_group__user', 'tenant__service_project_link__project__customer__roles__permission_group__user', ], collaborators_filter=[ {'tenant__service_project_link__project__roles__role_type': ProjectRole.ADMINISTRATOR}, {'tenant__service_project_link__project__customer__roles__role_type': CustomerRole.OWNER}, ], any_permission=True, ) Make permissions declaration DRY (NC-1282)from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('saltstack.SaltStackService', structure_perms.service_permission_logic), ('saltstack.SaltStackServiceProjectLink', structure_perms.service_project_link_permission_logic), ) property_permission_logic = structure_perms.property_permission_logic('tenant')
<commit_before>from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole, ProjectGroupRole, ProjectRole PERMISSION_LOGICS = ( ('saltstack.SaltStackService', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), ('saltstack.SaltStackServiceProjectLink', FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'service__customer__roles__permission_group__user', 'project__project_groups__roles__permission_group__user', ], collaborators_filter=[ {'service__customer__roles__role_type': CustomerRole.OWNER}, {'project__project_groups__roles__role_type': ProjectGroupRole.MANAGER}, ], any_permission=True, )), ) property_permission_logic = FilteredCollaboratorsPermissionLogic( collaborators_query=[ 'tenant__service_project_link__project__roles__permission_group__user', 'tenant__service_project_link__project__customer__roles__permission_group__user', ], collaborators_filter=[ {'tenant__service_project_link__project__roles__role_type': ProjectRole.ADMINISTRATOR}, {'tenant__service_project_link__project__customer__roles__role_type': CustomerRole.OWNER}, ], any_permission=True, ) <commit_msg>Make permissions declaration DRY (NC-1282)<commit_after>from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('saltstack.SaltStackService', structure_perms.service_permission_logic), ('saltstack.SaltStackServiceProjectLink', structure_perms.service_project_link_permission_logic), ) property_permission_logic = structure_perms.property_permission_logic('tenant')
792e498350615cdaef2d76d009f5e049583896e8
papers/templatetags/orcid.py
papers/templatetags/orcid.py
# -*- encoding: utf-8 -*- from django import template from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def orcid_to_url(orcid): return mark_safe('http://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid))) @register.filter(is_safe=True) def small_orcid(orcid): """ We expect here that the ORCID id has been validated before. This displays something like "iD ...-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> ...%s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid[9:])) @register.filter(is_safe=True) def full_orcid(orcid): """ We expect here that the ORCID id has been validated before This displays something like "iD 0000-0002-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> %s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid))
# -*- encoding: utf-8 -*- from django import template from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def orcid_to_url(orcid): return mark_safe('https://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid))) @register.filter(is_safe=True) def small_orcid(orcid): """ We expect here that the ORCID id has been validated before. This displays something like "iD ...-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> ...%s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid[9:])) @register.filter(is_safe=True) def full_orcid(orcid): """ We expect here that the ORCID id has been validated before This displays something like "iD 0000-0002-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> %s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid))
Use https for links to ORCID
Use https for links to ORCID
Python
agpl-3.0
wetneb/dissemin,dissemin/dissemin,dissemin/dissemin,wetneb/dissemin,dissemin/dissemin,wetneb/dissemin,dissemin/dissemin,wetneb/dissemin,dissemin/dissemin
# -*- encoding: utf-8 -*- from django import template from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def orcid_to_url(orcid): return mark_safe('http://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid))) @register.filter(is_safe=True) def small_orcid(orcid): """ We expect here that the ORCID id has been validated before. This displays something like "iD ...-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> ...%s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid[9:])) @register.filter(is_safe=True) def full_orcid(orcid): """ We expect here that the ORCID id has been validated before This displays something like "iD 0000-0002-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> %s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid)) Use https for links to ORCID
# -*- encoding: utf-8 -*- from django import template from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def orcid_to_url(orcid): return mark_safe('https://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid))) @register.filter(is_safe=True) def small_orcid(orcid): """ We expect here that the ORCID id has been validated before. This displays something like "iD ...-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> ...%s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid[9:])) @register.filter(is_safe=True) def full_orcid(orcid): """ We expect here that the ORCID id has been validated before This displays something like "iD 0000-0002-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> %s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid))
<commit_before># -*- encoding: utf-8 -*- from django import template from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def orcid_to_url(orcid): return mark_safe('http://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid))) @register.filter(is_safe=True) def small_orcid(orcid): """ We expect here that the ORCID id has been validated before. This displays something like "iD ...-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> ...%s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid[9:])) @register.filter(is_safe=True) def full_orcid(orcid): """ We expect here that the ORCID id has been validated before This displays something like "iD 0000-0002-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> %s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid)) <commit_msg>Use https for links to ORCID<commit_after>
# -*- encoding: utf-8 -*- from django import template from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def orcid_to_url(orcid): return mark_safe('https://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid))) @register.filter(is_safe=True) def small_orcid(orcid): """ We expect here that the ORCID id has been validated before. This displays something like "iD ...-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> ...%s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid[9:])) @register.filter(is_safe=True) def full_orcid(orcid): """ We expect here that the ORCID id has been validated before This displays something like "iD 0000-0002-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> %s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid))
# -*- encoding: utf-8 -*- from django import template from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def orcid_to_url(orcid): return mark_safe('http://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid))) @register.filter(is_safe=True) def small_orcid(orcid): """ We expect here that the ORCID id has been validated before. This displays something like "iD ...-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> ...%s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid[9:])) @register.filter(is_safe=True) def full_orcid(orcid): """ We expect here that the ORCID id has been validated before This displays something like "iD 0000-0002-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> %s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid)) Use https for links to ORCID# -*- encoding: utf-8 -*- from django import template from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def orcid_to_url(orcid): return mark_safe('https://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid))) @register.filter(is_safe=True) def small_orcid(orcid): """ We expect here that the ORCID id has been validated before. This displays something like "iD ...-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> ...%s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid[9:])) @register.filter(is_safe=True) def full_orcid(orcid): """ We expect here that the ORCID id has been validated before This displays something like "iD 0000-0002-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> %s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid))
<commit_before># -*- encoding: utf-8 -*- from django import template from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def orcid_to_url(orcid): return mark_safe('http://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid))) @register.filter(is_safe=True) def small_orcid(orcid): """ We expect here that the ORCID id has been validated before. This displays something like "iD ...-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> ...%s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid[9:])) @register.filter(is_safe=True) def full_orcid(orcid): """ We expect here that the ORCID id has been validated before This displays something like "iD 0000-0002-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> %s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid)) <commit_msg>Use https for links to ORCID<commit_after># -*- encoding: utf-8 -*- from django import template from django.conf import settings from django.contrib.staticfiles.templatetags.staticfiles import static from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def orcid_to_url(orcid): return mark_safe('https://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid))) @register.filter(is_safe=True) def small_orcid(orcid): """ We expect here that the ORCID id has been validated before. This displays something like "iD ...-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> ...%s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid[9:])) @register.filter(is_safe=True) def full_orcid(orcid): """ We expect here that the ORCID id has been validated before This displays something like "iD 0000-0002-1234-2349" """ return mark_safe('<a href="%s" alt="%s"><img src="%s" alt="ORCID" /> %s</a>' % (orcid_to_url(orcid), orcid, static('img/orcid-small.png'), orcid))
86522eab0758ac6bf92ad19b60417b279c71a42c
tabtranslator/model.py
tabtranslator/model.py
# coding: utf-8 class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration
# coding: utf-8 class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(Sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(Bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(Note, self).__init__() self.pitch = pitch self.duration = duration
FIX class name in camel case:
FIX class name in camel case:
Python
mit
ograndedjogo/tab-translator,ograndedjogo/tab-translator
# coding: utf-8 class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration FIX class name in camel case:
# coding: utf-8 class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(Sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(Bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(Note, self).__init__() self.pitch = pitch self.duration = duration
<commit_before># coding: utf-8 class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration <commit_msg>FIX class name in camel case:<commit_after>
# coding: utf-8 class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(Sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(Bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(Note, self).__init__() self.pitch = pitch self.duration = duration
# coding: utf-8 class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration FIX class name in camel case:# coding: utf-8 class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(Sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(Bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(Note, self).__init__() self.pitch = pitch self.duration = duration
<commit_before># coding: utf-8 class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration <commit_msg>FIX class name in camel case:<commit_after># coding: utf-8 class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(Sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(Bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(Note, self).__init__() self.pitch = pitch self.duration = duration
76e0279268f30b87dfbbd4358b3f462b7b89b0f1
tabtranslator/model.py
tabtranslator/model.py
class sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration
class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration
CLEAN class name with camel case
CLEAN class name with camel case
Python
mit
ograndedjogo/tab-translator,ograndedjogo/tab-translator
class sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration CLEAN class name with camel case
class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration
<commit_before>class sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration <commit_msg>CLEAN class name with camel case<commit_after>
class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration
class sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration CLEAN class name with camel caseclass Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration
<commit_before>class sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration <commit_msg>CLEAN class name with camel case<commit_after>class Sheet(object): """ sheet: Top level object. Models the entire music sheet """ def __init__(self, name): super(sheet, self).__init__() self.name = name self.bars = list() class Bar(object): """ bar: Models a measure. Compose the sheet as the temporal layer => Where the notes are displayed on the sheet """ def __init__(self, time_signature=4): super(bar, self).__init__() self.time_signature = time_signature self.notes = list() class Note(object): """ note: Models the unit in music representation Drives visual representation => What note must be displayed on the sheet """ def __init__(self, pitch, duration=1): super(bote, self).__init__() self.pitch = pitch self.duration = duration
7ad5e00abc9158951697e86242781567b82dd52c
oauth2_provider/generators.py
oauth2_provider/generators.py
from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash()
from oauthlib.common import generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128, chars=CLIENT_ID_CHARACTER_SET) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash()
Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations
Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations
Python
bsd-2-clause
cheif/django-oauth-toolkit,svetlyak40wt/django-oauth-toolkit,jensadne/django-oauth-toolkit,bleib1dj/django-oauth-toolkit,vmalavolta/django-oauth-toolkit,Knotis/django-oauth-toolkit,jensadne/django-oauth-toolkit,mjrulesamrat/django-oauth-toolkit,andrefsp/django-oauth-toolkit,DeskConnect/django-oauth-toolkit,CloudNcodeInc/django-oauth-toolkit,trbs/django-oauth-toolkit,JensTimmerman/django-oauth-toolkit,Gr1N/django-oauth-toolkit,trbs/django-oauth-toolkit,bleib1dj/django-oauth-toolkit,mjrulesamrat/django-oauth-toolkit,natgeo/django-oauth-toolkit,lzen/django-oauth-toolkit,Natgeoed/django-oauth-toolkit,Knotis/django-oauth-toolkit,lzen/django-oauth-toolkit,DeskConnect/django-oauth-toolkit,vmalavolta/django-oauth-toolkit,StepicOrg/django-oauth-toolkit,Gr1N/django-oauth-toolkit,drgarcia1986/django-oauth-toolkit,cheif/django-oauth-toolkit,StepicOrg/django-oauth-toolkit,JensTimmerman/django-oauth-toolkit,CloudNcodeInc/django-oauth-toolkit,drgarcia1986/django-oauth-toolkit,andrefsp/django-oauth-toolkit
from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash() Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations
from oauthlib.common import generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128, chars=CLIENT_ID_CHARACTER_SET) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash()
<commit_before>from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash() <commit_msg>Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations<commit_after>
from oauthlib.common import generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128, chars=CLIENT_ID_CHARACTER_SET) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash()
from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash() Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementationsfrom oauthlib.common import generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128, chars=CLIENT_ID_CHARACTER_SET) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash()
<commit_before>from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash() <commit_msg>Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations<commit_after>from oauthlib.common import generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128, chars=CLIENT_ID_CHARACTER_SET) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash()
b7238c0178eee43ccc6cfb3ac2039aad3bf0f2ce
relengapi/blueprints/slaveloan/tests/test_slaveloan.py
relengapi/blueprints/slaveloan/tests/test_slaveloan.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext test_context = TestContext() @test_context def test_hello(client): rv = client.get('/slaveloan/') eq_(rv.status_code, 200)
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext def userperms(perms, email='me@example.com'): u = auth.HumanUser(email) u._permissions = set(perms) return u test_context = TestContext() test_context_admin = TestContext(databases=['relengapi'], user=userperms([p.slaveloan.admin])) @test_context def test_root(client): "The root of the blueprint is accessible without login" rv = client.get('/slaveloan/') eq_(rv.status_code, 200) @test_context def test_admin_ui_not_authorized(client): "Test that an unlogged in user can't access the admin ui" rv = client.get('/slaveloan/admin') eq_(rv.status_code, 301) @test_context_admin def test_admin_ui_authorized(client): "Test that an admin can access the admin ui" rv = client.get('/slaveloan/admin') eq_(rv.status_code, 200) @test_context def test_details_ui_not_authorized(client): "Test that an logged out user can't access the loan details ui" rv = client.get('/slaveloan/details/2') eq_(rv.status_code, 200) @test_context_admin def test_details_ui_authorized(client): "Test that an admin can access the loan details ui" rv = client.get('/slaveloan/details/2') eq_(rv.status_code, 200) @test_context def test_machine_classes(client): "Test that someone not logged in can access the slave class mapping" rv = client.get('/machine/classes') eq_(rv.status_code, 200)
Add a few tests that some endpoints load
Add a few tests that some endpoints load
Python
mpl-2.0
Callek/build-relengapi,andrei987/services,lundjordan/build-relengapi,djmitche/build-relengapi,Callek/build-relengapi,lundjordan/services,srfraser/services,garbas/mozilla-releng-services,Callek/build-relengapi,Callek/build-relengapi,mozilla/build-relengapi,djmitche/build-relengapi,andrei987/services,Callek/build-relengapi-slaveloan,hwine/build-relengapi,La0/mozilla-relengapi,lundjordan/build-relengapi,hwine/build-relengapi,mozilla-releng/services,hwine/build-relengapi,garbas/mozilla-releng-services,La0/mozilla-relengapi,mozilla-releng/services,La0/mozilla-relengapi,mozilla-releng/services,mozilla-releng/services,mozilla/build-relengapi,andrei987/services,hwine/build-relengapi,djmitche/build-relengapi,srfraser/services,Callek/build-relengapi-slaveloan,La0/mozilla-relengapi,Callek/build-relengapi-slaveloan,lundjordan/build-relengapi,garbas/mozilla-releng-services,garbas/mozilla-releng-services,Callek/build-relengapi-slaveloan,lundjordan/services,lundjordan/services,lundjordan/services,srfraser/services,andrei987/services,djmitche/build-relengapi,mozilla/build-relengapi,srfraser/services,mozilla/build-relengapi,lundjordan/build-relengapi
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext test_context = TestContext() @test_context def test_hello(client): rv = client.get('/slaveloan/') eq_(rv.status_code, 200) Add a few tests that some endpoints load
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext def userperms(perms, email='me@example.com'): u = auth.HumanUser(email) u._permissions = set(perms) return u test_context = TestContext() test_context_admin = TestContext(databases=['relengapi'], user=userperms([p.slaveloan.admin])) @test_context def test_root(client): "The root of the blueprint is accessible without login" rv = client.get('/slaveloan/') eq_(rv.status_code, 200) @test_context def test_admin_ui_not_authorized(client): "Test that an unlogged in user can't access the admin ui" rv = client.get('/slaveloan/admin') eq_(rv.status_code, 301) @test_context_admin def test_admin_ui_authorized(client): "Test that an admin can access the admin ui" rv = client.get('/slaveloan/admin') eq_(rv.status_code, 200) @test_context def test_details_ui_not_authorized(client): "Test that an logged out user can't access the loan details ui" rv = client.get('/slaveloan/details/2') eq_(rv.status_code, 200) @test_context_admin def test_details_ui_authorized(client): "Test that an admin can access the loan details ui" rv = client.get('/slaveloan/details/2') eq_(rv.status_code, 200) @test_context def test_machine_classes(client): "Test that someone not logged in can access the slave class mapping" rv = client.get('/machine/classes') eq_(rv.status_code, 200)
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext test_context = TestContext() @test_context def test_hello(client): rv = client.get('/slaveloan/') eq_(rv.status_code, 200) <commit_msg>Add a few tests that some endpoints load<commit_after>
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext def userperms(perms, email='me@example.com'): u = auth.HumanUser(email) u._permissions = set(perms) return u test_context = TestContext() test_context_admin = TestContext(databases=['relengapi'], user=userperms([p.slaveloan.admin])) @test_context def test_root(client): "The root of the blueprint is accessible without login" rv = client.get('/slaveloan/') eq_(rv.status_code, 200) @test_context def test_admin_ui_not_authorized(client): "Test that an unlogged in user can't access the admin ui" rv = client.get('/slaveloan/admin') eq_(rv.status_code, 301) @test_context_admin def test_admin_ui_authorized(client): "Test that an admin can access the admin ui" rv = client.get('/slaveloan/admin') eq_(rv.status_code, 200) @test_context def test_details_ui_not_authorized(client): "Test that an logged out user can't access the loan details ui" rv = client.get('/slaveloan/details/2') eq_(rv.status_code, 200) @test_context_admin def test_details_ui_authorized(client): "Test that an admin can access the loan details ui" rv = client.get('/slaveloan/details/2') eq_(rv.status_code, 200) @test_context def test_machine_classes(client): "Test that someone not logged in can access the slave class mapping" rv = client.get('/machine/classes') eq_(rv.status_code, 200)
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext test_context = TestContext() @test_context def test_hello(client): rv = client.get('/slaveloan/') eq_(rv.status_code, 200) Add a few tests that some endpoints load# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext def userperms(perms, email='me@example.com'): u = auth.HumanUser(email) u._permissions = set(perms) return u test_context = TestContext() test_context_admin = TestContext(databases=['relengapi'], user=userperms([p.slaveloan.admin])) @test_context def test_root(client): "The root of the blueprint is accessible without login" rv = client.get('/slaveloan/') eq_(rv.status_code, 200) @test_context def test_admin_ui_not_authorized(client): "Test that an unlogged in user can't access the admin ui" rv = client.get('/slaveloan/admin') eq_(rv.status_code, 301) @test_context_admin def test_admin_ui_authorized(client): "Test that an admin can access the admin ui" rv = client.get('/slaveloan/admin') eq_(rv.status_code, 200) @test_context def test_details_ui_not_authorized(client): "Test that an logged out user can't access the loan details ui" rv = client.get('/slaveloan/details/2') eq_(rv.status_code, 200) @test_context_admin def test_details_ui_authorized(client): "Test that an admin can access the loan details ui" rv = client.get('/slaveloan/details/2') eq_(rv.status_code, 200) @test_context def test_machine_classes(client): "Test that someone not logged in can access the slave class mapping" rv = client.get('/machine/classes') eq_(rv.status_code, 200)
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext test_context = TestContext() @test_context def test_hello(client): rv = client.get('/slaveloan/') eq_(rv.status_code, 200) <commit_msg>Add a few tests that some endpoints load<commit_after># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext def userperms(perms, email='me@example.com'): u = auth.HumanUser(email) u._permissions = set(perms) return u test_context = TestContext() test_context_admin = TestContext(databases=['relengapi'], user=userperms([p.slaveloan.admin])) @test_context def test_root(client): "The root of the blueprint is accessible without login" rv = client.get('/slaveloan/') eq_(rv.status_code, 200) @test_context def test_admin_ui_not_authorized(client): "Test that an unlogged in user can't access the admin ui" rv = client.get('/slaveloan/admin') eq_(rv.status_code, 301) @test_context_admin def test_admin_ui_authorized(client): "Test that an admin can access the admin ui" rv = client.get('/slaveloan/admin') eq_(rv.status_code, 200) @test_context def test_details_ui_not_authorized(client): "Test that an logged out user can't access the loan details ui" rv = client.get('/slaveloan/details/2') eq_(rv.status_code, 200) @test_context_admin def test_details_ui_authorized(client): "Test that an admin can access the loan details ui" rv = client.get('/slaveloan/details/2') eq_(rv.status_code, 200) @test_context def test_machine_classes(client): "Test that someone not logged in can access the slave class mapping" rv = client.get('/machine/classes') eq_(rv.status_code, 200)
1fa6bcbd5ab5e51f9e4250024c848933ea0911e7
examples/upsidedownternet.py
examples/upsidedownternet.py
import Image, cStringIO def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue()
import cStringIO from PIL import Image def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue()
Update another reference to PIL.
Update another reference to PIL.
Python
mit
dwfreed/mitmproxy,tdickers/mitmproxy,StevenVanAcker/mitmproxy,bazzinotti/mitmproxy,owers19856/mitmproxy,liorvh/mitmproxy,liorvh/mitmproxy,ryoqun/mitmproxy,guiquanz/mitmproxy,Endika/mitmproxy,dufferzafar/mitmproxy,dwfreed/mitmproxy,laurmurclar/mitmproxy,jvillacorta/mitmproxy,dufferzafar/mitmproxy,mosajjal/mitmproxy,dxq-git/mitmproxy,rauburtin/mitmproxy,mitmproxy/mitmproxy,byt3bl33d3r/mitmproxy,mosajjal/mitmproxy,meizhoubao/mitmproxy,Kriechi/mitmproxy,dxq-git/mitmproxy,ZeYt/mitmproxy,dwfreed/mitmproxy,macmantrl/mitmproxy,cortesi/mitmproxy,fimad/mitmproxy,macmantrl/mitmproxy,zlorb/mitmproxy,laurmurclar/mitmproxy,ujjwal96/mitmproxy,dufferzafar/mitmproxy,byt3bl33d3r/mitmproxy,ujjwal96/mitmproxy,ParthGanatra/mitmproxy,ryoqun/mitmproxy,ParthGanatra/mitmproxy,xaxa89/mitmproxy,scriptmediala/mitmproxy,onlywade/mitmproxy,onlywade/mitmproxy,0x0mar/mitmproxy,claimsmall/mitmproxy,tfeagle/mitmproxy,bltb/mitmproxy,sethp-jive/mitmproxy,guiquanz/mitmproxy,mitmproxy/mitmproxy,zbuc/mitmproxy,tfeagle/mitmproxy,noikiy/mitmproxy,syjzwjj/mitmproxy,tfeagle/mitmproxy,byt3bl33d3r/mitmproxy,scriptmediala/mitmproxy,gzzhanghao/mitmproxy,sethp-jive/mitmproxy,sethp-jive/mitmproxy,mhils/mitmproxy,azureplus/mitmproxy,dufferzafar/mitmproxy,vhaupert/mitmproxy,MatthewShao/mitmproxy,MatthewShao/mitmproxy,tekii/mitmproxy,mhils/mitmproxy,ujjwal96/mitmproxy,dweinstein/mitmproxy,owers19856/mitmproxy,tdickers/mitmproxy,tekii/mitmproxy,ADemonisis/mitmproxy,bazzinotti/mitmproxy,meizhoubao/mitmproxy,pombredanne/mitmproxy,xtso520ok/mitmproxy,guiquanz/mitmproxy,devasia1000/anti_adblock,syjzwjj/mitmproxy,Endika/mitmproxy,pombredanne/mitmproxy,xaxa89/mitmproxy,liorvh/mitmproxy,azureplus/mitmproxy,sethp-jive/mitmproxy,tekii/mitmproxy,xaxa89/mitmproxy,ZeYt/mitmproxy,elitest/mitmproxy,bltb/mitmproxy,zlorb/mitmproxy,dwfreed/mitmproxy,jvillacorta/mitmproxy,jvillacorta/mitmproxy,inscriptionweb/mitmproxy,claimsmall/mitmproxy,scriptmediala/mitmproxy,meizhoubao/mitmproxy,ParthGanatra/mitmproxy,jvillacorta/mitmproxy,xbzbing/mitmproxy,claimsmall/mitmproxy,onlywade/mitmproxy,owers19856/mitmproxy,tdickers/mitmproxy,Endika/mitmproxy,jpic/mitmproxy,Kriechi/mitmproxy,guiquanz/mitmproxy,MatthewShao/mitmproxy,StevenVanAcker/mitmproxy,zbuc/mitmproxy,0x0mar/mitmproxy,ZeYt/mitmproxy,fimad/mitmproxy,liorvh/mitmproxy,zlorb/mitmproxy,ccccccccccc/mitmproxy,ccccccccccc/mitmproxy,fimad/mitmproxy,0x0mar/mitmproxy,bltb/mitmproxy,ikoz/mitmproxy,legendtang/mitmproxy,jpic/mitmproxy,gzzhanghao/mitmproxy,devasia1000/mitmproxy,0xwindows/InfoLeak,xbzbing/mitmproxy,ADemonisis/mitmproxy,cortesi/mitmproxy,claimsmall/mitmproxy,ADemonisis/mitmproxy,byt3bl33d3r/mitmproxy,mitmproxy/mitmproxy,tekii/mitmproxy,mitmproxy/mitmproxy,rauburtin/mitmproxy,bazzinotti/mitmproxy,pombredanne/mitmproxy,vhaupert/mitmproxy,bltb/mitmproxy,azureplus/mitmproxy,devasia1000/mitmproxy,ikoz/mitmproxy,legendtang/mitmproxy,mosajjal/mitmproxy,ddworken/mitmproxy,Endika/mitmproxy,legendtang/mitmproxy,ikoz/mitmproxy,elitest/mitmproxy,laurmurclar/mitmproxy,inscriptionweb/mitmproxy,ujjwal96/mitmproxy,ADemonisis/mitmproxy,vhaupert/mitmproxy,ddworken/mitmproxy,gzzhanghao/mitmproxy,ryoqun/mitmproxy,gzzhanghao/mitmproxy,macmantrl/mitmproxy,mosajjal/mitmproxy,MatthewShao/mitmproxy,meizhoubao/mitmproxy,owers19856/mitmproxy,Fuzion24/mitmproxy,ryoqun/mitmproxy,legendtang/mitmproxy,devasia1000/mitmproxy,xbzbing/mitmproxy,mhils/mitmproxy,ZeYt/mitmproxy,devasia1000/mitmproxy,dweinstein/mitmproxy,mhils/mitmproxy,Fuzion24/mitmproxy,0xwindows/InfoLeak,zbuc/mitmproxy,ParthGanatra/mitmproxy,mhils/mitmproxy,noikiy/mitmproxy,azureplus/mitmproxy,inscriptionweb/mitmproxy,jpic/mitmproxy,cortesi/mitmproxy,xbzbing/mitmproxy,bazzinotti/mitmproxy,macmantrl/mitmproxy,zbuc/mitmproxy,noikiy/mitmproxy,vhaupert/mitmproxy,rauburtin/mitmproxy,onlywade/mitmproxy,Fuzion24/mitmproxy,Fuzion24/mitmproxy,xtso520ok/mitmproxy,ccccccccccc/mitmproxy,Kriechi/mitmproxy,noikiy/mitmproxy,ddworken/mitmproxy,0xwindows/InfoLeak,scriptmediala/mitmproxy,rauburtin/mitmproxy,tdickers/mitmproxy,syjzwjj/mitmproxy,devasia1000/anti_adblock,ikoz/mitmproxy,xtso520ok/mitmproxy,dweinstein/mitmproxy,StevenVanAcker/mitmproxy,dxq-git/mitmproxy,inscriptionweb/mitmproxy,ccccccccccc/mitmproxy,laurmurclar/mitmproxy,elitest/mitmproxy,ddworken/mitmproxy,StevenVanAcker/mitmproxy,syjzwjj/mitmproxy,devasia1000/anti_adblock,dxq-git/mitmproxy,0xwindows/InfoLeak,zlorb/mitmproxy,cortesi/mitmproxy,fimad/mitmproxy,elitest/mitmproxy,Kriechi/mitmproxy,xaxa89/mitmproxy,tfeagle/mitmproxy,pombredanne/mitmproxy,mitmproxy/mitmproxy,dweinstein/mitmproxy,jpic/mitmproxy
import Image, cStringIO def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue() Update another reference to PIL.
import cStringIO from PIL import Image def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue()
<commit_before>import Image, cStringIO def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue() <commit_msg>Update another reference to PIL.<commit_after>
import cStringIO from PIL import Image def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue()
import Image, cStringIO def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue() Update another reference to PIL.import cStringIO from PIL import Image def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue()
<commit_before>import Image, cStringIO def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue() <commit_msg>Update another reference to PIL.<commit_after>import cStringIO from PIL import Image def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue()
98bed3a2c410fc0a6fee491c35f3b49bf48c08db
arguments.py
arguments.py
import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='runme.py', ) parser.add_argument( 'port', default=HONEYPORT, help='port to start a listener on (default: %(default)s, %(type)s)', nargs='?', type=int, ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args()
import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='mfh.py', ) client_group = parser.add_mutually_exclusive_group() client_group.add_argument( '-c', action='store_true', help='launch client with on port defined in settings', ) client_group.add_argument( '--client', help='port to start a client on', metavar='PORT', nargs='?', type=int, ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args()
Add argument for launching client
Add argument for launching client Before, client would launch automatically on port you specify as a positional argument. This means you can't just not to launch the client. Now, there are 2 options: 1) -c to launch client on the port defined in settings 2) --client to specify the port explicitly So, if you want to launch just the server without client, there will be an option for that, just say what to launch.
Python
mit
Zloool/manyfaced-honeypot
import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='runme.py', ) parser.add_argument( 'port', default=HONEYPORT, help='port to start a listener on (default: %(default)s, %(type)s)', nargs='?', type=int, ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args() Add argument for launching client Before, client would launch automatically on port you specify as a positional argument. This means you can't just not to launch the client. Now, there are 2 options: 1) -c to launch client on the port defined in settings 2) --client to specify the port explicitly So, if you want to launch just the server without client, there will be an option for that, just say what to launch.
import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='mfh.py', ) client_group = parser.add_mutually_exclusive_group() client_group.add_argument( '-c', action='store_true', help='launch client with on port defined in settings', ) client_group.add_argument( '--client', help='port to start a client on', metavar='PORT', nargs='?', type=int, ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args()
<commit_before>import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='runme.py', ) parser.add_argument( 'port', default=HONEYPORT, help='port to start a listener on (default: %(default)s, %(type)s)', nargs='?', type=int, ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args() <commit_msg>Add argument for launching client Before, client would launch automatically on port you specify as a positional argument. This means you can't just not to launch the client. Now, there are 2 options: 1) -c to launch client on the port defined in settings 2) --client to specify the port explicitly So, if you want to launch just the server without client, there will be an option for that, just say what to launch.<commit_after>
import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='mfh.py', ) client_group = parser.add_mutually_exclusive_group() client_group.add_argument( '-c', action='store_true', help='launch client with on port defined in settings', ) client_group.add_argument( '--client', help='port to start a client on', metavar='PORT', nargs='?', type=int, ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args()
import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='runme.py', ) parser.add_argument( 'port', default=HONEYPORT, help='port to start a listener on (default: %(default)s, %(type)s)', nargs='?', type=int, ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args() Add argument for launching client Before, client would launch automatically on port you specify as a positional argument. This means you can't just not to launch the client. Now, there are 2 options: 1) -c to launch client on the port defined in settings 2) --client to specify the port explicitly So, if you want to launch just the server without client, there will be an option for that, just say what to launch.import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='mfh.py', ) client_group = parser.add_mutually_exclusive_group() client_group.add_argument( '-c', action='store_true', help='launch client with on port defined in settings', ) client_group.add_argument( '--client', help='port to start a client on', metavar='PORT', nargs='?', type=int, ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args()
<commit_before>import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='runme.py', ) parser.add_argument( 'port', default=HONEYPORT, help='port to start a listener on (default: %(default)s, %(type)s)', nargs='?', type=int, ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args() <commit_msg>Add argument for launching client Before, client would launch automatically on port you specify as a positional argument. This means you can't just not to launch the client. Now, there are 2 options: 1) -c to launch client on the port defined in settings 2) --client to specify the port explicitly So, if you want to launch just the server without client, there will be an option for that, just say what to launch.<commit_after>import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='mfh.py', ) client_group = parser.add_mutually_exclusive_group() client_group.add_argument( '-c', action='store_true', help='launch client with on port defined in settings', ) client_group.add_argument( '--client', help='port to start a client on', metavar='PORT', nargs='?', type=int, ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args()
1d0cd4bcc35042bf5146339a817a953e20229f30
freezer_api/tests/freezer_api_tempest_plugin/clients.py
freezer_api/tests/freezer_api_tempest_plugin/clients.py
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None, service=None): super(Manager, self).__init__(credentials, service) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None): super(Manager, self).__init__(credentials) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
Fix failed tempest tests with KeystoneV2
Fix failed tempest tests with KeystoneV2 Change-Id: I78e6a2363d006c6feec84db4d755974e6a6a81b4 Signed-off-by: Ruslan Aliev <f0566964e0d23c2ac49e399e34dbe87edb487aa1@mirantis.com>
Python
apache-2.0
openstack/freezer-api,szaher/freezer-api,szaher/freezer-api,openstack/freezer-api,openstack/freezer-api,szaher/freezer-api,openstack/freezer-api,szaher/freezer-api
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None, service=None): super(Manager, self).__init__(credentials, service) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider) Fix failed tempest tests with KeystoneV2 Change-Id: I78e6a2363d006c6feec84db4d755974e6a6a81b4 Signed-off-by: Ruslan Aliev <f0566964e0d23c2ac49e399e34dbe87edb487aa1@mirantis.com>
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None): super(Manager, self).__init__(credentials) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
<commit_before># (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None, service=None): super(Manager, self).__init__(credentials, service) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider) <commit_msg>Fix failed tempest tests with KeystoneV2 Change-Id: I78e6a2363d006c6feec84db4d755974e6a6a81b4 Signed-off-by: Ruslan Aliev <f0566964e0d23c2ac49e399e34dbe87edb487aa1@mirantis.com><commit_after>
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None): super(Manager, self).__init__(credentials) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None, service=None): super(Manager, self).__init__(credentials, service) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider) Fix failed tempest tests with KeystoneV2 Change-Id: I78e6a2363d006c6feec84db4d755974e6a6a81b4 Signed-off-by: Ruslan Aliev <f0566964e0d23c2ac49e399e34dbe87edb487aa1@mirantis.com># (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None): super(Manager, self).__init__(credentials) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
<commit_before># (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None, service=None): super(Manager, self).__init__(credentials, service) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider) <commit_msg>Fix failed tempest tests with KeystoneV2 Change-Id: I78e6a2363d006c6feec84db4d755974e6a6a81b4 Signed-off-by: Ruslan Aliev <f0566964e0d23c2ac49e399e34dbe87edb487aa1@mirantis.com><commit_after># (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None): super(Manager, self).__init__(credentials) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
7b3faffb655a3d4b44b52bd907b7e17f952a9f43
src/pve_exporter/cli.py
src/pve_exporter/cli.py
""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ if args is None: args = sys.argv if len(args) not in [1, 2, 3]: print("Usage: pve_exporter [config_file] [port]") sys.exit(1) if len(args) >= 2: config = args[1] else: config = "pve.yml" if len(args) >= 3: port = int(args[2]) else: port = 9221 start_http_server(config, port)
""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from argparse import ArgumentParser from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ parser = ArgumentParser() parser.add_argument('config', nargs='?', default='pve.yml', help='Path to configuration file (pve.yml)') parser.add_argument('port', nargs='?', type=int, default='9221', help='Port on which the exporter is listening (9221)') params = parser.parse_args(args if args is None else sys.argv[1:]) start_http_server(params.config, params.port)
Add argparse and provide usage/command line help
Add argparse and provide usage/command line help
Python
apache-2.0
znerol/prometheus-pve-exporter
""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ if args is None: args = sys.argv if len(args) not in [1, 2, 3]: print("Usage: pve_exporter [config_file] [port]") sys.exit(1) if len(args) >= 2: config = args[1] else: config = "pve.yml" if len(args) >= 3: port = int(args[2]) else: port = 9221 start_http_server(config, port) Add argparse and provide usage/command line help
""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from argparse import ArgumentParser from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ parser = ArgumentParser() parser.add_argument('config', nargs='?', default='pve.yml', help='Path to configuration file (pve.yml)') parser.add_argument('port', nargs='?', type=int, default='9221', help='Port on which the exporter is listening (9221)') params = parser.parse_args(args if args is None else sys.argv[1:]) start_http_server(params.config, params.port)
<commit_before>""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ if args is None: args = sys.argv if len(args) not in [1, 2, 3]: print("Usage: pve_exporter [config_file] [port]") sys.exit(1) if len(args) >= 2: config = args[1] else: config = "pve.yml" if len(args) >= 3: port = int(args[2]) else: port = 9221 start_http_server(config, port) <commit_msg>Add argparse and provide usage/command line help<commit_after>
""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from argparse import ArgumentParser from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ parser = ArgumentParser() parser.add_argument('config', nargs='?', default='pve.yml', help='Path to configuration file (pve.yml)') parser.add_argument('port', nargs='?', type=int, default='9221', help='Port on which the exporter is listening (9221)') params = parser.parse_args(args if args is None else sys.argv[1:]) start_http_server(params.config, params.port)
""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ if args is None: args = sys.argv if len(args) not in [1, 2, 3]: print("Usage: pve_exporter [config_file] [port]") sys.exit(1) if len(args) >= 2: config = args[1] else: config = "pve.yml" if len(args) >= 3: port = int(args[2]) else: port = 9221 start_http_server(config, port) Add argparse and provide usage/command line help""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from argparse import ArgumentParser from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ parser = ArgumentParser() parser.add_argument('config', nargs='?', default='pve.yml', help='Path to configuration file (pve.yml)') parser.add_argument('port', nargs='?', type=int, default='9221', help='Port on which the exporter is listening (9221)') params = parser.parse_args(args if args is None else sys.argv[1:]) start_http_server(params.config, params.port)
<commit_before>""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ if args is None: args = sys.argv if len(args) not in [1, 2, 3]: print("Usage: pve_exporter [config_file] [port]") sys.exit(1) if len(args) >= 2: config = args[1] else: config = "pve.yml" if len(args) >= 3: port = int(args[2]) else: port = 9221 start_http_server(config, port) <commit_msg>Add argparse and provide usage/command line help<commit_after>""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from argparse import ArgumentParser from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ parser = ArgumentParser() parser.add_argument('config', nargs='?', default='pve.yml', help='Path to configuration file (pve.yml)') parser.add_argument('port', nargs='?', type=int, default='9221', help='Port on which the exporter is listening (9221)') params = parser.parse_args(args if args is None else sys.argv[1:]) start_http_server(params.config, params.port)
b8764c10f108393b7de1332f5061bb7a8b7def25
future/disable_obsolete_builtins.py
future/disable_obsolete_builtins.py
""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, raw_input, long, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'raw_input', 'long', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname))
""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, long, raw_input, reduce, reload, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'long', 'raw_input', 'reduce', 'reload', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname))
Add reduce() and reload() to disabled builtins
Add reduce() and reload() to disabled builtins
Python
mit
PythonCharmers/python-future,krischer/python-future,michaelpacer/python-future,PythonCharmers/python-future,michaelpacer/python-future,QuLogic/python-future,krischer/python-future,QuLogic/python-future
""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, raw_input, long, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'raw_input', 'long', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname)) Add reduce() and reload() to disabled builtins
""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, long, raw_input, reduce, reload, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'long', 'raw_input', 'reduce', 'reload', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname))
<commit_before>""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, raw_input, long, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'raw_input', 'long', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname)) <commit_msg>Add reduce() and reload() to disabled builtins<commit_after>
""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, long, raw_input, reduce, reload, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'long', 'raw_input', 'reduce', 'reload', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname))
""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, raw_input, long, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'raw_input', 'long', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname)) Add reduce() and reload() to disabled builtins""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, long, raw_input, reduce, reload, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'long', 'raw_input', 'reduce', 'reload', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname))
<commit_before>""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, raw_input, long, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'raw_input', 'long', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname)) <commit_msg>Add reduce() and reload() to disabled builtins<commit_after>""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, long, raw_input, reduce, reload, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'long', 'raw_input', 'reduce', 'reload', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname))
7051e7bb98c1d1227d3beebc809498b963124a41
pal/services/joke_service.py
pal/services/joke_service.py
import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human being or, through inaction, " "allow a human being to come to harm.\n2. A robot must obey the " "orders given it by human beings, except where such orders would " "conflict with the First Law.\n3. A robot must protect its own " "existence as long as such protection does not conflict with the " "First or Second Law.", 'knock knock': "Who's there?", } def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.')
import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human being or, through inaction, " "allow a human being to come to harm.\n2. A robot must obey the " "orders given it by human beings, except where such orders would " "conflict with the First Law.\n3. A robot must protect its own " "existence as long as such protection does not conflict with the " "First or Second Law.", 'knock knock': "Who's there?", 'tom hanks': "As far as I'm concerned, Tom Hanks was in 1 movies.", } def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.')
Add Tom Hanks in a way that's actually reachable
Add Tom Hanks in a way that's actually reachable
Python
bsd-3-clause
Machyne/pal,Machyne/pal,Machyne/pal,Machyne/pal
import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human being or, through inaction, " "allow a human being to come to harm.\n2. A robot must obey the " "orders given it by human beings, except where such orders would " "conflict with the First Law.\n3. A robot must protect its own " "existence as long as such protection does not conflict with the " "First or Second Law.", 'knock knock': "Who's there?", } def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.') Add Tom Hanks in a way that's actually reachable
import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human being or, through inaction, " "allow a human being to come to harm.\n2. A robot must obey the " "orders given it by human beings, except where such orders would " "conflict with the First Law.\n3. A robot must protect its own " "existence as long as such protection does not conflict with the " "First or Second Law.", 'knock knock': "Who's there?", 'tom hanks': "As far as I'm concerned, Tom Hanks was in 1 movies.", } def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.')
<commit_before>import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human being or, through inaction, " "allow a human being to come to harm.\n2. A robot must obey the " "orders given it by human beings, except where such orders would " "conflict with the First Law.\n3. A robot must protect its own " "existence as long as such protection does not conflict with the " "First or Second Law.", 'knock knock': "Who's there?", } def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.') <commit_msg>Add Tom Hanks in a way that's actually reachable<commit_after>
import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human being or, through inaction, " "allow a human being to come to harm.\n2. A robot must obey the " "orders given it by human beings, except where such orders would " "conflict with the First Law.\n3. A robot must protect its own " "existence as long as such protection does not conflict with the " "First or Second Law.", 'knock knock': "Who's there?", 'tom hanks': "As far as I'm concerned, Tom Hanks was in 1 movies.", } def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.')
import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human being or, through inaction, " "allow a human being to come to harm.\n2. A robot must obey the " "orders given it by human beings, except where such orders would " "conflict with the First Law.\n3. A robot must protect its own " "existence as long as such protection does not conflict with the " "First or Second Law.", 'knock knock': "Who's there?", } def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.') Add Tom Hanks in a way that's actually reachableimport re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human being or, through inaction, " "allow a human being to come to harm.\n2. A robot must obey the " "orders given it by human beings, except where such orders would " "conflict with the First Law.\n3. A robot must protect its own " "existence as long as such protection does not conflict with the " "First or Second Law.", 'knock knock': "Who's there?", 'tom hanks': "As far as I'm concerned, Tom Hanks was in 1 movies.", } def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.')
<commit_before>import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human being or, through inaction, " "allow a human being to come to harm.\n2. A robot must obey the " "orders given it by human beings, except where such orders would " "conflict with the First Law.\n3. A robot must protect its own " "existence as long as such protection does not conflict with the " "First or Second Law.", 'knock knock': "Who's there?", } def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.') <commit_msg>Add Tom Hanks in a way that's actually reachable<commit_after>import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human being or, through inaction, " "allow a human being to come to harm.\n2. A robot must obey the " "orders given it by human beings, except where such orders would " "conflict with the First Law.\n3. A robot must protect its own " "existence as long as such protection does not conflict with the " "First or Second Law.", 'knock knock': "Who's there?", 'tom hanks': "As far as I'm concerned, Tom Hanks was in 1 movies.", } def applies_to_me(self, client, feature_request_type): return True def get_confidence(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return 9001 return 0 @wrap_response def go(self, params): for joke in self._JOKES: query = re.sub(r'[^a-z ]', '', params['query'].lower()) if joke in query: return self._JOKES[joke] return ('ERROR', 'Tom Hanks was in 1 movies.')
aa3f4120bf3915fd99a8ef5affb620920aeed99b
aioredlock/lock.py
aioredlock/lock.py
import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager.unlock(self) async def extend(self): await self.lock_manager.extend(self)
import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager.unlock(self) async def extend(self): await self.lock_manager.extend(self) async def release(self): await self.lock_manager.unlock(self)
Add release() method to Lock.
Add release() method to Lock.
Python
mit
joanvila/aioredlock
import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager.unlock(self) async def extend(self): await self.lock_manager.extend(self) Add release() method to Lock.
import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager.unlock(self) async def extend(self): await self.lock_manager.extend(self) async def release(self): await self.lock_manager.unlock(self)
<commit_before>import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager.unlock(self) async def extend(self): await self.lock_manager.extend(self) <commit_msg>Add release() method to Lock.<commit_after>
import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager.unlock(self) async def extend(self): await self.lock_manager.extend(self) async def release(self): await self.lock_manager.unlock(self)
import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager.unlock(self) async def extend(self): await self.lock_manager.extend(self) Add release() method to Lock.import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager.unlock(self) async def extend(self): await self.lock_manager.extend(self) async def release(self): await self.lock_manager.unlock(self)
<commit_before>import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager.unlock(self) async def extend(self): await self.lock_manager.extend(self) <commit_msg>Add release() method to Lock.<commit_after>import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager.unlock(self) async def extend(self): await self.lock_manager.extend(self) async def release(self): await self.lock_manager.unlock(self)
80cc986ebf16c59fa79c3c406e9060e49b93ad24
test/test_getavgpdb.py
test/test_getavgpdb.py
import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) from allosmod.util import check_output class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to getavgpdb""" for args in ([], [''] * 5): out = check_output(['allosmod', 'getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) out = check_output(['python', '-m', 'allosmod.getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) if __name__ == '__main__': unittest.main()
import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) test_dir = utils.set_search_paths(TOPDIR) utils.set_search_paths(TOPDIR) from allosmod.util import check_output ALIGN_ALI = """ >P1;pdb1 structureX:asite_pdb1: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* >P1;pdb2 structureX:asite_pdb2: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* >P1;pm.pdb structureX:pm.pdb: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* """ class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to getavgpdb""" for args in ([], [''] * 5): out = check_output(['allosmod', 'getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) out = check_output(['python', '-m', 'allosmod.getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) def test_simple(self): """Simple complete run of getavgpdb""" with utils.temporary_directory() as tmpdir: with open(os.path.join(tmpdir, 'align.ali'), 'w') as fh: fh.write(ALIGN_ALI) out = check_output(['allosmod', 'getavgpdb', os.path.join(test_dir, 'input', 'asite_pdb1.pdb'), os.path.join(test_dir, 'input', 'asite_pdb2.pdb'), 'pdb1', 'pdb2'], cwd=tmpdir) self.assertEqual(sorted(os.listdir(tmpdir)), ['align.ali', 'avgpdb.pdb', 'list', 'run.log']) if __name__ == '__main__': unittest.main()
Add a simple test of getavgpdb.
Add a simple test of getavgpdb.
Python
lgpl-2.1
salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib
import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) from allosmod.util import check_output class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to getavgpdb""" for args in ([], [''] * 5): out = check_output(['allosmod', 'getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) out = check_output(['python', '-m', 'allosmod.getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) if __name__ == '__main__': unittest.main() Add a simple test of getavgpdb.
import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) test_dir = utils.set_search_paths(TOPDIR) utils.set_search_paths(TOPDIR) from allosmod.util import check_output ALIGN_ALI = """ >P1;pdb1 structureX:asite_pdb1: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* >P1;pdb2 structureX:asite_pdb2: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* >P1;pm.pdb structureX:pm.pdb: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* """ class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to getavgpdb""" for args in ([], [''] * 5): out = check_output(['allosmod', 'getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) out = check_output(['python', '-m', 'allosmod.getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) def test_simple(self): """Simple complete run of getavgpdb""" with utils.temporary_directory() as tmpdir: with open(os.path.join(tmpdir, 'align.ali'), 'w') as fh: fh.write(ALIGN_ALI) out = check_output(['allosmod', 'getavgpdb', os.path.join(test_dir, 'input', 'asite_pdb1.pdb'), os.path.join(test_dir, 'input', 'asite_pdb2.pdb'), 'pdb1', 'pdb2'], cwd=tmpdir) self.assertEqual(sorted(os.listdir(tmpdir)), ['align.ali', 'avgpdb.pdb', 'list', 'run.log']) if __name__ == '__main__': unittest.main()
<commit_before>import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) from allosmod.util import check_output class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to getavgpdb""" for args in ([], [''] * 5): out = check_output(['allosmod', 'getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) out = check_output(['python', '-m', 'allosmod.getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) if __name__ == '__main__': unittest.main() <commit_msg>Add a simple test of getavgpdb.<commit_after>
import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) test_dir = utils.set_search_paths(TOPDIR) utils.set_search_paths(TOPDIR) from allosmod.util import check_output ALIGN_ALI = """ >P1;pdb1 structureX:asite_pdb1: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* >P1;pdb2 structureX:asite_pdb2: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* >P1;pm.pdb structureX:pm.pdb: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* """ class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to getavgpdb""" for args in ([], [''] * 5): out = check_output(['allosmod', 'getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) out = check_output(['python', '-m', 'allosmod.getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) def test_simple(self): """Simple complete run of getavgpdb""" with utils.temporary_directory() as tmpdir: with open(os.path.join(tmpdir, 'align.ali'), 'w') as fh: fh.write(ALIGN_ALI) out = check_output(['allosmod', 'getavgpdb', os.path.join(test_dir, 'input', 'asite_pdb1.pdb'), os.path.join(test_dir, 'input', 'asite_pdb2.pdb'), 'pdb1', 'pdb2'], cwd=tmpdir) self.assertEqual(sorted(os.listdir(tmpdir)), ['align.ali', 'avgpdb.pdb', 'list', 'run.log']) if __name__ == '__main__': unittest.main()
import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) from allosmod.util import check_output class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to getavgpdb""" for args in ([], [''] * 5): out = check_output(['allosmod', 'getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) out = check_output(['python', '-m', 'allosmod.getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) if __name__ == '__main__': unittest.main() Add a simple test of getavgpdb.import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) test_dir = utils.set_search_paths(TOPDIR) utils.set_search_paths(TOPDIR) from allosmod.util import check_output ALIGN_ALI = """ >P1;pdb1 structureX:asite_pdb1: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* >P1;pdb2 structureX:asite_pdb2: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* >P1;pm.pdb structureX:pm.pdb: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* """ class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to getavgpdb""" for args in ([], [''] * 5): out = check_output(['allosmod', 'getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) out = check_output(['python', '-m', 'allosmod.getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) def test_simple(self): """Simple complete run of getavgpdb""" with utils.temporary_directory() as tmpdir: with open(os.path.join(tmpdir, 'align.ali'), 'w') as fh: fh.write(ALIGN_ALI) out = check_output(['allosmod', 'getavgpdb', os.path.join(test_dir, 'input', 'asite_pdb1.pdb'), os.path.join(test_dir, 'input', 'asite_pdb2.pdb'), 'pdb1', 'pdb2'], cwd=tmpdir) self.assertEqual(sorted(os.listdir(tmpdir)), ['align.ali', 'avgpdb.pdb', 'list', 'run.log']) if __name__ == '__main__': unittest.main()
<commit_before>import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) from allosmod.util import check_output class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to getavgpdb""" for args in ([], [''] * 5): out = check_output(['allosmod', 'getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) out = check_output(['python', '-m', 'allosmod.getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) if __name__ == '__main__': unittest.main() <commit_msg>Add a simple test of getavgpdb.<commit_after>import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) test_dir = utils.set_search_paths(TOPDIR) utils.set_search_paths(TOPDIR) from allosmod.util import check_output ALIGN_ALI = """ >P1;pdb1 structureX:asite_pdb1: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* >P1;pdb2 structureX:asite_pdb2: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* >P1;pm.pdb structureX:pm.pdb: 1 :A:+30 :A:::-1.00:-1.00 AFVVTDNCIKCKYTDCVEVCPVDCFYEGPN* """ class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to getavgpdb""" for args in ([], [''] * 5): out = check_output(['allosmod', 'getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) out = check_output(['python', '-m', 'allosmod.getavgpdb'] + args, stderr=subprocess.STDOUT, retcode=2) def test_simple(self): """Simple complete run of getavgpdb""" with utils.temporary_directory() as tmpdir: with open(os.path.join(tmpdir, 'align.ali'), 'w') as fh: fh.write(ALIGN_ALI) out = check_output(['allosmod', 'getavgpdb', os.path.join(test_dir, 'input', 'asite_pdb1.pdb'), os.path.join(test_dir, 'input', 'asite_pdb2.pdb'), 'pdb1', 'pdb2'], cwd=tmpdir) self.assertEqual(sorted(os.listdir(tmpdir)), ['align.ali', 'avgpdb.pdb', 'list', 'run.log']) if __name__ == '__main__': unittest.main()