text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_prj_browser(self, ): """Create the project browser This creates a combobox brower for projects and adds it to the ui :returns: the created combo box browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` :raises: None """
prjbrws = ComboBoxBrowser(1, headers=['Project:']) self.central_vbox.insertWidget(0, prjbrws) return prjbrws
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_shot_browser(self, ): """Create the shot browser This creates a list browser for shots and adds it to the ui :returns: the created borwser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None """
shotbrws = ListBrowser(4, headers=['Sequence', 'Shot', 'Task', 'Descriptor']) self.shot_browser_vbox.insertWidget(0, shotbrws) return shotbrws
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_asset_browser(self, ): """Create the asset browser This creates a list browser for assets and adds it to the ui :returns: the created borwser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None """
assetbrws = ListBrowser(4, headers=['Assettype', 'Asset', 'Task', 'Descriptor']) self.asset_browser_vbox.insertWidget(0, assetbrws) return assetbrws
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_ver_browser(self, layout): """Create a version browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` :raises: None """
brws = ComboBoxBrowser(1, headers=['Version:']) layout.insertWidget(1, brws) return brws
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_comment_browser(self, layout): """Create a comment browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None """
brws = CommentBrowser(1, headers=['Comments:']) layout.insertWidget(1, brws) return brws
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_current_pb(self, ): """Create a push button and place it in the corner of the tabwidget :returns: the created button :rtype: :class:`QtGui.QPushButton` :raises: None """
pb = QtGui.QPushButton("Select current") self.selection_tabw.setCornerWidget(pb) return pb
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_prj_model(self, ): """Create and return a tree model that represents a list of projects :returns: the creeated model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """
prjs = djadapter.projects.all() rootdata = treemodel.ListItemData(['Name', 'Short', 'Rootpath']) prjroot = treemodel.TreeItem(rootdata) for prj in prjs: prjdata = djitemdata.ProjectItemData(prj) treemodel.TreeItem(prjdata, prjroot) prjmodel = treemodel.TreeModel(prjroot) return prjmodel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_shot_model(self, project, releasetype): """Create and return a new tree model that represents shots til descriptors The tree will include sequences, shots, tasks and descriptors of the given releaetype. :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.models.Project` :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """
rootdata = treemodel.ListItemData(['Name']) rootitem = treemodel.TreeItem(rootdata) for seq in project.sequence_set.all(): seqdata = djitemdata.SequenceItemData(seq) seqitem = treemodel.TreeItem(seqdata, rootitem) for shot in seq.shot_set.all(): shotdata = djitemdata.ShotItemData(shot) shotitem = treemodel.TreeItem(shotdata, seqitem) for task in shot.tasks.all(): taskdata = djitemdata.TaskItemData(task) taskitem = treemodel.TreeItem(taskdata, shotitem) #get all mayafiles taskfiles = task.taskfile_set.filter(releasetype=releasetype, typ=self._filetype) # get all descriptor values as a list. disctinct eliminates duplicates. for d in taskfiles.order_by('descriptor').values_list('descriptor', flat=True).distinct(): ddata = treemodel.ListItemData([d,]) treemodel.TreeItem(ddata, taskitem) shotmodel = treemodel.TreeModel(rootitem) return shotmodel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_asset_model(self, project, releasetype): """Create and return a new tree model that represents assets til descriptors The tree will include assettypes, assets, tasks and descriptors of the given releaetype. :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the assets :type project: :class:`djadapter.models.Project` :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """
rootdata = treemodel.ListItemData(['Name']) rootitem = treemodel.TreeItem(rootdata) for atype in project.atype_set.all(): atypedata = djitemdata.AtypeItemData(atype) atypeitem = treemodel.TreeItem(atypedata, rootitem) for asset in atype.asset_set.filter(project=project): assetdata = djitemdata.AssetItemData(asset) assetitem = treemodel.TreeItem(assetdata, atypeitem) for task in asset.tasks.all(): taskdata = djitemdata.TaskItemData(task) taskitem = treemodel.TreeItem(taskdata, assetitem) taskfiles = task.taskfile_set.filter(releasetype=releasetype, typ=self._filetype) # get all descriptor values as a list. disctinct eliminates duplicates. for d in taskfiles.order_by('descriptor').values_list('descriptor', flat=True).distinct(): ddata = treemodel.ListItemData([d,]) treemodel.TreeItem(ddata, taskitem) assetmodel = treemodel.TreeModel(rootitem) return assetmodel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_version_model(self, task, releasetype, descriptor): """Create and return a new model that represents taskfiles for the given task, releasetpye and descriptor :param task: the task of the taskfiles :type task: :class:`djadapter.models.Task` :param releasetype: the releasetype :type releasetype: str :param descriptor: the descirptor :type descriptor: str|None :returns: the created tree model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """
rootdata = treemodel.ListItemData(['Version', 'Releasetype', 'Path']) rootitem = treemodel.TreeItem(rootdata) for tf in task.taskfile_set.filter(releasetype=releasetype, descriptor=descriptor).order_by('-version'): tfdata = djitemdata.TaskFileItemData(tf) tfitem = treemodel.TreeItem(tfdata, rootitem) for note in tf.notes.all(): notedata = djitemdata.NoteItemData(note) treemodel.TreeItem(notedata, tfitem) versionmodel = treemodel.TreeModel(rootitem) return versionmodel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_shot_browser(self, project, releasetype): """Update the shot browser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: None """
if project is None: self.shotbrws.set_model(None) return shotmodel = self.create_shot_model(project, releasetype) self.shotbrws.set_model(shotmodel)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_asset_browser(self, project, releasetype): """update the assetbrowser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the assets :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: None """
if project is None: self.assetbrws.set_model(None) return assetmodel = self.create_asset_model(project, releasetype) self.assetbrws.set_model(assetmodel)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_browsers(self, *args, **kwargs): """Update the shot and the assetbrowsers :returns: None :rtype: None :raises: None """
sel = self.prjbrws.selected_indexes(0) if not sel: return prjindex = sel[0] if not prjindex.isValid(): prj = None else: prjitem = prjindex.internalPointer() prj = prjitem.internal_data() self.set_project_banner(prj) releasetype = self.get_releasetype() self.update_shot_browser(prj, releasetype) self.update_asset_browser(prj, releasetype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_version_descriptor(self, task, releasetype, descriptor, verbrowser, commentbrowser): """Update the versions in the given browser :param task: the task of the taskfiles :type task: :class:`djadapter.models.Task` | None :param releasetype: the releasetype :type releasetype: str|None :param descriptor: the descirptor :type descriptor: str|None :param verbrowser: the browser to update (the version browser) :type verbrowser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param commentbrowser: the comment browser to update :type commentbrowser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :returns: None :rtype: None :raises: None """
if task is None: null = treemodel.TreeItem(None) verbrowser.set_model(treemodel.TreeModel(null)) return m = self.create_version_model(task, releasetype, descriptor) verbrowser.set_model(m) commentbrowser.set_model(m)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def selection_changed(self, index, source, update, commentbrowser, mapper): """Callback for when the asset or shot browser changed its selection :param index: the modelindex with the descriptor tree item as internal data :type index: QtCore.QModelIndex :param source: the shot or asset browser to that changed its selection :type source: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param update: the browser to update :type update: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param browser: the comment browser to update :type browser: :class:`jukeboxcore.gui.widgets.browser.AbstractTreeBrowser` :param mapper: the data widget mapper to update :type mapper: :class:`QtGui.QDataWidgetMapper` :returns: None :rtype: None :raises: None """
if not index.isValid(): # no descriptor selected self.update_version_descriptor(None, None, None, update, commentbrowser) self.set_info_mapper_model(mapper, None) return descitem = index.internalPointer() descriptor = descitem.internal_data()[0] taskdata = source.selected_indexes(2)[0].internalPointer() task = taskdata.internal_data() releasetype = self.get_releasetype() self.update_version_descriptor(task, releasetype, descriptor, update, commentbrowser) self.set_info_mapper_model(mapper, update.model) sel = update.selected_indexes(0) if sel: self.set_mapper_index(sel[0], mapper)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_info_mapper_model(self, mapper, model): """Set the model for the info mapper :param mapper: the mapper to update :type mapper: QtGui.QDataWidgetMapper :param model: The model to set :type model: QtGui.QAbstractItemModel | None :returns: None :rtype: None :raises: None """
# nothing changed. we can return. # I noticed that when you set the model the very first time to None # it printed a message: # QObject::connect: Cannot connect (null)::dataChanged(QModelIndex,QModelIndex) to # QDataWidgetMapper::_q_dataChanged(QModelIndex,QModelIndex) # QObject::connect: Cannot connect (null)::destroyed() to # QDataWidgetMapper::_q_modelDestroyed() # I don't know exactly why. But these two lines get rid of the message and outcome is the same if not mapper.model() and not model: return mapper.setModel(model) if mapper is self.asset_info_mapper: if model is None: self.asset_path_le.setText("") self.asset_created_by_le.setText("") self.asset_created_dte.findChild(QtGui.QLineEdit).setText('') self.asset_updated_dte.findChild(QtGui.QLineEdit).setText('') else: mapper.addMapping(self.asset_path_le, 2) mapper.addMapping(self.asset_created_by_le, 3) mapper.addMapping(self.asset_created_dte, 4) mapper.addMapping(self.asset_updated_dte, 5) else: if model is None: self.shot_path_le.setText("") self.shot_created_by_le.setText("") self.shot_created_dte.findChild(QtGui.QLineEdit).setText('') self.shot_updated_dte.findChild(QtGui.QLineEdit).setText('') else: mapper.addMapping(self.shot_path_le, 2) mapper.addMapping(self.shot_created_by_le, 3) mapper.addMapping(self.shot_created_dte, 4) mapper.addMapping(self.shot_updated_dte, 5)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_mapper_index(self, index, mapper): """Set the mapper to the given index :param index: the index to set :type index: QtCore.QModelIndex :param mapper: the mapper to set :type mapper: QtGui.QDataWidgetMapper :returns: None :rtype: None :raises: None """
parent = index.parent() mapper.setRootIndex(parent) mapper.setCurrentModelIndex(index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_releasetype(self, ): """Return the currently selected releasetype :returns: the selected releasetype :rtype: str :raises: None """
for rt, rb in self._releasetype_button_mapping.items(): if rb.isChecked(): return rt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_to_current(self, ): """Set the selection to the currently open one :returns: None :rtype: None :raises: None """
cur = self.get_current_file() if cur is not None: self.set_selection(cur) else: self.init_selection()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_selection(self, taskfile): """Set the selection to the given taskfile :param taskfile: the taskfile to set the selection to :type taskfile: :class:`djadapter.models.TaskFile` :returns: None :rtype: None :raises: None """
self.set_project(taskfile.task.project) self.set_releasetype(taskfile.releasetype) if taskfile.task.department.assetflag: browser = self.assetbrws verbrowser = self.assetverbrws tabi = 0 rootobj = taskfile.task.element.atype else: browser = self.shotbrws verbrowser = self.shotverbrws tabi = 1 rootobj = taskfile.task.element.sequence self.set_level(browser, 0, rootobj) self.set_level(browser, 1, taskfile.task.element) self.set_level(browser, 2, taskfile.task) self.set_level(browser, 3, [taskfile.descriptor]) self.set_level(verbrowser, 0, taskfile) self.selection_tabw.setCurrentIndex(tabi)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_project(self, project): """Set the project selection to the given project :param project: the project to select :type project: :class:`djadapter.models.Project` :returns: None :rtype: None :raises: ValueError """
prjroot = self.prjbrws.model.root prjitems = prjroot.childItems for row, item in enumerate(prjitems): prj = item.internal_data() if prj == project: prjindex = self.prjbrws.model.index(row, 0) break else: raise ValueError("Could not select the given taskfile. No project %s found." % project.name) self.prjbrws.set_index(0, prjindex)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_level(self, browser, lvl, obj): """Set the given browser level selection to the one that matches with obj This is going to compare the internal_data of the model with the obj :param browser: :type browser: :param lvl: the depth level to set :type lvl: int :param obj: the object to compare the indexes with :type obj: object :returns: None :rtype: None :raises: None """
if lvl == 0: index = QtCore.QModelIndex() root = browser.model.root items = root.childItems else: index = browser.selected_indexes(lvl-1)[0] item = index.internalPointer() items = item.childItems for row, item in enumerate(items): data = item.internal_data() if data == obj: newindex = browser.model.index(row, 0, index) break else: raise ValueError("Could not select the given object in the browser. %s not found." % obj) browser.set_index(lvl, newindex)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_model(self, tfi): """Update the model for the given tfi :param tfi: taskfile info :type tfi: :class:`TaskFileInfo` :returns: None :rtype: None :raises: None """
if tfi.task.department.assetflag: browser = self.assetbrws else: browser = self.shotbrws if tfi.version == 1: # add descriptor parent = browser.selected_indexes(2)[0] ddata = treemodel.ListItemData([tfi.descriptor]) ditem = treemodel.TreeItem(ddata) browser.model.insertRow(0, ditem, parent) self.set_level(browser, 3, [tfi.descriptor])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_asset_path(self, *args, **kwargs): """Open the currently selected asset in the filebrowser :returns: None :rtype: None :raises: None """
f = self.asset_path_le.text() d = os.path.dirname(f) osinter = get_interface() osinter.open_path(d)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_shot_path(self, *args, **kwargs): """Open the currently selected shot in the filebrowser :returns: None :rtype: None :raises: None """
f = self.shot_path_le.text() d = os.path.dirname(f) osinter = get_interface() osinter.open_path(d)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(self, *args, **kwargs): """Refresh the model :returns: None :rtype: None :raises: None """
self.prjbrws.set_model(self.create_prj_model()) if self.get_current_file(): self.set_to_current() else: self.init_selection()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def report(self, string='', level=0, prelude='', progress=False, abbreviate=True): '''If verbose=True, this will print to terminal. Otherwise, it won't.''' if self._mute == False: self._prefix = prelude + '{spacing}[{name}] '.format(name = self.nametag, spacing = ' '*level) self._prefix = "{0:>16}".format(self._prefix) equalspaces = ' '*len(self._prefix) toprint = string + '' if abbreviate: if shortcuts is not None: for k in shortcuts.keys(): toprint = toprint.replace(k, shortcuts[k]) if progress: print('\r' + self._prefix + toprint.replace('\n', '\n' + equalspaces),) else: print(self._prefix + toprint.replace('\n', '\n' + equalspaces))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def summarize(self): '''Print a summary of the contents of this object.''' self.speak('Here is a brief summary of {}.'.format(self.nametag)) s = '\n'+pprint.pformat(self.__dict__) print(s.replace('\n', '\n'+' '*(len(self._prefix)+1)) + '\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_path(): """Sets up the python include paths to include src"""
import os.path; import sys if sys.argv[0]: top_dir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path = [os.path.join(top_dir, "src")] + sys.path pass return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entry_verifier(entries, regex, delimiter): """Checks each entry against regex for validity, If an entry does not match the regex, the entry and regex are broken down by the delimiter and each segment is analyzed to produce an accurate error message. Args: entries (list): List of entries to check with regex regex (str): Regular expression to compare entries with delimiter (str): Character to split entry and regex by, used to check parts of entry and regex to narrow in on the error Raises: FormatError: Class containing regex match error data Example: """
cregex = re.compile(regex) # Compiling saves time if many entries given # Encode raw delimiter in order to split a bad entry python_version = int(sys.version.split('.')[0]) decoder = 'unicode-escape' if python_version == 3 else 'string-escape' dedelimiter = codecs.decode(delimiter, decoder) for entry in entries: match = re.match(cregex, entry) # Match failed, check regex and entry parts for error if not match: split_regex = regex.split(delimiter) split_entry = entry.split(dedelimiter) part = 0 # "Enumerate" zipped iter for regex_segment, entry_segment in zip(split_regex, split_entry): # Ensure regex_segment only matches entire entry_segment if not regex_segment[0] == '^': regex_segment = '^' + regex_segment if not regex_segment[-1] == '$': regex_segment += '$' # If segment fails, raise error and store info on failure if not re.match(regex_segment, entry_segment): raise FormatError(template=regex_segment, subject=entry_segment, part=part) part += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jira_connection(config): """ Gets a JIRA API connection. If a connection has already been created the existing connection will be returned. """
global _jira_connection if _jira_connection: return _jira_connection else: jira_options = {'server': config.get('jira').get('url')} cookies = configuration._get_cookies_as_dict() jira_connection = jira_ext.JIRA(options=jira_options) session = jira_connection._session reused_session = False if cookies: requests.utils.add_dict_to_cookiejar(session.cookies, cookies) try: jira_connection.session() reused_session = True except Exception: pass if not reused_session: session.auth = (config['jira']['username'], base64.b64decode(config['jira']['password'])) jira_connection.session() session.auth = None cookie_jar_hash = requests.utils.dict_from_cookiejar(session.cookies) for key, value in cookie_jar_hash.iteritems(): configuration._save_cookie(key, value) _jira_connection = jira_connection return _jira_connection
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def form_upload_valid(self, form): """Handle a valid upload form."""
self.current_step = self.STEP_LINES lines = form.cleaned_data['file'] initial_lines = [dict(zip(self.get_columns(), line)) for line in lines] inner_form = self.get_form(self.get_form_class(), data=None, files=None, initial=initial_lines, ) return self.render_to_response(self.get_context_data(form=inner_form))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def form_lines_valid(self, form): """Handle a valid LineFormSet."""
handled = 0 for inner_form in form: if not inner_form.cleaned_data.get(formsets.DELETION_FIELD_NAME): handled += 1 self.handle_inner_form(inner_form) self.log_and_notify_lines(handled) return http.HttpResponseRedirect(self.get_success_url())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rank_clusters(cluster_dict): """ Helper function for clustering that takes a dictionary mapping cluster ids to lists of the binary strings that are part of that cluster and returns a dictionary mapping cluster ids to integers representing their "rank". Ranks provide an ordering for the clusters such that each cluster has its own rank, and clusters are ordered from simplest to most complex. """
# Figure out the relative rank of each cluster cluster_ranks = dict.fromkeys(cluster_dict.keys()) for key in cluster_dict: cluster_ranks[key] = eval(string_avg(cluster_dict[key], binary=True)) i = len(cluster_ranks) for key in sorted(cluster_ranks, key=cluster_ranks.get): cluster_ranks[key] = i i -= 1 return cluster_ranks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_ranks(grid, n): """ Takes a grid of phenotypes or resource sets representing as strings representing binary numbers, and an integer indicating the maximum number of clusters to generated. Clusters the data in grid into a maximum of n groups, ranks each group by the complexity and length of its "average" member, and returns a dictionary mapping binary numbers to integers representing the rank of the cluster they're part of. """
phenotypes = deepcopy(grid) if type(phenotypes) is list and type(phenotypes[0]) is list: phenotypes = flatten_array(phenotypes) # Remove duplicates from types types = list(frozenset(phenotypes)) if len(types) < n: ranks = rank_types(types) else: ranks = cluster_types(types, n) return ranks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assign_ranks_to_grid(grid, ranks): """ Takes a 2D array of binary numbers represented as strings and a dictionary mapping binary strings to integers representing the rank of the cluster they belong to, and returns a grid in which each binary number has been replaced with the rank of its cluster. """
assignments = deepcopy(grid) ranks["0b0"] = 0 ranks["-0b1"] = -1 for i in range(len(grid)): for j in range(len(grid[i])): if type(grid[i][j]) is list: for k in range(len(grid[i][j])): assignments[i][j][k] = ranks[grid[i][j][k]] else: assignments[i][j] = ranks[grid[i][j]] return assignments
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster_types(types, max_clust=12): """ Generates a dictionary mapping each binary number in types to an integer from 0 to max_clust. Hierarchical clustering is used to determine which which binary numbers should map to the same integer. """
if len(types) < max_clust: max_clust = len(types) # Do actual clustering cluster_dict = do_clustering(types, max_clust) cluster_ranks = rank_clusters(cluster_dict) # Create a dictionary mapping binary numbers to indices ranks = {} for key in cluster_dict: for typ in cluster_dict[key]: ranks[typ] = cluster_ranks[key] return ranks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rank_types(types): """ Takes a list of binary numbers and returns a dictionary mapping each binary number to an integer indicating it's rank within the list. This is basically the better alternative to cluster_types, that works in that perfect world where we have few enough types to represent each as its own color. """
include_null = '0b0' in types sorted_types = deepcopy(types) for i in range(len(sorted_types)): sorted_types[i] = int(sorted_types[i], 2) sorted_types.sort() ranks = {} for t in types: ranks[t] = sorted_types.index(eval(t)) + int(not include_null) return ranks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_count_grid(data): """ Takes a 2 or 3d grid of strings representing binary numbers. Returns a grid of the same dimensions in which each binary number has been replaced by an integer indicating the number of ones that were in that number. """
data = deepcopy(data) for i in range(len(data)): for j in range(len(data[i])): for k in range(len(data[i][j])): if type(data[i][j][k]) is list: for l in range(len(data[i][j][k])): try: data[i][j][k] = data[i][j][k][l].count("1") except: data[i][j][k] = len(data[i][j][k][l]) else: try: data[i][j][k] = data[i][j][k].count("1") except: data[i][j][k] = len(data[i][j][k]) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_optimal_phenotype_grid(environment, phenotypes): """ Takes an EnvironmentFile object and a 2d array of phenotypes and returns a 2d array in which each location contains an index representing the distance between the phenotype in that location and the optimal phenotype for that location. This is acheived by using the task list in the EnvironmentFile to convert the phenotypes to sets of tasks, and comparing them to the sets of resources in the environment. So if the environment file that you created the EnvironmentFile object from for some reason doesn't contain all of the tasks, or doesn't contain them in the right order this won't work. If this is the environment file that you used for the run of Avida that generated this data, you should be fine. """
world_size = environment.size phenotypes = deepcopy(phenotypes) for i in range(world_size[1]): for j in range(world_size[0]): for k in range(len(phenotypes[i][j])): phenotype = phenotype_to_res_set(phenotypes[i][j][k], environment.tasks) diff = len(environment[i][j].symmetric_difference(phenotype)) phenotypes[i][j][k] = diff return phenotypes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fastq_iter(handle, header=None): """Iterate over FASTQ file and return FASTQ entries Args: handle (file): FASTQ file handle, can be any iterator so long as it it returns subsequent "lines" of a FASTQ entry header (str): Header line of next FASTQ entry, if 'handle' has been partially read and you want to start iterating at the next entry, read the next FASTQ header and pass it to this variable when calling fastq_iter. See 'Examples.' Yields: FastqEntry: class containing all FASTQ data Raises: IOError: If FASTQ entry doesn't start with '@' Examples: The following two examples demonstrate how to use fastq_iter. Note: These doctests will not pass, examples are only in doctest format as per convention. bio_utils uses pytests for testing. """
# Speed tricks: reduces function calls append = list.append join = str.join strip = str.strip next_line = next if header is None: header = next(handle) # Read first FASTQ entry header # Check if input is text or bytestream if (isinstance(header, bytes)): def next_line(i): return next(i).decode('utf-8') header = strip(header.decode('utf-8')) else: header = strip(header) try: # Manually construct a for loop to improve speed by using 'next' while True: # Loop until StopIteration Exception raised line = strip(next_line(handle)) data = FastqEntry() if not header[0] == '@': raise IOError('Bad FASTQ format: no "@" at beginning of line') try: data.id, data.description = header[1:].split(' ', 1) except ValueError: # No description data.id = header[1:] data.description = '' # obtain sequence sequence_list = [] while line and not line[0] == '+' and not line[0] == '#': append(sequence_list, line) line = strip(next_line(handle)) data.sequence = join('', sequence_list) line = strip(next_line(handle)) # Skip line containing only '+' # Obtain quality scores quality_list = [] seq_len = len(data.sequence) qual_len = 0 while line and qual_len < seq_len: append(quality_list, line) qual_len += len(line) line = strip(next_line(handle)) # Raises StopIteration at EOF header = line # Store current line so it's not lost next iteration data.quality = join('', quality_list) yield data except StopIteration: # Yield last FASTQ entry data.quality = join('', quality_list) yield data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self): """Return FASTQ formatted string Returns: str: FASTQ formatted string containing entire FASTQ entry """
if self.description: return '@{0} {1}{4}{2}{4}+{4}{3}{4}'.format(self.id, self.description, self.sequence, self.quality, os.linesep) else: return '@{0}{3}{1}{3}+{3}{2}{3}'.format(self.id, self.sequence, self.quality, os.linesep)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buildWorkbenchWithLauncher(): """Builds a workbench. The workbench has a launcher with all of the default tools. The launcher will be displayed on the workbench. """
workbench = ui.Workbench() tools = [exercises.SearchTool()] launcher = ui.Launcher(workbench, tools) workbench.display(launcher) return workbench, launcher
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buildMainLoop(workbench, launcher, **kwargs): """Builds a main loop from the given workbench and launcher. The main loop will have the default pallette, as well as the default unused key handler. The key handler will have a reference to the workbench and launcher so that it can clear the screen. The extra keyword arguments are passed to the main loop. """
unhandledInput = partial(ui._unhandledInput, workbench=workbench, launcher=launcher) mainLoop = urwid.MainLoop(widget=workbench.widget, palette=ui.DEFAULT_PALETTE, unhandled_input=unhandledInput, event_loop=urwid.TwistedEventLoop(), **kwargs) return mainLoop
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_status(status, message=None, extra=None): """ Try to create an error from status code :param int status: HTTP status :param str message: Body content :param dict extra: Additional info :return: An error :rtype: cdumay_rest_client.errors.Error """
if status in HTTP_STATUS_CODES: return HTTP_STATUS_CODES[status](message=message, extra=extra) else: return Error( code=status, message=message if message else "Unknown Error", extra=extra )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_response(response, url): """ Try to create an error from a HTTP response :param request.Response response: HTTP response :param str url: URL attained :return: An error :rtype: cdumay_rest_client.errors.Error """
# noinspection PyBroadException try: data = response.json() if not isinstance(data, dict): return from_status( response.status_code, response.text, extra=dict(url=url, response=response.text) ) code = data.get('code', response.status_code) if code in HTTP_STATUS_CODES: return HTTP_STATUS_CODES[code](**ErrorSchema().load(data)) else: return Error(**ErrorSchema().load(data)) except Exception: return from_status( response.status_code, response.text, extra=dict(url=url, response=response.text) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort(self): """ Sort triggers and their associated responses """
# Sort triggers by word and character length first for priority, triggers in self._triggers.items(): self._log.debug('Sorting priority {priority} triggers'.format(priority=priority)) # Get and sort our atomic and wildcard patterns atomics = [trigger for trigger in triggers if trigger.pattern_is_atomic] wildcards = [trigger for trigger in triggers if not trigger.pattern_is_atomic] atomics = sorted(atomics, key=lambda trigger: (trigger.pattern_words, trigger.pattern_len), reverse=True) wildcards = sorted(wildcards, key=lambda trigger: (trigger.pattern_words, trigger.pattern_len), reverse=True) # Replace our sorted triggers self._triggers[priority] = atomics + wildcards # Finally, sort triggers by priority self._sorted_triggers = [] for triggers in [self._triggers[priority] for priority in sorted(self._triggers.keys(), reverse=True)]: for trigger in triggers: self._sorted_triggers.append(trigger) self.sorted = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpreter(self): """ Launch an AML interpreter session for testing """
while True: message = input('[#] ') if message.lower().strip() == 'exit': break reply = self.get_reply('#interpreter#', message) if not reply: print('No reply received.', end='\n\n') continue # typewrite(reply, end='\n\n') TODO print(reply, end='\n\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def responses_callback(request): """Responses Request Handler. Converts a call intercepted by Responses to the Stack-In-A-Box infrastructure :param request: request object :returns: tuple - (int, dict, string) containing: int - the HTTP response status code dict - the headers for the HTTP response string - HTTP string response """
method = request.method headers = CaseInsensitiveDict() request_headers = CaseInsensitiveDict() request_headers.update(request.headers) request.headers = request_headers uri = request.url return StackInABox.call_into(method, request, uri, headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def registration(uri): """Responses handler registration. Registers a handler for a given URI with Responses so that it can be intercepted and handed to Stack-In-A-Box. :param uri: URI used for the base of the HTTP requests :returns: n/a """
# log the URI that is used to access the Stack-In-A-Box services logger.debug('Registering Stack-In-A-Box at {0} under Python Responses' .format(uri)) # tell Stack-In-A-Box what URI to match with StackInABox.update_uri(uri) # Build the regex for the URI and register all HTTP verbs # with Responses regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri), re.I) METHODS = [ responses.DELETE, responses.GET, responses.HEAD, responses.OPTIONS, responses.PATCH, responses.POST, responses.PUT ] for method in METHODS: responses.add_callback(method, regex, callback=responses_callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cacheOnSameArgs(timeout=None): """ Caches the return of the function until the the specified time has elapsed or the arguments change. If timeout is None it will not be considered. """
if isinstance(timeout, int): timeout = datetime.timedelta(0, timeout) def decorator(f): _cache = [None] def wrapper(*args, **kwargs): if _cache[0] is not None: cached_ret, dt, cached_args, cached_kwargs = _cache[0] if (timeout is not None and dt + timeout <= datetime.datetime.now()): _cache[0] = None if (cached_args, cached_kwargs) != (args, kwargs): _cache[0] = None if _cache[0] is None: ret = f(*args, **kwargs) _cache[0] = (ret, datetime.datetime.now(), args, kwargs) return _cache[0][0] return wrapper return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_module(module): """ | Given a module `service`, try to import it. | It will autodiscovers all the entrypoints | and add them in `ENTRYPOINTS`. :param module: The module's name to import. :type module: str :rtype: None :raises ImportError: When the service/module to start is not found. """
try: __import__('{0}.service'.format(module)) except ImportError: LOGGER.error('No module/service found. Quit.') sys.exit(0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_models(module): """ | Given a module `service`, try to import its models module. :param module: The module's name to import the models. :type module: str :rtype: list :returns: all the models defined. """
try: module = importlib.import_module('{0}.models'.format(module)) except ImportError: return [] else: clsmembers = inspect.getmembers(module, lambda member: inspect.isclass(member) and member.__module__ == module.__name__) return [kls for name, kls in clsmembers]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(): """ | Start all the registered entrypoints | that have been added to `ENTRYPOINTS`. :rtype: None """
pool = gevent.threadpool.ThreadPool(len(ENTRYPOINTS)) for entrypoint, callback, args, kwargs in ENTRYPOINTS: cname = callback.__name__ #1. Retrieve the class which owns the callback for name, klass in inspect.getmembers(sys.modules[callback.__module__], inspect.isclass): if hasattr(klass, cname): service_name = name.lower() break #2.Start the entrypoint callback = getattr(klass(), cname) kwargs.update({'service':service_name, 'callback':callback, 'callback_name': cname}) LOGGER.info('Start service %s[%s].', service_name.capitalize(), cname) obj = entrypoint(*args, **kwargs) pool.spawn(obj.start, *args, **kwargs) pool.join() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_uri(cls, uri): """Set the URI of the StackInABox framework. :param uri: the base URI used to match the service. """
logger.debug('Request: Update URI to {0}'.format(uri)) local_store.instance.base_url = uri
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_services_url(url, base_url): """Get the URI from a given URL. :returns: URI within the URL """
length = len(base_url) checks = ['http://', 'https://'] for check in checks: if url.startswith(check): length = length + len(check) break result = url[length:] logger.debug('{0} from {1} equals {2}' .format(base_url, url, result)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def base_url(self, value): """Set the Base URL property, updating all associated services."""
logger.debug('StackInABox({0}): Updating URL from {1} to {2}' .format(self.__id, self.__base_url, value)) self.__base_url = value for k, v in six.iteritems(self.services): matcher, service = v service.base_url = StackInABox.__get_service_url(value, service.name) logger.debug('StackInABox({0}): Service {1} has url {2}' .format(self.__id, service.name, service.base_url))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Reset StackInABox to a like-new state."""
logger.debug('StackInABox({0}): Resetting...' .format(self.__id)) for k, v in six.iteritems(self.services): matcher, service = v logger.debug('StackInABox({0}): Resetting Service {1}' .format(self.__id, service.name)) service.reset() self.services = {} self.holds = {} logger.debug('StackInABox({0}): Reset Complete' .format(self.__id))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main_callback(self, *args, **kwargs): """ Main callback called when an event is received from an entry point. :returns: The entry point's callback. :rtype: function :raises NotImplementedError: When the entrypoint doesn't have the required attributes. """
if not self.callback: raise NotImplementedError('Entrypoints must declare `callback`') if not self.settings: raise NotImplementedError('Entrypoints must declare `settings`') self.callback.im_self.db = None #1. Start all the middlewares with self.debug(*args, **kwargs): with self.database(): #2. `Real` callback result = self.callback(*args, **kwargs)#pylint: disable=not-callable return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def canRead(variable): """ mention if an element can be read. :param variable: the element to evaluate. :type variable: Lifepo4weredEnum :return: true when read access is available, otherwise false. :rtype: bool :raises ValueError: if parameter value is not a member of Lifepo4weredEnum. """
if variable not in variablesEnum: raise ValueError('Use a lifepo4wered enum element as parameter.') return lifepo4weredSO.access_lifepo4wered(variable.value, defines.ACCESS_READ)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def canWrite(variable): """ mention if an element can be written. :param variable: the element to evaluate. :type variable: Lifepo4weredEnum :return: true when write access is available, otherwise false :rtype: bool :raises ValueError: if parameter value is not a member of Lifepo4weredEnum """
if variable not in variablesEnum: raise ValueError('Use a lifepo4wered enum element as parameter.') return lifepo4weredSO.access_lifepo4wered(variable.value, defines.ACCESS_WRITE)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(variable): """ read an element from LiFePO4wered. :param variable: the element to read. :type variable: Lifepo4weredEnum :return: the value of the element :rtype: int :raises ValueError: if parameter value is not a member of Lifepo4weredEnum """
if variable not in variablesEnum: raise ValueError('Use a lifepo4wered enum element as read parameter.') if canRead(variable): return lifepo4weredSO.read_lifepo4wered(variable.value) else: raise RuntimeError('You cannot read {0} value, just write it'.format(variable.name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(variable, value): """ write an element to LiFePO4wered. :param variable: the element. :type variable: Lifepo4weredEnum :param int value: the value to write. :return: the written value :rtype: int :raises ValueError: if variable parameter is not a member of Lifepo4weredEnum :raises ValueError: if value is not an int type """
if variable not in variablesEnum: raise ValueError('Use a lifepo4wered enum element as write element.') if isinstance(value, int) is False: raise TypeError('Use a int as value.') if canWrite(variable): return lifepo4weredSO.write_lifepo4wered(variable.value, value) else: raise RuntimeError('You cannot write {0} value, just read it'.format(variable.name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def force_encoding(value, encoding='utf-8'): """ Return a string encoded in the provided encoding """
if not isinstance(value, (str, unicode)): value = str(value) if isinstance(value, unicode): value = value.encode(encoding) elif encoding != 'utf-8': value = value.decode('utf-8').encode(encoding) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def force_unicode(value): """ return an utf-8 unicode entry """
if not isinstance(value, (str, unicode)): value = unicode(value) if isinstance(value, str): value = value.decode('utf-8') return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def camel_case_to_name(name): """ Used to convert a classname to a lowercase name """
def convert_func(val): return "_" + val.group(0).lower() return name[0].lower() + re.sub(r'([A-Z])', convert_func, name[1:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_utf8(datas): """ Force utf8 string entries in the given datas """
res = datas if isinstance(datas, dict): res = {} for key, value in datas.items(): key = to_utf8(key) value = to_utf8(value) res[key] = value elif isinstance(datas, (list, tuple)): res = [] for data in datas: res.append(to_utf8(data)) elif isinstance(datas, unicode): res = datas.encode('utf-8') return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_eids(self): """ Returns a list of all known eids """
entities = self.list() return sorted([int(eid) for eid in entities])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_by_entityid(self, entityid): """ Returns the entity with the given entity ID as a dict """
data = self.list(entityid=entityid) if len(data) == 0: return None eid = int( next(iter(data)) ) entity = self.get(eid) self.debug(0x01,entity) return entity
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, eid): """ Returns a dict with the complete record of the entity with the given eID """
data = self._http_req('connections/%u' % eid) self.debug(0x01, data['decoded']) return data['decoded']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, eid): """ Removes the entity with the given eid """
result = self._http_req('connections/%u' % eid, method='DELETE') status = result['status'] if not status == 302: raise ServiceRegistryError(status, "Could not delete entity %u: %u" % (eid,status)) self.debug(0x01,result) return result['decoded']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, entity): """ Adds the supplied dict as a new entity """
result = self._http_req('connections', method='POST', payload=entity) status = result['status'] if not status==201: raise ServiceRegistryError(status,"Couldn't add entity") self.debug(0x01,result) return result['decoded']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connectiontable(self, state='prodaccepted'): """ Returns a matrix of all entities showing which ones are connected together. """
entities = self.list_full(state) # sort entities idps = OrderedDict() sps = OrderedDict() for eid, entity in entities.items(): if entity['isActive'] and entity['state']==state: if entity['type']=='saml20-idp': idps[eid] = entity elif entity['type']=='saml20-sp': sps[eid] = entity else: raise(ServiceRegistryError(0,"unknown type `%s' for eid=%s" % (entity['type'],entity['id']))) # use numpy here for the connection matrix to simplify extraction of rows and columns lateron max_eid = max(entities.keys()) #print(max_eid) connections = dok_matrix((max_eid+1,max_eid+1), dtype=np.bool_) for idp_eid, idp_entity in idps.items(): #pprint(idp_entity) sps_allowed = set([e['id'] for e in idp_entity['allowedConnections']]) for sp_eid, sp_entity in sps.items(): idps_allowed = set([ e['id'] for e in sp_entity['allowedConnections'] ]) acl = ( idp_entity['allowAllEntities'] or (sp_eid in sps_allowed ) ) \ and ( sp_entity[ 'allowAllEntities'] or (idp_eid in idps_allowed) ) connections[idp_eid,sp_eid] = acl self._connections[state] = dict() self._connections[state]['idp'] = idps self._connections[state]['sp' ] = sps self._connections[state]['acl'] = connections return connections
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(config): """Commits any pending modifications, ie save a configuration file if it has been marked "dirty" as a result of an normal assignment. The modifications are written to the first writable source in this config object. .. note:: This is a static method, ie not a method on any object instance. This is because all attribute access on a LayeredConfig object is meant to retrieve configuration settings. :param config: The configuration object to save :type config: layeredconfig.LayeredConfig """
root = config while root._parent: root = root._parent for source in root._sources: if source.writable and source.dirty: source.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(config): """Returns the entire content of the config object in a way that can be easily examined, compared or dumped to a string or file. :param config: The configuration object to dump :rtype: dict """
def _dump(element): if not isinstance(element, config.__class__): return element section = dict() for key, subsection in element._subsections.items(): section[key] = _dump(subsection) for key in element: section[key] = getattr(element, key) return section return _dump(config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _make_methods(): "Automagically generates methods based on the API endpoints" for k, v in PokeAPI().get_endpoints().items(): string = "\t@BaseAPI._memoize\n" string += ("\tdef get_{0}(self, id_or_name='', limit=None," .format(k.replace('-', '_')) + ' offset=None):\n') string += ("\t\tparams = self._parse_params(locals().copy(), " + "['id_or_name'])\n") string += "\t\tquery_string = '{0}/'\n".format(v.split('/')[-2]) string += "\t\tquery_string += str(id_or_name) + '?'\n" string += '\t\tquery_string += params\n' string += '\t\treturn self._get(query_string)\n' print(string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def heat_map(grid, name, **kwargs): """ Generic function for making a heat map based on the values in a grid. Arguments: grid - the grid of numbers or binary strings to be visualized. name - string indicating what the file storing the image should be called. kwargs: palette - a seaborn palette (list of RGB values) indicating how to color values. Will be converted to a continuous colormap if necessary denom - the maximum value of numbers in the grid (only used if the grid actually contains numbers). This is used to normalize values and use the full dynamic range of the color pallete. """
denom, palette = get_kwargs(grid, kwargs) if "mask_zeros" in kwargs: mask_zeros = kwargs["mask_zeros"] else: mask_zeros = False grid = color_grid(grid, palette, denom, mask_zeros) make_imshow_plot(grid, name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_phens(phen_grid, **kwargs): """ Plots circles colored according to the values in phen_grid. -1 serves as a sentinel value, indicating that a circle should not be plotted in that location. """
denom, palette = get_kwargs(phen_grid, kwargs, True) grid = color_grid(phen_grid, palette, denom) for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] != -1 and tuple(grid[i][j]) != -1: plt.gca().add_patch(plt.Circle((j, i), radius=.3, lw=1, ec="black", facecolor=grid[i][j], zorder=2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_phens_circles(phen_grid, **kwargs): """ Plots phenotypes represented as concentric circles. Each circle represents one task that the phenotype can perform, with larger circles representing more complex tasks. Arguments: phen_grid - a 2D array of strings representing binary numbers kwargs: palette - a seaborn palette (list of RGB values) indicating how to color values. Will be converted to a continuous colormap if necessary denom - the maximum value of numbers in the grid (only used if the grid actually contains numbers). This is used to normalize values and use the full dynamic range of the color pallete. TODO: come up with way to represent organisms that don't do any tasks. """
denom, palette = get_kwargs(phen_grid, kwargs, True) n_tasks = len(palette) grid = phen_grid for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] != -1 and int(grid[i][j], 2) != -1 and \ int(grid[i][j], 2) != 0: first = True b_ind = grid[i][j].find("b") phen = grid[i][j][b_ind+1:] for k in range(len(phen)): if int(phen[k]) == 1: plt.gca().add_patch( plt.Circle( (j, i), radius=(n_tasks - k)*.05, lw=.1 if first else 0, ec="black", facecolor=palette[k], zorder=2+k)) first = False elif int(grid[i][j], 2) == 0: plt.gca().add_patch( plt.Circle( (j, i), radius=(n_tasks)*.05, lw=.1, ec="black", facecolor="grey", zorder=2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_phens_blits(phen_grid, patches, **kwargs): """ A version of plot_phens designed to be used in animations. Takes a 2D array of phenotypes and a list of matplotlib patch objects that have already been added to the current axes and recolors the patches based on the array. """
denom, palette = get_kwargs(phen_grid, kwargs) grid = color_grid(phen_grid, palette, denom) for i in range(len(grid)): for j in range(len(grid[i])): curr_patch = patches[i * len(grid[i]) + j] if grid[i][j] == -1: curr_patch.set_visible(False) else: curr_patch.set_facecolor(grid[i][j]) curr_patch.set_visible(True) return patches
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def color_array_by_value(value, palette, denom, mask_zeros): """ Figure out the appropriate RGB or RGBA color for the given numerical value based on the palette, denom, and whether zeros should be masked. """
if value == -1: # sentinel value return -1 if value == 0 and mask_zeros: # This value is masked if type(palette) is list: return (1, 1, 1) return (1, 1, 1, 1) if type(palette) is list: # This is a palette return palette[value] # This is continuous data so the palette is actually a colormap return palette(float(value)/float(denom))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def color_array_by_hue_mix(value, palette): """ Figure out the appropriate color for a binary string value by averaging the colors corresponding the indices of each one that it contains. Makes for visualizations that intuitively show patch overlap. """
if int(value, 2) > 0: # Convert bits to list and reverse order to avoid issues with # differing lengths int_list = [int(i) for i in list(value[2:])] int_list.reverse() # since this is a 1D array, we need the zeroth elements # of np.nonzero. locs = np.nonzero(int_list)[0] # print(locs) # print(palette) rgb_vals = [palette[i] for i in locs] rgb = [0]*len(rgb_vals[0]) # We don't know if it's rgb or rgba for val in rgb_vals: for index in range(len(val)): rgb[index] += val[index] for i in range(len(rgb)): rgb[i] /= len(locs) return tuple(rgb) if int(value, 2) == 0: return (1, 1, 1) if len(palette[0]) == 3 else (1, 1, 1, 1) return -1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def color_percentages(file_list, n_tasks=9, file_name="color_percent.png", intensification_factor=1.2): """ Creates an image in which each cell in the avida grid is represented as a square of 9 sub-cells. Each of these 9 sub-cells represents a different task, and is colored such that cooler colors represent more complex tasks. The saturation of each sub-cell indicates the percentage of grids in the given data-set in which the organism in that cell could perform the corresponding task. Inputs: file_list - list of names of of avida task grid files to be used in making figure. intensification_factor (default 1.2): A number to multiply the percentage of organisms doing a task by in order to increase visibility. This can be useful in cases where a lot of the percentages are too low to be easily visualized. Returns: Grid indicating appropriate color values for images. """
# Load data data = task_percentages(load_grid_data(file_list)) # Initialize grid grid = [[]] * len(data)*3 for i in range(len(grid)): grid[i] = [[]]*len(data[0])*3 # Color grid for i in range(len(data)): for j in range(len(data[i])): for k in range(3): # create grid of sub-cells for l in range(3): if len(data[i][j]) > k*3+l: # build a color in matplotlib's preferred hsv format arr = np.zeros((1, 1, 3)) arr[0, 0, 1] = float(data[i][j][k*3 + l]) \ * intensification_factor # saturate based on data arr[0, 0, 0] = (k*3 + l)/9.0 # hue based on task arr[0, 0, 2] = 1 # value is always 1 rgb = matplotlib.colors.hsv_to_rgb(arr) # convert rgb grid[i*3+k][j*3+l] = list(rgb[0][0]) else: grid[i*3+k][j*3+l] = (1, 1, 1, 1) return make_imshow_plot(grid, "colorpercentages")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_imshow_plot(grid, name): """ Takes a grid of RGB or RGBA values and a filename to save the figure into. Generates a figure by coloring all grid cells appropriately. """
plt.tick_params(labelbottom="off", labeltop="off", labelleft="off", labelright="off", bottom="off", top="off", left="off", right="off") plt.imshow(grid, interpolation="nearest", aspect=1, zorder=1) plt.tight_layout() plt.savefig(name, dpi=1000, bbox_inches="tight")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_file(old, new): """Copy the old file to the location of the new file :param old: The file to copy :type old: :class:`JB_File` :param new: The JB_File for the new location :type new: :class:`JB_File` :returns: None :rtype: None :raises: None """
oldp = old.get_fullpath() newp = new.get_fullpath() log.info("Copying %s to %s", oldp, newp) new.create_directory() shutil.copy(oldp, newp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_file(f): """Delete the given file :param f: the file to delete :type f: :class:`JB_File` :returns: None :rtype: None :raises: :class:`OSError` """
fp = f.get_fullpath() log.info("Deleting file %s", fp) os.remove(fp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_next(cls, task, releasetype, typ, descriptor=None): """Returns a TaskFileInfo that with the next available version and the provided info :param task: the task of the taskfile :type task: :class:`jukeboxcore.djadapter.models.Task` :param releasetype: the releasetype :type releasetype: str - :data:`jukeboxcore.djadapter.RELEASETYPES` :param typ: the file type, see :data:`TaskFileInfo.TYPES` :type typ: str :param descriptor: the descriptor, if the taskfile has one. :type descriptor: str|None :returns: taskfileinfoobject with next available version and the provided info :rtype: :class:`TaskFileInfo` :raises: None """
qs = dj.taskfiles.filter(task=task, releasetype=releasetype, descriptor=descriptor, typ=typ) if qs.exists(): ver = qs.aggregate(Max('version'))['version__max']+1 else: ver = 1 return TaskFileInfo(task=task, version=ver, releasetype=releasetype, typ=typ, descriptor=descriptor)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_taskfile(self, taskfile): """Create a new TaskFileInfo and return it for the given taskfile :param taskfile: the taskfile to represent :type taskfile: :class:`jukeboxcore.djadapter.models.TaskFile` :returns: a taskfileinfo :rtype: :class:`TaskFileInfo` :raises: None """
return TaskFileInfo(task=taskfile.task, version=taskfile.version, releasetype=taskfile.releasetype, descriptor=taskfile.descriptor, typ=taskfile.typ)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_db_entry(self, comment=''): """Create a db entry for this task file info and link it with a optional comment :param comment: a comment for the task file entry :type comment: str :returns: The created TaskFile django instance and the comment. If the comment was empty, None is returned instead :rtype: tuple of :class:`dj.models.TaskFile` and :class:`dj.models.Note` :raises: ValidationError, If the comment could not be created, the TaskFile is deleted and the Exception is propagated. """
jbfile = JB_File(self) p = jbfile.get_fullpath() user = dj.get_current_user() tf = dj.models.TaskFile(path=p, task=self.task, version=self.version, releasetype=self.releasetype, descriptor=self.descriptor, typ=self.typ, user=user) tf.full_clean() tf.save() note = None if comment: try: note = dj.models.Note(user=user, parent=tf, content=comment) note.full_clean() note.save() except Exception, e: tf.delete() raise e return tf, note
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dir(self, obj): """Return the dirattr of obj formatted with the dirfomat specified in the constructor. If the attr is None then ``None`` is returned not the string ``\'None\'``. :param obj: the fileinfo with information. :type obj: :class:`FileInfo` :returns: the directory or None :rtype: str|None :raises: None """
if self._dirattr is None: return a = attrgetter(self._dirattr)(obj) if a is None: return s = self._dirformat % a return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_chunk(self, obj): """Return the chunkattr of obj formatted with the chunkfomat specified in the constructor If the attr is None then ``None`` is returned not the string ``\'None\'``. :param obj: the fileinfo with information. :type obj: :class:`FileInfo` :returns: the chunk or None :rtype: str|None :raises: None """
if self._chunkattr is None: return a = attrgetter(self._chunkattr)(obj) if a is None: return s = self._chunkformat % a return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ext(self, obj=None): """Return the file extension :param obj: the fileinfo with information. If None, this will use the stored object of JB_File :type obj: :class:`FileInfo` :returns: the file extension :rtype: str :raises: None """
if obj is None: obj = self._obj return self._extel.get_ext(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_name(self, obj=None, withext=True): """Return the filename :param obj: the fileinfo with information. If None, this will use the stored object of JB_File :type obj: :class:`FileInfo` :param withext: If True, return with the fileextension. :type withext: bool :returns: the filename, default is with fileextension :rtype: str :raises: None """
if obj is None: obj = self._obj chunks = [] for e in self._elements: c = e.get_chunk(obj) if c is not None: chunks.append(c) name = '_'.join(chunks) if withext: name = os.extsep.join([name, self.get_ext(obj)]) return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_fullpath(self, withext=True): """Return the filepath with the filename :param withext: If True, return with the fileextension. :type withext: bool :returns: None :rtype: None :raises: None """
p = self.get_path(self._obj) n = self.get_name(self._obj, withext) fp = os.path.join(p,n) return os.path.normpath(fp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_directory(self, path=None): """Create the directory for the given path. If path is None use the path of this instance :param path: the path to create :type path: str :returns: None :rtype: None :raises: OSError """
if path is None: path = self.get_path() if not os.path.exists(path): os.makedirs(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def corpus(self): '''Command to add a corpus to the dsrt library''' # Initialize the addcorpus subcommand's argparser description = '''The corpus subcommand has a number of subcommands of its own, including: list\t-\tlists all available corpora in dsrt's library add\t-\tadds a corpus to dsrt's library''' parser = argparse.ArgumentParser(description=description) self.init_corpus_args(parser) # parse the args we got args = parser.parse_args(sys.argv[2:3]) corpus_command = 'corpus_' + args.corpus_command if not hasattr(self, corpus_command): print('Unrecognized corpus command.') parser.print_help() exit(1) getattr(self, corpus_command)()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dataset(self): '''Command for manipulating or viewing datasets; has a number of subcommands''' # Initialize the addcorpus subcommand's argparser description = '''The dataset subcommand has a number of subcommands of its own, including: list\t-\tlists all available datasets in dsrt's library prepare\t-\tprocesses a corpus into a dataset and adds the processed dataset to dsrt's library''' parser = argparse.ArgumentParser(description=description) self.init_dataset_args(parser) # parse the args we got args = parser.parse_args(sys.argv[2:3]) corpus_command = 'dataset_' + args.dataset_command if not hasattr(self, corpus_command): print('Unrecognized dataset command.') parser.print_help() exit(1) getattr(self, corpus_command)()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dataset_prepare(self): '''Subcommand of dataset for processing a corpus into a dataset''' # Initialize the prepare subcommand's argparser parser = argparse.ArgumentParser(description='Preprocess a raw dialogue corpus into a dsrt dataset') self.init_dataset_prepare_args(parser) # Parse the args we got args = parser.parse_args(sys.argv[3:]) args.config = ConfigurationLoader(args.config).load().data_config print(CLI_DIVIDER + '\n') Preprocessor(**vars(args)).run()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dataset_list(self): '''Subcommand of dataset for listing available datasets''' # Initialize the prepare subcommand's argparser parser = argparse.ArgumentParser(description='Preprocess a raw dialogue corpus into a dsrt dataset') self.init_dataset_list_args(parser) # Parse the args we got args = parser.parse_args(sys.argv[3:]) print(CLI_DIVIDER + '\n') dsrt.application.utils.list_dataset()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def train(self): '''The 'train' subcommand''' # Initialize the train subcommand's argparser parser = argparse.ArgumentParser(description='Train a dialogue model on a dialogue corpus or a dsrt dataset') self.init_train_args(parser) # Parse the args we got args = parser.parse_args(sys.argv[2:]) args.config = ConfigurationLoader(args.config).load().model_config print(CLI_DIVIDER + '\n') Trainer(**vars(args)).run()