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 b... |
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: :cl... |
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: ... |
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 ... |
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 :t... |
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... |
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.t... |
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.Tr... |
<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, s... |
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():
... |
<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... |
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(proje... |
<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 des... |
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 = treemo... |
<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 rele... |
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 rel... |
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)
... |
<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... |
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: th... |
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]
ta... |
<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 :p... |
# 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)
#... |
<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... |
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:`djada... |
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:
... |
<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.P... |
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 ValueErro... |
<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 t... |
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(... |
<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... |
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... |
<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.... |
<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 bro... |
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)
... |
<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._sessio... |
<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,
)
... |
<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 t... |
# 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_r... |
<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 m... |
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(ty... |
<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 represen... |
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:
... |
<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... |
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 clust... |
<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.... |
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... |
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] = 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 make_optimal_phenotype_grid(environment, phenotypes):
""" Takes an EnvironmentFile object and a 2d array of phenotypes and returns a 2d array in which each l... |
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],
en... |
<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 ... |
# 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_li... |
<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,
... |
<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 workbe... |
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 w... |
unhandledInput = partial(ui._unhandledInput,
workbench=workbench,
launcher=launcher)
mainLoop = urwid.MainLoop(widget=workbench.widget,
palette=ui.DEFAULT_PALETTE,
unhandled_input=unhandledInpu... |
<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 :p... |
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 :r... |
# 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.sta... |
<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 t... |
<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
# typewri... |
<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: requ... |
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,
... |
<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... |
# 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 verb... |
<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 ... |
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 an... |
<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 ... |
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: ... |
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 ... |
<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_u... |
<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,
... |
<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))
ser... |
<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: f... |
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(*... |
<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 ... |
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 w... |
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 eleme... |
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 w... |
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:
... |
<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... |
<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
e... |
<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 modi... |
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:... |
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[ke... |
<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')
... |
<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 str... |
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 shou... |
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),
... |
<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 perfo... |
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:
... |
<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 m... |
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)
el... |
<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,... |
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 ... |
<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 e... |
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.nonzer... |
<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... |
# 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): # creat... |
<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 ap... |
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 fo... |
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... |
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, descripto... |
<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 task... |
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 fi... |
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... |
<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 ... |
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... |
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 ob... |
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... |
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)])
... |
<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 :retur... |
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 ... |
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-\t... |
<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 ds... |
<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)
... |
<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 th... |
<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.p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.