repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
harvard-nrg/yaxil
yaxil/bids/__init__.py
iterconfig
def iterconfig(config, scan_type): ''' Iterate over BIDS configuration file ''' if scan_type in config: for modality,scans in iter(config[scan_type].items()): for scan in scans: scan.update({ 'type': scan_type, 'modality': modality }) yield scan
python
def iterconfig(config, scan_type): ''' Iterate over BIDS configuration file ''' if scan_type in config: for modality,scans in iter(config[scan_type].items()): for scan in scans: scan.update({ 'type': scan_type, 'modality': modality }) yield scan
[ "def", "iterconfig", "(", "config", ",", "scan_type", ")", ":", "if", "scan_type", "in", "config", ":", "for", "modality", ",", "scans", "in", "iter", "(", "config", "[", "scan_type", "]", ".", "items", "(", ")", ")", ":", "for", "scan", "in", "scans...
Iterate over BIDS configuration file
[ "Iterate", "over", "BIDS", "configuration", "file" ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/bids/__init__.py#L181-L192
train
49,100
harvard-nrg/yaxil
yaxil/bids/__init__.py
rename_fmapm
def rename_fmapm(bids_base, basename): ''' Rename magnitude fieldmap file to BIDS specification ''' files = dict() for ext in ['nii.gz', 'json']: for echo in [1, 2]: fname = '{0}_e{1}.{2}'.format(basename, echo, ext) src = os.path.join(bids_base, 'fmap', fname) if os.path.exists(src): dst = src.replace( 'magnitude_e{0}'.format(echo), 'magnitude{0}'.format(echo) ) logger.debug('renaming %s to %s', src, dst) os.rename(src, dst) files[ext] = dst return files
python
def rename_fmapm(bids_base, basename): ''' Rename magnitude fieldmap file to BIDS specification ''' files = dict() for ext in ['nii.gz', 'json']: for echo in [1, 2]: fname = '{0}_e{1}.{2}'.format(basename, echo, ext) src = os.path.join(bids_base, 'fmap', fname) if os.path.exists(src): dst = src.replace( 'magnitude_e{0}'.format(echo), 'magnitude{0}'.format(echo) ) logger.debug('renaming %s to %s', src, dst) os.rename(src, dst) files[ext] = dst return files
[ "def", "rename_fmapm", "(", "bids_base", ",", "basename", ")", ":", "files", "=", "dict", "(", ")", "for", "ext", "in", "[", "'nii.gz'", ",", "'json'", "]", ":", "for", "echo", "in", "[", "1", ",", "2", "]", ":", "fname", "=", "'{0}_e{1}.{2}'", "."...
Rename magnitude fieldmap file to BIDS specification
[ "Rename", "magnitude", "fieldmap", "file", "to", "BIDS", "specification" ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/bids/__init__.py#L194-L211
train
49,101
harvard-nrg/yaxil
yaxil/bids/__init__.py
convert
def convert(input, output): ''' Run dcm2niix on input file ''' dirname = os.path.dirname(output) if not os.path.exists(dirname): os.makedirs(dirname) basename = os.path.basename(output) basename = re.sub('.nii(.gz)?', '', basename) dcm2niix = commons.which('dcm2niix') cmd = [ 'dcm2niix', '-s', 'y', '-b', 'y', '-z', 'y', '-f', basename, '-o', dirname, input ] logger.debug(cmd) sp.check_output(cmd)
python
def convert(input, output): ''' Run dcm2niix on input file ''' dirname = os.path.dirname(output) if not os.path.exists(dirname): os.makedirs(dirname) basename = os.path.basename(output) basename = re.sub('.nii(.gz)?', '', basename) dcm2niix = commons.which('dcm2niix') cmd = [ 'dcm2niix', '-s', 'y', '-b', 'y', '-z', 'y', '-f', basename, '-o', dirname, input ] logger.debug(cmd) sp.check_output(cmd)
[ "def", "convert", "(", "input", ",", "output", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "output", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")", "...
Run dcm2niix on input file
[ "Run", "dcm2niix", "on", "input", "file" ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/bids/__init__.py#L231-L251
train
49,102
Parsely/birding
src/birding/spout.py
DispatchSpout
def DispatchSpout(*a, **kw): """Factory to dispatch spout class based on config.""" spout_class_name = get_config()['Spout'] spout_class = import_name(spout_class_name, default_ns='birding.spout') return spout_class(*a, **kw)
python
def DispatchSpout(*a, **kw): """Factory to dispatch spout class based on config.""" spout_class_name = get_config()['Spout'] spout_class = import_name(spout_class_name, default_ns='birding.spout') return spout_class(*a, **kw)
[ "def", "DispatchSpout", "(", "*", "a", ",", "*", "*", "kw", ")", ":", "spout_class_name", "=", "get_config", "(", ")", "[", "'Spout'", "]", "spout_class", "=", "import_name", "(", "spout_class_name", ",", "default_ns", "=", "'birding.spout'", ")", "return", ...
Factory to dispatch spout class based on config.
[ "Factory", "to", "dispatch", "spout", "class", "based", "on", "config", "." ]
c7f6eee56424234e361b1a455595de202e744dac
https://github.com/Parsely/birding/blob/c7f6eee56424234e361b1a455595de202e744dac/src/birding/spout.py#L11-L15
train
49,103
harvard-nrg/yaxil
yaxil/commons/__init__.py
which
def which(x): ''' Same as which command on Linux ''' for p in os.environ.get('PATH').split(os.pathsep): p = os.path.join(p, x) if os.path.exists(p): return os.path.abspath(p) return None
python
def which(x): ''' Same as which command on Linux ''' for p in os.environ.get('PATH').split(os.pathsep): p = os.path.join(p, x) if os.path.exists(p): return os.path.abspath(p) return None
[ "def", "which", "(", "x", ")", ":", "for", "p", "in", "os", ".", "environ", ".", "get", "(", "'PATH'", ")", ".", "split", "(", "os", ".", "pathsep", ")", ":", "p", "=", "os", ".", "path", ".", "join", "(", "p", ",", "x", ")", "if", "os", ...
Same as which command on Linux
[ "Same", "as", "which", "command", "on", "Linux" ]
af594082258e62d1904d6e6841fce0bb5c0bf309
https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/commons/__init__.py#L83-L91
train
49,104
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/tasks.py
serve
def serve(context: Context, port=8000, browsersync_port=3000, browsersync_ui_port=3030): """ Starts a development server with auto-building and live-reload """ try: from watchdog.observers import Observer except ImportError: context.pip_command('install', 'watchdog>0.8,<0.9') from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class RebuildHandler(PatternMatchingEventHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._patterns = ['*.js', '*.scss', '*.html'] self._ignore_directories = True self.builder = None self.rebuild_javascript = threading.Event() self.rebuild_stylesheets = threading.Event() def on_any_event(self, event): if self.builder: self.builder.cancel() extension = event.src_path.rsplit('.', 1)[-1].lower() if extension == 'js': self.rebuild_javascript.set() elif extension == 'scss': self.rebuild_stylesheets.set() self.builder = threading.Timer(3, self.rebuild) self.builder.start() def rebuild(self): if self.rebuild_javascript.is_set(): self.rebuild_javascript.clear() context.debug('Triggering javascript build') bundle_javascript(context) if self.rebuild_stylesheets.is_set(): self.rebuild_stylesheets.clear() context.debug('Triggering stylesheet build') bundle_stylesheets(context) context.debug('Reloading browsers') context.node_tool('browser-sync', 'reload', '--port=%s' % browsersync_port) context.info('Watching sources') observer = Observer() paths = [ context.app.common_asset_source_path, context.app.asset_source_path, context.app.common_templates_path, context.app.templates_path, ] handler = RebuildHandler() for path in paths: observer.schedule(handler, path, recursive=True) observer.setDaemon(True) observer.start() context.info('Starting browser sync') browsersync_args = ['start', '--host=localhost', '--no-open', '--logLevel', {0: 'silent', 1: 'info', 2: 'debug'}[context.verbosity], '--port=%s' % browsersync_port, '--proxy=localhost:%s' % port, '--ui-port=%s' % browsersync_ui_port] browsersync = functools.partial(context.node_tool, 'browser-sync', *browsersync_args) threading.Thread(target=browsersync, daemon=True).start() context.info('Starting web server') return start(context, port=port)
python
def serve(context: Context, port=8000, browsersync_port=3000, browsersync_ui_port=3030): """ Starts a development server with auto-building and live-reload """ try: from watchdog.observers import Observer except ImportError: context.pip_command('install', 'watchdog>0.8,<0.9') from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class RebuildHandler(PatternMatchingEventHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._patterns = ['*.js', '*.scss', '*.html'] self._ignore_directories = True self.builder = None self.rebuild_javascript = threading.Event() self.rebuild_stylesheets = threading.Event() def on_any_event(self, event): if self.builder: self.builder.cancel() extension = event.src_path.rsplit('.', 1)[-1].lower() if extension == 'js': self.rebuild_javascript.set() elif extension == 'scss': self.rebuild_stylesheets.set() self.builder = threading.Timer(3, self.rebuild) self.builder.start() def rebuild(self): if self.rebuild_javascript.is_set(): self.rebuild_javascript.clear() context.debug('Triggering javascript build') bundle_javascript(context) if self.rebuild_stylesheets.is_set(): self.rebuild_stylesheets.clear() context.debug('Triggering stylesheet build') bundle_stylesheets(context) context.debug('Reloading browsers') context.node_tool('browser-sync', 'reload', '--port=%s' % browsersync_port) context.info('Watching sources') observer = Observer() paths = [ context.app.common_asset_source_path, context.app.asset_source_path, context.app.common_templates_path, context.app.templates_path, ] handler = RebuildHandler() for path in paths: observer.schedule(handler, path, recursive=True) observer.setDaemon(True) observer.start() context.info('Starting browser sync') browsersync_args = ['start', '--host=localhost', '--no-open', '--logLevel', {0: 'silent', 1: 'info', 2: 'debug'}[context.verbosity], '--port=%s' % browsersync_port, '--proxy=localhost:%s' % port, '--ui-port=%s' % browsersync_ui_port] browsersync = functools.partial(context.node_tool, 'browser-sync', *browsersync_args) threading.Thread(target=browsersync, daemon=True).start() context.info('Starting web server') return start(context, port=port)
[ "def", "serve", "(", "context", ":", "Context", ",", "port", "=", "8000", ",", "browsersync_port", "=", "3000", ",", "browsersync_ui_port", "=", "3030", ")", ":", "try", ":", "from", "watchdog", ".", "observers", "import", "Observer", "except", "ImportError"...
Starts a development server with auto-building and live-reload
[ "Starts", "a", "development", "server", "with", "auto", "-", "building", "and", "live", "-", "reload" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L34-L101
train
49,105
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/tasks.py
create_build_paths
def create_build_paths(context: Context): """ Creates directories needed for build outputs """ paths = [context.app.asset_build_path, context.app.screenshots_build_path, context.app.collected_assets_path] for path in filter(None, paths): os.makedirs(path, exist_ok=True)
python
def create_build_paths(context: Context): """ Creates directories needed for build outputs """ paths = [context.app.asset_build_path, context.app.screenshots_build_path, context.app.collected_assets_path] for path in filter(None, paths): os.makedirs(path, exist_ok=True)
[ "def", "create_build_paths", "(", "context", ":", "Context", ")", ":", "paths", "=", "[", "context", ".", "app", ".", "asset_build_path", ",", "context", ".", "app", ".", "screenshots_build_path", ",", "context", ".", "app", ".", "collected_assets_path", "]", ...
Creates directories needed for build outputs
[ "Creates", "directories", "needed", "for", "build", "outputs" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L121-L127
train
49,106
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/tasks.py
node_dependencies
def node_dependencies(context: Context): """ Updates node.js dependencies """ args = ['--loglevel', {0: 'silent', 1: 'warn', 2: 'info'}[context.verbosity]] if not context.use_colour: args.append('--color false') args.append('install') return context.shell('npm', *args)
python
def node_dependencies(context: Context): """ Updates node.js dependencies """ args = ['--loglevel', {0: 'silent', 1: 'warn', 2: 'info'}[context.verbosity]] if not context.use_colour: args.append('--color false') args.append('install') return context.shell('npm', *args)
[ "def", "node_dependencies", "(", "context", ":", "Context", ")", ":", "args", "=", "[", "'--loglevel'", ",", "{", "0", ":", "'silent'", ",", "1", ":", "'warn'", ",", "2", ":", "'info'", "}", "[", "context", ".", "verbosity", "]", "]", "if", "not", ...
Updates node.js dependencies
[ "Updates", "node", ".", "js", "dependencies" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L151-L159
train
49,107
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/tasks.py
local_docker
def local_docker(context: Context): """ Runs the app in a docker container; for local development only! Once performed, `docker-compose up` can be used directly """ output = io.StringIO() with contextlib.redirect_stdout(output): context.shell('docker-machine', 'ip', 'default') host_machine_ip = output.getvalue().strip() or socket.gethostbyname(socket.gethostname()) args = () if context.verbosity > 1: args += ('--verbose',) args += ('up', '--build', '--remove-orphans') if not context.use_colour: args += ('--no-color',) context.shell('docker-compose', *args, environment={'HOST_MACHINE_IP': host_machine_ip})
python
def local_docker(context: Context): """ Runs the app in a docker container; for local development only! Once performed, `docker-compose up` can be used directly """ output = io.StringIO() with contextlib.redirect_stdout(output): context.shell('docker-machine', 'ip', 'default') host_machine_ip = output.getvalue().strip() or socket.gethostbyname(socket.gethostname()) args = () if context.verbosity > 1: args += ('--verbose',) args += ('up', '--build', '--remove-orphans') if not context.use_colour: args += ('--no-color',) context.shell('docker-compose', *args, environment={'HOST_MACHINE_IP': host_machine_ip})
[ "def", "local_docker", "(", "context", ":", "Context", ")", ":", "output", "=", "io", ".", "StringIO", "(", ")", "with", "contextlib", ".", "redirect_stdout", "(", "output", ")", ":", "context", ".", "shell", "(", "'docker-machine'", ",", "'ip'", ",", "'...
Runs the app in a docker container; for local development only! Once performed, `docker-compose up` can be used directly
[ "Runs", "the", "app", "in", "a", "docker", "container", ";", "for", "local", "development", "only!", "Once", "performed", "docker", "-", "compose", "up", "can", "be", "used", "directly" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L180-L195
train
49,108
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/tasks.py
lint_javascript
def lint_javascript(context: Context): """ Tests javascript for code and style errors """ args = [ '--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'eslintrc.json'), '--format', 'stylish', ] if context.verbosity == 0: args.append('--quiet') if not context.use_colour: args.append('--no-color') args.append(context.app.javascript_source_path) return context.node_tool('eslint', *args)
python
def lint_javascript(context: Context): """ Tests javascript for code and style errors """ args = [ '--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'eslintrc.json'), '--format', 'stylish', ] if context.verbosity == 0: args.append('--quiet') if not context.use_colour: args.append('--no-color') args.append(context.app.javascript_source_path) return context.node_tool('eslint', *args)
[ "def", "lint_javascript", "(", "context", ":", "Context", ")", ":", "args", "=", "[", "'--config'", ",", "os", ".", "path", ".", "join", "(", "context", ".", "app", ".", "common_templates_path", ",", "'mtp_common'", ",", "'build_tasks'", ",", "'eslintrc.json...
Tests javascript for code and style errors
[ "Tests", "javascript", "for", "code", "and", "style", "errors" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L249-L262
train
49,109
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/tasks.py
lint_stylesheets
def lint_stylesheets(context: Context): """ Tests stylesheets for code and style errors """ args = [ '--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'sass-lint.yml'), '--format', 'stylish', '--syntax', 'scss', ] if context.verbosity > 1: args.append('--verbose') args.append(os.path.join(context.app.scss_source_path, '**', '*.scss')) return context.node_tool('sass-lint', *args)
python
def lint_stylesheets(context: Context): """ Tests stylesheets for code and style errors """ args = [ '--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'sass-lint.yml'), '--format', 'stylish', '--syntax', 'scss', ] if context.verbosity > 1: args.append('--verbose') args.append(os.path.join(context.app.scss_source_path, '**', '*.scss')) return context.node_tool('sass-lint', *args)
[ "def", "lint_stylesheets", "(", "context", ":", "Context", ")", ":", "args", "=", "[", "'--config'", ",", "os", ".", "path", ".", "join", "(", "context", ".", "app", ".", "common_templates_path", ",", "'mtp_common'", ",", "'build_tasks'", ",", "'sass-lint.ym...
Tests stylesheets for code and style errors
[ "Tests", "stylesheets", "for", "code", "and", "style", "errors" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L266-L278
train
49,110
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/tasks.py
govuk_template
def govuk_template(context: Context, version='0.23.0', replace_fonts=True): """ Installs GOV.UK template """ if FileSet(os.path.join(context.app.govuk_templates_path, 'base.html')): # NB: check is only on main template and not the assets included return url = 'https://github.com/alphagov/govuk_template/releases' \ '/download/v{0}/django_govuk_template-{0}.tgz'.format(version) try: context.shell('curl --location %(silent)s --output govuk_template.tgz %(url)s' % { 'silent': '--silent' if context.verbosity == 0 else '', 'url': url, }) context.shell('tar xzf govuk_template.tgz ./govuk_template') rsync_flags = '-avz' if context.verbosity == 2 else '-az' context.shell('rsync %s govuk_template/static/ %s/' % (rsync_flags, context.app.asset_build_path)) context.shell('rsync %s govuk_template/templates/ %s/' % (rsync_flags, context.app.templates_path)) finally: context.shell('rm -rf govuk_template.tgz ./govuk_template') if replace_fonts: # govuk_template includes .eot font files for IE, but they load relative to current URL not the stylesheet # this option removes these files so common's fonts-ie8.css override is used context.shell('rm -rf %s/stylesheets/fonts-ie8.css' ' %s/stylesheets/fonts/' % (context.app.asset_build_path, context.app.asset_build_path))
python
def govuk_template(context: Context, version='0.23.0', replace_fonts=True): """ Installs GOV.UK template """ if FileSet(os.path.join(context.app.govuk_templates_path, 'base.html')): # NB: check is only on main template and not the assets included return url = 'https://github.com/alphagov/govuk_template/releases' \ '/download/v{0}/django_govuk_template-{0}.tgz'.format(version) try: context.shell('curl --location %(silent)s --output govuk_template.tgz %(url)s' % { 'silent': '--silent' if context.verbosity == 0 else '', 'url': url, }) context.shell('tar xzf govuk_template.tgz ./govuk_template') rsync_flags = '-avz' if context.verbosity == 2 else '-az' context.shell('rsync %s govuk_template/static/ %s/' % (rsync_flags, context.app.asset_build_path)) context.shell('rsync %s govuk_template/templates/ %s/' % (rsync_flags, context.app.templates_path)) finally: context.shell('rm -rf govuk_template.tgz ./govuk_template') if replace_fonts: # govuk_template includes .eot font files for IE, but they load relative to current URL not the stylesheet # this option removes these files so common's fonts-ie8.css override is used context.shell('rm -rf %s/stylesheets/fonts-ie8.css' ' %s/stylesheets/fonts/' % (context.app.asset_build_path, context.app.asset_build_path))
[ "def", "govuk_template", "(", "context", ":", "Context", ",", "version", "=", "'0.23.0'", ",", "replace_fonts", "=", "True", ")", ":", "if", "FileSet", "(", "os", ".", "path", ".", "join", "(", "context", ".", "app", ".", "govuk_templates_path", ",", "'b...
Installs GOV.UK template
[ "Installs", "GOV", ".", "UK", "template" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L289-L313
train
49,111
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/tasks.py
additional_assets
def additional_assets(context: Context): """ Collects assets from GOV.UK frontend toolkit """ rsync_flags = '-avz' if context.verbosity == 2 else '-az' for path in context.app.additional_asset_paths: context.shell('rsync %s %s %s/' % (rsync_flags, path, context.app.asset_build_path))
python
def additional_assets(context: Context): """ Collects assets from GOV.UK frontend toolkit """ rsync_flags = '-avz' if context.verbosity == 2 else '-az' for path in context.app.additional_asset_paths: context.shell('rsync %s %s %s/' % (rsync_flags, path, context.app.asset_build_path))
[ "def", "additional_assets", "(", "context", ":", "Context", ")", ":", "rsync_flags", "=", "'-avz'", "if", "context", ".", "verbosity", "==", "2", "else", "'-az'", "for", "path", "in", "context", ".", "app", ".", "additional_asset_paths", ":", "context", ".",...
Collects assets from GOV.UK frontend toolkit
[ "Collects", "assets", "from", "GOV", ".", "UK", "frontend", "toolkit" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L317-L323
train
49,112
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/tasks.py
precompile_python_code
def precompile_python_code(context: Context): """ Pre-compiles python modules """ from compileall import compile_dir kwargs = {} if context.verbosity < 2: kwargs['quiet'] = True compile_dir(context.app.django_app_name, **kwargs)
python
def precompile_python_code(context: Context): """ Pre-compiles python modules """ from compileall import compile_dir kwargs = {} if context.verbosity < 2: kwargs['quiet'] = True compile_dir(context.app.django_app_name, **kwargs)
[ "def", "precompile_python_code", "(", "context", ":", "Context", ")", ":", "from", "compileall", "import", "compile_dir", "kwargs", "=", "{", "}", "if", "context", ".", "verbosity", "<", "2", ":", "kwargs", "[", "'quiet'", "]", "=", "True", "compile_dir", ...
Pre-compiles python modules
[ "Pre", "-", "compiles", "python", "modules" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L344-L353
train
49,113
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/tasks.py
make_messages
def make_messages(context: Context, javascript=False, fuzzy=False): """ Collects text into translation source files """ kwargs = { 'all': True, 'keep_pot': True, 'no_wrap': True, } if fuzzy: kwargs['allow_fuzzy'] = True if javascript: kwargs.update(domain='djangojs', ignore_patterns=['*.bundle.js']) with in_dir(context.app.django_app_name): return context.management_command('makemessages', **kwargs)
python
def make_messages(context: Context, javascript=False, fuzzy=False): """ Collects text into translation source files """ kwargs = { 'all': True, 'keep_pot': True, 'no_wrap': True, } if fuzzy: kwargs['allow_fuzzy'] = True if javascript: kwargs.update(domain='djangojs', ignore_patterns=['*.bundle.js']) with in_dir(context.app.django_app_name): return context.management_command('makemessages', **kwargs)
[ "def", "make_messages", "(", "context", ":", "Context", ",", "javascript", "=", "False", ",", "fuzzy", "=", "False", ")", ":", "kwargs", "=", "{", "'all'", ":", "True", ",", "'keep_pot'", ":", "True", ",", "'no_wrap'", ":", "True", ",", "}", "if", "f...
Collects text into translation source files
[ "Collects", "text", "into", "translation", "source", "files" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L357-L371
train
49,114
koreyou/word_embedding_loader
word_embedding_loader/word_embedding.py
classify_format
def classify_format(f): """ Determine the format of word embedding file by their content. This operation only looks at the first two lines and does not check the sanity of input file. Args: f (Filelike): Returns: class """ l0, l1 = _get_two_lines(f) if loader.glove.check_valid(l0, l1): return _glove elif loader.word2vec_text.check_valid(l0, l1): return _word2vec_text elif loader.word2vec_bin.check_valid(l0, l1): return _word2vec_bin else: raise OSError(b"Invalid format")
python
def classify_format(f): """ Determine the format of word embedding file by their content. This operation only looks at the first two lines and does not check the sanity of input file. Args: f (Filelike): Returns: class """ l0, l1 = _get_two_lines(f) if loader.glove.check_valid(l0, l1): return _glove elif loader.word2vec_text.check_valid(l0, l1): return _word2vec_text elif loader.word2vec_bin.check_valid(l0, l1): return _word2vec_bin else: raise OSError(b"Invalid format")
[ "def", "classify_format", "(", "f", ")", ":", "l0", ",", "l1", "=", "_get_two_lines", "(", "f", ")", "if", "loader", ".", "glove", ".", "check_valid", "(", "l0", ",", "l1", ")", ":", "return", "_glove", "elif", "loader", ".", "word2vec_text", ".", "c...
Determine the format of word embedding file by their content. This operation only looks at the first two lines and does not check the sanity of input file. Args: f (Filelike): Returns: class
[ "Determine", "the", "format", "of", "word", "embedding", "file", "by", "their", "content", ".", "This", "operation", "only", "looks", "at", "the", "first", "two", "lines", "and", "does", "not", "check", "the", "sanity", "of", "input", "file", "." ]
1bc123f1a8bea12646576dcd768dae3ecea39c06
https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/word_embedding.py#L63-L84
train
49,115
koreyou/word_embedding_loader
word_embedding_loader/word_embedding.py
WordEmbedding.load
def load(cls, path, vocab=None, dtype=np.float32, max_vocab=None, format=None, binary=False): """ Load pretrained word embedding from a file. Args: path (str): Path of file to load. vocab (str or None): Path to vocabulary file created by word2vec with ``-save-vocab <file>`` option. If vocab is given, :py:attr:`~vectors` and :py:attr:`~vocab` is ordered in descending order of frequency. dtype (numpy.dtype): Element data type to use for the array. max_vocab (int): Number of vocabulary to read. format (str or None): Format of the file. ``'word2vec'`` for file that was implemented in `word2vec <https://code.google.com/archive/p/word2vec/>`_, by Mikolov et al.. ``'glove'`` for file that was implemented in `GloVe <https://nlp.stanford.edu/projects/glove/>`_, Global Vectors for Word Representation, by Jeffrey Pennington, Richard Socher, Christopher D. Manning from Stanford NLP group. If ``None`` is given, the format is guessed from the content. binary (bool): Load file as binary file as in word embedding file created by `word2vec <https://code.google.com/archive/p/word2vec/>`_ with ``-binary 1`` option. If ``format`` is ``'glove'`` or ``None``, this argument is simply ignored Returns: :class:`~word_embedding_loader.word_embedding.WordEmbedding` """ freqs = None if vocab is not None: with open(vocab, mode='rb') as f: freqs = loader.vocab.load_vocab(f) # Create vocab from freqs # [:None] gives all the list member vocab = {k: i for i, (k, v) in enumerate( sorted(six.iteritems(freqs), key=lambda k_v: k_v[1], reverse=True)[:max_vocab])} with open(path, mode='rb') as f: if format is None: mod = classify_format(f) else: mod = _select_module(format, binary) with open(path, mode='rb') as f: if vocab is not None: arr = mod.loader.load_with_vocab(f, vocab, dtype=dtype) v = vocab else: arr, v = mod.loader.load(f, max_vocab=max_vocab, dtype=dtype) obj = cls(arr, v, freqs) obj._load_cond = mod return obj
python
def load(cls, path, vocab=None, dtype=np.float32, max_vocab=None, format=None, binary=False): """ Load pretrained word embedding from a file. Args: path (str): Path of file to load. vocab (str or None): Path to vocabulary file created by word2vec with ``-save-vocab <file>`` option. If vocab is given, :py:attr:`~vectors` and :py:attr:`~vocab` is ordered in descending order of frequency. dtype (numpy.dtype): Element data type to use for the array. max_vocab (int): Number of vocabulary to read. format (str or None): Format of the file. ``'word2vec'`` for file that was implemented in `word2vec <https://code.google.com/archive/p/word2vec/>`_, by Mikolov et al.. ``'glove'`` for file that was implemented in `GloVe <https://nlp.stanford.edu/projects/glove/>`_, Global Vectors for Word Representation, by Jeffrey Pennington, Richard Socher, Christopher D. Manning from Stanford NLP group. If ``None`` is given, the format is guessed from the content. binary (bool): Load file as binary file as in word embedding file created by `word2vec <https://code.google.com/archive/p/word2vec/>`_ with ``-binary 1`` option. If ``format`` is ``'glove'`` or ``None``, this argument is simply ignored Returns: :class:`~word_embedding_loader.word_embedding.WordEmbedding` """ freqs = None if vocab is not None: with open(vocab, mode='rb') as f: freqs = loader.vocab.load_vocab(f) # Create vocab from freqs # [:None] gives all the list member vocab = {k: i for i, (k, v) in enumerate( sorted(six.iteritems(freqs), key=lambda k_v: k_v[1], reverse=True)[:max_vocab])} with open(path, mode='rb') as f: if format is None: mod = classify_format(f) else: mod = _select_module(format, binary) with open(path, mode='rb') as f: if vocab is not None: arr = mod.loader.load_with_vocab(f, vocab, dtype=dtype) v = vocab else: arr, v = mod.loader.load(f, max_vocab=max_vocab, dtype=dtype) obj = cls(arr, v, freqs) obj._load_cond = mod return obj
[ "def", "load", "(", "cls", ",", "path", ",", "vocab", "=", "None", ",", "dtype", "=", "np", ".", "float32", ",", "max_vocab", "=", "None", ",", "format", "=", "None", ",", "binary", "=", "False", ")", ":", "freqs", "=", "None", "if", "vocab", "is...
Load pretrained word embedding from a file. Args: path (str): Path of file to load. vocab (str or None): Path to vocabulary file created by word2vec with ``-save-vocab <file>`` option. If vocab is given, :py:attr:`~vectors` and :py:attr:`~vocab` is ordered in descending order of frequency. dtype (numpy.dtype): Element data type to use for the array. max_vocab (int): Number of vocabulary to read. format (str or None): Format of the file. ``'word2vec'`` for file that was implemented in `word2vec <https://code.google.com/archive/p/word2vec/>`_, by Mikolov et al.. ``'glove'`` for file that was implemented in `GloVe <https://nlp.stanford.edu/projects/glove/>`_, Global Vectors for Word Representation, by Jeffrey Pennington, Richard Socher, Christopher D. Manning from Stanford NLP group. If ``None`` is given, the format is guessed from the content. binary (bool): Load file as binary file as in word embedding file created by `word2vec <https://code.google.com/archive/p/word2vec/>`_ with ``-binary 1`` option. If ``format`` is ``'glove'`` or ``None``, this argument is simply ignored Returns: :class:`~word_embedding_loader.word_embedding.WordEmbedding`
[ "Load", "pretrained", "word", "embedding", "from", "a", "file", "." ]
1bc123f1a8bea12646576dcd768dae3ecea39c06
https://github.com/koreyou/word_embedding_loader/blob/1bc123f1a8bea12646576dcd768dae3ecea39c06/word_embedding_loader/word_embedding.py#L129-L184
train
49,116
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/paths.py
paths_for_shell
def paths_for_shell(paths, separator=' '): """ Converts a list of paths for use in shell commands """ paths = filter(None, paths) paths = map(shlex.quote, paths) if separator is None: return paths return separator.join(paths)
python
def paths_for_shell(paths, separator=' '): """ Converts a list of paths for use in shell commands """ paths = filter(None, paths) paths = map(shlex.quote, paths) if separator is None: return paths return separator.join(paths)
[ "def", "paths_for_shell", "(", "paths", ",", "separator", "=", "' '", ")", ":", "paths", "=", "filter", "(", "None", ",", "paths", ")", "paths", "=", "map", "(", "shlex", ".", "quote", ",", "paths", ")", "if", "separator", "is", "None", ":", "return"...
Converts a list of paths for use in shell commands
[ "Converts", "a", "list", "of", "paths", "for", "use", "in", "shell", "commands" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/paths.py#L19-L27
train
49,117
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
Tasks.register
def register(self, *dependencies, default=False, hidden=False, ignore_return_code=False): """ Decorates a callable to turn it into a task """ def outer(func): task = Task(func, *dependencies, default=default, hidden=hidden, ignore_return_code=ignore_return_code) overidden_task = self._tasks.pop(task.name, None) if overidden_task: self._overidden_tasks[task.name].append(overidden_task) self[task.name] = task return task return outer
python
def register(self, *dependencies, default=False, hidden=False, ignore_return_code=False): """ Decorates a callable to turn it into a task """ def outer(func): task = Task(func, *dependencies, default=default, hidden=hidden, ignore_return_code=ignore_return_code) overidden_task = self._tasks.pop(task.name, None) if overidden_task: self._overidden_tasks[task.name].append(overidden_task) self[task.name] = task return task return outer
[ "def", "register", "(", "self", ",", "*", "dependencies", ",", "default", "=", "False", ",", "hidden", "=", "False", ",", "ignore_return_code", "=", "False", ")", ":", "def", "outer", "(", "func", ")", ":", "task", "=", "Task", "(", "func", ",", "*",...
Decorates a callable to turn it into a task
[ "Decorates", "a", "callable", "to", "turn", "it", "into", "a", "task" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L56-L69
train
49,118
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
Tasks.lookup_task
def lookup_task(self, task): """ Looks up a task by name or by callable """ if isinstance(task, str): try: return self[task] except KeyError: pass raise TaskError('Unknown task %s' % task)
python
def lookup_task(self, task): """ Looks up a task by name or by callable """ if isinstance(task, str): try: return self[task] except KeyError: pass raise TaskError('Unknown task %s' % task)
[ "def", "lookup_task", "(", "self", ",", "task", ")", ":", "if", "isinstance", "(", "task", ",", "str", ")", ":", "try", ":", "return", "self", "[", "task", "]", "except", "KeyError", ":", "pass", "raise", "TaskError", "(", "'Unknown task %s'", "%", "ta...
Looks up a task by name or by callable
[ "Looks", "up", "a", "task", "by", "name", "or", "by", "callable" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L71-L80
train
49,119
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
Tasks.get_default_task
def get_default_task(self): """ Returns the default task if there is only one """ default_tasks = list(filter(lambda task: task.default, self.values())) if len(default_tasks) == 1: return default_tasks[0]
python
def get_default_task(self): """ Returns the default task if there is only one """ default_tasks = list(filter(lambda task: task.default, self.values())) if len(default_tasks) == 1: return default_tasks[0]
[ "def", "get_default_task", "(", "self", ")", ":", "default_tasks", "=", "list", "(", "filter", "(", "lambda", "task", ":", "task", ".", "default", ",", "self", ".", "values", "(", ")", ")", ")", "if", "len", "(", "default_tasks", ")", "==", "1", ":",...
Returns the default task if there is only one
[ "Returns", "the", "default", "task", "if", "there", "is", "only", "one" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L82-L88
train
49,120
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
ParameterGroup.from_callable
def from_callable(cls, func, ignored_parameters=set()): """ Reads a function or method signature to produce a set of parameters """ group = cls() signature = inspect.signature(func) for parameter in signature.parameters.values(): if parameter.name.startswith('_') or parameter.name in ignored_parameters: continue parameter = Parameter.from_callable_parameter(parameter) group[parameter.name] = parameter return group
python
def from_callable(cls, func, ignored_parameters=set()): """ Reads a function or method signature to produce a set of parameters """ group = cls() signature = inspect.signature(func) for parameter in signature.parameters.values(): if parameter.name.startswith('_') or parameter.name in ignored_parameters: continue parameter = Parameter.from_callable_parameter(parameter) group[parameter.name] = parameter return group
[ "def", "from_callable", "(", "cls", ",", "func", ",", "ignored_parameters", "=", "set", "(", ")", ")", ":", "group", "=", "cls", "(", ")", "signature", "=", "inspect", ".", "signature", "(", "func", ")", "for", "parameter", "in", "signature", ".", "par...
Reads a function or method signature to produce a set of parameters
[ "Reads", "a", "function", "or", "method", "signature", "to", "produce", "a", "set", "of", "parameters" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L137-L148
train
49,121
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
ParameterGroup.from_mapping
def from_mapping(cls, mapping): """ Produces a set of parameters from a mapping """ group = cls() for name, value in mapping.items(): if name.startswith('_'): continue group[name] = Parameter( name=name, value=value, constraint=Parameter.constraint_from_type(value), ) return group
python
def from_mapping(cls, mapping): """ Produces a set of parameters from a mapping """ group = cls() for name, value in mapping.items(): if name.startswith('_'): continue group[name] = Parameter( name=name, value=value, constraint=Parameter.constraint_from_type(value), ) return group
[ "def", "from_mapping", "(", "cls", ",", "mapping", ")", ":", "group", "=", "cls", "(", ")", "for", "name", ",", "value", "in", "mapping", ".", "items", "(", ")", ":", "if", "name", ".", "startswith", "(", "'_'", ")", ":", "continue", "group", "[", ...
Produces a set of parameters from a mapping
[ "Produces", "a", "set", "of", "parameters", "from", "a", "mapping" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L151-L164
train
49,122
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
ParameterGroup.to_dict
def to_dict(self): """ Converts the set of parameters into a dict """ return dict((parameter.name, parameter.value) for parameter in self.values())
python
def to_dict(self): """ Converts the set of parameters into a dict """ return dict((parameter.name, parameter.value) for parameter in self.values())
[ "def", "to_dict", "(", "self", ")", ":", "return", "dict", "(", "(", "parameter", ".", "name", ",", "parameter", ".", "value", ")", "for", "parameter", "in", "self", ".", "values", "(", ")", ")" ]
Converts the set of parameters into a dict
[ "Converts", "the", "set", "of", "parameters", "into", "a", "dict" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L189-L193
train
49,123
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
ParameterGroup.consume_arguments
def consume_arguments(self, argument_list): """ Takes arguments from a list while there are parameters that can accept them """ while True: argument_count = len(argument_list) for parameter in self.values(): argument_list = parameter.consume_arguments(argument_list) if len(argument_list) == argument_count: return argument_list
python
def consume_arguments(self, argument_list): """ Takes arguments from a list while there are parameters that can accept them """ while True: argument_count = len(argument_list) for parameter in self.values(): argument_list = parameter.consume_arguments(argument_list) if len(argument_list) == argument_count: return argument_list
[ "def", "consume_arguments", "(", "self", ",", "argument_list", ")", ":", "while", "True", ":", "argument_count", "=", "len", "(", "argument_list", ")", "for", "parameter", "in", "self", ".", "values", "(", ")", ":", "argument_list", "=", "parameter", ".", ...
Takes arguments from a list while there are parameters that can accept them
[ "Takes", "arguments", "from", "a", "list", "while", "there", "are", "parameters", "that", "can", "accept", "them" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L195-L204
train
49,124
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
ParameterGroup.update_from
def update_from(self, mapping): """ Updates the set of parameters from a mapping for keys that already exist """ for key, value in mapping.items(): if key in self: if isinstance(value, Parameter): value = value.value self[key].value = value
python
def update_from(self, mapping): """ Updates the set of parameters from a mapping for keys that already exist """ for key, value in mapping.items(): if key in self: if isinstance(value, Parameter): value = value.value self[key].value = value
[ "def", "update_from", "(", "self", ",", "mapping", ")", ":", "for", "key", ",", "value", "in", "mapping", ".", "items", "(", ")", ":", "if", "key", "in", "self", ":", "if", "isinstance", "(", "value", ",", "Parameter", ")", ":", "value", "=", "valu...
Updates the set of parameters from a mapping for keys that already exist
[ "Updates", "the", "set", "of", "parameters", "from", "a", "mapping", "for", "keys", "that", "already", "exist" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L206-L214
train
49,125
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
Parameter.from_callable_parameter
def from_callable_parameter(cls, parameter): """ Produces a parameter from a function or method """ if parameter.kind == parameter.KEYWORD_ONLY or \ parameter.kind == parameter.POSITIONAL_OR_KEYWORD and parameter.default is not parameter.empty: if parameter.annotation is not parameter.empty: constraint = parameter.annotation else: constraint = Parameter.constraint_from_type(parameter.default) return cls( name=parameter.name, value=parameter.default, constraint=constraint, ) else: raise ParameterError('Only keyword parameters are supported')
python
def from_callable_parameter(cls, parameter): """ Produces a parameter from a function or method """ if parameter.kind == parameter.KEYWORD_ONLY or \ parameter.kind == parameter.POSITIONAL_OR_KEYWORD and parameter.default is not parameter.empty: if parameter.annotation is not parameter.empty: constraint = parameter.annotation else: constraint = Parameter.constraint_from_type(parameter.default) return cls( name=parameter.name, value=parameter.default, constraint=constraint, ) else: raise ParameterError('Only keyword parameters are supported')
[ "def", "from_callable_parameter", "(", "cls", ",", "parameter", ")", ":", "if", "parameter", ".", "kind", "==", "parameter", ".", "KEYWORD_ONLY", "or", "parameter", ".", "kind", "==", "parameter", ".", "POSITIONAL_OR_KEYWORD", "and", "parameter", ".", "default",...
Produces a parameter from a function or method
[ "Produces", "a", "parameter", "from", "a", "function", "or", "method" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L223-L239
train
49,126
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
Parameter.constraint_from_type
def constraint_from_type(cls, value): """ Returns the constraint callable given a value """ if value is None: return None value_type = type(value) if value_type in (str, int, bool): return value_type raise ParameterError('Parameter type cannot be %s' % value_type)
python
def constraint_from_type(cls, value): """ Returns the constraint callable given a value """ if value is None: return None value_type = type(value) if value_type in (str, int, bool): return value_type raise ParameterError('Parameter type cannot be %s' % value_type)
[ "def", "constraint_from_type", "(", "cls", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "value_type", "=", "type", "(", "value", ")", "if", "value_type", "in", "(", "str", ",", "int", ",", "bool", ")", ":", "return", "v...
Returns the constraint callable given a value
[ "Returns", "the", "constraint", "callable", "given", "a", "value" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L242-L251
train
49,127
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
Parameter.constraint_from_choices
def constraint_from_choices(cls, value_type: type, choices: collections.Sequence): """ Returns a constraint callable based on choices of a given type """ choices_str = ', '.join(map(str, choices)) def constraint(value): value = value_type(value) if value not in choices: raise ParameterError('Argument must be one of %s' % choices_str) return value constraint.__name__ = 'choices_%s' % value_type.__name__ constraint.__doc__ = 'choice of %s' % choices_str return constraint
python
def constraint_from_choices(cls, value_type: type, choices: collections.Sequence): """ Returns a constraint callable based on choices of a given type """ choices_str = ', '.join(map(str, choices)) def constraint(value): value = value_type(value) if value not in choices: raise ParameterError('Argument must be one of %s' % choices_str) return value constraint.__name__ = 'choices_%s' % value_type.__name__ constraint.__doc__ = 'choice of %s' % choices_str return constraint
[ "def", "constraint_from_choices", "(", "cls", ",", "value_type", ":", "type", ",", "choices", ":", "collections", ".", "Sequence", ")", ":", "choices_str", "=", "', '", ".", "join", "(", "map", "(", "str", ",", "choices", ")", ")", "def", "constraint", "...
Returns a constraint callable based on choices of a given type
[ "Returns", "a", "constraint", "callable", "based", "on", "choices", "of", "a", "given", "type" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L254-L268
train
49,128
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
Parameter.arg_name
def arg_name(self): """ Returns the name of the parameter as a command line flag """ if self.constraint is bool and self.value: return '--no-%s' % self.name.replace('_', '-') return '--%s' % self.name.replace('_', '-')
python
def arg_name(self): """ Returns the name of the parameter as a command line flag """ if self.constraint is bool and self.value: return '--no-%s' % self.name.replace('_', '-') return '--%s' % self.name.replace('_', '-')
[ "def", "arg_name", "(", "self", ")", ":", "if", "self", ".", "constraint", "is", "bool", "and", "self", ".", "value", ":", "return", "'--no-%s'", "%", "self", ".", "name", ".", "replace", "(", "'_'", ",", "'-'", ")", "return", "'--%s'", "%", "self", ...
Returns the name of the parameter as a command line flag
[ "Returns", "the", "name", "of", "the", "parameter", "as", "a", "command", "line", "flag" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L280-L286
train
49,129
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
Parameter.consume_arguments
def consume_arguments(self, argument_list): """ Takes arguments from a list while this parameter can accept them """ if len(argument_list) == 0: return [] if argument_list[0] == self.arg_name: argument_list = argument_list[1:] if self.constraint is bool: self.value = not self.value else: try: value = argument_list.pop(0) except IndexError: raise ParameterError('Argument %s expects a value' % self.arg_name) self.value = value return argument_list
python
def consume_arguments(self, argument_list): """ Takes arguments from a list while this parameter can accept them """ if len(argument_list) == 0: return [] if argument_list[0] == self.arg_name: argument_list = argument_list[1:] if self.constraint is bool: self.value = not self.value else: try: value = argument_list.pop(0) except IndexError: raise ParameterError('Argument %s expects a value' % self.arg_name) self.value = value return argument_list
[ "def", "consume_arguments", "(", "self", ",", "argument_list", ")", ":", "if", "len", "(", "argument_list", ")", "==", "0", ":", "return", "[", "]", "if", "argument_list", "[", "0", "]", "==", "self", ".", "arg_name", ":", "argument_list", "=", "argument...
Takes arguments from a list while this parameter can accept them
[ "Takes", "arguments", "from", "a", "list", "while", "this", "parameter", "can", "accept", "them" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L314-L330
train
49,130
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
Context.pip_command
def pip_command(self, command, *args): """ Runs a pip command """ try: from pip._internal import main as pip_main except ImportError: from pip import main as pip_main args = [command] + list(args) if self.verbosity == 0: args.insert(0, '--quiet') elif self.verbosity == 2: args.insert(0, '--verbose') return pip_main(args)
python
def pip_command(self, command, *args): """ Runs a pip command """ try: from pip._internal import main as pip_main except ImportError: from pip import main as pip_main args = [command] + list(args) if self.verbosity == 0: args.insert(0, '--quiet') elif self.verbosity == 2: args.insert(0, '--verbose') return pip_main(args)
[ "def", "pip_command", "(", "self", ",", "command", ",", "*", "args", ")", ":", "try", ":", "from", "pip", ".", "_internal", "import", "main", "as", "pip_main", "except", "ImportError", ":", "from", "pip", "import", "main", "as", "pip_main", "args", "=", ...
Runs a pip command
[ "Runs", "a", "pip", "command" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L418-L432
train
49,131
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
Context.shell
def shell(self, command, *args, environment=None): """ Runs a shell command """ command += ' ' + ' '.join(args) command = command.strip() self.debug(self.yellow_style('$ %s' % command)) env = self.env.copy() env.update(environment or {}) return subprocess.call(command, shell=True, env=env)
python
def shell(self, command, *args, environment=None): """ Runs a shell command """ command += ' ' + ' '.join(args) command = command.strip() self.debug(self.yellow_style('$ %s' % command)) env = self.env.copy() env.update(environment or {}) return subprocess.call(command, shell=True, env=env)
[ "def", "shell", "(", "self", ",", "command", ",", "*", "args", ",", "environment", "=", "None", ")", ":", "command", "+=", "' '", "+", "' '", ".", "join", "(", "args", ")", "command", "=", "command", ".", "strip", "(", ")", "self", ".", "debug", ...
Runs a shell command
[ "Runs", "a", "shell", "command" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L434-L443
train
49,132
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
Context.management_command
def management_command(self, command, *args, **kwargs): """ Runs a Django management command """ self.setup_django() if 'verbosity' not in kwargs: kwargs['verbosity'] = self.verbosity if not self.use_colour: kwargs['no_color'] = False self.debug(self.yellow_style('$ manage.py %s' % command)) return call_command(command, *args, **kwargs)
python
def management_command(self, command, *args, **kwargs): """ Runs a Django management command """ self.setup_django() if 'verbosity' not in kwargs: kwargs['verbosity'] = self.verbosity if not self.use_colour: kwargs['no_color'] = False self.debug(self.yellow_style('$ manage.py %s' % command)) return call_command(command, *args, **kwargs)
[ "def", "management_command", "(", "self", ",", "command", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "setup_django", "(", ")", "if", "'verbosity'", "not", "in", "kwargs", ":", "kwargs", "[", "'verbosity'", "]", "=", "self", ".", ...
Runs a Django management command
[ "Runs", "a", "Django", "management", "command" ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L451-L461
train
49,133
ministryofjustice/money-to-prisoners-common
mtp_common/auth/__init__.py
login
def login(request, user): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: session_key = request.session[SESSION_KEY] if session_key != user.pk or ( session_auth_hash and request.session.get(HASH_SESSION_KEY) != session_auth_hash): # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: request.session.cycle_key() request.session[SESSION_KEY] = user.pk request.session[BACKEND_SESSION_KEY] = user.backend request.session[USER_DATA_SESSION_KEY] = user.user_data request.session[HASH_SESSION_KEY] = session_auth_hash update_token_in_session(request.session, user.token) if hasattr(request, 'user'): request.user = user rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user)
python
def login(request, user): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: session_key = request.session[SESSION_KEY] if session_key != user.pk or ( session_auth_hash and request.session.get(HASH_SESSION_KEY) != session_auth_hash): # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: request.session.cycle_key() request.session[SESSION_KEY] = user.pk request.session[BACKEND_SESSION_KEY] = user.backend request.session[USER_DATA_SESSION_KEY] = user.user_data request.session[HASH_SESSION_KEY] = session_auth_hash update_token_in_session(request.session, user.token) if hasattr(request, 'user'): request.user = user rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user)
[ "def", "login", "(", "request", ",", "user", ")", ":", "session_auth_hash", "=", "''", "if", "user", "is", "None", ":", "user", "=", "request", ".", "user", "if", "hasattr", "(", "user", ",", "'get_session_auth_hash'", ")", ":", "session_auth_hash", "=", ...
Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in.
[ "Persist", "a", "user", "id", "and", "a", "backend", "in", "the", "request", ".", "This", "way", "a", "user", "doesn", "t", "have", "to", "reauthenticate", "on", "every", "request", ".", "Note", "that", "data", "set", "during", "the", "anonymous", "sessi...
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/__init__.py#L22-L55
train
49,134
ministryofjustice/money-to-prisoners-common
mtp_common/auth/__init__.py
get_user
def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `MojAnonymousUser` is returned. """ user = None try: user_id = request.session[SESSION_KEY] token = request.session[AUTH_TOKEN_SESSION_KEY] user_data = request.session[USER_DATA_SESSION_KEY] backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id, token, user_data) # Verify the session if hasattr(user, 'get_session_auth_hash'): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: request.session.flush() user = None return user or MojAnonymousUser()
python
def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `MojAnonymousUser` is returned. """ user = None try: user_id = request.session[SESSION_KEY] token = request.session[AUTH_TOKEN_SESSION_KEY] user_data = request.session[USER_DATA_SESSION_KEY] backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id, token, user_data) # Verify the session if hasattr(user, 'get_session_auth_hash'): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: request.session.flush() user = None return user or MojAnonymousUser()
[ "def", "get_user", "(", "request", ")", ":", "user", "=", "None", "try", ":", "user_id", "=", "request", ".", "session", "[", "SESSION_KEY", "]", "token", "=", "request", ".", "session", "[", "AUTH_TOKEN_SESSION_KEY", "]", "user_data", "=", "request", ".",...
Returns the user model instance associated with the given request session. If no user is retrieved an instance of `MojAnonymousUser` is returned.
[ "Returns", "the", "user", "model", "instance", "associated", "with", "the", "given", "request", "session", ".", "If", "no", "user", "is", "retrieved", "an", "instance", "of", "MojAnonymousUser", "is", "returned", "." ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/__init__.py#L58-L86
train
49,135
ministryofjustice/money-to-prisoners-common
mtp_common/auth/__init__.py
logout
def logout(request): """ Removes the authenticated user's ID from the request and flushes their session data. """ # Dispatch the signal before the user is logged out so the receivers have a # chance to find out *who* logged out. user = getattr(request, 'user', None) if hasattr(user, 'is_authenticated') and not user.is_authenticated: user = None user_logged_out.send(sender=user.__class__, request=request, user=user) # remember language choice saved to session language = request.session.get(LANGUAGE_SESSION_KEY) request.session.flush() if language is not None: request.session[LANGUAGE_SESSION_KEY] = language if hasattr(request, 'user'): request.user = MojAnonymousUser()
python
def logout(request): """ Removes the authenticated user's ID from the request and flushes their session data. """ # Dispatch the signal before the user is logged out so the receivers have a # chance to find out *who* logged out. user = getattr(request, 'user', None) if hasattr(user, 'is_authenticated') and not user.is_authenticated: user = None user_logged_out.send(sender=user.__class__, request=request, user=user) # remember language choice saved to session language = request.session.get(LANGUAGE_SESSION_KEY) request.session.flush() if language is not None: request.session[LANGUAGE_SESSION_KEY] = language if hasattr(request, 'user'): request.user = MojAnonymousUser()
[ "def", "logout", "(", "request", ")", ":", "# Dispatch the signal before the user is logged out so the receivers have a", "# chance to find out *who* logged out.", "user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "if", "hasattr", "(", "user", ",", ...
Removes the authenticated user's ID from the request and flushes their session data.
[ "Removes", "the", "authenticated", "user", "s", "ID", "from", "the", "request", "and", "flushes", "their", "session", "data", "." ]
33c43a2912cb990d9148da7c8718f480f07d90a1
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/auth/__init__.py#L96-L117
train
49,136
Jaymon/prom
prom/model.py
Orm.fields
def fields(self): """ return all the fields and their raw values for this Orm instance. This property returns a dict with the field names and their current values if you want to control the values for outputting to an api, use .jsonable() """ return {k:getattr(self, k, None) for k in self.schema.fields}
python
def fields(self): """ return all the fields and their raw values for this Orm instance. This property returns a dict with the field names and their current values if you want to control the values for outputting to an api, use .jsonable() """ return {k:getattr(self, k, None) for k in self.schema.fields}
[ "def", "fields", "(", "self", ")", ":", "return", "{", "k", ":", "getattr", "(", "self", ",", "k", ",", "None", ")", "for", "k", "in", "self", ".", "schema", ".", "fields", "}" ]
return all the fields and their raw values for this Orm instance. This property returns a dict with the field names and their current values if you want to control the values for outputting to an api, use .jsonable()
[ "return", "all", "the", "fields", "and", "their", "raw", "values", "for", "this", "Orm", "instance", ".", "This", "property", "returns", "a", "dict", "with", "the", "field", "names", "and", "their", "current", "values" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L144-L151
train
49,137
Jaymon/prom
prom/model.py
Orm.create
def create(cls, fields=None, **fields_kwargs): """ create an instance of cls with the passed in fields and set it into the db fields -- dict -- field_name keys, with their respective values **fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also """ # NOTE -- you cannot use hydrate/populate here because populate alters modified fields instance = cls(fields, **fields_kwargs) instance.save() return instance
python
def create(cls, fields=None, **fields_kwargs): """ create an instance of cls with the passed in fields and set it into the db fields -- dict -- field_name keys, with their respective values **fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also """ # NOTE -- you cannot use hydrate/populate here because populate alters modified fields instance = cls(fields, **fields_kwargs) instance.save() return instance
[ "def", "create", "(", "cls", ",", "fields", "=", "None", ",", "*", "*", "fields_kwargs", ")", ":", "# NOTE -- you cannot use hydrate/populate here because populate alters modified fields", "instance", "=", "cls", "(", "fields", ",", "*", "*", "fields_kwargs", ")", "...
create an instance of cls with the passed in fields and set it into the db fields -- dict -- field_name keys, with their respective values **fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also
[ "create", "an", "instance", "of", "cls", "with", "the", "passed", "in", "fields", "and", "set", "it", "into", "the", "db" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L182-L192
train
49,138
Jaymon/prom
prom/model.py
Orm.populate
def populate(self, fields=None, **fields_kwargs): """take the passed in fields, combine them with missing fields that should be there and then run all those through appropriate methods to hydrate this orm. The method replaces cls.hydrate() since it was becoming hard to understand what was going on with all these methods that did things just a little bit different. This is used to completely set all the fields of self. If you just want to set certain fields, you can use the submethod _populate :param fields: dict, the fields in a dict :param **fields_kwargs: dict, if you would like to pass the fields as key=val this picks those up and combines them with fields """ # this will run all the fields of the Orm, not just the fields in fields # dict, another name would be hydrate pop_fields = {} fields = self.make_dict(fields, fields_kwargs) for k in self.schema.fields.keys(): pop_fields[k] = fields.get(k, None) self._populate(pop_fields)
python
def populate(self, fields=None, **fields_kwargs): """take the passed in fields, combine them with missing fields that should be there and then run all those through appropriate methods to hydrate this orm. The method replaces cls.hydrate() since it was becoming hard to understand what was going on with all these methods that did things just a little bit different. This is used to completely set all the fields of self. If you just want to set certain fields, you can use the submethod _populate :param fields: dict, the fields in a dict :param **fields_kwargs: dict, if you would like to pass the fields as key=val this picks those up and combines them with fields """ # this will run all the fields of the Orm, not just the fields in fields # dict, another name would be hydrate pop_fields = {} fields = self.make_dict(fields, fields_kwargs) for k in self.schema.fields.keys(): pop_fields[k] = fields.get(k, None) self._populate(pop_fields)
[ "def", "populate", "(", "self", ",", "fields", "=", "None", ",", "*", "*", "fields_kwargs", ")", ":", "# this will run all the fields of the Orm, not just the fields in fields", "# dict, another name would be hydrate", "pop_fields", "=", "{", "}", "fields", "=", "self", ...
take the passed in fields, combine them with missing fields that should be there and then run all those through appropriate methods to hydrate this orm. The method replaces cls.hydrate() since it was becoming hard to understand what was going on with all these methods that did things just a little bit different. This is used to completely set all the fields of self. If you just want to set certain fields, you can use the submethod _populate :param fields: dict, the fields in a dict :param **fields_kwargs: dict, if you would like to pass the fields as key=val this picks those up and combines them with fields
[ "take", "the", "passed", "in", "fields", "combine", "them", "with", "missing", "fields", "that", "should", "be", "there", "and", "then", "run", "all", "those", "through", "appropriate", "methods", "to", "hydrate", "this", "orm", "." ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L225-L249
train
49,139
Jaymon/prom
prom/model.py
Orm._populate
def _populate(self, fields): """this runs all the fields through their iget methods to mimic them freshly coming out of the db, then resets modified :param fields: dict, the fields that were passed in """ schema = self.schema for k, v in fields.items(): fields[k] = schema.fields[k].iget(self, v) self.modify(fields) self.reset_modified()
python
def _populate(self, fields): """this runs all the fields through their iget methods to mimic them freshly coming out of the db, then resets modified :param fields: dict, the fields that were passed in """ schema = self.schema for k, v in fields.items(): fields[k] = schema.fields[k].iget(self, v) self.modify(fields) self.reset_modified()
[ "def", "_populate", "(", "self", ",", "fields", ")", ":", "schema", "=", "self", ".", "schema", "for", "k", ",", "v", "in", "fields", ".", "items", "(", ")", ":", "fields", "[", "k", "]", "=", "schema", ".", "fields", "[", "k", "]", ".", "iget"...
this runs all the fields through their iget methods to mimic them freshly coming out of the db, then resets modified :param fields: dict, the fields that were passed in
[ "this", "runs", "all", "the", "fields", "through", "their", "iget", "methods", "to", "mimic", "them", "freshly", "coming", "out", "of", "the", "db", "then", "resets", "modified" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L251-L262
train
49,140
Jaymon/prom
prom/model.py
Orm.depopulate
def depopulate(self, is_update): """Get all the fields that need to be saved :param is_udpate: bool, True if update query, False if insert :returns: dict, key is field_name and val is the field value to be saved """ fields = {} schema = self.schema for k, field in schema.fields.items(): is_modified = k in self.modified_fields orig_v = getattr(self, k) v = field.iset( self, orig_v, is_update=is_update, is_modified=is_modified ) if is_modified or v is not None: if is_update and field.is_pk() and v == orig_v: continue else: fields[k] = v if not is_update: for field_name in schema.required_fields.keys(): if field_name not in fields: raise KeyError("Missing required field {}".format(field_name)) return fields
python
def depopulate(self, is_update): """Get all the fields that need to be saved :param is_udpate: bool, True if update query, False if insert :returns: dict, key is field_name and val is the field value to be saved """ fields = {} schema = self.schema for k, field in schema.fields.items(): is_modified = k in self.modified_fields orig_v = getattr(self, k) v = field.iset( self, orig_v, is_update=is_update, is_modified=is_modified ) if is_modified or v is not None: if is_update and field.is_pk() and v == orig_v: continue else: fields[k] = v if not is_update: for field_name in schema.required_fields.keys(): if field_name not in fields: raise KeyError("Missing required field {}".format(field_name)) return fields
[ "def", "depopulate", "(", "self", ",", "is_update", ")", ":", "fields", "=", "{", "}", "schema", "=", "self", ".", "schema", "for", "k", ",", "field", "in", "schema", ".", "fields", ".", "items", "(", ")", ":", "is_modified", "=", "k", "in", "self"...
Get all the fields that need to be saved :param is_udpate: bool, True if update query, False if insert :returns: dict, key is field_name and val is the field value to be saved
[ "Get", "all", "the", "fields", "that", "need", "to", "be", "saved" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L264-L294
train
49,141
Jaymon/prom
prom/model.py
Orm.insert
def insert(self): """persist the field values of this orm""" ret = True schema = self.schema fields = self.depopulate(False) q = self.query q.set_fields(fields) pk = q.insert() if pk: fields = q.fields fields[schema.pk.name] = pk self._populate(fields) else: ret = False return ret
python
def insert(self): """persist the field values of this orm""" ret = True schema = self.schema fields = self.depopulate(False) q = self.query q.set_fields(fields) pk = q.insert() if pk: fields = q.fields fields[schema.pk.name] = pk self._populate(fields) else: ret = False return ret
[ "def", "insert", "(", "self", ")", ":", "ret", "=", "True", "schema", "=", "self", ".", "schema", "fields", "=", "self", ".", "depopulate", "(", "False", ")", "q", "=", "self", ".", "query", "q", ".", "set_fields", "(", "fields", ")", "pk", "=", ...
persist the field values of this orm
[ "persist", "the", "field", "values", "of", "this", "orm" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L296-L314
train
49,142
Jaymon/prom
prom/model.py
Orm.update
def update(self): """re-persist the updated field values of this orm that has a primary key""" ret = True fields = self.depopulate(True) q = self.query q.set_fields(fields) pk = self.pk if pk: q.is_field(self.schema.pk.name, pk) else: raise ValueError("You cannot update without a primary key") if q.update(): fields = q.fields self._populate(fields) else: ret = False return ret
python
def update(self): """re-persist the updated field values of this orm that has a primary key""" ret = True fields = self.depopulate(True) q = self.query q.set_fields(fields) pk = self.pk if pk: q.is_field(self.schema.pk.name, pk) else: raise ValueError("You cannot update without a primary key") if q.update(): fields = q.fields self._populate(fields) else: ret = False return ret
[ "def", "update", "(", "self", ")", ":", "ret", "=", "True", "fields", "=", "self", ".", "depopulate", "(", "True", ")", "q", "=", "self", ".", "query", "q", ".", "set_fields", "(", "fields", ")", "pk", "=", "self", ".", "pk", "if", "pk", ":", "...
re-persist the updated field values of this orm that has a primary key
[ "re", "-", "persist", "the", "updated", "field", "values", "of", "this", "orm", "that", "has", "a", "primary", "key" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L316-L337
train
49,143
Jaymon/prom
prom/model.py
Orm.save
def save(self): """ persist the fields in this object into the db, this will update if _id is set, otherwise it will insert see also -- .insert(), .update() """ ret = False # we will only use the primary key if it hasn't been modified pk = None if self.schema.pk.name not in self.modified_fields: pk = self.pk if pk: ret = self.update() else: ret = self.insert() return ret
python
def save(self): """ persist the fields in this object into the db, this will update if _id is set, otherwise it will insert see also -- .insert(), .update() """ ret = False # we will only use the primary key if it hasn't been modified pk = None if self.schema.pk.name not in self.modified_fields: pk = self.pk if pk: ret = self.update() else: ret = self.insert() return ret
[ "def", "save", "(", "self", ")", ":", "ret", "=", "False", "# we will only use the primary key if it hasn't been modified", "pk", "=", "None", "if", "self", ".", "schema", ".", "pk", ".", "name", "not", "in", "self", ".", "modified_fields", ":", "pk", "=", "...
persist the fields in this object into the db, this will update if _id is set, otherwise it will insert see also -- .insert(), .update()
[ "persist", "the", "fields", "in", "this", "object", "into", "the", "db", "this", "will", "update", "if", "_id", "is", "set", "otherwise", "it", "will", "insert" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L340-L359
train
49,144
Jaymon/prom
prom/model.py
Orm.delete
def delete(self): """delete the object from the db if pk is set""" ret = False q = self.query pk = self.pk if pk: pk_name = self.schema.pk.name self.query.is_field(pk_name, pk).delete() setattr(self, pk_name, None) # mark all the fields that still exist as modified self.reset_modified() for field_name in self.schema.fields: if getattr(self, field_name, None) != None: self.modified_fields.add(field_name) ret = True return ret
python
def delete(self): """delete the object from the db if pk is set""" ret = False q = self.query pk = self.pk if pk: pk_name = self.schema.pk.name self.query.is_field(pk_name, pk).delete() setattr(self, pk_name, None) # mark all the fields that still exist as modified self.reset_modified() for field_name in self.schema.fields: if getattr(self, field_name, None) != None: self.modified_fields.add(field_name) ret = True return ret
[ "def", "delete", "(", "self", ")", ":", "ret", "=", "False", "q", "=", "self", ".", "query", "pk", "=", "self", ".", "pk", "if", "pk", ":", "pk_name", "=", "self", ".", "schema", ".", "pk", ".", "name", "self", ".", "query", ".", "is_field", "(...
delete the object from the db if pk is set
[ "delete", "the", "object", "from", "the", "db", "if", "pk", "is", "set" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L361-L379
train
49,145
Jaymon/prom
prom/model.py
Orm.reset_modified
def reset_modified(self): """ reset field modification tracking this is handy for when you are loading a new Orm with the results from a query and you don't want set() to do anything, you can Orm(**fields) and then orm.reset_modified() to clear all the passed in fields from the modified list """ self.modified_fields = set() # compensate for us not having knowledge of certain fields changing for field_name, field in self.schema.normal_fields.items(): if isinstance(field, ObjectField): self.modified_fields.add(field_name)
python
def reset_modified(self): """ reset field modification tracking this is handy for when you are loading a new Orm with the results from a query and you don't want set() to do anything, you can Orm(**fields) and then orm.reset_modified() to clear all the passed in fields from the modified list """ self.modified_fields = set() # compensate for us not having knowledge of certain fields changing for field_name, field in self.schema.normal_fields.items(): if isinstance(field, ObjectField): self.modified_fields.add(field_name)
[ "def", "reset_modified", "(", "self", ")", ":", "self", ".", "modified_fields", "=", "set", "(", ")", "# compensate for us not having knowledge of certain fields changing", "for", "field_name", ",", "field", "in", "self", ".", "schema", ".", "normal_fields", ".", "i...
reset field modification tracking this is handy for when you are loading a new Orm with the results from a query and you don't want set() to do anything, you can Orm(**fields) and then orm.reset_modified() to clear all the passed in fields from the modified list
[ "reset", "field", "modification", "tracking" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L385-L398
train
49,146
Jaymon/prom
prom/model.py
Orm.modify
def modify(self, fields=None, **fields_kwargs): """update the fields of this instance with the values in dict fields this should rarely be messed with, if you would like to manipulate the fields you should override _modify() :param fields: dict, the fields in a dict :param **fields_kwargs: dict, if you would like to pass the fields as key=val this picks those up and combines them with fields :returns: set, all the names of the fields that were modified """ modified_fields = set() fields = self.make_dict(fields, fields_kwargs) fields = self._modify(fields) for field_name, field_val in fields.items(): in_schema = field_name in self.schema.fields if in_schema: setattr(self, field_name, field_val) modified_fields.add(field_name) return modified_fields
python
def modify(self, fields=None, **fields_kwargs): """update the fields of this instance with the values in dict fields this should rarely be messed with, if you would like to manipulate the fields you should override _modify() :param fields: dict, the fields in a dict :param **fields_kwargs: dict, if you would like to pass the fields as key=val this picks those up and combines them with fields :returns: set, all the names of the fields that were modified """ modified_fields = set() fields = self.make_dict(fields, fields_kwargs) fields = self._modify(fields) for field_name, field_val in fields.items(): in_schema = field_name in self.schema.fields if in_schema: setattr(self, field_name, field_val) modified_fields.add(field_name) return modified_fields
[ "def", "modify", "(", "self", ",", "fields", "=", "None", ",", "*", "*", "fields_kwargs", ")", ":", "modified_fields", "=", "set", "(", ")", "fields", "=", "self", ".", "make_dict", "(", "fields", ",", "fields_kwargs", ")", "fields", "=", "self", ".", ...
update the fields of this instance with the values in dict fields this should rarely be messed with, if you would like to manipulate the fields you should override _modify() :param fields: dict, the fields in a dict :param **fields_kwargs: dict, if you would like to pass the fields as key=val this picks those up and combines them with fields :returns: set, all the names of the fields that were modified
[ "update", "the", "fields", "of", "this", "instance", "with", "the", "values", "in", "dict", "fields" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L400-L420
train
49,147
Jaymon/prom
prom/model.py
Orm.jsonable
def jsonable(self, *args, **options): """ return a public version of this instance that can be jsonified Note that this does not return _id, _created, _updated, the reason why is because lots of times you have a different name for _id (like if it is a user object, then you might want to call it user_id instead of _id) and I didn't want to make assumptions note 2, I'm not crazy about the name, but I didn't like to_dict() and pretty much any time I need to convert the object to a dict is for json, I kind of like dictify() though, but I've already used this method in so many places """ d = {} for field_name, field in self.schema.normal_fields.items(): field_val = getattr(self, field_name, None) field_val = field.jsonable(self, field_val) if field_val is not None: d[field_name] = field_val return d
python
def jsonable(self, *args, **options): """ return a public version of this instance that can be jsonified Note that this does not return _id, _created, _updated, the reason why is because lots of times you have a different name for _id (like if it is a user object, then you might want to call it user_id instead of _id) and I didn't want to make assumptions note 2, I'm not crazy about the name, but I didn't like to_dict() and pretty much any time I need to convert the object to a dict is for json, I kind of like dictify() though, but I've already used this method in so many places """ d = {} for field_name, field in self.schema.normal_fields.items(): field_val = getattr(self, field_name, None) field_val = field.jsonable(self, field_val) if field_val is not None: d[field_name] = field_val return d
[ "def", "jsonable", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "d", "=", "{", "}", "for", "field_name", ",", "field", "in", "self", ".", "schema", ".", "normal_fields", ".", "items", "(", ")", ":", "field_val", "=", "getattr"...
return a public version of this instance that can be jsonified Note that this does not return _id, _created, _updated, the reason why is because lots of times you have a different name for _id (like if it is a user object, then you might want to call it user_id instead of _id) and I didn't want to make assumptions note 2, I'm not crazy about the name, but I didn't like to_dict() and pretty much any time I need to convert the object to a dict is for json, I kind of like dictify() though, but I've already used this method in so many places
[ "return", "a", "public", "version", "of", "this", "instance", "that", "can", "be", "jsonified" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/model.py#L466-L486
train
49,148
guaix-ucm/pyemir
emirdrp/tools/merge2images.py
merge2images
def merge2images(hdu1, hdu2, debugplot): """Merge 2 EMIR images, averaging the common region. Parameters ---------- hdu1 : HDUList object Input image #1. hdu2 : HDUList object Input image #2. debugplot : int Determines whether intermediate computations and/or plots are displayed. The valid codes are defined in numina.array.display.pause_debugplot. Returns ------- image_merged : HDUList object Output image. """ # check image dimensions image_header = hdu1[0].header image_header_ = hdu2[0].header # naxis = image_header['naxis'] naxis_ = image_header_['naxis'] if naxis != naxis_: raise ValueError('Incompatible NAXIS values: {}, {}'.format( naxis, naxis_ )) naxis1 = image_header['naxis1'] naxis1_ = image_header_['naxis1'] if naxis1 != naxis1_: raise ValueError('Incompatible NAXIS1 values: {}, {}'.format( naxis1, naxis1_ )) if naxis == 1: naxis2 = 1 elif naxis == 2: naxis2 = image_header['naxis2'] naxis2_ = image_header_['naxis2'] if naxis2 != naxis2_: raise ValueError('Incompatible NAXIS2 values: {}, {}'.format( naxis2, naxis2_ )) else: raise ValueError('Unexpected NAXIS value: {}'.format(naxis)) # initialize output array image2d_merged = np.zeros((naxis2, naxis1)) # main loop data1 = hdu1[0].data data2 = hdu2[0].data for i in range(naxis2): sp1 = data1[i, :] sp2 = data2[i, :] jmin1, jmax1 = find_pix_borders(sp1, sought_value=0) jmin2, jmax2 = find_pix_borders(sp2, sought_value=0) image2d_merged[i, :] = sp1 + sp2 useful1 = (jmin1 != -1) and (jmax1 != naxis1) useful2 = (jmin2 != -1) and (jmax2 != naxis1) if useful1 and useful2: jmineff = max(jmin1, jmin2) jmaxeff = min(jmax1, jmax2) image2d_merged[i, jmineff:(jmaxeff+1)] /= 2 # return result image_merged = fits.PrimaryHDU(data=image2d_merged.astype(np.float32), header=image_header) return image_merged
python
def merge2images(hdu1, hdu2, debugplot): """Merge 2 EMIR images, averaging the common region. Parameters ---------- hdu1 : HDUList object Input image #1. hdu2 : HDUList object Input image #2. debugplot : int Determines whether intermediate computations and/or plots are displayed. The valid codes are defined in numina.array.display.pause_debugplot. Returns ------- image_merged : HDUList object Output image. """ # check image dimensions image_header = hdu1[0].header image_header_ = hdu2[0].header # naxis = image_header['naxis'] naxis_ = image_header_['naxis'] if naxis != naxis_: raise ValueError('Incompatible NAXIS values: {}, {}'.format( naxis, naxis_ )) naxis1 = image_header['naxis1'] naxis1_ = image_header_['naxis1'] if naxis1 != naxis1_: raise ValueError('Incompatible NAXIS1 values: {}, {}'.format( naxis1, naxis1_ )) if naxis == 1: naxis2 = 1 elif naxis == 2: naxis2 = image_header['naxis2'] naxis2_ = image_header_['naxis2'] if naxis2 != naxis2_: raise ValueError('Incompatible NAXIS2 values: {}, {}'.format( naxis2, naxis2_ )) else: raise ValueError('Unexpected NAXIS value: {}'.format(naxis)) # initialize output array image2d_merged = np.zeros((naxis2, naxis1)) # main loop data1 = hdu1[0].data data2 = hdu2[0].data for i in range(naxis2): sp1 = data1[i, :] sp2 = data2[i, :] jmin1, jmax1 = find_pix_borders(sp1, sought_value=0) jmin2, jmax2 = find_pix_borders(sp2, sought_value=0) image2d_merged[i, :] = sp1 + sp2 useful1 = (jmin1 != -1) and (jmax1 != naxis1) useful2 = (jmin2 != -1) and (jmax2 != naxis1) if useful1 and useful2: jmineff = max(jmin1, jmin2) jmaxeff = min(jmax1, jmax2) image2d_merged[i, jmineff:(jmaxeff+1)] /= 2 # return result image_merged = fits.PrimaryHDU(data=image2d_merged.astype(np.float32), header=image_header) return image_merged
[ "def", "merge2images", "(", "hdu1", ",", "hdu2", ",", "debugplot", ")", ":", "# check image dimensions", "image_header", "=", "hdu1", "[", "0", "]", ".", "header", "image_header_", "=", "hdu2", "[", "0", "]", ".", "header", "#", "naxis", "=", "image_header...
Merge 2 EMIR images, averaging the common region. Parameters ---------- hdu1 : HDUList object Input image #1. hdu2 : HDUList object Input image #2. debugplot : int Determines whether intermediate computations and/or plots are displayed. The valid codes are defined in numina.array.display.pause_debugplot. Returns ------- image_merged : HDUList object Output image.
[ "Merge", "2", "EMIR", "images", "averaging", "the", "common", "region", "." ]
fef6bbabcb13f80123cafd1800a0f508a3c21702
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/tools/merge2images.py#L34-L106
train
49,149
Jaymon/prom
prom/interface/__init__.py
configure_environ
def configure_environ(dsn_env_name='PROM_DSN', connection_class=DsnConnection): """ configure interfaces based on environment variables by default, when prom is imported, it will look for PROM_DSN, and PROM_DSN_N (where N is 1 through infinity) in the environment, if it finds them, it will assume they are dsn urls that prom understands and will configure db connections with them. If you don't want this behavior (ie, you want to configure prom manually) then just make sure you don't have any environment variables with matching names The num checks (eg PROM_DSN_1, PROM_DSN_2) go in order, so you can't do PROM_DSN_1, PROM_DSN_3, because it will fail on _2 and move on, so make sure your num dsns are in order (eg, 1, 2, 3, ...) example -- export PROM_DSN_1=some.Interface://host:port/dbname#i1 export PROM_DSN_2=some.Interface://host2:port/dbname2#i2 $ python >>> import prom >>> print prom.interfaces # prints a dict with interfaces i1 and i2 keys :param dsn_env_name: string, the name of the environment variables """ inters = [] cs = dsnparse.parse_environs(dsn_env_name, parse_class=connection_class) for c in cs: inter = c.interface set_interface(inter, c.name) inters.append(inter) return inters
python
def configure_environ(dsn_env_name='PROM_DSN', connection_class=DsnConnection): """ configure interfaces based on environment variables by default, when prom is imported, it will look for PROM_DSN, and PROM_DSN_N (where N is 1 through infinity) in the environment, if it finds them, it will assume they are dsn urls that prom understands and will configure db connections with them. If you don't want this behavior (ie, you want to configure prom manually) then just make sure you don't have any environment variables with matching names The num checks (eg PROM_DSN_1, PROM_DSN_2) go in order, so you can't do PROM_DSN_1, PROM_DSN_3, because it will fail on _2 and move on, so make sure your num dsns are in order (eg, 1, 2, 3, ...) example -- export PROM_DSN_1=some.Interface://host:port/dbname#i1 export PROM_DSN_2=some.Interface://host2:port/dbname2#i2 $ python >>> import prom >>> print prom.interfaces # prints a dict with interfaces i1 and i2 keys :param dsn_env_name: string, the name of the environment variables """ inters = [] cs = dsnparse.parse_environs(dsn_env_name, parse_class=connection_class) for c in cs: inter = c.interface set_interface(inter, c.name) inters.append(inter) return inters
[ "def", "configure_environ", "(", "dsn_env_name", "=", "'PROM_DSN'", ",", "connection_class", "=", "DsnConnection", ")", ":", "inters", "=", "[", "]", "cs", "=", "dsnparse", ".", "parse_environs", "(", "dsn_env_name", ",", "parse_class", "=", "connection_class", ...
configure interfaces based on environment variables by default, when prom is imported, it will look for PROM_DSN, and PROM_DSN_N (where N is 1 through infinity) in the environment, if it finds them, it will assume they are dsn urls that prom understands and will configure db connections with them. If you don't want this behavior (ie, you want to configure prom manually) then just make sure you don't have any environment variables with matching names The num checks (eg PROM_DSN_1, PROM_DSN_2) go in order, so you can't do PROM_DSN_1, PROM_DSN_3, because it will fail on _2 and move on, so make sure your num dsns are in order (eg, 1, 2, 3, ...) example -- export PROM_DSN_1=some.Interface://host:port/dbname#i1 export PROM_DSN_2=some.Interface://host2:port/dbname2#i2 $ python >>> import prom >>> print prom.interfaces # prints a dict with interfaces i1 and i2 keys :param dsn_env_name: string, the name of the environment variables
[ "configure", "interfaces", "based", "on", "environment", "variables" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/__init__.py#L13-L42
train
49,150
Jaymon/prom
prom/interface/__init__.py
configure
def configure(dsn, connection_class=DsnConnection): """ configure an interface to be used to query a backend you use this function to configure an Interface using a dsn, then you can get that interface using the get_interface() method dsn -- string -- a properly formatted prom dsn, see DsnConnection for how to format the dsn """ c = dsnparse.parse(dsn, parse_class=connection_class) inter = c.interface set_interface(inter, c.name) return inter
python
def configure(dsn, connection_class=DsnConnection): """ configure an interface to be used to query a backend you use this function to configure an Interface using a dsn, then you can get that interface using the get_interface() method dsn -- string -- a properly formatted prom dsn, see DsnConnection for how to format the dsn """ c = dsnparse.parse(dsn, parse_class=connection_class) inter = c.interface set_interface(inter, c.name) return inter
[ "def", "configure", "(", "dsn", ",", "connection_class", "=", "DsnConnection", ")", ":", "c", "=", "dsnparse", ".", "parse", "(", "dsn", ",", "parse_class", "=", "connection_class", ")", "inter", "=", "c", ".", "interface", "set_interface", "(", "inter", "...
configure an interface to be used to query a backend you use this function to configure an Interface using a dsn, then you can get that interface using the get_interface() method dsn -- string -- a properly formatted prom dsn, see DsnConnection for how to format the dsn
[ "configure", "an", "interface", "to", "be", "used", "to", "query", "a", "backend" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/__init__.py#L45-L57
train
49,151
Jaymon/prom
prom/interface/__init__.py
set_interface
def set_interface(interface, name=''): """ don't want to bother with a dsn? Use this method to make an interface available """ global interfaces if not interface: raise ValueError('interface is empty') # close down the interface before we discard it if name in interfaces: interfaces[name].close() interfaces[name] = interface
python
def set_interface(interface, name=''): """ don't want to bother with a dsn? Use this method to make an interface available """ global interfaces if not interface: raise ValueError('interface is empty') # close down the interface before we discard it if name in interfaces: interfaces[name].close() interfaces[name] = interface
[ "def", "set_interface", "(", "interface", ",", "name", "=", "''", ")", ":", "global", "interfaces", "if", "not", "interface", ":", "raise", "ValueError", "(", "'interface is empty'", ")", "# close down the interface before we discard it", "if", "name", "in", "interf...
don't want to bother with a dsn? Use this method to make an interface available
[ "don", "t", "want", "to", "bother", "with", "a", "dsn?", "Use", "this", "method", "to", "make", "an", "interface", "available" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/__init__.py#L69-L81
train
49,152
Fuyukai/asyncwebsockets
asyncwebsockets/server.py
open_websocket_server
async def open_websocket_server(sock, filter=None): # pylint: disable=W0622 """ A context manager which serves this websocket. :param filter: an async callback which accepts the connection request and returns a bool, or an explicit Accept/Reject message. """ ws = await create_websocket_server(sock, filter=filter) try: yield ws finally: await ws.close()
python
async def open_websocket_server(sock, filter=None): # pylint: disable=W0622 """ A context manager which serves this websocket. :param filter: an async callback which accepts the connection request and returns a bool, or an explicit Accept/Reject message. """ ws = await create_websocket_server(sock, filter=filter) try: yield ws finally: await ws.close()
[ "async", "def", "open_websocket_server", "(", "sock", ",", "filter", "=", "None", ")", ":", "# pylint: disable=W0622", "ws", "=", "await", "create_websocket_server", "(", "sock", ",", "filter", "=", "filter", ")", "try", ":", "yield", "ws", "finally", ":", "...
A context manager which serves this websocket. :param filter: an async callback which accepts the connection request and returns a bool, or an explicit Accept/Reject message.
[ "A", "context", "manager", "which", "serves", "this", "websocket", "." ]
e33e75fd51ce5ae0feac244e8407d2672c5b4745
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/server.py#L14-L25
train
49,153
Fuyukai/asyncwebsockets
asyncwebsockets/server.py
create_websocket_server
async def create_websocket_server(sock, filter=None): # pylint: disable=W0622 """ A more low-level form of open_websocket_server. You are responsible for closing this websocket. """ ws = Websocket() await ws.start_server(sock, filter=filter) return ws
python
async def create_websocket_server(sock, filter=None): # pylint: disable=W0622 """ A more low-level form of open_websocket_server. You are responsible for closing this websocket. """ ws = Websocket() await ws.start_server(sock, filter=filter) return ws
[ "async", "def", "create_websocket_server", "(", "sock", ",", "filter", "=", "None", ")", ":", "# pylint: disable=W0622", "ws", "=", "Websocket", "(", ")", "await", "ws", ".", "start_server", "(", "sock", ",", "filter", "=", "filter", ")", "return", "ws" ]
A more low-level form of open_websocket_server. You are responsible for closing this websocket.
[ "A", "more", "low", "-", "level", "form", "of", "open_websocket_server", ".", "You", "are", "responsible", "for", "closing", "this", "websocket", "." ]
e33e75fd51ce5ae0feac244e8407d2672c5b4745
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/server.py#L28-L35
train
49,154
Jaymon/prom
prom/config.py
Schema.magic_fields
def magic_fields(self): """the magic fields for the schema""" return {f:v for f, v in self.fields.items() if f.startswith('_')}
python
def magic_fields(self): """the magic fields for the schema""" return {f:v for f, v in self.fields.items() if f.startswith('_')}
[ "def", "magic_fields", "(", "self", ")", ":", "return", "{", "f", ":", "v", "for", "f", ",", "v", "in", "self", ".", "fields", ".", "items", "(", ")", "if", "f", ".", "startswith", "(", "'_'", ")", "}" ]
the magic fields for the schema
[ "the", "magic", "fields", "for", "the", "schema" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/config.py#L180-L182
train
49,155
Jaymon/prom
prom/config.py
Schema.set_index
def set_index(self, index_name, index): """ add an index to the schema for the most part, you will use the __getattr__ method of adding indexes for a more fluid interface, but you can use this if you want to get closer to the bare metal index_name -- string -- the name of the index index -- Index() -- an Index instance """ if not index_name: raise ValueError("index_name must have a value") if index_name in self.indexes: raise ValueError("index_name {} has already been defined on {}".format( index_name, str(self.indexes[index_name].fields) )) if not isinstance(index, Index): raise ValueError("{} is not an Index instance".format(type(index))) index.name = index_name self.indexes[index_name] = index return self
python
def set_index(self, index_name, index): """ add an index to the schema for the most part, you will use the __getattr__ method of adding indexes for a more fluid interface, but you can use this if you want to get closer to the bare metal index_name -- string -- the name of the index index -- Index() -- an Index instance """ if not index_name: raise ValueError("index_name must have a value") if index_name in self.indexes: raise ValueError("index_name {} has already been defined on {}".format( index_name, str(self.indexes[index_name].fields) )) if not isinstance(index, Index): raise ValueError("{} is not an Index instance".format(type(index))) index.name = index_name self.indexes[index_name] = index return self
[ "def", "set_index", "(", "self", ",", "index_name", ",", "index", ")", ":", "if", "not", "index_name", ":", "raise", "ValueError", "(", "\"index_name must have a value\"", ")", "if", "index_name", "in", "self", ".", "indexes", ":", "raise", "ValueError", "(", ...
add an index to the schema for the most part, you will use the __getattr__ method of adding indexes for a more fluid interface, but you can use this if you want to get closer to the bare metal index_name -- string -- the name of the index index -- Index() -- an Index instance
[ "add", "an", "index", "to", "the", "schema" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/config.py#L281-L301
train
49,156
Jaymon/prom
prom/config.py
Field.schema
def schema(self): """return the schema instance if this is reference to another table""" if not hasattr(self, "_schema"): ret = None o = self._type if isinstance(o, type): ret = getattr(o, "schema", None) elif isinstance(o, Schema): ret = o else: module, klass = utils.get_objects(o) ret = klass.schema self._schema = ret return self._schema
python
def schema(self): """return the schema instance if this is reference to another table""" if not hasattr(self, "_schema"): ret = None o = self._type if isinstance(o, type): ret = getattr(o, "schema", None) elif isinstance(o, Schema): ret = o else: module, klass = utils.get_objects(o) ret = klass.schema self._schema = ret return self._schema
[ "def", "schema", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_schema\"", ")", ":", "ret", "=", "None", "o", "=", "self", ".", "_type", "if", "isinstance", "(", "o", ",", "type", ")", ":", "ret", "=", "getattr", "(", "o", ...
return the schema instance if this is reference to another table
[ "return", "the", "schema", "instance", "if", "this", "is", "reference", "to", "another", "table" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/config.py#L390-L407
train
49,157
Jaymon/prom
prom/config.py
Field.fval
def fval(self, instance): """return the raw value that this property is holding internally for instance""" try: val = instance.__dict__[self.instance_field_name] except KeyError as e: #raise AttributeError(str(e)) val = None return val
python
def fval(self, instance): """return the raw value that this property is holding internally for instance""" try: val = instance.__dict__[self.instance_field_name] except KeyError as e: #raise AttributeError(str(e)) val = None return val
[ "def", "fval", "(", "self", ",", "instance", ")", ":", "try", ":", "val", "=", "instance", ".", "__dict__", "[", "self", ".", "instance_field_name", "]", "except", "KeyError", "as", "e", ":", "#raise AttributeError(str(e))", "val", "=", "None", "return", "...
return the raw value that this property is holding internally for instance
[ "return", "the", "raw", "value", "that", "this", "property", "is", "holding", "internally", "for", "instance" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/config.py#L561-L569
train
49,158
openmicroanalysis/pyxray
pyxray/base.py
_Database.set_default_reference
def set_default_reference(self, method, reference): """ Set the default reference for a method. :arg method: name of a method :type method: :class:`str` {reference} """ if method not in self._available_methods: raise ValueError('Unknown method: {0}'.format(method)) self._default_references[method] = reference
python
def set_default_reference(self, method, reference): """ Set the default reference for a method. :arg method: name of a method :type method: :class:`str` {reference} """ if method not in self._available_methods: raise ValueError('Unknown method: {0}'.format(method)) self._default_references[method] = reference
[ "def", "set_default_reference", "(", "self", ",", "method", ",", "reference", ")", ":", "if", "method", "not", "in", "self", ".", "_available_methods", ":", "raise", "ValueError", "(", "'Unknown method: {0}'", ".", "format", "(", "method", ")", ")", "self", ...
Set the default reference for a method. :arg method: name of a method :type method: :class:`str` {reference}
[ "Set", "the", "default", "reference", "for", "a", "method", "." ]
cae89677f00ebcc0952f94d1ab70e6b35e1a51e9
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/base.py#L74-L85
train
49,159
openmicroanalysis/pyxray
pyxray/base.py
_Database.get_default_reference
def get_default_reference(self, method): """ Returns the default reference for a method. :arg method: name of a method :type method: :class:`str` :return: reference :rtype: :class:`Reference <pyxray.descriptor.Reference>` or :class:`str` """ if method not in self._available_methods: raise ValueError('Unknown method: {0}'.format(method)) return self._default_references.get(method)
python
def get_default_reference(self, method): """ Returns the default reference for a method. :arg method: name of a method :type method: :class:`str` :return: reference :rtype: :class:`Reference <pyxray.descriptor.Reference>` or :class:`str` """ if method not in self._available_methods: raise ValueError('Unknown method: {0}'.format(method)) return self._default_references.get(method)
[ "def", "get_default_reference", "(", "self", ",", "method", ")", ":", "if", "method", "not", "in", "self", ".", "_available_methods", ":", "raise", "ValueError", "(", "'Unknown method: {0}'", ".", "format", "(", "method", ")", ")", "return", "self", ".", "_d...
Returns the default reference for a method. :arg method: name of a method :type method: :class:`str` :return: reference :rtype: :class:`Reference <pyxray.descriptor.Reference>` or :class:`str`
[ "Returns", "the", "default", "reference", "for", "a", "method", "." ]
cae89677f00ebcc0952f94d1ab70e6b35e1a51e9
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/base.py#L87-L99
train
49,160
openmicroanalysis/pyxray
pyxray/base.py
_Database.print_element_xray_transitions
def print_element_xray_transitions(self, element, file=sys.stdout, tabulate_kwargs=None): """ Prints all x-ray transitions for an element, with their different notations and energy. {element} :arg file: file for output, default to standard out """ header = ['IUPAC', 'Siegbahn', 'Energy (eV)', 'Probability'] rows = [] for xraytransition in self.element_xray_transitions(element): try: iupac = self.xray_transition_notation(xraytransition, 'iupac') except: iupac = '' try: siegbahn = self.xray_transition_notation(xraytransition, 'siegbahn') except: siegbahn = '' try: energy_eV = self.xray_transition_energy_eV(element, xraytransition) except: energy_eV = '' try: probability = self.xray_transition_probability(element, xraytransition) except: probability = '' rows.append([iupac, siegbahn, energy_eV, probability]) rows.sort(key=operator.itemgetter(2)) if tabulate_kwargs is None: tabulate_kwargs = {} file.write(tabulate.tabulate(rows, header, **tabulate_kwargs))
python
def print_element_xray_transitions(self, element, file=sys.stdout, tabulate_kwargs=None): """ Prints all x-ray transitions for an element, with their different notations and energy. {element} :arg file: file for output, default to standard out """ header = ['IUPAC', 'Siegbahn', 'Energy (eV)', 'Probability'] rows = [] for xraytransition in self.element_xray_transitions(element): try: iupac = self.xray_transition_notation(xraytransition, 'iupac') except: iupac = '' try: siegbahn = self.xray_transition_notation(xraytransition, 'siegbahn') except: siegbahn = '' try: energy_eV = self.xray_transition_energy_eV(element, xraytransition) except: energy_eV = '' try: probability = self.xray_transition_probability(element, xraytransition) except: probability = '' rows.append([iupac, siegbahn, energy_eV, probability]) rows.sort(key=operator.itemgetter(2)) if tabulate_kwargs is None: tabulate_kwargs = {} file.write(tabulate.tabulate(rows, header, **tabulate_kwargs))
[ "def", "print_element_xray_transitions", "(", "self", ",", "element", ",", "file", "=", "sys", ".", "stdout", ",", "tabulate_kwargs", "=", "None", ")", ":", "header", "=", "[", "'IUPAC'", ",", "'Siegbahn'", ",", "'Energy (eV)'", ",", "'Probability'", "]", "r...
Prints all x-ray transitions for an element, with their different notations and energy. {element} :arg file: file for output, default to standard out
[ "Prints", "all", "x", "-", "ray", "transitions", "for", "an", "element", "with", "their", "different", "notations", "and", "energy", "." ]
cae89677f00ebcc0952f94d1ab70e6b35e1a51e9
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/base.py#L243-L282
train
49,161
Jaymon/prom
prom/cli/dump.py
get_subclasses
def get_subclasses(modulepath, parent_class): """given a module return all the parent_class subclasses that are found in that module and any submodules. :param modulepath: string, a path like foo.bar.che :param parent_class: object, the class whose children you are looking for :returns: set, all the found child classes in modulepath of parent_class """ if isinstance(modulepath, ModuleType): modules = get_modules(modulepath.__name__) else: modules = get_modules(modulepath) ret = set() for m in modules: cs = inspect.getmembers(m, lambda v: inspect.isclass(v) and issubclass(v, parent_class)) for class_name, klass in cs: ret.add(klass) return ret
python
def get_subclasses(modulepath, parent_class): """given a module return all the parent_class subclasses that are found in that module and any submodules. :param modulepath: string, a path like foo.bar.che :param parent_class: object, the class whose children you are looking for :returns: set, all the found child classes in modulepath of parent_class """ if isinstance(modulepath, ModuleType): modules = get_modules(modulepath.__name__) else: modules = get_modules(modulepath) ret = set() for m in modules: cs = inspect.getmembers(m, lambda v: inspect.isclass(v) and issubclass(v, parent_class)) for class_name, klass in cs: ret.add(klass) return ret
[ "def", "get_subclasses", "(", "modulepath", ",", "parent_class", ")", ":", "if", "isinstance", "(", "modulepath", ",", "ModuleType", ")", ":", "modules", "=", "get_modules", "(", "modulepath", ".", "__name__", ")", "else", ":", "modules", "=", "get_modules", ...
given a module return all the parent_class subclasses that are found in that module and any submodules. :param modulepath: string, a path like foo.bar.che :param parent_class: object, the class whose children you are looking for :returns: set, all the found child classes in modulepath of parent_class
[ "given", "a", "module", "return", "all", "the", "parent_class", "subclasses", "that", "are", "found", "in", "that", "module", "and", "any", "submodules", "." ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/cli/dump.py#L44-L63
train
49,162
Jaymon/prom
prom/cli/dump.py
build_dump_order
def build_dump_order(orm_class, orm_classes): """pass in an array, when you encounter a ref, call this method again with the array when something has no more refs, then it gets appended to the array and returns, each time something gets through the list they are added, but before they are added to the list it is checked to see if it is already in the listt""" if orm_class in orm_classes: return for field_name, field_val in orm_class.schema.fields.items(): if field_val.is_ref(): build_dump_order(field_val.schema.orm_class, orm_classes) if orm_class not in orm_classes: orm_classes.append(orm_class)
python
def build_dump_order(orm_class, orm_classes): """pass in an array, when you encounter a ref, call this method again with the array when something has no more refs, then it gets appended to the array and returns, each time something gets through the list they are added, but before they are added to the list it is checked to see if it is already in the listt""" if orm_class in orm_classes: return for field_name, field_val in orm_class.schema.fields.items(): if field_val.is_ref(): build_dump_order(field_val.schema.orm_class, orm_classes) if orm_class not in orm_classes: orm_classes.append(orm_class)
[ "def", "build_dump_order", "(", "orm_class", ",", "orm_classes", ")", ":", "if", "orm_class", "in", "orm_classes", ":", "return", "for", "field_name", ",", "field_val", "in", "orm_class", ".", "schema", ".", "fields", ".", "items", "(", ")", ":", "if", "fi...
pass in an array, when you encounter a ref, call this method again with the array when something has no more refs, then it gets appended to the array and returns, each time something gets through the list they are added, but before they are added to the list it is checked to see if it is already in the listt
[ "pass", "in", "an", "array", "when", "you", "encounter", "a", "ref", "call", "this", "method", "again", "with", "the", "array", "when", "something", "has", "no", "more", "refs", "then", "it", "gets", "appended", "to", "the", "array", "and", "returns", "e...
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/cli/dump.py#L66-L78
train
49,163
Jaymon/prom
prom/cli/dump.py
main_dump
def main_dump(paths, directory, dry_run): """dump all or part of the prom data, currently only works on Postgres databases basically just a wrapper around `dump backup` https://github.com/Jaymon/dump """ table_map = get_table_map(paths) for conn_name, conn_info in table_map.items(): inter = conn_info["interface"] conn = inter.connection_config table_names = conn_info["table_names"] cmd = get_base_cmd("backup", inter, directory) cmd.extend(table_names) if dry_run: echo.out(" ".join(cmd)) else: run_cmd(cmd)
python
def main_dump(paths, directory, dry_run): """dump all or part of the prom data, currently only works on Postgres databases basically just a wrapper around `dump backup` https://github.com/Jaymon/dump """ table_map = get_table_map(paths) for conn_name, conn_info in table_map.items(): inter = conn_info["interface"] conn = inter.connection_config table_names = conn_info["table_names"] cmd = get_base_cmd("backup", inter, directory) cmd.extend(table_names) if dry_run: echo.out(" ".join(cmd)) else: run_cmd(cmd)
[ "def", "main_dump", "(", "paths", ",", "directory", ",", "dry_run", ")", ":", "table_map", "=", "get_table_map", "(", "paths", ")", "for", "conn_name", ",", "conn_info", "in", "table_map", ".", "items", "(", ")", ":", "inter", "=", "conn_info", "[", "\"i...
dump all or part of the prom data, currently only works on Postgres databases basically just a wrapper around `dump backup` https://github.com/Jaymon/dump
[ "dump", "all", "or", "part", "of", "the", "prom", "data", "currently", "only", "works", "on", "Postgres", "databases" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/cli/dump.py#L182-L201
train
49,164
Jaymon/prom
prom/cli/dump.py
main_restore
def main_restore(directory, conn_name): """Restore your database dumped with the dump command just a wrapper around `dump restore` https://github.com/Jaymon/dump """ inter = get_interface(conn_name) conn = inter.connection_config cmd = get_base_cmd("restore", inter, directory) run_cmd(cmd)
python
def main_restore(directory, conn_name): """Restore your database dumped with the dump command just a wrapper around `dump restore` https://github.com/Jaymon/dump """ inter = get_interface(conn_name) conn = inter.connection_config cmd = get_base_cmd("restore", inter, directory) run_cmd(cmd)
[ "def", "main_restore", "(", "directory", ",", "conn_name", ")", ":", "inter", "=", "get_interface", "(", "conn_name", ")", "conn", "=", "inter", ".", "connection_config", "cmd", "=", "get_base_cmd", "(", "\"restore\"", ",", "inter", ",", "directory", ")", "r...
Restore your database dumped with the dump command just a wrapper around `dump restore` https://github.com/Jaymon/dump
[ "Restore", "your", "database", "dumped", "with", "the", "dump", "command" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/cli/dump.py#L211-L219
train
49,165
Jaymon/prom
prom/interface/postgres.py
PostgreSQL._get_fields
def _get_fields(self, table_name, **kwargs): """return all the fields for the given schema""" ret = {} query_str = [] query_args = ['f', table_name] # I had to brush up on my join knowledge while writing this query # https://en.wikipedia.org/wiki/Join_(SQL) # # other helpful links # https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns # https://www.postgresql.org/docs/9.4/static/catalog-pg-attribute.html # https://www.postgresql.org/docs/9.3/static/catalog-pg-type.html # # another approach # http://dba.stackexchange.com/questions/22362/how-do-i-list-all-columns-for-a-specified-table # http://gis.stackexchange.com/questions/94049/how-to-get-the-data-type-of-each-column-from-a-postgis-table query_str.append('SELECT') query_str.append(', '.join([ 'a.attnum', 'a.attname', 'a.attnotnull', 't.typname', 'i.indisprimary', #'s.conname', #'pg_get_constraintdef(s.oid, true) as condef', 'c.relname AS confrelname', ])) query_str.append('FROM') query_str.append(' pg_attribute a') query_str.append('JOIN pg_type t ON a.atttypid = t.oid') query_str.append('LEFT JOIN pg_index i ON a.attrelid = i.indrelid') query_str.append(' AND a.attnum = any(i.indkey)') query_str.append('LEFT JOIN pg_constraint s ON a.attrelid = s.conrelid') query_str.append(' AND s.contype = {} AND a.attnum = any(s.conkey)'.format(self.val_placeholder)) query_str.append('LEFT JOIN pg_class c ON s.confrelid = c.oid') query_str.append('WHERE') query_str.append(' a.attrelid = {}::regclass'.format(self.val_placeholder)) query_str.append(' AND a.attisdropped = False') query_str.append(' AND a.attnum > 0') query_str.append('ORDER BY a.attnum ASC') query_str = os.linesep.join(query_str) fields = self.query(query_str, *query_args, **kwargs) pg_types = { "float8": float, "timestamp": datetime.datetime, "int2": int, "int4": int, "int8": long, "numeric": decimal.Decimal, "text": str, "bpchar": str, "varchar": str, "bool": bool, "date": datetime.date, "blob": bytearray, } # the rows we can set: field_type, name, field_required, min_size, max_size, # size, unique, pk, <foreign key info> # These keys will roughly correspond with schema.Field for row in fields: field = { "name": row["attname"], "field_type": pg_types[row["typname"]], "field_required": row["attnotnull"], "pk": bool(row["indisprimary"]), } if row["confrelname"]: # TODO -- I can't decide which name I like field["schema_table_name"] = row["confrelname"] field["ref_table_name"] = row["confrelname"] ret[field["name"]] = field return ret
python
def _get_fields(self, table_name, **kwargs): """return all the fields for the given schema""" ret = {} query_str = [] query_args = ['f', table_name] # I had to brush up on my join knowledge while writing this query # https://en.wikipedia.org/wiki/Join_(SQL) # # other helpful links # https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns # https://www.postgresql.org/docs/9.4/static/catalog-pg-attribute.html # https://www.postgresql.org/docs/9.3/static/catalog-pg-type.html # # another approach # http://dba.stackexchange.com/questions/22362/how-do-i-list-all-columns-for-a-specified-table # http://gis.stackexchange.com/questions/94049/how-to-get-the-data-type-of-each-column-from-a-postgis-table query_str.append('SELECT') query_str.append(', '.join([ 'a.attnum', 'a.attname', 'a.attnotnull', 't.typname', 'i.indisprimary', #'s.conname', #'pg_get_constraintdef(s.oid, true) as condef', 'c.relname AS confrelname', ])) query_str.append('FROM') query_str.append(' pg_attribute a') query_str.append('JOIN pg_type t ON a.atttypid = t.oid') query_str.append('LEFT JOIN pg_index i ON a.attrelid = i.indrelid') query_str.append(' AND a.attnum = any(i.indkey)') query_str.append('LEFT JOIN pg_constraint s ON a.attrelid = s.conrelid') query_str.append(' AND s.contype = {} AND a.attnum = any(s.conkey)'.format(self.val_placeholder)) query_str.append('LEFT JOIN pg_class c ON s.confrelid = c.oid') query_str.append('WHERE') query_str.append(' a.attrelid = {}::regclass'.format(self.val_placeholder)) query_str.append(' AND a.attisdropped = False') query_str.append(' AND a.attnum > 0') query_str.append('ORDER BY a.attnum ASC') query_str = os.linesep.join(query_str) fields = self.query(query_str, *query_args, **kwargs) pg_types = { "float8": float, "timestamp": datetime.datetime, "int2": int, "int4": int, "int8": long, "numeric": decimal.Decimal, "text": str, "bpchar": str, "varchar": str, "bool": bool, "date": datetime.date, "blob": bytearray, } # the rows we can set: field_type, name, field_required, min_size, max_size, # size, unique, pk, <foreign key info> # These keys will roughly correspond with schema.Field for row in fields: field = { "name": row["attname"], "field_type": pg_types[row["typname"]], "field_required": row["attnotnull"], "pk": bool(row["indisprimary"]), } if row["confrelname"]: # TODO -- I can't decide which name I like field["schema_table_name"] = row["confrelname"] field["ref_table_name"] = row["confrelname"] ret[field["name"]] = field return ret
[ "def", "_get_fields", "(", "self", ",", "table_name", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "query_str", "=", "[", "]", "query_args", "=", "[", "'f'", ",", "table_name", "]", "# I had to brush up on my join knowledge while writing this query",...
return all the fields for the given schema
[ "return", "all", "the", "fields", "for", "the", "given", "schema" ]
b7ad2c259eca198da03e1e4bc7d95014c168c361
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/postgres.py#L184-L262
train
49,166
IdentityPython/oidcendpoint
src/oidcendpoint/oidc/token.py
AccessToken.client_authentication
def client_authentication(self, request, auth=None, **kwargs): """ Deal with client authentication :param request: The refresh access token request :param auth: Client authentication information :param kwargs: Extra keyword arguments :return: dictionary containing client id, client authentication method and possibly access token. """ try: auth_info = verify_client(self.endpoint_context, request, auth) except Exception as err: msg = "Failed to verify client due to: {}".format(err) logger.error(msg) return self.error_cls(error="unauthorized_client", error_description=msg) else: if 'client_id' not in auth_info: logger.error('No client_id, authentication failed') return self.error_cls(error="unauthorized_client", error_description='unknown client') return auth_info
python
def client_authentication(self, request, auth=None, **kwargs): """ Deal with client authentication :param request: The refresh access token request :param auth: Client authentication information :param kwargs: Extra keyword arguments :return: dictionary containing client id, client authentication method and possibly access token. """ try: auth_info = verify_client(self.endpoint_context, request, auth) except Exception as err: msg = "Failed to verify client due to: {}".format(err) logger.error(msg) return self.error_cls(error="unauthorized_client", error_description=msg) else: if 'client_id' not in auth_info: logger.error('No client_id, authentication failed') return self.error_cls(error="unauthorized_client", error_description='unknown client') return auth_info
[ "def", "client_authentication", "(", "self", ",", "request", ",", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "auth_info", "=", "verify_client", "(", "self", ".", "endpoint_context", ",", "request", ",", "auth", ")", "except", "Ex...
Deal with client authentication :param request: The refresh access token request :param auth: Client authentication information :param kwargs: Extra keyword arguments :return: dictionary containing client id, client authentication method and possibly access token.
[ "Deal", "with", "client", "authentication" ]
6c1d729d51bfb6332816117fe476073df7a1d823
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/oidc/token.py#L111-L135
train
49,167
IdentityPython/oidcendpoint
src/oidcendpoint/oidc/token.py
AccessToken._post_parse_request
def _post_parse_request(self, request, client_id='', **kwargs): """ This is where clients come to get their access tokens :param request: The request :param authn: Authentication info, comes from HTTP header :returns: """ if 'state' in request: try: sinfo = self.endpoint_context.sdb[request['code']] except KeyError: logger.error('Code not present in SessionDB') return self.error_cls(error="unauthorized_client") else: state = sinfo['authn_req']['state'] if state != request['state']: logger.error('State value mismatch') return self.error_cls(error="unauthorized_client") if "client_id" not in request: # Optional for access token request request["client_id"] = client_id logger.debug("%s: %s" % (request.__class__.__name__, sanitize(request))) return request
python
def _post_parse_request(self, request, client_id='', **kwargs): """ This is where clients come to get their access tokens :param request: The request :param authn: Authentication info, comes from HTTP header :returns: """ if 'state' in request: try: sinfo = self.endpoint_context.sdb[request['code']] except KeyError: logger.error('Code not present in SessionDB') return self.error_cls(error="unauthorized_client") else: state = sinfo['authn_req']['state'] if state != request['state']: logger.error('State value mismatch') return self.error_cls(error="unauthorized_client") if "client_id" not in request: # Optional for access token request request["client_id"] = client_id logger.debug("%s: %s" % (request.__class__.__name__, sanitize(request))) return request
[ "def", "_post_parse_request", "(", "self", ",", "request", ",", "client_id", "=", "''", ",", "*", "*", "kwargs", ")", ":", "if", "'state'", "in", "request", ":", "try", ":", "sinfo", "=", "self", ".", "endpoint_context", ".", "sdb", "[", "request", "["...
This is where clients come to get their access tokens :param request: The request :param authn: Authentication info, comes from HTTP header :returns:
[ "This", "is", "where", "clients", "come", "to", "get", "their", "access", "tokens" ]
6c1d729d51bfb6332816117fe476073df7a1d823
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/oidc/token.py#L137-L164
train
49,168
BreakingBytes/simkit
simkit/core/outputs.py
OutputRegistry.register
def register(self, new_outputs, *args, **kwargs): """ Register outputs and metadata. * ``initial_value`` - used in dynamic calculations * ``size`` - number of elements per timestep * ``uncertainty`` - in percent of nominal value * ``variance`` - dictionary of covariances, diagonal is square of uncertianties, no units * ``jacobian`` - dictionary of sensitivities dxi/dfj * ``isconstant`` - ``True`` if constant, ``False`` if periodic * ``isproperty`` - ``True`` if output stays at last value during thresholds, ``False`` if reverts to initial value * ``timeseries`` - name of corresponding time series output, ``None`` if no time series * ``output_source`` - name :param new_outputs: new outputs to register. """ kwargs.update(zip(self.meta_names, args)) # call super method super(OutputRegistry, self).register(new_outputs, **kwargs)
python
def register(self, new_outputs, *args, **kwargs): """ Register outputs and metadata. * ``initial_value`` - used in dynamic calculations * ``size`` - number of elements per timestep * ``uncertainty`` - in percent of nominal value * ``variance`` - dictionary of covariances, diagonal is square of uncertianties, no units * ``jacobian`` - dictionary of sensitivities dxi/dfj * ``isconstant`` - ``True`` if constant, ``False`` if periodic * ``isproperty`` - ``True`` if output stays at last value during thresholds, ``False`` if reverts to initial value * ``timeseries`` - name of corresponding time series output, ``None`` if no time series * ``output_source`` - name :param new_outputs: new outputs to register. """ kwargs.update(zip(self.meta_names, args)) # call super method super(OutputRegistry, self).register(new_outputs, **kwargs)
[ "def", "register", "(", "self", ",", "new_outputs", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "zip", "(", "self", ".", "meta_names", ",", "args", ")", ")", "# call super method", "super", "(", "OutputRegistry", ...
Register outputs and metadata. * ``initial_value`` - used in dynamic calculations * ``size`` - number of elements per timestep * ``uncertainty`` - in percent of nominal value * ``variance`` - dictionary of covariances, diagonal is square of uncertianties, no units * ``jacobian`` - dictionary of sensitivities dxi/dfj * ``isconstant`` - ``True`` if constant, ``False`` if periodic * ``isproperty`` - ``True`` if output stays at last value during thresholds, ``False`` if reverts to initial value * ``timeseries`` - name of corresponding time series output, ``None`` if no time series * ``output_source`` - name :param new_outputs: new outputs to register.
[ "Register", "outputs", "and", "metadata", "." ]
205163d879d3880b6c9ef609f1b723a58773026b
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/outputs.py#L31-L52
train
49,169
guaix-ucm/pyemir
emirdrp/recipes/image/dither.py
FullDitheredImagesRecipe.initial_classification
def initial_classification(self, obresult, target_is_sky=False): """Classify input frames, """ # lists of targets and sky frames with obresult.frames[0].open() as baseimg: # Initial checks has_bpm_ext = 'BPM' in baseimg self.logger.debug('images have BPM extension: %s', has_bpm_ext) images_info = [] for f in obresult.frames: with f.open() as img: # Getting some metadata from FITS header hdr = img[0].header iinfo = ImageInfo(f) finfo = {} iinfo.metadata = finfo finfo['uuid'] = hdr['UUID'] finfo['exposure'] = hdr['EXPTIME'] # frame.baseshape = get_image_shape(hdr) finfo['airmass'] = hdr['airmass'] finfo['mjd'] = hdr['tstamp'] iinfo.label = 'result_image_{}'.format(finfo['uuid']) iinfo.mask = nfcom.Extension("BPM") # Insert pixel offsets between frames iinfo.objmask_data = None iinfo.valid_target = False iinfo.valid_sky = False # FIXME: hardcode itype for the moment iinfo.itype = 'TARGET' if iinfo.itype == 'TARGET': iinfo.valid_target = True #targetframes.append(iinfo) if target_is_sky: iinfo.valid_sky = True #skyframes.append(iinfo) if iinfo.itype == 'SKY': iinfo.valid_sky = True #skyframes.append(iinfo) images_info.append(iinfo) return images_info
python
def initial_classification(self, obresult, target_is_sky=False): """Classify input frames, """ # lists of targets and sky frames with obresult.frames[0].open() as baseimg: # Initial checks has_bpm_ext = 'BPM' in baseimg self.logger.debug('images have BPM extension: %s', has_bpm_ext) images_info = [] for f in obresult.frames: with f.open() as img: # Getting some metadata from FITS header hdr = img[0].header iinfo = ImageInfo(f) finfo = {} iinfo.metadata = finfo finfo['uuid'] = hdr['UUID'] finfo['exposure'] = hdr['EXPTIME'] # frame.baseshape = get_image_shape(hdr) finfo['airmass'] = hdr['airmass'] finfo['mjd'] = hdr['tstamp'] iinfo.label = 'result_image_{}'.format(finfo['uuid']) iinfo.mask = nfcom.Extension("BPM") # Insert pixel offsets between frames iinfo.objmask_data = None iinfo.valid_target = False iinfo.valid_sky = False # FIXME: hardcode itype for the moment iinfo.itype = 'TARGET' if iinfo.itype == 'TARGET': iinfo.valid_target = True #targetframes.append(iinfo) if target_is_sky: iinfo.valid_sky = True #skyframes.append(iinfo) if iinfo.itype == 'SKY': iinfo.valid_sky = True #skyframes.append(iinfo) images_info.append(iinfo) return images_info
[ "def", "initial_classification", "(", "self", ",", "obresult", ",", "target_is_sky", "=", "False", ")", ":", "# lists of targets and sky frames", "with", "obresult", ".", "frames", "[", "0", "]", ".", "open", "(", ")", "as", "baseimg", ":", "# Initial checks", ...
Classify input frames,
[ "Classify", "input", "frames" ]
fef6bbabcb13f80123cafd1800a0f508a3c21702
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/recipes/image/dither.py#L427-L473
train
49,170
thorgate/tg-utils
tg_utils/managers.py
NotifyPostChangeQuerySet.update_or_create
def update_or_create(self, *args, **kwargs): """ Only sent when not created, since default implementation will call `self.create` when creating which triggers our signal already. """ obj, created = super().update_or_create(*args, **kwargs) if not created: return self.with_signal(result=(obj, created)) return obj, created
python
def update_or_create(self, *args, **kwargs): """ Only sent when not created, since default implementation will call `self.create` when creating which triggers our signal already. """ obj, created = super().update_or_create(*args, **kwargs) if not created: return self.with_signal(result=(obj, created)) return obj, created
[ "def", "update_or_create", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "obj", ",", "created", "=", "super", "(", ")", ".", "update_or_create", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "created", ":", "retur...
Only sent when not created, since default implementation will call `self.create` when creating which triggers our signal already.
[ "Only", "sent", "when", "not", "created", "since", "default", "implementation", "will", "call", "self", ".", "create", "when", "creating", "which", "triggers", "our", "signal", "already", "." ]
81e404e837334b241686d9159cc3eb44de509a88
https://github.com/thorgate/tg-utils/blob/81e404e837334b241686d9159cc3eb44de509a88/tg_utils/managers.py#L41-L51
train
49,171
Yelp/uwsgi_metrics
uwsgi_metrics/timer.py
Timer.update
def update(self, duration): """Add a recorded duration.""" if duration >= 0: self.histogram.update(duration) self.meter.mark()
python
def update(self, duration): """Add a recorded duration.""" if duration >= 0: self.histogram.update(duration) self.meter.mark()
[ "def", "update", "(", "self", ",", "duration", ")", ":", "if", "duration", ">=", "0", ":", "self", ".", "histogram", ".", "update", "(", "duration", ")", "self", ".", "meter", ".", "mark", "(", ")" ]
Add a recorded duration.
[ "Add", "a", "recorded", "duration", "." ]
534966fd461ff711aecd1e3d4caaafdc23ac33f0
https://github.com/Yelp/uwsgi_metrics/blob/534966fd461ff711aecd1e3d4caaafdc23ac33f0/uwsgi_metrics/timer.py#L44-L48
train
49,172
BeyondTheClouds/enoslib
enoslib/infra/enos_vmong5k/provider.py
_build_g5k_conf
def _build_g5k_conf(vmong5k_conf): """Build the conf of the g5k provider from the vmong5k conf.""" clusters = [m.cluster for m in vmong5k_conf.machines] sites = g5k_api_utils.get_clusters_sites(clusters) site_names = set(sites.values()) if len(site_names) > 1: raise Exception("Multisite deployment not supported yet") site = site_names.pop() return _do_build_g5k_conf(vmong5k_conf, site)
python
def _build_g5k_conf(vmong5k_conf): """Build the conf of the g5k provider from the vmong5k conf.""" clusters = [m.cluster for m in vmong5k_conf.machines] sites = g5k_api_utils.get_clusters_sites(clusters) site_names = set(sites.values()) if len(site_names) > 1: raise Exception("Multisite deployment not supported yet") site = site_names.pop() return _do_build_g5k_conf(vmong5k_conf, site)
[ "def", "_build_g5k_conf", "(", "vmong5k_conf", ")", ":", "clusters", "=", "[", "m", ".", "cluster", "for", "m", "in", "vmong5k_conf", ".", "machines", "]", "sites", "=", "g5k_api_utils", ".", "get_clusters_sites", "(", "clusters", ")", "site_names", "=", "se...
Build the conf of the g5k provider from the vmong5k conf.
[ "Build", "the", "conf", "of", "the", "g5k", "provider", "from", "the", "vmong5k", "conf", "." ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_vmong5k/provider.py#L79-L87
train
49,173
BreakingBytes/simkit
simkit/contrib/readers.py
copy_model_instance
def copy_model_instance(obj): """ Copy Django model instance as a dictionary excluding automatically created fields like an auto-generated sequence as a primary key or an auto-created many-to-one reverse relation. :param obj: Django model object :return: copy of model instance as dictionary """ meta = getattr(obj, '_meta') # make pycharm happy # dictionary of model values excluding auto created and related fields return {f.name: getattr(obj, f.name) for f in meta.get_fields(include_parents=False) if not f.auto_created}
python
def copy_model_instance(obj): """ Copy Django model instance as a dictionary excluding automatically created fields like an auto-generated sequence as a primary key or an auto-created many-to-one reverse relation. :param obj: Django model object :return: copy of model instance as dictionary """ meta = getattr(obj, '_meta') # make pycharm happy # dictionary of model values excluding auto created and related fields return {f.name: getattr(obj, f.name) for f in meta.get_fields(include_parents=False) if not f.auto_created}
[ "def", "copy_model_instance", "(", "obj", ")", ":", "meta", "=", "getattr", "(", "obj", ",", "'_meta'", ")", "# make pycharm happy", "# dictionary of model values excluding auto created and related fields", "return", "{", "f", ".", "name", ":", "getattr", "(", "obj", ...
Copy Django model instance as a dictionary excluding automatically created fields like an auto-generated sequence as a primary key or an auto-created many-to-one reverse relation. :param obj: Django model object :return: copy of model instance as dictionary
[ "Copy", "Django", "model", "instance", "as", "a", "dictionary", "excluding", "automatically", "created", "fields", "like", "an", "auto", "-", "generated", "sequence", "as", "a", "primary", "key", "or", "an", "auto", "-", "created", "many", "-", "to", "-", ...
205163d879d3880b6c9ef609f1b723a58773026b
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/contrib/readers.py#L18-L31
train
49,174
BreakingBytes/simkit
simkit/contrib/readers.py
ArgumentReader.load_data
def load_data(self, *args, **kwargs): """ Collects positional and keyword arguments into `data` and applies units. :return: data """ # get positional argument names from parameters and apply them to args # update data with additional kwargs argpos = { v['extras']['argpos']: k for k, v in self.parameters.iteritems() if 'argpos' in v['extras'] } data = dict( {argpos[n]: a for n, a in enumerate(args)}, **kwargs ) return self.apply_units_to_cache(data)
python
def load_data(self, *args, **kwargs): """ Collects positional and keyword arguments into `data` and applies units. :return: data """ # get positional argument names from parameters and apply them to args # update data with additional kwargs argpos = { v['extras']['argpos']: k for k, v in self.parameters.iteritems() if 'argpos' in v['extras'] } data = dict( {argpos[n]: a for n, a in enumerate(args)}, **kwargs ) return self.apply_units_to_cache(data)
[ "def", "load_data", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# get positional argument names from parameters and apply them to args", "# update data with additional kwargs", "argpos", "=", "{", "v", "[", "'extras'", "]", "[", "'argpos'", "]",...
Collects positional and keyword arguments into `data` and applies units. :return: data
[ "Collects", "positional", "and", "keyword", "arguments", "into", "data", "and", "applies", "units", "." ]
205163d879d3880b6c9ef609f1b723a58773026b
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/contrib/readers.py#L60-L75
train
49,175
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
grid_reload_from_name
def grid_reload_from_name(job_name): """Reload all running or pending jobs of Grid'5000 with a given name. By default all the sites will be searched for jobs with the name ``job_name``. Using EnOSlib there can be only one job per site with name ``job_name``. Note that it honors the ``exluded_sites`` attribute of the client so the scan can be reduced. Args: job_name (str): the job name Returns: The list of the python-grid5000 jobs retrieved. Raises: EnosG5kDuplicateJobsError: if there's several jobs with the same name on a site. """ gk = get_api_client() sites = get_all_sites_obj() jobs = [] for site in [s for s in sites if s.uid not in gk.excluded_site]: logger.info("Reloading %s from %s" % (job_name, site.uid)) _jobs = site.jobs.list(name=job_name, state="waiting,launching,running") if len(_jobs) == 1: logger.info("Reloading %s from %s" % (_jobs[0].uid, site.uid)) jobs.append(_jobs[0]) elif len(_jobs) > 1: raise EnosG5kDuplicateJobsError(site, job_name) return jobs
python
def grid_reload_from_name(job_name): """Reload all running or pending jobs of Grid'5000 with a given name. By default all the sites will be searched for jobs with the name ``job_name``. Using EnOSlib there can be only one job per site with name ``job_name``. Note that it honors the ``exluded_sites`` attribute of the client so the scan can be reduced. Args: job_name (str): the job name Returns: The list of the python-grid5000 jobs retrieved. Raises: EnosG5kDuplicateJobsError: if there's several jobs with the same name on a site. """ gk = get_api_client() sites = get_all_sites_obj() jobs = [] for site in [s for s in sites if s.uid not in gk.excluded_site]: logger.info("Reloading %s from %s" % (job_name, site.uid)) _jobs = site.jobs.list(name=job_name, state="waiting,launching,running") if len(_jobs) == 1: logger.info("Reloading %s from %s" % (_jobs[0].uid, site.uid)) jobs.append(_jobs[0]) elif len(_jobs) > 1: raise EnosG5kDuplicateJobsError(site, job_name) return jobs
[ "def", "grid_reload_from_name", "(", "job_name", ")", ":", "gk", "=", "get_api_client", "(", ")", "sites", "=", "get_all_sites_obj", "(", ")", "jobs", "=", "[", "]", "for", "site", "in", "[", "s", "for", "s", "in", "sites", "if", "s", ".", "uid", "no...
Reload all running or pending jobs of Grid'5000 with a given name. By default all the sites will be searched for jobs with the name ``job_name``. Using EnOSlib there can be only one job per site with name ``job_name``. Note that it honors the ``exluded_sites`` attribute of the client so the scan can be reduced. Args: job_name (str): the job name Returns: The list of the python-grid5000 jobs retrieved. Raises: EnosG5kDuplicateJobsError: if there's several jobs with the same name on a site.
[ "Reload", "all", "running", "or", "pending", "jobs", "of", "Grid", "5000", "with", "a", "given", "name", "." ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L96-L129
train
49,176
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
grid_reload_from_ids
def grid_reload_from_ids(oargrid_jobids): """Reload all running or pending jobs of Grid'5000 from their ids Args: oargrid_jobids (list): list of ``(site, oar_jobid)`` identifying the jobs on each site Returns: The list of python-grid5000 jobs retrieved """ gk = get_api_client() jobs = [] for site, job_id in oargrid_jobids: jobs.append(gk.sites[site].jobs[job_id]) return jobs
python
def grid_reload_from_ids(oargrid_jobids): """Reload all running or pending jobs of Grid'5000 from their ids Args: oargrid_jobids (list): list of ``(site, oar_jobid)`` identifying the jobs on each site Returns: The list of python-grid5000 jobs retrieved """ gk = get_api_client() jobs = [] for site, job_id in oargrid_jobids: jobs.append(gk.sites[site].jobs[job_id]) return jobs
[ "def", "grid_reload_from_ids", "(", "oargrid_jobids", ")", ":", "gk", "=", "get_api_client", "(", ")", "jobs", "=", "[", "]", "for", "site", ",", "job_id", "in", "oargrid_jobids", ":", "jobs", ".", "append", "(", "gk", ".", "sites", "[", "site", "]", "...
Reload all running or pending jobs of Grid'5000 from their ids Args: oargrid_jobids (list): list of ``(site, oar_jobid)`` identifying the jobs on each site Returns: The list of python-grid5000 jobs retrieved
[ "Reload", "all", "running", "or", "pending", "jobs", "of", "Grid", "5000", "from", "their", "ids" ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L132-L146
train
49,177
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
grid_destroy_from_name
def grid_destroy_from_name(job_name): """Destroy all the jobs with a given name. Args: job_name (str): the job name """ jobs = grid_reload_from_name(job_name) for job in jobs: job.delete() logger.info("Killing the job (%s, %s)" % (job.site, job.uid))
python
def grid_destroy_from_name(job_name): """Destroy all the jobs with a given name. Args: job_name (str): the job name """ jobs = grid_reload_from_name(job_name) for job in jobs: job.delete() logger.info("Killing the job (%s, %s)" % (job.site, job.uid))
[ "def", "grid_destroy_from_name", "(", "job_name", ")", ":", "jobs", "=", "grid_reload_from_name", "(", "job_name", ")", "for", "job", "in", "jobs", ":", "job", ".", "delete", "(", ")", "logger", ".", "info", "(", "\"Killing the job (%s, %s)\"", "%", "(", "jo...
Destroy all the jobs with a given name. Args: job_name (str): the job name
[ "Destroy", "all", "the", "jobs", "with", "a", "given", "name", "." ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L149-L158
train
49,178
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
grid_destroy_from_ids
def grid_destroy_from_ids(oargrid_jobids): """Destroy all the jobs with corresponding ids Args: oargrid_jobids (list): the ``(site, oar_job_id)`` list of tuple identifying the jobs for each site. """ jobs = grid_reload_from_ids(oargrid_jobids) for job in jobs: job.delete() logger.info("Killing the jobs %s" % oargrid_jobids)
python
def grid_destroy_from_ids(oargrid_jobids): """Destroy all the jobs with corresponding ids Args: oargrid_jobids (list): the ``(site, oar_job_id)`` list of tuple identifying the jobs for each site. """ jobs = grid_reload_from_ids(oargrid_jobids) for job in jobs: job.delete() logger.info("Killing the jobs %s" % oargrid_jobids)
[ "def", "grid_destroy_from_ids", "(", "oargrid_jobids", ")", ":", "jobs", "=", "grid_reload_from_ids", "(", "oargrid_jobids", ")", "for", "job", "in", "jobs", ":", "job", ".", "delete", "(", ")", "logger", ".", "info", "(", "\"Killing the jobs %s\"", "%", "oarg...
Destroy all the jobs with corresponding ids Args: oargrid_jobids (list): the ``(site, oar_job_id)`` list of tuple identifying the jobs for each site.
[ "Destroy", "all", "the", "jobs", "with", "corresponding", "ids" ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L161-L170
train
49,179
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
wait_for_jobs
def wait_for_jobs(jobs): """Waits for all the jobs to be runnning. Args: jobs(list): list of the python-grid5000 jobs to wait for Raises: Exception: if one of the job gets in error state. """ all_running = False while not all_running: all_running = True time.sleep(5) for job in jobs: job.refresh() scheduled = getattr(job, "scheduled_at", None) if scheduled is not None: logger.info("Waiting for %s on %s [%s]" % (job.uid, job.site, _date2h(scheduled))) all_running = all_running and job.state == "running" if job.state == "error": raise Exception("The job %s is in error state" % job) logger.info("All jobs are Running !")
python
def wait_for_jobs(jobs): """Waits for all the jobs to be runnning. Args: jobs(list): list of the python-grid5000 jobs to wait for Raises: Exception: if one of the job gets in error state. """ all_running = False while not all_running: all_running = True time.sleep(5) for job in jobs: job.refresh() scheduled = getattr(job, "scheduled_at", None) if scheduled is not None: logger.info("Waiting for %s on %s [%s]" % (job.uid, job.site, _date2h(scheduled))) all_running = all_running and job.state == "running" if job.state == "error": raise Exception("The job %s is in error state" % job) logger.info("All jobs are Running !")
[ "def", "wait_for_jobs", "(", "jobs", ")", ":", "all_running", "=", "False", "while", "not", "all_running", ":", "all_running", "=", "True", "time", ".", "sleep", "(", "5", ")", "for", "job", "in", "jobs", ":", "job", ".", "refresh", "(", ")", "schedule...
Waits for all the jobs to be runnning. Args: jobs(list): list of the python-grid5000 jobs to wait for Raises: Exception: if one of the job gets in error state.
[ "Waits", "for", "all", "the", "jobs", "to", "be", "runnning", "." ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L195-L220
train
49,180
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
grid_deploy
def grid_deploy(site, nodes, options): """Deploy and wait for the deployment to be finished. Args: site(str): the site nodes(list): list of nodes (str) to depoy options(dict): option of the deployment (refer to the Grid'5000 API Specifications) Returns: tuple of deployed(list), undeployed(list) nodes. """ gk = get_api_client() environment = options.pop("env_name") options.update(environment=environment) options.update(nodes=nodes) key_path = DEFAULT_SSH_KEYFILE options.update(key=key_path.read_text()) logger.info("Deploying %s with options %s" % (nodes, options)) deployment = gk.sites[site].deployments.create(options) while deployment.status not in ["terminated", "error"]: deployment.refresh() print("Waiting for the end of deployment [%s]" % deployment.uid) time.sleep(10) deploy = [] undeploy = [] if deployment.status == "terminated": deploy = [node for node, v in deployment.result.items() if v["state"] == "OK"] undeploy = [node for node, v in deployment.result.items() if v["state"] == "KO"] elif deployment.status == "error": undeploy = nodes return deploy, undeploy
python
def grid_deploy(site, nodes, options): """Deploy and wait for the deployment to be finished. Args: site(str): the site nodes(list): list of nodes (str) to depoy options(dict): option of the deployment (refer to the Grid'5000 API Specifications) Returns: tuple of deployed(list), undeployed(list) nodes. """ gk = get_api_client() environment = options.pop("env_name") options.update(environment=environment) options.update(nodes=nodes) key_path = DEFAULT_SSH_KEYFILE options.update(key=key_path.read_text()) logger.info("Deploying %s with options %s" % (nodes, options)) deployment = gk.sites[site].deployments.create(options) while deployment.status not in ["terminated", "error"]: deployment.refresh() print("Waiting for the end of deployment [%s]" % deployment.uid) time.sleep(10) deploy = [] undeploy = [] if deployment.status == "terminated": deploy = [node for node, v in deployment.result.items() if v["state"] == "OK"] undeploy = [node for node, v in deployment.result.items() if v["state"] == "KO"] elif deployment.status == "error": undeploy = nodes return deploy, undeploy
[ "def", "grid_deploy", "(", "site", ",", "nodes", ",", "options", ")", ":", "gk", "=", "get_api_client", "(", ")", "environment", "=", "options", ".", "pop", "(", "\"env_name\"", ")", "options", ".", "update", "(", "environment", "=", "environment", ")", ...
Deploy and wait for the deployment to be finished. Args: site(str): the site nodes(list): list of nodes (str) to depoy options(dict): option of the deployment (refer to the Grid'5000 API Specifications) Returns: tuple of deployed(list), undeployed(list) nodes.
[ "Deploy", "and", "wait", "for", "the", "deployment", "to", "be", "finished", "." ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L223-L257
train
49,181
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
set_nodes_vlan
def set_nodes_vlan(site, nodes, interface, vlan_id): """Set the interface of the nodes in a specific vlan. It is assumed that the same interface name is available on the node. Args: site(str): site to consider nodes(list): nodes to consider interface(str): the network interface to put in the vlan vlan_id(str): the id of the vlan """ def _to_network_address(host): """Translate a host to a network address e.g: paranoia-20.rennes.grid5000.fr -> paranoia-20-eth2.rennes.grid5000.fr """ splitted = host.split('.') splitted[0] = splitted[0] + "-" + interface return ".".join(splitted) gk = get_api_client() network_addresses = [_to_network_address(n) for n in nodes] gk.sites[site].vlans[str(vlan_id)].submit({"nodes": network_addresses})
python
def set_nodes_vlan(site, nodes, interface, vlan_id): """Set the interface of the nodes in a specific vlan. It is assumed that the same interface name is available on the node. Args: site(str): site to consider nodes(list): nodes to consider interface(str): the network interface to put in the vlan vlan_id(str): the id of the vlan """ def _to_network_address(host): """Translate a host to a network address e.g: paranoia-20.rennes.grid5000.fr -> paranoia-20-eth2.rennes.grid5000.fr """ splitted = host.split('.') splitted[0] = splitted[0] + "-" + interface return ".".join(splitted) gk = get_api_client() network_addresses = [_to_network_address(n) for n in nodes] gk.sites[site].vlans[str(vlan_id)].submit({"nodes": network_addresses})
[ "def", "set_nodes_vlan", "(", "site", ",", "nodes", ",", "interface", ",", "vlan_id", ")", ":", "def", "_to_network_address", "(", "host", ")", ":", "\"\"\"Translate a host to a network address\n e.g:\n paranoia-20.rennes.grid5000.fr -> paranoia-20-eth2.rennes.grid5...
Set the interface of the nodes in a specific vlan. It is assumed that the same interface name is available on the node. Args: site(str): site to consider nodes(list): nodes to consider interface(str): the network interface to put in the vlan vlan_id(str): the id of the vlan
[ "Set", "the", "interface", "of", "the", "nodes", "in", "a", "specific", "vlan", "." ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L260-L282
train
49,182
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
clusters_sites_obj
def clusters_sites_obj(clusters): """Get all the corresponding sites of the passed clusters. Args: clusters(list): list of string uid of sites (e.g 'rennes') Return: dict corresponding to the mapping cluster uid to python-grid5000 site """ result = {} all_clusters = get_all_clusters_sites() clusters_sites = {c: s for (c, s) in all_clusters.items() if c in clusters} for cluster, site in clusters_sites.items(): # here we want the site python-grid5000 site object result.update({cluster: get_site_obj(site)}) return result
python
def clusters_sites_obj(clusters): """Get all the corresponding sites of the passed clusters. Args: clusters(list): list of string uid of sites (e.g 'rennes') Return: dict corresponding to the mapping cluster uid to python-grid5000 site """ result = {} all_clusters = get_all_clusters_sites() clusters_sites = {c: s for (c, s) in all_clusters.items() if c in clusters} for cluster, site in clusters_sites.items(): # here we want the site python-grid5000 site object result.update({cluster: get_site_obj(site)}) return result
[ "def", "clusters_sites_obj", "(", "clusters", ")", ":", "result", "=", "{", "}", "all_clusters", "=", "get_all_clusters_sites", "(", ")", "clusters_sites", "=", "{", "c", ":", "s", "for", "(", "c", ",", "s", ")", "in", "all_clusters", ".", "items", "(", ...
Get all the corresponding sites of the passed clusters. Args: clusters(list): list of string uid of sites (e.g 'rennes') Return: dict corresponding to the mapping cluster uid to python-grid5000 site
[ "Get", "all", "the", "corresponding", "sites", "of", "the", "passed", "clusters", "." ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L309-L326
train
49,183
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
get_all_clusters_sites
def get_all_clusters_sites(): """Get all the cluster of all the sites. Returns: dict corresponding to the mapping cluster uid to python-grid5000 site """ result = {} gk = get_api_client() sites = gk.sites.list() for site in sites: clusters = site.clusters.list() result.update({c.uid: site.uid for c in clusters}) return result
python
def get_all_clusters_sites(): """Get all the cluster of all the sites. Returns: dict corresponding to the mapping cluster uid to python-grid5000 site """ result = {} gk = get_api_client() sites = gk.sites.list() for site in sites: clusters = site.clusters.list() result.update({c.uid: site.uid for c in clusters}) return result
[ "def", "get_all_clusters_sites", "(", ")", ":", "result", "=", "{", "}", "gk", "=", "get_api_client", "(", ")", "sites", "=", "gk", ".", "sites", ".", "list", "(", ")", "for", "site", "in", "sites", ":", "clusters", "=", "site", ".", "clusters", ".",...
Get all the cluster of all the sites. Returns: dict corresponding to the mapping cluster uid to python-grid5000 site
[ "Get", "all", "the", "cluster", "of", "all", "the", "sites", "." ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L330-L342
train
49,184
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
get_nodes
def get_nodes(cluster): """Get all the nodes of a given cluster. Args: cluster(string): uid of the cluster (e.g 'rennes') """ gk = get_api_client() site = get_cluster_site(cluster) return gk.sites[site].clusters[cluster].nodes.list()
python
def get_nodes(cluster): """Get all the nodes of a given cluster. Args: cluster(string): uid of the cluster (e.g 'rennes') """ gk = get_api_client() site = get_cluster_site(cluster) return gk.sites[site].clusters[cluster].nodes.list()
[ "def", "get_nodes", "(", "cluster", ")", ":", "gk", "=", "get_api_client", "(", ")", "site", "=", "get_cluster_site", "(", "cluster", ")", "return", "gk", ".", "sites", "[", "site", "]", ".", "clusters", "[", "cluster", "]", ".", "nodes", ".", "list", ...
Get all the nodes of a given cluster. Args: cluster(string): uid of the cluster (e.g 'rennes')
[ "Get", "all", "the", "nodes", "of", "a", "given", "cluster", "." ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L372-L380
train
49,185
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
get_cluster_interfaces
def get_cluster_interfaces(cluster, extra_cond=lambda nic: True): """Get the network interfaces names corresponding to a criteria. Note that the cluster is passed (not the individual node names), thus it is assumed that all nodes in a cluster have the same interface names same configuration. In addition to ``extra_cond``, only the mountable and Ehernet interfaces are returned. Args: cluster(str): the cluster to consider extra_cond(lambda): boolean lambda that takes the nic(dict) as parameter """ nics = get_nics(cluster) # NOTE(msimonin): Since 05/18 nics on g5k nodes have predictable names but # the api description keep the legacy name (device key) and the new # predictable name (key name). The legacy names is still used for api # request to the vlan endpoint This should be fixed in # https://intranet.grid5000.fr/bugzilla/show_bug.cgi?id=9272 # When its fixed we should be able to only use the new predictable name. nics = [(nic['device'], nic['name']) for nic in nics if nic['mountable'] and nic['interface'] == 'Ethernet' and not nic['management'] and extra_cond(nic)] nics = sorted(nics) return nics
python
def get_cluster_interfaces(cluster, extra_cond=lambda nic: True): """Get the network interfaces names corresponding to a criteria. Note that the cluster is passed (not the individual node names), thus it is assumed that all nodes in a cluster have the same interface names same configuration. In addition to ``extra_cond``, only the mountable and Ehernet interfaces are returned. Args: cluster(str): the cluster to consider extra_cond(lambda): boolean lambda that takes the nic(dict) as parameter """ nics = get_nics(cluster) # NOTE(msimonin): Since 05/18 nics on g5k nodes have predictable names but # the api description keep the legacy name (device key) and the new # predictable name (key name). The legacy names is still used for api # request to the vlan endpoint This should be fixed in # https://intranet.grid5000.fr/bugzilla/show_bug.cgi?id=9272 # When its fixed we should be able to only use the new predictable name. nics = [(nic['device'], nic['name']) for nic in nics if nic['mountable'] and nic['interface'] == 'Ethernet' and not nic['management'] and extra_cond(nic)] nics = sorted(nics) return nics
[ "def", "get_cluster_interfaces", "(", "cluster", ",", "extra_cond", "=", "lambda", "nic", ":", "True", ")", ":", "nics", "=", "get_nics", "(", "cluster", ")", "# NOTE(msimonin): Since 05/18 nics on g5k nodes have predictable names but", "# the api description keep the legacy ...
Get the network interfaces names corresponding to a criteria. Note that the cluster is passed (not the individual node names), thus it is assumed that all nodes in a cluster have the same interface names same configuration. In addition to ``extra_cond``, only the mountable and Ehernet interfaces are returned. Args: cluster(str): the cluster to consider extra_cond(lambda): boolean lambda that takes the nic(dict) as parameter
[ "Get", "the", "network", "interfaces", "names", "corresponding", "to", "a", "criteria", "." ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L397-L423
train
49,186
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
get_clusters_interfaces
def get_clusters_interfaces(clusters, extra_cond=lambda nic: True): """ Returns for each cluster the available cluster interfaces Args: clusters (str): list of the clusters extra_cond (lambda): extra predicate to filter network card retrieved from the API. E.g lambda nic: not nic['mounted'] will retrieve all the usable network cards that are not mounted by default. Returns: dict of cluster with their associated nic names Examples: .. code-block:: python # pseudo code actual = get_clusters_interfaces(["paravance"]) expected = {"paravance": ["eth0", "eth1"]} assertDictEquals(expected, actual) """ interfaces = {} for cluster in clusters: nics = get_cluster_interfaces(cluster, extra_cond=extra_cond) interfaces.setdefault(cluster, nics) return interfaces
python
def get_clusters_interfaces(clusters, extra_cond=lambda nic: True): """ Returns for each cluster the available cluster interfaces Args: clusters (str): list of the clusters extra_cond (lambda): extra predicate to filter network card retrieved from the API. E.g lambda nic: not nic['mounted'] will retrieve all the usable network cards that are not mounted by default. Returns: dict of cluster with their associated nic names Examples: .. code-block:: python # pseudo code actual = get_clusters_interfaces(["paravance"]) expected = {"paravance": ["eth0", "eth1"]} assertDictEquals(expected, actual) """ interfaces = {} for cluster in clusters: nics = get_cluster_interfaces(cluster, extra_cond=extra_cond) interfaces.setdefault(cluster, nics) return interfaces
[ "def", "get_clusters_interfaces", "(", "clusters", ",", "extra_cond", "=", "lambda", "nic", ":", "True", ")", ":", "interfaces", "=", "{", "}", "for", "cluster", "in", "clusters", ":", "nics", "=", "get_cluster_interfaces", "(", "cluster", ",", "extra_cond", ...
Returns for each cluster the available cluster interfaces Args: clusters (str): list of the clusters extra_cond (lambda): extra predicate to filter network card retrieved from the API. E.g lambda nic: not nic['mounted'] will retrieve all the usable network cards that are not mounted by default. Returns: dict of cluster with their associated nic names Examples: .. code-block:: python # pseudo code actual = get_clusters_interfaces(["paravance"]) expected = {"paravance": ["eth0", "eth1"]} assertDictEquals(expected, actual)
[ "Returns", "for", "each", "cluster", "the", "available", "cluster", "interfaces" ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L426-L452
train
49,187
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/g5k_api_utils.py
_do_synchronise_jobs
def _do_synchronise_jobs(walltime, machines): """ This returns a common reservation date for all the jobs. This reservation date is really only a hint and will be supplied to each oar server. Without this *common* reservation_date, one oar server can decide to postpone the start of the job while the other are already running. But this doens't prevent the start of a job on one site to drift (e.g because the machines need to be restarted.) But this shouldn't exceed few minutes. """ offset = SYNCHRONISATION_OFFSET start = time.time() + offset _t = time.strptime(walltime, "%H:%M:%S") _walltime = _t.tm_hour * 3600 + _t.tm_min * 60 + _t.tm_sec # Compute the demand for each cluster demands = defaultdict(int) for machine in machines: cluster = machine["cluster"] demands[cluster] += machine["nodes"] # Early leave if only one cluster is there if len(list(demands.keys())) <= 1: logger.debug("Only one cluster detected: no synchronisation needed") return None clusters = clusters_sites_obj(list(demands.keys())) # Early leave if only one site is concerned sites = set(list(clusters.values())) if len(sites) <= 1: logger.debug("Only one site detected: no synchronisation needed") return None # Test the proposed reservation_date ok = True for cluster, nodes in demands.items(): cluster_status = clusters[cluster].status.list() ok = ok and can_start_on_cluster(cluster_status.nodes, nodes, start, _walltime) if not ok: break if ok: # The proposed reservation_date fits logger.info("Reservation_date=%s (%s)" % (_date2h(start), sites)) return start if start is None: raise EnosG5kSynchronisationError(sites)
python
def _do_synchronise_jobs(walltime, machines): """ This returns a common reservation date for all the jobs. This reservation date is really only a hint and will be supplied to each oar server. Without this *common* reservation_date, one oar server can decide to postpone the start of the job while the other are already running. But this doens't prevent the start of a job on one site to drift (e.g because the machines need to be restarted.) But this shouldn't exceed few minutes. """ offset = SYNCHRONISATION_OFFSET start = time.time() + offset _t = time.strptime(walltime, "%H:%M:%S") _walltime = _t.tm_hour * 3600 + _t.tm_min * 60 + _t.tm_sec # Compute the demand for each cluster demands = defaultdict(int) for machine in machines: cluster = machine["cluster"] demands[cluster] += machine["nodes"] # Early leave if only one cluster is there if len(list(demands.keys())) <= 1: logger.debug("Only one cluster detected: no synchronisation needed") return None clusters = clusters_sites_obj(list(demands.keys())) # Early leave if only one site is concerned sites = set(list(clusters.values())) if len(sites) <= 1: logger.debug("Only one site detected: no synchronisation needed") return None # Test the proposed reservation_date ok = True for cluster, nodes in demands.items(): cluster_status = clusters[cluster].status.list() ok = ok and can_start_on_cluster(cluster_status.nodes, nodes, start, _walltime) if not ok: break if ok: # The proposed reservation_date fits logger.info("Reservation_date=%s (%s)" % (_date2h(start), sites)) return start if start is None: raise EnosG5kSynchronisationError(sites)
[ "def", "_do_synchronise_jobs", "(", "walltime", ",", "machines", ")", ":", "offset", "=", "SYNCHRONISATION_OFFSET", "start", "=", "time", ".", "time", "(", ")", "+", "offset", "_t", "=", "time", ".", "strptime", "(", "walltime", ",", "\"%H:%M:%S\"", ")", "...
This returns a common reservation date for all the jobs. This reservation date is really only a hint and will be supplied to each oar server. Without this *common* reservation_date, one oar server can decide to postpone the start of the job while the other are already running. But this doens't prevent the start of a job on one site to drift (e.g because the machines need to be restarted.) But this shouldn't exceed few minutes.
[ "This", "returns", "a", "common", "reservation", "date", "for", "all", "the", "jobs", "." ]
fb00be58e56a7848cfe482187d659744919fe2f7
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/g5k_api_utils.py#L493-L543
train
49,188
volafiled/python-volapi
volapi/handler.py
Handler.add_data
def add_data(self, rawdata): """Add data to given room's state""" for data in rawdata: try: item = data[0] if item[0] == 2: # Flush messages but we got nothing to flush continue if item[0] != 0: warnings.warn(f"Unknown message type '{item[0]}'", Warning) continue item = item[1] # convert target to string because error codes are ints target = str(item[0]) try: data = item[1] except IndexError: data = dict() try: method = getattr(self, self.__head + target) method(data) except AttributeError: self._handle_unhandled(target, data) except IndexError: LOGGER.warning("Wrongly constructed message received: %r", data) self.conn.process_queues()
python
def add_data(self, rawdata): """Add data to given room's state""" for data in rawdata: try: item = data[0] if item[0] == 2: # Flush messages but we got nothing to flush continue if item[0] != 0: warnings.warn(f"Unknown message type '{item[0]}'", Warning) continue item = item[1] # convert target to string because error codes are ints target = str(item[0]) try: data = item[1] except IndexError: data = dict() try: method = getattr(self, self.__head + target) method(data) except AttributeError: self._handle_unhandled(target, data) except IndexError: LOGGER.warning("Wrongly constructed message received: %r", data) self.conn.process_queues()
[ "def", "add_data", "(", "self", ",", "rawdata", ")", ":", "for", "data", "in", "rawdata", ":", "try", ":", "item", "=", "data", "[", "0", "]", "if", "item", "[", "0", "]", "==", "2", ":", "# Flush messages but we got nothing to flush", "continue", "if", ...
Add data to given room's state
[ "Add", "data", "to", "given", "room", "s", "state" ]
5f0bc03dbde703264ac6ed494e2050761f688a3e
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L34-L61
train
49,189
volafiled/python-volapi
volapi/handler.py
Handler.register_callback
def register_callback(self): """Register callback that we will have to wait for""" cid = str(self.__cid) self.__cid += 1 event = queue.Queue() self.__callbacks[cid] = event return cid, event
python
def register_callback(self): """Register callback that we will have to wait for""" cid = str(self.__cid) self.__cid += 1 event = queue.Queue() self.__callbacks[cid] = event return cid, event
[ "def", "register_callback", "(", "self", ")", ":", "cid", "=", "str", "(", "self", ".", "__cid", ")", "self", ".", "__cid", "+=", "1", "event", "=", "queue", ".", "Queue", "(", ")", "self", ".", "__callbacks", "[", "cid", "]", "=", "event", "return...
Register callback that we will have to wait for
[ "Register", "callback", "that", "we", "will", "have", "to", "wait", "for" ]
5f0bc03dbde703264ac6ed494e2050761f688a3e
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L63-L70
train
49,190
volafiled/python-volapi
volapi/handler.py
Handler._handle_callback
def _handle_callback(self, data): """Handle lain's callback. Only used with getFileinfo so far""" cb_id = data.get("id") args = data.get("args") event = self.__callbacks.pop(cb_id, None) if not event: return if not args: event.put(args) return err, info = args if err is None: event.put(info) else: LOGGER.warning("Callback returned error of %s", str(err)) event.put(err)
python
def _handle_callback(self, data): """Handle lain's callback. Only used with getFileinfo so far""" cb_id = data.get("id") args = data.get("args") event = self.__callbacks.pop(cb_id, None) if not event: return if not args: event.put(args) return err, info = args if err is None: event.put(info) else: LOGGER.warning("Callback returned error of %s", str(err)) event.put(err)
[ "def", "_handle_callback", "(", "self", ",", "data", ")", ":", "cb_id", "=", "data", ".", "get", "(", "\"id\"", ")", "args", "=", "data", ".", "get", "(", "\"args\"", ")", "event", "=", "self", ".", "__callbacks", ".", "pop", "(", "cb_id", ",", "No...
Handle lain's callback. Only used with getFileinfo so far
[ "Handle", "lain", "s", "callback", ".", "Only", "used", "with", "getFileinfo", "so", "far" ]
5f0bc03dbde703264ac6ed494e2050761f688a3e
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L97-L113
train
49,191
volafiled/python-volapi
volapi/handler.py
Handler._handle_userCount
def _handle_userCount(self, data): """Handle user count changes""" self.room.user_count = data self.conn.enqueue_data("user_count", self.room.user_count)
python
def _handle_userCount(self, data): """Handle user count changes""" self.room.user_count = data self.conn.enqueue_data("user_count", self.room.user_count)
[ "def", "_handle_userCount", "(", "self", ",", "data", ")", ":", "self", ".", "room", ".", "user_count", "=", "data", "self", ".", "conn", ".", "enqueue_data", "(", "\"user_count\"", ",", "self", ".", "room", ".", "user_count", ")" ]
Handle user count changes
[ "Handle", "user", "count", "changes" ]
5f0bc03dbde703264ac6ed494e2050761f688a3e
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L115-L119
train
49,192
volafiled/python-volapi
volapi/handler.py
Handler._handle_userInfo
def _handle_userInfo(self, data): """Handle user information""" for k, v in data.items(): if k == "nick": if v == "None": v = "Volaphile" setattr(self.room.user, k, v) self.conn.enqueue_data(k, self.room.user.nick) elif k != "profile": if not hasattr(self.room, k): warnings.warn(f"Skipping unset property {k}", ResourceWarning) continue setattr(self.room, k, v) self.conn.enqueue_data(k, getattr(self.room, k)) self.room.user_info = k, v self.conn.enqueue_data("user_info", self.room.user_info)
python
def _handle_userInfo(self, data): """Handle user information""" for k, v in data.items(): if k == "nick": if v == "None": v = "Volaphile" setattr(self.room.user, k, v) self.conn.enqueue_data(k, self.room.user.nick) elif k != "profile": if not hasattr(self.room, k): warnings.warn(f"Skipping unset property {k}", ResourceWarning) continue setattr(self.room, k, v) self.conn.enqueue_data(k, getattr(self.room, k)) self.room.user_info = k, v self.conn.enqueue_data("user_info", self.room.user_info)
[ "def", "_handle_userInfo", "(", "self", ",", "data", ")", ":", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "if", "k", "==", "\"nick\"", ":", "if", "v", "==", "\"None\"", ":", "v", "=", "\"Volaphile\"", "setattr", "(", "self", ...
Handle user information
[ "Handle", "user", "information" ]
5f0bc03dbde703264ac6ed494e2050761f688a3e
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L121-L137
train
49,193
volafiled/python-volapi
volapi/handler.py
Handler._handle_config
def _handle_config(self, data): """Handle initial config push and config changes""" self.room.config.update(data) self.conn.enqueue_data("config", data)
python
def _handle_config(self, data): """Handle initial config push and config changes""" self.room.config.update(data) self.conn.enqueue_data("config", data)
[ "def", "_handle_config", "(", "self", ",", "data", ")", ":", "self", ".", "room", ".", "config", ".", "update", "(", "data", ")", "self", ".", "conn", ".", "enqueue_data", "(", "\"config\"", ",", "data", ")" ]
Handle initial config push and config changes
[ "Handle", "initial", "config", "push", "and", "config", "changes" ]
5f0bc03dbde703264ac6ed494e2050761f688a3e
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L145-L149
train
49,194
volafiled/python-volapi
volapi/handler.py
Handler._handle_files
def _handle_files(self, data): """Handle new files being uploaded""" initial = data.get("set", False) files = data["files"] for f in files: try: fobj = File( self.room, self.conn, f[0], f[1], type=f[2], size=f[3], expire_time=int(f[4]) / 1000, uploader=f[6].get("nick") or f[6].get("user"), ) self.room.filedict = fobj.fid, fobj if not initial: self.conn.enqueue_data("file", fobj) except Exception: import pprint LOGGER.exception("bad file") pprint.pprint(f) if initial: self.conn.enqueue_data("initial_files", self.room.files)
python
def _handle_files(self, data): """Handle new files being uploaded""" initial = data.get("set", False) files = data["files"] for f in files: try: fobj = File( self.room, self.conn, f[0], f[1], type=f[2], size=f[3], expire_time=int(f[4]) / 1000, uploader=f[6].get("nick") or f[6].get("user"), ) self.room.filedict = fobj.fid, fobj if not initial: self.conn.enqueue_data("file", fobj) except Exception: import pprint LOGGER.exception("bad file") pprint.pprint(f) if initial: self.conn.enqueue_data("initial_files", self.room.files)
[ "def", "_handle_files", "(", "self", ",", "data", ")", ":", "initial", "=", "data", ".", "get", "(", "\"set\"", ",", "False", ")", "files", "=", "data", "[", "\"files\"", "]", "for", "f", "in", "files", ":", "try", ":", "fobj", "=", "File", "(", ...
Handle new files being uploaded
[ "Handle", "new", "files", "being", "uploaded" ]
5f0bc03dbde703264ac6ed494e2050761f688a3e
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L151-L177
train
49,195
volafiled/python-volapi
volapi/handler.py
Handler._handle_delete_file
def _handle_delete_file(self, data): """Handle files being removed""" file = self.room.filedict.get(data) if file: self.room.filedict = data, None self.conn.enqueue_data("delete_file", file)
python
def _handle_delete_file(self, data): """Handle files being removed""" file = self.room.filedict.get(data) if file: self.room.filedict = data, None self.conn.enqueue_data("delete_file", file)
[ "def", "_handle_delete_file", "(", "self", ",", "data", ")", ":", "file", "=", "self", ".", "room", ".", "filedict", ".", "get", "(", "data", ")", "if", "file", ":", "self", ".", "room", ".", "filedict", "=", "data", ",", "None", "self", ".", "conn...
Handle files being removed
[ "Handle", "files", "being", "removed" ]
5f0bc03dbde703264ac6ed494e2050761f688a3e
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L179-L185
train
49,196
volafiled/python-volapi
volapi/handler.py
Handler._handle_chat
def _handle_chat(self, data): """Handle chat messages""" self.conn.enqueue_data( "chat", ChatMessage.from_data(self.room, self.conn, data) )
python
def _handle_chat(self, data): """Handle chat messages""" self.conn.enqueue_data( "chat", ChatMessage.from_data(self.room, self.conn, data) )
[ "def", "_handle_chat", "(", "self", ",", "data", ")", ":", "self", ".", "conn", ".", "enqueue_data", "(", "\"chat\"", ",", "ChatMessage", ".", "from_data", "(", "self", ".", "room", ",", "self", ".", "conn", ",", "data", ")", ")" ]
Handle chat messages
[ "Handle", "chat", "messages" ]
5f0bc03dbde703264ac6ed494e2050761f688a3e
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L187-L192
train
49,197
volafiled/python-volapi
volapi/handler.py
Handler._handle_changed_config
def _handle_changed_config(self, change): """Handle configuration changes""" key, value = change.get("key"), change.get("value") self.room.config.update({key: value}) self.conn.enqueue_data("config", self.room.config)
python
def _handle_changed_config(self, change): """Handle configuration changes""" key, value = change.get("key"), change.get("value") self.room.config.update({key: value}) self.conn.enqueue_data("config", self.room.config)
[ "def", "_handle_changed_config", "(", "self", ",", "change", ")", ":", "key", ",", "value", "=", "change", ".", "get", "(", "\"key\"", ")", ",", "change", ".", "get", "(", "\"value\"", ")", "self", ".", "room", ".", "config", ".", "update", "(", "{",...
Handle configuration changes
[ "Handle", "configuration", "changes" ]
5f0bc03dbde703264ac6ed494e2050761f688a3e
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L194-L199
train
49,198
volafiled/python-volapi
volapi/handler.py
Handler._handle_chat_name
def _handle_chat_name(self, data): """Handle user name changes""" self.room.user.nick = data self.conn.enqueue_data("user", self.room.user)
python
def _handle_chat_name(self, data): """Handle user name changes""" self.room.user.nick = data self.conn.enqueue_data("user", self.room.user)
[ "def", "_handle_chat_name", "(", "self", ",", "data", ")", ":", "self", ".", "room", ".", "user", ".", "nick", "=", "data", "self", ".", "conn", ".", "enqueue_data", "(", "\"user\"", ",", "self", ".", "room", ".", "user", ")" ]
Handle user name changes
[ "Handle", "user", "name", "changes" ]
5f0bc03dbde703264ac6ed494e2050761f688a3e
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/handler.py#L201-L205
train
49,199