repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
project-generator/project_generator
project_generator/tools/iar.py
IAREmbeddedWorkbenchProject._ewp_files_set
def _ewp_files_set(self, ewp_dic, project_dic): """ Fills files in the ewp dictionary """ # empty any files in the template which are not grouped try: ewp_dic['project']['file'] = [] except KeyError: pass # empty groups ewp_dic['project']['group'] = [] i = 0 for group_name, files in project_dic['groups'].items(): ewp_dic['project']['group'].append({'name': group_name, 'file': []}) for file in files: ewp_dic['project']['group'][i]['file'].append({'name': file}) ewp_dic['project']['group'][i]['file'] = sorted(ewp_dic['project']['group'][i]['file'], key=lambda x: os.path.basename(x['name'].lower())) i += 1
python
def _ewp_files_set(self, ewp_dic, project_dic): """ Fills files in the ewp dictionary """ # empty any files in the template which are not grouped try: ewp_dic['project']['file'] = [] except KeyError: pass # empty groups ewp_dic['project']['group'] = [] i = 0 for group_name, files in project_dic['groups'].items(): ewp_dic['project']['group'].append({'name': group_name, 'file': []}) for file in files: ewp_dic['project']['group'][i]['file'].append({'name': file}) ewp_dic['project']['group'][i]['file'] = sorted(ewp_dic['project']['group'][i]['file'], key=lambda x: os.path.basename(x['name'].lower())) i += 1
[ "def", "_ewp_files_set", "(", "self", ",", "ewp_dic", ",", "project_dic", ")", ":", "# empty any files in the template which are not grouped", "try", ":", "ewp_dic", "[", "'project'", "]", "[", "'file'", "]", "=", "[", "]", "except", "KeyError", ":", "pass", "# ...
Fills files in the ewp dictionary
[ "Fills", "files", "in", "the", "ewp", "dictionary" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L173-L188
train
26,100
project-generator/project_generator
project_generator/tools/iar.py
IAREmbeddedWorkbenchProject._clean_xmldict_single_dic
def _clean_xmldict_single_dic(self, dictionary): """ Every None replace by '' in the dic, as xml parsers puts None in those fiels, which is not valid for IAR """ for k, v in dictionary.items(): if v is None: dictionary[k] = ''
python
def _clean_xmldict_single_dic(self, dictionary): """ Every None replace by '' in the dic, as xml parsers puts None in those fiels, which is not valid for IAR """ for k, v in dictionary.items(): if v is None: dictionary[k] = ''
[ "def", "_clean_xmldict_single_dic", "(", "self", ",", "dictionary", ")", ":", "for", "k", ",", "v", "in", "dictionary", ".", "items", "(", ")", ":", "if", "v", "is", "None", ":", "dictionary", "[", "k", "]", "=", "''" ]
Every None replace by '' in the dic, as xml parsers puts None in those fiels, which is not valid for IAR
[ "Every", "None", "replace", "by", "in", "the", "dic", "as", "xml", "parsers", "puts", "None", "in", "those", "fiels", "which", "is", "not", "valid", "for", "IAR" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L196-L200
train
26,101
project-generator/project_generator
project_generator/tools/iar.py
IAREmbeddedWorkbench._fix_paths
def _fix_paths(self, data): """ All paths needs to be fixed - add PROJ_DIR prefix + normalize """ data['include_paths'] = [join('$PROJ_DIR$', path) for path in data['include_paths']] if data['linker_file']: data['linker_file'] = join('$PROJ_DIR$', data['linker_file']) data['groups'] = {} for attribute in SOURCE_KEYS: for k, v in data[attribute].items(): if k not in data['groups']: data['groups'][k] = [] data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v]) for k,v in data['include_files'].items(): if k not in data['groups']: data['groups'][k] = [] data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v]) # sort groups data['groups'] = OrderedDict(sorted(data['groups'].items(), key=lambda t: t[0]))
python
def _fix_paths(self, data): """ All paths needs to be fixed - add PROJ_DIR prefix + normalize """ data['include_paths'] = [join('$PROJ_DIR$', path) for path in data['include_paths']] if data['linker_file']: data['linker_file'] = join('$PROJ_DIR$', data['linker_file']) data['groups'] = {} for attribute in SOURCE_KEYS: for k, v in data[attribute].items(): if k not in data['groups']: data['groups'][k] = [] data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v]) for k,v in data['include_files'].items(): if k not in data['groups']: data['groups'][k] = [] data['groups'][k].extend([join('$PROJ_DIR$', file) for file in v]) # sort groups data['groups'] = OrderedDict(sorted(data['groups'].items(), key=lambda t: t[0]))
[ "def", "_fix_paths", "(", "self", ",", "data", ")", ":", "data", "[", "'include_paths'", "]", "=", "[", "join", "(", "'$PROJ_DIR$'", ",", "path", ")", "for", "path", "in", "data", "[", "'include_paths'", "]", "]", "if", "data", "[", "'linker_file'", "]...
All paths needs to be fixed - add PROJ_DIR prefix + normalize
[ "All", "paths", "needs", "to", "be", "fixed", "-", "add", "PROJ_DIR", "prefix", "+", "normalize" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L335-L354
train
26,102
project-generator/project_generator
project_generator/tools/iar.py
IAREmbeddedWorkbench.build_project
def build_project(self): """ Build IAR project """ # > IarBuild [project_path] -build [project_name] proj_path = join(getcwd(), self.workspace['files']['ewp']) if proj_path.split('.')[-1] != 'ewp': proj_path += '.ewp' if not os.path.exists(proj_path): logger.debug("The file: %s does not exists, exported prior building?" % proj_path) return -1 logger.debug("Building IAR project: %s" % proj_path) args = [join(self.env_settings.get_env_settings('iar'), 'IarBuild.exe'), proj_path, '-build', os.path.splitext(os.path.basename(self.workspace['files']['ewp']))[0]] logger.debug(args) try: p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) output, err = p.communicate() except: logger.error("Project: %s build failed. Please check IARBUILD path in the user_settings.py file." % self.workspace['files']['ewp']) return -1 else: build_log_path = os.path.join(os.path.dirname(proj_path),'build_log.txt') with open(build_log_path, 'w') as f: f.write(output) num_errors = self._parse_subprocess_output(output) if num_errors == 0: logger.info("Project: %s build completed." % self.workspace['files']['ewp']) return 0 else: logger.error("Project: %s build failed with %d errors" % (self.workspace['files']['ewp'], num_errors)) return -1
python
def build_project(self): """ Build IAR project """ # > IarBuild [project_path] -build [project_name] proj_path = join(getcwd(), self.workspace['files']['ewp']) if proj_path.split('.')[-1] != 'ewp': proj_path += '.ewp' if not os.path.exists(proj_path): logger.debug("The file: %s does not exists, exported prior building?" % proj_path) return -1 logger.debug("Building IAR project: %s" % proj_path) args = [join(self.env_settings.get_env_settings('iar'), 'IarBuild.exe'), proj_path, '-build', os.path.splitext(os.path.basename(self.workspace['files']['ewp']))[0]] logger.debug(args) try: p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) output, err = p.communicate() except: logger.error("Project: %s build failed. Please check IARBUILD path in the user_settings.py file." % self.workspace['files']['ewp']) return -1 else: build_log_path = os.path.join(os.path.dirname(proj_path),'build_log.txt') with open(build_log_path, 'w') as f: f.write(output) num_errors = self._parse_subprocess_output(output) if num_errors == 0: logger.info("Project: %s build completed." % self.workspace['files']['ewp']) return 0 else: logger.error("Project: %s build failed with %d errors" % (self.workspace['files']['ewp'], num_errors)) return -1
[ "def", "build_project", "(", "self", ")", ":", "# > IarBuild [project_path] -build [project_name]", "proj_path", "=", "join", "(", "getcwd", "(", ")", ",", "self", ".", "workspace", "[", "'files'", "]", "[", "'ewp'", "]", ")", "if", "proj_path", ".", "split", ...
Build IAR project
[ "Build", "IAR", "project" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/iar.py#L544-L575
train
26,103
project-generator/project_generator
project_generator/tools/tool.py
Exporter.gen_file_jinja
def gen_file_jinja(self, template_file, data, output, dest_path): if not os.path.exists(dest_path): os.makedirs(dest_path) output = join(dest_path, output) logger.debug("Generating: %s" % output) """ Fills data to the project template, using jinja2. """ env = Environment() env.loader = FileSystemLoader(self.TEMPLATE_DIR) # TODO: undefined=StrictUndefined - this needs fixes in templates template = env.get_template(template_file) target_text = template.render(data) open(output, "w").write(target_text) return dirname(output), output
python
def gen_file_jinja(self, template_file, data, output, dest_path): if not os.path.exists(dest_path): os.makedirs(dest_path) output = join(dest_path, output) logger.debug("Generating: %s" % output) """ Fills data to the project template, using jinja2. """ env = Environment() env.loader = FileSystemLoader(self.TEMPLATE_DIR) # TODO: undefined=StrictUndefined - this needs fixes in templates template = env.get_template(template_file) target_text = template.render(data) open(output, "w").write(target_text) return dirname(output), output
[ "def", "gen_file_jinja", "(", "self", ",", "template_file", ",", "data", ",", "output", ",", "dest_path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dest_path", ")", ":", "os", ".", "makedirs", "(", "dest_path", ")", "output", "=", ...
Fills data to the project template, using jinja2.
[ "Fills", "data", "to", "the", "project", "template", "using", "jinja2", "." ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/tool.py#L140-L154
train
26,104
project-generator/project_generator
project_generator/tools/tool.py
Exporter._expand_data
def _expand_data(self, old_data, new_data, group): """ data expansion - uvision needs filename and path separately. """ for file in old_data: if file: extension = file.split(".")[-1].lower() if extension in self.file_types.keys(): new_data['groups'][group].append(self._expand_one_file(normpath(file), new_data, extension)) else: logger.debug("Filetype for file %s not recognized" % file) if hasattr(self, '_expand_sort_key'): new_data['groups'][group] = sorted(new_data['groups'][group], key=self._expand_sort_key)
python
def _expand_data(self, old_data, new_data, group): """ data expansion - uvision needs filename and path separately. """ for file in old_data: if file: extension = file.split(".")[-1].lower() if extension in self.file_types.keys(): new_data['groups'][group].append(self._expand_one_file(normpath(file), new_data, extension)) else: logger.debug("Filetype for file %s not recognized" % file) if hasattr(self, '_expand_sort_key'): new_data['groups'][group] = sorted(new_data['groups'][group], key=self._expand_sort_key)
[ "def", "_expand_data", "(", "self", ",", "old_data", ",", "new_data", ",", "group", ")", ":", "for", "file", "in", "old_data", ":", "if", "file", ":", "extension", "=", "file", ".", "split", "(", "\".\"", ")", "[", "-", "1", "]", ".", "lower", "(",...
data expansion - uvision needs filename and path separately.
[ "data", "expansion", "-", "uvision", "needs", "filename", "and", "path", "separately", "." ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/tool.py#L163-L175
train
26,105
project-generator/project_generator
project_generator/tools/tool.py
Exporter._get_groups
def _get_groups(self, data): """ Get all groups defined """ groups = [] for attribute in SOURCE_KEYS: for k, v in data[attribute].items(): if k == None: k = 'Sources' if k not in groups: groups.append(k) for k, v in data['include_files'].items(): if k == None: k = 'Includes' if k not in groups: groups.append(k) return groups
python
def _get_groups(self, data): """ Get all groups defined """ groups = [] for attribute in SOURCE_KEYS: for k, v in data[attribute].items(): if k == None: k = 'Sources' if k not in groups: groups.append(k) for k, v in data['include_files'].items(): if k == None: k = 'Includes' if k not in groups: groups.append(k) return groups
[ "def", "_get_groups", "(", "self", ",", "data", ")", ":", "groups", "=", "[", "]", "for", "attribute", "in", "SOURCE_KEYS", ":", "for", "k", ",", "v", "in", "data", "[", "attribute", "]", ".", "items", "(", ")", ":", "if", "k", "==", "None", ":",...
Get all groups defined
[ "Get", "all", "groups", "defined" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/tool.py#L177-L191
train
26,106
project-generator/project_generator
project_generator/tools/tool.py
Exporter._iterate
def _iterate(self, data, expanded_data): """ _Iterate through all data, store the result expansion in extended dictionary """ for attribute in SOURCE_KEYS: for k, v in data[attribute].items(): if k == None: group = 'Sources' else: group = k if group in data[attribute].keys(): self._expand_data(data[attribute][group], expanded_data, group) for k, v in data['include_files'].items(): if k == None: group = 'Includes' else: group = k self._expand_data(data['include_files'][group], expanded_data, group) # sort groups expanded_data['groups'] = OrderedDict(sorted(expanded_data['groups'].items(), key=lambda t: t[0]))
python
def _iterate(self, data, expanded_data): """ _Iterate through all data, store the result expansion in extended dictionary """ for attribute in SOURCE_KEYS: for k, v in data[attribute].items(): if k == None: group = 'Sources' else: group = k if group in data[attribute].keys(): self._expand_data(data[attribute][group], expanded_data, group) for k, v in data['include_files'].items(): if k == None: group = 'Includes' else: group = k self._expand_data(data['include_files'][group], expanded_data, group) # sort groups expanded_data['groups'] = OrderedDict(sorted(expanded_data['groups'].items(), key=lambda t: t[0]))
[ "def", "_iterate", "(", "self", ",", "data", ",", "expanded_data", ")", ":", "for", "attribute", "in", "SOURCE_KEYS", ":", "for", "k", ",", "v", "in", "data", "[", "attribute", "]", ".", "items", "(", ")", ":", "if", "k", "==", "None", ":", "group"...
_Iterate through all data, store the result expansion in extended dictionary
[ "_Iterate", "through", "all", "data", "store", "the", "result", "expansion", "in", "extended", "dictionary" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/tool.py#L193-L211
train
26,107
project-generator/project_generator
project_generator/tools/eclipse.py
EclipseGnuARM.export_project
def export_project(self): """ Processes groups and misc options specific for eclipse, and run generator """ output = copy.deepcopy(self.generated_project) data_for_make = self.workspace.copy() self.exporter.process_data_for_makefile(data_for_make) output['path'], output['files']['makefile'] = self.gen_file_jinja('makefile_gcc.tmpl', data_for_make, 'Makefile', data_for_make['output_dir']['path']) expanded_dic = self.workspace.copy() expanded_dic['rel_path'] = data_for_make['output_dir']['rel_path'] groups = self._get_groups(expanded_dic) expanded_dic['groups'] = {} for group in groups: expanded_dic['groups'][group] = [] self._iterate(self.workspace, expanded_dic) # Project file project_path, output['files']['cproj'] = self.gen_file_jinja( 'eclipse_makefile.cproject.tmpl', expanded_dic, '.cproject', data_for_make['output_dir']['path']) project_path, output['files']['proj_file'] = self.gen_file_jinja( 'eclipse.project.tmpl', expanded_dic, '.project', data_for_make['output_dir']['path']) return output
python
def export_project(self): """ Processes groups and misc options specific for eclipse, and run generator """ output = copy.deepcopy(self.generated_project) data_for_make = self.workspace.copy() self.exporter.process_data_for_makefile(data_for_make) output['path'], output['files']['makefile'] = self.gen_file_jinja('makefile_gcc.tmpl', data_for_make, 'Makefile', data_for_make['output_dir']['path']) expanded_dic = self.workspace.copy() expanded_dic['rel_path'] = data_for_make['output_dir']['rel_path'] groups = self._get_groups(expanded_dic) expanded_dic['groups'] = {} for group in groups: expanded_dic['groups'][group] = [] self._iterate(self.workspace, expanded_dic) # Project file project_path, output['files']['cproj'] = self.gen_file_jinja( 'eclipse_makefile.cproject.tmpl', expanded_dic, '.cproject', data_for_make['output_dir']['path']) project_path, output['files']['proj_file'] = self.gen_file_jinja( 'eclipse.project.tmpl', expanded_dic, '.project', data_for_make['output_dir']['path']) return output
[ "def", "export_project", "(", "self", ")", ":", "output", "=", "copy", ".", "deepcopy", "(", "self", ".", "generated_project", ")", "data_for_make", "=", "self", ".", "workspace", ".", "copy", "(", ")", "self", ".", "exporter", ".", "process_data_for_makefil...
Processes groups and misc options specific for eclipse, and run generator
[ "Processes", "groups", "and", "misc", "options", "specific", "for", "eclipse", "and", "run", "generator" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/eclipse.py#L65-L87
train
26,108
project-generator/project_generator
project_generator/project.py
ProjectWorkspace.generate
def generate(self, tool, copied=False, copy=False): """ Generates a workspace """ # copied - already done by external script, copy - do actual copy tools = [] if not tool: logger.info("Workspace supports one tool for all projects within.") return -1 else: tools = [tool] result = 0 for export_tool in tools: tool_export = ToolsSupported().get_tool(export_tool) if tool_export is None: result = -1 continue project_export_dir_overwrite = False if self.settings.export_location_format != self.settings.DEFAULT_EXPORT_LOCATION_FORMAT: location_format = self.settings.export_location_format else: if 'export_dir' in self.workspace_settings: location_format = self.workspace_settings['export_dir'][0] project_export_dir_overwrite = True else: location_format = self.settings.export_location_format # substitute all of the different dynamic values location = PartialFormatter().format(location_format, **{ 'project_name': self.name, 'tool': tool, 'workspace_name': self.name }) workspace_dic = { 'projects': [], 'settings': { 'name': self.name, 'path': os.path.normpath(location), }, } for project in self.projects: generated_files = { 'projects' : [], 'workspaces': [], } if project_export_dir_overwrite: project.project['common']['export_dir'] = location # Merge all dics, copy sources if required, correct output dir. This happens here # because we need tool to set proper path (tool might be used as string template) project._fill_export_dict(export_tool, copied) if copy: project._copy_sources_to_generated_destination() project.project['export']['singular'] = False files = tool_export(project.project['export'], self.settings).export_project() # we gather all generated files, needed for workspace files workspace_dic['projects'].append(files) generated_files['projects'].append(files) # all projects are genereated, now generate workspace files generated_files['workspaces'] = tool_export(workspace_dic, self.settings).export_workspace() self.generated_files[export_tool] = generated_files return result
python
def generate(self, tool, copied=False, copy=False): """ Generates a workspace """ # copied - already done by external script, copy - do actual copy tools = [] if not tool: logger.info("Workspace supports one tool for all projects within.") return -1 else: tools = [tool] result = 0 for export_tool in tools: tool_export = ToolsSupported().get_tool(export_tool) if tool_export is None: result = -1 continue project_export_dir_overwrite = False if self.settings.export_location_format != self.settings.DEFAULT_EXPORT_LOCATION_FORMAT: location_format = self.settings.export_location_format else: if 'export_dir' in self.workspace_settings: location_format = self.workspace_settings['export_dir'][0] project_export_dir_overwrite = True else: location_format = self.settings.export_location_format # substitute all of the different dynamic values location = PartialFormatter().format(location_format, **{ 'project_name': self.name, 'tool': tool, 'workspace_name': self.name }) workspace_dic = { 'projects': [], 'settings': { 'name': self.name, 'path': os.path.normpath(location), }, } for project in self.projects: generated_files = { 'projects' : [], 'workspaces': [], } if project_export_dir_overwrite: project.project['common']['export_dir'] = location # Merge all dics, copy sources if required, correct output dir. This happens here # because we need tool to set proper path (tool might be used as string template) project._fill_export_dict(export_tool, copied) if copy: project._copy_sources_to_generated_destination() project.project['export']['singular'] = False files = tool_export(project.project['export'], self.settings).export_project() # we gather all generated files, needed for workspace files workspace_dic['projects'].append(files) generated_files['projects'].append(files) # all projects are genereated, now generate workspace files generated_files['workspaces'] = tool_export(workspace_dic, self.settings).export_workspace() self.generated_files[export_tool] = generated_files return result
[ "def", "generate", "(", "self", ",", "tool", ",", "copied", "=", "False", ",", "copy", "=", "False", ")", ":", "# copied - already done by external script, copy - do actual copy", "tools", "=", "[", "]", "if", "not", "tool", ":", "logger", ".", "info", "(", ...
Generates a workspace
[ "Generates", "a", "workspace" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L38-L106
train
26,109
project-generator/project_generator
project_generator/project.py
Project._validate_tools
def _validate_tools(self, tool): """ Use tool_supported or tool """ tools = [] if not tool: if len(self.project['common']['tools_supported']) == 0: logger.info("No tool defined.") return -1 tools = self.project['common']['tools_supported'] else: tools = [tool] return tools
python
def _validate_tools(self, tool): """ Use tool_supported or tool """ tools = [] if not tool: if len(self.project['common']['tools_supported']) == 0: logger.info("No tool defined.") return -1 tools = self.project['common']['tools_supported'] else: tools = [tool] return tools
[ "def", "_validate_tools", "(", "self", ",", "tool", ")", ":", "tools", "=", "[", "]", "if", "not", "tool", ":", "if", "len", "(", "self", ".", "project", "[", "'common'", "]", "[", "'tools_supported'", "]", ")", "==", "0", ":", "logger", ".", "info...
Use tool_supported or tool
[ "Use", "tool_supported", "or", "tool" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L339-L350
train
26,110
project-generator/project_generator
project_generator/project.py
Project._generate_output_dir
def _generate_output_dir(settings, path): """ This is a separate function, so that it can be more easily tested """ relpath = os.path.relpath(settings.root,path) count = relpath.count(os.sep) + 1 return relpath+os.path.sep, count
python
def _generate_output_dir(settings, path): """ This is a separate function, so that it can be more easily tested """ relpath = os.path.relpath(settings.root,path) count = relpath.count(os.sep) + 1 return relpath+os.path.sep, count
[ "def", "_generate_output_dir", "(", "settings", ",", "path", ")", ":", "relpath", "=", "os", ".", "path", ".", "relpath", "(", "settings", ".", "root", ",", "path", ")", "count", "=", "relpath", ".", "count", "(", "os", ".", "sep", ")", "+", "1", "...
This is a separate function, so that it can be more easily tested
[ "This", "is", "a", "separate", "function", "so", "that", "it", "can", "be", "more", "easily", "tested" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L353-L359
train
26,111
project-generator/project_generator
project_generator/project.py
Project._copy_sources_to_generated_destination
def _copy_sources_to_generated_destination(self): """ Copies all project files to specified directory - generated dir """ files = [] for key in FILES_EXTENSIONS.keys(): if type(self.project['export'][key]) is dict: for k,v in self.project['export'][key].items(): files.extend(v) elif type(self.project['export'][key]) is list: files.extend(self.project['export'][key]) else: files.append(self.project['export'][key]) destination = os.path.join(self.settings.root, self.project['export']['output_dir']['path']) if os.path.exists(destination): shutil.rmtree(destination) for item in files: s = os.path.join(self.settings.root, item) d = os.path.join(destination, item) if os.path.isdir(s): shutil.copytree(s,d) else: if not os.path.exists(os.path.dirname(d)): os.makedirs(os.path.join(self.settings.root, os.path.dirname(d))) shutil.copy2(s,d)
python
def _copy_sources_to_generated_destination(self): """ Copies all project files to specified directory - generated dir """ files = [] for key in FILES_EXTENSIONS.keys(): if type(self.project['export'][key]) is dict: for k,v in self.project['export'][key].items(): files.extend(v) elif type(self.project['export'][key]) is list: files.extend(self.project['export'][key]) else: files.append(self.project['export'][key]) destination = os.path.join(self.settings.root, self.project['export']['output_dir']['path']) if os.path.exists(destination): shutil.rmtree(destination) for item in files: s = os.path.join(self.settings.root, item) d = os.path.join(destination, item) if os.path.isdir(s): shutil.copytree(s,d) else: if not os.path.exists(os.path.dirname(d)): os.makedirs(os.path.join(self.settings.root, os.path.dirname(d))) shutil.copy2(s,d)
[ "def", "_copy_sources_to_generated_destination", "(", "self", ")", ":", "files", "=", "[", "]", "for", "key", "in", "FILES_EXTENSIONS", ".", "keys", "(", ")", ":", "if", "type", "(", "self", ".", "project", "[", "'export'", "]", "[", "key", "]", ")", "...
Copies all project files to specified directory - generated dir
[ "Copies", "all", "project", "files", "to", "specified", "directory", "-", "generated", "dir" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L475-L499
train
26,112
project-generator/project_generator
project_generator/project.py
Project.clean
def clean(self, tool): """ Clean a project """ tools = self._validate_tools(tool) if tools == -1: return -1 for current_tool in tools: # We get the export dict formed, then use it for cleaning self._fill_export_dict(current_tool) path = self.project['export']['output_dir']['path'] if os.path.isdir(path): logger.info("Cleaning directory %s" % path) shutil.rmtree(path) return 0
python
def clean(self, tool): """ Clean a project """ tools = self._validate_tools(tool) if tools == -1: return -1 for current_tool in tools: # We get the export dict formed, then use it for cleaning self._fill_export_dict(current_tool) path = self.project['export']['output_dir']['path'] if os.path.isdir(path): logger.info("Cleaning directory %s" % path) shutil.rmtree(path) return 0
[ "def", "clean", "(", "self", ",", "tool", ")", ":", "tools", "=", "self", ".", "_validate_tools", "(", "tool", ")", "if", "tools", "==", "-", "1", ":", "return", "-", "1", "for", "current_tool", "in", "tools", ":", "# We get the export dict formed, then us...
Clean a project
[ "Clean", "a", "project" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L501-L517
train
26,113
project-generator/project_generator
project_generator/project.py
Project.generate
def generate(self, tool, copied=False, copy=False): """ Generates a project """ tools = self._validate_tools(tool) if tools == -1: return -1 generated_files = {} result = 0 for export_tool in tools: exporter = ToolsSupported().get_tool(export_tool) # None is an error if exporter is None: result = -1 logger.debug("Tool: %s was not found" % export_tool) continue self._fill_export_dict(export_tool, copied) if copy: logger.debug("Copying sources to the output directory") self._copy_sources_to_generated_destination() # dump a log file if debug is enabled if logger.isEnabledFor(logging.DEBUG): dump_data = {} dump_data['common'] = self.project['common'] dump_data['tool_specific'] = self.project['tool_specific'] dump_data['merged'] = self.project['export'] handler = logging.FileHandler(os.path.join(os.getcwd(), "%s.log" % self.name),"w", encoding=None, delay="true") handler.setLevel(logging.DEBUG) logger.addHandler(handler) logger.debug("\n" + yaml.dump(dump_data)) files = exporter(self.project['export'], self.settings).export_project() generated_files[export_tool] = files self.generated_files = generated_files return result
python
def generate(self, tool, copied=False, copy=False): """ Generates a project """ tools = self._validate_tools(tool) if tools == -1: return -1 generated_files = {} result = 0 for export_tool in tools: exporter = ToolsSupported().get_tool(export_tool) # None is an error if exporter is None: result = -1 logger.debug("Tool: %s was not found" % export_tool) continue self._fill_export_dict(export_tool, copied) if copy: logger.debug("Copying sources to the output directory") self._copy_sources_to_generated_destination() # dump a log file if debug is enabled if logger.isEnabledFor(logging.DEBUG): dump_data = {} dump_data['common'] = self.project['common'] dump_data['tool_specific'] = self.project['tool_specific'] dump_data['merged'] = self.project['export'] handler = logging.FileHandler(os.path.join(os.getcwd(), "%s.log" % self.name),"w", encoding=None, delay="true") handler.setLevel(logging.DEBUG) logger.addHandler(handler) logger.debug("\n" + yaml.dump(dump_data)) files = exporter(self.project['export'], self.settings).export_project() generated_files[export_tool] = files self.generated_files = generated_files return result
[ "def", "generate", "(", "self", ",", "tool", ",", "copied", "=", "False", ",", "copy", "=", "False", ")", ":", "tools", "=", "self", ".", "_validate_tools", "(", "tool", ")", "if", "tools", "==", "-", "1", ":", "return", "-", "1", "generated_files", ...
Generates a project
[ "Generates", "a", "project" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L519-L555
train
26,114
project-generator/project_generator
project_generator/project.py
Project.build
def build(self, tool): """build the project""" tools = self._validate_tools(tool) if tools == -1: return -1 result = 0 for build_tool in tools: builder = ToolsSupported().get_tool(build_tool) # None is an error if builder is None: logger.debug("Tool: %s was not found" % builder) result = -1 continue logger.debug("Building for tool: %s", build_tool) logger.debug(self.generated_files) if builder(self.generated_files[build_tool], self.settings).build_project() == -1: # if one fails, set to -1 to report result = -1 return result
python
def build(self, tool): """build the project""" tools = self._validate_tools(tool) if tools == -1: return -1 result = 0 for build_tool in tools: builder = ToolsSupported().get_tool(build_tool) # None is an error if builder is None: logger.debug("Tool: %s was not found" % builder) result = -1 continue logger.debug("Building for tool: %s", build_tool) logger.debug(self.generated_files) if builder(self.generated_files[build_tool], self.settings).build_project() == -1: # if one fails, set to -1 to report result = -1 return result
[ "def", "build", "(", "self", ",", "tool", ")", ":", "tools", "=", "self", ".", "_validate_tools", "(", "tool", ")", "if", "tools", "==", "-", "1", ":", "return", "-", "1", "result", "=", "0", "for", "build_tool", "in", "tools", ":", "builder", "=",...
build the project
[ "build", "the", "project" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L557-L579
train
26,115
project-generator/project_generator
project_generator/project.py
Project.get_generated_project_files
def get_generated_project_files(self, tool): """ Get generated project files, the content depends on a tool. Look at tool implementation """ exporter = ToolsSupported().get_tool(tool) return exporter(self.generated_files[tool], self.settings).get_generated_project_files()
python
def get_generated_project_files(self, tool): """ Get generated project files, the content depends on a tool. Look at tool implementation """ exporter = ToolsSupported().get_tool(tool) return exporter(self.generated_files[tool], self.settings).get_generated_project_files()
[ "def", "get_generated_project_files", "(", "self", ",", "tool", ")", ":", "exporter", "=", "ToolsSupported", "(", ")", ".", "get_tool", "(", "tool", ")", "return", "exporter", "(", "self", ".", "generated_files", "[", "tool", "]", ",", "self", ".", "settin...
Get generated project files, the content depends on a tool. Look at tool implementation
[ "Get", "generated", "project", "files", "the", "content", "depends", "on", "a", "tool", ".", "Look", "at", "tool", "implementation" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/project.py#L581-L585
train
26,116
project-generator/project_generator
project_generator/tools/makearmcc.py
MakefileArmcc.export_project
def export_project(self): """ Processes misc options specific for GCC ARM, and run generator """ generated_projects = deepcopy(self.generated_projects) self.process_data_for_makefile(self.workspace) generated_projects['path'], generated_projects['files']['makefile'] = self.gen_file_jinja('makefile_armcc.tmpl', self.workspace, 'Makefile', self.workspace['output_dir']['path']) return generated_projects
python
def export_project(self): """ Processes misc options specific for GCC ARM, and run generator """ generated_projects = deepcopy(self.generated_projects) self.process_data_for_makefile(self.workspace) generated_projects['path'], generated_projects['files']['makefile'] = self.gen_file_jinja('makefile_armcc.tmpl', self.workspace, 'Makefile', self.workspace['output_dir']['path']) return generated_projects
[ "def", "export_project", "(", "self", ")", ":", "generated_projects", "=", "deepcopy", "(", "self", ".", "generated_projects", ")", "self", ".", "process_data_for_makefile", "(", "self", ".", "workspace", ")", "generated_projects", "[", "'path'", "]", ",", "gene...
Processes misc options specific for GCC ARM, and run generator
[ "Processes", "misc", "options", "specific", "for", "GCC", "ARM", "and", "run", "generator" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/makearmcc.py#L35-L40
train
26,117
project-generator/project_generator
project_generator/tools/makefile.py
MakefileTool._parse_specific_options
def _parse_specific_options(self, data): """ Parse all specific setttings. """ data['common_flags'] = [] data['ld_flags'] = [] data['c_flags'] = [] data['cxx_flags'] = [] data['asm_flags'] = [] for k, v in data['misc'].items(): if type(v) is list: if k not in data: data[k] = [] data[k].extend(v) else: if k not in data: data[k] = '' data[k] = v
python
def _parse_specific_options(self, data): """ Parse all specific setttings. """ data['common_flags'] = [] data['ld_flags'] = [] data['c_flags'] = [] data['cxx_flags'] = [] data['asm_flags'] = [] for k, v in data['misc'].items(): if type(v) is list: if k not in data: data[k] = [] data[k].extend(v) else: if k not in data: data[k] = '' data[k] = v
[ "def", "_parse_specific_options", "(", "self", ",", "data", ")", ":", "data", "[", "'common_flags'", "]", "=", "[", "]", "data", "[", "'ld_flags'", "]", "=", "[", "]", "data", "[", "'c_flags'", "]", "=", "[", "]", "data", "[", "'cxx_flags'", "]", "="...
Parse all specific setttings.
[ "Parse", "all", "specific", "setttings", "." ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/makefile.py#L54-L69
train
26,118
project-generator/project_generator
project_generator/tools/sublimetext.py
SublimeTextMakeGccARM.export_project
def export_project(self): """ Processes misc options specific for GCC ARM, and run generator. """ output = copy.deepcopy(self.generated_project) self.process_data_for_makefile(self.workspace) self._fix_sublime_paths(self.workspace) self.workspace['linker_options'] =[] output['path'], output['files']['makefile'] = self.gen_file_jinja('makefile_gcc.tmpl', self.workspace, 'Makefile', self.workspace['output_dir']['path']) self.workspace['buildsys_name'] = 'Make' self.workspace['buildsys_cmd'] = 'make all' path, output['files']['sublimetext'] = self.gen_file_jinja( 'sublimetext.sublime-project.tmpl', self.workspace, '%s.sublime-project' % self.workspace['name'], self.workspace['output_dir']['path']) generated_projects = output return generated_projects
python
def export_project(self): """ Processes misc options specific for GCC ARM, and run generator. """ output = copy.deepcopy(self.generated_project) self.process_data_for_makefile(self.workspace) self._fix_sublime_paths(self.workspace) self.workspace['linker_options'] =[] output['path'], output['files']['makefile'] = self.gen_file_jinja('makefile_gcc.tmpl', self.workspace, 'Makefile', self.workspace['output_dir']['path']) self.workspace['buildsys_name'] = 'Make' self.workspace['buildsys_cmd'] = 'make all' path, output['files']['sublimetext'] = self.gen_file_jinja( 'sublimetext.sublime-project.tmpl', self.workspace, '%s.sublime-project' % self.workspace['name'], self.workspace['output_dir']['path']) generated_projects = output return generated_projects
[ "def", "export_project", "(", "self", ")", ":", "output", "=", "copy", ".", "deepcopy", "(", "self", ".", "generated_project", ")", "self", ".", "process_data_for_makefile", "(", "self", ".", "workspace", ")", "self", ".", "_fix_sublime_paths", "(", "self", ...
Processes misc options specific for GCC ARM, and run generator.
[ "Processes", "misc", "options", "specific", "for", "GCC", "ARM", "and", "run", "generator", "." ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/tools/sublimetext.py#L46-L61
train
26,119
project-generator/project_generator
project_generator/util.py
fix_paths
def fix_paths(project_data, rel_path, extensions): """ Fix paths for extension list """ norm_func = lambda path : os.path.normpath(os.path.join(rel_path, path)) for key in extensions: if type(project_data[key]) is dict: for k,v in project_data[key].items(): project_data[key][k] = [norm_func(i) for i in v] elif type(project_data[key]) is list: project_data[key] = [norm_func(i) for i in project_data[key]] else: project_data[key] = norm_func(project_data[key])
python
def fix_paths(project_data, rel_path, extensions): """ Fix paths for extension list """ norm_func = lambda path : os.path.normpath(os.path.join(rel_path, path)) for key in extensions: if type(project_data[key]) is dict: for k,v in project_data[key].items(): project_data[key][k] = [norm_func(i) for i in v] elif type(project_data[key]) is list: project_data[key] = [norm_func(i) for i in project_data[key]] else: project_data[key] = norm_func(project_data[key])
[ "def", "fix_paths", "(", "project_data", ",", "rel_path", ",", "extensions", ")", ":", "norm_func", "=", "lambda", "path", ":", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "rel_path", ",", "path", ")", ")", "for", "k...
Fix paths for extension list
[ "Fix", "paths", "for", "extension", "list" ]
a361be16eeb5a8829ff5cd26850ddd4b264296fe
https://github.com/project-generator/project_generator/blob/a361be16eeb5a8829ff5cd26850ddd4b264296fe/project_generator/util.py#L91-L101
train
26,120
RusticiSoftware/TinCanPython
tincan/typed_list.py
TypedList._make_cls
def _make_cls(self, value): """If value is not instance of self._cls, converts and returns it. Otherwise, returns value. :param value: the thing to make a self._cls from :rtype self._cls """ if isinstance(value, self._cls): return value return self._cls(value)
python
def _make_cls(self, value): """If value is not instance of self._cls, converts and returns it. Otherwise, returns value. :param value: the thing to make a self._cls from :rtype self._cls """ if isinstance(value, self._cls): return value return self._cls(value)
[ "def", "_make_cls", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "self", ".", "_cls", ")", ":", "return", "value", "return", "self", ".", "_cls", "(", "value", ")" ]
If value is not instance of self._cls, converts and returns it. Otherwise, returns value. :param value: the thing to make a self._cls from :rtype self._cls
[ "If", "value", "is", "not", "instance", "of", "self", ".", "_cls", "converts", "and", "returns", "it", ".", "Otherwise", "returns", "value", "." ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/typed_list.py#L45-L54
train
26,121
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS._send_request
def _send_request(self, request): """Establishes connection and returns http response based off of request. :param request: HTTPRequest object :type request: :class:`tincan.http_request.HTTPRequest` :returns: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse` """ headers = {"X-Experience-API-Version": self.version} if self.auth is not None: headers["Authorization"] = self.auth headers.update(request.headers) params = request.query_params params = {k: unicode(params[k]).encode('utf-8') for k in params.keys()} params = urllib.urlencode(params) if request.resource.startswith('http'): url = request.resource else: url = self.endpoint url += request.resource parsed = urlparse(url) if parsed.scheme == "https": web_req = httplib.HTTPSConnection(parsed.hostname, parsed.port) else: web_req = httplib.HTTPConnection(parsed.hostname, parsed.port) path = parsed.path if parsed.query or parsed.path: path += "?" if parsed.query: path += parsed.query if params: path += params if hasattr(request, "content") and request.content is not None: web_req.request( method=request.method, url=path, body=request.content, headers=headers, ) else: web_req.request( method=request.method, url=path, headers=headers, ) response = web_req.getresponse() data = response.read() web_req.close() if (200 <= response.status < 300 or (response.status == 404 and hasattr(request, "ignore404") and request.ignore404)): success = True else: success = False return LRSResponse( success=success, request=request, response=response, data=data, )
python
def _send_request(self, request): """Establishes connection and returns http response based off of request. :param request: HTTPRequest object :type request: :class:`tincan.http_request.HTTPRequest` :returns: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse` """ headers = {"X-Experience-API-Version": self.version} if self.auth is not None: headers["Authorization"] = self.auth headers.update(request.headers) params = request.query_params params = {k: unicode(params[k]).encode('utf-8') for k in params.keys()} params = urllib.urlencode(params) if request.resource.startswith('http'): url = request.resource else: url = self.endpoint url += request.resource parsed = urlparse(url) if parsed.scheme == "https": web_req = httplib.HTTPSConnection(parsed.hostname, parsed.port) else: web_req = httplib.HTTPConnection(parsed.hostname, parsed.port) path = parsed.path if parsed.query or parsed.path: path += "?" if parsed.query: path += parsed.query if params: path += params if hasattr(request, "content") and request.content is not None: web_req.request( method=request.method, url=path, body=request.content, headers=headers, ) else: web_req.request( method=request.method, url=path, headers=headers, ) response = web_req.getresponse() data = response.read() web_req.close() if (200 <= response.status < 300 or (response.status == 404 and hasattr(request, "ignore404") and request.ignore404)): success = True else: success = False return LRSResponse( success=success, request=request, response=response, data=data, )
[ "def", "_send_request", "(", "self", ",", "request", ")", ":", "headers", "=", "{", "\"X-Experience-API-Version\"", ":", "self", ".", "version", "}", "if", "self", ".", "auth", "is", "not", "None", ":", "headers", "[", "\"Authorization\"", "]", "=", "self"...
Establishes connection and returns http response based off of request. :param request: HTTPRequest object :type request: :class:`tincan.http_request.HTTPRequest` :returns: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Establishes", "connection", "and", "returns", "http", "response", "based", "off", "of", "request", "." ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L89-L160
train
26,122
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.about
def about(self): """Gets about response from LRS :return: LRS Response object with the returned LRS about object as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="GET", resource="about" ) lrs_response = self._send_request(request) if lrs_response.success: lrs_response.content = About.from_json(lrs_response.data) return lrs_response
python
def about(self): """Gets about response from LRS :return: LRS Response object with the returned LRS about object as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="GET", resource="about" ) lrs_response = self._send_request(request) if lrs_response.success: lrs_response.content = About.from_json(lrs_response.data) return lrs_response
[ "def", "about", "(", "self", ")", ":", "request", "=", "HTTPRequest", "(", "method", "=", "\"GET\"", ",", "resource", "=", "\"about\"", ")", "lrs_response", "=", "self", ".", "_send_request", "(", "request", ")", "if", "lrs_response", ".", "success", ":", ...
Gets about response from LRS :return: LRS Response object with the returned LRS about object as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Gets", "about", "response", "from", "LRS" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L162-L177
train
26,123
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.save_statement
def save_statement(self, statement): """Save statement to LRS and update statement id if necessary :param statement: Statement object to be saved :type statement: :class:`tincan.statement.Statement` :return: LRS Response object with the saved statement as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(statement, Statement): statement = Statement(statement) request = HTTPRequest( method="POST", resource="statements" ) if statement.id is not None: request.method = "PUT" request.query_params["statementId"] = statement.id request.headers["Content-Type"] = "application/json" request.content = statement.to_json(self.version) lrs_response = self._send_request(request) if lrs_response.success: if statement.id is None: statement.id = json.loads(lrs_response.data)[0] lrs_response.content = statement return lrs_response
python
def save_statement(self, statement): """Save statement to LRS and update statement id if necessary :param statement: Statement object to be saved :type statement: :class:`tincan.statement.Statement` :return: LRS Response object with the saved statement as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(statement, Statement): statement = Statement(statement) request = HTTPRequest( method="POST", resource="statements" ) if statement.id is not None: request.method = "PUT" request.query_params["statementId"] = statement.id request.headers["Content-Type"] = "application/json" request.content = statement.to_json(self.version) lrs_response = self._send_request(request) if lrs_response.success: if statement.id is None: statement.id = json.loads(lrs_response.data)[0] lrs_response.content = statement return lrs_response
[ "def", "save_statement", "(", "self", ",", "statement", ")", ":", "if", "not", "isinstance", "(", "statement", ",", "Statement", ")", ":", "statement", "=", "Statement", "(", "statement", ")", "request", "=", "HTTPRequest", "(", "method", "=", "\"POST\"", ...
Save statement to LRS and update statement id if necessary :param statement: Statement object to be saved :type statement: :class:`tincan.statement.Statement` :return: LRS Response object with the saved statement as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Save", "statement", "to", "LRS", "and", "update", "statement", "id", "if", "necessary" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L179-L208
train
26,124
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.save_statements
def save_statements(self, statements): """Save statements to LRS and update their statement id's :param statements: A list of statement objects to be saved :type statements: :class:`StatementList` :return: LRS Response object with the saved list of statements as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(statements, StatementList): statements = StatementList(statements) request = HTTPRequest( method="POST", resource="statements" ) request.headers["Content-Type"] = "application/json" request.content = statements.to_json() lrs_response = self._send_request(request) if lrs_response.success: id_list = json.loads(lrs_response.data) for s, statement_id in zip(statements, id_list): s.id = statement_id lrs_response.content = statements return lrs_response
python
def save_statements(self, statements): """Save statements to LRS and update their statement id's :param statements: A list of statement objects to be saved :type statements: :class:`StatementList` :return: LRS Response object with the saved list of statements as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(statements, StatementList): statements = StatementList(statements) request = HTTPRequest( method="POST", resource="statements" ) request.headers["Content-Type"] = "application/json" request.content = statements.to_json() lrs_response = self._send_request(request) if lrs_response.success: id_list = json.loads(lrs_response.data) for s, statement_id in zip(statements, id_list): s.id = statement_id lrs_response.content = statements return lrs_response
[ "def", "save_statements", "(", "self", ",", "statements", ")", ":", "if", "not", "isinstance", "(", "statements", ",", "StatementList", ")", ":", "statements", "=", "StatementList", "(", "statements", ")", "request", "=", "HTTPRequest", "(", "method", "=", "...
Save statements to LRS and update their statement id's :param statements: A list of statement objects to be saved :type statements: :class:`StatementList` :return: LRS Response object with the saved list of statements as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Save", "statements", "to", "LRS", "and", "update", "their", "statement", "id", "s" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L210-L238
train
26,125
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.retrieve_statement
def retrieve_statement(self, statement_id): """Retrieve a statement from the server from its id :param statement_id: The UUID of the desired statement :type statement_id: str | unicode :return: LRS Response object with the retrieved statement as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="GET", resource="statements" ) request.query_params["statementId"] = statement_id lrs_response = self._send_request(request) if lrs_response.success: lrs_response.content = Statement.from_json(lrs_response.data) return lrs_response
python
def retrieve_statement(self, statement_id): """Retrieve a statement from the server from its id :param statement_id: The UUID of the desired statement :type statement_id: str | unicode :return: LRS Response object with the retrieved statement as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="GET", resource="statements" ) request.query_params["statementId"] = statement_id lrs_response = self._send_request(request) if lrs_response.success: lrs_response.content = Statement.from_json(lrs_response.data) return lrs_response
[ "def", "retrieve_statement", "(", "self", ",", "statement_id", ")", ":", "request", "=", "HTTPRequest", "(", "method", "=", "\"GET\"", ",", "resource", "=", "\"statements\"", ")", "request", ".", "query_params", "[", "\"statementId\"", "]", "=", "statement_id", ...
Retrieve a statement from the server from its id :param statement_id: The UUID of the desired statement :type statement_id: str | unicode :return: LRS Response object with the retrieved statement as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Retrieve", "a", "statement", "from", "the", "server", "from", "its", "id" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L240-L259
train
26,126
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.query_statements
def query_statements(self, query): """Query the LRS for statements with specified parameters :param query: Dictionary of query parameters and their values :type query: dict :return: LRS Response object with the returned StatementsResult object as content :rtype: :class:`tincan.lrs_response.LRSResponse` .. note:: Optional query parameters are\n **statementId:** (*str*) ID of the Statement to fetch **voidedStatementId:** (*str*) ID of the voided Statement to fetch **agent:** (*Agent* |*Group*) Filter to return Statements for which the specified Agent or Group is the Actor **verb:** (*Verb id IRI*) Filter to return Statements matching the verb id **activity:** (*Activity id IRI*) Filter to return Statements for which the specified Activity is the Object **registration:** (*UUID*) Filter to return Statements matching the specified registration ID **related_activities:** (*bool*) Include Statements for which the Object, Context Activities or any Sub-Statement properties match the specified Activity **related_agents:** (*bool*) Include Statements for which the Actor, Object, Authority, Instructor, Team, or any Sub-Statement properties match the specified Agent **since:** (*datetime*) Filter to return Statements stored since the specified datetime **until:** (*datetime*) Filter to return Statements stored at or before the specified datetime **limit:** (*positive int*) Allow <limit> Statements to be returned. 0 indicates the maximum supported by the LRS **format:** (*str* {"ids"|"exact"|"canonical"}) Manipulates how the LRS handles importing and returning the statements **attachments:** (*bool*) If true, the LRS will use multipart responses and include all attachment data per Statement returned. Otherwise, application/json is used and no attachment information will be returned **ascending:** (*bool*) If true, the LRS will return results in ascending order of stored time (oldest first) """ params = {} param_keys = [ "registration", "since", "until", "limit", "ascending", "related_activities", "related_agents", "format", "attachments", ] for k, v in query.iteritems(): if v is not None: if k == "agent": params[k] = v.to_json(self.version) elif k == "verb" or k == "activity": params[k] = v.id elif k in param_keys: params[k] = v request = HTTPRequest( method="GET", resource="statements" ) request.query_params = params lrs_response = self._send_request(request) if lrs_response.success: lrs_response.content = StatementsResult.from_json(lrs_response.data) return lrs_response
python
def query_statements(self, query): """Query the LRS for statements with specified parameters :param query: Dictionary of query parameters and their values :type query: dict :return: LRS Response object with the returned StatementsResult object as content :rtype: :class:`tincan.lrs_response.LRSResponse` .. note:: Optional query parameters are\n **statementId:** (*str*) ID of the Statement to fetch **voidedStatementId:** (*str*) ID of the voided Statement to fetch **agent:** (*Agent* |*Group*) Filter to return Statements for which the specified Agent or Group is the Actor **verb:** (*Verb id IRI*) Filter to return Statements matching the verb id **activity:** (*Activity id IRI*) Filter to return Statements for which the specified Activity is the Object **registration:** (*UUID*) Filter to return Statements matching the specified registration ID **related_activities:** (*bool*) Include Statements for which the Object, Context Activities or any Sub-Statement properties match the specified Activity **related_agents:** (*bool*) Include Statements for which the Actor, Object, Authority, Instructor, Team, or any Sub-Statement properties match the specified Agent **since:** (*datetime*) Filter to return Statements stored since the specified datetime **until:** (*datetime*) Filter to return Statements stored at or before the specified datetime **limit:** (*positive int*) Allow <limit> Statements to be returned. 0 indicates the maximum supported by the LRS **format:** (*str* {"ids"|"exact"|"canonical"}) Manipulates how the LRS handles importing and returning the statements **attachments:** (*bool*) If true, the LRS will use multipart responses and include all attachment data per Statement returned. Otherwise, application/json is used and no attachment information will be returned **ascending:** (*bool*) If true, the LRS will return results in ascending order of stored time (oldest first) """ params = {} param_keys = [ "registration", "since", "until", "limit", "ascending", "related_activities", "related_agents", "format", "attachments", ] for k, v in query.iteritems(): if v is not None: if k == "agent": params[k] = v.to_json(self.version) elif k == "verb" or k == "activity": params[k] = v.id elif k in param_keys: params[k] = v request = HTTPRequest( method="GET", resource="statements" ) request.query_params = params lrs_response = self._send_request(request) if lrs_response.success: lrs_response.content = StatementsResult.from_json(lrs_response.data) return lrs_response
[ "def", "query_statements", "(", "self", ",", "query", ")", ":", "params", "=", "{", "}", "param_keys", "=", "[", "\"registration\"", ",", "\"since\"", ",", "\"until\"", ",", "\"limit\"", ",", "\"ascending\"", ",", "\"related_activities\"", ",", "\"related_agents...
Query the LRS for statements with specified parameters :param query: Dictionary of query parameters and their values :type query: dict :return: LRS Response object with the returned StatementsResult object as content :rtype: :class:`tincan.lrs_response.LRSResponse` .. note:: Optional query parameters are\n **statementId:** (*str*) ID of the Statement to fetch **voidedStatementId:** (*str*) ID of the voided Statement to fetch **agent:** (*Agent* |*Group*) Filter to return Statements for which the specified Agent or Group is the Actor **verb:** (*Verb id IRI*) Filter to return Statements matching the verb id **activity:** (*Activity id IRI*) Filter to return Statements for which the specified Activity is the Object **registration:** (*UUID*) Filter to return Statements matching the specified registration ID **related_activities:** (*bool*) Include Statements for which the Object, Context Activities or any Sub-Statement properties match the specified Activity **related_agents:** (*bool*) Include Statements for which the Actor, Object, Authority, Instructor, Team, or any Sub-Statement properties match the specified Agent **since:** (*datetime*) Filter to return Statements stored since the specified datetime **until:** (*datetime*) Filter to return Statements stored at or before the specified datetime **limit:** (*positive int*) Allow <limit> Statements to be returned. 0 indicates the maximum supported by the LRS **format:** (*str* {"ids"|"exact"|"canonical"}) Manipulates how the LRS handles importing and returning the statements **attachments:** (*bool*) If true, the LRS will use multipart responses and include all attachment data per Statement returned. Otherwise, application/json is used and no attachment information will be returned **ascending:** (*bool*) If true, the LRS will return results in ascending order of stored time (oldest first)
[ "Query", "the", "LRS", "for", "statements", "with", "specified", "parameters" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L282-L351
train
26,127
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.more_statements
def more_statements(self, more_url): """Query the LRS for more statements :param more_url: URL from a StatementsResult object used to retrieve more statements :type more_url: str | unicode :return: LRS Response object with the returned StatementsResult object as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if isinstance(more_url, StatementsResult): more_url = more_url.more more_url = self.get_endpoint_server_root() + more_url request = HTTPRequest( method="GET", resource=more_url ) lrs_response = self._send_request(request) if lrs_response.success: lrs_response.content = StatementsResult.from_json(lrs_response.data) return lrs_response
python
def more_statements(self, more_url): """Query the LRS for more statements :param more_url: URL from a StatementsResult object used to retrieve more statements :type more_url: str | unicode :return: LRS Response object with the returned StatementsResult object as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if isinstance(more_url, StatementsResult): more_url = more_url.more more_url = self.get_endpoint_server_root() + more_url request = HTTPRequest( method="GET", resource=more_url ) lrs_response = self._send_request(request) if lrs_response.success: lrs_response.content = StatementsResult.from_json(lrs_response.data) return lrs_response
[ "def", "more_statements", "(", "self", ",", "more_url", ")", ":", "if", "isinstance", "(", "more_url", ",", "StatementsResult", ")", ":", "more_url", "=", "more_url", ".", "more", "more_url", "=", "self", ".", "get_endpoint_server_root", "(", ")", "+", "more...
Query the LRS for more statements :param more_url: URL from a StatementsResult object used to retrieve more statements :type more_url: str | unicode :return: LRS Response object with the returned StatementsResult object as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Query", "the", "LRS", "for", "more", "statements" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L353-L376
train
26,128
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.retrieve_state_ids
def retrieve_state_ids(self, activity, agent, registration=None, since=None): """Retrieve state id's from the LRS with the provided parameters :param activity: Activity object of desired states :type activity: :class:`tincan.activity.Activity` :param agent: Agent object of desired states :type agent: :class:`tincan.agent.Agent` :param registration: Registration UUID of desired states :type registration: str | unicode :param since: Retrieve state id's since this time :type since: str | unicode :return: LRS Response object with the retrieved state id's as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(activity, Activity): activity = Activity(activity) if not isinstance(agent, Agent): agent = Agent(agent) request = HTTPRequest( method="GET", resource="activities/state" ) request.query_params = { "activityId": activity.id, "agent": agent.to_json(self.version) } if registration is not None: request.query_params["registration"] = registration if since is not None: request.query_params["since"] = since lrs_response = self._send_request(request) if lrs_response.success: lrs_response.content = json.loads(lrs_response.data) return lrs_response
python
def retrieve_state_ids(self, activity, agent, registration=None, since=None): """Retrieve state id's from the LRS with the provided parameters :param activity: Activity object of desired states :type activity: :class:`tincan.activity.Activity` :param agent: Agent object of desired states :type agent: :class:`tincan.agent.Agent` :param registration: Registration UUID of desired states :type registration: str | unicode :param since: Retrieve state id's since this time :type since: str | unicode :return: LRS Response object with the retrieved state id's as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(activity, Activity): activity = Activity(activity) if not isinstance(agent, Agent): agent = Agent(agent) request = HTTPRequest( method="GET", resource="activities/state" ) request.query_params = { "activityId": activity.id, "agent": agent.to_json(self.version) } if registration is not None: request.query_params["registration"] = registration if since is not None: request.query_params["since"] = since lrs_response = self._send_request(request) if lrs_response.success: lrs_response.content = json.loads(lrs_response.data) return lrs_response
[ "def", "retrieve_state_ids", "(", "self", ",", "activity", ",", "agent", ",", "registration", "=", "None", ",", "since", "=", "None", ")", ":", "if", "not", "isinstance", "(", "activity", ",", "Activity", ")", ":", "activity", "=", "Activity", "(", "acti...
Retrieve state id's from the LRS with the provided parameters :param activity: Activity object of desired states :type activity: :class:`tincan.activity.Activity` :param agent: Agent object of desired states :type agent: :class:`tincan.agent.Agent` :param registration: Registration UUID of desired states :type registration: str | unicode :param since: Retrieve state id's since this time :type since: str | unicode :return: LRS Response object with the retrieved state id's as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Retrieve", "state", "id", "s", "from", "the", "LRS", "with", "the", "provided", "parameters" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L378-L417
train
26,129
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.retrieve_state
def retrieve_state(self, activity, agent, state_id, registration=None): """Retrieve state from LRS with the provided parameters :param activity: Activity object of desired state :type activity: :class:`tincan.activity.Activity` :param agent: Agent object of desired state :type agent: :class:`tincan.agent.Agent` :param state_id: UUID of desired state :type state_id: str | unicode :param registration: registration UUID of desired state :type registration: str | unicode :return: LRS Response object with retrieved state document as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(activity, Activity): activity = Activity(activity) if not isinstance(agent, Agent): agent = Agent(agent) request = HTTPRequest( method="GET", resource="activities/state", ignore404=True ) request.query_params = { "activityId": activity.id, "agent": agent.to_json(self.version), "stateId": state_id } if registration is not None: request.query_params["registration"] = registration lrs_response = self._send_request(request) if lrs_response.success: doc = StateDocument( id=state_id, content=lrs_response.data, activity=activity, agent=agent ) if registration is not None: doc.registration = registration headers = lrs_response.response.getheaders() if "lastModified" in headers and headers["lastModified"] is not None: doc.timestamp = headers["lastModified"] if "contentType" in headers and headers["contentType"] is not None: doc.content_type = headers["contentType"] if "etag" in headers and headers["etag"] is not None: doc.etag = headers["etag"] lrs_response.content = doc return lrs_response
python
def retrieve_state(self, activity, agent, state_id, registration=None): """Retrieve state from LRS with the provided parameters :param activity: Activity object of desired state :type activity: :class:`tincan.activity.Activity` :param agent: Agent object of desired state :type agent: :class:`tincan.agent.Agent` :param state_id: UUID of desired state :type state_id: str | unicode :param registration: registration UUID of desired state :type registration: str | unicode :return: LRS Response object with retrieved state document as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(activity, Activity): activity = Activity(activity) if not isinstance(agent, Agent): agent = Agent(agent) request = HTTPRequest( method="GET", resource="activities/state", ignore404=True ) request.query_params = { "activityId": activity.id, "agent": agent.to_json(self.version), "stateId": state_id } if registration is not None: request.query_params["registration"] = registration lrs_response = self._send_request(request) if lrs_response.success: doc = StateDocument( id=state_id, content=lrs_response.data, activity=activity, agent=agent ) if registration is not None: doc.registration = registration headers = lrs_response.response.getheaders() if "lastModified" in headers and headers["lastModified"] is not None: doc.timestamp = headers["lastModified"] if "contentType" in headers and headers["contentType"] is not None: doc.content_type = headers["contentType"] if "etag" in headers and headers["etag"] is not None: doc.etag = headers["etag"] lrs_response.content = doc return lrs_response
[ "def", "retrieve_state", "(", "self", ",", "activity", ",", "agent", ",", "state_id", ",", "registration", "=", "None", ")", ":", "if", "not", "isinstance", "(", "activity", ",", "Activity", ")", ":", "activity", "=", "Activity", "(", "activity", ")", "i...
Retrieve state from LRS with the provided parameters :param activity: Activity object of desired state :type activity: :class:`tincan.activity.Activity` :param agent: Agent object of desired state :type agent: :class:`tincan.agent.Agent` :param state_id: UUID of desired state :type state_id: str | unicode :param registration: registration UUID of desired state :type registration: str | unicode :return: LRS Response object with retrieved state document as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Retrieve", "state", "from", "LRS", "with", "the", "provided", "parameters" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L419-L476
train
26,130
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.save_state
def save_state(self, state): """Save a state doc to the LRS :param state: State document to be saved :type state: :class:`tincan.documents.state_document.StateDocument` :return: LRS Response object with saved state as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="PUT", resource="activities/state", content=state.content, ) if state.content_type is not None: request.headers["Content-Type"] = state.content_type else: request.headers["Content-Type"] = "application/octet-stream" if state.etag is not None: request.headers["If-Match"] = state.etag request.query_params = { "stateId": state.id, "activityId": state.activity.id, "agent": state.agent.to_json(self.version) } lrs_response = self._send_request(request) lrs_response.content = state return self._send_request(request)
python
def save_state(self, state): """Save a state doc to the LRS :param state: State document to be saved :type state: :class:`tincan.documents.state_document.StateDocument` :return: LRS Response object with saved state as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="PUT", resource="activities/state", content=state.content, ) if state.content_type is not None: request.headers["Content-Type"] = state.content_type else: request.headers["Content-Type"] = "application/octet-stream" if state.etag is not None: request.headers["If-Match"] = state.etag request.query_params = { "stateId": state.id, "activityId": state.activity.id, "agent": state.agent.to_json(self.version) } lrs_response = self._send_request(request) lrs_response.content = state return self._send_request(request)
[ "def", "save_state", "(", "self", ",", "state", ")", ":", "request", "=", "HTTPRequest", "(", "method", "=", "\"PUT\"", ",", "resource", "=", "\"activities/state\"", ",", "content", "=", "state", ".", "content", ",", ")", "if", "state", ".", "content_type"...
Save a state doc to the LRS :param state: State document to be saved :type state: :class:`tincan.documents.state_document.StateDocument` :return: LRS Response object with saved state as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Save", "a", "state", "doc", "to", "the", "LRS" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L478-L507
train
26,131
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS._delete_state
def _delete_state(self, activity, agent, state_id=None, registration=None, etag=None): """Private method to delete a specified state from the LRS :param activity: Activity object of state to be deleted :type activity: :class:`tincan.activity.Activity` :param agent: Agent object of state to be deleted :type agent: :class:`tincan.agent.Agent` :param state_id: UUID of state to be deleted :type state_id: str | unicode :param registration: registration UUID of state to be deleted :type registration: str | unicode :param etag: etag of state to be deleted :type etag: str | unicode :return: LRS Response object with deleted state as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(activity, Activity): activity = Activity(activity) if not isinstance(agent, Agent): agent = Agent(agent) request = HTTPRequest( method="DELETE", resource="activities/state" ) if etag is not None: request.headers["If-Match"] = etag request.query_params = { "activityId": activity.id, "agent": agent.to_json(self.version) } if state_id is not None: request.query_params["stateId"] = state_id if registration is not None: request.query_params["registration"] = registration lrs_response = self._send_request(request) return lrs_response
python
def _delete_state(self, activity, agent, state_id=None, registration=None, etag=None): """Private method to delete a specified state from the LRS :param activity: Activity object of state to be deleted :type activity: :class:`tincan.activity.Activity` :param agent: Agent object of state to be deleted :type agent: :class:`tincan.agent.Agent` :param state_id: UUID of state to be deleted :type state_id: str | unicode :param registration: registration UUID of state to be deleted :type registration: str | unicode :param etag: etag of state to be deleted :type etag: str | unicode :return: LRS Response object with deleted state as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(activity, Activity): activity = Activity(activity) if not isinstance(agent, Agent): agent = Agent(agent) request = HTTPRequest( method="DELETE", resource="activities/state" ) if etag is not None: request.headers["If-Match"] = etag request.query_params = { "activityId": activity.id, "agent": agent.to_json(self.version) } if state_id is not None: request.query_params["stateId"] = state_id if registration is not None: request.query_params["registration"] = registration lrs_response = self._send_request(request) return lrs_response
[ "def", "_delete_state", "(", "self", ",", "activity", ",", "agent", ",", "state_id", "=", "None", ",", "registration", "=", "None", ",", "etag", "=", "None", ")", ":", "if", "not", "isinstance", "(", "activity", ",", "Activity", ")", ":", "activity", "...
Private method to delete a specified state from the LRS :param activity: Activity object of state to be deleted :type activity: :class:`tincan.activity.Activity` :param agent: Agent object of state to be deleted :type agent: :class:`tincan.agent.Agent` :param state_id: UUID of state to be deleted :type state_id: str | unicode :param registration: registration UUID of state to be deleted :type registration: str | unicode :param etag: etag of state to be deleted :type etag: str | unicode :return: LRS Response object with deleted state as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Private", "method", "to", "delete", "a", "specified", "state", "from", "the", "LRS" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L509-L551
train
26,132
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.delete_state
def delete_state(self, state): """Delete a specified state from the LRS :param state: State document to be deleted :type state: :class:`tincan.documents.state_document.StateDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse` """ return self._delete_state( activity=state.activity, agent=state.agent, state_id=state.id, etag=state.etag )
python
def delete_state(self, state): """Delete a specified state from the LRS :param state: State document to be deleted :type state: :class:`tincan.documents.state_document.StateDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse` """ return self._delete_state( activity=state.activity, agent=state.agent, state_id=state.id, etag=state.etag )
[ "def", "delete_state", "(", "self", ",", "state", ")", ":", "return", "self", ".", "_delete_state", "(", "activity", "=", "state", ".", "activity", ",", "agent", "=", "state", ".", "agent", ",", "state_id", "=", "state", ".", "id", ",", "etag", "=", ...
Delete a specified state from the LRS :param state: State document to be deleted :type state: :class:`tincan.documents.state_document.StateDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Delete", "a", "specified", "state", "from", "the", "LRS" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L553-L566
train
26,133
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.retrieve_activity_profile
def retrieve_activity_profile(self, activity, profile_id): """Retrieve activity profile with the specified parameters :param activity: Activity object of the desired activity profile :type activity: :class:`tincan.activity.Activity` :param profile_id: UUID of the desired profile :type profile_id: str | unicode :return: LRS Response object with an activity profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(activity, Activity): activity = Activity(activity) request = HTTPRequest( method="GET", resource="activities/profile", ignore404=True ) request.query_params = { "profileId": profile_id, "activityId": activity.id } lrs_response = self._send_request(request) if lrs_response.success: doc = ActivityProfileDocument( id=profile_id, content=lrs_response.data, activity=activity ) headers = lrs_response.response.getheaders() if "lastModified" in headers and headers["lastModified"] is not None: doc.timestamp = headers["lastModified"] if "contentType" in headers and headers["contentType"] is not None: doc.content_type = headers["contentType"] if "etag" in headers and headers["etag"] is not None: doc.etag = headers["etag"] lrs_response.content = doc return lrs_response
python
def retrieve_activity_profile(self, activity, profile_id): """Retrieve activity profile with the specified parameters :param activity: Activity object of the desired activity profile :type activity: :class:`tincan.activity.Activity` :param profile_id: UUID of the desired profile :type profile_id: str | unicode :return: LRS Response object with an activity profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(activity, Activity): activity = Activity(activity) request = HTTPRequest( method="GET", resource="activities/profile", ignore404=True ) request.query_params = { "profileId": profile_id, "activityId": activity.id } lrs_response = self._send_request(request) if lrs_response.success: doc = ActivityProfileDocument( id=profile_id, content=lrs_response.data, activity=activity ) headers = lrs_response.response.getheaders() if "lastModified" in headers and headers["lastModified"] is not None: doc.timestamp = headers["lastModified"] if "contentType" in headers and headers["contentType"] is not None: doc.content_type = headers["contentType"] if "etag" in headers and headers["etag"] is not None: doc.etag = headers["etag"] lrs_response.content = doc return lrs_response
[ "def", "retrieve_activity_profile", "(", "self", ",", "activity", ",", "profile_id", ")", ":", "if", "not", "isinstance", "(", "activity", ",", "Activity", ")", ":", "activity", "=", "Activity", "(", "activity", ")", "request", "=", "HTTPRequest", "(", "meth...
Retrieve activity profile with the specified parameters :param activity: Activity object of the desired activity profile :type activity: :class:`tincan.activity.Activity` :param profile_id: UUID of the desired profile :type profile_id: str | unicode :return: LRS Response object with an activity profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Retrieve", "activity", "profile", "with", "the", "specified", "parameters" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L615-L655
train
26,134
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.save_activity_profile
def save_activity_profile(self, profile): """Save an activity profile doc to the LRS :param profile: Activity profile doc to be saved :type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument` :return: LRS Response object with the saved activity profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="PUT", resource="activities/profile", content=profile.content ) if profile.content_type is not None: request.headers["Content-Type"] = profile.content_type else: request.headers["Content-Type"] = "application/octet-stream" if profile.etag is not None: request.headers["If-Match"] = profile.etag request.query_params = { "profileId": profile.id, "activityId": profile.activity.id } lrs_response = self._send_request(request) lrs_response.content = profile return lrs_response
python
def save_activity_profile(self, profile): """Save an activity profile doc to the LRS :param profile: Activity profile doc to be saved :type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument` :return: LRS Response object with the saved activity profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="PUT", resource="activities/profile", content=profile.content ) if profile.content_type is not None: request.headers["Content-Type"] = profile.content_type else: request.headers["Content-Type"] = "application/octet-stream" if profile.etag is not None: request.headers["If-Match"] = profile.etag request.query_params = { "profileId": profile.id, "activityId": profile.activity.id } lrs_response = self._send_request(request) lrs_response.content = profile return lrs_response
[ "def", "save_activity_profile", "(", "self", ",", "profile", ")", ":", "request", "=", "HTTPRequest", "(", "method", "=", "\"PUT\"", ",", "resource", "=", "\"activities/profile\"", ",", "content", "=", "profile", ".", "content", ")", "if", "profile", ".", "c...
Save an activity profile doc to the LRS :param profile: Activity profile doc to be saved :type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument` :return: LRS Response object with the saved activity profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Save", "an", "activity", "profile", "doc", "to", "the", "LRS" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L657-L685
train
26,135
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.delete_activity_profile
def delete_activity_profile(self, profile): """Delete activity profile doc from LRS :param profile: Activity profile document to be deleted :type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="DELETE", resource="activities/profile" ) request.query_params = { "profileId": profile.id, "activityId": profile.activity.id } if profile.etag is not None: request.headers["If-Match"] = profile.etag return self._send_request(request)
python
def delete_activity_profile(self, profile): """Delete activity profile doc from LRS :param profile: Activity profile document to be deleted :type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="DELETE", resource="activities/profile" ) request.query_params = { "profileId": profile.id, "activityId": profile.activity.id } if profile.etag is not None: request.headers["If-Match"] = profile.etag return self._send_request(request)
[ "def", "delete_activity_profile", "(", "self", ",", "profile", ")", ":", "request", "=", "HTTPRequest", "(", "method", "=", "\"DELETE\"", ",", "resource", "=", "\"activities/profile\"", ")", "request", ".", "query_params", "=", "{", "\"profileId\"", ":", "profil...
Delete activity profile doc from LRS :param profile: Activity profile document to be deleted :type profile: :class:`tincan.documents.activity_profile_document.ActivityProfileDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Delete", "activity", "profile", "doc", "from", "LRS" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L687-L707
train
26,136
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.retrieve_agent_profile
def retrieve_agent_profile(self, agent, profile_id): """Retrieve agent profile with the specified parameters :param agent: Agent object of the desired agent profile :type agent: :class:`tincan.agent.Agent` :param profile_id: UUID of the desired agent profile :type profile_id: str | unicode :return: LRS Response object with an agent profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(agent, Agent): agent = Agent(agent) request = HTTPRequest( method="GET", resource="agents/profile", ignore404=True ) request.query_params = { "profileId": profile_id, "agent": agent.to_json(self.version) } lrs_response = self._send_request(request) if lrs_response.success: doc = AgentProfileDocument( id=profile_id, content=lrs_response.data, agent=agent ) headers = lrs_response.response.getheaders() if "lastModified" in headers and headers["lastModified"] is not None: doc.timestamp = headers["lastModified"] if "contentType" in headers and headers["contentType"] is not None: doc.content_type = headers["contentType"] if "etag" in headers and headers["etag"] is not None: doc.etag = headers["etag"] lrs_response.content = doc return lrs_response
python
def retrieve_agent_profile(self, agent, profile_id): """Retrieve agent profile with the specified parameters :param agent: Agent object of the desired agent profile :type agent: :class:`tincan.agent.Agent` :param profile_id: UUID of the desired agent profile :type profile_id: str | unicode :return: LRS Response object with an agent profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ if not isinstance(agent, Agent): agent = Agent(agent) request = HTTPRequest( method="GET", resource="agents/profile", ignore404=True ) request.query_params = { "profileId": profile_id, "agent": agent.to_json(self.version) } lrs_response = self._send_request(request) if lrs_response.success: doc = AgentProfileDocument( id=profile_id, content=lrs_response.data, agent=agent ) headers = lrs_response.response.getheaders() if "lastModified" in headers and headers["lastModified"] is not None: doc.timestamp = headers["lastModified"] if "contentType" in headers and headers["contentType"] is not None: doc.content_type = headers["contentType"] if "etag" in headers and headers["etag"] is not None: doc.etag = headers["etag"] lrs_response.content = doc return lrs_response
[ "def", "retrieve_agent_profile", "(", "self", ",", "agent", ",", "profile_id", ")", ":", "if", "not", "isinstance", "(", "agent", ",", "Agent", ")", ":", "agent", "=", "Agent", "(", "agent", ")", "request", "=", "HTTPRequest", "(", "method", "=", "\"GET\...
Retrieve agent profile with the specified parameters :param agent: Agent object of the desired agent profile :type agent: :class:`tincan.agent.Agent` :param profile_id: UUID of the desired agent profile :type profile_id: str | unicode :return: LRS Response object with an agent profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Retrieve", "agent", "profile", "with", "the", "specified", "parameters" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L738-L779
train
26,137
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.save_agent_profile
def save_agent_profile(self, profile): """Save an agent profile doc to the LRS :param profile: Agent profile doc to be saved :type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument` :return: LRS Response object with the saved agent profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="PUT", resource="agents/profile", content=profile.content, ) if profile.content_type is not None: request.headers["Content-Type"] = profile.content_type else: request.headers["Content-Type"] = "application/octet-stream" if profile.etag is not None: request.headers["If-Match"] = profile.etag request.query_params = { "profileId": profile.id, "agent": profile.agent.to_json(self.version) } lrs_response = self._send_request(request) lrs_response.content = profile return lrs_response
python
def save_agent_profile(self, profile): """Save an agent profile doc to the LRS :param profile: Agent profile doc to be saved :type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument` :return: LRS Response object with the saved agent profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="PUT", resource="agents/profile", content=profile.content, ) if profile.content_type is not None: request.headers["Content-Type"] = profile.content_type else: request.headers["Content-Type"] = "application/octet-stream" if profile.etag is not None: request.headers["If-Match"] = profile.etag request.query_params = { "profileId": profile.id, "agent": profile.agent.to_json(self.version) } lrs_response = self._send_request(request) lrs_response.content = profile return lrs_response
[ "def", "save_agent_profile", "(", "self", ",", "profile", ")", ":", "request", "=", "HTTPRequest", "(", "method", "=", "\"PUT\"", ",", "resource", "=", "\"agents/profile\"", ",", "content", "=", "profile", ".", "content", ",", ")", "if", "profile", ".", "c...
Save an agent profile doc to the LRS :param profile: Agent profile doc to be saved :type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument` :return: LRS Response object with the saved agent profile doc as content :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Save", "an", "agent", "profile", "doc", "to", "the", "LRS" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L781-L809
train
26,138
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.delete_agent_profile
def delete_agent_profile(self, profile): """Delete agent profile doc from LRS :param profile: Agent profile document to be deleted :type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="DELETE", resource="agents/profile" ) request.query_params = { "profileId": profile.id, "agent": profile.agent.to_json(self.version) } if profile.etag is not None: request.headers["If-Match"] = profile.etag return self._send_request(request)
python
def delete_agent_profile(self, profile): """Delete agent profile doc from LRS :param profile: Agent profile document to be deleted :type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse` """ request = HTTPRequest( method="DELETE", resource="agents/profile" ) request.query_params = { "profileId": profile.id, "agent": profile.agent.to_json(self.version) } if profile.etag is not None: request.headers["If-Match"] = profile.etag return self._send_request(request)
[ "def", "delete_agent_profile", "(", "self", ",", "profile", ")", ":", "request", "=", "HTTPRequest", "(", "method", "=", "\"DELETE\"", ",", "resource", "=", "\"agents/profile\"", ")", "request", ".", "query_params", "=", "{", "\"profileId\"", ":", "profile", "...
Delete agent profile doc from LRS :param profile: Agent profile document to be deleted :type profile: :class:`tincan.documents.agent_profile_document.AgentProfileDocument` :return: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse`
[ "Delete", "agent", "profile", "doc", "from", "LRS" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L811-L831
train
26,139
RusticiSoftware/TinCanPython
tincan/remote_lrs.py
RemoteLRS.get_endpoint_server_root
def get_endpoint_server_root(self): """Parses RemoteLRS object's endpoint and returns its root :return: Root of the RemoteLRS object endpoint :rtype: unicode """ parsed = urlparse(self._endpoint) root = parsed.scheme + "://" + parsed.hostname if parsed.port is not None: root += ":" + unicode(parsed.port) return root
python
def get_endpoint_server_root(self): """Parses RemoteLRS object's endpoint and returns its root :return: Root of the RemoteLRS object endpoint :rtype: unicode """ parsed = urlparse(self._endpoint) root = parsed.scheme + "://" + parsed.hostname if parsed.port is not None: root += ":" + unicode(parsed.port) return root
[ "def", "get_endpoint_server_root", "(", "self", ")", ":", "parsed", "=", "urlparse", "(", "self", ".", "_endpoint", ")", "root", "=", "parsed", ".", "scheme", "+", "\"://\"", "+", "parsed", ".", "hostname", "if", "parsed", ".", "port", "is", "not", "None...
Parses RemoteLRS object's endpoint and returns its root :return: Root of the RemoteLRS object endpoint :rtype: unicode
[ "Parses", "RemoteLRS", "object", "s", "endpoint", "and", "returns", "its", "root" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L894-L906
train
26,140
RusticiSoftware/TinCanPython
tincan/serializable_base.py
SerializableBase.from_json
def from_json(cls, json_data): """Tries to convert a JSON representation to an object of the same type as self A class can provide a _fromJSON implementation in order to do specific type checking or other custom implementation details. This method will throw a ValueError for invalid JSON, a TypeError for improperly constructed, but valid JSON, and any custom errors that can be be propagated from class constructors. :param json_data: The JSON string to convert :type json_data: str | unicode :raises: TypeError, ValueError, LanguageMapInitError """ data = json.loads(json_data) result = cls(data) if hasattr(result, "_from_json"): result._from_json() return result
python
def from_json(cls, json_data): """Tries to convert a JSON representation to an object of the same type as self A class can provide a _fromJSON implementation in order to do specific type checking or other custom implementation details. This method will throw a ValueError for invalid JSON, a TypeError for improperly constructed, but valid JSON, and any custom errors that can be be propagated from class constructors. :param json_data: The JSON string to convert :type json_data: str | unicode :raises: TypeError, ValueError, LanguageMapInitError """ data = json.loads(json_data) result = cls(data) if hasattr(result, "_from_json"): result._from_json() return result
[ "def", "from_json", "(", "cls", ",", "json_data", ")", ":", "data", "=", "json", ".", "loads", "(", "json_data", ")", "result", "=", "cls", "(", "data", ")", "if", "hasattr", "(", "result", ",", "\"_from_json\"", ")", ":", "result", ".", "_from_json", ...
Tries to convert a JSON representation to an object of the same type as self A class can provide a _fromJSON implementation in order to do specific type checking or other custom implementation details. This method will throw a ValueError for invalid JSON, a TypeError for improperly constructed, but valid JSON, and any custom errors that can be be propagated from class constructors. :param json_data: The JSON string to convert :type json_data: str | unicode :raises: TypeError, ValueError, LanguageMapInitError
[ "Tries", "to", "convert", "a", "JSON", "representation", "to", "an", "object", "of", "the", "same", "type", "as", "self" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/serializable_base.py#L70-L89
train
26,141
RusticiSoftware/TinCanPython
tincan/serializable_base.py
SerializableBase.to_json
def to_json(self, version=Version.latest): """Tries to convert an object into a JSON representation and return the resulting string An Object can define how it is serialized by overriding the as_version() implementation. A caller may further define how the object is serialized by passing in a custom encoder. The default encoder will ignore properties of an object that are None at the time of serialization. :param version: The version to which the object must be serialized to. This will default to the latest version supported by the library. :type version: str | unicode """ return json.dumps(self.as_version(version))
python
def to_json(self, version=Version.latest): """Tries to convert an object into a JSON representation and return the resulting string An Object can define how it is serialized by overriding the as_version() implementation. A caller may further define how the object is serialized by passing in a custom encoder. The default encoder will ignore properties of an object that are None at the time of serialization. :param version: The version to which the object must be serialized to. This will default to the latest version supported by the library. :type version: str | unicode """ return json.dumps(self.as_version(version))
[ "def", "to_json", "(", "self", ",", "version", "=", "Version", ".", "latest", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "as_version", "(", "version", ")", ")" ]
Tries to convert an object into a JSON representation and return the resulting string An Object can define how it is serialized by overriding the as_version() implementation. A caller may further define how the object is serialized by passing in a custom encoder. The default encoder will ignore properties of an object that are None at the time of serialization. :param version: The version to which the object must be serialized to. This will default to the latest version supported by the library. :type version: str | unicode
[ "Tries", "to", "convert", "an", "object", "into", "a", "JSON", "representation", "and", "return", "the", "resulting", "string" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/serializable_base.py#L91-L105
train
26,142
RusticiSoftware/TinCanPython
tincan/serializable_base.py
SerializableBase.as_version
def as_version(self, version=Version.latest): """Returns a dict that has been modified based on versioning in order to be represented in JSON properly A class should overload as_version(self, version) implementation in order to tailor a more specific representation :param version: the relevant version. This allows for variance between versions :type version: str | unicode """ if not isinstance(self, list): result = {} for k, v in self.iteritems() if isinstance(self, dict) else vars(self).iteritems(): k = self._props_corrected.get(k, k) if isinstance(v, SerializableBase): result[k] = v.as_version(version) elif isinstance(v, list): result[k] = [] for val in v: if isinstance(val, SerializableBase): result[k].append(val.as_version(version)) else: result[k].append(val) elif isinstance(v, uuid.UUID): result[k] = unicode(v) elif isinstance(v, datetime.timedelta): result[k] = jsonify_timedelta(v) elif isinstance(v, datetime.datetime): result[k] = jsonify_datetime(v) else: result[k] = v result = self._filter_none(result) else: result = [] for v in self: if isinstance(v, SerializableBase): result.append(v.as_version(version)) else: result.append(v) return result
python
def as_version(self, version=Version.latest): """Returns a dict that has been modified based on versioning in order to be represented in JSON properly A class should overload as_version(self, version) implementation in order to tailor a more specific representation :param version: the relevant version. This allows for variance between versions :type version: str | unicode """ if not isinstance(self, list): result = {} for k, v in self.iteritems() if isinstance(self, dict) else vars(self).iteritems(): k = self._props_corrected.get(k, k) if isinstance(v, SerializableBase): result[k] = v.as_version(version) elif isinstance(v, list): result[k] = [] for val in v: if isinstance(val, SerializableBase): result[k].append(val.as_version(version)) else: result[k].append(val) elif isinstance(v, uuid.UUID): result[k] = unicode(v) elif isinstance(v, datetime.timedelta): result[k] = jsonify_timedelta(v) elif isinstance(v, datetime.datetime): result[k] = jsonify_datetime(v) else: result[k] = v result = self._filter_none(result) else: result = [] for v in self: if isinstance(v, SerializableBase): result.append(v.as_version(version)) else: result.append(v) return result
[ "def", "as_version", "(", "self", ",", "version", "=", "Version", ".", "latest", ")", ":", "if", "not", "isinstance", "(", "self", ",", "list", ")", ":", "result", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "iteritems", "(", ")", "if...
Returns a dict that has been modified based on versioning in order to be represented in JSON properly A class should overload as_version(self, version) implementation in order to tailor a more specific representation :param version: the relevant version. This allows for variance between versions :type version: str | unicode
[ "Returns", "a", "dict", "that", "has", "been", "modified", "based", "on", "versioning", "in", "order", "to", "be", "represented", "in", "JSON", "properly" ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/serializable_base.py#L107-L148
train
26,143
RusticiSoftware/TinCanPython
tincan/serializable_base.py
SerializableBase._filter_none
def _filter_none(obj): """Filters out attributes set to None prior to serialization, and returns a new object without those attributes. This saves the serializer from sending empty bytes over the network. This method also fixes the keys to look as expected by ignoring a leading '_' if it is present. :param obj: the dictionary representation of an object that may have None attributes :type obj: dict """ result = {} for k, v in obj.iteritems(): if v is not None: if k.startswith('_'): k = k[1:] result[k] = v return result
python
def _filter_none(obj): """Filters out attributes set to None prior to serialization, and returns a new object without those attributes. This saves the serializer from sending empty bytes over the network. This method also fixes the keys to look as expected by ignoring a leading '_' if it is present. :param obj: the dictionary representation of an object that may have None attributes :type obj: dict """ result = {} for k, v in obj.iteritems(): if v is not None: if k.startswith('_'): k = k[1:] result[k] = v return result
[ "def", "_filter_none", "(", "obj", ")", ":", "result", "=", "{", "}", "for", "k", ",", "v", "in", "obj", ".", "iteritems", "(", ")", ":", "if", "v", "is", "not", "None", ":", "if", "k", ".", "startswith", "(", "'_'", ")", ":", "k", "=", "k", ...
Filters out attributes set to None prior to serialization, and returns a new object without those attributes. This saves the serializer from sending empty bytes over the network. This method also fixes the keys to look as expected by ignoring a leading '_' if it is present. :param obj: the dictionary representation of an object that may have None attributes :type obj: dict
[ "Filters", "out", "attributes", "set", "to", "None", "prior", "to", "serialization", "and", "returns", "a", "new", "object", "without", "those", "attributes", ".", "This", "saves", "the", "serializer", "from", "sending", "empty", "bytes", "over", "the", "netwo...
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/serializable_base.py#L151-L169
train
26,144
RusticiSoftware/TinCanPython
tincan/conversions/iso8601.py
jsonify_timedelta
def jsonify_timedelta(value): """Converts a `datetime.timedelta` to an ISO 8601 duration string for JSON-ification. :param value: something to convert :type value: datetime.timedelta :return: the value after conversion :rtype unicode """ assert isinstance(value, datetime.timedelta) # split seconds to larger units seconds = value.total_seconds() minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) days, hours, minutes = map(int, (days, hours, minutes)) seconds = round(seconds, 6) # build date date = '' if days: date = '%sD' % days # build time time = u'T' # hours bigger_exists = date or hours if bigger_exists: time += '{:02}H'.format(hours) # minutes bigger_exists = bigger_exists or minutes if bigger_exists: time += '{:02}M'.format(minutes) # seconds if seconds.is_integer(): seconds = '{:02}'.format(int(seconds)) else: # 9 chars long w/leading 0, 6 digits after decimal seconds = '%09.6f' % seconds # remove trailing zeros seconds = seconds.rstrip('0') time += '{}S'.format(seconds) return u'P' + date + time
python
def jsonify_timedelta(value): """Converts a `datetime.timedelta` to an ISO 8601 duration string for JSON-ification. :param value: something to convert :type value: datetime.timedelta :return: the value after conversion :rtype unicode """ assert isinstance(value, datetime.timedelta) # split seconds to larger units seconds = value.total_seconds() minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) days, hours, minutes = map(int, (days, hours, minutes)) seconds = round(seconds, 6) # build date date = '' if days: date = '%sD' % days # build time time = u'T' # hours bigger_exists = date or hours if bigger_exists: time += '{:02}H'.format(hours) # minutes bigger_exists = bigger_exists or minutes if bigger_exists: time += '{:02}M'.format(minutes) # seconds if seconds.is_integer(): seconds = '{:02}'.format(int(seconds)) else: # 9 chars long w/leading 0, 6 digits after decimal seconds = '%09.6f' % seconds # remove trailing zeros seconds = seconds.rstrip('0') time += '{}S'.format(seconds) return u'P' + date + time
[ "def", "jsonify_timedelta", "(", "value", ")", ":", "assert", "isinstance", "(", "value", ",", "datetime", ".", "timedelta", ")", "# split seconds to larger units", "seconds", "=", "value", ".", "total_seconds", "(", ")", "minutes", ",", "seconds", "=", "divmod"...
Converts a `datetime.timedelta` to an ISO 8601 duration string for JSON-ification. :param value: something to convert :type value: datetime.timedelta :return: the value after conversion :rtype unicode
[ "Converts", "a", "datetime", ".", "timedelta", "to", "an", "ISO", "8601", "duration", "string", "for", "JSON", "-", "ification", "." ]
424eedaa6d19221efb1108edb915fc332abbb317
https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/conversions/iso8601.py#L84-L135
train
26,145
globality-corp/microcosm
microcosm/config/validation.py
zip_dicts
def zip_dicts(left, right, prefix=()): """ Modified zip through two dictionaries. Iterate through all keys of left dictionary, returning: - A nested path - A value and parent for both dictionaries """ for key, left_value in left.items(): path = prefix + (key, ) right_value = right.get(key) if isinstance(left_value, dict): yield from zip_dicts(left_value, right_value or {}, path) else: yield path, left, left_value, right, right_value
python
def zip_dicts(left, right, prefix=()): """ Modified zip through two dictionaries. Iterate through all keys of left dictionary, returning: - A nested path - A value and parent for both dictionaries """ for key, left_value in left.items(): path = prefix + (key, ) right_value = right.get(key) if isinstance(left_value, dict): yield from zip_dicts(left_value, right_value or {}, path) else: yield path, left, left_value, right, right_value
[ "def", "zip_dicts", "(", "left", ",", "right", ",", "prefix", "=", "(", ")", ")", ":", "for", "key", ",", "left_value", "in", "left", ".", "items", "(", ")", ":", "path", "=", "prefix", "+", "(", "key", ",", ")", "right_value", "=", "right", ".",...
Modified zip through two dictionaries. Iterate through all keys of left dictionary, returning: - A nested path - A value and parent for both dictionaries
[ "Modified", "zip", "through", "two", "dictionaries", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/config/validation.py#L35-L52
train
26,146
globality-corp/microcosm
microcosm/config/api.py
configure
def configure(defaults, metadata, loader): """ Build a fresh configuration. :params defaults: a nested dictionary of keys and their default values :params metadata: the graph metadata :params loader: a configuration loader """ config = Configuration(defaults) config.merge(loader(metadata)) validate(defaults, metadata, config) return config
python
def configure(defaults, metadata, loader): """ Build a fresh configuration. :params defaults: a nested dictionary of keys and their default values :params metadata: the graph metadata :params loader: a configuration loader """ config = Configuration(defaults) config.merge(loader(metadata)) validate(defaults, metadata, config) return config
[ "def", "configure", "(", "defaults", ",", "metadata", ",", "loader", ")", ":", "config", "=", "Configuration", "(", "defaults", ")", "config", ".", "merge", "(", "loader", "(", "metadata", ")", ")", "validate", "(", "defaults", ",", "metadata", ",", "con...
Build a fresh configuration. :params defaults: a nested dictionary of keys and their default values :params metadata: the graph metadata :params loader: a configuration loader
[ "Build", "a", "fresh", "configuration", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/config/api.py#L9-L21
train
26,147
globality-corp/microcosm
microcosm/config/types.py
boolean
def boolean(value): """ Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars). """ if isinstance(value, bool): return value if value == "": return False return strtobool(value)
python
def boolean(value): """ Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars). """ if isinstance(value, bool): return value if value == "": return False return strtobool(value)
[ "def", "boolean", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "value", "if", "value", "==", "\"\"", ":", "return", "False", "return", "strtobool", "(", "value", ")" ]
Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars).
[ "Configuration", "-", "friendly", "boolean", "type", "converter", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/config/types.py#L8-L21
train
26,148
globality-corp/microcosm
microcosm/loaders/environment.py
_load_from_environ
def _load_from_environ(metadata, value_func=None): """ Load configuration from environment variables. Any environment variable prefixed with the metadata's name will be used to recursively set dictionary keys, splitting on '__'. :param value_func: a mutator for the envvar's value (if any) """ # We'll match the ennvar name against the metadata's name. The ennvar # name must be uppercase and hyphens in names converted to underscores. # # | envar | name | matches? | # +-------------+---------+----------+ # | FOO_BAR | foo | yes | # | FOO_BAR | bar | no | # | foo_bar | bar | no | # | FOO_BAR_BAZ | foo_bar | yes | # | FOO_BAR_BAZ | foo-bar | yes | # +-------------+---------+----------+ prefix = metadata.name.upper().replace("-", "_") return expand_config( environ, separator="__", skip_to=1, key_parts_filter=lambda key_parts: len(key_parts) > 1 and key_parts[0] == prefix, value_func=lambda value: value_func(value) if value_func else value, )
python
def _load_from_environ(metadata, value_func=None): """ Load configuration from environment variables. Any environment variable prefixed with the metadata's name will be used to recursively set dictionary keys, splitting on '__'. :param value_func: a mutator for the envvar's value (if any) """ # We'll match the ennvar name against the metadata's name. The ennvar # name must be uppercase and hyphens in names converted to underscores. # # | envar | name | matches? | # +-------------+---------+----------+ # | FOO_BAR | foo | yes | # | FOO_BAR | bar | no | # | foo_bar | bar | no | # | FOO_BAR_BAZ | foo_bar | yes | # | FOO_BAR_BAZ | foo-bar | yes | # +-------------+---------+----------+ prefix = metadata.name.upper().replace("-", "_") return expand_config( environ, separator="__", skip_to=1, key_parts_filter=lambda key_parts: len(key_parts) > 1 and key_parts[0] == prefix, value_func=lambda value: value_func(value) if value_func else value, )
[ "def", "_load_from_environ", "(", "metadata", ",", "value_func", "=", "None", ")", ":", "# We'll match the ennvar name against the metadata's name. The ennvar", "# name must be uppercase and hyphens in names converted to underscores.", "#", "# | envar | name | matches? |", "# +-...
Load configuration from environment variables. Any environment variable prefixed with the metadata's name will be used to recursively set dictionary keys, splitting on '__'. :param value_func: a mutator for the envvar's value (if any)
[ "Load", "configuration", "from", "environment", "variables", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/environment.py#L13-L43
train
26,149
globality-corp/microcosm
microcosm/loaders/__init__.py
load_from_dict
def load_from_dict(dct=None, **kwargs): """ Load configuration from a dictionary. """ dct = dct or dict() dct.update(kwargs) def _load_from_dict(metadata): return dict(dct) return _load_from_dict
python
def load_from_dict(dct=None, **kwargs): """ Load configuration from a dictionary. """ dct = dct or dict() dct.update(kwargs) def _load_from_dict(metadata): return dict(dct) return _load_from_dict
[ "def", "load_from_dict", "(", "dct", "=", "None", ",", "*", "*", "kwargs", ")", ":", "dct", "=", "dct", "or", "dict", "(", ")", "dct", ".", "update", "(", "kwargs", ")", "def", "_load_from_dict", "(", "metadata", ")", ":", "return", "dict", "(", "d...
Load configuration from a dictionary.
[ "Load", "configuration", "from", "a", "dictionary", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/__init__.py#L26-L36
train
26,150
globality-corp/microcosm
microcosm/decorators.py
binding
def binding(key, registry=None): """ Creates a decorator that binds a factory function to a key. :param key: the binding key :param: registry: the registry to bind to; defaults to the global registry """ if registry is None: registry = _registry def decorator(func): registry.bind(key, func) return func return decorator
python
def binding(key, registry=None): """ Creates a decorator that binds a factory function to a key. :param key: the binding key :param: registry: the registry to bind to; defaults to the global registry """ if registry is None: registry = _registry def decorator(func): registry.bind(key, func) return func return decorator
[ "def", "binding", "(", "key", ",", "registry", "=", "None", ")", ":", "if", "registry", "is", "None", ":", "registry", "=", "_registry", "def", "decorator", "(", "func", ")", ":", "registry", ".", "bind", "(", "key", ",", "func", ")", "return", "func...
Creates a decorator that binds a factory function to a key. :param key: the binding key :param: registry: the registry to bind to; defaults to the global registry
[ "Creates", "a", "decorator", "that", "binds", "a", "factory", "function", "to", "a", "key", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/decorators.py#L9-L23
train
26,151
globality-corp/microcosm
microcosm/decorators.py
defaults
def defaults(**kwargs): """ Creates a decorator that saves the provided kwargs as defaults for a factory function. """ def decorator(func): setattr(func, DEFAULTS, kwargs) return func return decorator
python
def defaults(**kwargs): """ Creates a decorator that saves the provided kwargs as defaults for a factory function. """ def decorator(func): setattr(func, DEFAULTS, kwargs) return func return decorator
[ "def", "defaults", "(", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "setattr", "(", "func", ",", "DEFAULTS", ",", "kwargs", ")", "return", "func", "return", "decorator" ]
Creates a decorator that saves the provided kwargs as defaults for a factory function.
[ "Creates", "a", "decorator", "that", "saves", "the", "provided", "kwargs", "as", "defaults", "for", "a", "factory", "function", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/decorators.py#L26-L34
train
26,152
globality-corp/microcosm
microcosm/hooks.py
_invoke_hook
def _invoke_hook(hook_name, target): """ Generic hook invocation. """ try: for value in getattr(target, hook_name): func, args, kwargs = value func(target, *args, **kwargs) except AttributeError: # no hook defined pass except (TypeError, ValueError): # hook not properly defined (might be a mock) pass
python
def _invoke_hook(hook_name, target): """ Generic hook invocation. """ try: for value in getattr(target, hook_name): func, args, kwargs = value func(target, *args, **kwargs) except AttributeError: # no hook defined pass except (TypeError, ValueError): # hook not properly defined (might be a mock) pass
[ "def", "_invoke_hook", "(", "hook_name", ",", "target", ")", ":", "try", ":", "for", "value", "in", "getattr", "(", "target", ",", "hook_name", ")", ":", "func", ",", "args", ",", "kwargs", "=", "value", "func", "(", "target", ",", "*", "args", ",", ...
Generic hook invocation.
[ "Generic", "hook", "invocation", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/hooks.py#L45-L59
train
26,153
globality-corp/microcosm
microcosm/hooks.py
_register_hook
def _register_hook(hook_name, target, func, *args, **kwargs): """ Generic hook registration. """ call = (func, args, kwargs) try: getattr(target, hook_name).append(call) except AttributeError: setattr(target, hook_name, [call])
python
def _register_hook(hook_name, target, func, *args, **kwargs): """ Generic hook registration. """ call = (func, args, kwargs) try: getattr(target, hook_name).append(call) except AttributeError: setattr(target, hook_name, [call])
[ "def", "_register_hook", "(", "hook_name", ",", "target", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "call", "=", "(", "func", ",", "args", ",", "kwargs", ")", "try", ":", "getattr", "(", "target", ",", "hook_name", ")", ".",...
Generic hook registration.
[ "Generic", "hook", "registration", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/hooks.py#L62-L71
train
26,154
globality-corp/microcosm
microcosm/hooks.py
on_resolve
def on_resolve(target, func, *args, **kwargs): """ Register a resolution hook. """ return _register_hook(ON_RESOLVE, target, func, *args, **kwargs)
python
def on_resolve(target, func, *args, **kwargs): """ Register a resolution hook. """ return _register_hook(ON_RESOLVE, target, func, *args, **kwargs)
[ "def", "on_resolve", "(", "target", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_register_hook", "(", "ON_RESOLVE", ",", "target", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Register a resolution hook.
[ "Register", "a", "resolution", "hook", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/hooks.py#L82-L87
train
26,155
globality-corp/microcosm
microcosm/caching.py
create_cache
def create_cache(name): """ Create a cache by name. Defaults to `NaiveCache` """ caches = { subclass.name(): subclass for subclass in Cache.__subclasses__() } return caches.get(name, NaiveCache)()
python
def create_cache(name): """ Create a cache by name. Defaults to `NaiveCache` """ caches = { subclass.name(): subclass for subclass in Cache.__subclasses__() } return caches.get(name, NaiveCache)()
[ "def", "create_cache", "(", "name", ")", ":", "caches", "=", "{", "subclass", ".", "name", "(", ")", ":", "subclass", "for", "subclass", "in", "Cache", ".", "__subclasses__", "(", ")", "}", "return", "caches", ".", "get", "(", "name", ",", "NaiveCache"...
Create a cache by name. Defaults to `NaiveCache`
[ "Create", "a", "cache", "by", "name", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/caching.py#L92-L103
train
26,156
globality-corp/microcosm
microcosm/loaders/settings.py
get_config_filename
def get_config_filename(metadata): """ Derive a configuration file name from the FOO_SETTINGS environment variable. """ envvar = "{}__SETTINGS".format(underscore(metadata.name).upper()) try: return environ[envvar] except KeyError: return None
python
def get_config_filename(metadata): """ Derive a configuration file name from the FOO_SETTINGS environment variable. """ envvar = "{}__SETTINGS".format(underscore(metadata.name).upper()) try: return environ[envvar] except KeyError: return None
[ "def", "get_config_filename", "(", "metadata", ")", ":", "envvar", "=", "\"{}__SETTINGS\"", ".", "format", "(", "underscore", "(", "metadata", ".", "name", ")", ".", "upper", "(", ")", ")", "try", ":", "return", "environ", "[", "envvar", "]", "except", "...
Derive a configuration file name from the FOO_SETTINGS environment variable.
[ "Derive", "a", "configuration", "file", "name", "from", "the", "FOO_SETTINGS", "environment", "variable", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/settings.py#L14-L24
train
26,157
globality-corp/microcosm
microcosm/loaders/settings.py
_load_from_file
def _load_from_file(metadata, load_func): """ Load configuration from a file. The file path is derived from an environment variable named after the service of the form FOO_SETTINGS. """ config_filename = get_config_filename(metadata) if config_filename is None: return dict() with open(config_filename, "r") as file_: data = load_func(file_.read()) return dict(data)
python
def _load_from_file(metadata, load_func): """ Load configuration from a file. The file path is derived from an environment variable named after the service of the form FOO_SETTINGS. """ config_filename = get_config_filename(metadata) if config_filename is None: return dict() with open(config_filename, "r") as file_: data = load_func(file_.read()) return dict(data)
[ "def", "_load_from_file", "(", "metadata", ",", "load_func", ")", ":", "config_filename", "=", "get_config_filename", "(", "metadata", ")", "if", "config_filename", "is", "None", ":", "return", "dict", "(", ")", "with", "open", "(", "config_filename", ",", "\"...
Load configuration from a file. The file path is derived from an environment variable named after the service of the form FOO_SETTINGS.
[ "Load", "configuration", "from", "a", "file", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/settings.py#L27-L41
train
26,158
globality-corp/microcosm
microcosm/scoping/factories.py
ScopedFactory.get_scoped_config
def get_scoped_config(self, graph): """ Compute a configuration using the current scope. """ def loader(metadata): if not self.current_scope: target = graph.config else: target = graph.config.get(self.current_scope, {}) return { self.key: target.get(self.key, {}), } defaults = { self.key: get_defaults(self.func), } return configure(defaults, graph.metadata, loader)
python
def get_scoped_config(self, graph): """ Compute a configuration using the current scope. """ def loader(metadata): if not self.current_scope: target = graph.config else: target = graph.config.get(self.current_scope, {}) return { self.key: target.get(self.key, {}), } defaults = { self.key: get_defaults(self.func), } return configure(defaults, graph.metadata, loader)
[ "def", "get_scoped_config", "(", "self", ",", "graph", ")", ":", "def", "loader", "(", "metadata", ")", ":", "if", "not", "self", ".", "current_scope", ":", "target", "=", "graph", ".", "config", "else", ":", "target", "=", "graph", ".", "config", ".",...
Compute a configuration using the current scope.
[ "Compute", "a", "configuration", "using", "the", "current", "scope", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/factories.py#L46-L63
train
26,159
globality-corp/microcosm
microcosm/scoping/factories.py
ScopedFactory.resolve
def resolve(self, graph): """ Resolve a scoped component, respecting the graph cache. """ cached = graph.get(self.scoped_key) if cached: return cached component = self.create(graph) graph.assign(self.scoped_key, component) return component
python
def resolve(self, graph): """ Resolve a scoped component, respecting the graph cache. """ cached = graph.get(self.scoped_key) if cached: return cached component = self.create(graph) graph.assign(self.scoped_key, component) return component
[ "def", "resolve", "(", "self", ",", "graph", ")", ":", "cached", "=", "graph", ".", "get", "(", "self", ".", "scoped_key", ")", "if", "cached", ":", "return", "cached", "component", "=", "self", ".", "create", "(", "graph", ")", "graph", ".", "assign...
Resolve a scoped component, respecting the graph cache.
[ "Resolve", "a", "scoped", "component", "respecting", "the", "graph", "cache", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/factories.py#L73-L84
train
26,160
globality-corp/microcosm
microcosm/scoping/factories.py
ScopedFactory.create
def create(self, graph): """ Create a new scoped component. """ scoped_config = self.get_scoped_config(graph) scoped_graph = ScopedGraph(graph, scoped_config) return self.func(scoped_graph)
python
def create(self, graph): """ Create a new scoped component. """ scoped_config = self.get_scoped_config(graph) scoped_graph = ScopedGraph(graph, scoped_config) return self.func(scoped_graph)
[ "def", "create", "(", "self", ",", "graph", ")", ":", "scoped_config", "=", "self", ".", "get_scoped_config", "(", "graph", ")", "scoped_graph", "=", "ScopedGraph", "(", "graph", ",", "scoped_config", ")", "return", "self", ".", "func", "(", "scoped_graph", ...
Create a new scoped component.
[ "Create", "a", "new", "scoped", "component", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/factories.py#L86-L93
train
26,161
globality-corp/microcosm
microcosm/scoping/factories.py
ScopedFactory.infect
def infect(cls, graph, key, default_scope=None): """ Forcibly convert an entry-point based factory to a ScopedFactory. Must be invoked before resolving the entry point. :raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding """ func = graph.factory_for(key) if isinstance(func, cls): func = func.func factory = cls(key, func, default_scope) graph._registry.factories[key] = factory return factory
python
def infect(cls, graph, key, default_scope=None): """ Forcibly convert an entry-point based factory to a ScopedFactory. Must be invoked before resolving the entry point. :raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding """ func = graph.factory_for(key) if isinstance(func, cls): func = func.func factory = cls(key, func, default_scope) graph._registry.factories[key] = factory return factory
[ "def", "infect", "(", "cls", ",", "graph", ",", "key", ",", "default_scope", "=", "None", ")", ":", "func", "=", "graph", ".", "factory_for", "(", "key", ")", "if", "isinstance", "(", "func", ",", "cls", ")", ":", "func", "=", "func", ".", "func", ...
Forcibly convert an entry-point based factory to a ScopedFactory. Must be invoked before resolving the entry point. :raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding
[ "Forcibly", "convert", "an", "entry", "-", "point", "based", "factory", "to", "a", "ScopedFactory", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/factories.py#L96-L110
train
26,162
globality-corp/microcosm
microcosm/loaders/compose.py
load_each
def load_each(*loaders): """ Loader factory that combines a series of loaders. """ def _load_each(metadata): return merge( loader(metadata) for loader in loaders ) return _load_each
python
def load_each(*loaders): """ Loader factory that combines a series of loaders. """ def _load_each(metadata): return merge( loader(metadata) for loader in loaders ) return _load_each
[ "def", "load_each", "(", "*", "loaders", ")", ":", "def", "_load_each", "(", "metadata", ")", ":", "return", "merge", "(", "loader", "(", "metadata", ")", "for", "loader", "in", "loaders", ")", "return", "_load_each" ]
Loader factory that combines a series of loaders.
[ "Loader", "factory", "that", "combines", "a", "series", "of", "loaders", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/compose.py#L17-L27
train
26,163
globality-corp/microcosm
microcosm/registry.py
Registry.all
def all(self): """ Return a synthetic dictionary of all factories. """ return { key: value for key, value in chain(self.entry_points.items(), self.factories.items()) }
python
def all(self): """ Return a synthetic dictionary of all factories. """ return { key: value for key, value in chain(self.entry_points.items(), self.factories.items()) }
[ "def", "all", "(", "self", ")", ":", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "chain", "(", "self", ".", "entry_points", ".", "items", "(", ")", ",", "self", ".", "factories", ".", "items", "(", ")", ")", "}" ]
Return a synthetic dictionary of all factories.
[ "Return", "a", "synthetic", "dictionary", "of", "all", "factories", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/registry.py#L43-L51
train
26,164
globality-corp/microcosm
microcosm/registry.py
Registry.defaults
def defaults(self): """ Return a nested dicionary of all registered factory defaults. """ return { key: get_defaults(value) for key, value in self.all.items() }
python
def defaults(self): """ Return a nested dicionary of all registered factory defaults. """ return { key: get_defaults(value) for key, value in self.all.items() }
[ "def", "defaults", "(", "self", ")", ":", "return", "{", "key", ":", "get_defaults", "(", "value", ")", "for", "key", ",", "value", "in", "self", ".", "all", ".", "items", "(", ")", "}" ]
Return a nested dicionary of all registered factory defaults.
[ "Return", "a", "nested", "dicionary", "of", "all", "registered", "factory", "defaults", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/registry.py#L54-L62
train
26,165
globality-corp/microcosm
microcosm/registry.py
Registry.bind
def bind(self, key, factory): """ Bind a factory to a key. :raises AlreadyBoundError: if the key is alrady bound """ if key in self.factories: raise AlreadyBoundError(key) else: self.factories[key] = factory
python
def bind(self, key, factory): """ Bind a factory to a key. :raises AlreadyBoundError: if the key is alrady bound """ if key in self.factories: raise AlreadyBoundError(key) else: self.factories[key] = factory
[ "def", "bind", "(", "self", ",", "key", ",", "factory", ")", ":", "if", "key", "in", "self", ".", "factories", ":", "raise", "AlreadyBoundError", "(", "key", ")", "else", ":", "self", ".", "factories", "[", "key", "]", "=", "factory" ]
Bind a factory to a key. :raises AlreadyBoundError: if the key is alrady bound
[ "Bind", "a", "factory", "to", "a", "key", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/registry.py#L64-L74
train
26,166
globality-corp/microcosm
microcosm/registry.py
Registry.resolve
def resolve(self, key): """ Resolve a key to a factory. Attempts to resolve explicit bindings and entry points, preferring explicit bindings. :raises NotBoundError: if the key cannot be resolved """ try: return self._resolve_from_binding(key) except NotBoundError: return self._resolve_from_entry_point(key)
python
def resolve(self, key): """ Resolve a key to a factory. Attempts to resolve explicit bindings and entry points, preferring explicit bindings. :raises NotBoundError: if the key cannot be resolved """ try: return self._resolve_from_binding(key) except NotBoundError: return self._resolve_from_entry_point(key)
[ "def", "resolve", "(", "self", ",", "key", ")", ":", "try", ":", "return", "self", ".", "_resolve_from_binding", "(", "key", ")", "except", "NotBoundError", ":", "return", "self", ".", "_resolve_from_entry_point", "(", "key", ")" ]
Resolve a key to a factory. Attempts to resolve explicit bindings and entry points, preferring explicit bindings. :raises NotBoundError: if the key cannot be resolved
[ "Resolve", "a", "key", "to", "a", "factory", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/registry.py#L76-L89
train
26,167
globality-corp/microcosm
microcosm/loaders/keys.py
expand_config
def expand_config(dct, separator='.', skip_to=0, key_func=lambda key: key.lower(), key_parts_filter=lambda key_parts: True, value_func=lambda value: value): """ Expand a dictionary recursively by splitting keys along the separator. :param dct: a non-recursive dictionary :param separator: a separator charactor for splitting dictionary keys :param skip_to: index to start splitting keys on; can be used to skip over a key prefix :param key_func: a key mapping function :param key_parts_filter: a filter function for excluding keys :param value_func: a value mapping func """ config = {} for key, value in dct.items(): key_separator = separator(key) if callable(separator) else separator key_parts = key.split(key_separator) if not key_parts_filter(key_parts): continue key_config = config # skip prefix for key_part in key_parts[skip_to:-1]: key_config = key_config.setdefault(key_func(key_part), dict()) key_config[key_func(key_parts[-1])] = value_func(value) return config
python
def expand_config(dct, separator='.', skip_to=0, key_func=lambda key: key.lower(), key_parts_filter=lambda key_parts: True, value_func=lambda value: value): """ Expand a dictionary recursively by splitting keys along the separator. :param dct: a non-recursive dictionary :param separator: a separator charactor for splitting dictionary keys :param skip_to: index to start splitting keys on; can be used to skip over a key prefix :param key_func: a key mapping function :param key_parts_filter: a filter function for excluding keys :param value_func: a value mapping func """ config = {} for key, value in dct.items(): key_separator = separator(key) if callable(separator) else separator key_parts = key.split(key_separator) if not key_parts_filter(key_parts): continue key_config = config # skip prefix for key_part in key_parts[skip_to:-1]: key_config = key_config.setdefault(key_func(key_part), dict()) key_config[key_func(key_parts[-1])] = value_func(value) return config
[ "def", "expand_config", "(", "dct", ",", "separator", "=", "'.'", ",", "skip_to", "=", "0", ",", "key_func", "=", "lambda", "key", ":", "key", ".", "lower", "(", ")", ",", "key_parts_filter", "=", "lambda", "key_parts", ":", "True", ",", "value_func", ...
Expand a dictionary recursively by splitting keys along the separator. :param dct: a non-recursive dictionary :param separator: a separator charactor for splitting dictionary keys :param skip_to: index to start splitting keys on; can be used to skip over a key prefix :param key_func: a key mapping function :param key_parts_filter: a filter function for excluding keys :param value_func: a value mapping func
[ "Expand", "a", "dictionary", "recursively", "by", "splitting", "keys", "along", "the", "separator", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/loaders/keys.py#L7-L37
train
26,168
globality-corp/microcosm
microcosm/object_graph.py
create_object_graph
def create_object_graph(name, debug=False, testing=False, import_name=None, root_path=None, loader=load_from_environ, registry=_registry, profiler=None, cache=None): """ Create a new object graph. :param name: the name of the microservice :param debug: is development debugging enabled? :param testing: is unit testing enabled? :param loader: the configuration loader to use :param registry: the registry to use (defaults to the global) """ metadata = Metadata( name=name, debug=debug, testing=testing, import_name=import_name, root_path=root_path, ) defaults = registry.defaults config = configure(defaults, metadata, loader) if profiler is None: profiler = NoopProfiler() if cache is None or isinstance(cache, str): cache = create_cache(cache) return ObjectGraph( metadata=metadata, config=config, registry=registry, profiler=profiler, cache=cache, loader=loader, )
python
def create_object_graph(name, debug=False, testing=False, import_name=None, root_path=None, loader=load_from_environ, registry=_registry, profiler=None, cache=None): """ Create a new object graph. :param name: the name of the microservice :param debug: is development debugging enabled? :param testing: is unit testing enabled? :param loader: the configuration loader to use :param registry: the registry to use (defaults to the global) """ metadata = Metadata( name=name, debug=debug, testing=testing, import_name=import_name, root_path=root_path, ) defaults = registry.defaults config = configure(defaults, metadata, loader) if profiler is None: profiler = NoopProfiler() if cache is None or isinstance(cache, str): cache = create_cache(cache) return ObjectGraph( metadata=metadata, config=config, registry=registry, profiler=profiler, cache=cache, loader=loader, )
[ "def", "create_object_graph", "(", "name", ",", "debug", "=", "False", ",", "testing", "=", "False", ",", "import_name", "=", "None", ",", "root_path", "=", "None", ",", "loader", "=", "load_from_environ", ",", "registry", "=", "_registry", ",", "profiler", ...
Create a new object graph. :param name: the name of the microservice :param debug: is development debugging enabled? :param testing: is unit testing enabled? :param loader: the configuration loader to use :param registry: the registry to use (defaults to the global)
[ "Create", "a", "new", "object", "graph", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/object_graph.py#L143-L186
train
26,169
globality-corp/microcosm
microcosm/object_graph.py
ObjectGraph._reserve
def _reserve(self, key): """ Reserve a component's binding temporarily. Protects against cycles. """ self.assign(key, RESERVED) try: yield finally: del self._cache[key]
python
def _reserve(self, key): """ Reserve a component's binding temporarily. Protects against cycles. """ self.assign(key, RESERVED) try: yield finally: del self._cache[key]
[ "def", "_reserve", "(", "self", ",", "key", ")", ":", "self", ".", "assign", "(", "key", ",", "RESERVED", ")", "try", ":", "yield", "finally", ":", "del", "self", ".", "_cache", "[", "key", "]" ]
Reserve a component's binding temporarily. Protects against cycles.
[ "Reserve", "a", "component", "s", "binding", "temporarily", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/object_graph.py#L111-L122
train
26,170
globality-corp/microcosm
microcosm/object_graph.py
ObjectGraph._resolve_key
def _resolve_key(self, key): """ Attempt to lazily create a component. :raises NotBoundError: if the component does not have a bound factory :raises CyclicGraphError: if the factory function requires a cycle :raises LockedGraphError: if the graph is locked """ with self._reserve(key): factory = self.factory_for(key) with self._profiler(key): component = factory(self) invoke_resolve_hook(component) return self.assign(key, component)
python
def _resolve_key(self, key): """ Attempt to lazily create a component. :raises NotBoundError: if the component does not have a bound factory :raises CyclicGraphError: if the factory function requires a cycle :raises LockedGraphError: if the graph is locked """ with self._reserve(key): factory = self.factory_for(key) with self._profiler(key): component = factory(self) invoke_resolve_hook(component) return self.assign(key, component)
[ "def", "_resolve_key", "(", "self", ",", "key", ")", ":", "with", "self", ".", "_reserve", "(", "key", ")", ":", "factory", "=", "self", ".", "factory_for", "(", "key", ")", "with", "self", ".", "_profiler", "(", "key", ")", ":", "component", "=", ...
Attempt to lazily create a component. :raises NotBoundError: if the component does not have a bound factory :raises CyclicGraphError: if the factory function requires a cycle :raises LockedGraphError: if the graph is locked
[ "Attempt", "to", "lazily", "create", "a", "component", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/object_graph.py#L124-L138
train
26,171
globality-corp/microcosm
microcosm/scoping/proxies.py
ScopedProxy.scoped_to
def scoped_to(self, scope): """ Context manager to switch scopes. """ previous_scope = self.__factory__.current_scope try: self.__factory__.current_scope = scope yield finally: self.__factory__.current_scope = previous_scope
python
def scoped_to(self, scope): """ Context manager to switch scopes. """ previous_scope = self.__factory__.current_scope try: self.__factory__.current_scope = scope yield finally: self.__factory__.current_scope = previous_scope
[ "def", "scoped_to", "(", "self", ",", "scope", ")", ":", "previous_scope", "=", "self", ".", "__factory__", ".", "current_scope", "try", ":", "self", ".", "__factory__", ".", "current_scope", "=", "scope", "yield", "finally", ":", "self", ".", "__factory__",...
Context manager to switch scopes.
[ "Context", "manager", "to", "switch", "scopes", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/proxies.py#L62-L72
train
26,172
globality-corp/microcosm
microcosm/scoping/proxies.py
ScopedProxy.scoped
def scoped(self, func): """ Decorator to switch scopes. """ @wraps(func) def wrapper(*args, **kwargs): scope = kwargs.get("scope", self.__factory__.default_scope) with self.scoped_to(scope): return func(*args, **kwargs) return wrapper
python
def scoped(self, func): """ Decorator to switch scopes. """ @wraps(func) def wrapper(*args, **kwargs): scope = kwargs.get("scope", self.__factory__.default_scope) with self.scoped_to(scope): return func(*args, **kwargs) return wrapper
[ "def", "scoped", "(", "self", ",", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "scope", "=", "kwargs", ".", "get", "(", "\"scope\"", ",", "self", ".", "__factory__", "."...
Decorator to switch scopes.
[ "Decorator", "to", "switch", "scopes", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/scoping/proxies.py#L74-L84
train
26,173
globality-corp/microcosm
microcosm/config/model.py
Configuration.merge
def merge(self, dct=None, **kwargs): """ Recursively merge a dictionary or kwargs into the current dict. """ if dct is None: dct = {} if kwargs: dct.update(**kwargs) for key, value in dct.items(): if all(( isinstance(value, dict), isinstance(self.get(key), Configuration), getattr(self.get(key), "__merge__", True), )): # recursively merge self[key].merge(value) elif isinstance(value, list) and isinstance(self.get(key), list): # append self[key] += value else: # set the new value self[key] = value
python
def merge(self, dct=None, **kwargs): """ Recursively merge a dictionary or kwargs into the current dict. """ if dct is None: dct = {} if kwargs: dct.update(**kwargs) for key, value in dct.items(): if all(( isinstance(value, dict), isinstance(self.get(key), Configuration), getattr(self.get(key), "__merge__", True), )): # recursively merge self[key].merge(value) elif isinstance(value, list) and isinstance(self.get(key), list): # append self[key] += value else: # set the new value self[key] = value
[ "def", "merge", "(", "self", ",", "dct", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "dct", "is", "None", ":", "dct", "=", "{", "}", "if", "kwargs", ":", "dct", ".", "update", "(", "*", "*", "kwargs", ")", "for", "key", ",", "value"...
Recursively merge a dictionary or kwargs into the current dict.
[ "Recursively", "merge", "a", "dictionary", "or", "kwargs", "into", "the", "current", "dict", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/config/model.py#L44-L67
train
26,174
globality-corp/microcosm
microcosm/config/model.py
Requirement.validate
def validate(self, metadata, path, value): """ Validate this requirement. """ if isinstance(value, Requirement): # if the RHS is still a Requirement object, it was not set if metadata.testing and self.mock_value is not None: value = self.mock_value elif self.default_value is not None: value = self.default_value elif not value.required: return None else: raise ValidationError(f"Missing required configuration for: {'.'.join(path)}") try: return self.type(value) except ValueError: raise ValidationError(f"Missing required configuration for: {'.'.join(path)}: {value}")
python
def validate(self, metadata, path, value): """ Validate this requirement. """ if isinstance(value, Requirement): # if the RHS is still a Requirement object, it was not set if metadata.testing and self.mock_value is not None: value = self.mock_value elif self.default_value is not None: value = self.default_value elif not value.required: return None else: raise ValidationError(f"Missing required configuration for: {'.'.join(path)}") try: return self.type(value) except ValueError: raise ValidationError(f"Missing required configuration for: {'.'.join(path)}: {value}")
[ "def", "validate", "(", "self", ",", "metadata", ",", "path", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Requirement", ")", ":", "# if the RHS is still a Requirement object, it was not set", "if", "metadata", ".", "testing", "and", "self", "...
Validate this requirement.
[ "Validate", "this", "requirement", "." ]
6856200ca295da4269c8c1c9de7db0b97c1f4523
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/config/model.py#L88-L107
train
26,175
palantir/conjure-python-client
conjure_python_client/_serde/decoder.py
ConjureDecoder.decode_conjure_union_type
def decode_conjure_union_type(cls, obj, conjure_type): """Decodes json into a conjure union type. Args: obj: the json object to decode conjure_type: a class object which is the union type we're decoding into Returns: An instance of type conjure_type. """ type_of_union = obj["type"] # type: str for attr, conjure_field in conjure_type._options().items(): if conjure_field.identifier == type_of_union: attribute = attr conjure_field_definition = conjure_field break else: raise ValueError( "unknown union type {0} for {1}".format( type_of_union, conjure_type ) ) deserialized = {} # type: Dict[str, Any] if type_of_union not in obj or obj[type_of_union] is None: cls.check_null_field(obj, deserialized, conjure_field_definition) else: value = obj[type_of_union] field_type = conjure_field_definition.field_type deserialized[attribute] = cls.do_decode(value, field_type) return conjure_type(**deserialized)
python
def decode_conjure_union_type(cls, obj, conjure_type): """Decodes json into a conjure union type. Args: obj: the json object to decode conjure_type: a class object which is the union type we're decoding into Returns: An instance of type conjure_type. """ type_of_union = obj["type"] # type: str for attr, conjure_field in conjure_type._options().items(): if conjure_field.identifier == type_of_union: attribute = attr conjure_field_definition = conjure_field break else: raise ValueError( "unknown union type {0} for {1}".format( type_of_union, conjure_type ) ) deserialized = {} # type: Dict[str, Any] if type_of_union not in obj or obj[type_of_union] is None: cls.check_null_field(obj, deserialized, conjure_field_definition) else: value = obj[type_of_union] field_type = conjure_field_definition.field_type deserialized[attribute] = cls.do_decode(value, field_type) return conjure_type(**deserialized)
[ "def", "decode_conjure_union_type", "(", "cls", ",", "obj", ",", "conjure_type", ")", ":", "type_of_union", "=", "obj", "[", "\"type\"", "]", "# type: str", "for", "attr", ",", "conjure_field", "in", "conjure_type", ".", "_options", "(", ")", ".", "items", "...
Decodes json into a conjure union type. Args: obj: the json object to decode conjure_type: a class object which is the union type we're decoding into Returns: An instance of type conjure_type.
[ "Decodes", "json", "into", "a", "conjure", "union", "type", "." ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/decoder.py#L77-L107
train
26,176
palantir/conjure-python-client
conjure_python_client/_serde/decoder.py
ConjureDecoder.decode_conjure_enum_type
def decode_conjure_enum_type(cls, obj, conjure_type): """Decodes json into a conjure enum type. Args: obj: the json object to decode conjure_type: a class object which is the enum type we're decoding into. Returns: An instance of enum of type conjure_type. """ if not (isinstance(obj, str) or str(type(obj)) == "<type 'unicode'>"): raise Exception( 'Expected to find str type but found {} instead'.format( type(obj))) if obj in conjure_type.__members__: return conjure_type[obj] else: return conjure_type["UNKNOWN"]
python
def decode_conjure_enum_type(cls, obj, conjure_type): """Decodes json into a conjure enum type. Args: obj: the json object to decode conjure_type: a class object which is the enum type we're decoding into. Returns: An instance of enum of type conjure_type. """ if not (isinstance(obj, str) or str(type(obj)) == "<type 'unicode'>"): raise Exception( 'Expected to find str type but found {} instead'.format( type(obj))) if obj in conjure_type.__members__: return conjure_type[obj] else: return conjure_type["UNKNOWN"]
[ "def", "decode_conjure_enum_type", "(", "cls", ",", "obj", ",", "conjure_type", ")", ":", "if", "not", "(", "isinstance", "(", "obj", ",", "str", ")", "or", "str", "(", "type", "(", "obj", ")", ")", "==", "\"<type 'unicode'>\"", ")", ":", "raise", "Exc...
Decodes json into a conjure enum type. Args: obj: the json object to decode conjure_type: a class object which is the enum type we're decoding into. Returns: An instance of enum of type conjure_type.
[ "Decodes", "json", "into", "a", "conjure", "enum", "type", "." ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/decoder.py#L110-L129
train
26,177
palantir/conjure-python-client
conjure_python_client/_serde/decoder.py
ConjureDecoder.decode_list
def decode_list(cls, obj, element_type): # type: (List[Any], ConjureTypeType) -> List[Any] """Decodes json into a list, handling conversion of the elements. Args: obj: the json object to decode element_type: a class object which is the conjure type of the elements in this list. Returns: A python list where the elements are instances of type element_type. """ if not isinstance(obj, list): raise Exception("expected a python list") return list(map(lambda x: cls.do_decode(x, element_type), obj))
python
def decode_list(cls, obj, element_type): # type: (List[Any], ConjureTypeType) -> List[Any] """Decodes json into a list, handling conversion of the elements. Args: obj: the json object to decode element_type: a class object which is the conjure type of the elements in this list. Returns: A python list where the elements are instances of type element_type. """ if not isinstance(obj, list): raise Exception("expected a python list") return list(map(lambda x: cls.do_decode(x, element_type), obj))
[ "def", "decode_list", "(", "cls", ",", "obj", ",", "element_type", ")", ":", "# type: (List[Any], ConjureTypeType) -> List[Any]", "if", "not", "isinstance", "(", "obj", ",", "list", ")", ":", "raise", "Exception", "(", "\"expected a python list\"", ")", "return", ...
Decodes json into a list, handling conversion of the elements. Args: obj: the json object to decode element_type: a class object which is the conjure type of the elements in this list. Returns: A python list where the elements are instances of type element_type.
[ "Decodes", "json", "into", "a", "list", "handling", "conversion", "of", "the", "elements", "." ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/decoder.py#L166-L181
train
26,178
palantir/conjure-python-client
conjure_python_client/_serde/decoder.py
ConjureDecoder.do_decode
def do_decode(cls, obj, obj_type): # type: (Any, ConjureTypeType) -> Any """Decodes json into the specified type Args: obj: the json object to decode element_type: a class object which is the type we're decoding into. """ if inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureBeanType ): return cls.decode_conjure_bean_type(obj, obj_type) # type: ignore elif inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureUnionType ): return cls.decode_conjure_union_type(obj, obj_type) elif inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureEnumType ): return cls.decode_conjure_enum_type(obj, obj_type) elif isinstance(obj_type, DictType): return cls.decode_dict(obj, obj_type.key_type, obj_type.value_type) elif isinstance(obj_type, ListType): return cls.decode_list(obj, obj_type.item_type) elif isinstance(obj_type, OptionalType): return cls.decode_optional(obj, obj_type.item_type) return cls.decode_primitive(obj, obj_type)
python
def do_decode(cls, obj, obj_type): # type: (Any, ConjureTypeType) -> Any """Decodes json into the specified type Args: obj: the json object to decode element_type: a class object which is the type we're decoding into. """ if inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureBeanType ): return cls.decode_conjure_bean_type(obj, obj_type) # type: ignore elif inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureUnionType ): return cls.decode_conjure_union_type(obj, obj_type) elif inspect.isclass(obj_type) and issubclass( # type: ignore obj_type, ConjureEnumType ): return cls.decode_conjure_enum_type(obj, obj_type) elif isinstance(obj_type, DictType): return cls.decode_dict(obj, obj_type.key_type, obj_type.value_type) elif isinstance(obj_type, ListType): return cls.decode_list(obj, obj_type.item_type) elif isinstance(obj_type, OptionalType): return cls.decode_optional(obj, obj_type.item_type) return cls.decode_primitive(obj, obj_type)
[ "def", "do_decode", "(", "cls", ",", "obj", ",", "obj_type", ")", ":", "# type: (Any, ConjureTypeType) -> Any", "if", "inspect", ".", "isclass", "(", "obj_type", ")", "and", "issubclass", "(", "# type: ignore", "obj_type", ",", "ConjureBeanType", ")", ":", "retu...
Decodes json into the specified type Args: obj: the json object to decode element_type: a class object which is the type we're decoding into.
[ "Decodes", "json", "into", "the", "specified", "type" ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/decoder.py#L221-L253
train
26,179
palantir/conjure-python-client
conjure_python_client/_serde/encoder.py
ConjureEncoder.encode_conjure_bean_type
def encode_conjure_bean_type(cls, obj): # type: (ConjureBeanType) -> Any """Encodes a conjure bean into json""" encoded = {} # type: Dict[str, Any] for attribute_name, field_definition in obj._fields().items(): encoded[field_definition.identifier] = cls.do_encode( getattr(obj, attribute_name) ) return encoded
python
def encode_conjure_bean_type(cls, obj): # type: (ConjureBeanType) -> Any """Encodes a conjure bean into json""" encoded = {} # type: Dict[str, Any] for attribute_name, field_definition in obj._fields().items(): encoded[field_definition.identifier] = cls.do_encode( getattr(obj, attribute_name) ) return encoded
[ "def", "encode_conjure_bean_type", "(", "cls", ",", "obj", ")", ":", "# type: (ConjureBeanType) -> Any", "encoded", "=", "{", "}", "# type: Dict[str, Any]", "for", "attribute_name", ",", "field_definition", "in", "obj", ".", "_fields", "(", ")", ".", "items", "(",...
Encodes a conjure bean into json
[ "Encodes", "a", "conjure", "bean", "into", "json" ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/encoder.py#L25-L33
train
26,180
palantir/conjure-python-client
conjure_python_client/_serde/encoder.py
ConjureEncoder.encode_conjure_union_type
def encode_conjure_union_type(cls, obj): # type: (ConjureUnionType) -> Any """Encodes a conjure union into json""" encoded = {} # type: Dict[str, Any] encoded["type"] = obj.type for attr, field_definition in obj._options().items(): if field_definition.identifier == obj.type: attribute = attr break else: raise ValueError( "could not find attribute for union " + "member {0} of type {1}".format(obj.type, obj.__class__) ) defined_field_definition = obj._options()[attribute] encoded[defined_field_definition.identifier] = cls.do_encode( getattr(obj, attribute) ) return encoded
python
def encode_conjure_union_type(cls, obj): # type: (ConjureUnionType) -> Any """Encodes a conjure union into json""" encoded = {} # type: Dict[str, Any] encoded["type"] = obj.type for attr, field_definition in obj._options().items(): if field_definition.identifier == obj.type: attribute = attr break else: raise ValueError( "could not find attribute for union " + "member {0} of type {1}".format(obj.type, obj.__class__) ) defined_field_definition = obj._options()[attribute] encoded[defined_field_definition.identifier] = cls.do_encode( getattr(obj, attribute) ) return encoded
[ "def", "encode_conjure_union_type", "(", "cls", ",", "obj", ")", ":", "# type: (ConjureUnionType) -> Any", "encoded", "=", "{", "}", "# type: Dict[str, Any]", "encoded", "[", "\"type\"", "]", "=", "obj", ".", "type", "for", "attr", ",", "field_definition", "in", ...
Encodes a conjure union into json
[ "Encodes", "a", "conjure", "union", "into", "json" ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/encoder.py#L36-L55
train
26,181
palantir/conjure-python-client
conjure_python_client/_serde/encoder.py
ConjureEncoder.do_encode
def do_encode(cls, obj): # type: (Any) -> Any """Encodes the passed object into json""" if isinstance(obj, ConjureBeanType): return cls.encode_conjure_bean_type(obj) elif isinstance(obj, ConjureUnionType): return cls.encode_conjure_union_type(obj) elif isinstance(obj, ConjureEnumType): return obj.value elif isinstance(obj, list): return list(map(cls.do_encode, obj)) elif isinstance(obj, dict): return {cls.do_encode(key): cls.do_encode(value) for key, value in obj.items()} else: return cls.encode_primitive(obj)
python
def do_encode(cls, obj): # type: (Any) -> Any """Encodes the passed object into json""" if isinstance(obj, ConjureBeanType): return cls.encode_conjure_bean_type(obj) elif isinstance(obj, ConjureUnionType): return cls.encode_conjure_union_type(obj) elif isinstance(obj, ConjureEnumType): return obj.value elif isinstance(obj, list): return list(map(cls.do_encode, obj)) elif isinstance(obj, dict): return {cls.do_encode(key): cls.do_encode(value) for key, value in obj.items()} else: return cls.encode_primitive(obj)
[ "def", "do_encode", "(", "cls", ",", "obj", ")", ":", "# type: (Any) -> Any", "if", "isinstance", "(", "obj", ",", "ConjureBeanType", ")", ":", "return", "cls", ".", "encode_conjure_bean_type", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "Conjure...
Encodes the passed object into json
[ "Encodes", "the", "passed", "object", "into", "json" ]
e6814a80bae3ec01fa147d5fd445538a677b1349
https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/encoder.py#L66-L86
train
26,182
leancloud/python-sdk
leancloud/geo_point.py
GeoPoint.radians_to
def radians_to(self, other): """ Returns the distance from this GeoPoint to another in radians. :param other: point the other GeoPoint :type other: GeoPoint :rtype: float """ d2r = math.pi / 180.0 lat1rad = self.latitude * d2r long1rad = self.longitude * d2r lat2rad = other.latitude * d2r long2rad = other.longitude * d2r delta_lat = lat1rad - lat2rad delta_long = long1rad - long2rad sin_delta_lat_div2 = math.sin(delta_lat / 2.0) sin_delta_long_div2 = math.sin(delta_long / 2.0) a = ((sin_delta_lat_div2 * sin_delta_lat_div2) + (math.cos(lat1rad) * math.cos(lat2rad) * sin_delta_long_div2 * sin_delta_long_div2)) a = min(1.0, a) return 2 * math.asin(math.sqrt(a))
python
def radians_to(self, other): """ Returns the distance from this GeoPoint to another in radians. :param other: point the other GeoPoint :type other: GeoPoint :rtype: float """ d2r = math.pi / 180.0 lat1rad = self.latitude * d2r long1rad = self.longitude * d2r lat2rad = other.latitude * d2r long2rad = other.longitude * d2r delta_lat = lat1rad - lat2rad delta_long = long1rad - long2rad sin_delta_lat_div2 = math.sin(delta_lat / 2.0) sin_delta_long_div2 = math.sin(delta_long / 2.0) a = ((sin_delta_lat_div2 * sin_delta_lat_div2) + (math.cos(lat1rad) * math.cos(lat2rad) * sin_delta_long_div2 * sin_delta_long_div2)) a = min(1.0, a) return 2 * math.asin(math.sqrt(a))
[ "def", "radians_to", "(", "self", ",", "other", ")", ":", "d2r", "=", "math", ".", "pi", "/", "180.0", "lat1rad", "=", "self", ".", "latitude", "*", "d2r", "long1rad", "=", "self", ".", "longitude", "*", "d2r", "lat2rad", "=", "other", ".", "latitude...
Returns the distance from this GeoPoint to another in radians. :param other: point the other GeoPoint :type other: GeoPoint :rtype: float
[ "Returns", "the", "distance", "from", "this", "GeoPoint", "to", "another", "in", "radians", "." ]
fea3240257ce65e6a32c7312a5cee1f94a51a587
https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/geo_point.py#L74-L99
train
26,183
pyblish/pyblish-lite
pyblish_lite/model.py
Abstract.append
def append(self, item): """Append item to end of model""" self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount()) self.items.append(item) self.endInsertRows()
python
def append(self, item): """Append item to end of model""" self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount()) self.items.append(item) self.endInsertRows()
[ "def", "append", "(", "self", ",", "item", ")", ":", "self", ".", "beginInsertRows", "(", "QtCore", ".", "QModelIndex", "(", ")", ",", "self", ".", "rowCount", "(", ")", ",", "self", ".", "rowCount", "(", ")", ")", "self", ".", "items", ".", "appen...
Append item to end of model
[ "Append", "item", "to", "end", "of", "model" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/model.py#L101-L108
train
26,184
pyblish/pyblish-lite
pyblish_lite/window.py
Window.on_item_toggled
def on_item_toggled(self, index, state=None): """An item is requesting to be toggled""" if not index.data(model.IsIdle): return self.info("Cannot toggle") if not index.data(model.IsOptional): return self.info("This item is mandatory") if state is None: state = not index.data(model.IsChecked) index.model().setData(index, state, model.IsChecked) # Withdraw option to publish if no instances are toggled play = self.findChild(QtWidgets.QWidget, "Play") validate = self.findChild(QtWidgets.QWidget, "Validate") any_instances = any(index.data(model.IsChecked) for index in self.data["models"]["instances"]) play.setEnabled(any_instances) validate.setEnabled(any_instances) # Emit signals if index.data(model.Type) == "instance": instance = self.data["models"]["instances"].items[index.row()] util.defer( 100, lambda: self.controller.emit_( signal="instanceToggled", kwargs={"new_value": state, "old_value": not state, "instance": instance})) if index.data(model.Type) == "plugin": util.defer( 100, lambda: self.controller.emit_( signal="pluginToggled", kwargs={"new_value": state, "old_value": not state, "plugin": index.data(model.Object)}))
python
def on_item_toggled(self, index, state=None): """An item is requesting to be toggled""" if not index.data(model.IsIdle): return self.info("Cannot toggle") if not index.data(model.IsOptional): return self.info("This item is mandatory") if state is None: state = not index.data(model.IsChecked) index.model().setData(index, state, model.IsChecked) # Withdraw option to publish if no instances are toggled play = self.findChild(QtWidgets.QWidget, "Play") validate = self.findChild(QtWidgets.QWidget, "Validate") any_instances = any(index.data(model.IsChecked) for index in self.data["models"]["instances"]) play.setEnabled(any_instances) validate.setEnabled(any_instances) # Emit signals if index.data(model.Type) == "instance": instance = self.data["models"]["instances"].items[index.row()] util.defer( 100, lambda: self.controller.emit_( signal="instanceToggled", kwargs={"new_value": state, "old_value": not state, "instance": instance})) if index.data(model.Type) == "plugin": util.defer( 100, lambda: self.controller.emit_( signal="pluginToggled", kwargs={"new_value": state, "old_value": not state, "plugin": index.data(model.Object)}))
[ "def", "on_item_toggled", "(", "self", ",", "index", ",", "state", "=", "None", ")", ":", "if", "not", "index", ".", "data", "(", "model", ".", "IsIdle", ")", ":", "return", "self", ".", "info", "(", "\"Cannot toggle\"", ")", "if", "not", "index", "....
An item is requesting to be toggled
[ "An", "item", "is", "requesting", "to", "be", "toggled" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L622-L659
train
26,185
pyblish/pyblish-lite
pyblish_lite/window.py
Window.on_comment_entered
def on_comment_entered(self): """The user has typed a comment""" text_edit = self.findChild(QtWidgets.QWidget, "CommentBox") comment = text_edit.text() # Store within context context = self.controller.context context.data["comment"] = comment placeholder = self.findChild(QtWidgets.QLabel, "CommentPlaceholder") placeholder.setVisible(not comment)
python
def on_comment_entered(self): """The user has typed a comment""" text_edit = self.findChild(QtWidgets.QWidget, "CommentBox") comment = text_edit.text() # Store within context context = self.controller.context context.data["comment"] = comment placeholder = self.findChild(QtWidgets.QLabel, "CommentPlaceholder") placeholder.setVisible(not comment)
[ "def", "on_comment_entered", "(", "self", ")", ":", "text_edit", "=", "self", ".", "findChild", "(", "QtWidgets", ".", "QWidget", ",", "\"CommentBox\"", ")", "comment", "=", "text_edit", ".", "text", "(", ")", "# Store within context", "context", "=", "self", ...
The user has typed a comment
[ "The", "user", "has", "typed", "a", "comment" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L697-L707
train
26,186
pyblish/pyblish-lite
pyblish_lite/window.py
Window.on_finished
def on_finished(self): """Finished signal handler""" self.controller.is_running = False error = self.controller.current_error if error is not None: self.info(self.tr("Stopped due to error(s), see Terminal.")) else: self.info(self.tr("Finished successfully!"))
python
def on_finished(self): """Finished signal handler""" self.controller.is_running = False error = self.controller.current_error if error is not None: self.info(self.tr("Stopped due to error(s), see Terminal.")) else: self.info(self.tr("Finished successfully!"))
[ "def", "on_finished", "(", "self", ")", ":", "self", ".", "controller", ".", "is_running", "=", "False", "error", "=", "self", ".", "controller", ".", "current_error", "if", "error", "is", "not", "None", ":", "self", ".", "info", "(", "self", ".", "tr"...
Finished signal handler
[ "Finished", "signal", "handler" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L871-L879
train
26,187
pyblish/pyblish-lite
pyblish_lite/window.py
Window.reset
def reset(self): """Prepare GUI for reset""" self.info(self.tr("About to reset..")) models = self.data["models"] models["instances"].store_checkstate() models["plugins"].store_checkstate() # Reset current ids to secure no previous instances get mixed in. models["instances"].ids = [] for m in models.values(): m.reset() for b in self.data["buttons"].values(): b.hide() comment_box = self.findChild(QtWidgets.QWidget, "CommentBox") comment_box.hide() util.defer(500, self.controller.reset)
python
def reset(self): """Prepare GUI for reset""" self.info(self.tr("About to reset..")) models = self.data["models"] models["instances"].store_checkstate() models["plugins"].store_checkstate() # Reset current ids to secure no previous instances get mixed in. models["instances"].ids = [] for m in models.values(): m.reset() for b in self.data["buttons"].values(): b.hide() comment_box = self.findChild(QtWidgets.QWidget, "CommentBox") comment_box.hide() util.defer(500, self.controller.reset)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "info", "(", "self", ".", "tr", "(", "\"About to reset..\"", ")", ")", "models", "=", "self", ".", "data", "[", "\"models\"", "]", "models", "[", "\"instances\"", "]", ".", "store_checkstate", "(", ")...
Prepare GUI for reset
[ "Prepare", "GUI", "for", "reset" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L887-L908
train
26,188
pyblish/pyblish-lite
pyblish_lite/window.py
Window.closeEvent
def closeEvent(self, event): """Perform post-flight checks before closing Make sure processing of any kind is wrapped up before closing """ # Make it snappy, but take care to clean it all up. # TODO(marcus): Enable GUI to return on problem, such # as asking whether or not the user really wants to quit # given there are things currently running. self.hide() if self.data["state"]["is_closing"]: # Explicitly clear potentially referenced data self.info(self.tr("Cleaning up models..")) for v in self.data["views"].values(): v.model().deleteLater() v.setModel(None) self.info(self.tr("Cleaning up terminal..")) for item in self.data["models"]["terminal"].items: del(item) self.info(self.tr("Cleaning up controller..")) self.controller.cleanup() self.info(self.tr("All clean!")) self.info(self.tr("Good bye")) return super(Window, self).closeEvent(event) self.info(self.tr("Closing..")) def on_problem(): self.heads_up("Warning", "Had trouble closing down. " "Please tell someone and try again.") self.show() if self.controller.is_running: self.info(self.tr("..as soon as processing is finished..")) self.controller.is_running = False self.finished.connect(self.close) util.defer(2000, on_problem) return event.ignore() self.data["state"]["is_closing"] = True util.defer(200, self.close) return event.ignore()
python
def closeEvent(self, event): """Perform post-flight checks before closing Make sure processing of any kind is wrapped up before closing """ # Make it snappy, but take care to clean it all up. # TODO(marcus): Enable GUI to return on problem, such # as asking whether or not the user really wants to quit # given there are things currently running. self.hide() if self.data["state"]["is_closing"]: # Explicitly clear potentially referenced data self.info(self.tr("Cleaning up models..")) for v in self.data["views"].values(): v.model().deleteLater() v.setModel(None) self.info(self.tr("Cleaning up terminal..")) for item in self.data["models"]["terminal"].items: del(item) self.info(self.tr("Cleaning up controller..")) self.controller.cleanup() self.info(self.tr("All clean!")) self.info(self.tr("Good bye")) return super(Window, self).closeEvent(event) self.info(self.tr("Closing..")) def on_problem(): self.heads_up("Warning", "Had trouble closing down. " "Please tell someone and try again.") self.show() if self.controller.is_running: self.info(self.tr("..as soon as processing is finished..")) self.controller.is_running = False self.finished.connect(self.close) util.defer(2000, on_problem) return event.ignore() self.data["state"]["is_closing"] = True util.defer(200, self.close) return event.ignore()
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "# Make it snappy, but take care to clean it all up.", "# TODO(marcus): Enable GUI to return on problem, such", "# as asking whether or not the user really wants to quit", "# given there are things currently running.", "self", ".", ...
Perform post-flight checks before closing Make sure processing of any kind is wrapped up before closing
[ "Perform", "post", "-", "flight", "checks", "before", "closing" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L953-L1002
train
26,189
pyblish/pyblish-lite
pyblish_lite/window.py
Window.reject
def reject(self): """Handle ESC key""" if self.controller.is_running: self.info(self.tr("Stopping..")) self.controller.is_running = False
python
def reject(self): """Handle ESC key""" if self.controller.is_running: self.info(self.tr("Stopping..")) self.controller.is_running = False
[ "def", "reject", "(", "self", ")", ":", "if", "self", ".", "controller", ".", "is_running", ":", "self", ".", "info", "(", "self", ".", "tr", "(", "\"Stopping..\"", ")", ")", "self", ".", "controller", ".", "is_running", "=", "False" ]
Handle ESC key
[ "Handle", "ESC", "key" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L1004-L1009
train
26,190
pyblish/pyblish-lite
pyblish_lite/window.py
Window.info
def info(self, message): """Print user-facing information Arguments: message (str): Text message for the user """ info = self.findChild(QtWidgets.QLabel, "Info") info.setText(message) # Include message in terminal self.data["models"]["terminal"].append({ "label": message, "type": "info" }) animation = self.data["animation"]["display_info"] animation.stop() animation.start() # TODO(marcus): Should this be configurable? Do we want # the shell to fill up with these messages? util.u_print(message)
python
def info(self, message): """Print user-facing information Arguments: message (str): Text message for the user """ info = self.findChild(QtWidgets.QLabel, "Info") info.setText(message) # Include message in terminal self.data["models"]["terminal"].append({ "label": message, "type": "info" }) animation = self.data["animation"]["display_info"] animation.stop() animation.start() # TODO(marcus): Should this be configurable? Do we want # the shell to fill up with these messages? util.u_print(message)
[ "def", "info", "(", "self", ",", "message", ")", ":", "info", "=", "self", ".", "findChild", "(", "QtWidgets", ".", "QLabel", ",", "\"Info\"", ")", "info", ".", "setText", "(", "message", ")", "# Include message in terminal", "self", ".", "data", "[", "\...
Print user-facing information Arguments: message (str): Text message for the user
[ "Print", "user", "-", "facing", "information" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/window.py#L1017-L1040
train
26,191
pyblish/pyblish-lite
pyblish_lite/view.py
LogView.rowsInserted
def rowsInserted(self, parent, start, end): """Automatically scroll to bottom on each new item added Arguments: parent (QtCore.QModelIndex): The model itself, since this is a list start (int): Start index of item end (int): End index of item """ super(LogView, self).rowsInserted(parent, start, end) # IMPORTANT: This must be done *after* the superclass to get # an accurate value of the delegate's height. self.scrollToBottom()
python
def rowsInserted(self, parent, start, end): """Automatically scroll to bottom on each new item added Arguments: parent (QtCore.QModelIndex): The model itself, since this is a list start (int): Start index of item end (int): End index of item """ super(LogView, self).rowsInserted(parent, start, end) # IMPORTANT: This must be done *after* the superclass to get # an accurate value of the delegate's height. self.scrollToBottom()
[ "def", "rowsInserted", "(", "self", ",", "parent", ",", "start", ",", "end", ")", ":", "super", "(", "LogView", ",", "self", ")", ".", "rowsInserted", "(", "parent", ",", "start", ",", "end", ")", "# IMPORTANT: This must be done *after* the superclass to get", ...
Automatically scroll to bottom on each new item added Arguments: parent (QtCore.QModelIndex): The model itself, since this is a list start (int): Start index of item end (int): End index of item
[ "Automatically", "scroll", "to", "bottom", "on", "each", "new", "item", "added" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/view.py#L90-L104
train
26,192
pyblish/pyblish-lite
pyblish_lite/control.py
Controller.reset
def reset(self): """Discover plug-ins and run collection""" self.context = pyblish.api.Context() self.plugins = pyblish.api.discover() self.was_discovered.emit() self.pair_generator = None self.current_pair = (None, None) self.current_error = None self.processing = { "nextOrder": None, "ordersWithError": set() } self._load() self._run(until=pyblish.api.CollectorOrder, on_finished=self.was_reset.emit)
python
def reset(self): """Discover plug-ins and run collection""" self.context = pyblish.api.Context() self.plugins = pyblish.api.discover() self.was_discovered.emit() self.pair_generator = None self.current_pair = (None, None) self.current_error = None self.processing = { "nextOrder": None, "ordersWithError": set() } self._load() self._run(until=pyblish.api.CollectorOrder, on_finished=self.was_reset.emit)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "context", "=", "pyblish", ".", "api", ".", "Context", "(", ")", "self", ".", "plugins", "=", "pyblish", ".", "api", ".", "discover", "(", ")", "self", ".", "was_discovered", ".", "emit", "(", ")"...
Discover plug-ins and run collection
[ "Discover", "plug", "-", "ins", "and", "run", "collection" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L61-L79
train
26,193
pyblish/pyblish-lite
pyblish_lite/control.py
Controller._load
def _load(self): """Initiate new generator and load first pair""" self.is_running = True self.pair_generator = self._iterator(self.plugins, self.context) self.current_pair = next(self.pair_generator, (None, None)) self.current_error = None self.is_running = False
python
def _load(self): """Initiate new generator and load first pair""" self.is_running = True self.pair_generator = self._iterator(self.plugins, self.context) self.current_pair = next(self.pair_generator, (None, None)) self.current_error = None self.is_running = False
[ "def", "_load", "(", "self", ")", ":", "self", ".", "is_running", "=", "True", "self", ".", "pair_generator", "=", "self", ".", "_iterator", "(", "self", ".", "plugins", ",", "self", ".", "context", ")", "self", ".", "current_pair", "=", "next", "(", ...
Initiate new generator and load first pair
[ "Initiate", "new", "generator", "and", "load", "first", "pair" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L108-L115
train
26,194
pyblish/pyblish-lite
pyblish_lite/control.py
Controller._process
def _process(self, plugin, instance=None): """Produce `result` from `plugin` and `instance` :func:`process` shares state with :func:`_iterator` such that an instance/plugin pair can be fetched and processed in isolation. Arguments: plugin (pyblish.api.Plugin): Produce result using plug-in instance (optional, pyblish.api.Instance): Process this instance, if no instance is provided, context is processed. """ self.processing["nextOrder"] = plugin.order try: result = pyblish.plugin.process(plugin, self.context, instance) except Exception as e: raise Exception("Unknown error: %s" % e) else: # Make note of the order at which the # potential error error occured. has_error = result["error"] is not None if has_error: self.processing["ordersWithError"].add(plugin.order) return result
python
def _process(self, plugin, instance=None): """Produce `result` from `plugin` and `instance` :func:`process` shares state with :func:`_iterator` such that an instance/plugin pair can be fetched and processed in isolation. Arguments: plugin (pyblish.api.Plugin): Produce result using plug-in instance (optional, pyblish.api.Instance): Process this instance, if no instance is provided, context is processed. """ self.processing["nextOrder"] = plugin.order try: result = pyblish.plugin.process(plugin, self.context, instance) except Exception as e: raise Exception("Unknown error: %s" % e) else: # Make note of the order at which the # potential error error occured. has_error = result["error"] is not None if has_error: self.processing["ordersWithError"].add(plugin.order) return result
[ "def", "_process", "(", "self", ",", "plugin", ",", "instance", "=", "None", ")", ":", "self", ".", "processing", "[", "\"nextOrder\"", "]", "=", "plugin", ".", "order", "try", ":", "result", "=", "pyblish", ".", "plugin", ".", "process", "(", "plugin"...
Produce `result` from `plugin` and `instance` :func:`process` shares state with :func:`_iterator` such that an instance/plugin pair can be fetched and processed in isolation. Arguments: plugin (pyblish.api.Plugin): Produce result using plug-in instance (optional, pyblish.api.Instance): Process this instance, if no instance is provided, context is processed.
[ "Produce", "result", "from", "plugin", "and", "instance" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L117-L145
train
26,195
pyblish/pyblish-lite
pyblish_lite/control.py
Controller._run
def _run(self, until=float("inf"), on_finished=lambda: None): """Process current pair and store next pair for next process Arguments: until (pyblish.api.Order, optional): Keep fetching next() until this order, default value is infinity. on_finished (callable, optional): What to do when finishing, defaults to doing nothing. """ def on_next(): if self.current_pair == (None, None): return util.defer(100, on_finished_) # The magic number 0.5 is the range between # the various CVEI processing stages; # e.g. # - Collection is 0 +- 0.5 (-0.5 - 0.5) # - Validation is 1 +- 0.5 (0.5 - 1.5) # # TODO(marcus): Make this less magical # order = self.current_pair[0].order if order > (until + 0.5): return util.defer(100, on_finished_) self.about_to_process.emit(*self.current_pair) util.defer(10, on_process) def on_process(): try: result = self._process(*self.current_pair) if result["error"] is not None: self.current_error = result["error"] self.was_processed.emit(result) except Exception as e: stack = traceback.format_exc(e) return util.defer( 500, lambda: on_unexpected_error(error=stack)) # Now that processing has completed, and context potentially # modified with new instances, produce the next pair. # # IMPORTANT: This *must* be done *after* processing of # the current pair, otherwise data generated at that point # will *not* be included. try: self.current_pair = next(self.pair_generator) except StopIteration: # All pairs were processed successfully! self.current_pair = (None, None) return util.defer(500, on_finished_) except Exception as e: # This is a bug stack = traceback.format_exc(e) self.current_pair = (None, None) return util.defer( 500, lambda: on_unexpected_error(error=stack)) util.defer(10, on_next) def on_unexpected_error(error): util.u_print(u"An unexpected error occurred:\n %s" % error) return util.defer(500, on_finished_) def on_finished_(): on_finished() self.was_finished.emit() self.is_running = True util.defer(10, on_next)
python
def _run(self, until=float("inf"), on_finished=lambda: None): """Process current pair and store next pair for next process Arguments: until (pyblish.api.Order, optional): Keep fetching next() until this order, default value is infinity. on_finished (callable, optional): What to do when finishing, defaults to doing nothing. """ def on_next(): if self.current_pair == (None, None): return util.defer(100, on_finished_) # The magic number 0.5 is the range between # the various CVEI processing stages; # e.g. # - Collection is 0 +- 0.5 (-0.5 - 0.5) # - Validation is 1 +- 0.5 (0.5 - 1.5) # # TODO(marcus): Make this less magical # order = self.current_pair[0].order if order > (until + 0.5): return util.defer(100, on_finished_) self.about_to_process.emit(*self.current_pair) util.defer(10, on_process) def on_process(): try: result = self._process(*self.current_pair) if result["error"] is not None: self.current_error = result["error"] self.was_processed.emit(result) except Exception as e: stack = traceback.format_exc(e) return util.defer( 500, lambda: on_unexpected_error(error=stack)) # Now that processing has completed, and context potentially # modified with new instances, produce the next pair. # # IMPORTANT: This *must* be done *after* processing of # the current pair, otherwise data generated at that point # will *not* be included. try: self.current_pair = next(self.pair_generator) except StopIteration: # All pairs were processed successfully! self.current_pair = (None, None) return util.defer(500, on_finished_) except Exception as e: # This is a bug stack = traceback.format_exc(e) self.current_pair = (None, None) return util.defer( 500, lambda: on_unexpected_error(error=stack)) util.defer(10, on_next) def on_unexpected_error(error): util.u_print(u"An unexpected error occurred:\n %s" % error) return util.defer(500, on_finished_) def on_finished_(): on_finished() self.was_finished.emit() self.is_running = True util.defer(10, on_next)
[ "def", "_run", "(", "self", ",", "until", "=", "float", "(", "\"inf\"", ")", ",", "on_finished", "=", "lambda", ":", "None", ")", ":", "def", "on_next", "(", ")", ":", "if", "self", ".", "current_pair", "==", "(", "None", ",", "None", ")", ":", "...
Process current pair and store next pair for next process Arguments: until (pyblish.api.Order, optional): Keep fetching next() until this order, default value is infinity. on_finished (callable, optional): What to do when finishing, defaults to doing nothing.
[ "Process", "current", "pair", "and", "store", "next", "pair", "for", "next", "process" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L147-L224
train
26,196
pyblish/pyblish-lite
pyblish_lite/control.py
Controller._iterator
def _iterator(self, plugins, context): """Yield next plug-in and instance to process. Arguments: plugins (list): Plug-ins to process context (pyblish.api.Context): Context to process """ test = pyblish.logic.registered_test() for plug, instance in pyblish.logic.Iterator(plugins, context): if not plug.active: continue if instance is not None and instance.data.get("publish") is False: continue self.processing["nextOrder"] = plug.order if not self.is_running: raise StopIteration("Stopped") if test(**self.processing): raise StopIteration("Stopped due to %s" % test( **self.processing)) yield plug, instance
python
def _iterator(self, plugins, context): """Yield next plug-in and instance to process. Arguments: plugins (list): Plug-ins to process context (pyblish.api.Context): Context to process """ test = pyblish.logic.registered_test() for plug, instance in pyblish.logic.Iterator(plugins, context): if not plug.active: continue if instance is not None and instance.data.get("publish") is False: continue self.processing["nextOrder"] = plug.order if not self.is_running: raise StopIteration("Stopped") if test(**self.processing): raise StopIteration("Stopped due to %s" % test( **self.processing)) yield plug, instance
[ "def", "_iterator", "(", "self", ",", "plugins", ",", "context", ")", ":", "test", "=", "pyblish", ".", "logic", ".", "registered_test", "(", ")", "for", "plug", ",", "instance", "in", "pyblish", ".", "logic", ".", "Iterator", "(", "plugins", ",", "con...
Yield next plug-in and instance to process. Arguments: plugins (list): Plug-ins to process context (pyblish.api.Context): Context to process
[ "Yield", "next", "plug", "-", "in", "and", "instance", "to", "process", "." ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L226-L253
train
26,197
pyblish/pyblish-lite
pyblish_lite/control.py
Controller.cleanup
def cleanup(self): """Forcefully delete objects from memory In an ideal world, this shouldn't be necessary. Garbage collection guarantees that anything without reference is automatically removed. However, because this application is designed to be run multiple times from the same interpreter process, extra case must be taken to ensure there are no memory leaks. Explicitly deleting objects shines a light on where objects may still be referenced in the form of an error. No errors means this was uneccesary, but that's ok. """ for instance in self.context: del(instance) for plugin in self.plugins: del(plugin)
python
def cleanup(self): """Forcefully delete objects from memory In an ideal world, this shouldn't be necessary. Garbage collection guarantees that anything without reference is automatically removed. However, because this application is designed to be run multiple times from the same interpreter process, extra case must be taken to ensure there are no memory leaks. Explicitly deleting objects shines a light on where objects may still be referenced in the form of an error. No errors means this was uneccesary, but that's ok. """ for instance in self.context: del(instance) for plugin in self.plugins: del(plugin)
[ "def", "cleanup", "(", "self", ")", ":", "for", "instance", "in", "self", ".", "context", ":", "del", "(", "instance", ")", "for", "plugin", "in", "self", ".", "plugins", ":", "del", "(", "plugin", ")" ]
Forcefully delete objects from memory In an ideal world, this shouldn't be necessary. Garbage collection guarantees that anything without reference is automatically removed. However, because this application is designed to be run multiple times from the same interpreter process, extra case must be taken to ensure there are no memory leaks. Explicitly deleting objects shines a light on where objects may still be referenced in the form of an error. No errors means this was uneccesary, but that's ok.
[ "Forcefully", "delete", "objects", "from", "memory" ]
9172b81c7ae19a36e99c89dd16e102201992dc20
https://github.com/pyblish/pyblish-lite/blob/9172b81c7ae19a36e99c89dd16e102201992dc20/pyblish_lite/control.py#L255-L276
train
26,198
adamalton/django-csp-reports
cspreports/summary.py
get_root_uri
def get_root_uri(uri): """Return root URI - strip query and fragment.""" chunks = urlsplit(uri) return urlunsplit((chunks.scheme, chunks.netloc, chunks.path, '', ''))
python
def get_root_uri(uri): """Return root URI - strip query and fragment.""" chunks = urlsplit(uri) return urlunsplit((chunks.scheme, chunks.netloc, chunks.path, '', ''))
[ "def", "get_root_uri", "(", "uri", ")", ":", "chunks", "=", "urlsplit", "(", "uri", ")", "return", "urlunsplit", "(", "(", "chunks", ".", "scheme", ",", "chunks", ".", "netloc", ",", "chunks", ".", "path", ",", "''", ",", "''", ")", ")" ]
Return root URI - strip query and fragment.
[ "Return", "root", "URI", "-", "strip", "query", "and", "fragment", "." ]
867992c6f535cf6afbf911f92af7eea4c61e4b73
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/summary.py#L14-L17
train
26,199