Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|> 'type': 'cppdbg',
'request': 'launch',
'program': path,
'args': [],
'stopAtEntry': stop_at_entry[1],
'cwd': cwd,
'MIMode': 'lldb',
'preLaunchTask': tgt if pre_launch_build[1] else ''
}
launch['configurations'].append(c)
# add a python code-generator debug config
c = {
'name': 'fips codegen',
'type': 'python',
'request': 'launch',
'stopOnEntry': True,
'pythonPath': '${config:python.pythonPath}',
'program': build_dir + '/fips-gen.py',
'args': [ build_dir + '/fips_codegen.yml' ],
"cwd": proj_dir,
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
]
}
launch['configurations'].append(c)
# add a python debug config for each fips verb
<|code_end|>
. Write the next line using the current file imports:
import platform,subprocess, os, yaml, json, inspect, tempfile, glob, shutil
from mod import util, log, verb, dep
from mod.tools import cmake
and context from other files:
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/verb.py
# def import_verbs_from(proj_name, proj_dir, verb_dir) :
# def import_verbs(fips_dir, proj_dir) :
#
# Path: mod/dep.py
# def get_imports(fips_dir, proj_dir) :
# def get_exports(proj_dir) :
# def get_policy(proj_dir, policy) :
# def _rec_get_all_imports_exports(fips_dir, proj_dir, result) :
# def get_all_imports_exports(fips_dir, proj_dir) :
# def _rec_fetch_imports(fips_dir, proj_dir, handled) :
# def fetch_imports(fips_dir, proj_dir) :
# def gather_imports(fips_dir, proj_dir) :
# def write_imports(fips_dir, proj_dir, cfg_name, imported) :
# def gather_and_write_imports(fips_dir, proj_dir, cfg_name) :
# def check_imports(fips_dir, proj_dir) :
# def check_local_changes(fips_dir, proj_dir) :
# def _rec_update_imports(fips_dir, proj_dir, handled) :
# def update_imports(fips_dir, proj_dir):
#
# Path: mod/tools/cmake.py
# def check_exists(fips_dir, major=2, minor=8) :
# def run_gen(cfg, fips_dir, project_dir, build_dir, local_build, toolchain_path, defines) :
# def run_build(fips_dir, target, build_type, build_dir, num_jobs=1, args=None) :
# def run_clean(fips_dir, build_dir) :
, which may include functions, classes, or code. Output only the next line. | for verb_name, verb_mod in verb.verbs.items() : |
Predict the next line after this snippet: <|code_start|> log.info(' writing {}'.format(ws_path))
with open(ws_path, 'w') as f:
json.dump(ws, f, indent=1, separators=(',',':'))
#-------------------------------------------------------------------------------
def remove_vscode_tasks_launch_files(fips_dir, proj_dir, impex, cfg):
'''walks through the dependencies, and deletes the .vscode/tasks.json
and .vscode/launch.json files
'''
for dep_proj_name in reversed(impex):
dep_proj_dir = util.get_project_dir(fips_dir, dep_proj_name)
tasks_path = dep_proj_dir + '/.vscode/tasks.json'
launch_path = dep_proj_dir + '/.vscode/launch.json'
if os.path.exists(tasks_path):
log.info(' deleting {}'.format(tasks_path))
os.remove(tasks_path)
if os.path.exists(launch_path):
log.info(' deleting {}'.format(launch_path))
os.remove(launch_path)
#-------------------------------------------------------------------------------
def write_workspace_settings(fips_dir, proj_dir, cfg, proj_settings):
'''write the VSCode launch.json, tasks.json and
c_cpp_properties.json files from cmake output files
'''
log.info("=== writing Visual Studio Code config files...")
vscode_dir = proj_dir + '/.vscode'
if not os.path.isdir(vscode_dir):
os.makedirs(vscode_dir)
# fetch all project dependencies
<|code_end|>
using the current file's imports:
import platform,subprocess, os, yaml, json, inspect, tempfile, glob, shutil
from mod import util, log, verb, dep
from mod.tools import cmake
and any relevant context from other files:
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/verb.py
# def import_verbs_from(proj_name, proj_dir, verb_dir) :
# def import_verbs(fips_dir, proj_dir) :
#
# Path: mod/dep.py
# def get_imports(fips_dir, proj_dir) :
# def get_exports(proj_dir) :
# def get_policy(proj_dir, policy) :
# def _rec_get_all_imports_exports(fips_dir, proj_dir, result) :
# def get_all_imports_exports(fips_dir, proj_dir) :
# def _rec_fetch_imports(fips_dir, proj_dir, handled) :
# def fetch_imports(fips_dir, proj_dir) :
# def gather_imports(fips_dir, proj_dir) :
# def write_imports(fips_dir, proj_dir, cfg_name, imported) :
# def gather_and_write_imports(fips_dir, proj_dir, cfg_name) :
# def check_imports(fips_dir, proj_dir) :
# def check_local_changes(fips_dir, proj_dir) :
# def _rec_update_imports(fips_dir, proj_dir, handled) :
# def update_imports(fips_dir, proj_dir):
#
# Path: mod/tools/cmake.py
# def check_exists(fips_dir, major=2, minor=8) :
# def run_gen(cfg, fips_dir, project_dir, build_dir, local_build, toolchain_path, defines) :
# def run_build(fips_dir, target, build_type, build_dir, num_jobs=1, args=None) :
# def run_clean(fips_dir, build_dir) :
. Output only the next line. | success, impex = dep.get_all_imports_exports(fips_dir, proj_dir) |
Given snippet: <|code_start|>
# dictionary of "name: module"
verbs = {}
# dictionary of "projname: name"
proj_verbs = OrderedDict()
#-------------------------------------------------------------------------------
def import_verbs_from(proj_name, proj_dir, verb_dir) :
"""import all verb modules from a directory, populates the
verb and proj_verbs global variables
:param proj_dir: name of project that owns verb_dir
:param verb_dir: directory with verb python scripts (can be None)
"""
global verbs, proj_verbs
# make sure project-verbs find their modules
sys.path.insert(0, proj_dir)
if verb_dir and os.path.isdir(verb_dir):
# get all .py file in verb dir
verb_paths = glob.glob(verb_dir + '/*.py')
if verb_paths :
for verb_path in verb_paths :
verb_module_name = os.path.split(verb_path)[1]
verb_module_name = os.path.splitext(verb_module_name)[0]
if not verb_module_name.startswith('__') :
if is_python3:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import os
import glob
import importlib.util
import imp
from collections import OrderedDict
from mod import log, util, dep
and context:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/dep.py
# def get_imports(fips_dir, proj_dir) :
# def get_exports(proj_dir) :
# def get_policy(proj_dir, policy) :
# def _rec_get_all_imports_exports(fips_dir, proj_dir, result) :
# def get_all_imports_exports(fips_dir, proj_dir) :
# def _rec_fetch_imports(fips_dir, proj_dir, handled) :
# def fetch_imports(fips_dir, proj_dir) :
# def gather_imports(fips_dir, proj_dir) :
# def write_imports(fips_dir, proj_dir, cfg_name, imported) :
# def gather_and_write_imports(fips_dir, proj_dir, cfg_name) :
# def check_imports(fips_dir, proj_dir) :
# def check_local_changes(fips_dir, proj_dir) :
# def _rec_update_imports(fips_dir, proj_dir, handled) :
# def update_imports(fips_dir, proj_dir):
which might include code, classes, or functions. Output only the next line. | spec = importlib.util.spec_from_file_location(verb_module_name, verb_path) |
Given the following code snippet before the placeholder: <|code_start|> verb_module_name = os.path.split(verb_path)[1]
verb_module_name = os.path.splitext(verb_module_name)[0]
if not verb_module_name.startswith('__') :
if is_python3:
spec = importlib.util.spec_from_file_location(verb_module_name, verb_path)
verb_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(verb_module)
else:
# FIXME: PYTHON2
fp, pathname, desc = imp.find_module(verb_module_name, [verb_dir])
verb_module = imp.load_module(verb_module_name, fp, pathname, desc)
verbs[verb_module_name] = verb_module
if proj_name not in proj_verbs :
proj_verbs[proj_name] = []
proj_verbs[proj_name].append(verb_module_name)
#-------------------------------------------------------------------------------
def import_verbs(fips_dir, proj_dir) :
"""import verbs from local and imported projects, populates
the 'verbs' and 'proj_verbs' dictionaries
:param fipsdir: absolute fips directory
:param proj_dir: absolute project directory
"""
# first import verbs from fips directory
import_verbs_from('fips', fips_dir, fips_dir + '/verbs')
# now go through all imported projects
if fips_dir != proj_dir :
<|code_end|>
, predict the next line using imports from the current file:
import sys
import os
import glob
import importlib.util
import imp
from collections import OrderedDict
from mod import log, util, dep
and context including class names, function names, and sometimes code from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/dep.py
# def get_imports(fips_dir, proj_dir) :
# def get_exports(proj_dir) :
# def get_policy(proj_dir, policy) :
# def _rec_get_all_imports_exports(fips_dir, proj_dir, result) :
# def get_all_imports_exports(fips_dir, proj_dir) :
# def _rec_fetch_imports(fips_dir, proj_dir, handled) :
# def fetch_imports(fips_dir, proj_dir) :
# def gather_imports(fips_dir, proj_dir) :
# def write_imports(fips_dir, proj_dir, cfg_name, imported) :
# def gather_and_write_imports(fips_dir, proj_dir, cfg_name) :
# def check_imports(fips_dir, proj_dir) :
# def check_local_changes(fips_dir, proj_dir) :
# def _rec_update_imports(fips_dir, proj_dir, handled) :
# def update_imports(fips_dir, proj_dir):
. Output only the next line. | _, imported_projs = dep.get_all_imports_exports(fips_dir, proj_dir) |
Continue the code snippet: <|code_start|> os.makedirs(get_sdkroot_dir(fips_dir))
#-------------------------------------------------------------------------------
def get_emsdk_dir(fips_dir):
return get_sdkroot_dir(fips_dir) + '/emsdk'
#-------------------------------------------------------------------------------
def emsdk_dir_exists(fips_dir):
emsdk_dir = get_emsdk_dir(fips_dir)
return os.path.isdir(emsdk_dir)
#-------------------------------------------------------------------------------
def get_emsdk_path(fips_dir):
emsdk_script = 'emsdk.bat' if util.get_host_platform() == 'win' else 'emsdk'
emsdk_path = get_emsdk_dir(fips_dir) + '/' + emsdk_script
return emsdk_path
#-------------------------------------------------------------------------------
def check_exists(fips_dir):
emsdk_path = get_emsdk_path(fips_dir)
return os.path.isfile(emsdk_path)
#-------------------------------------------------------------------------------
def get_em_config(fips_dir):
# returns the path to the local .emscripten file
return get_emsdk_dir(fips_dir) + '/.emscripten'
#-------------------------------------------------------------------------------
def run(fips_dir, cmdline):
if not check_exists(fips_dir):
<|code_end|>
. Use current file imports:
import os, stat, subprocess, shutil
from mod import log, util
from mod.tools import git
and context (classes, functions, or code) from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/tools/git.py
# def check_exists(fips_dir=None) :
# def check_exists_with_error():
# def clone(url, branch, depth, name, cwd) :
# def add(proj_dir, update=False):
# def commit(proj_dir, msg):
# def commit_allow_empty(proj_dir, msg):
# def push(proj_dir):
# def has_local_changes(proj_dir):
# def update_submodule(proj_dir):
# def update(proj_dir):
# def update_force_and_ignore_local_changes(proj_dir):
# def get_branches(proj_dir) :
# def checkout(proj_dir, revision) :
# def has_uncommitted_files(proj_dir) :
# def get_remote_rev(proj_dir, remote_branch) :
# def get_local_rev(proj_dir, local_branch) :
# def check_out_of_sync(proj_dir) :
# def check_branch_out_of_sync(proj_dir, branch) :
. Output only the next line. | log.error("emsdk script not found at '{}', please run './fips emsdk install'".format(get_emsdk_path(fips_dir))) |
Predict the next line for this snippet: <|code_start|> Backend code for the new 'emsdk' verb.
This provides a more flexible wrapper for the emsdk emscripten SDK
installer.
Changes to the previous approach:
- emsdk is installed via git
- things like updating or switching SDK versions work by directly
forwarding commands to the emsdk script
- it's possible to query the active SDK root directory for forwarding
to cmake (the emscripten cmake toolchain file will no longer
be hardwired to a specific version)
"""
EMSDK_URL = "https://github.com/emscripten-core/emsdk.git"
EMSDK_DEFAULT_VERSION = 'latest'
# this is an error callback function for shutil.rmtree to make
# read-only files writable after rmtree failed to delete them
#
# from: https://docs.python.org/3.5/library/shutil.html#rmtree-example
#
def remove_readonly(func, path, _):
os.chmod(path, stat.S_IWRITE)
func(path)
#-------------------------------------------------------------------------------
def get_sdkroot_dir(fips_dir):
<|code_end|>
with the help of current file imports:
import os, stat, subprocess, shutil
from mod import log, util
from mod.tools import git
and context from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/tools/git.py
# def check_exists(fips_dir=None) :
# def check_exists_with_error():
# def clone(url, branch, depth, name, cwd) :
# def add(proj_dir, update=False):
# def commit(proj_dir, msg):
# def commit_allow_empty(proj_dir, msg):
# def push(proj_dir):
# def has_local_changes(proj_dir):
# def update_submodule(proj_dir):
# def update(proj_dir):
# def update_force_and_ignore_local_changes(proj_dir):
# def get_branches(proj_dir) :
# def checkout(proj_dir, revision) :
# def has_uncommitted_files(proj_dir) :
# def get_remote_rev(proj_dir, remote_branch) :
# def get_local_rev(proj_dir, local_branch) :
# def check_out_of_sync(proj_dir) :
# def check_branch_out_of_sync(proj_dir, branch) :
, which may contain function names, class names, or code. Output only the next line. | return util.get_workspace_dir(fips_dir) + '/fips-sdks' |
Here is a snippet: <|code_start|>def get_emsdk_path(fips_dir):
emsdk_script = 'emsdk.bat' if util.get_host_platform() == 'win' else 'emsdk'
emsdk_path = get_emsdk_dir(fips_dir) + '/' + emsdk_script
return emsdk_path
#-------------------------------------------------------------------------------
def check_exists(fips_dir):
emsdk_path = get_emsdk_path(fips_dir)
return os.path.isfile(emsdk_path)
#-------------------------------------------------------------------------------
def get_em_config(fips_dir):
# returns the path to the local .emscripten file
return get_emsdk_dir(fips_dir) + '/.emscripten'
#-------------------------------------------------------------------------------
def run(fips_dir, cmdline):
if not check_exists(fips_dir):
log.error("emsdk script not found at '{}', please run './fips emsdk install'".format(get_emsdk_path(fips_dir)))
emsdk_path = get_emsdk_path(fips_dir)
emsdk_dir = get_emsdk_dir(fips_dir)
cmd = '{} {}'.format(emsdk_path, cmdline)
subprocess.call(cmd, cwd=emsdk_dir, shell=True)
#-------------------------------------------------------------------------------
def clone_or_update_emsdk(fips_dir):
# returns True on success
emsdk_dir = get_emsdk_dir(fips_dir)
if emsdk_dir_exists(fips_dir):
log.colored(log.YELLOW, "=== updating emscripten SDK at '{}'".format(emsdk_dir))
<|code_end|>
. Write the next line using the current file imports:
import os, stat, subprocess, shutil
from mod import log, util
from mod.tools import git
and context from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/tools/git.py
# def check_exists(fips_dir=None) :
# def check_exists_with_error():
# def clone(url, branch, depth, name, cwd) :
# def add(proj_dir, update=False):
# def commit(proj_dir, msg):
# def commit_allow_empty(proj_dir, msg):
# def push(proj_dir):
# def has_local_changes(proj_dir):
# def update_submodule(proj_dir):
# def update(proj_dir):
# def update_force_and_ignore_local_changes(proj_dir):
# def get_branches(proj_dir) :
# def checkout(proj_dir, revision) :
# def has_uncommitted_files(proj_dir) :
# def get_remote_rev(proj_dir, remote_branch) :
# def get_local_rev(proj_dir, local_branch) :
# def check_out_of_sync(proj_dir) :
# def check_branch_out_of_sync(proj_dir, branch) :
, which may include functions, classes, or code. Output only the next line. | return git.update_force_and_ignore_local_changes(emsdk_dir) |
Given the following code snippet before the placeholder: <|code_start|>"""helper verb for CLion support
clion clean -- removes all .idea directories in all dependencies
"""
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
if not util.is_valid_project_dir(proj_dir) :
<|code_end|>
, predict the next line using imports from the current file:
from mod import log, util
from mod.tools import clion
and context including class names, function names, and sometimes code from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/tools/clion.py
# def check_exists(fips_dir) :
# def match(build_tool):
# def run(proj_dir):
# def write_clion_module_files(fips_dir, proj_dir, cfg):
# def write_clion_workspace_file(fips_dir, proj_dir, cfg):
# def write_workspace_settings(fips_dir, proj_dir, cfg):
# def cleanup(fips_dir, proj_dir):
. Output only the next line. | log.error('must be run in a project directory') |
Next line prediction: <|code_start|>"""helper verb for CLion support
clion clean -- removes all .idea directories in all dependencies
"""
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
if not util.is_valid_project_dir(proj_dir) :
log.error('must be run in a project directory')
if len(args) > 0:
if args[0] == 'clean':
<|code_end|>
. Use current file imports:
(from mod import log, util
from mod.tools import clion)
and context including class names, function names, or small code snippets from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/tools/clion.py
# def check_exists(fips_dir) :
# def match(build_tool):
# def run(proj_dir):
# def write_clion_module_files(fips_dir, proj_dir, cfg):
# def write_clion_workspace_file(fips_dir, proj_dir, cfg):
# def write_workspace_settings(fips_dir, proj_dir, cfg):
# def cleanup(fips_dir, proj_dir):
. Output only the next line. | clion.cleanup(fips_dir, proj_dir) |
Based on the snippet: <|code_start|>"""implement 'make' verb (builds a single target)
make
make [target]
make [target] [config]
"""
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
"""build a single target"""
if not util.is_valid_project_dir(proj_dir) :
<|code_end|>
, predict the immediate next line with the help of imports:
from mod import log, util, settings, project
and context (classes, functions, sometimes code) from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/settings.py
# def load(proj_dir) :
# def save(proj_dir, settings) :
# def get_default(key) :
# def get(proj_dir, key) :
# def set(proj_dir, key, value) :
# def unset(proj_dir, key) :
# def get_all_settings(proj_dir):
#
# Path: mod/project.py
# def init(fips_dir, proj_name) :
# def clone(fips_dir, url) :
# def gen_project(fips_dir, proj_dir, cfg, force) :
# def gen(fips_dir, proj_dir, cfg_name) :
# def configure(fips_dir, proj_dir, cfg_name) :
# def make_clean(fips_dir, proj_dir, cfg_name) :
# def build(fips_dir, proj_dir, cfg_name, target=None, build_tool_args=None) :
# def run(fips_dir, proj_dir, cfg_name, target_name, target_args, target_cwd) :
# def clean(fips_dir, proj_dir, cfg_name) :
# def get_target_list(fips_dir, proj_dir, cfg_name) :
. Output only the next line. | log.error('must be run in a project directory') |
Based on the snippet: <|code_start|>"""implement 'make' verb (builds a single target)
make
make [target]
make [target] [config]
"""
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
"""build a single target"""
<|code_end|>
, predict the immediate next line with the help of imports:
from mod import log, util, settings, project
and context (classes, functions, sometimes code) from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/settings.py
# def load(proj_dir) :
# def save(proj_dir, settings) :
# def get_default(key) :
# def get(proj_dir, key) :
# def set(proj_dir, key, value) :
# def unset(proj_dir, key) :
# def get_all_settings(proj_dir):
#
# Path: mod/project.py
# def init(fips_dir, proj_name) :
# def clone(fips_dir, url) :
# def gen_project(fips_dir, proj_dir, cfg, force) :
# def gen(fips_dir, proj_dir, cfg_name) :
# def configure(fips_dir, proj_dir, cfg_name) :
# def make_clean(fips_dir, proj_dir, cfg_name) :
# def build(fips_dir, proj_dir, cfg_name, target=None, build_tool_args=None) :
# def run(fips_dir, proj_dir, cfg_name, target_name, target_args, target_cwd) :
# def clean(fips_dir, proj_dir, cfg_name) :
# def get_target_list(fips_dir, proj_dir, cfg_name) :
. Output only the next line. | if not util.is_valid_project_dir(proj_dir) : |
Here is a snippet: <|code_start|>"""implement 'make' verb (builds a single target)
make
make [target]
make [target] [config]
"""
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
"""build a single target"""
if not util.is_valid_project_dir(proj_dir) :
log.error('must be run in a project directory')
tgt_name = None
cfg_name = None
build_tool_args = None
if '--' in args:
idx = args.index('--')
build_tool_args = args[(idx + 1):]
args = args[:idx];
if len(args) > 0 :
tgt_name = args[0]
if len(args) > 1:
cfg_name = args[1]
if not cfg_name :
<|code_end|>
. Write the next line using the current file imports:
from mod import log, util, settings, project
and context from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/settings.py
# def load(proj_dir) :
# def save(proj_dir, settings) :
# def get_default(key) :
# def get(proj_dir, key) :
# def set(proj_dir, key, value) :
# def unset(proj_dir, key) :
# def get_all_settings(proj_dir):
#
# Path: mod/project.py
# def init(fips_dir, proj_name) :
# def clone(fips_dir, url) :
# def gen_project(fips_dir, proj_dir, cfg, force) :
# def gen(fips_dir, proj_dir, cfg_name) :
# def configure(fips_dir, proj_dir, cfg_name) :
# def make_clean(fips_dir, proj_dir, cfg_name) :
# def build(fips_dir, proj_dir, cfg_name, target=None, build_tool_args=None) :
# def run(fips_dir, proj_dir, cfg_name, target_name, target_args, target_cwd) :
# def clean(fips_dir, proj_dir, cfg_name) :
# def get_target_list(fips_dir, proj_dir, cfg_name) :
, which may include functions, classes, or code. Output only the next line. | cfg_name = settings.get(proj_dir, 'config') |
Predict the next line after this snippet: <|code_start|>"""implement 'make' verb (builds a single target)
make
make [target]
make [target] [config]
"""
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
"""build a single target"""
if not util.is_valid_project_dir(proj_dir) :
log.error('must be run in a project directory')
tgt_name = None
cfg_name = None
build_tool_args = None
if '--' in args:
idx = args.index('--')
build_tool_args = args[(idx + 1):]
args = args[:idx];
if len(args) > 0 :
tgt_name = args[0]
if len(args) > 1:
cfg_name = args[1]
if not cfg_name :
cfg_name = settings.get(proj_dir, 'config')
if not tgt_name :
tgt_name = settings.get(proj_dir, 'target')
if tgt_name == 'clean' :
<|code_end|>
using the current file's imports:
from mod import log, util, settings, project
and any relevant context from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/settings.py
# def load(proj_dir) :
# def save(proj_dir, settings) :
# def get_default(key) :
# def get(proj_dir, key) :
# def set(proj_dir, key, value) :
# def unset(proj_dir, key) :
# def get_all_settings(proj_dir):
#
# Path: mod/project.py
# def init(fips_dir, proj_name) :
# def clone(fips_dir, url) :
# def gen_project(fips_dir, proj_dir, cfg, force) :
# def gen(fips_dir, proj_dir, cfg_name) :
# def configure(fips_dir, proj_dir, cfg_name) :
# def make_clean(fips_dir, proj_dir, cfg_name) :
# def build(fips_dir, proj_dir, cfg_name, target=None, build_tool_args=None) :
# def run(fips_dir, proj_dir, cfg_name, target_name, target_args, target_cwd) :
# def clean(fips_dir, proj_dir, cfg_name) :
# def get_target_list(fips_dir, proj_dir, cfg_name) :
. Output only the next line. | project.make_clean(fips_dir, proj_dir, cfg_name) |
Predict the next line for this snippet: <|code_start|>
value = None
settings = load(proj_dir)
if key in settings :
value = settings[key]
if value is None :
value = get_default(key)
return value
#-------------------------------------------------------------------------------
def set(proj_dir, key, value) :
"""update a settings value by key and save project-local
.fips-settings file
:param proj_dir: absolute project directory
:param key: settings key
:param value: new value associated with key
"""
util.ensure_valid_project_dir(proj_dir)
settings = load(proj_dir)
settings[key] = value
save(proj_dir, settings)
proj_name = util.get_project_name_from_dir(proj_dir)
if type(value) is bool :
value_str = 'on' if value else 'off'
else :
value_str = str(value)
<|code_end|>
with the help of current file imports:
import yaml
import os.path
from mod import log, util, config
and context from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/config.py
# def valid_build_tool(name) :
# def get_default_config() :
# def get_toolchain(fips_dir, proj_dir, cfg) :
# def exists(pattern, proj_dirs) :
# def get_config_dirs(fips_dir, proj_dir) :
# def list(fips_dir, proj_dir, pattern) :
# def load(fips_dir, proj_dir, pattern) :
# def missing_build_tools(fips_dir, tool_name) :
# def check_sdk(fips_dir, platform_name) :
# def check_config_valid(fips_dir, proj_dir, cfg, print_errors=False) :
, which may contain function names, class names, or code. Output only the next line. | log.info("'{}' set to '{}' in project '{}'".format(key, value_str, proj_name)) |
Continue the code snippet: <|code_start|>"""project-specific settings"""
valid_settings = ['config', 'target', 'jobs', 'ccache', 'iosteam', 'vscode-launch-configs']
default_settings = {
'config': config.get_default_config(),
'target': None,
<|code_end|>
. Use current file imports:
import yaml
import os.path
from mod import log, util, config
and context (classes, functions, or code) from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/config.py
# def valid_build_tool(name) :
# def get_default_config() :
# def get_toolchain(fips_dir, proj_dir, cfg) :
# def exists(pattern, proj_dirs) :
# def get_config_dirs(fips_dir, proj_dir) :
# def list(fips_dir, proj_dir, pattern) :
# def load(fips_dir, proj_dir, pattern) :
# def missing_build_tools(fips_dir, tool_name) :
# def check_sdk(fips_dir, platform_name) :
# def check_config_valid(fips_dir, proj_dir, cfg, print_errors=False) :
. Output only the next line. | 'jobs': util.get_num_cpucores() + 2, |
Given snippet: <|code_start|> target_cwd = None
dic = load_fips_yml(proj_dir)
if 'run' in dic :
if target in dic['run'] :
if 'cwd' in dic['run'][target] :
target_cwd = proj_dir + '/' + dic['run'][target]['cwd']
return target_cwd
#-------------------------------------------------------------------------------
def is_valid_project_dir(proj_dir) :
"""test if the provided directory is a valid fips project (has a
fips.yml file)
:param proj_dir: absolute project directory to check
:returns: True if a valid fips project
"""
if os.path.isdir(proj_dir) :
if not os.path.isfile(proj_dir + '/fips.yml') :
return False
return True
else :
return False
#-------------------------------------------------------------------------------
def ensure_valid_project_dir(proj_dir) :
"""test if project dir is valid, if not, dump error and abort
:param proj_dir: absolute project directory to check
"""
if not is_valid_project_dir(proj_dir) :
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os.path
import sys
import platform
import multiprocessing
import yaml
from mod import log
from mod import settings
from mod import settings
and context:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
which might include code, classes, or functions. Output only the next line. | log.error("'{}' is not a valid project directory".format(proj_dir)) |
Using the snippet: <|code_start|>'''CLion helper functions'''
name = 'clion'
platforms = ['osx','linux','win']
optional = True
not_found = 'used as IDE with clion configs'
#------------------------------------------------------------------------------
def check_exists(fips_dir) :
"""test if 'clion' is in the path
:returns: True if clion is in the path
"""
<|code_end|>
, determine the next line of code. You have imports:
import subprocess, os, shutil
from mod import util, log, verb, dep
from mod.tools import cmake
from distutils.spawn import find_executable
and context (class names, function names, or code) available:
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/verb.py
# def import_verbs_from(proj_name, proj_dir, verb_dir) :
# def import_verbs(fips_dir, proj_dir) :
#
# Path: mod/dep.py
# def get_imports(fips_dir, proj_dir) :
# def get_exports(proj_dir) :
# def get_policy(proj_dir, policy) :
# def _rec_get_all_imports_exports(fips_dir, proj_dir, result) :
# def get_all_imports_exports(fips_dir, proj_dir) :
# def _rec_fetch_imports(fips_dir, proj_dir, handled) :
# def fetch_imports(fips_dir, proj_dir) :
# def gather_imports(fips_dir, proj_dir) :
# def write_imports(fips_dir, proj_dir, cfg_name, imported) :
# def gather_and_write_imports(fips_dir, proj_dir, cfg_name) :
# def check_imports(fips_dir, proj_dir) :
# def check_local_changes(fips_dir, proj_dir) :
# def _rec_update_imports(fips_dir, proj_dir, handled) :
# def update_imports(fips_dir, proj_dir):
#
# Path: mod/tools/cmake.py
# def check_exists(fips_dir, major=2, minor=8) :
# def run_gen(cfg, fips_dir, project_dir, build_dir, local_build, toolchain_path, defines) :
# def run_build(fips_dir, target, build_type, build_dir, num_jobs=1, args=None) :
# def run_clean(fips_dir, build_dir) :
. Output only the next line. | host = util.get_host_platform() |
Given snippet: <|code_start|> # or added to the path using the "create launcher" command in CLion, which would by default
# create a symlink from clion.sh to /usr/local/bin/clion.
# This will also pick up CLion if it was installed using snap.
if find_executable("clion.sh") is not None or find_executable("clion") is not None:
return True
else:
return False
elif host == 'osx':
try:
subprocess.check_output("mdfind -name CLion.app | grep 'CLion'", shell=True)
return True
except (OSError, subprocess.CalledProcessError):
return False
else:
return False
#------------------------------------------------------------------------------
def match(build_tool):
return build_tool == 'clion'
#------------------------------------------------------------------------------
def run(proj_dir):
host = util.get_host_platform()
if host == 'linux':
try:
if find_executable("clion.sh") is not None:
subprocess.Popen('clion.sh {}'.format(proj_dir), cwd=proj_dir, shell=True)
else:
subprocess.Popen('clion {}'.format(proj_dir), cwd=proj_dir, shell=True)
except OSError:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import subprocess, os, shutil
from mod import util, log, verb, dep
from mod.tools import cmake
from distutils.spawn import find_executable
and context:
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/verb.py
# def import_verbs_from(proj_name, proj_dir, verb_dir) :
# def import_verbs(fips_dir, proj_dir) :
#
# Path: mod/dep.py
# def get_imports(fips_dir, proj_dir) :
# def get_exports(proj_dir) :
# def get_policy(proj_dir, policy) :
# def _rec_get_all_imports_exports(fips_dir, proj_dir, result) :
# def get_all_imports_exports(fips_dir, proj_dir) :
# def _rec_fetch_imports(fips_dir, proj_dir, handled) :
# def fetch_imports(fips_dir, proj_dir) :
# def gather_imports(fips_dir, proj_dir) :
# def write_imports(fips_dir, proj_dir, cfg_name, imported) :
# def gather_and_write_imports(fips_dir, proj_dir, cfg_name) :
# def check_imports(fips_dir, proj_dir) :
# def check_local_changes(fips_dir, proj_dir) :
# def _rec_update_imports(fips_dir, proj_dir, handled) :
# def update_imports(fips_dir, proj_dir):
#
# Path: mod/tools/cmake.py
# def check_exists(fips_dir, major=2, minor=8) :
# def run_gen(cfg, fips_dir, project_dir, build_dir, local_build, toolchain_path, defines) :
# def run_build(fips_dir, target, build_type, build_dir, num_jobs=1, args=None) :
# def run_clean(fips_dir, build_dir) :
which might include code, classes, or functions. Output only the next line. | log.error("Failed to run JetBrains CLion as 'clion' or 'clion.sh'") |
Here is a snippet: <|code_start|>"""
wrapper for node's http-server module, this is preferred over
python's SimpleHTTPServer module because it supports
HTTP range requests
"""
name = 'http-server'
platforms = ['osx', 'linux', 'win']
optional = True
not_found = "required for running emscripten targets (npm install http-server -g)"
#-------------------------------------------------------------------------------
def check_exists(fips_dir) :
try:
if platform.system() == 'Windows':
subprocess.check_output(['http-server', '-h'], shell=True)
else:
subprocess.check_output(['http-server', '-h'])
return True
except (OSError, subprocess.CalledProcessError):
return False
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, target_name, target_cwd):
if not check_exists(fips_dir):
<|code_end|>
. Write the next line using the current file imports:
import subprocess
import platform
from mod import log,util
and context from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
, which may include functions, classes, or code. Output only the next line. | log.error("http-server tool not found (npm install http-server -g)") |
Predict the next line for this snippet: <|code_start|>"""
wrapper for node's http-server module, this is preferred over
python's SimpleHTTPServer module because it supports
HTTP range requests
"""
name = 'http-server'
platforms = ['osx', 'linux', 'win']
optional = True
not_found = "required for running emscripten targets (npm install http-server -g)"
#-------------------------------------------------------------------------------
def check_exists(fips_dir) :
try:
if platform.system() == 'Windows':
subprocess.check_output(['http-server', '-h'], shell=True)
else:
subprocess.check_output(['http-server', '-h'])
return True
except (OSError, subprocess.CalledProcessError):
return False
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, target_name, target_cwd):
if not check_exists(fips_dir):
log.error("http-server tool not found (npm install http-server -g)")
return
html_name = target_name + '.html'
<|code_end|>
with the help of current file imports:
import subprocess
import platform
from mod import log,util
and context from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
, which may contain function names, class names, or code. Output only the next line. | if util.get_host_platform() == 'osx' : |
Given snippet: <|code_start|>
urls = {
'linux': 'https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-14/wasi-sdk-14.0-linux.tar.gz',
'osx': 'https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-14/wasi-sdk-14.0-macos.tar.gz',
'win': 'https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-14/wasi-sdk-14.0-mingw.tar.gz'
}
def get_sdk_dir(fips_dir):
return util.get_workspace_dir(fips_dir) + '/fips-sdks/wasisdk'
def check_exists(fips_dir):
return os.path.isdir(get_sdk_dir(fips_dir))
def get_url():
return urls[util.get_host_platform()]
def get_archive_path(fips_dir):
return get_sdk_dir(fips_dir) + '/' + os.path.basename(get_url())
def get_wasisdk_root(fips_dir):
return get_sdk_dir(fips_dir) + '/' + dir_name
def sdk_dir_exists(fips_dir):
return os.path.isdir(get_sdk_dir(fips_dir))
def ensure_sdk_dirs(fips_dir) :
if not sdk_dir_exists(fips_dir):
os.makedirs(get_sdk_dir(fips_dir))
def install(fips_dir):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys, os, tarfile, shutil
from mod import log, util
from urllib.request import urlretrieve
from urllib import urlretrieve
and context:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
which might include code, classes, or functions. Output only the next line. | log.colored(log.YELLOW, '=== installing WASI SDK:') |
Here is a snippet: <|code_start|>"""
Manage the wasisdk.
"""
if sys.version_info[0] >= 3:
else:
dir_name = 'wasi-sdk-14.0'
urls = {
'linux': 'https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-14/wasi-sdk-14.0-linux.tar.gz',
'osx': 'https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-14/wasi-sdk-14.0-macos.tar.gz',
'win': 'https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-14/wasi-sdk-14.0-mingw.tar.gz'
}
def get_sdk_dir(fips_dir):
<|code_end|>
. Write the next line using the current file imports:
import sys, os, tarfile, shutil
from mod import log, util
from urllib.request import urlretrieve
from urllib import urlretrieve
and context from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
, which may include functions, classes, or code. Output only the next line. | return util.get_workspace_dir(fips_dir) + '/fips-sdks/wasisdk' |
Predict the next line after this snippet: <|code_start|>"""implements the cache verb
Opens the CMakeCache.txt in a text editor for a given config
cache
cache [config-name]
"""
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
if not util.is_valid_project_dir(proj_dir) :
<|code_end|>
using the current file's imports:
import os, sys, subprocess
from mod import log, util, project, settings
and any relevant context from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/project.py
# def init(fips_dir, proj_name) :
# def clone(fips_dir, url) :
# def gen_project(fips_dir, proj_dir, cfg, force) :
# def gen(fips_dir, proj_dir, cfg_name) :
# def configure(fips_dir, proj_dir, cfg_name) :
# def make_clean(fips_dir, proj_dir, cfg_name) :
# def build(fips_dir, proj_dir, cfg_name, target=None, build_tool_args=None) :
# def run(fips_dir, proj_dir, cfg_name, target_name, target_args, target_cwd) :
# def clean(fips_dir, proj_dir, cfg_name) :
# def get_target_list(fips_dir, proj_dir, cfg_name) :
#
# Path: mod/settings.py
# def load(proj_dir) :
# def save(proj_dir, settings) :
# def get_default(key) :
# def get(proj_dir, key) :
# def set(proj_dir, key, value) :
# def unset(proj_dir, key) :
# def get_all_settings(proj_dir):
. Output only the next line. | log.error('must be run in a project directory') |
Continue the code snippet: <|code_start|>"""implements the cache verb
Opens the CMakeCache.txt in a text editor for a given config
cache
cache [config-name]
"""
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
<|code_end|>
. Use current file imports:
import os, sys, subprocess
from mod import log, util, project, settings
and context (classes, functions, or code) from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/project.py
# def init(fips_dir, proj_name) :
# def clone(fips_dir, url) :
# def gen_project(fips_dir, proj_dir, cfg, force) :
# def gen(fips_dir, proj_dir, cfg_name) :
# def configure(fips_dir, proj_dir, cfg_name) :
# def make_clean(fips_dir, proj_dir, cfg_name) :
# def build(fips_dir, proj_dir, cfg_name, target=None, build_tool_args=None) :
# def run(fips_dir, proj_dir, cfg_name, target_name, target_args, target_cwd) :
# def clean(fips_dir, proj_dir, cfg_name) :
# def get_target_list(fips_dir, proj_dir, cfg_name) :
#
# Path: mod/settings.py
# def load(proj_dir) :
# def save(proj_dir, settings) :
# def get_default(key) :
# def get(proj_dir, key) :
# def set(proj_dir, key, value) :
# def unset(proj_dir, key) :
# def get_all_settings(proj_dir):
. Output only the next line. | if not util.is_valid_project_dir(proj_dir) : |
Predict the next line after this snippet: <|code_start|>"""implements the cache verb
Opens the CMakeCache.txt in a text editor for a given config
cache
cache [config-name]
"""
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
if not util.is_valid_project_dir(proj_dir) :
log.error('must be run in a project directory')
proj_name = util.get_project_name_from_dir(proj_dir)
cfg_name = None
if len(args) > 0 :
cfg_name = args[0]
if not cfg_name :
<|code_end|>
using the current file's imports:
import os, sys, subprocess
from mod import log, util, project, settings
and any relevant context from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
#
# Path: mod/project.py
# def init(fips_dir, proj_name) :
# def clone(fips_dir, url) :
# def gen_project(fips_dir, proj_dir, cfg, force) :
# def gen(fips_dir, proj_dir, cfg_name) :
# def configure(fips_dir, proj_dir, cfg_name) :
# def make_clean(fips_dir, proj_dir, cfg_name) :
# def build(fips_dir, proj_dir, cfg_name, target=None, build_tool_args=None) :
# def run(fips_dir, proj_dir, cfg_name, target_name, target_args, target_cwd) :
# def clean(fips_dir, proj_dir, cfg_name) :
# def get_target_list(fips_dir, proj_dir, cfg_name) :
#
# Path: mod/settings.py
# def load(proj_dir) :
# def save(proj_dir, settings) :
# def get_default(key) :
# def get(proj_dir, key) :
# def set(proj_dir, key, value) :
# def unset(proj_dir, key) :
# def get_all_settings(proj_dir):
. Output only the next line. | cfg_name = settings.get(proj_dir, 'config') |
Given the code snippet: <|code_start|>"""wrapper for some git commands"""
name = 'git'
platforms = ['linux', 'osx', 'win']
optional = False
not_found = "git not found in path, can't happen(?)"
# default git clone depth
clone_depth = 10
#-------------------------------------------------------------------------------
def check_exists(fips_dir=None) :
"""test if git is in the path
:returns: True if git is in the path
"""
try :
subprocess.check_output(['git', '--version'])
return True
except (OSError, subprocess.CalledProcessError) :
return False
#-------------------------------------------------------------------------------
def check_exists_with_error():
"""checks if git exists, and if not throws a fatal error"""
if not check_exists():
<|code_end|>
, generate the next line using the imports in this file:
import re
import subprocess
from mod import log
and context (functions, classes, or occasionally code) from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
. Output only the next line. | log.error("git not found, please run and fix './fips diag tools'") |
Continue the code snippet: <|code_start|>"""fips main module"""
VERSION = '0.0.1'
init()
#-------------------------------------------------------------------------------
def show_help(args) :
"""show help text"""
if len(args) > 0 :
# show help for one verb
verb_name = args[0]
if verb_name in verb.verbs :
verb.verbs[verb_name].help()
else :
<|code_end|>
. Use current file imports:
from colorama import init
from mod import log, verb, util
import yaml
and context (classes, functions, or code) from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/verb.py
# def import_verbs_from(proj_name, proj_dir, verb_dir) :
# def import_verbs(fips_dir, proj_dir) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
. Output only the next line. | log.error("unknown verb '{}'".format(verb)) |
Continue the code snippet: <|code_start|>"""fips main module"""
VERSION = '0.0.1'
init()
#-------------------------------------------------------------------------------
def show_help(args) :
"""show help text"""
if len(args) > 0 :
# show help for one verb
verb_name = args[0]
<|code_end|>
. Use current file imports:
from colorama import init
from mod import log, verb, util
import yaml
and context (classes, functions, or code) from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/verb.py
# def import_verbs_from(proj_name, proj_dir, verb_dir) :
# def import_verbs(fips_dir, proj_dir) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
. Output only the next line. | if verb_name in verb.verbs : |
Predict the next line after this snippet: <|code_start|>VERSION = '0.0.1'
init()
#-------------------------------------------------------------------------------
def show_help(args) :
"""show help text"""
if len(args) > 0 :
# show help for one verb
verb_name = args[0]
if verb_name in verb.verbs :
verb.verbs[verb_name].help()
else :
log.error("unknown verb '{}'".format(verb))
else :
# show generic help
log.info("fips: the high-level, multi-platform build system wrapper\n"
"v{}\n"
"https://www.github.com/floooh/fips\n".format(VERSION))
for proj_name in verb.proj_verbs :
if proj_name != 'fips' :
log.colored(log.BLUE, "=== imported from '{}':".format(proj_name))
for verb_name in verb.proj_verbs[proj_name] :
verb.verbs[verb_name].help()
log.info(' ')
#-------------------------------------------------------------------------------
def run(fips_path, proj_path, args) :
<|code_end|>
using the current file's imports:
from colorama import init
from mod import log, verb, util
import yaml
and any relevant context from other files:
# Path: mod/log.py
# RED = '\033[1;31m'
# GREEN = '\033[1;32m'
# YELLOW = '\033[1;33m'
# BLUE = '\033[1;36m'
# DEF = '\033[0;0m'
# def error(msg, fatal=True) :
# def warn(msg) :
# def ok(item, status) :
# def failed(item, status) :
# def optional(item, status) :
# def info(msg) :
# def colored(color, msg) :
#
# Path: mod/verb.py
# def import_verbs_from(proj_name, proj_dir, verb_dir) :
# def import_verbs(fips_dir, proj_dir) :
#
# Path: mod/util.py
# def fix_path(path) :
# def get_workspace_dir(fips_dir) :
# def get_project_dir(fips_dir, proj_name) :
# def get_build_root_dir(fips_dir, proj_name):
# def get_deploy_root_dir(fips_dir, proj_name):
# def get_build_dir(fips_dir, proj_name, cfg) :
# def get_deploy_dir(fips_dir, proj_name, cfg) :
# def get_fips_dir(proj_dir, name):
# def get_configs_dir(proj_dir):
# def get_verbs_dir(proj_dir):
# def get_generators_dir(proj_dir):
# def get_toolchains_dir(proj_dir):
# def get_giturl_from_url(url) :
# def get_gitbranch_from_url(url) :
# def get_project_name_from_url(url) :
# def get_project_name_from_dir(proj_dir) :
# def load_fips_yml(proj_dir) :
# def lookup_target_cwd(proj_dir, target) :
# def is_valid_project_dir(proj_dir) :
# def ensure_valid_project_dir(proj_dir) :
# def is_git_url(url) :
# def confirm(question) :
# def url_download_hook(count, block_size, total_size) :
# def get_host_platform() :
# def get_cfg_target_list(fips_dir, proj_dir, cfg):
# def get_cfg_headersdirs_by_target(fips_dir, proj_dir, cfg):
# def get_cfg_defines_by_target(fips_dir, proj_dir, cfg):
# def get_num_cpucores():
. Output only the next line. | fips_path = util.fix_path(fips_path) |
Next line prediction: <|code_start|>#!/usr/bin/env python3
IGNORE_PET_NPCID = [
185475, # Tezpet https://www.wowhead.com/npc=185475
125494, # SpeedyNumberIII https://www.wowhead.com/npc=125494
]
PET_SOURCE_ENUM = {
0: 'Drop',
1: 'Quest',
2: 'Vendor',
3: 'Profession',
4: 'Wild',
5: 'Achievement',
6: 'World Event',
7: 'Promotion',
8: 'Trading Card Game',
9: 'Store',
10: 'Discovery',
}
<|code_end|>
. Use current file imports:
(from .fixer import WowToolsFixer
from .tools import icat, changelog)
and context including class names, function names, or small code snippets from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def icat(dct, cat=None, subcat=None, error_absent=False):
# if cat is not None:
# res = find_or_create_item(dct, cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
. Output only the next line. | class PetFixer(WowToolsFixer): |
Predict the next line for this snippet: <|code_start|> 'creatureId': int(creature_id),
'spellid': int(spell_id),
**({'itemId': int(item_id)} if item_id else {})
}
def get_pet_source(self, pet_id):
return PET_SOURCE_ENUM.get(
int(self.wt_battlepetspecies[pet_id]['SourceTypeEnum']),
'Unknown'
)
def fix_missing_pet(self, pet_id):
if (
# Flag 0x20 : HideFromJournal
int(self.wt_battlepetspecies[pet_id]['Flags']) & 0x20
or (
int(self.wt_battlepetspecies[pet_id]['CreatureID'])
in IGNORE_PET_NPCID
)
):
return
pet = self.get_pet(pet_id)
if pet is None:
return
changelog('Pet {} missing: https://www.wowhead.com/npc={}'
.format(pet_id, pet['creatureId']))
source = self.get_pet_source(pet_id)
if source == 'Wild':
<|code_end|>
with the help of current file imports:
from .fixer import WowToolsFixer
from .tools import icat, changelog
and context from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def icat(dct, cat=None, subcat=None, error_absent=False):
# if cat is not None:
# res = find_or_create_item(dct, cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
, which may contain function names, class names, or code. Output only the next line. | icat(self.battlepets, 'TODO', 'TODO')['items'].append(pet) |
Next line prediction: <|code_start|>
return {
'ID': int(pet_id),
'name': name,
'icon': icon_name,
'creatureId': int(creature_id),
'spellid': int(spell_id),
**({'itemId': int(item_id)} if item_id else {})
}
def get_pet_source(self, pet_id):
return PET_SOURCE_ENUM.get(
int(self.wt_battlepetspecies[pet_id]['SourceTypeEnum']),
'Unknown'
)
def fix_missing_pet(self, pet_id):
if (
# Flag 0x20 : HideFromJournal
int(self.wt_battlepetspecies[pet_id]['Flags']) & 0x20
or (
int(self.wt_battlepetspecies[pet_id]['CreatureID'])
in IGNORE_PET_NPCID
)
):
return
pet = self.get_pet(pet_id)
if pet is None:
return
<|code_end|>
. Use current file imports:
(from .fixer import WowToolsFixer
from .tools import icat, changelog)
and context including class names, function names, or small code snippets from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def icat(dct, cat=None, subcat=None, error_absent=False):
# if cat is not None:
# res = find_or_create_item(dct, cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
. Output only the next line. | changelog('Pet {} missing: https://www.wowhead.com/npc={}' |
Next line prediction: <|code_start|>#!/usr/bin/env python3
class RealmFixer:
def __init__(self, realms_eu, realms_us, build=None):
self.realms_eu = realms_eu
self.realms_us = realms_us
def fix_realms(self, region):
<|code_end|>
. Use current file imports:
(from .providers import wowgraphql)
and context including class names, function names, or small code snippets from other files:
# Path: dataimporter/providers/wowgraphql.py
# async def get_realm_list(session, region):
# def get_realm_list_sync(region):
# async def _run():
. Output only the next line. | master_list = wowgraphql.get_realm_list_sync(region) |
Based on the snippet: <|code_start|> 1738, # Defender Illona
1739, # Vivianne
1740, # Aeda Brightdawn
1741, # Leorajh
# Venthyr Ember Court
2446, # Baroness Vashj
2447, # Lady Moonberry
2448, # Mikanikos
2449, # The Countess
2450, # Alexandros Mograine
2451, # Hunt-Captain Korayn
2452, # Polemarch Adrestes
2453, # Rendle and Cudgelface
2454, # Choofa
2455, # Cryptkeeper Kassir
2456, # Droman Aliothe
2457, # Grandmaster Vole
2458, # Kleia and Pelagos
2459, # Sika
2460, # Stonehead
2461, # Plague Deviser Marileth
# Necrolord Abomination Factory
2462, # Stitchmasters
]
def fcat(dct, cat=None):
if cat is not None:
<|code_end|>
, predict the immediate next line with the help of imports:
from .tools import find_or_create_item, changelog
from .fixer import WowToolsFixer
and context (classes, functions, sometimes code) from other files:
# Path: dataimporter/tools.py
# def find_or_create_item(L, name, subitems_name=None, error_absent=False):
# try:
# return list_find(L, lambda x: x['name'] == name)
# except StopIteration:
# if not error_absent:
# d = {'id': genid(), 'name': name}
# if subitems_name:
# d[subitems_name] = []
# L.append(d)
# return d
# else:
# raise
#
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
. Output only the next line. | res = find_or_create_item(dct, cat, 'factions') |
Here is a snippet: <|code_start|> # visible.
and not int(rep['ReputationFlags[0]']) & 0x2
)
):
return
if not children:
self.wt_faction[int(rep['ID'])] = rep
for row in children:
_recurse_rep(int(row['ID']), level + 1)
_recurse_rep(0)
def register_old_factions(self):
for cat in self.factions:
for item in cat['factions']:
self.id_to_old_faction[int(item['id'])] = item
def get_faction(self, faction_id: int):
if int(faction_id) not in self.wt_faction:
return None
name = self.wt_faction[int(faction_id)]['Name_lang']
return {
'id': int(faction_id),
'name': name,
}
def fix_missing_faction(self, faction_id: int):
faction = self.get_faction(faction_id)
<|code_end|>
. Write the next line using the current file imports:
from .tools import find_or_create_item, changelog
from .fixer import WowToolsFixer
and context from other files:
# Path: dataimporter/tools.py
# def find_or_create_item(L, name, subitems_name=None, error_absent=False):
# try:
# return list_find(L, lambda x: x['name'] == name)
# except StopIteration:
# if not error_absent:
# d = {'id': genid(), 'name': name}
# if subitems_name:
# d[subitems_name] = []
# L.append(d)
# return d
# else:
# raise
#
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
, which may include functions, classes, or code. Output only the next line. | changelog( |
Given snippet: <|code_start|>
# Venthyr Ember Court
2446, # Baroness Vashj
2447, # Lady Moonberry
2448, # Mikanikos
2449, # The Countess
2450, # Alexandros Mograine
2451, # Hunt-Captain Korayn
2452, # Polemarch Adrestes
2453, # Rendle and Cudgelface
2454, # Choofa
2455, # Cryptkeeper Kassir
2456, # Droman Aliothe
2457, # Grandmaster Vole
2458, # Kleia and Pelagos
2459, # Sika
2460, # Stonehead
2461, # Plague Deviser Marileth
# Necrolord Abomination Factory
2462, # Stitchmasters
]
def fcat(dct, cat=None):
if cat is not None:
res = find_or_create_item(dct, cat, 'factions')
return res
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .tools import find_or_create_item, changelog
from .fixer import WowToolsFixer
and context:
# Path: dataimporter/tools.py
# def find_or_create_item(L, name, subitems_name=None, error_absent=False):
# try:
# return list_find(L, lambda x: x['name'] == name)
# except StopIteration:
# if not error_absent:
# d = {'id': genid(), 'name': name}
# if subitems_name:
# d[subitems_name] = []
# L.append(d)
# return d
# else:
# raise
#
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
which might include code, classes, or functions. Output only the next line. | class FactionFixer(WowToolsFixer): |
Here is a snippet: <|code_start|> 'icon': icon_name,
'spellid': int(spell_id),
**({'itemId': item_id} if item_id else {})
}
def get_mount_source(self, mount_id: int):
return MOUNT_SOURCE_ENUM.get(
int(self.wt_mount[mount_id]['SourceTypeEnum']),
'Unknown'
)
def fix_missing_mount(self, mount_id: int):
if (
# No summon spell ID
not int(self.wt_mount[mount_id]['SourceSpellID'])
# Flag 0x100 : Invalid mount
or int(self.wt_mount[mount_id]['Flags']) & 0x100
):
return
mount = self.get_mount(mount_id)
if mount is None:
return
changelog(
f"Mount {mount_id} \"{mount['name']}\" missing:"
f" https://www.wowhead.com/mount/{mount_id}"
)
source = self.get_mount_source(mount_id)
<|code_end|>
. Write the next line using the current file imports:
from .tools import icat, changelog
from .fixer import WowToolsFixer
and context from other files:
# Path: dataimporter/tools.py
# def icat(dct, cat=None, subcat=None, error_absent=False):
# if cat is not None:
# res = find_or_create_item(dct, cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
, which may include functions, classes, or code. Output only the next line. | icat(self.mounts, 'TODO', source)['items'].append(mount) |
Given the following code snippet before the placeholder: <|code_start|> except KeyError:
item_id = None
return {
'ID': int(mount_id),
'name': name,
'icon': icon_name,
'spellid': int(spell_id),
**({'itemId': item_id} if item_id else {})
}
def get_mount_source(self, mount_id: int):
return MOUNT_SOURCE_ENUM.get(
int(self.wt_mount[mount_id]['SourceTypeEnum']),
'Unknown'
)
def fix_missing_mount(self, mount_id: int):
if (
# No summon spell ID
not int(self.wt_mount[mount_id]['SourceSpellID'])
# Flag 0x100 : Invalid mount
or int(self.wt_mount[mount_id]['Flags']) & 0x100
):
return
mount = self.get_mount(mount_id)
if mount is None:
return
<|code_end|>
, predict the next line using imports from the current file:
from .tools import icat, changelog
from .fixer import WowToolsFixer
and context including class names, function names, and sometimes code from other files:
# Path: dataimporter/tools.py
# def icat(dct, cat=None, subcat=None, error_absent=False):
# if cat is not None:
# res = find_or_create_item(dct, cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
. Output only the next line. | changelog( |
Predict the next line for this snippet: <|code_start|> 333, # Magic Rooster https://www.wowhead.com/mount/333
334, # Magic Rooster https://www.wowhead.com/mount/334
335, # Magic Rooster https://www.wowhead.com/mount/335
462, # White Riding Yak https://www.wowhead.com/mount/462
484, # Black Riding Yak https://www.wowhead.com/mount/484
485, # Brown Riding Yak https://www.wowhead.com/mount/485
776, # Swift Spectral Rylak https://www.wowhead.com/mount/776
934, # Swift Spectral Hippogryph https://www.wowhead.com/mount/934
935, # Blue Qiraji War Tank https://www.wowhead.com/mount/935
936, # Red Qiraji War Tank https://www.wowhead.com/mount/936
1269, # Swift Spectral Fathom Ray https://www.wowhead.com/mount/1269
1270, # Swift Spectral Magnetocraft https://www.wowhead.com/mount/1270
1271, # Swift Spectral Armored Gryphon https://www.wowhead.com/mount/1271
1272, # Swift Spectral Pterrordax https://www.wowhead.com/mount/1272
]
MOUNT_SOURCE_ENUM = {
0: 'Drop',
1: 'Quest',
2: 'Vendor',
3: 'Profession',
5: 'Achievement',
6: 'World Event',
7: 'Promotion',
8: 'Trading Card Game',
9: 'Store',
10: 'Discovery',
}
<|code_end|>
with the help of current file imports:
from .tools import icat, changelog
from .fixer import WowToolsFixer
and context from other files:
# Path: dataimporter/tools.py
# def icat(dct, cat=None, subcat=None, error_absent=False):
# if cat is not None:
# res = find_or_create_item(dct, cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
, which may contain function names, class names, or code. Output only the next line. | class MountFixer(WowToolsFixer): |
Based on the snippet: <|code_start|>
class WowToolsFixer:
"""Base class for Wowtools-based data fixers."""
load_files = False
def __init__(self, *args, build=None):
self.build = build
self._store_init(*args)
if self.load_files:
self.wt_files = {
int(e['ID']): e for e in self.wt_get_table('files')
}
def _store_init(self, *args):
raise NotImplementedError
def run(self):
raise NotImplementedError
def wt_get_table(self, table_name):
<|code_end|>
, predict the immediate next line with the help of imports:
from .providers import wowtools
and context (classes, functions, sometimes code) from other files:
# Path: dataimporter/providers/wowtools.py
# def csv_to_list(csv_text, **kwargs):
# def __init__(self):
# async def __aenter__(self):
# async def __aexit__(self, exc_type, exc_value, tb):
# async def get_table_versions(self, table_name):
# async def get_matching_build_version(self, table_name, build=None):
# async def get_table(self, table_name, build=None):
# async def get_file_list(self):
# def get_table(table_name, build=None):
# async def _get_table():
# class WowToolsClient:
. Output only the next line. | return wowtools.get_table(table_name, self.build) |
Given the code snippet: <|code_start|>
IGNORE_TOY_ITEMID = [
88587,
110586,
119220,
119221,
129111,
130249,
141300,
143545,
166851,
174445,
183810,
]
TOY_SOURCE_ENUM = {
0: 'Drop',
1: 'Quest',
2: 'Vendor',
3: 'Profession',
4: 'NPC',
5: 'Achievement',
6: 'World Event',
7: 'Promotion',
9: 'Store',
}
<|code_end|>
, generate the next line using the imports in this file:
from .fixer import WowToolsFixer
from .tools import changelog, icat
and context (functions, classes, or occasionally code) from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# def icat(dct, cat=None, subcat=None, error_absent=False):
# if cat is not None:
# res = find_or_create_item(dct, cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
. Output only the next line. | class ToyFixer(WowToolsFixer): |
Given the following code snippet before the placeholder: <|code_start|>
def get_toy(self, toy_id):
toy_id = str(toy_id)
# Name
if toy_id not in self.wt_itemsparse:
return None
name = self.wt_itemsparse[toy_id]['Display_lang']
# Icon
icon_id = self.wt_item[toy_id]['IconFileDataID']
icon_name = self.get_icon_name(int(icon_id))
return {
'itemId': int(toy_id),
'name': name,
'icon': icon_name,
}
def get_toy_source(self, toy_id):
return TOY_SOURCE_ENUM.get(
int(self.wt_toy[toy_id]['SourceTypeEnum']),
'Unknown'
)
def fix_missing_toy(self, toy_id):
toy = self.get_toy(toy_id)
if toy is None:
return
<|code_end|>
, predict the next line using imports from the current file:
from .fixer import WowToolsFixer
from .tools import changelog, icat
and context including class names, function names, and sometimes code from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# def icat(dct, cat=None, subcat=None, error_absent=False):
# if cat is not None:
# res = find_or_create_item(dct, cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
. Output only the next line. | changelog('Toy {} missing: https://www.wowhead.com/item={}' |
Based on the snippet: <|code_start|> # Name
if toy_id not in self.wt_itemsparse:
return None
name = self.wt_itemsparse[toy_id]['Display_lang']
# Icon
icon_id = self.wt_item[toy_id]['IconFileDataID']
icon_name = self.get_icon_name(int(icon_id))
return {
'itemId': int(toy_id),
'name': name,
'icon': icon_name,
}
def get_toy_source(self, toy_id):
return TOY_SOURCE_ENUM.get(
int(self.wt_toy[toy_id]['SourceTypeEnum']),
'Unknown'
)
def fix_missing_toy(self, toy_id):
toy = self.get_toy(toy_id)
if toy is None:
return
changelog('Toy {} missing: https://www.wowhead.com/item={}'
.format(toy_id, toy_id))
source = self.get_toy_source(toy_id)
<|code_end|>
, predict the immediate next line with the help of imports:
from .fixer import WowToolsFixer
from .tools import changelog, icat
and context (classes, functions, sometimes code) from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# def icat(dct, cat=None, subcat=None, error_absent=False):
# if cat is not None:
# res = find_or_create_item(dct, cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
. Output only the next line. | icat(self.toys, 'TODO', source)['items'].append(toy) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
IGNORE_ACHIEV_ID = [
7268,
7269,
7270,
]
<|code_end|>
with the help of current file imports:
import collections
from .fixer import WowToolsFixer
from .tools import (changelog, genid, filter_del, sort_try_respect_order,
iscat, list_find)
and context from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# def genid():
# return binascii.b2a_hex(os.urandom(4)).decode('ascii')
#
# def filter_del(L, cond, deleted=None, format_deleted=None):
# kept = [item for item in L if cond(item)]
# if deleted is not None:
# if format_deleted is None:
# format_deleted = lambda x: x # noqa
# deleted.extend(format_deleted(item) for item in L if not cond(item))
# return kept
#
# def sort_try_respect_order(L, order_list, key='name'):
# d = {k: v for v, k in enumerate(order_list)}
# L.sort(key=lambda k: d.get(k[key], float('inf')))
#
# def iscat(dct, supercat=None, cat=None, subcat=None, *, error_absent=False):
# if supercat is not None:
# res = find_or_create_item(
# dct['supercats'], supercat, 'cats', error_absent
# )
# if cat is not None:
# res = find_or_create_item(res['cats'], cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def list_find(L, pred):
# return next(item for item in L if pred(item))
, which may contain function names, class names, or code. Output only the next line. | class AchievementFixer(WowToolsFixer): |
Continue the code snippet: <|code_start|> 0: 'H',
1: 'A',
}.get(int(wt_ach['Faction']))
def genach(self, ach_id):
ach_id = int(ach_id)
if ach_id in self.id_to_sa_ach:
return self.id_to_sa_ach[ach_id]
else:
wt_ach = self.wt_achiev[ach_id]
faction = self.get_faction(ach_id)
return {
'id': int(ach_id),
'title': wt_ach['Title_lang'],
'icon': self.get_icon_name(int(wt_ach['IconFileID'])),
'points': int(wt_ach['Points']),
**({'side': faction} if faction else {})
}
def delete_removed_achievements(self):
ach_deleted = []
for supercat in self.achievs['supercats']:
for cat in supercat['cats']:
for subcat in cat['subcats']:
subcat['items'] = filter_del(
subcat['items'],
lambda item: int(item['id']) in self.id_to_cat,
ach_deleted, lambda item: str(item['id'])
)
if ach_deleted:
<|code_end|>
. Use current file imports:
import collections
from .fixer import WowToolsFixer
from .tools import (changelog, genid, filter_del, sort_try_respect_order,
iscat, list_find)
and context (classes, functions, or code) from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# def genid():
# return binascii.b2a_hex(os.urandom(4)).decode('ascii')
#
# def filter_del(L, cond, deleted=None, format_deleted=None):
# kept = [item for item in L if cond(item)]
# if deleted is not None:
# if format_deleted is None:
# format_deleted = lambda x: x # noqa
# deleted.extend(format_deleted(item) for item in L if not cond(item))
# return kept
#
# def sort_try_respect_order(L, order_list, key='name'):
# d = {k: v for v, k in enumerate(order_list)}
# L.sort(key=lambda k: d.get(k[key], float('inf')))
#
# def iscat(dct, supercat=None, cat=None, subcat=None, *, error_absent=False):
# if supercat is not None:
# res = find_or_create_item(
# dct['supercats'], supercat, 'cats', error_absent
# )
# if cat is not None:
# res = find_or_create_item(res['cats'], cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def list_find(L, pred):
# return next(item for item in L if pred(item))
. Output only the next line. | changelog("* Deleted removed achievements: {}" |
Given the code snippet: <|code_start|> if deleted_supcats:
changelog("* Deleted super-categories:\n{}"
.format('\n'.join(deleted_supcats)))
def fix_moved_subcategories(self):
for supercat in self.achievs['supercats']:
for cat in supercat['cats']:
subcat_to_remove = set()
for i, subcat in enumerate(cat['subcats']):
expected = (supercat['name'], cat['name'])
id_list = [int(item['id']) for item in subcat['items']]
ach_to_idx = {int(item['id']): idx
for idx, item in enumerate(subcat['items'])}
if not id_list:
continue
path_to_achs = collections.defaultdict(list)
for id in id_list:
path_to_achs[self.id_to_cat[id]].append(
self.genach(int(id)))
first_path = list(path_to_achs.keys())[0]
if len(path_to_achs) > 1:
changelog('* Splitted sub-category {} > {} > {}'
' in the following categories:'
.format(*expected, subcat['name']))
achs_to_remove = set()
for path, achs in path_to_achs.items():
if path == expected:
continue
(iscat(self.achievs, *path)
['subcats'].append({
<|code_end|>
, generate the next line using the imports in this file:
import collections
from .fixer import WowToolsFixer
from .tools import (changelog, genid, filter_del, sort_try_respect_order,
iscat, list_find)
and context (functions, classes, or occasionally code) from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# def genid():
# return binascii.b2a_hex(os.urandom(4)).decode('ascii')
#
# def filter_del(L, cond, deleted=None, format_deleted=None):
# kept = [item for item in L if cond(item)]
# if deleted is not None:
# if format_deleted is None:
# format_deleted = lambda x: x # noqa
# deleted.extend(format_deleted(item) for item in L if not cond(item))
# return kept
#
# def sort_try_respect_order(L, order_list, key='name'):
# d = {k: v for v, k in enumerate(order_list)}
# L.sort(key=lambda k: d.get(k[key], float('inf')))
#
# def iscat(dct, supercat=None, cat=None, subcat=None, *, error_absent=False):
# if supercat is not None:
# res = find_or_create_item(
# dct['supercats'], supercat, 'cats', error_absent
# )
# if cat is not None:
# res = find_or_create_item(res['cats'], cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def list_find(L, pred):
# return next(item for item in L if pred(item))
. Output only the next line. | 'id': genid(), |
Next line prediction: <|code_start|> for item in subcat['items']:
self.id_to_sa_ach[int(item['id'])] = item
def get_faction(self, ach_id: int):
wt_ach = self.wt_achiev[int(ach_id)]
return {
0: 'H',
1: 'A',
}.get(int(wt_ach['Faction']))
def genach(self, ach_id):
ach_id = int(ach_id)
if ach_id in self.id_to_sa_ach:
return self.id_to_sa_ach[ach_id]
else:
wt_ach = self.wt_achiev[ach_id]
faction = self.get_faction(ach_id)
return {
'id': int(ach_id),
'title': wt_ach['Title_lang'],
'icon': self.get_icon_name(int(wt_ach['IconFileID'])),
'points': int(wt_ach['Points']),
**({'side': faction} if faction else {})
}
def delete_removed_achievements(self):
ach_deleted = []
for supercat in self.achievs['supercats']:
for cat in supercat['cats']:
for subcat in cat['subcats']:
<|code_end|>
. Use current file imports:
(import collections
from .fixer import WowToolsFixer
from .tools import (changelog, genid, filter_del, sort_try_respect_order,
iscat, list_find))
and context including class names, function names, or small code snippets from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# def genid():
# return binascii.b2a_hex(os.urandom(4)).decode('ascii')
#
# def filter_del(L, cond, deleted=None, format_deleted=None):
# kept = [item for item in L if cond(item)]
# if deleted is not None:
# if format_deleted is None:
# format_deleted = lambda x: x # noqa
# deleted.extend(format_deleted(item) for item in L if not cond(item))
# return kept
#
# def sort_try_respect_order(L, order_list, key='name'):
# d = {k: v for v, k in enumerate(order_list)}
# L.sort(key=lambda k: d.get(k[key], float('inf')))
#
# def iscat(dct, supercat=None, cat=None, subcat=None, *, error_absent=False):
# if supercat is not None:
# res = find_or_create_item(
# dct['supercats'], supercat, 'cats', error_absent
# )
# if cat is not None:
# res = find_or_create_item(res['cats'], cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def list_find(L, pred):
# return next(item for item in L if pred(item))
. Output only the next line. | subcat['items'] = filter_del( |
Based on the snippet: <|code_start|> faction))
if faction is not None:
item['side'] = faction
else:
item.pop('side', '')
def fix_types_data(self):
for supercat in self.achievs['supercats']:
for cat in supercat['cats']:
for subcat in cat['subcats']:
for item in subcat['items']:
ach_id = int(item['id'])
wt_ach = self.wt_achiev[ach_id]
item['id'] = int(ach_id)
item['points'] = int(wt_ach['Points'])
item['title'] = wt_ach['Title_lang']
item.pop('criteria', None)
item.pop('name', None)
def reorder_categories(self):
def get_name_order_for_category(cat_id):
subcats = [
e
for e in self.wt_achiev_category.values()
if int(e['Parent']) == int(cat_id)
]
subcats.sort(key=lambda x: int(x['Ui_order']))
return [e['Name_lang'] for e in subcats]
# Sort supercategories
<|code_end|>
, predict the immediate next line with the help of imports:
import collections
from .fixer import WowToolsFixer
from .tools import (changelog, genid, filter_del, sort_try_respect_order,
iscat, list_find)
and context (classes, functions, sometimes code) from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# def genid():
# return binascii.b2a_hex(os.urandom(4)).decode('ascii')
#
# def filter_del(L, cond, deleted=None, format_deleted=None):
# kept = [item for item in L if cond(item)]
# if deleted is not None:
# if format_deleted is None:
# format_deleted = lambda x: x # noqa
# deleted.extend(format_deleted(item) for item in L if not cond(item))
# return kept
#
# def sort_try_respect_order(L, order_list, key='name'):
# d = {k: v for v, k in enumerate(order_list)}
# L.sort(key=lambda k: d.get(k[key], float('inf')))
#
# def iscat(dct, supercat=None, cat=None, subcat=None, *, error_absent=False):
# if supercat is not None:
# res = find_or_create_item(
# dct['supercats'], supercat, 'cats', error_absent
# )
# if cat is not None:
# res = find_or_create_item(res['cats'], cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def list_find(L, pred):
# return next(item for item in L if pred(item))
. Output only the next line. | sort_try_respect_order( |
Here is a snippet: <|code_start|> lambda item: ' - {}'.format(item['name'])
)
if deleted_supcats:
changelog("* Deleted super-categories:\n{}"
.format('\n'.join(deleted_supcats)))
def fix_moved_subcategories(self):
for supercat in self.achievs['supercats']:
for cat in supercat['cats']:
subcat_to_remove = set()
for i, subcat in enumerate(cat['subcats']):
expected = (supercat['name'], cat['name'])
id_list = [int(item['id']) for item in subcat['items']]
ach_to_idx = {int(item['id']): idx
for idx, item in enumerate(subcat['items'])}
if not id_list:
continue
path_to_achs = collections.defaultdict(list)
for id in id_list:
path_to_achs[self.id_to_cat[id]].append(
self.genach(int(id)))
first_path = list(path_to_achs.keys())[0]
if len(path_to_achs) > 1:
changelog('* Splitted sub-category {} > {} > {}'
' in the following categories:'
.format(*expected, subcat['name']))
achs_to_remove = set()
for path, achs in path_to_achs.items():
if path == expected:
continue
<|code_end|>
. Write the next line using the current file imports:
import collections
from .fixer import WowToolsFixer
from .tools import (changelog, genid, filter_del, sort_try_respect_order,
iscat, list_find)
and context from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# def genid():
# return binascii.b2a_hex(os.urandom(4)).decode('ascii')
#
# def filter_del(L, cond, deleted=None, format_deleted=None):
# kept = [item for item in L if cond(item)]
# if deleted is not None:
# if format_deleted is None:
# format_deleted = lambda x: x # noqa
# deleted.extend(format_deleted(item) for item in L if not cond(item))
# return kept
#
# def sort_try_respect_order(L, order_list, key='name'):
# d = {k: v for v, k in enumerate(order_list)}
# L.sort(key=lambda k: d.get(k[key], float('inf')))
#
# def iscat(dct, supercat=None, cat=None, subcat=None, *, error_absent=False):
# if supercat is not None:
# res = find_or_create_item(
# dct['supercats'], supercat, 'cats', error_absent
# )
# if cat is not None:
# res = find_or_create_item(res['cats'], cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def list_find(L, pred):
# return next(item for item in L if pred(item))
, which may include functions, classes, or code. Output only the next line. | (iscat(self.achievs, *path) |
Here is a snippet: <|code_start|> for cat in supercat['cats']:
for subcat in cat['subcats']:
for item in subcat['items']:
ach_id = int(item['id'])
wt_ach = self.wt_achiev[ach_id]
item['id'] = int(ach_id)
item['points'] = int(wt_ach['Points'])
item['title'] = wt_ach['Title_lang']
item.pop('criteria', None)
item.pop('name', None)
def reorder_categories(self):
def get_name_order_for_category(cat_id):
subcats = [
e
for e in self.wt_achiev_category.values()
if int(e['Parent']) == int(cat_id)
]
subcats.sort(key=lambda x: int(x['Ui_order']))
return [e['Name_lang'] for e in subcats]
# Sort supercategories
sort_try_respect_order(
self.achievs['supercats'],
get_name_order_for_category(-1)
)
# Sort subcategories
for supercat in self.achievs['supercats']:
try:
<|code_end|>
. Write the next line using the current file imports:
import collections
from .fixer import WowToolsFixer
from .tools import (changelog, genid, filter_del, sort_try_respect_order,
iscat, list_find)
and context from other files:
# Path: dataimporter/fixer.py
# class WowToolsFixer:
# """Base class for Wowtools-based data fixers."""
# load_files = False
#
# def __init__(self, *args, build=None):
# self.build = build
# self._store_init(*args)
# if self.load_files:
# self.wt_files = {
# int(e['ID']): e for e in self.wt_get_table('files')
# }
#
# def _store_init(self, *args):
# raise NotImplementedError
#
# def run(self):
# raise NotImplementedError
#
# def wt_get_table(self, table_name):
# return wowtools.get_table(table_name, self.build)
#
# def get_icon_name(self, icon_id: int):
# assert self.load_files
# icon_name = str(icon_id)
# if icon_id in self.wt_files:
# icon_path = self.wt_files[icon_id]['Path']
# if 'encrypted' not in icon_path:
# icon_name = icon_path.split('/')[-1].rsplit('.', 1)[0].lower()
# icon_name = icon_name.replace(' ', '-')
#
# return icon_name
#
# Path: dataimporter/tools.py
# def changelog(*args, **kwargs):
# print(*args, **kwargs, file=sys.stderr)
#
# def genid():
# return binascii.b2a_hex(os.urandom(4)).decode('ascii')
#
# def filter_del(L, cond, deleted=None, format_deleted=None):
# kept = [item for item in L if cond(item)]
# if deleted is not None:
# if format_deleted is None:
# format_deleted = lambda x: x # noqa
# deleted.extend(format_deleted(item) for item in L if not cond(item))
# return kept
#
# def sort_try_respect_order(L, order_list, key='name'):
# d = {k: v for v, k in enumerate(order_list)}
# L.sort(key=lambda k: d.get(k[key], float('inf')))
#
# def iscat(dct, supercat=None, cat=None, subcat=None, *, error_absent=False):
# if supercat is not None:
# res = find_or_create_item(
# dct['supercats'], supercat, 'cats', error_absent
# )
# if cat is not None:
# res = find_or_create_item(res['cats'], cat, 'subcats', error_absent)
# if subcat is not None:
# res = find_or_create_item(
# res['subcats'], subcat, 'items', error_absent
# )
# return res
#
# def list_find(L, pred):
# return next(item for item in L if pred(item))
, which may include functions, classes, or code. Output only the next line. | wt_supercat = list_find( |
Here is a snippet: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility functions for Error Reporting."""
def build_flask_context(request):
"""Builds an HTTP context object from a Flask (Werkzeug) request object.
This helper method extracts the relevant HTTP context from a Flask request
object into an object ready to be sent to Error Reporting.
.. code-block:: python
>>> @app.errorhandler(HTTPException)
... def handle_error(exc):
... client.report_exception(
... http_context=build_flask_context(request))
... # rest of error response code here
:type request: :class:`werkzeug.wrappers.request`
:param request: The Flask request object to convert.
:rtype: :class:`~google.cloud.error_reporting.client.HTTPContext`
:returns: An HTTPContext object ready to be sent to the Error Reporting
API.
"""
<|code_end|>
. Write the next line using the current file imports:
from google.cloud.error_reporting.client import HTTPContext
and context from other files:
# Path: google/cloud/error_reporting/client.py
# class HTTPContext(object):
# """HTTPContext defines an object that captures the parameter for the
# httpRequest part of Error Reporting API
#
# :type method: str
# :param method: The type of HTTP request, such as GET, POST, etc.
#
# :type url: str
# :param url: The URL of the request
#
# :type user_agent: str
# :param user_agent: The user agent information that is provided with the
# request.
#
# :type referrer: str
# :param referrer: The referrer information that is provided with the
# request.
#
# :type response_status_code: int
# :param response_status_code: The HTTP response status code for the request.
#
# :type remote_ip: str
# :param remote_ip: The IP address from which the request originated. This
# can be IPv4, IPv6, or a token which is derived from
# the IP address, depending on the data that has been
# provided in the error report.
# """
#
# def __init__(
# self,
# method=None,
# url=None,
# user_agent=None,
# referrer=None,
# response_status_code=None,
# remote_ip=None,
# ):
# self.method = method
# self.url = url
# # intentionally camel case for mapping to JSON API expects
# # pylint: disable=invalid-name
# self.userAgent = user_agent
# self.referrer = referrer
# self.responseStatusCode = response_status_code
# self.remoteIp = remote_ip
, which may include functions, classes, or code. Output only the next line. | return HTTPContext( |
Next line prediction: <|code_start|> # Save the credentials.
self._credentials = credentials
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
self._wrapped_methods = {
self.list_group_stats: gapic_v1.method.wrap_method(
self.list_group_stats, default_timeout=None, client_info=client_info,
),
self.list_events: gapic_v1.method.wrap_method(
self.list_events, default_timeout=None, client_info=client_info,
),
self.delete_events: gapic_v1.method.wrap_method(
self.delete_events, default_timeout=None, client_info=client_info,
),
}
def close(self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()
@property
def list_group_stats(
self,
) -> Callable[
<|code_end|>
. Use current file imports:
(import abc
import pkg_resources
import google.auth # type: ignore
import google.api_core
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.errorreporting_v1beta1.types import error_stats_service)
and context including class names, function names, or small code snippets from other files:
# Path: google/cloud/errorreporting_v1beta1/types/error_stats_service.py
# class TimedCountAlignment(proto.Enum):
# class ErrorGroupOrder(proto.Enum):
# class ListGroupStatsRequest(proto.Message):
# class ListGroupStatsResponse(proto.Message):
# class ErrorGroupStats(proto.Message):
# class TimedCount(proto.Message):
# class ListEventsRequest(proto.Message):
# class ListEventsResponse(proto.Message):
# class QueryTimeRange(proto.Message):
# class Period(proto.Enum):
# class ServiceContextFilter(proto.Message):
# class DeleteEventsRequest(proto.Message):
# class DeleteEventsResponse(proto.Message):
# ERROR_COUNT_ALIGNMENT_UNSPECIFIED = 0
# ALIGNMENT_EQUAL_ROUNDED = 1
# ALIGNMENT_EQUAL_AT_END = 2
# GROUP_ORDER_UNSPECIFIED = 0
# COUNT_DESC = 1
# LAST_SEEN_DESC = 2
# CREATED_DESC = 3
# AFFECTED_USERS_DESC = 4
# PERIOD_UNSPECIFIED = 0
# PERIOD_1_HOUR = 1
# PERIOD_6_HOURS = 2
# PERIOD_1_DAY = 3
# PERIOD_1_WEEK = 4
# PERIOD_30_DAYS = 5
# def raw_page(self):
# def raw_page(self):
. Output only the next line. | [error_stats_service.ListGroupStatsRequest], |
Using the snippet: <|code_start|> - Inside the requested time interval
- Non-overlapping, and
- Ordered by ascending time.
first_seen_time (google.protobuf.timestamp_pb2.Timestamp):
Approximate first occurrence that was ever seen for this
group and which matches the given filter criteria, ignoring
the time_range that was specified in the request.
last_seen_time (google.protobuf.timestamp_pb2.Timestamp):
Approximate last occurrence that was ever seen for this
group and which matches the given filter criteria, ignoring
the time_range that was specified in the request.
affected_services (Sequence[google.cloud.errorreporting_v1beta1.types.ServiceContext]):
Service contexts with a non-zero error count for the given
filter criteria. This list can be truncated if multiple
services are affected. Refer to ``num_affected_services``
for the total count.
num_affected_services (int):
The total number of services with a non-zero
error count for the given filter criteria.
representative (google.cloud.errorreporting_v1beta1.types.ErrorEvent):
An arbitrary event that is chosen as
representative for the whole group. The
representative event is intended to be used as a
quick preview for the whole group. Events in the
group are usually sufficiently similar to each
other such that showing an arbitrary
representative provides insight into the
characteristics of the group as a whole.
"""
<|code_end|>
, determine the next line of code. You have imports:
import proto # type: ignore
from google.cloud.errorreporting_v1beta1.types import common
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
and context (class names, function names, or code) available:
# Path: google/cloud/errorreporting_v1beta1/types/common.py
# class ResolutionStatus(proto.Enum):
# class ErrorGroup(proto.Message):
# class TrackingIssue(proto.Message):
# class ErrorEvent(proto.Message):
# class ServiceContext(proto.Message):
# class ErrorContext(proto.Message):
# class HttpRequestContext(proto.Message):
# class SourceLocation(proto.Message):
# RESOLUTION_STATUS_UNSPECIFIED = 0
# OPEN = 1
# ACKNOWLEDGED = 2
# RESOLVED = 3
# MUTED = 4
. Output only the next line. | group = proto.Field(proto.MESSAGE, number=1, message=common.ErrorGroup,) |
Next line prediction: <|code_start|> credentials = credentials.with_always_use_jwt_access(True)
# Save the credentials.
self._credentials = credentials
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
self._wrapped_methods = {
self.get_group: gapic_v1.method.wrap_method(
self.get_group, default_timeout=None, client_info=client_info,
),
self.update_group: gapic_v1.method.wrap_method(
self.update_group, default_timeout=None, client_info=client_info,
),
}
def close(self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()
@property
def get_group(
self,
) -> Callable[
[error_group_service.GetGroupRequest],
<|code_end|>
. Use current file imports:
(import abc
import pkg_resources
import google.auth # type: ignore
import google.api_core
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.errorreporting_v1beta1.types import common
from google.cloud.errorreporting_v1beta1.types import error_group_service)
and context including class names, function names, or small code snippets from other files:
# Path: google/cloud/errorreporting_v1beta1/types/common.py
# class ResolutionStatus(proto.Enum):
# class ErrorGroup(proto.Message):
# class TrackingIssue(proto.Message):
# class ErrorEvent(proto.Message):
# class ServiceContext(proto.Message):
# class ErrorContext(proto.Message):
# class HttpRequestContext(proto.Message):
# class SourceLocation(proto.Message):
# RESOLUTION_STATUS_UNSPECIFIED = 0
# OPEN = 1
# ACKNOWLEDGED = 2
# RESOLVED = 3
# MUTED = 4
#
# Path: google/cloud/errorreporting_v1beta1/types/error_group_service.py
# class GetGroupRequest(proto.Message):
# class UpdateGroupRequest(proto.Message):
. Output only the next line. | Union[common.ErrorGroup, Awaitable[common.ErrorGroup]], |
Given the following code snippet before the placeholder: <|code_start|> ):
credentials = credentials.with_always_use_jwt_access(True)
# Save the credentials.
self._credentials = credentials
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
self._wrapped_methods = {
self.get_group: gapic_v1.method.wrap_method(
self.get_group, default_timeout=None, client_info=client_info,
),
self.update_group: gapic_v1.method.wrap_method(
self.update_group, default_timeout=None, client_info=client_info,
),
}
def close(self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()
@property
def get_group(
self,
) -> Callable[
<|code_end|>
, predict the next line using imports from the current file:
import abc
import pkg_resources
import google.auth # type: ignore
import google.api_core
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.errorreporting_v1beta1.types import common
from google.cloud.errorreporting_v1beta1.types import error_group_service
and context including class names, function names, and sometimes code from other files:
# Path: google/cloud/errorreporting_v1beta1/types/common.py
# class ResolutionStatus(proto.Enum):
# class ErrorGroup(proto.Message):
# class TrackingIssue(proto.Message):
# class ErrorEvent(proto.Message):
# class ServiceContext(proto.Message):
# class ErrorContext(proto.Message):
# class HttpRequestContext(proto.Message):
# class SourceLocation(proto.Message):
# RESOLUTION_STATUS_UNSPECIFIED = 0
# OPEN = 1
# ACKNOWLEDGED = 2
# RESOLVED = 3
# MUTED = 4
#
# Path: google/cloud/errorreporting_v1beta1/types/error_group_service.py
# class GetGroupRequest(proto.Message):
# class UpdateGroupRequest(proto.Message):
. Output only the next line. | [error_group_service.GetGroupRequest], |
Given the following code snippet before the placeholder: <|code_start|> channel creation.
Returns:
grpc.Channel: A gRPC channel object.
Raises:
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
quota_project_id=quota_project_id,
default_scopes=cls.AUTH_SCOPES,
scopes=scopes,
default_host=cls.DEFAULT_HOST,
**kwargs,
)
@property
def grpc_channel(self) -> grpc.Channel:
"""Return the channel designed to connect to this service.
"""
return self._grpc_channel
@property
def report_error_event(
self,
) -> Callable[
<|code_end|>
, predict the next line using imports from the current file:
import warnings
import google.auth # type: ignore
import grpc # type: ignore
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers
from google.api_core import gapic_v1
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.cloud.errorreporting_v1beta1.types import report_errors_service
from .base import ReportErrorsServiceTransport, DEFAULT_CLIENT_INFO
and context including class names, function names, and sometimes code from other files:
# Path: google/cloud/errorreporting_v1beta1/types/report_errors_service.py
# class ReportErrorEventRequest(proto.Message):
# class ReportErrorEventResponse(proto.Message):
# class ReportedErrorEvent(proto.Message):
#
# Path: google/cloud/errorreporting_v1beta1/services/report_errors_service/transports/base.py
# class ReportErrorsServiceTransport(abc.ABC):
# """Abstract transport class for ReportErrorsService."""
#
# AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
#
# DEFAULT_HOST: str = "clouderrorreporting.googleapis.com"
#
# def __init__(
# self,
# *,
# host: str = DEFAULT_HOST,
# credentials: ga_credentials.Credentials = None,
# credentials_file: Optional[str] = None,
# scopes: Optional[Sequence[str]] = None,
# quota_project_id: Optional[str] = None,
# client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
# always_use_jwt_access: Optional[bool] = False,
# **kwargs,
# ) -> None:
# """Instantiate the transport.
#
# Args:
# host (Optional[str]):
# The hostname to connect to.
# credentials (Optional[google.auth.credentials.Credentials]): The
# authorization credentials to attach to requests. These
# credentials identify the application to the service; if none
# are specified, the client will attempt to ascertain the
# credentials from the environment.
# credentials_file (Optional[str]): A file with credentials that can
# be loaded with :func:`google.auth.load_credentials_from_file`.
# This argument is mutually exclusive with credentials.
# scopes (Optional[Sequence[str]]): A list of scopes.
# quota_project_id (Optional[str]): An optional project to use for billing
# and quota.
# client_info (google.api_core.gapic_v1.client_info.ClientInfo):
# The client info used to send a user-agent string along with
# API requests. If ``None``, then default info will be used.
# Generally, you only need to set this if you're developing
# your own client library.
# always_use_jwt_access (Optional[bool]): Whether self signed JWT should
# be used for service account credentials.
# """
# # Save the hostname. Default to port 443 (HTTPS) if none is specified.
# if ":" not in host:
# host += ":443"
# self._host = host
#
# scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
#
# # Save the scopes.
# self._scopes = scopes
#
# # If no credentials are provided, then determine the appropriate
# # defaults.
# if credentials and credentials_file:
# raise core_exceptions.DuplicateCredentialArgs(
# "'credentials_file' and 'credentials' are mutually exclusive"
# )
#
# if credentials_file is not None:
# credentials, _ = google.auth.load_credentials_from_file(
# credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
# )
# elif credentials is None:
# credentials, _ = google.auth.default(
# **scopes_kwargs, quota_project_id=quota_project_id
# )
#
# # If the credentials are service account credentials, then always try to use self signed JWT.
# if (
# always_use_jwt_access
# and isinstance(credentials, service_account.Credentials)
# and hasattr(service_account.Credentials, "with_always_use_jwt_access")
# ):
# credentials = credentials.with_always_use_jwt_access(True)
#
# # Save the credentials.
# self._credentials = credentials
#
# def _prep_wrapped_messages(self, client_info):
# # Precompute the wrapped methods.
# self._wrapped_methods = {
# self.report_error_event: gapic_v1.method.wrap_method(
# self.report_error_event, default_timeout=None, client_info=client_info,
# ),
# }
#
# def close(self):
# """Closes resources associated with the transport.
#
# .. warning::
# Only call this method if the transport is NOT shared
# with other clients - this may cause errors in other clients!
# """
# raise NotImplementedError()
#
# @property
# def report_error_event(
# self,
# ) -> Callable[
# [report_errors_service.ReportErrorEventRequest],
# Union[
# report_errors_service.ReportErrorEventResponse,
# Awaitable[report_errors_service.ReportErrorEventResponse],
# ],
# ]:
# raise NotImplementedError()
#
# DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
# gapic_version=pkg_resources.get_distribution(
# "google-cloud-errorreporting",
# ).version,
# )
. Output only the next line. | [report_errors_service.ReportErrorEventRequest], |
Given the following code snippet before the placeholder: <|code_start|> always_use_jwt_access
and isinstance(credentials, service_account.Credentials)
and hasattr(service_account.Credentials, "with_always_use_jwt_access")
):
credentials = credentials.with_always_use_jwt_access(True)
# Save the credentials.
self._credentials = credentials
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
self._wrapped_methods = {
self.report_error_event: gapic_v1.method.wrap_method(
self.report_error_event, default_timeout=None, client_info=client_info,
),
}
def close(self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()
@property
def report_error_event(
self,
) -> Callable[
<|code_end|>
, predict the next line using imports from the current file:
import abc
import pkg_resources
import google.auth # type: ignore
import google.api_core
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.errorreporting_v1beta1.types import report_errors_service
and context including class names, function names, and sometimes code from other files:
# Path: google/cloud/errorreporting_v1beta1/types/report_errors_service.py
# class ReportErrorEventRequest(proto.Message):
# class ReportErrorEventResponse(proto.Message):
# class ReportedErrorEvent(proto.Message):
. Output only the next line. | [report_errors_service.ReportErrorEventRequest], |
Given the code snippet: <|code_start|> metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.errorreporting_v1beta1.types.ListEventsRequest):
The initial request object.
response (google.cloud.errorreporting_v1beta1.types.ListEventsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = error_stats_service.ListEventsRequest(request)
self._response = response
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterator[error_stats_service.ListEventsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
yield self._response
<|code_end|>
, generate the next line using the imports in this file:
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Sequence,
Tuple,
Optional,
Iterator,
)
from google.cloud.errorreporting_v1beta1.types import common
from google.cloud.errorreporting_v1beta1.types import error_stats_service
and context (functions, classes, or occasionally code) from other files:
# Path: google/cloud/errorreporting_v1beta1/types/common.py
# class ResolutionStatus(proto.Enum):
# class ErrorGroup(proto.Message):
# class TrackingIssue(proto.Message):
# class ErrorEvent(proto.Message):
# class ServiceContext(proto.Message):
# class ErrorContext(proto.Message):
# class HttpRequestContext(proto.Message):
# class SourceLocation(proto.Message):
# RESOLUTION_STATUS_UNSPECIFIED = 0
# OPEN = 1
# ACKNOWLEDGED = 2
# RESOLVED = 3
# MUTED = 4
#
# Path: google/cloud/errorreporting_v1beta1/types/error_stats_service.py
# class TimedCountAlignment(proto.Enum):
# class ErrorGroupOrder(proto.Enum):
# class ListGroupStatsRequest(proto.Message):
# class ListGroupStatsResponse(proto.Message):
# class ErrorGroupStats(proto.Message):
# class TimedCount(proto.Message):
# class ListEventsRequest(proto.Message):
# class ListEventsResponse(proto.Message):
# class QueryTimeRange(proto.Message):
# class Period(proto.Enum):
# class ServiceContextFilter(proto.Message):
# class DeleteEventsRequest(proto.Message):
# class DeleteEventsResponse(proto.Message):
# ERROR_COUNT_ALIGNMENT_UNSPECIFIED = 0
# ALIGNMENT_EQUAL_ROUNDED = 1
# ALIGNMENT_EQUAL_AT_END = 2
# GROUP_ORDER_UNSPECIFIED = 0
# COUNT_DESC = 1
# LAST_SEEN_DESC = 2
# CREATED_DESC = 3
# AFFECTED_USERS_DESC = 4
# PERIOD_UNSPECIFIED = 0
# PERIOD_1_HOUR = 1
# PERIOD_6_HOURS = 2
# PERIOD_1_DAY = 3
# PERIOD_1_WEEK = 4
# PERIOD_30_DAYS = 5
# def raw_page(self):
# def raw_page(self):
. Output only the next line. | def __iter__(self) -> Iterator[common.ErrorEvent]: |
Given the code snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class ListGroupStatsPager:
"""A pager for iterating through ``list_group_stats`` requests.
This class thinly wraps an initial
:class:`google.cloud.errorreporting_v1beta1.types.ListGroupStatsResponse` object, and
provides an ``__iter__`` method to iterate through its
``error_group_stats`` field.
If there are more pages, the ``__iter__`` method will make additional
``ListGroupStats`` requests and continue to iterate
through the ``error_group_stats`` field on the
corresponding responses.
All the usual :class:`google.cloud.errorreporting_v1beta1.types.ListGroupStatsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(
self,
<|code_end|>
, generate the next line using the imports in this file:
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Sequence,
Tuple,
Optional,
Iterator,
)
from google.cloud.errorreporting_v1beta1.types import common
from google.cloud.errorreporting_v1beta1.types import error_stats_service
and context (functions, classes, or occasionally code) from other files:
# Path: google/cloud/errorreporting_v1beta1/types/common.py
# class ResolutionStatus(proto.Enum):
# class ErrorGroup(proto.Message):
# class TrackingIssue(proto.Message):
# class ErrorEvent(proto.Message):
# class ServiceContext(proto.Message):
# class ErrorContext(proto.Message):
# class HttpRequestContext(proto.Message):
# class SourceLocation(proto.Message):
# RESOLUTION_STATUS_UNSPECIFIED = 0
# OPEN = 1
# ACKNOWLEDGED = 2
# RESOLVED = 3
# MUTED = 4
#
# Path: google/cloud/errorreporting_v1beta1/types/error_stats_service.py
# class TimedCountAlignment(proto.Enum):
# class ErrorGroupOrder(proto.Enum):
# class ListGroupStatsRequest(proto.Message):
# class ListGroupStatsResponse(proto.Message):
# class ErrorGroupStats(proto.Message):
# class TimedCount(proto.Message):
# class ListEventsRequest(proto.Message):
# class ListEventsResponse(proto.Message):
# class QueryTimeRange(proto.Message):
# class Period(proto.Enum):
# class ServiceContextFilter(proto.Message):
# class DeleteEventsRequest(proto.Message):
# class DeleteEventsResponse(proto.Message):
# ERROR_COUNT_ALIGNMENT_UNSPECIFIED = 0
# ALIGNMENT_EQUAL_ROUNDED = 1
# ALIGNMENT_EQUAL_AT_END = 2
# GROUP_ORDER_UNSPECIFIED = 0
# COUNT_DESC = 1
# LAST_SEEN_DESC = 2
# CREATED_DESC = 3
# AFFECTED_USERS_DESC = 4
# PERIOD_UNSPECIFIED = 0
# PERIOD_1_HOUR = 1
# PERIOD_6_HOURS = 2
# PERIOD_1_DAY = 3
# PERIOD_1_WEEK = 4
# PERIOD_30_DAYS = 5
# def raw_page(self):
# def raw_page(self):
. Output only the next line. | method: Callable[..., error_stats_service.ListGroupStatsResponse], |
Based on the snippet: <|code_start|> package="google.devtools.clouderrorreporting.v1beta1",
manifest={"GetGroupRequest", "UpdateGroupRequest",},
)
class GetGroupRequest(proto.Message):
r"""A request to return an individual group.
Attributes:
group_name (str):
Required. The group resource name. Written as
``projects/{projectID}/groups/{group_name}``. Call
```groupStats.list`` <https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.groupStats/list>`__
to return a list of groups belonging to this project.
Example: ``projects/my-project-123/groups/my-group``
"""
group_name = proto.Field(proto.STRING, number=1,)
class UpdateGroupRequest(proto.Message):
r"""A request to replace the existing data for the given group.
Attributes:
group (google.cloud.errorreporting_v1beta1.types.ErrorGroup):
Required. The group which replaces the
resource on the server.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import proto # type: ignore
from google.cloud.errorreporting_v1beta1.types import common
and context (classes, functions, sometimes code) from other files:
# Path: google/cloud/errorreporting_v1beta1/types/common.py
# class ResolutionStatus(proto.Enum):
# class ErrorGroup(proto.Message):
# class TrackingIssue(proto.Message):
# class ErrorEvent(proto.Message):
# class ServiceContext(proto.Message):
# class ErrorContext(proto.Message):
# class HttpRequestContext(proto.Message):
# class SourceLocation(proto.Message):
# RESOLUTION_STATUS_UNSPECIFIED = 0
# OPEN = 1
# ACKNOWLEDGED = 2
# RESOLVED = 3
# MUTED = 4
. Output only the next line. | group = proto.Field(proto.MESSAGE, number=1, message=common.ErrorGroup,) |
Using the snippet: <|code_start|> contain a header (typically consisting of the exception type
name and an error message) and an exception stack trace in
one of the supported programming languages and formats.
Supported languages are Java, Python, JavaScript, Ruby, C#,
PHP, and Go. Supported stack trace formats are:
- **Java**: Must be the return value of
```Throwable.printStackTrace()`` <https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace%28%29>`__.
- **Python**: Must be the return value of
```traceback.format_exc()`` <https://docs.python.org/2/library/traceback.html#traceback.format_exc>`__.
- **JavaScript**: Must be the value of
```error.stack`` <https://github.com/v8/v8/wiki/Stack-Trace-API>`__
as returned by V8.
- **Ruby**: Must contain frames returned by
```Exception.backtrace`` <https://ruby-doc.org/core-2.2.0/Exception.html#method-i-backtrace>`__.
- **C#**: Must be the return value of
```Exception.ToString()`` <https://msdn.microsoft.com/en-us/library/system.exception.tostring.aspx>`__.
- **PHP**: Must start with
``PHP (Notice|Parse error|Fatal error|Warning)`` and
contain the result of
```(string)$exception`` <http://php.net/manual/en/exception.tostring.php>`__.
- **Go**: Must be the return value of
```runtime.Stack()`` <https://golang.org/pkg/runtime/debug/#Stack>`__.
context (google.cloud.errorreporting_v1beta1.types.ErrorContext):
Optional. A description of the context in
which the error occurred.
"""
event_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,)
service_context = proto.Field(
<|code_end|>
, determine the next line of code. You have imports:
import proto # type: ignore
from google.cloud.errorreporting_v1beta1.types import common
from google.protobuf import timestamp_pb2 # type: ignore
and context (class names, function names, or code) available:
# Path: google/cloud/errorreporting_v1beta1/types/common.py
# class ResolutionStatus(proto.Enum):
# class ErrorGroup(proto.Message):
# class TrackingIssue(proto.Message):
# class ErrorEvent(proto.Message):
# class ServiceContext(proto.Message):
# class ErrorContext(proto.Message):
# class HttpRequestContext(proto.Message):
# class SourceLocation(proto.Message):
# RESOLUTION_STATUS_UNSPECIFIED = 0
# OPEN = 1
# ACKNOWLEDGED = 2
# RESOLVED = 3
# MUTED = 4
. Output only the next line. | proto.MESSAGE, number=2, message=common.ServiceContext, |
Given the following code snippet before the placeholder: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Lookup Embedding module."""
if typing.TYPE_CHECKING:
class BasicEmbeddingLookup(input_embedding_base.InputEmbeddingBase):
"""The class that uses the base embedding lookup."""
def __init__(self, encoder_config: "configdict.ConfigDict",
emb_dim_dict: Dict[str, int]):
"""Initialize the embedding base object."""
super().__init__(encoder_config, emb_dim_dict)
with tf.variable_scope(None, default_name=self._name) as variable_scope:
self.variable_scope = variable_scope
# Initialize all the weights.
self._initialize_weights()
def _initialize_weights(self):
"""Initialize the weights for embedding computations."""
for feat_type in self._all_features:
<|code_end|>
, predict the next line using imports from the current file:
import typing
import tensorflow.compat.v1 as tf
from typing import Dict
from ehr_prediction_modeling.embeddings import input_embedding_base
from ehr_prediction_modeling.models.nets import sparse_lookup
from ehr_prediction_modeling import configdict
and context including class names, function names, and sometimes code from other files:
# Path: ehr_prediction_modeling/embeddings/input_embedding_base.py
# class InputEmbeddingBase(metaclass=abc.ABCMeta):
# def __init__(self,
# encoder_config: "configdict.ConfigDict",
# emb_dim_dict: Dict[str, int],
# has_embedding_loss: Optional[bool] = False):
# def get_encoders(self):
# def _initialize_weights(self):
# def get_embedding_loss(self, *unused_args, **unused_kwargs
# ) -> Tuple[tf.Tensor, Dict[str, tf.Tensor]]:
# def _embed_feature(
# self,
# feat_type: str,
# input_data: Tuple[tf.SparseTensor, tf.SparseTensor],
# context: Optional[Dict[str, Any]] = None
# ) -> tf.Tensor:
# def provide_embeddings_to_forward_fn(
# self,
# data: Dict[str, tf.SparseTensor],
# feature_types: List[str]
# ) -> tf.Tensor:
#
# Path: ehr_prediction_modeling/models/nets/sparse_lookup.py
# VALID_COMBINERS = ["sum", "sqrtn", "mean"]
# def combiner_correction(sparse_combiner: str, embed: tf.Tensor) -> tf.Tensor:
# def __init__(self,
# ndim_emb: int,
# ndim_input: int,
# n_act: Optional[int] = None,
# activate_final: bool = False,
# act_fn: Callable[[tf.Tensor], tf.Tensor] = tf.nn.tanh,
# sparse_lookup_dropout_prob: float = 0.,
# dropout_is_training: bool = True,
# sparse_combine: str = "sum",
# name: Optional[str] = None,
# identity_lookup: bool = False):
# def _build(
# self,
# input_data: Tuple[tf.SparseTensor, tf.SparseTensor],
# context: Optional[Dict[str, Union[tf.Tensor, bool,
# tf.SparseTensor]]] = None
# ) -> tf.Tensor:
# class SparseLookupEncoder(snt.AbstractModule):
. Output only the next line. | self._encoders[feat_type] = sparse_lookup.SparseLookupEncoder( |
Using the snippet: <|code_start|># limitations under the License.
# Lint as: python3
"""Metric calculator for classification tasks."""
CONFIDENCE_CALIBRATION_HISTOGRAM_KEY = "full_confidence_calibration_histogram"
RISK_CALIBRATION_HISTOGRAM_KEY = "full_risk_calibration_histogram"
METRICS_EPSILON = 1e-5
ListOrArray = Union[List[Union[float, int]], np.ndarray]
class ClassificationTaskMetricCalculator(base.MetricCalculatorBase):
"""Calculator class for evaluation metrics for classification tasks."""
ALL_METRICS = [
"true_positives", "false_positives", "true_negatives", "false_negatives",
"rocauc", "prauc", "normalised_prauc", "nb_ex", "nb_ex_pos", "nb_ex_neg",
"tp", "tn", "ppv", "npv", "acc", "f1", "f2", "mcc",
"expected_confidence_calibration_error",
"maximum_confidence_calibration_error",
CONFIDENCE_CALIBRATION_HISTOGRAM_KEY, "expected_risk_calibration_error",
"maximum_risk_calibration_error", RISK_CALIBRATION_HISTOGRAM_KEY
]
def __init__(self,
pos: ListOrArray,
neg: ListOrArray,
pos_weights: ListOrArray,
neg_weights: ListOrArray,
<|code_end|>
, determine the next line of code. You have imports:
import math
import numpy as np
from typing import List, Mapping, Optional, Union
from ehr_prediction_modeling.metrics import calibration
from ehr_prediction_modeling.metrics import pr_roc
from ehr_prediction_modeling.metrics.calculators import base
and context (class names, function names, or code) available:
# Path: ehr_prediction_modeling/metrics/calibration.py
# DEFAULT_NUM_BINS = 50
# class Error(Exception):
# class MismatchedPredictionArraysError(Error):
# def reliability_histogram(
# predictions: ListOrArray,
# labels: ListOrArray,
# confidence_scores: ListOrArray,
# num_bins: int = DEFAULT_NUM_BINS,
# example_weights: Optional[ListOrArray] = None
# ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
# def risk_reliability_histogram(
# labels: ListOrArray,
# risk_scores: ListOrArray,
# num_bins=DEFAULT_NUM_BINS,
# example_weights: Optional[ListOrArray] = None
# ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
# def expected_calibration_error(observed_score_histogram: ListOrArray,
# predicted_score_histogram: ListOrArray,
# bin_example_counts: ListOrArray) -> float:
# def maximum_calibration_error(observed_score_histogram: np.ndarray,
# predicted_score_histogram: np.ndarray) -> float:
# def reliability_diagram_from_posneg_lists(
# pos: ListOrArray,
# neg: ListOrArray,
# pos_weights: ListOrArray,
# neg_weights: ListOrArray,
# num_bins: int = DEFAULT_NUM_BINS,
# class_threshold: float = 0.5) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
# def risk_reliability_diagram_from_posneg_lists(
# pos: ListOrArray,
# neg: ListOrArray,
# pos_weights: ListOrArray,
# neg_weights: ListOrArray,
# num_bins: int = DEFAULT_NUM_BINS
# ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
#
# Path: ehr_prediction_modeling/metrics/pr_roc.py
# def area_under_curve_from_raw_scores(scores_pos: ListOrArray,
# scores_neg: ListOrArray) -> float:
# def pr_area_under_curve_from_raw_scores(scores_pos: ListOrArray,
# scores_neg: ListOrArray) -> float:
# def weighted_area_under_curve_from_raw_scores(
# scores_pos: ListOrArray, scores_neg: ListOrArray,
# weights_pos: ListOrArray, weights_neg: ListOrArray) -> float:
# def weighted_pr_area_under_curve_from_raw_scores(
# scores_pos: ListOrArray, scores_neg: ListOrArray,
# weights_pos: ListOrArray, weights_neg: ListOrArray) -> float:
# def roc_curve_from_raw_scores(
# scores_pos: ListOrArray,
# scores_neg: ListOrArray,
# weights_pos: Optional[ListOrArray] = None,
# weights_neg: Optional[ListOrArray] = None) -> CurvePoints:
# def pr_curve_from_raw_scores(
# scores_pos: ListOrArray,
# scores_neg: ListOrArray,
# weights_pos: Optional[ListOrArray] = None,
# weights_neg: Optional[ListOrArray] = None) -> CurvePoints:
# def _curve_area(curve: CurvePoints) -> float:
# def _trapezoid_area(point_left: List[float], point_right: List[float]) -> float:
#
# Path: ehr_prediction_modeling/metrics/calculators/base.py
# class Error(Exception):
# class InvalidClassThresholdError(Error):
# class MetricCalculatorBase():
# ALL_METRICS = []
# def get_metrics_dict(self) -> Mapping[str, Any]:
. Output only the next line. | num_calibration_bins: int = calibration.DEFAULT_NUM_BINS, |
Predict the next line after this snippet: <|code_start|> return {
"positive_rate_histogram": self._positive_rate_histogram,
"risk_histogram": self._risk_histogram,
"risk_bin_counts": self._risk_bin_counts
}
def expected_confidence_calibration_error(self) -> float:
"""Compute the expected confidence calibration error."""
return calibration.expected_calibration_error(self._accuracy_histogram,
self._confidence_histogram,
self._confidence_bin_counts)
def maximum_confidence_calibration_error(self) -> float:
"""Compute the maximum confidence calibration error."""
return calibration.maximum_calibration_error(self._accuracy_histogram,
self._confidence_histogram)
def expected_risk_calibration_error(self) -> float:
"""Compute the expected risk calibration error."""
return calibration.expected_calibration_error(self._positive_rate_histogram,
self._risk_histogram,
self._risk_bin_counts)
def maximum_risk_calibration_error(self) -> float:
"""Compute the maximum risk calibration error."""
return calibration.maximum_calibration_error(self._positive_rate_histogram,
self._risk_histogram)
def rocauc(self) -> float:
"""Get the AUC from the given predictions."""
<|code_end|>
using the current file's imports:
import math
import numpy as np
from typing import List, Mapping, Optional, Union
from ehr_prediction_modeling.metrics import calibration
from ehr_prediction_modeling.metrics import pr_roc
from ehr_prediction_modeling.metrics.calculators import base
and any relevant context from other files:
# Path: ehr_prediction_modeling/metrics/calibration.py
# DEFAULT_NUM_BINS = 50
# class Error(Exception):
# class MismatchedPredictionArraysError(Error):
# def reliability_histogram(
# predictions: ListOrArray,
# labels: ListOrArray,
# confidence_scores: ListOrArray,
# num_bins: int = DEFAULT_NUM_BINS,
# example_weights: Optional[ListOrArray] = None
# ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
# def risk_reliability_histogram(
# labels: ListOrArray,
# risk_scores: ListOrArray,
# num_bins=DEFAULT_NUM_BINS,
# example_weights: Optional[ListOrArray] = None
# ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
# def expected_calibration_error(observed_score_histogram: ListOrArray,
# predicted_score_histogram: ListOrArray,
# bin_example_counts: ListOrArray) -> float:
# def maximum_calibration_error(observed_score_histogram: np.ndarray,
# predicted_score_histogram: np.ndarray) -> float:
# def reliability_diagram_from_posneg_lists(
# pos: ListOrArray,
# neg: ListOrArray,
# pos_weights: ListOrArray,
# neg_weights: ListOrArray,
# num_bins: int = DEFAULT_NUM_BINS,
# class_threshold: float = 0.5) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
# def risk_reliability_diagram_from_posneg_lists(
# pos: ListOrArray,
# neg: ListOrArray,
# pos_weights: ListOrArray,
# neg_weights: ListOrArray,
# num_bins: int = DEFAULT_NUM_BINS
# ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
#
# Path: ehr_prediction_modeling/metrics/pr_roc.py
# def area_under_curve_from_raw_scores(scores_pos: ListOrArray,
# scores_neg: ListOrArray) -> float:
# def pr_area_under_curve_from_raw_scores(scores_pos: ListOrArray,
# scores_neg: ListOrArray) -> float:
# def weighted_area_under_curve_from_raw_scores(
# scores_pos: ListOrArray, scores_neg: ListOrArray,
# weights_pos: ListOrArray, weights_neg: ListOrArray) -> float:
# def weighted_pr_area_under_curve_from_raw_scores(
# scores_pos: ListOrArray, scores_neg: ListOrArray,
# weights_pos: ListOrArray, weights_neg: ListOrArray) -> float:
# def roc_curve_from_raw_scores(
# scores_pos: ListOrArray,
# scores_neg: ListOrArray,
# weights_pos: Optional[ListOrArray] = None,
# weights_neg: Optional[ListOrArray] = None) -> CurvePoints:
# def pr_curve_from_raw_scores(
# scores_pos: ListOrArray,
# scores_neg: ListOrArray,
# weights_pos: Optional[ListOrArray] = None,
# weights_neg: Optional[ListOrArray] = None) -> CurvePoints:
# def _curve_area(curve: CurvePoints) -> float:
# def _trapezoid_area(point_left: List[float], point_right: List[float]) -> float:
#
# Path: ehr_prediction_modeling/metrics/calculators/base.py
# class Error(Exception):
# class InvalidClassThresholdError(Error):
# class MetricCalculatorBase():
# ALL_METRICS = []
# def get_metrics_dict(self) -> Mapping[str, Any]:
. Output only the next line. | return pr_roc.weighted_area_under_curve_from_raw_scores( |
Continue the code snippet: <|code_start|># coding=utf-8
# Copyright 2021 Google Health Research.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Metric calculator for classification tasks."""
CONFIDENCE_CALIBRATION_HISTOGRAM_KEY = "full_confidence_calibration_histogram"
RISK_CALIBRATION_HISTOGRAM_KEY = "full_risk_calibration_histogram"
METRICS_EPSILON = 1e-5
ListOrArray = Union[List[Union[float, int]], np.ndarray]
<|code_end|>
. Use current file imports:
import math
import numpy as np
from typing import List, Mapping, Optional, Union
from ehr_prediction_modeling.metrics import calibration
from ehr_prediction_modeling.metrics import pr_roc
from ehr_prediction_modeling.metrics.calculators import base
and context (classes, functions, or code) from other files:
# Path: ehr_prediction_modeling/metrics/calibration.py
# DEFAULT_NUM_BINS = 50
# class Error(Exception):
# class MismatchedPredictionArraysError(Error):
# def reliability_histogram(
# predictions: ListOrArray,
# labels: ListOrArray,
# confidence_scores: ListOrArray,
# num_bins: int = DEFAULT_NUM_BINS,
# example_weights: Optional[ListOrArray] = None
# ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
# def risk_reliability_histogram(
# labels: ListOrArray,
# risk_scores: ListOrArray,
# num_bins=DEFAULT_NUM_BINS,
# example_weights: Optional[ListOrArray] = None
# ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
# def expected_calibration_error(observed_score_histogram: ListOrArray,
# predicted_score_histogram: ListOrArray,
# bin_example_counts: ListOrArray) -> float:
# def maximum_calibration_error(observed_score_histogram: np.ndarray,
# predicted_score_histogram: np.ndarray) -> float:
# def reliability_diagram_from_posneg_lists(
# pos: ListOrArray,
# neg: ListOrArray,
# pos_weights: ListOrArray,
# neg_weights: ListOrArray,
# num_bins: int = DEFAULT_NUM_BINS,
# class_threshold: float = 0.5) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
# def risk_reliability_diagram_from_posneg_lists(
# pos: ListOrArray,
# neg: ListOrArray,
# pos_weights: ListOrArray,
# neg_weights: ListOrArray,
# num_bins: int = DEFAULT_NUM_BINS
# ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
#
# Path: ehr_prediction_modeling/metrics/pr_roc.py
# def area_under_curve_from_raw_scores(scores_pos: ListOrArray,
# scores_neg: ListOrArray) -> float:
# def pr_area_under_curve_from_raw_scores(scores_pos: ListOrArray,
# scores_neg: ListOrArray) -> float:
# def weighted_area_under_curve_from_raw_scores(
# scores_pos: ListOrArray, scores_neg: ListOrArray,
# weights_pos: ListOrArray, weights_neg: ListOrArray) -> float:
# def weighted_pr_area_under_curve_from_raw_scores(
# scores_pos: ListOrArray, scores_neg: ListOrArray,
# weights_pos: ListOrArray, weights_neg: ListOrArray) -> float:
# def roc_curve_from_raw_scores(
# scores_pos: ListOrArray,
# scores_neg: ListOrArray,
# weights_pos: Optional[ListOrArray] = None,
# weights_neg: Optional[ListOrArray] = None) -> CurvePoints:
# def pr_curve_from_raw_scores(
# scores_pos: ListOrArray,
# scores_neg: ListOrArray,
# weights_pos: Optional[ListOrArray] = None,
# weights_neg: Optional[ListOrArray] = None) -> CurvePoints:
# def _curve_area(curve: CurvePoints) -> float:
# def _trapezoid_area(point_left: List[float], point_right: List[float]) -> float:
#
# Path: ehr_prediction_modeling/metrics/calculators/base.py
# class Error(Exception):
# class InvalidClassThresholdError(Error):
# class MetricCalculatorBase():
# ALL_METRICS = []
# def get_metrics_dict(self) -> Mapping[str, Any]:
. Output only the next line. | class ClassificationTaskMetricCalculator(base.MetricCalculatorBase): |
Predict the next line for this snippet: <|code_start|># limitations under the License.
# Lint as: python3
"""Base class for EHR embeddings."""
if typing.TYPE_CHECKING:
class InputEmbeddingBase(metaclass=abc.ABCMeta):
"""The base embedding class declaring the interface."""
def __init__(self,
encoder_config: "configdict.ConfigDict",
emb_dim_dict: Dict[str, int],
has_embedding_loss: Optional[bool] = False):
"""Initialize the embedding base object.
Args:
encoder_config: ConfigDict of encoder parameters.
emb_dim_dict: Dict of feature name to dimension of the embedding for that
feature.
has_embedding_loss: True if this embedding has a loss.
"""
self._config = encoder_config
# Regularization depends on this
self._name = self._config.embedding_type
self._embed_dim_dict = emb_dim_dict
# Boolean, whether in training mode to apply dropout / batch normalization.
<|code_end|>
with the help of current file imports:
import abc
import collections
import typing
import tensorflow.compat.v1 as tf
from typing import Any, Dict, List, Optional, Tuple
from ehr_prediction_modeling import types
from ehr_prediction_modeling import configdict
and context from other files:
# Path: ehr_prediction_modeling/types.py
# class ForwardFunctionReturns(
# collections.namedtuple(
# "ForwardFunctionReturns",
# ["model_output", "hidden_states", "inputs", "activations"],
# )):
# class EmbeddingType(object):
# class EmbeddingEncoderType(object):
# class ActivationFunction(object):
# class RegularizationType(object):
# class TaskType(object):
# class BestModelMetric(object):
# class TaskNames(object):
# class TaskTypes(object):
# class TaskLossType(object):
# class RNNCellType(object):
# class FeatureTypes(object):
# class Optimizers(object):
# class LearningRateScheduling(object):
# class EmbeddingCombinationMethod(object):
# class SNRBlockConnType(object):
# class SubNettoSubNetConnType(object):
# class SNRInputCombinationType(object):
# class LossCombinationType(object):
# class ModelTypes(object):
# class TaskLayerTypes(object):
# class ModelMode(object):
# LOOKUP = "Lookup"
# DEEP_EMBEDDING = "DeepEmbedding"
# RESIDUAL = "residual"
# FC = "fc"
# SNR = "snr"
# TANH = "tanh"
# RELU = "relu"
# LRELU = "lrelu"
# SWISH = "swish"
# ELU = "elu"
# SLU = "selu"
# ELISH = "elish"
# HARD_ELISH = "hard_elish"
# SIGMOID = "sigmoid"
# HARD_SIGMOID = "hard_sigmoid"
# TANH_PEN = "tanh_pen"
# NONE = "None"
# L1 = "L1"
# L2 = "L2"
# BINARY_CLASSIFICATION = "BinaryClassification"
# REGRESSION = "Regression"
# PRAUC = "prauc"
# ROCAUC = "rocauc"
# L1 = "l1"
# ADVERSE_OUTCOME_RISK = "AdverseOutcomeRisk"
# LAB_REGRESSION = "Labs"
# BINARIZED_LOS = "BinarizedLengthOfStay"
# REGRESSION_LOS = "RegressionLengthOfStay"
# MORTALITY = "MortalityRisk"
# READMISSION = "ReadmissionRisk"
# ADVERSE_OUTCOME_RISK = "ao_risk"
# LAB_REGRESSION = "labs_regression"
# LOS = "length_of_stay"
# MORTALITY = "mortality"
# READMISSION = "readmission"
# CE = "CE"
# MULTI_CE = "MULTI_CE"
# BRIER = "Brier"
# L1 = "L1"
# L2 = "L2"
# SRU = "SRU"
# LSTM = "LSTM"
# UGRNN = "UGRNN"
# PRESENCE_SEQ = "pres_s" # Sequential presence features
# NUMERIC_SEQ = "num_s" # Sequential numerical features
# CATEGORY_COUNTS_SEQ = "count_s" # Sequential category counts features
# FEAT_TO_NAME = {
# "pres_s": "presence",
# "num_s": "numeric",
# "count_s": "category_counts",
# }
# SGD = "SGD"
# ADAM = "Adam"
# RMSPROP = "RMSprop"
# FIXED = "fixed"
# EXPONENTIAL_DECAY = "exponential_decay"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum_all"
# SUM_BY_SUFFIX = "sum_by_suffix"
# COMBINE_SNR_OUT = "combine_snr_out"
# FC = "fc"
# HIGHWAY = "highway"
# RESIDUAL = "residual"
# NONE = "None"
# BOOL = "bool"
# SCALAR_WEIGHT = "scalar_weight"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum"
# SUM_ALL = "SUM_ALL"
# UNCERTAINTY_WEIGHTED = "UNCERTAINTY_WEIGHTED"
# RNN = "RNN"
# SNRNN = "SNRNN"
# NONE = "none"
# MLP = "MLP"
# SNRMLP = "SNRMLP"
# TRAIN = "train"
# EVAL = "eval"
# PREDICT = "predict"
# def is_train(cls, mode: str) -> bool:
, which may contain function names, class names, or code. Output only the next line. | self._is_training = types.ModelMode.is_train( |
Given the code snippet: <|code_start|># coding=utf-8
# Copyright 2021 Google Health Research.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Factory for creation of cells."""
if typing.TYPE_CHECKING:
def _map_cell_type(config: "configdict.ConfigDict") -> snt.AbstractModule:
"""Returns cell corresponding to cell_type string."""
cells_not_allowing_wrappers = [
<|code_end|>
, generate the next line using the imports in this file:
import functools
import typing
import sonnet as snt
import tensorflow.compat.v1 as tf
from ehr_prediction_modeling import types
from ehr_prediction_modeling.models import reset_core
from tensorflow import contrib as tf_contrib
from ehr_prediction_modeling import configdict
and context (functions, classes, or occasionally code) from other files:
# Path: ehr_prediction_modeling/types.py
# class ForwardFunctionReturns(
# collections.namedtuple(
# "ForwardFunctionReturns",
# ["model_output", "hidden_states", "inputs", "activations"],
# )):
# class EmbeddingType(object):
# class EmbeddingEncoderType(object):
# class ActivationFunction(object):
# class RegularizationType(object):
# class TaskType(object):
# class BestModelMetric(object):
# class TaskNames(object):
# class TaskTypes(object):
# class TaskLossType(object):
# class RNNCellType(object):
# class FeatureTypes(object):
# class Optimizers(object):
# class LearningRateScheduling(object):
# class EmbeddingCombinationMethod(object):
# class SNRBlockConnType(object):
# class SubNettoSubNetConnType(object):
# class SNRInputCombinationType(object):
# class LossCombinationType(object):
# class ModelTypes(object):
# class TaskLayerTypes(object):
# class ModelMode(object):
# LOOKUP = "Lookup"
# DEEP_EMBEDDING = "DeepEmbedding"
# RESIDUAL = "residual"
# FC = "fc"
# SNR = "snr"
# TANH = "tanh"
# RELU = "relu"
# LRELU = "lrelu"
# SWISH = "swish"
# ELU = "elu"
# SLU = "selu"
# ELISH = "elish"
# HARD_ELISH = "hard_elish"
# SIGMOID = "sigmoid"
# HARD_SIGMOID = "hard_sigmoid"
# TANH_PEN = "tanh_pen"
# NONE = "None"
# L1 = "L1"
# L2 = "L2"
# BINARY_CLASSIFICATION = "BinaryClassification"
# REGRESSION = "Regression"
# PRAUC = "prauc"
# ROCAUC = "rocauc"
# L1 = "l1"
# ADVERSE_OUTCOME_RISK = "AdverseOutcomeRisk"
# LAB_REGRESSION = "Labs"
# BINARIZED_LOS = "BinarizedLengthOfStay"
# REGRESSION_LOS = "RegressionLengthOfStay"
# MORTALITY = "MortalityRisk"
# READMISSION = "ReadmissionRisk"
# ADVERSE_OUTCOME_RISK = "ao_risk"
# LAB_REGRESSION = "labs_regression"
# LOS = "length_of_stay"
# MORTALITY = "mortality"
# READMISSION = "readmission"
# CE = "CE"
# MULTI_CE = "MULTI_CE"
# BRIER = "Brier"
# L1 = "L1"
# L2 = "L2"
# SRU = "SRU"
# LSTM = "LSTM"
# UGRNN = "UGRNN"
# PRESENCE_SEQ = "pres_s" # Sequential presence features
# NUMERIC_SEQ = "num_s" # Sequential numerical features
# CATEGORY_COUNTS_SEQ = "count_s" # Sequential category counts features
# FEAT_TO_NAME = {
# "pres_s": "presence",
# "num_s": "numeric",
# "count_s": "category_counts",
# }
# SGD = "SGD"
# ADAM = "Adam"
# RMSPROP = "RMSprop"
# FIXED = "fixed"
# EXPONENTIAL_DECAY = "exponential_decay"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum_all"
# SUM_BY_SUFFIX = "sum_by_suffix"
# COMBINE_SNR_OUT = "combine_snr_out"
# FC = "fc"
# HIGHWAY = "highway"
# RESIDUAL = "residual"
# NONE = "None"
# BOOL = "bool"
# SCALAR_WEIGHT = "scalar_weight"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum"
# SUM_ALL = "SUM_ALL"
# UNCERTAINTY_WEIGHTED = "UNCERTAINTY_WEIGHTED"
# RNN = "RNN"
# SNRNN = "SNRNN"
# NONE = "none"
# MLP = "MLP"
# SNRMLP = "SNRMLP"
# TRAIN = "train"
# EVAL = "eval"
# PREDICT = "predict"
# def is_train(cls, mode: str) -> bool:
#
# Path: ehr_prediction_modeling/models/reset_core.py
# class ResetCore(snt.RNNCore):
# def __init__(self, core: RNNCore):
# def _build(self, input_should_reset: Tuple[tf.Tensor, tf.Tensor],
# state: tf.Tensor, **kwargs) -> Tuple[tf.Tensor, tf.Tensor]:
# def wrapped_core(self) -> RNNCore:
# def state_size(self) -> tf.TensorShape:
# def output_size(self) -> tf.TensorShape:
# def trainable_weights(self) -> List[tf.Tensor]:
# def initial_state(self, *args, **kwargs) -> List[tf.Tensor]:
. Output only the next line. | types.RNNCellType.SRU, |
Given the following code snippet before the placeholder: <|code_start|> num_units=config.ndim_lstm,
activation=config.activation_fn),
# Simple Recurrent Unit. Faster training.
types.RNNCellType.SRU:
functools.partial(
tf_contrib.rnn.SRUCell,
num_units=config.ndim_lstm,
activation=config.activation_fn),
types.RNNCellType.UGRNN:
functools.partial(
tf_contrib.rnn.UGRNNCell,
num_units=config.ndim_lstm,
activation=config.activation_fn),
}
if config.cell_type not in cell_construction_mapping:
raise ValueError(f"Invalid cell_type: {config.cell_type}")
cell = cell_construction_mapping[config.cell_type]()
if config.cell_type in cells_not_allowing_wrappers:
# Certain cells do not support wrappers.
return cell
if config.use_highway_connections:
cell = tf_contrib.rnn.HighwayWrapper(cell)
return cell
def init_deep_cell(
<|code_end|>
, predict the next line using imports from the current file:
import functools
import typing
import sonnet as snt
import tensorflow.compat.v1 as tf
from ehr_prediction_modeling import types
from ehr_prediction_modeling.models import reset_core
from tensorflow import contrib as tf_contrib
from ehr_prediction_modeling import configdict
and context including class names, function names, and sometimes code from other files:
# Path: ehr_prediction_modeling/types.py
# class ForwardFunctionReturns(
# collections.namedtuple(
# "ForwardFunctionReturns",
# ["model_output", "hidden_states", "inputs", "activations"],
# )):
# class EmbeddingType(object):
# class EmbeddingEncoderType(object):
# class ActivationFunction(object):
# class RegularizationType(object):
# class TaskType(object):
# class BestModelMetric(object):
# class TaskNames(object):
# class TaskTypes(object):
# class TaskLossType(object):
# class RNNCellType(object):
# class FeatureTypes(object):
# class Optimizers(object):
# class LearningRateScheduling(object):
# class EmbeddingCombinationMethod(object):
# class SNRBlockConnType(object):
# class SubNettoSubNetConnType(object):
# class SNRInputCombinationType(object):
# class LossCombinationType(object):
# class ModelTypes(object):
# class TaskLayerTypes(object):
# class ModelMode(object):
# LOOKUP = "Lookup"
# DEEP_EMBEDDING = "DeepEmbedding"
# RESIDUAL = "residual"
# FC = "fc"
# SNR = "snr"
# TANH = "tanh"
# RELU = "relu"
# LRELU = "lrelu"
# SWISH = "swish"
# ELU = "elu"
# SLU = "selu"
# ELISH = "elish"
# HARD_ELISH = "hard_elish"
# SIGMOID = "sigmoid"
# HARD_SIGMOID = "hard_sigmoid"
# TANH_PEN = "tanh_pen"
# NONE = "None"
# L1 = "L1"
# L2 = "L2"
# BINARY_CLASSIFICATION = "BinaryClassification"
# REGRESSION = "Regression"
# PRAUC = "prauc"
# ROCAUC = "rocauc"
# L1 = "l1"
# ADVERSE_OUTCOME_RISK = "AdverseOutcomeRisk"
# LAB_REGRESSION = "Labs"
# BINARIZED_LOS = "BinarizedLengthOfStay"
# REGRESSION_LOS = "RegressionLengthOfStay"
# MORTALITY = "MortalityRisk"
# READMISSION = "ReadmissionRisk"
# ADVERSE_OUTCOME_RISK = "ao_risk"
# LAB_REGRESSION = "labs_regression"
# LOS = "length_of_stay"
# MORTALITY = "mortality"
# READMISSION = "readmission"
# CE = "CE"
# MULTI_CE = "MULTI_CE"
# BRIER = "Brier"
# L1 = "L1"
# L2 = "L2"
# SRU = "SRU"
# LSTM = "LSTM"
# UGRNN = "UGRNN"
# PRESENCE_SEQ = "pres_s" # Sequential presence features
# NUMERIC_SEQ = "num_s" # Sequential numerical features
# CATEGORY_COUNTS_SEQ = "count_s" # Sequential category counts features
# FEAT_TO_NAME = {
# "pres_s": "presence",
# "num_s": "numeric",
# "count_s": "category_counts",
# }
# SGD = "SGD"
# ADAM = "Adam"
# RMSPROP = "RMSprop"
# FIXED = "fixed"
# EXPONENTIAL_DECAY = "exponential_decay"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum_all"
# SUM_BY_SUFFIX = "sum_by_suffix"
# COMBINE_SNR_OUT = "combine_snr_out"
# FC = "fc"
# HIGHWAY = "highway"
# RESIDUAL = "residual"
# NONE = "None"
# BOOL = "bool"
# SCALAR_WEIGHT = "scalar_weight"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum"
# SUM_ALL = "SUM_ALL"
# UNCERTAINTY_WEIGHTED = "UNCERTAINTY_WEIGHTED"
# RNN = "RNN"
# SNRNN = "SNRNN"
# NONE = "none"
# MLP = "MLP"
# SNRMLP = "SNRMLP"
# TRAIN = "train"
# EVAL = "eval"
# PREDICT = "predict"
# def is_train(cls, mode: str) -> bool:
#
# Path: ehr_prediction_modeling/models/reset_core.py
# class ResetCore(snt.RNNCore):
# def __init__(self, core: RNNCore):
# def _build(self, input_should_reset: Tuple[tf.Tensor, tf.Tensor],
# state: tf.Tensor, **kwargs) -> Tuple[tf.Tensor, tf.Tensor]:
# def wrapped_core(self) -> RNNCore:
# def state_size(self) -> tf.TensorShape:
# def output_size(self) -> tf.TensorShape:
# def trainable_weights(self) -> List[tf.Tensor]:
# def initial_state(self, *args, **kwargs) -> List[tf.Tensor]:
. Output only the next line. | cell_config: "configdict.ConfigDict") -> reset_core.ResetCore: |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2021 Google Health Research.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Defining some masks' names and utils."""
# Names of component masks available to tasks.
# Masks intervals for patient history based on labels set for censoring during
# preprocessing.
INTERVAL_MASK = "interval_mask"
# Masks entire patients based on labels set for censoring during preprocessing.
PATIENT_MASK = "patient_mask"
UNKNOWN_LOOKAHEAD_MASK = "unknown_lookahead_mask"
IGNORE_MASK = "ignore_mask"
PADDED_EVENT_MASK = "padded_event_mask"
SINCE_EVENT_TRAIN_MASK = "since_event_train_mask"
SINCE_EVENT_EVAL_MASK = "since_event_eval_mask"
<|code_end|>
, predict the next line using imports from the current file:
import re
import tensorflow.compat.v1 as tf
from typing import Dict, List, Tuple, Union
from ehr_prediction_modeling.utils import label_utils
and context including class names, function names, and sometimes code from other files:
# Path: ehr_prediction_modeling/utils/label_utils.py
# ADVERSE_OUTCOME_IN_ADMISSION = "adverse_outcome_in_admission"
# MORTALITY_IN_ADMISSION_LABEL = "mortality_in_admission"
# MORTALITY_LOOKAHEAD_LABEL_BASE = "mortality_in"
# READMISSION_LABEL_BASE = "readmission_within"
# TIME_UNTIL_NEXT_ADMISSION = "time_until_next_admission"
# SEGMENT_LABEL = "segment_mask"
# CENSORED_PATIENT_LABEL = "patient_mask"
# LAB_LOOKAHEAD_REGEX_BASE = r"lab_[0-9]+_value_within"
# LOS_LABEL = "length_of_stay"
# TIMESTAMP_KEY = "timestamp"
# TSA_LABEL = "time_since_admission"
# IGNORE_LABEL = "ignore_label"
# TOD_LABEL = "time_of_day_label"
# DISCHARGE_LABEL = "discharge_label"
# DEFAULT_LOOKAHEAD_WINDOWS = [6, 12, 18, 24, 36, 48, 60, 72]
# def get_lab_label_lookahead_key(lab_number: str,
# time_window_hours: int,
# suffix=None) -> str:
# def get_adverse_outcome_lookahead_label_key(time_window_hours: int) -> str:
# def get_readmission_label_keys(time_windows: List[int]) -> List[str]:
. Output only the next line. | AT_DISCHARGE_MASK = label_utils.DISCHARGE_LABEL |
Predict the next line for this snippet: <|code_start|># coding=utf-8
# Copyright 2021 Google Health Research.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Loss function utility to be used in tasks."""
def loss_fn(y: tf.Tensor,
targets: tf.Tensor,
loss_mask: tf.Tensor,
<|code_end|>
with the help of current file imports:
from typing import Optional
from ehr_prediction_modeling import types
import tensorflow.compat.v1 as tf
and context from other files:
# Path: ehr_prediction_modeling/types.py
# class ForwardFunctionReturns(
# collections.namedtuple(
# "ForwardFunctionReturns",
# ["model_output", "hidden_states", "inputs", "activations"],
# )):
# class EmbeddingType(object):
# class EmbeddingEncoderType(object):
# class ActivationFunction(object):
# class RegularizationType(object):
# class TaskType(object):
# class BestModelMetric(object):
# class TaskNames(object):
# class TaskTypes(object):
# class TaskLossType(object):
# class RNNCellType(object):
# class FeatureTypes(object):
# class Optimizers(object):
# class LearningRateScheduling(object):
# class EmbeddingCombinationMethod(object):
# class SNRBlockConnType(object):
# class SubNettoSubNetConnType(object):
# class SNRInputCombinationType(object):
# class LossCombinationType(object):
# class ModelTypes(object):
# class TaskLayerTypes(object):
# class ModelMode(object):
# LOOKUP = "Lookup"
# DEEP_EMBEDDING = "DeepEmbedding"
# RESIDUAL = "residual"
# FC = "fc"
# SNR = "snr"
# TANH = "tanh"
# RELU = "relu"
# LRELU = "lrelu"
# SWISH = "swish"
# ELU = "elu"
# SLU = "selu"
# ELISH = "elish"
# HARD_ELISH = "hard_elish"
# SIGMOID = "sigmoid"
# HARD_SIGMOID = "hard_sigmoid"
# TANH_PEN = "tanh_pen"
# NONE = "None"
# L1 = "L1"
# L2 = "L2"
# BINARY_CLASSIFICATION = "BinaryClassification"
# REGRESSION = "Regression"
# PRAUC = "prauc"
# ROCAUC = "rocauc"
# L1 = "l1"
# ADVERSE_OUTCOME_RISK = "AdverseOutcomeRisk"
# LAB_REGRESSION = "Labs"
# BINARIZED_LOS = "BinarizedLengthOfStay"
# REGRESSION_LOS = "RegressionLengthOfStay"
# MORTALITY = "MortalityRisk"
# READMISSION = "ReadmissionRisk"
# ADVERSE_OUTCOME_RISK = "ao_risk"
# LAB_REGRESSION = "labs_regression"
# LOS = "length_of_stay"
# MORTALITY = "mortality"
# READMISSION = "readmission"
# CE = "CE"
# MULTI_CE = "MULTI_CE"
# BRIER = "Brier"
# L1 = "L1"
# L2 = "L2"
# SRU = "SRU"
# LSTM = "LSTM"
# UGRNN = "UGRNN"
# PRESENCE_SEQ = "pres_s" # Sequential presence features
# NUMERIC_SEQ = "num_s" # Sequential numerical features
# CATEGORY_COUNTS_SEQ = "count_s" # Sequential category counts features
# FEAT_TO_NAME = {
# "pres_s": "presence",
# "num_s": "numeric",
# "count_s": "category_counts",
# }
# SGD = "SGD"
# ADAM = "Adam"
# RMSPROP = "RMSprop"
# FIXED = "fixed"
# EXPONENTIAL_DECAY = "exponential_decay"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum_all"
# SUM_BY_SUFFIX = "sum_by_suffix"
# COMBINE_SNR_OUT = "combine_snr_out"
# FC = "fc"
# HIGHWAY = "highway"
# RESIDUAL = "residual"
# NONE = "None"
# BOOL = "bool"
# SCALAR_WEIGHT = "scalar_weight"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum"
# SUM_ALL = "SUM_ALL"
# UNCERTAINTY_WEIGHTED = "UNCERTAINTY_WEIGHTED"
# RNN = "RNN"
# SNRNN = "SNRNN"
# NONE = "none"
# MLP = "MLP"
# SNRMLP = "SNRMLP"
# TRAIN = "train"
# EVAL = "eval"
# PREDICT = "predict"
# def is_train(cls, mode: str) -> bool:
, which may contain function names, class names, or code. Output only the next line. | loss_type: str = types.TaskLossType.CE, |
Next line prediction: <|code_start|># coding=utf-8
# Copyright 2021 Google Health Research.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""TensorFlow utility functions to extract Tensor and batch from tf protos."""
class BatchGenerator(object):
"""Tool for working with a TF dataset."""
def __init__(
self,
config: configdict.ConfigDict,
is_training: bool,
<|code_end|>
. Use current file imports:
(import os
import tensorflow.compat.v1 as tf
from typing import List, Optional
from absl import logging
from ehr_prediction_modeling.data import tf_dataset_utils
from ehr_prediction_modeling.tasks import coordinator
from ehr_prediction_modeling.utils import batches
from ehr_prediction_modeling import configdict)
and context including class names, function names, or small code snippets from other files:
# Path: ehr_prediction_modeling/data/tf_dataset_utils.py
# def sample_segments(
# seq_lens: tf.Tensor,
# segment_length: tf.Tensor,
# random_offset: bool,
# ) -> tf.Tensor:
# def flatten(x):
# def slice_tensor(
# tensor: tf.Tensor,
# seq_starts: tf.Tensor,
# segment_length: int,
# ) -> tf.Tensor:
# def loop_body(i, ta):
# def slice_sparse_tensor_sequences(
# tensor: tf.SparseTensor,
# seq_starts: tf.Tensor,
# segment_length: int,
# ) -> tf.SparseTensor:
# def slice_sparse_tensor_context(tensor: tf.SparseTensor,
# seq_starts: tf.Tensor) -> tf.SparseTensor:
# def convert_to_segments(
# examples: SeqexDictType,
# segment_len: int,
# ) -> SeqexDictType:
# def read_seqex_dataset(tfrecords_filename: str) -> tf.data.TFRecordDataset:
# def tile_context(
# ctx: Dict[str, tf.Tensor],
# seq_len: int,
# batch_padding: Optional[int] = None,
# ) -> Dict[str, tf.Tensor]:
# def add_beginning_of_sequence_mask_and_pad(
# example: SeqexDictType,
# batch_size: int,
# num_unroll: int,
# ) -> tf.data.Dataset:
# def seqex_to_dict(
# serialized_examples: bytes,
# context_d: Dict[str, str],
# sequence_d: Dict[str, str],
# ) -> SeqexDictType:
# def get_label_dicts(
# task_coordinator: coordinator.Coordinator,
# context_features: List[str],
# sequential_features: List[str],
# ) -> Tuple[Dict[str, Union[tf.FixedLenSequenceFeature, tf.FixedLenFeature]],
# def to_time_major(tensor: tf.Tensor) -> tf.Tensor:
# def _transpose(value, dimension):
# def sparse_tensor_to_time_major(
# sparse_tensor: tf.SparseTensor) -> tf.SparseTensor:
# def convert_to_time_major(examples: SeqexDictType) -> SeqexDictType:
#
# Path: ehr_prediction_modeling/tasks/coordinator.py
# class Coordinator():
# def __init__(self, task_list: List[base_task.Task],
# optimizer_config: configdict.ConfigDict):
# def num_targets_list(self) -> List[int]:
# def task_list(self) -> List[base_task.Task]:
# def task_names(self) -> List[str]:
# def target_names_list(self) -> List[str]:
# def task_prediction_types(self) -> List[str]:
# def task_eval_masks_list(self) -> List[List[str]]:
# def task_layers(self) -> Mapping[str, Any]:
# def get_task_layers_variables(self) -> Sequence[tf.Variable]:
# def get_coordinator_variables(
# self, batch: batches.TFBatch,
# model_output: Union[tf.Tensor, None]) -> task_data.CoordinatorVariables:
# def get_task_regularization_losses(self) -> tf.Tensor:
# def _get_task_variables_and_loss(
# self, batch: batches.TFBatch,
# model_output: tf.Tensor) -> task_data.CoordinatorVariables:
# def _get_task_variables(
# self, batch: batches.TFBatch) -> task_data.CoordinatorVariables:
# def get_label_dicts(
# self
# ) -> Tuple[Dict[str, Union[tf.FixedLenSequenceFeature, tf.FixedLenFeature]],
#
# Path: ehr_prediction_modeling/utils/batches.py
# def batch_to_components(
# batch: TFBatch,
# context_features: List[str],
# sequential_features: List[str],
# ) -> Dict[str, tf.Tensor]:
# def _batch_to_components(
# batch: TFBatch,
# context_features: List[str],
# sequential_features: List[str],
# ) -> Dict[str, tf.Tensor]:
# def _extract_features(
# batch_field: Dict[str, tf.Tensor],
# features: List[str],
# outp_prefix: str,
# inp_prefix: str,
# ) -> Dict[str, tf.Tensor]:
# def flatten_batch(val: tf.Tensor) -> tf.Tensor:
# def get_unflatten_batch_fn(
# batch_shape: tf.Tensor) -> Callable[[tf.Tensor], tf.Tensor]:
# def unflatten_batch(val):
# def sparse_fill_empty_rows(
# val: Union[tf.Tensor,
# tf.SparseTensor]) -> Union[tf.Tensor, tf.SparseTensor]:
#
# Path: ehr_prediction_modeling/configdict.py
# class ConfigDict(dict):
# def __init__(self, config=None, **kwargs): # pylint: disable=super-init-not-called
# def __setattr__(self, key, value):
# def __getitem__(self, key):
# def update(self, config=None, **f):
# def get(self, key, default=None):
. Output only the next line. | task_coordinator: Optional[coordinator.Coordinator], |
Given snippet: <|code_start|>
# Lint as: python3
"""TensorFlow utility functions to extract Tensor and batch from tf protos."""
class BatchGenerator(object):
"""Tool for working with a TF dataset."""
def __init__(
self,
config: configdict.ConfigDict,
is_training: bool,
task_coordinator: Optional[coordinator.Coordinator],
data_split_name: str,
):
self._config = config
self._is_training = is_training
self._task_coordinator = task_coordinator
self._split_name = data_split_name
self._iterator = None # Initialized in create_batch.
self._batch = self._create_batch()
@property
def iterator(self) -> tf.data.Iterator:
return self._iterator
@property
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import tensorflow.compat.v1 as tf
from typing import List, Optional
from absl import logging
from ehr_prediction_modeling.data import tf_dataset_utils
from ehr_prediction_modeling.tasks import coordinator
from ehr_prediction_modeling.utils import batches
from ehr_prediction_modeling import configdict
and context:
# Path: ehr_prediction_modeling/data/tf_dataset_utils.py
# def sample_segments(
# seq_lens: tf.Tensor,
# segment_length: tf.Tensor,
# random_offset: bool,
# ) -> tf.Tensor:
# def flatten(x):
# def slice_tensor(
# tensor: tf.Tensor,
# seq_starts: tf.Tensor,
# segment_length: int,
# ) -> tf.Tensor:
# def loop_body(i, ta):
# def slice_sparse_tensor_sequences(
# tensor: tf.SparseTensor,
# seq_starts: tf.Tensor,
# segment_length: int,
# ) -> tf.SparseTensor:
# def slice_sparse_tensor_context(tensor: tf.SparseTensor,
# seq_starts: tf.Tensor) -> tf.SparseTensor:
# def convert_to_segments(
# examples: SeqexDictType,
# segment_len: int,
# ) -> SeqexDictType:
# def read_seqex_dataset(tfrecords_filename: str) -> tf.data.TFRecordDataset:
# def tile_context(
# ctx: Dict[str, tf.Tensor],
# seq_len: int,
# batch_padding: Optional[int] = None,
# ) -> Dict[str, tf.Tensor]:
# def add_beginning_of_sequence_mask_and_pad(
# example: SeqexDictType,
# batch_size: int,
# num_unroll: int,
# ) -> tf.data.Dataset:
# def seqex_to_dict(
# serialized_examples: bytes,
# context_d: Dict[str, str],
# sequence_d: Dict[str, str],
# ) -> SeqexDictType:
# def get_label_dicts(
# task_coordinator: coordinator.Coordinator,
# context_features: List[str],
# sequential_features: List[str],
# ) -> Tuple[Dict[str, Union[tf.FixedLenSequenceFeature, tf.FixedLenFeature]],
# def to_time_major(tensor: tf.Tensor) -> tf.Tensor:
# def _transpose(value, dimension):
# def sparse_tensor_to_time_major(
# sparse_tensor: tf.SparseTensor) -> tf.SparseTensor:
# def convert_to_time_major(examples: SeqexDictType) -> SeqexDictType:
#
# Path: ehr_prediction_modeling/tasks/coordinator.py
# class Coordinator():
# def __init__(self, task_list: List[base_task.Task],
# optimizer_config: configdict.ConfigDict):
# def num_targets_list(self) -> List[int]:
# def task_list(self) -> List[base_task.Task]:
# def task_names(self) -> List[str]:
# def target_names_list(self) -> List[str]:
# def task_prediction_types(self) -> List[str]:
# def task_eval_masks_list(self) -> List[List[str]]:
# def task_layers(self) -> Mapping[str, Any]:
# def get_task_layers_variables(self) -> Sequence[tf.Variable]:
# def get_coordinator_variables(
# self, batch: batches.TFBatch,
# model_output: Union[tf.Tensor, None]) -> task_data.CoordinatorVariables:
# def get_task_regularization_losses(self) -> tf.Tensor:
# def _get_task_variables_and_loss(
# self, batch: batches.TFBatch,
# model_output: tf.Tensor) -> task_data.CoordinatorVariables:
# def _get_task_variables(
# self, batch: batches.TFBatch) -> task_data.CoordinatorVariables:
# def get_label_dicts(
# self
# ) -> Tuple[Dict[str, Union[tf.FixedLenSequenceFeature, tf.FixedLenFeature]],
#
# Path: ehr_prediction_modeling/utils/batches.py
# def batch_to_components(
# batch: TFBatch,
# context_features: List[str],
# sequential_features: List[str],
# ) -> Dict[str, tf.Tensor]:
# def _batch_to_components(
# batch: TFBatch,
# context_features: List[str],
# sequential_features: List[str],
# ) -> Dict[str, tf.Tensor]:
# def _extract_features(
# batch_field: Dict[str, tf.Tensor],
# features: List[str],
# outp_prefix: str,
# inp_prefix: str,
# ) -> Dict[str, tf.Tensor]:
# def flatten_batch(val: tf.Tensor) -> tf.Tensor:
# def get_unflatten_batch_fn(
# batch_shape: tf.Tensor) -> Callable[[tf.Tensor], tf.Tensor]:
# def unflatten_batch(val):
# def sparse_fill_empty_rows(
# val: Union[tf.Tensor,
# tf.SparseTensor]) -> Union[tf.Tensor, tf.SparseTensor]:
#
# Path: ehr_prediction_modeling/configdict.py
# class ConfigDict(dict):
# def __init__(self, config=None, **kwargs): # pylint: disable=super-init-not-called
# def __setattr__(self, key, value):
# def __getitem__(self, key):
# def update(self, config=None, **f):
# def get(self, key, default=None):
which might include code, classes, or functions. Output only the next line. | def batch(self) -> batches.TFBatch: |
Here is a snippet: <|code_start|># coding=utf-8
# Copyright 2021 Google Health Research.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""TensorFlow utility functions to extract Tensor and batch from tf protos."""
class BatchGenerator(object):
"""Tool for working with a TF dataset."""
def __init__(
self,
<|code_end|>
. Write the next line using the current file imports:
import os
import tensorflow.compat.v1 as tf
from typing import List, Optional
from absl import logging
from ehr_prediction_modeling.data import tf_dataset_utils
from ehr_prediction_modeling.tasks import coordinator
from ehr_prediction_modeling.utils import batches
from ehr_prediction_modeling import configdict
and context from other files:
# Path: ehr_prediction_modeling/data/tf_dataset_utils.py
# def sample_segments(
# seq_lens: tf.Tensor,
# segment_length: tf.Tensor,
# random_offset: bool,
# ) -> tf.Tensor:
# def flatten(x):
# def slice_tensor(
# tensor: tf.Tensor,
# seq_starts: tf.Tensor,
# segment_length: int,
# ) -> tf.Tensor:
# def loop_body(i, ta):
# def slice_sparse_tensor_sequences(
# tensor: tf.SparseTensor,
# seq_starts: tf.Tensor,
# segment_length: int,
# ) -> tf.SparseTensor:
# def slice_sparse_tensor_context(tensor: tf.SparseTensor,
# seq_starts: tf.Tensor) -> tf.SparseTensor:
# def convert_to_segments(
# examples: SeqexDictType,
# segment_len: int,
# ) -> SeqexDictType:
# def read_seqex_dataset(tfrecords_filename: str) -> tf.data.TFRecordDataset:
# def tile_context(
# ctx: Dict[str, tf.Tensor],
# seq_len: int,
# batch_padding: Optional[int] = None,
# ) -> Dict[str, tf.Tensor]:
# def add_beginning_of_sequence_mask_and_pad(
# example: SeqexDictType,
# batch_size: int,
# num_unroll: int,
# ) -> tf.data.Dataset:
# def seqex_to_dict(
# serialized_examples: bytes,
# context_d: Dict[str, str],
# sequence_d: Dict[str, str],
# ) -> SeqexDictType:
# def get_label_dicts(
# task_coordinator: coordinator.Coordinator,
# context_features: List[str],
# sequential_features: List[str],
# ) -> Tuple[Dict[str, Union[tf.FixedLenSequenceFeature, tf.FixedLenFeature]],
# def to_time_major(tensor: tf.Tensor) -> tf.Tensor:
# def _transpose(value, dimension):
# def sparse_tensor_to_time_major(
# sparse_tensor: tf.SparseTensor) -> tf.SparseTensor:
# def convert_to_time_major(examples: SeqexDictType) -> SeqexDictType:
#
# Path: ehr_prediction_modeling/tasks/coordinator.py
# class Coordinator():
# def __init__(self, task_list: List[base_task.Task],
# optimizer_config: configdict.ConfigDict):
# def num_targets_list(self) -> List[int]:
# def task_list(self) -> List[base_task.Task]:
# def task_names(self) -> List[str]:
# def target_names_list(self) -> List[str]:
# def task_prediction_types(self) -> List[str]:
# def task_eval_masks_list(self) -> List[List[str]]:
# def task_layers(self) -> Mapping[str, Any]:
# def get_task_layers_variables(self) -> Sequence[tf.Variable]:
# def get_coordinator_variables(
# self, batch: batches.TFBatch,
# model_output: Union[tf.Tensor, None]) -> task_data.CoordinatorVariables:
# def get_task_regularization_losses(self) -> tf.Tensor:
# def _get_task_variables_and_loss(
# self, batch: batches.TFBatch,
# model_output: tf.Tensor) -> task_data.CoordinatorVariables:
# def _get_task_variables(
# self, batch: batches.TFBatch) -> task_data.CoordinatorVariables:
# def get_label_dicts(
# self
# ) -> Tuple[Dict[str, Union[tf.FixedLenSequenceFeature, tf.FixedLenFeature]],
#
# Path: ehr_prediction_modeling/utils/batches.py
# def batch_to_components(
# batch: TFBatch,
# context_features: List[str],
# sequential_features: List[str],
# ) -> Dict[str, tf.Tensor]:
# def _batch_to_components(
# batch: TFBatch,
# context_features: List[str],
# sequential_features: List[str],
# ) -> Dict[str, tf.Tensor]:
# def _extract_features(
# batch_field: Dict[str, tf.Tensor],
# features: List[str],
# outp_prefix: str,
# inp_prefix: str,
# ) -> Dict[str, tf.Tensor]:
# def flatten_batch(val: tf.Tensor) -> tf.Tensor:
# def get_unflatten_batch_fn(
# batch_shape: tf.Tensor) -> Callable[[tf.Tensor], tf.Tensor]:
# def unflatten_batch(val):
# def sparse_fill_empty_rows(
# val: Union[tf.Tensor,
# tf.SparseTensor]) -> Union[tf.Tensor, tf.SparseTensor]:
#
# Path: ehr_prediction_modeling/configdict.py
# class ConfigDict(dict):
# def __init__(self, config=None, **kwargs): # pylint: disable=super-init-not-called
# def __setattr__(self, key, value):
# def __getitem__(self, key):
# def update(self, config=None, **f):
# def get(self, key, default=None):
, which may include functions, classes, or code. Output only the next line. | config: configdict.ConfigDict, |
Given the following code snippet before the placeholder: <|code_start|># You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Utilities for model and encoders."""
if typing.TYPE_CHECKING:
def get_regularizer(
regularizer_type: str, l_reg_factor_weight: float
) -> Optional[Callable[[tf.Tensor], Optional[tf.Tensor]]]:
"""Gets a regularizer of a given type and scale.
Args:
regularizer_type: One of types.RegularizationType
l_reg_factor_weight: Scale for regularization.
Returns:
A function with weights parameter that applies regularization.
"""
<|code_end|>
, predict the next line using imports from the current file:
import collections
import typing
import tensorflow.compat.v1 as tf
import tf_slim as slim
import tree as nest
from typing import Callable, Dict, List, Optional, Union
from absl import logging
from ehr_prediction_modeling import types
from ehr_prediction_modeling import configdict
and context including class names, function names, and sometimes code from other files:
# Path: ehr_prediction_modeling/types.py
# class ForwardFunctionReturns(
# collections.namedtuple(
# "ForwardFunctionReturns",
# ["model_output", "hidden_states", "inputs", "activations"],
# )):
# class EmbeddingType(object):
# class EmbeddingEncoderType(object):
# class ActivationFunction(object):
# class RegularizationType(object):
# class TaskType(object):
# class BestModelMetric(object):
# class TaskNames(object):
# class TaskTypes(object):
# class TaskLossType(object):
# class RNNCellType(object):
# class FeatureTypes(object):
# class Optimizers(object):
# class LearningRateScheduling(object):
# class EmbeddingCombinationMethod(object):
# class SNRBlockConnType(object):
# class SubNettoSubNetConnType(object):
# class SNRInputCombinationType(object):
# class LossCombinationType(object):
# class ModelTypes(object):
# class TaskLayerTypes(object):
# class ModelMode(object):
# LOOKUP = "Lookup"
# DEEP_EMBEDDING = "DeepEmbedding"
# RESIDUAL = "residual"
# FC = "fc"
# SNR = "snr"
# TANH = "tanh"
# RELU = "relu"
# LRELU = "lrelu"
# SWISH = "swish"
# ELU = "elu"
# SLU = "selu"
# ELISH = "elish"
# HARD_ELISH = "hard_elish"
# SIGMOID = "sigmoid"
# HARD_SIGMOID = "hard_sigmoid"
# TANH_PEN = "tanh_pen"
# NONE = "None"
# L1 = "L1"
# L2 = "L2"
# BINARY_CLASSIFICATION = "BinaryClassification"
# REGRESSION = "Regression"
# PRAUC = "prauc"
# ROCAUC = "rocauc"
# L1 = "l1"
# ADVERSE_OUTCOME_RISK = "AdverseOutcomeRisk"
# LAB_REGRESSION = "Labs"
# BINARIZED_LOS = "BinarizedLengthOfStay"
# REGRESSION_LOS = "RegressionLengthOfStay"
# MORTALITY = "MortalityRisk"
# READMISSION = "ReadmissionRisk"
# ADVERSE_OUTCOME_RISK = "ao_risk"
# LAB_REGRESSION = "labs_regression"
# LOS = "length_of_stay"
# MORTALITY = "mortality"
# READMISSION = "readmission"
# CE = "CE"
# MULTI_CE = "MULTI_CE"
# BRIER = "Brier"
# L1 = "L1"
# L2 = "L2"
# SRU = "SRU"
# LSTM = "LSTM"
# UGRNN = "UGRNN"
# PRESENCE_SEQ = "pres_s" # Sequential presence features
# NUMERIC_SEQ = "num_s" # Sequential numerical features
# CATEGORY_COUNTS_SEQ = "count_s" # Sequential category counts features
# FEAT_TO_NAME = {
# "pres_s": "presence",
# "num_s": "numeric",
# "count_s": "category_counts",
# }
# SGD = "SGD"
# ADAM = "Adam"
# RMSPROP = "RMSprop"
# FIXED = "fixed"
# EXPONENTIAL_DECAY = "exponential_decay"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum_all"
# SUM_BY_SUFFIX = "sum_by_suffix"
# COMBINE_SNR_OUT = "combine_snr_out"
# FC = "fc"
# HIGHWAY = "highway"
# RESIDUAL = "residual"
# NONE = "None"
# BOOL = "bool"
# SCALAR_WEIGHT = "scalar_weight"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum"
# SUM_ALL = "SUM_ALL"
# UNCERTAINTY_WEIGHTED = "UNCERTAINTY_WEIGHTED"
# RNN = "RNN"
# SNRNN = "SNRNN"
# NONE = "none"
# MLP = "MLP"
# SNRMLP = "SNRMLP"
# TRAIN = "train"
# EVAL = "eval"
# PREDICT = "predict"
# def is_train(cls, mode: str) -> bool:
. Output only the next line. | if regularizer_type == types.RegularizationType.NONE: |
Based on the snippet: <|code_start|>def get_task_specific_snr_routing_connections(model, encoder, losses_per_task):
"""Returns the task-specific SNR connections.
If use_task_specific_routing is disabled in both the model and the encoder
it will return an (empty dictionary, empty list) tuple.
For sub-network routing when optimizing task specific connections we
want to optimize each corresponding to the specific task loss they're
associated with.
If the model type is not SNRNN and the encoder type is not SNR then this
function will return empty collections.
Args:
model: The instantiated model. Must be an SNRNN in order to have
any connections returned.
encoder: The instantiated encoder. Must have SNREncoders associated
with the embedding in order to have any connections returned.
losses_per_task: A dictionary from task name to associated total loss for
that task.
Returns:
A tuple where the first element is a dictionary from a task specific loss
to a variable list that will be optimized wrt to it, and the second element
is a set of all the routing connections in the architecture.
"""
loss_to_vars = {}
routing_connections_for_task = collections.defaultdict(set)
# In some cases the model is wrapped in an RNNModelWithPersistentState
# class.
<|code_end|>
, predict the immediate next line with the help of imports:
import collections
import itertools
from absl import logging
from ehr_prediction_modeling.models import snrnn_model
from ehr_prediction_modeling.models.nets import deep_encoders
and context (classes, functions, sometimes code) from other files:
# Path: ehr_prediction_modeling/models/snrnn_model.py
# class SNRNNModel(rnn_model.BaseRNNModel):
# def __init__(self, config: configdict.ConfigDict, tasks: List[Text],
# embedding_size: int) -> None:
# def input_size_fn(self, layer_i: int,
# use_task_specific_routing: bool) -> Union[int, None]:
# def _compute_input_size_for_list(inputs):
# def _init_rnn(self) -> None:
# def initial_state(
# self,
# batch_size: int,
# dtype: tf.dtypes.DType = tf.float32) -> List[List[tf.Tensor]]:
# def _build(
# self, features: tf.Tensor, beginning_of_sequence_mask: tf.Tensor,
# t_vect: tf.Tensor,
# prev_states: List[List[tf.Tensor]]) -> types.ForwardFunctionReturns:
# def _get_snr_connections(self) -> List[tf.Variable]:
# def _get_variables_for_regularization(self) -> List[tf.Variable]:
# def get_task_routing_connections(self) -> Dict[str, List[tf.Variable]]:
# def get_snr_regularization_loss(self) -> tf.Tensor:
# def get_model_regularization_loss(self) -> tf.Tensor:
#
# Path: ehr_prediction_modeling/models/nets/deep_encoders.py
# class FullyConnectedEncoder(encoder_base.DeepEncoderBase):
# class ResidualEncoder(encoder_base.DeepEncoderBase):
# class SNREncoder(encoder_base.DeepEncoderBase):
# def _build(
# self,
# input_data: encoder_base.EncoderInput,
# context: encoder_base.EncoderContext = None
# ) -> tf.Tensor:
# def _build(
# self,
# input_data: encoder_base.EncoderInput,
# context: encoder_base.EncoderContext = None
# ) -> tf.Tensor:
# def __init__(self, *args, **kwargs):
# def embed_out(self) -> int:
# def initial_embed_size(self) -> int:
# def _tasks(self) -> List[str]:
# def get_task_routing_connections(self):
# def get_regularization_penalty(self) -> tf.Tensor:
# def _build(
# self,
# input_data: encoder_base.EncoderInput,
# context: encoder_base.EncoderContext = None
# ) -> tf.Tensor:
# def get_snr_embed_out_size(config, feat):
# def _snr_embed_out_skip(feat_layer_size):
# def get_snr_embedding_dim_dict(config):
# def compute_combined_snr_embedding(embedding_dict):
# def get_encoder(encoder_type: str) -> Type[encoder_base.DeepEncoderTypes]:
. Output only the next line. | if (isinstance(model, snrnn_model.SNRNNModel) or |
Given snippet: <|code_start|>
For sub-network routing when optimizing task specific connections we
want to optimize each corresponding to the specific task loss they're
associated with.
If the model type is not SNRNN and the encoder type is not SNR then this
function will return empty collections.
Args:
model: The instantiated model. Must be an SNRNN in order to have
any connections returned.
encoder: The instantiated encoder. Must have SNREncoders associated
with the embedding in order to have any connections returned.
losses_per_task: A dictionary from task name to associated total loss for
that task.
Returns:
A tuple where the first element is a dictionary from a task specific loss
to a variable list that will be optimized wrt to it, and the second element
is a set of all the routing connections in the architecture.
"""
loss_to_vars = {}
routing_connections_for_task = collections.defaultdict(set)
# In some cases the model is wrapped in an RNNModelWithPersistentState
# class.
if (isinstance(model, snrnn_model.SNRNNModel) or
isinstance(model.get_model, snrnn_model.SNRNNModel)):
for task, conn in model.get_task_routing_connections().items():
routing_connections_for_task[task].update(conn)
for enc in encoder.embedding.get_encoders().values():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import collections
import itertools
from absl import logging
from ehr_prediction_modeling.models import snrnn_model
from ehr_prediction_modeling.models.nets import deep_encoders
and context:
# Path: ehr_prediction_modeling/models/snrnn_model.py
# class SNRNNModel(rnn_model.BaseRNNModel):
# def __init__(self, config: configdict.ConfigDict, tasks: List[Text],
# embedding_size: int) -> None:
# def input_size_fn(self, layer_i: int,
# use_task_specific_routing: bool) -> Union[int, None]:
# def _compute_input_size_for_list(inputs):
# def _init_rnn(self) -> None:
# def initial_state(
# self,
# batch_size: int,
# dtype: tf.dtypes.DType = tf.float32) -> List[List[tf.Tensor]]:
# def _build(
# self, features: tf.Tensor, beginning_of_sequence_mask: tf.Tensor,
# t_vect: tf.Tensor,
# prev_states: List[List[tf.Tensor]]) -> types.ForwardFunctionReturns:
# def _get_snr_connections(self) -> List[tf.Variable]:
# def _get_variables_for_regularization(self) -> List[tf.Variable]:
# def get_task_routing_connections(self) -> Dict[str, List[tf.Variable]]:
# def get_snr_regularization_loss(self) -> tf.Tensor:
# def get_model_regularization_loss(self) -> tf.Tensor:
#
# Path: ehr_prediction_modeling/models/nets/deep_encoders.py
# class FullyConnectedEncoder(encoder_base.DeepEncoderBase):
# class ResidualEncoder(encoder_base.DeepEncoderBase):
# class SNREncoder(encoder_base.DeepEncoderBase):
# def _build(
# self,
# input_data: encoder_base.EncoderInput,
# context: encoder_base.EncoderContext = None
# ) -> tf.Tensor:
# def _build(
# self,
# input_data: encoder_base.EncoderInput,
# context: encoder_base.EncoderContext = None
# ) -> tf.Tensor:
# def __init__(self, *args, **kwargs):
# def embed_out(self) -> int:
# def initial_embed_size(self) -> int:
# def _tasks(self) -> List[str]:
# def get_task_routing_connections(self):
# def get_regularization_penalty(self) -> tf.Tensor:
# def _build(
# self,
# input_data: encoder_base.EncoderInput,
# context: encoder_base.EncoderContext = None
# ) -> tf.Tensor:
# def get_snr_embed_out_size(config, feat):
# def _snr_embed_out_skip(feat_layer_size):
# def get_snr_embedding_dim_dict(config):
# def compute_combined_snr_embedding(embedding_dict):
# def get_encoder(encoder_type: str) -> Type[encoder_base.DeepEncoderTypes]:
which might include code, classes, or functions. Output only the next line. | if isinstance(enc, deep_encoders.SNREncoder): |
Continue the code snippet: <|code_start|>
# Lint as: python3
"""Coordinator for metrics of various targets in evaluation."""
@dataclasses.dataclass(frozen=True)
class MetricsTarget(object):
"""Describes a target metrics will be computed for."""
target_name: str
split_name: str
mask_name: Optional[str] = None
def to_string(self) -> str:
"""Returns a string description of this target."""
return (f"Target: {self.target_name}, Split: {self.split_name}, Mask: "
f"{self.mask_name}")
class MetricsCoordinator(object):
"""Base class for accumulating data used to calculate metrics."""
def __init__(self):
"""Initializes metrics coordinator."""
self._data_dict = {}
def add_data(self,
<|code_end|>
. Use current file imports:
import collections
import os
import dataclasses
import numpy as np
import tensorflow.compat.v1 as tf
from typing import List, Mapping, Optional, Tuple, Type
from absl import logging
from ehr_prediction_modeling.eval import metrics_data
and context (classes, functions, or code) from other files:
# Path: ehr_prediction_modeling/eval/metrics_data.py
# MAX_METRICS_KEY_LENGTH = 64
# class MetricsData():
# class BinaryMetricsData(MetricsData):
# class RegressionMetricsData(MetricsData):
# def get_metrics(self) -> Mapping[str, Any]:
# def add_data(self):
# def log_metrics(self, target_name: str, current_step: int) -> None:
# def __init__(
# self,
# positive_predictions: Optional[List[float]] = None,
# negative_predictions: Optional[List[float]] = None,
# positive_weights: Optional[List[float]] = None,
# negative_weights: Optional[List[float]] = None):
# def __eq__(self, other):
# def __str__(self):
# def add_data(self, positive_predictions, negative_predictions,
# positive_weights, negative_weights):
# def get_metrics(self) -> Mapping[str, Any]:
# def __init__(
# self,
# predictions: Optional[List[float]] = None,
# targets: Optional[List[float]] = None,
# weights: Optional[List[float]] = None) -> None:
# def __eq__(self, other):
# def __str__(self):
# def add_data(self, predictions, targets, weights):
# def get_metrics(self) -> Mapping[str, Any]:
. Output only the next line. | metrics_data_type: Type[metrics_data.MetricsTypes], |
Given the following code snippet before the placeholder: <|code_start|> embedding_size: Union[int, List[int]], name: str):
"""Initializes the parameters of the model.
Args:
config: Configuration specifying model parameters.
embedding_size: The total size of the embedding.
name: The name of the model
"""
super().__init__(name=name)
self._config = config
self._embedding_size = embedding_size
@abc.abstractmethod
def _build(self, features: tf.Tensor) -> tf.Tensor:
"""Runs a forward pass through the model.
Args:
features: Tensor of shape [num_unroll, batch_size, embedding_size].
Returns:
Tensor of shape [num_unroll, batch_size, ndim_model_output].
"""
@abc.abstractmethod
def get_model_regularization_loss(self) -> tf.Tensor:
"""Gets the regularization loss for model weights."""
@property
def mode(self) -> str:
"""One of types.ModelMode."""
<|code_end|>
, predict the next line using imports from the current file:
import abc
import typing
import sonnet as snt
import tensorflow.compat.v1 as tf
from typing import List, Optional, Union
from ehr_prediction_modeling import types
from ehr_prediction_modeling import configdict
and context including class names, function names, and sometimes code from other files:
# Path: ehr_prediction_modeling/types.py
# class ForwardFunctionReturns(
# collections.namedtuple(
# "ForwardFunctionReturns",
# ["model_output", "hidden_states", "inputs", "activations"],
# )):
# class EmbeddingType(object):
# class EmbeddingEncoderType(object):
# class ActivationFunction(object):
# class RegularizationType(object):
# class TaskType(object):
# class BestModelMetric(object):
# class TaskNames(object):
# class TaskTypes(object):
# class TaskLossType(object):
# class RNNCellType(object):
# class FeatureTypes(object):
# class Optimizers(object):
# class LearningRateScheduling(object):
# class EmbeddingCombinationMethod(object):
# class SNRBlockConnType(object):
# class SubNettoSubNetConnType(object):
# class SNRInputCombinationType(object):
# class LossCombinationType(object):
# class ModelTypes(object):
# class TaskLayerTypes(object):
# class ModelMode(object):
# LOOKUP = "Lookup"
# DEEP_EMBEDDING = "DeepEmbedding"
# RESIDUAL = "residual"
# FC = "fc"
# SNR = "snr"
# TANH = "tanh"
# RELU = "relu"
# LRELU = "lrelu"
# SWISH = "swish"
# ELU = "elu"
# SLU = "selu"
# ELISH = "elish"
# HARD_ELISH = "hard_elish"
# SIGMOID = "sigmoid"
# HARD_SIGMOID = "hard_sigmoid"
# TANH_PEN = "tanh_pen"
# NONE = "None"
# L1 = "L1"
# L2 = "L2"
# BINARY_CLASSIFICATION = "BinaryClassification"
# REGRESSION = "Regression"
# PRAUC = "prauc"
# ROCAUC = "rocauc"
# L1 = "l1"
# ADVERSE_OUTCOME_RISK = "AdverseOutcomeRisk"
# LAB_REGRESSION = "Labs"
# BINARIZED_LOS = "BinarizedLengthOfStay"
# REGRESSION_LOS = "RegressionLengthOfStay"
# MORTALITY = "MortalityRisk"
# READMISSION = "ReadmissionRisk"
# ADVERSE_OUTCOME_RISK = "ao_risk"
# LAB_REGRESSION = "labs_regression"
# LOS = "length_of_stay"
# MORTALITY = "mortality"
# READMISSION = "readmission"
# CE = "CE"
# MULTI_CE = "MULTI_CE"
# BRIER = "Brier"
# L1 = "L1"
# L2 = "L2"
# SRU = "SRU"
# LSTM = "LSTM"
# UGRNN = "UGRNN"
# PRESENCE_SEQ = "pres_s" # Sequential presence features
# NUMERIC_SEQ = "num_s" # Sequential numerical features
# CATEGORY_COUNTS_SEQ = "count_s" # Sequential category counts features
# FEAT_TO_NAME = {
# "pres_s": "presence",
# "num_s": "numeric",
# "count_s": "category_counts",
# }
# SGD = "SGD"
# ADAM = "Adam"
# RMSPROP = "RMSprop"
# FIXED = "fixed"
# EXPONENTIAL_DECAY = "exponential_decay"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum_all"
# SUM_BY_SUFFIX = "sum_by_suffix"
# COMBINE_SNR_OUT = "combine_snr_out"
# FC = "fc"
# HIGHWAY = "highway"
# RESIDUAL = "residual"
# NONE = "None"
# BOOL = "bool"
# SCALAR_WEIGHT = "scalar_weight"
# CONCATENATE = "concatenate"
# SUM_ALL = "sum"
# SUM_ALL = "SUM_ALL"
# UNCERTAINTY_WEIGHTED = "UNCERTAINTY_WEIGHTED"
# RNN = "RNN"
# SNRNN = "SNRNN"
# NONE = "none"
# MLP = "MLP"
# SNRMLP = "SNRMLP"
# TRAIN = "train"
# EVAL = "eval"
# PREDICT = "predict"
# def is_train(cls, mode: str) -> bool:
. Output only the next line. | return self._config.get("mode", types.ModelMode.TRAIN) |
Based on the snippet: <|code_start|>
class SearchEventForm(forms.Form):
countries._countries.append(Event.CUSTOM_COUNTRY_ENTRIES[0])
countries._countries.append(Event.CUSTOM_COUNTRY_ENTRIES[1])
# XK is temp code for Kosovo; remove from COUNTRIES_OVERRIDE when
# Kosovo gets its own ISO code and is added to django-countries
if not 'Kosovo' in list(dict(countries._countries).values()):
countries._countries.append((u'XK', u'Kosovo'))
q = forms.CharField(
required=False,
widget=forms.TextInput(
attrs={
'placeholder': 'Search for event name or tag',
'class': 'form-control'}))
past = forms.ChoiceField(
label='Include past events',
required=False,
choices=(('yes', 'yes'), ('no', 'no')),
widget=forms.RadioSelect(attrs={'class': 'search-form-element'}),
)
country = forms.ChoiceField(
label='Select country',
required=False,
widget=forms.Select(attrs={'class': 'search-form-element'}),
choices=countries
)
theme = forms.ModelMultipleChoiceField(
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from django_countries.fields import countries
from api.models import Event
from api.models.events import EventTheme, EventAudience
and context (classes, functions, sometimes code) from other files:
# Path: api/models/events.py
# class EventTheme(models.Model):
# name = models.CharField(max_length=255)
# order = models.IntegerField(default=0)
#
# def __unicode__(self):
# return self.name
#
# class Meta:
# app_label = 'api'
# ordering = ['order', 'name']
#
# class EventAudience(models.Model):
# name = models.CharField(max_length=255)
#
# def __unicode__(self):
# return self.name
#
# class Meta:
# app_label = 'api'
. Output only the next line. | queryset=EventTheme.objects.all(), |
Here is a snippet: <|code_start|> if not 'Kosovo' in list(dict(countries._countries).values()):
countries._countries.append((u'XK', u'Kosovo'))
q = forms.CharField(
required=False,
widget=forms.TextInput(
attrs={
'placeholder': 'Search for event name or tag',
'class': 'form-control'}))
past = forms.ChoiceField(
label='Include past events',
required=False,
choices=(('yes', 'yes'), ('no', 'no')),
widget=forms.RadioSelect(attrs={'class': 'search-form-element'}),
)
country = forms.ChoiceField(
label='Select country',
required=False,
widget=forms.Select(attrs={'class': 'search-form-element'}),
choices=countries
)
theme = forms.ModelMultipleChoiceField(
queryset=EventTheme.objects.all(),
label='Theme',
required=False,
widget=forms.CheckboxSelectMultiple(
attrs={
'class': 'search-form-element'}),
)
audience = forms.ModelMultipleChoiceField(
<|code_end|>
. Write the next line using the current file imports:
from django import forms
from django_countries.fields import countries
from api.models import Event
from api.models.events import EventTheme, EventAudience
and context from other files:
# Path: api/models/events.py
# class EventTheme(models.Model):
# name = models.CharField(max_length=255)
# order = models.IntegerField(default=0)
#
# def __unicode__(self):
# return self.name
#
# class Meta:
# app_label = 'api'
# ordering = ['order', 'name']
#
# class EventAudience(models.Model):
# name = models.CharField(max_length=255)
#
# def __unicode__(self):
# return self.name
#
# class Meta:
# app_label = 'api'
, which may include functions, classes, or code. Output only the next line. | queryset=EventAudience.objects.all(), |
Here is a snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Generates and sends event report to ambassadors users
'''
def send_event_report_email(user, event):
template = loader.get_template("mailer/event_email.txt")
context = Context({'user': user, 'event': event})
txt_content = template.render(context)
send_mail('A new event on codeweek.eu needs your attention',
txt_content, "info@codeweek.eu", [user.email])
def send_email_to_country_ambassadors(event):
<|code_end|>
. Write the next line using the current file imports:
from django.core.mail import send_mail
from django.template import loader, Context
from django.conf import settings
from web.processors.user import get_ambassadors_for_country
and context from other files:
# Path: web/processors/user.py
# def get_ambassadors_for_country(country):
# ambassadors = User.objects.filter(
# groups__name='ambassadors',
# userprofile__country=country)
# return ambassadors
, which may include functions, classes, or code. Output only the next line. | ambassadors = get_ambassadors_for_country(event.country) |
Predict the next line after this snippet: <|code_start|>@login_required
@never_cache
def user_profile(request):
if request.method == 'POST':
# populate form with original instance and add post info on top of that
uform = UserForm(request.POST, instance=request.user)
pform = UserProfileForm(request.POST, instance=request.user.profile)
if uform.is_valid() and pform.is_valid():
uform.save()
pform.save()
messages.success(request, 'Profile details updated')
else:
user = request.user
uform = UserForm(instance=user)
profile = user.profile
pform = UserProfileForm(instance=profile)
context = {}
context.update(csrf(request))
context['uform'] = uform
context['pform'] = pform
return render_to_response(
'pages/profile.html',
context,
context_instance=RequestContext(request))
def ambassadors(request):
try:
<|code_end|>
using the current file's imports:
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.context_processors import csrf
from django.contrib import messages
from django.views.decorators.cache import never_cache
from web.forms.user_profile import UserForm, UserProfileForm
from web.views.events import get_client_ip
from web.processors.user import get_ambassadors_for_countries
from web.processors.event import get_country_from_user_ip
from web.decorators.events import login_required
from web.processors.event import list_countries
from web.processors.event import get_country_pos
and any relevant context from other files:
# Path: web/views/events.py
# def index(request):
# def map(request):
# def add_event(request):
# def edit_event(request, event_id):
# def report_event(request, event_id):
# def view_event_by_country(request, country_code):
# def view_changed_event(request, event_id, slug):
# def view_event(request, event_id, slug):
# def view_event_by_id(request, event_id):
# def list_pending_events(request, country_code):
# def list_approved_events(request, country_code):
# def created_events(request):
# def events_to_report(request):
# def search_events(request):
# def scoreboard(request):
# def change_status(request, event_id):
# def reject_status(request, event_id):
#
# Path: web/processors/user.py
# def get_ambassadors_for_countries():
# ambassadors = get_ambassadors()
# countries_ambassadors = []
# # list countries minus two CUSTOM_COUNTRY_ENTRIES
# for code, name in list(countries)[2:]:
# readable_name = unicode(name)
# country_ambassadors = [ambassador for ambassador in ambassadors if ambassador.country == code]
# # load main ambassadors
# main_ambassadors = [ambassador for ambassador in country_ambassadors if ambassador.is_main_contact]
# # exclude main ambassadors
# supporting_ambassadors = [ambassador for ambassador in country_ambassadors if not ambassador.is_main_contact]
# countries_ambassadors.append(
# (code, readable_name, supporting_ambassadors, main_ambassadors, facebook(readable_name)))
#
# countries_ambassadors.sort(key=lambda country: country[1], reverse=False)
#
# return countries_ambassadors
#
# Path: web/processors/event.py
# def get_country_from_user_ip(ip):
# """
# Return country of IP
# """
# g = GeoIP()
# return g.country(ip)
#
# Path: web/processors/event.py
# def list_countries():
# all_countries = []
# for code, name in list(countries):
# readable_name = unicode(name)
# all_countries.append((readable_name, code))
# all_countries.sort()
# return all_countries
#
# Path: web/processors/event.py
# def get_country_pos(item):
# """
# Return country position
# """
# pos = 1
# # not including the first two fake countries in the list
# for country in list(countries)[2:]:
# country_name = country[1]
# if item == country_name:
# break
# else:
# pos = pos + 1
#
# return pos
. Output only the next line. | user_ip = get_client_ip( |
Predict the next line for this snippet: <|code_start|> uform.save()
pform.save()
messages.success(request, 'Profile details updated')
else:
user = request.user
uform = UserForm(instance=user)
profile = user.profile
pform = UserProfileForm(instance=profile)
context = {}
context.update(csrf(request))
context['uform'] = uform
context['pform'] = pform
return render_to_response(
'pages/profile.html',
context,
context_instance=RequestContext(request))
def ambassadors(request):
try:
user_ip = get_client_ip(
forwarded=request.META.get('HTTP_X_FORWARDED_FOR'),
remote=request.META.get('REMOTE_ADDR'))
user_country = get_country_from_user_ip(user_ip)
except:
user_country = None
<|code_end|>
with the help of current file imports:
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.context_processors import csrf
from django.contrib import messages
from django.views.decorators.cache import never_cache
from web.forms.user_profile import UserForm, UserProfileForm
from web.views.events import get_client_ip
from web.processors.user import get_ambassadors_for_countries
from web.processors.event import get_country_from_user_ip
from web.decorators.events import login_required
from web.processors.event import list_countries
from web.processors.event import get_country_pos
and context from other files:
# Path: web/views/events.py
# def index(request):
# def map(request):
# def add_event(request):
# def edit_event(request, event_id):
# def report_event(request, event_id):
# def view_event_by_country(request, country_code):
# def view_changed_event(request, event_id, slug):
# def view_event(request, event_id, slug):
# def view_event_by_id(request, event_id):
# def list_pending_events(request, country_code):
# def list_approved_events(request, country_code):
# def created_events(request):
# def events_to_report(request):
# def search_events(request):
# def scoreboard(request):
# def change_status(request, event_id):
# def reject_status(request, event_id):
#
# Path: web/processors/user.py
# def get_ambassadors_for_countries():
# ambassadors = get_ambassadors()
# countries_ambassadors = []
# # list countries minus two CUSTOM_COUNTRY_ENTRIES
# for code, name in list(countries)[2:]:
# readable_name = unicode(name)
# country_ambassadors = [ambassador for ambassador in ambassadors if ambassador.country == code]
# # load main ambassadors
# main_ambassadors = [ambassador for ambassador in country_ambassadors if ambassador.is_main_contact]
# # exclude main ambassadors
# supporting_ambassadors = [ambassador for ambassador in country_ambassadors if not ambassador.is_main_contact]
# countries_ambassadors.append(
# (code, readable_name, supporting_ambassadors, main_ambassadors, facebook(readable_name)))
#
# countries_ambassadors.sort(key=lambda country: country[1], reverse=False)
#
# return countries_ambassadors
#
# Path: web/processors/event.py
# def get_country_from_user_ip(ip):
# """
# Return country of IP
# """
# g = GeoIP()
# return g.country(ip)
#
# Path: web/processors/event.py
# def list_countries():
# all_countries = []
# for code, name in list(countries):
# readable_name = unicode(name)
# all_countries.append((readable_name, code))
# all_countries.sort()
# return all_countries
#
# Path: web/processors/event.py
# def get_country_pos(item):
# """
# Return country position
# """
# pos = 1
# # not including the first two fake countries in the list
# for country in list(countries)[2:]:
# country_name = country[1]
# if item == country_name:
# break
# else:
# pos = pos + 1
#
# return pos
, which may contain function names, class names, or code. Output only the next line. | countries_ambassadors = get_ambassadors_for_countries() |
Using the snippet: <|code_start|> if request.method == 'POST':
# populate form with original instance and add post info on top of that
uform = UserForm(request.POST, instance=request.user)
pform = UserProfileForm(request.POST, instance=request.user.profile)
if uform.is_valid() and pform.is_valid():
uform.save()
pform.save()
messages.success(request, 'Profile details updated')
else:
user = request.user
uform = UserForm(instance=user)
profile = user.profile
pform = UserProfileForm(instance=profile)
context = {}
context.update(csrf(request))
context['uform'] = uform
context['pform'] = pform
return render_to_response(
'pages/profile.html',
context,
context_instance=RequestContext(request))
def ambassadors(request):
try:
user_ip = get_client_ip(
forwarded=request.META.get('HTTP_X_FORWARDED_FOR'),
remote=request.META.get('REMOTE_ADDR'))
<|code_end|>
, determine the next line of code. You have imports:
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.context_processors import csrf
from django.contrib import messages
from django.views.decorators.cache import never_cache
from web.forms.user_profile import UserForm, UserProfileForm
from web.views.events import get_client_ip
from web.processors.user import get_ambassadors_for_countries
from web.processors.event import get_country_from_user_ip
from web.decorators.events import login_required
from web.processors.event import list_countries
from web.processors.event import get_country_pos
and context (class names, function names, or code) available:
# Path: web/views/events.py
# def index(request):
# def map(request):
# def add_event(request):
# def edit_event(request, event_id):
# def report_event(request, event_id):
# def view_event_by_country(request, country_code):
# def view_changed_event(request, event_id, slug):
# def view_event(request, event_id, slug):
# def view_event_by_id(request, event_id):
# def list_pending_events(request, country_code):
# def list_approved_events(request, country_code):
# def created_events(request):
# def events_to_report(request):
# def search_events(request):
# def scoreboard(request):
# def change_status(request, event_id):
# def reject_status(request, event_id):
#
# Path: web/processors/user.py
# def get_ambassadors_for_countries():
# ambassadors = get_ambassadors()
# countries_ambassadors = []
# # list countries minus two CUSTOM_COUNTRY_ENTRIES
# for code, name in list(countries)[2:]:
# readable_name = unicode(name)
# country_ambassadors = [ambassador for ambassador in ambassadors if ambassador.country == code]
# # load main ambassadors
# main_ambassadors = [ambassador for ambassador in country_ambassadors if ambassador.is_main_contact]
# # exclude main ambassadors
# supporting_ambassadors = [ambassador for ambassador in country_ambassadors if not ambassador.is_main_contact]
# countries_ambassadors.append(
# (code, readable_name, supporting_ambassadors, main_ambassadors, facebook(readable_name)))
#
# countries_ambassadors.sort(key=lambda country: country[1], reverse=False)
#
# return countries_ambassadors
#
# Path: web/processors/event.py
# def get_country_from_user_ip(ip):
# """
# Return country of IP
# """
# g = GeoIP()
# return g.country(ip)
#
# Path: web/processors/event.py
# def list_countries():
# all_countries = []
# for code, name in list(countries):
# readable_name = unicode(name)
# all_countries.append((readable_name, code))
# all_countries.sort()
# return all_countries
#
# Path: web/processors/event.py
# def get_country_pos(item):
# """
# Return country position
# """
# pos = 1
# # not including the first two fake countries in the list
# for country in list(countries)[2:]:
# country_name = country[1]
# if item == country_name:
# break
# else:
# pos = pos + 1
#
# return pos
. Output only the next line. | user_country = get_country_from_user_ip(user_ip) |
Given the following code snippet before the placeholder: <|code_start|>
class EventListSerializers(serializers.ModelSerializer):
description_short = serializers.CharField(source='description')
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
from django.utils.text import Truncator
from rest_framework import serializers
from api.models.events import Event
and context including class names, function names, and sometimes code from other files:
# Path: api/models/events.py
# class Event(models.Model):
#
# STATUS_CHOICES = (
# ('APPROVED', 'Approved'),
# ('PENDING', 'Pending'),
# ('REJECTED', 'Rejected'),
# )
#
# CUSTOM_COUNTRY_ENTRIES = (
# ('00', ' All countries'),
# ('01', '---------------'),
# )
#
# status = models.CharField(
# max_length=50,
# choices=STATUS_CHOICES,
# default='PENDING')
# title = models.CharField(max_length=255, default=None)
# slug = models.SlugField(max_length=255, null=True, blank=True)
# creator = models.ForeignKey(User)
# organizer = models.CharField(max_length=255, default=None)
# description = models.TextField(max_length=1000)
# geoposition = GeopositionField()
# location = models.CharField(max_length=1000)
# country = CountryField()
# start_date = models.DateTimeField()
# end_date = models.DateTimeField()
# event_url = models.URLField(blank=True)
# contact_person = models.EmailField(blank=True)
# picture = models.ImageField(
# upload_to=settings.MEDIA_UPLOAD_FOLDER, blank=True)
# pub_date = models.DateTimeField(default=datetime.datetime.now())
# audience = models.ManyToManyField(
# EventAudience, related_name='event_audience')
# theme = models.ManyToManyField(EventTheme, related_name='event_theme')
# tags = TaggableManager(blank=True)
# created = models.DateTimeField(auto_now_add=True)
# updated = models.DateTimeField(auto_now_add=True)
# last_report_notification_sent_at = models.DateTimeField(null=True, blank=True)
# report_notifications_count = models.IntegerField(default=0, blank=True)
# name_for_certificate = models.CharField(
# max_length=255, default='', blank=True,
# validators=[MaxLengthValidator(70), validate_ascii_text]
# )
# participants_count = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(0)])
# average_participant_age = models.FloatField(null=True, blank=True, validators=[MinValueValidator(1)])
# percentage_of_females = models.FloatField(null=True, blank=True, validators=[MinValueValidator(0), MaxValueValidator(100)])
# codeweek_for_all_participation_code = models.CharField(max_length=100, default='', blank=True)
# reported_at = models.DateTimeField(null=True, blank=True)
# certificate_generated_at = models.DateTimeField(null=True, blank=True)
#
# def __unicode__(self):
# return self.title
#
# class Meta:
# ordering = ['start_date']
# app_label = 'api'
# permissions = (
# ('edit_event', 'Can edit event'),
# ('submit_event', 'Can submit event'),
# ('reject_event', 'Can reject event'),
# )
#
# def __init__(self, *args, **kwargs):
# try:
# self.tag = kwargs['tags']
# del kwargs['tags']
# except KeyError:
# pass
#
# try:
# self.audiencelist = kwargs['audience']
# del kwargs['audience']
# except KeyError:
# pass
#
# try:
# self.themelist = kwargs['theme']
# del kwargs['theme']
# except KeyError:
# pass
#
# super(Event, self).__init__(*args, **kwargs)
#
# def save(self, *args, **kwargs):
# if not self.slug:
# self.slug = slugify(self.title) or 'event'
#
# super(Event, self).save(*args, **kwargs)
#
# try:
# for tag in self.tag:
# self.tags.add(tag)
# for entry in self.audiencelist:
# self.audience.add(entry)
# for entry in self.themelist:
# self.theme.add(entry)
# except AttributeError:
# pass
#
# def get_tags(self):
# return ', '.join([e.name for e in self.tags.all()])
#
# def get_audience_array(self):
# return [audience.pk for audience in self.audience.all()]
#
# def get_theme_array(self):
# return [theme.pk for theme in self.theme.all()]
#
# def has_started(self):
# return timezone.now() > self.start_date
#
# def has_ended(self):
# return timezone.now() > self.end_date
#
# def get_absolute_url(self):
# return reverse('web.view_event', args=[self.pk, self.slug])
#
# def is_reported(self):
# return self.reported_at is not None
#
# def is_certificate_generated(self):
# return self.certificate_generated_at is not None
#
# def is_reporting_allowed(self):
# return self.has_started() \
# and not self.is_reported() \
# and self.status == 'APPROVED' \
# and self.start_date.date().year >= 2015
#
# def certificate_file_name(self):
# obfuscated_part = sha1(settings.SECRET_KEY + str(self.pk)).hexdigest()
#
# return str(self.pk) + '-' + obfuscated_part + '.pdf'
#
# def certificate_file_path(self):
# return 'certificates/' + self.certificate_file_name()
. Output only the next line. | model = Event |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class CachedListAPIView(generics.ListAPIView):
"""
Concrete cached view for listing a queryset.
"""
@cache_response(timeout=21600, key_func='calculate_cache_key')
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def calculate_cache_key(self, view_instance, view_method, request, args, kwargs):
return sha1('-'.join([
repr(request.GET),
repr(args),
repr(kwargs),
])).hexdigest()
class EventListApi(CachedListAPIView):
""" Lists approved Events, takes the following optional GET parameters:
* limit
* order
* country_code
* past
"""
<|code_end|>
. Use current file imports:
from hashlib import sha1
from rest_framework import generics
from rest_framework_extensions.cache.decorators import cache_response
from api.serializers import EventListSerializers, EventDetailSerializer
from api.processors import get_approved_events, get_event_detail
from api.serializers import ScoreboardSerializer
from web.processors.event import count_approved_events_for_country
and context (classes, functions, or code) from other files:
# Path: api/serializers.py
# class EventListSerializers(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'id'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# class EventDetailSerializer(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'title',
# 'id',
# 'slug',
# 'description_short',
# 'picture'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# Path: api/processors.py
# def get_approved_events(limit=None, order=None, country_code=None, past=False):
# """
# Select all events which are approved and optionally limit and/or order them
# """
#
# events = Event.objects.filter(status='APPROVED')
#
# if not past:
# events = events.filter(end_date__gte=datetime.datetime.now())
# if country_code:
# events = events.filter(country=country_code)
# if order:
# events = events.order_by(order)
# if limit:
# events = events[:limit]
#
# return events
#
# def get_event_detail(id):
# """
# Select event by ID
# """
#
# events = Event.objects.filter(id=id)
#
#
#
# return events
#
# Path: api/serializers.py
# class ScoreboardSerializer(serializers.Serializer):
# country_name = serializers.CharField()
# score = serializers.FloatField()
# events = serializers.IntegerField()
# country_code = serializers.CharField(max_length=2)
#
# Path: web/processors/event.py
# def \
# count_approved_events_for_country(past=True):
# """
# Count the number of approved events and score for each country
# """
#
# all_events = Event.objects.filter(status='APPROVED')
#
# country_count = []
#
# # not including the first two fake countries in the list
# for country in list(countries)[2:]:
# country_code = country[0]
# country_name = country[1]
# number_of_events = all_events.filter(
# country=country_code).filter(
# start_date__gte=datetime.date(
# datetime.datetime.now().year, 1, 1)).count()
# population = Country.objects.get(iso=country_code).population
# country_score = 0
# if number_of_events > 0 and population > 0 and population != "":
# country_score = 1. * number_of_events / population
# country_entry = {'country_code': country_code,
# 'country_name': country_name,
# 'events': number_of_events,
# 'score': country_score}
# if number_of_events > 0:
# country_count.append(country_entry)
#
# sorted_count = sorted(
# country_count,
# key=lambda k: k['score'],
# reverse=True)
# return sorted_count
. Output only the next line. | serializer_class = EventListSerializers |
Predict the next line for this snippet: <|code_start|> def calculate_cache_key(self, view_instance, view_method, request, args, kwargs):
return sha1('-'.join([
repr(request.GET),
repr(args),
repr(kwargs),
])).hexdigest()
class EventListApi(CachedListAPIView):
""" Lists approved Events, takes the following optional GET parameters:
* limit
* order
* country_code
* past
"""
serializer_class = EventListSerializers
def get_queryset(self):
params = {
'limit': self.request.GET.get('limit', None),
'order': self.request.GET.get('order', None),
'country_code': self.request.GET.get('country_code', None),
'past': self.request.GET.get('past', False)
}
return get_approved_events(**params)
class EventDetailApi(CachedListAPIView):
<|code_end|>
with the help of current file imports:
from hashlib import sha1
from rest_framework import generics
from rest_framework_extensions.cache.decorators import cache_response
from api.serializers import EventListSerializers, EventDetailSerializer
from api.processors import get_approved_events, get_event_detail
from api.serializers import ScoreboardSerializer
from web.processors.event import count_approved_events_for_country
and context from other files:
# Path: api/serializers.py
# class EventListSerializers(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'id'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# class EventDetailSerializer(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'title',
# 'id',
# 'slug',
# 'description_short',
# 'picture'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# Path: api/processors.py
# def get_approved_events(limit=None, order=None, country_code=None, past=False):
# """
# Select all events which are approved and optionally limit and/or order them
# """
#
# events = Event.objects.filter(status='APPROVED')
#
# if not past:
# events = events.filter(end_date__gte=datetime.datetime.now())
# if country_code:
# events = events.filter(country=country_code)
# if order:
# events = events.order_by(order)
# if limit:
# events = events[:limit]
#
# return events
#
# def get_event_detail(id):
# """
# Select event by ID
# """
#
# events = Event.objects.filter(id=id)
#
#
#
# return events
#
# Path: api/serializers.py
# class ScoreboardSerializer(serializers.Serializer):
# country_name = serializers.CharField()
# score = serializers.FloatField()
# events = serializers.IntegerField()
# country_code = serializers.CharField(max_length=2)
#
# Path: web/processors/event.py
# def \
# count_approved_events_for_country(past=True):
# """
# Count the number of approved events and score for each country
# """
#
# all_events = Event.objects.filter(status='APPROVED')
#
# country_count = []
#
# # not including the first two fake countries in the list
# for country in list(countries)[2:]:
# country_code = country[0]
# country_name = country[1]
# number_of_events = all_events.filter(
# country=country_code).filter(
# start_date__gte=datetime.date(
# datetime.datetime.now().year, 1, 1)).count()
# population = Country.objects.get(iso=country_code).population
# country_score = 0
# if number_of_events > 0 and population > 0 and population != "":
# country_score = 1. * number_of_events / population
# country_entry = {'country_code': country_code,
# 'country_name': country_name,
# 'events': number_of_events,
# 'score': country_score}
# if number_of_events > 0:
# country_count.append(country_entry)
#
# sorted_count = sorted(
# country_count,
# key=lambda k: k['score'],
# reverse=True)
# return sorted_count
, which may contain function names, class names, or code. Output only the next line. | serializer_class = EventDetailSerializer |
Given the following code snippet before the placeholder: <|code_start|> @cache_response(timeout=21600, key_func='calculate_cache_key')
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def calculate_cache_key(self, view_instance, view_method, request, args, kwargs):
return sha1('-'.join([
repr(request.GET),
repr(args),
repr(kwargs),
])).hexdigest()
class EventListApi(CachedListAPIView):
""" Lists approved Events, takes the following optional GET parameters:
* limit
* order
* country_code
* past
"""
serializer_class = EventListSerializers
def get_queryset(self):
params = {
'limit': self.request.GET.get('limit', None),
'order': self.request.GET.get('order', None),
'country_code': self.request.GET.get('country_code', None),
'past': self.request.GET.get('past', False)
}
<|code_end|>
, predict the next line using imports from the current file:
from hashlib import sha1
from rest_framework import generics
from rest_framework_extensions.cache.decorators import cache_response
from api.serializers import EventListSerializers, EventDetailSerializer
from api.processors import get_approved_events, get_event_detail
from api.serializers import ScoreboardSerializer
from web.processors.event import count_approved_events_for_country
and context including class names, function names, and sometimes code from other files:
# Path: api/serializers.py
# class EventListSerializers(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'id'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# class EventDetailSerializer(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'title',
# 'id',
# 'slug',
# 'description_short',
# 'picture'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# Path: api/processors.py
# def get_approved_events(limit=None, order=None, country_code=None, past=False):
# """
# Select all events which are approved and optionally limit and/or order them
# """
#
# events = Event.objects.filter(status='APPROVED')
#
# if not past:
# events = events.filter(end_date__gte=datetime.datetime.now())
# if country_code:
# events = events.filter(country=country_code)
# if order:
# events = events.order_by(order)
# if limit:
# events = events[:limit]
#
# return events
#
# def get_event_detail(id):
# """
# Select event by ID
# """
#
# events = Event.objects.filter(id=id)
#
#
#
# return events
#
# Path: api/serializers.py
# class ScoreboardSerializer(serializers.Serializer):
# country_name = serializers.CharField()
# score = serializers.FloatField()
# events = serializers.IntegerField()
# country_code = serializers.CharField(max_length=2)
#
# Path: web/processors/event.py
# def \
# count_approved_events_for_country(past=True):
# """
# Count the number of approved events and score for each country
# """
#
# all_events = Event.objects.filter(status='APPROVED')
#
# country_count = []
#
# # not including the first two fake countries in the list
# for country in list(countries)[2:]:
# country_code = country[0]
# country_name = country[1]
# number_of_events = all_events.filter(
# country=country_code).filter(
# start_date__gte=datetime.date(
# datetime.datetime.now().year, 1, 1)).count()
# population = Country.objects.get(iso=country_code).population
# country_score = 0
# if number_of_events > 0 and population > 0 and population != "":
# country_score = 1. * number_of_events / population
# country_entry = {'country_code': country_code,
# 'country_name': country_name,
# 'events': number_of_events,
# 'score': country_score}
# if number_of_events > 0:
# country_count.append(country_entry)
#
# sorted_count = sorted(
# country_count,
# key=lambda k: k['score'],
# reverse=True)
# return sorted_count
. Output only the next line. | return get_approved_events(**params) |
Given the following code snippet before the placeholder: <|code_start|>
class EventListApi(CachedListAPIView):
""" Lists approved Events, takes the following optional GET parameters:
* limit
* order
* country_code
* past
"""
serializer_class = EventListSerializers
def get_queryset(self):
params = {
'limit': self.request.GET.get('limit', None),
'order': self.request.GET.get('order', None),
'country_code': self.request.GET.get('country_code', None),
'past': self.request.GET.get('past', False)
}
return get_approved_events(**params)
class EventDetailApi(CachedListAPIView):
serializer_class = EventDetailSerializer
def get_queryset(self):
params = {
'id': self.request.GET.get('id', None)
}
<|code_end|>
, predict the next line using imports from the current file:
from hashlib import sha1
from rest_framework import generics
from rest_framework_extensions.cache.decorators import cache_response
from api.serializers import EventListSerializers, EventDetailSerializer
from api.processors import get_approved_events, get_event_detail
from api.serializers import ScoreboardSerializer
from web.processors.event import count_approved_events_for_country
and context including class names, function names, and sometimes code from other files:
# Path: api/serializers.py
# class EventListSerializers(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'id'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# class EventDetailSerializer(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'title',
# 'id',
# 'slug',
# 'description_short',
# 'picture'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# Path: api/processors.py
# def get_approved_events(limit=None, order=None, country_code=None, past=False):
# """
# Select all events which are approved and optionally limit and/or order them
# """
#
# events = Event.objects.filter(status='APPROVED')
#
# if not past:
# events = events.filter(end_date__gte=datetime.datetime.now())
# if country_code:
# events = events.filter(country=country_code)
# if order:
# events = events.order_by(order)
# if limit:
# events = events[:limit]
#
# return events
#
# def get_event_detail(id):
# """
# Select event by ID
# """
#
# events = Event.objects.filter(id=id)
#
#
#
# return events
#
# Path: api/serializers.py
# class ScoreboardSerializer(serializers.Serializer):
# country_name = serializers.CharField()
# score = serializers.FloatField()
# events = serializers.IntegerField()
# country_code = serializers.CharField(max_length=2)
#
# Path: web/processors/event.py
# def \
# count_approved_events_for_country(past=True):
# """
# Count the number of approved events and score for each country
# """
#
# all_events = Event.objects.filter(status='APPROVED')
#
# country_count = []
#
# # not including the first two fake countries in the list
# for country in list(countries)[2:]:
# country_code = country[0]
# country_name = country[1]
# number_of_events = all_events.filter(
# country=country_code).filter(
# start_date__gte=datetime.date(
# datetime.datetime.now().year, 1, 1)).count()
# population = Country.objects.get(iso=country_code).population
# country_score = 0
# if number_of_events > 0 and population > 0 and population != "":
# country_score = 1. * number_of_events / population
# country_entry = {'country_code': country_code,
# 'country_name': country_name,
# 'events': number_of_events,
# 'score': country_score}
# if number_of_events > 0:
# country_count.append(country_entry)
#
# sorted_count = sorted(
# country_count,
# key=lambda k: k['score'],
# reverse=True)
# return sorted_count
. Output only the next line. | return get_event_detail(**params) |
Given the following code snippet before the placeholder: <|code_start|>* country_code
* past
"""
serializer_class = EventListSerializers
def get_queryset(self):
params = {
'limit': self.request.GET.get('limit', None),
'order': self.request.GET.get('order', None),
'country_code': self.request.GET.get('country_code', None),
'past': self.request.GET.get('past', False)
}
return get_approved_events(**params)
class EventDetailApi(CachedListAPIView):
serializer_class = EventDetailSerializer
def get_queryset(self):
params = {
'id': self.request.GET.get('id', None)
}
return get_event_detail(**params)
class ScoreBoardApi(CachedListAPIView):
"Lists scoreboard entries"
<|code_end|>
, predict the next line using imports from the current file:
from hashlib import sha1
from rest_framework import generics
from rest_framework_extensions.cache.decorators import cache_response
from api.serializers import EventListSerializers, EventDetailSerializer
from api.processors import get_approved_events, get_event_detail
from api.serializers import ScoreboardSerializer
from web.processors.event import count_approved_events_for_country
and context including class names, function names, and sometimes code from other files:
# Path: api/serializers.py
# class EventListSerializers(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'id'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# class EventDetailSerializer(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'title',
# 'id',
# 'slug',
# 'description_short',
# 'picture'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# Path: api/processors.py
# def get_approved_events(limit=None, order=None, country_code=None, past=False):
# """
# Select all events which are approved and optionally limit and/or order them
# """
#
# events = Event.objects.filter(status='APPROVED')
#
# if not past:
# events = events.filter(end_date__gte=datetime.datetime.now())
# if country_code:
# events = events.filter(country=country_code)
# if order:
# events = events.order_by(order)
# if limit:
# events = events[:limit]
#
# return events
#
# def get_event_detail(id):
# """
# Select event by ID
# """
#
# events = Event.objects.filter(id=id)
#
#
#
# return events
#
# Path: api/serializers.py
# class ScoreboardSerializer(serializers.Serializer):
# country_name = serializers.CharField()
# score = serializers.FloatField()
# events = serializers.IntegerField()
# country_code = serializers.CharField(max_length=2)
#
# Path: web/processors/event.py
# def \
# count_approved_events_for_country(past=True):
# """
# Count the number of approved events and score for each country
# """
#
# all_events = Event.objects.filter(status='APPROVED')
#
# country_count = []
#
# # not including the first two fake countries in the list
# for country in list(countries)[2:]:
# country_code = country[0]
# country_name = country[1]
# number_of_events = all_events.filter(
# country=country_code).filter(
# start_date__gte=datetime.date(
# datetime.datetime.now().year, 1, 1)).count()
# population = Country.objects.get(iso=country_code).population
# country_score = 0
# if number_of_events > 0 and population > 0 and population != "":
# country_score = 1. * number_of_events / population
# country_entry = {'country_code': country_code,
# 'country_name': country_name,
# 'events': number_of_events,
# 'score': country_score}
# if number_of_events > 0:
# country_count.append(country_entry)
#
# sorted_count = sorted(
# country_count,
# key=lambda k: k['score'],
# reverse=True)
# return sorted_count
. Output only the next line. | serializer_class = ScoreboardSerializer |
Based on the snippet: <|code_start|> serializer_class = EventListSerializers
def get_queryset(self):
params = {
'limit': self.request.GET.get('limit', None),
'order': self.request.GET.get('order', None),
'country_code': self.request.GET.get('country_code', None),
'past': self.request.GET.get('past', False)
}
return get_approved_events(**params)
class EventDetailApi(CachedListAPIView):
serializer_class = EventDetailSerializer
def get_queryset(self):
params = {
'id': self.request.GET.get('id', None)
}
return get_event_detail(**params)
class ScoreBoardApi(CachedListAPIView):
"Lists scoreboard entries"
serializer_class = ScoreboardSerializer
def get_queryset(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from hashlib import sha1
from rest_framework import generics
from rest_framework_extensions.cache.decorators import cache_response
from api.serializers import EventListSerializers, EventDetailSerializer
from api.processors import get_approved_events, get_event_detail
from api.serializers import ScoreboardSerializer
from web.processors.event import count_approved_events_for_country
and context (classes, functions, sometimes code) from other files:
# Path: api/serializers.py
# class EventListSerializers(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'id'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# class EventDetailSerializer(serializers.ModelSerializer):
# description_short = serializers.CharField(source='description')
#
# class Meta:
# model = Event
# fields = (
# 'geoposition',
# 'title',
# 'id',
# 'slug',
# 'description_short',
# 'picture'
# )
#
# def transform_description_short(self, obj, value):
# return Truncator(value).chars(160)
#
# Path: api/processors.py
# def get_approved_events(limit=None, order=None, country_code=None, past=False):
# """
# Select all events which are approved and optionally limit and/or order them
# """
#
# events = Event.objects.filter(status='APPROVED')
#
# if not past:
# events = events.filter(end_date__gte=datetime.datetime.now())
# if country_code:
# events = events.filter(country=country_code)
# if order:
# events = events.order_by(order)
# if limit:
# events = events[:limit]
#
# return events
#
# def get_event_detail(id):
# """
# Select event by ID
# """
#
# events = Event.objects.filter(id=id)
#
#
#
# return events
#
# Path: api/serializers.py
# class ScoreboardSerializer(serializers.Serializer):
# country_name = serializers.CharField()
# score = serializers.FloatField()
# events = serializers.IntegerField()
# country_code = serializers.CharField(max_length=2)
#
# Path: web/processors/event.py
# def \
# count_approved_events_for_country(past=True):
# """
# Count the number of approved events and score for each country
# """
#
# all_events = Event.objects.filter(status='APPROVED')
#
# country_count = []
#
# # not including the first two fake countries in the list
# for country in list(countries)[2:]:
# country_code = country[0]
# country_name = country[1]
# number_of_events = all_events.filter(
# country=country_code).filter(
# start_date__gte=datetime.date(
# datetime.datetime.now().year, 1, 1)).count()
# population = Country.objects.get(iso=country_code).population
# country_score = 0
# if number_of_events > 0 and population > 0 and population != "":
# country_score = 1. * number_of_events / population
# country_entry = {'country_code': country_code,
# 'country_name': country_name,
# 'events': number_of_events,
# 'score': country_score}
# if number_of_events > 0:
# country_count.append(country_entry)
#
# sorted_count = sorted(
# country_count,
# key=lambda k: k['score'],
# reverse=True)
# return sorted_count
. Output only the next line. | return count_approved_events_for_country() |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
urlpatterns = patterns('',
url(r'^event/list/$',
EventListApi.as_view(),
name='event.list'),
url(r'^event/detail/$',
<|code_end|>
using the current file's imports:
from django.conf.urls import patterns, url
from api.views import EventListApi, EventDetailApi
from api.views import ScoreBoardApi
and any relevant context from other files:
# Path: api/views.py
# class EventListApi(CachedListAPIView):
# """ Lists approved Events, takes the following optional GET parameters:
#
# * limit
# * order
# * country_code
# * past
# """
# serializer_class = EventListSerializers
#
# def get_queryset(self):
# params = {
# 'limit': self.request.GET.get('limit', None),
# 'order': self.request.GET.get('order', None),
# 'country_code': self.request.GET.get('country_code', None),
# 'past': self.request.GET.get('past', False)
# }
#
# return get_approved_events(**params)
#
# class EventDetailApi(CachedListAPIView):
# serializer_class = EventDetailSerializer
#
# def get_queryset(self):
# params = {
# 'id': self.request.GET.get('id', None)
# }
#
# return get_event_detail(**params)
#
# Path: api/views.py
# class ScoreBoardApi(CachedListAPIView):
# "Lists scoreboard entries"
# serializer_class = ScoreboardSerializer
#
# def get_queryset(self):
# return count_approved_events_for_country()
. Output only the next line. | EventDetailApi.as_view(), |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
urlpatterns = patterns('',
url(r'^event/list/$',
EventListApi.as_view(),
name='event.list'),
url(r'^event/detail/$',
EventDetailApi.as_view(),
name='event.detail'),
url(r'^scoreboard/$',
<|code_end|>
, predict the next line using imports from the current file:
from django.conf.urls import patterns, url
from api.views import EventListApi, EventDetailApi
from api.views import ScoreBoardApi
and context including class names, function names, and sometimes code from other files:
# Path: api/views.py
# class EventListApi(CachedListAPIView):
# """ Lists approved Events, takes the following optional GET parameters:
#
# * limit
# * order
# * country_code
# * past
# """
# serializer_class = EventListSerializers
#
# def get_queryset(self):
# params = {
# 'limit': self.request.GET.get('limit', None),
# 'order': self.request.GET.get('order', None),
# 'country_code': self.request.GET.get('country_code', None),
# 'past': self.request.GET.get('past', False)
# }
#
# return get_approved_events(**params)
#
# class EventDetailApi(CachedListAPIView):
# serializer_class = EventDetailSerializer
#
# def get_queryset(self):
# params = {
# 'id': self.request.GET.get('id', None)
# }
#
# return get_event_detail(**params)
#
# Path: api/views.py
# class ScoreBoardApi(CachedListAPIView):
# "Lists scoreboard entries"
# serializer_class = ScoreboardSerializer
#
# def get_queryset(self):
# return count_approved_events_for_country()
. Output only the next line. | ScoreBoardApi.as_view(), |
Predict the next line for this snippet: <|code_start|>
class TestRestApi:
def test_event_list_all(self, client, admin_user):
event_data = {
"start_date": datetime.datetime.now() -
datetime.timedelta(
days=1,
hours=3),
"end_date": datetime.datetime.now() +
datetime.timedelta(
days=3,
hours=3),
"organizer": "some organizer",
"creator": admin_user,
"title": "Unique REST API Event",
"pub_date": datetime.datetime.now(),
"country": "SI",
"geoposition": "46.05528,14.51444",
"location": "Ljubljana",
"audience": [1],
"theme": [1],
"tags": [
"tag1",
"tag2"],
}
<|code_end|>
with the help of current file imports:
import json
import datetime
from geoposition import Geoposition
from web.processors.event import create_or_update_event
and context from other files:
# Path: web/processors/event.py
# def create_or_update_event(event_id=None, **event_data):
# """
# Creates or updates Event object
# """
# event = Event.objects.filter(id=event_id)
# if event:
# event = event[0]
#
# if event_data:
# # many to many fields have to updated after other fields are
# # updated
# new_audiences = event_data['audience']
# event_data.pop('audience')
# new_themes = event_data['theme']
# event_data.pop('theme')
#
# event_tags = []
# if 'tags' in event_data:
# event_tags = event_data['tags']
# event_data.pop('tags')
#
# # in case we have geoposition data in event_data
# if 'geoposition' in event_data and event_data['geoposition'] != '':
# # updating geoposition field is a bit fuzzy
# event_latitude = event_data['geoposition'][0]
# event_longitude = event_data['geoposition'][1]
# event_data.pop('geoposition')
# # updating all other fields
# event.__dict__.update(event_data)
# # setting new values for geoposition
# event.__dict__['geoposition'].latitude = event_latitude
# event.__dict__['geoposition'].longitude = event_longitude
# event.save()
# else:
# event.__dict__.update(event_data)
# event.save()
#
# if 'picture' not in event_data:
# event.picture = ''
# event.save()
#
# # delete old categories and tags and store new ones
# event.audience.clear()
# event.audience.add(*new_audiences)
# event.theme.clear()
# event.theme.add(*new_themes)
# event.tags.set(*event_tags)
#
# else:
# event = Event.objects.create(**event_data)
# send_email_to_country_ambassadors(event)
#
# return event
, which may contain function names, class names, or code. Output only the next line. | event = create_or_update_event(**event_data) |
Predict the next line for this snippet: <|code_start|>
status = models.CharField(
max_length=50,
choices=STATUS_CHOICES,
default='PENDING')
title = models.CharField(max_length=255, default=None)
slug = models.SlugField(max_length=255, null=True, blank=True)
creator = models.ForeignKey(User)
organizer = models.CharField(max_length=255, default=None)
description = models.TextField(max_length=1000)
geoposition = GeopositionField()
location = models.CharField(max_length=1000)
country = CountryField()
start_date = models.DateTimeField()
end_date = models.DateTimeField()
event_url = models.URLField(blank=True)
contact_person = models.EmailField(blank=True)
picture = models.ImageField(
upload_to=settings.MEDIA_UPLOAD_FOLDER, blank=True)
pub_date = models.DateTimeField(default=datetime.datetime.now())
audience = models.ManyToManyField(
EventAudience, related_name='event_audience')
theme = models.ManyToManyField(EventTheme, related_name='event_theme')
tags = TaggableManager(blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now_add=True)
last_report_notification_sent_at = models.DateTimeField(null=True, blank=True)
report_notifications_count = models.IntegerField(default=0, blank=True)
name_for_certificate = models.CharField(
max_length=255, default='', blank=True,
<|code_end|>
with the help of current file imports:
import datetime
from hashlib import sha1
from django.utils import timezone
from django.db import models
from django.template.defaultfilters import slugify
from taggit.managers import TaggableManager
from geoposition.fields import GeopositionField
from django_countries.fields import CountryField
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.core.validators import MaxLengthValidator
from django.core.validators import MinValueValidator
from django.core.validators import MaxValueValidator
from validators.ascii import validate_ascii_text
and context from other files:
# Path: validators/ascii.py
# def validate_ascii_text(text):
# "Check if text is a text with ASCII-only characters."
#
# if not is_ascii(text):
# raise ValidationError(
# 'Please use only ASCII (Latin) letters.',
# code='invalid',
# params={'text': text},
# )
, which may contain function names, class names, or code. Output only the next line. | validators=[MaxLengthValidator(70), validate_ascii_text] |
Predict the next line for this snippet: <|code_start|>
# in case we have geoposition data in event_data
if 'geoposition' in event_data and event_data['geoposition'] != '':
# updating geoposition field is a bit fuzzy
event_latitude = event_data['geoposition'][0]
event_longitude = event_data['geoposition'][1]
event_data.pop('geoposition')
# updating all other fields
event.__dict__.update(event_data)
# setting new values for geoposition
event.__dict__['geoposition'].latitude = event_latitude
event.__dict__['geoposition'].longitude = event_longitude
event.save()
else:
event.__dict__.update(event_data)
event.save()
if 'picture' not in event_data:
event.picture = ''
event.save()
# delete old categories and tags and store new ones
event.audience.clear()
event.audience.add(*new_audiences)
event.theme.clear()
event.theme.add(*new_themes)
event.tags.set(*event_tags)
else:
event = Event.objects.create(**event_data)
<|code_end|>
with the help of current file imports:
import datetime
from django.conf import settings
from django.contrib.gis.geoip import GeoIP
from api.models import Event
from django_countries import countries
from countries_plus.models import Country
from web.processors import media
from mailer.event_report_mailer import send_email_to_country_ambassadors
and context from other files:
# Path: web/processors/media.py
# class UploadImageError(Exception):
# class ImageSizeTooLargeException(Exception):
# def process_image(image_file):
#
# Path: mailer/event_report_mailer.py
# def send_email_to_country_ambassadors(event):
# ambassadors = get_ambassadors_for_country(event.country)
# for user in ambassadors:
# send_event_report_email(user, event)
, which may contain function names, class names, or code. Output only the next line. | send_email_to_country_ambassadors(event) |
Predict the next line for this snippet: <|code_start|> action='store',
dest='emails_per_run',
help='Required. The number of emails to send per run.'
),
make_option('--notifications-limit',
type='int',
action='store',
dest='notifications_limit',
default=3,
help='Send at most X notification emails for event reporting.'
),
make_option('--notifications-interval-in-days',
type='int',
action='store',
dest='notifications_interval_in_days',
default=21,
help="If we're allowed to send more than one reminder email, notifications will be sent each X days."
),
)
def handle(self, *args, **options):
last_reminder_sent_before = datetime.now() - timedelta(days=options['notifications_interval_in_days'])
if options['emails_per_run'] == None:
self.stderr.write(
"Please specify the emails to send per run as a positional argument. E.g.:\n\n" +
"manage.py remind_organizers_to_report_events --emails-per-run 100"
)
exit(1)
<|code_end|>
with the help of current file imports:
from datetime import datetime, timedelta
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from api.processors import events_pending_for_report
from api.processors import events_pending_for_report_for
from api.models.users import User
from mailer.event_report_mailer import send_reminder_for_event_report_and_certificate
and context from other files:
# Path: api/processors.py
# def events_pending_for_report():
# return Event.objects.filter(
# reported_at=None,
# status='APPROVED',
# start_date__lte=datetime.datetime.now(),
# start_date__gte=datetime.datetime(2015, 1, 1, 0, 0 ,0))
#
# Path: api/processors.py
# def events_pending_for_report_for(creator):
# return events_pending_for_report().filter(creator=creator)
#
# Path: api/models/users.py
# class UserProfile(models.Model):
# class Meta:
# class SocialAccountList(models.Model):
# class Meta:
# def __unicode__(self):
# def is_ambassador(self):
# def get_user_profile(self):
# def email_with_name(self):
# def full_name(self):
# def __unicode__(self):
#
# Path: mailer/event_report_mailer.py
# def send_reminder_for_event_report_and_certificate(
# user,
# unreported_events_count,
# previous_emails_count=0,
# max_emails_count=None,
# test_mode=False
# ):
# template = loader.get_template("mailer/reminder_for_event_report_and_certificate.txt")
# context = Context({
# 'name': user.full_name(),
# 'email': user.email,
# 'previous_emails_count': previous_emails_count,
# 'total_emails_count': previous_emails_count + 1,
# 'max_emails_count': max_emails_count,
# 'unreported_events_count': unreported_events_count,
# })
#
# content = template.render(context)
# subject = '[CodeWeekEU] your feedback and your certificate of recognition'
# sender = settings.EVENT_REPORT_REMINDERS_FROM_EMAIL
# recipient = user.email_with_name()
#
# if test_mode:
# print("------------------------------------------------------------")
# print(u"To: " + recipient)
# print(u"From: " + sender)
# print(u"Subject: " + subject)
# print(u"\n" + content)
# print("------------------------------------------------------------")
# else:
# send_mail(subject, content, sender, [recipient])
, which may contain function names, class names, or code. Output only the next line. | events_to_report = events_pending_for_report().filter( |
Based on the snippet: <|code_start|> "manage.py remind_organizers_to_report_events --emails-per-run 100"
)
exit(1)
events_to_report = events_pending_for_report().filter(
Q(last_report_notification_sent_at=None) |
Q(last_report_notification_sent_at__lte=last_reminder_sent_before)
).filter(
report_notifications_count__lt=options['notifications_limit']
).order_by(
'report_notifications_count', 'start_date'
)
organizer_ids = events_to_report.distinct().values_list('creator_id', flat=True)
# The values above may not be unique as we're using ordering. See here for more info:
# https://docs.djangoproject.com/en/1.6/ref/models/querysets/#django.db.models.query.QuerySet.distinct
organizer_ids = list(set(organizer_ids))
organizers = User.objects.filter(id__in=organizer_ids)
self.stdout.write(
u'We have to notify {organizers_count} organizer(s) in a total of {events_count} event(s). Will send at most {emails_per_run} email(s) now.'.format(
events_count=events_to_report.count(),
organizers_count=organizers.count(),
emails_per_run=options['emails_per_run']
)
)
for organizer in organizers[:options['emails_per_run']]:
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime, timedelta
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from api.processors import events_pending_for_report
from api.processors import events_pending_for_report_for
from api.models.users import User
from mailer.event_report_mailer import send_reminder_for_event_report_and_certificate
and context (classes, functions, sometimes code) from other files:
# Path: api/processors.py
# def events_pending_for_report():
# return Event.objects.filter(
# reported_at=None,
# status='APPROVED',
# start_date__lte=datetime.datetime.now(),
# start_date__gte=datetime.datetime(2015, 1, 1, 0, 0 ,0))
#
# Path: api/processors.py
# def events_pending_for_report_for(creator):
# return events_pending_for_report().filter(creator=creator)
#
# Path: api/models/users.py
# class UserProfile(models.Model):
# class Meta:
# class SocialAccountList(models.Model):
# class Meta:
# def __unicode__(self):
# def is_ambassador(self):
# def get_user_profile(self):
# def email_with_name(self):
# def full_name(self):
# def __unicode__(self):
#
# Path: mailer/event_report_mailer.py
# def send_reminder_for_event_report_and_certificate(
# user,
# unreported_events_count,
# previous_emails_count=0,
# max_emails_count=None,
# test_mode=False
# ):
# template = loader.get_template("mailer/reminder_for_event_report_and_certificate.txt")
# context = Context({
# 'name': user.full_name(),
# 'email': user.email,
# 'previous_emails_count': previous_emails_count,
# 'total_emails_count': previous_emails_count + 1,
# 'max_emails_count': max_emails_count,
# 'unreported_events_count': unreported_events_count,
# })
#
# content = template.render(context)
# subject = '[CodeWeekEU] your feedback and your certificate of recognition'
# sender = settings.EVENT_REPORT_REMINDERS_FROM_EMAIL
# recipient = user.email_with_name()
#
# if test_mode:
# print("------------------------------------------------------------")
# print(u"To: " + recipient)
# print(u"From: " + sender)
# print(u"Subject: " + subject)
# print(u"\n" + content)
# print("------------------------------------------------------------")
# else:
# send_mail(subject, content, sender, [recipient])
. Output only the next line. | unreported_organizer_events = events_pending_for_report_for(organizer) |
Given snippet: <|code_start|> default=21,
help="If we're allowed to send more than one reminder email, notifications will be sent each X days."
),
)
def handle(self, *args, **options):
last_reminder_sent_before = datetime.now() - timedelta(days=options['notifications_interval_in_days'])
if options['emails_per_run'] == None:
self.stderr.write(
"Please specify the emails to send per run as a positional argument. E.g.:\n\n" +
"manage.py remind_organizers_to_report_events --emails-per-run 100"
)
exit(1)
events_to_report = events_pending_for_report().filter(
Q(last_report_notification_sent_at=None) |
Q(last_report_notification_sent_at__lte=last_reminder_sent_before)
).filter(
report_notifications_count__lt=options['notifications_limit']
).order_by(
'report_notifications_count', 'start_date'
)
organizer_ids = events_to_report.distinct().values_list('creator_id', flat=True)
# The values above may not be unique as we're using ordering. See here for more info:
# https://docs.djangoproject.com/en/1.6/ref/models/querysets/#django.db.models.query.QuerySet.distinct
organizer_ids = list(set(organizer_ids))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from datetime import datetime, timedelta
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from api.processors import events_pending_for_report
from api.processors import events_pending_for_report_for
from api.models.users import User
from mailer.event_report_mailer import send_reminder_for_event_report_and_certificate
and context:
# Path: api/processors.py
# def events_pending_for_report():
# return Event.objects.filter(
# reported_at=None,
# status='APPROVED',
# start_date__lte=datetime.datetime.now(),
# start_date__gte=datetime.datetime(2015, 1, 1, 0, 0 ,0))
#
# Path: api/processors.py
# def events_pending_for_report_for(creator):
# return events_pending_for_report().filter(creator=creator)
#
# Path: api/models/users.py
# class UserProfile(models.Model):
# class Meta:
# class SocialAccountList(models.Model):
# class Meta:
# def __unicode__(self):
# def is_ambassador(self):
# def get_user_profile(self):
# def email_with_name(self):
# def full_name(self):
# def __unicode__(self):
#
# Path: mailer/event_report_mailer.py
# def send_reminder_for_event_report_and_certificate(
# user,
# unreported_events_count,
# previous_emails_count=0,
# max_emails_count=None,
# test_mode=False
# ):
# template = loader.get_template("mailer/reminder_for_event_report_and_certificate.txt")
# context = Context({
# 'name': user.full_name(),
# 'email': user.email,
# 'previous_emails_count': previous_emails_count,
# 'total_emails_count': previous_emails_count + 1,
# 'max_emails_count': max_emails_count,
# 'unreported_events_count': unreported_events_count,
# })
#
# content = template.render(context)
# subject = '[CodeWeekEU] your feedback and your certificate of recognition'
# sender = settings.EVENT_REPORT_REMINDERS_FROM_EMAIL
# recipient = user.email_with_name()
#
# if test_mode:
# print("------------------------------------------------------------")
# print(u"To: " + recipient)
# print(u"From: " + sender)
# print(u"Subject: " + subject)
# print(u"\n" + content)
# print("------------------------------------------------------------")
# else:
# send_mail(subject, content, sender, [recipient])
which might include code, classes, or functions. Output only the next line. | organizers = User.objects.filter(id__in=organizer_ids) |
Based on the snippet: <|code_start|> 'report_notifications_count', 'start_date'
)
organizer_ids = events_to_report.distinct().values_list('creator_id', flat=True)
# The values above may not be unique as we're using ordering. See here for more info:
# https://docs.djangoproject.com/en/1.6/ref/models/querysets/#django.db.models.query.QuerySet.distinct
organizer_ids = list(set(organizer_ids))
organizers = User.objects.filter(id__in=organizer_ids)
self.stdout.write(
u'We have to notify {organizers_count} organizer(s) in a total of {events_count} event(s). Will send at most {emails_per_run} email(s) now.'.format(
events_count=events_to_report.count(),
organizers_count=organizers.count(),
emails_per_run=options['emails_per_run']
)
)
for organizer in organizers[:options['emails_per_run']]:
unreported_organizer_events = events_pending_for_report_for(organizer)
unrepored_events_count = unreported_organizer_events.count()
self.stdout.write(
u'Emailing {contact} for {events_count} unreported event(s)'.format(
contact=organizer.email_with_name(),
events_count=unrepored_events_count
)
)
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime, timedelta
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from api.processors import events_pending_for_report
from api.processors import events_pending_for_report_for
from api.models.users import User
from mailer.event_report_mailer import send_reminder_for_event_report_and_certificate
and context (classes, functions, sometimes code) from other files:
# Path: api/processors.py
# def events_pending_for_report():
# return Event.objects.filter(
# reported_at=None,
# status='APPROVED',
# start_date__lte=datetime.datetime.now(),
# start_date__gte=datetime.datetime(2015, 1, 1, 0, 0 ,0))
#
# Path: api/processors.py
# def events_pending_for_report_for(creator):
# return events_pending_for_report().filter(creator=creator)
#
# Path: api/models/users.py
# class UserProfile(models.Model):
# class Meta:
# class SocialAccountList(models.Model):
# class Meta:
# def __unicode__(self):
# def is_ambassador(self):
# def get_user_profile(self):
# def email_with_name(self):
# def full_name(self):
# def __unicode__(self):
#
# Path: mailer/event_report_mailer.py
# def send_reminder_for_event_report_and_certificate(
# user,
# unreported_events_count,
# previous_emails_count=0,
# max_emails_count=None,
# test_mode=False
# ):
# template = loader.get_template("mailer/reminder_for_event_report_and_certificate.txt")
# context = Context({
# 'name': user.full_name(),
# 'email': user.email,
# 'previous_emails_count': previous_emails_count,
# 'total_emails_count': previous_emails_count + 1,
# 'max_emails_count': max_emails_count,
# 'unreported_events_count': unreported_events_count,
# })
#
# content = template.render(context)
# subject = '[CodeWeekEU] your feedback and your certificate of recognition'
# sender = settings.EVENT_REPORT_REMINDERS_FROM_EMAIL
# recipient = user.email_with_name()
#
# if test_mode:
# print("------------------------------------------------------------")
# print(u"To: " + recipient)
# print(u"From: " + sender)
# print(u"Subject: " + subject)
# print(u"\n" + content)
# print("------------------------------------------------------------")
# else:
# send_mail(subject, content, sender, [recipient])
. Output only the next line. | send_reminder_for_event_report_and_certificate( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.