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 authenticate_with_serviceaccount(reactor, **kw):
""" Create an ``IAgent`` which can issue authenticated requests to a particular Kubernetes server using a se... |
config = KubeConfig.from_service_account(**kw)
policy = https_policy_from_config(config)
token = config.user["token"]
agent = HeaderInjectingAgent(
_to_inject=Headers({u"authorization": [u"Bearer {}".format(token)]}),
_agent=Agent(reactor, contextFactory=policy),
)
return agent |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def first_time_setup(self):
"""First time running Open Sesame? Create keyring and an auto-unlock key in default keyring. Make sure these things don't already exi... |
if not self._auto_unlock_key_position():
pw = password.create_passwords()[0]
attrs = {'application': self.keyring}
gkr.item_create_sync(self.default_keyring
,gkr.ITEM_GENERIC_SECRET
,self.keyring
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _auto_unlock_key_position(self):
"""Find the open sesame password in the default keyring """ |
found_pos = None
default_keyring_ids = gkr.list_item_ids_sync(self.default_keyring)
for pos in default_keyring_ids:
item_attrs = gkr.item_get_attributes_sync(self.default_keyring, pos)
app = 'application'
if item_attrs.has_key(app) and item_attrs[app] == "ope... |
<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_position_searchable(self):
"""Return dict of the position and corrasponding searchable str """ |
ids = gkr.list_item_ids_sync(self.keyring)
position_searchable = {}
for i in ids:
item_attrs = gkr.item_get_attributes_sync(self.keyring, i)
position_searchable[i] = item_attrs['searchable']
return position_searchable |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _match_exists(self, searchable):
"""Make sure the searchable description doesn't already exist """ |
position_searchable = self.get_position_searchable()
for pos,val in position_searchable.iteritems():
if val == searchable:
return pos
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_password(self, password, **attrs):
"""Save the new password, save the old password with the date prepended """ |
pos_of_match = self._match_exists(attrs['searchable'])
if pos_of_match:
old_password = self.get_password(pos_of_match).get_secret()
gkr.item_delete_sync(self.keyring, pos_of_match)
desc = str(int(time.time())) + "_" + attrs['searchable']
gkr.item_create_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_descriptor_for_idcode(idcode):
"""Use this method to find bsdl descriptions for devices. The caching on this method drastically lower the execution time ... |
idcode = idcode&0x0fffffff
id_str = "XXXX"+bin(idcode)[2:].zfill(28)
descr_file_path = _check_cache_for_idcode(id_str)
if descr_file_path:
with open(descr_file_path, 'r') as f:
dat = json.load(f)
if dat.get("_file_version",-1) == JTAGDeviceDescription.version:
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 _fetch_dimensions(self, dataset):
""" Iterate through semesters, counties and municipalities. """ |
yield Dimension(u"school")
yield Dimension(u"year",
datatype="year")
yield Dimension(u"semester",
datatype="academic_term",
dialect="swedish") # HT/VT
yield Dimension(u"municipality",
dataty... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _merge_configs(configs):
""" Merge one or more ``KubeConfig`` objects. :param list[KubeConfig] configs: The configurations to merge. :return KubeConfig: A si... |
result = {
u"contexts": [],
u"users": [],
u"clusters": [],
u"current-context": None,
}
for config in configs:
for k in {u"contexts", u"users", u"clusters"}:
try:
values = config.doc[k]
except KeyError:
pass
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _merge_configs_from_env(kubeconfigs):
""" Merge configuration files from a ``KUBECONFIG`` environment variable. :param bytes kubeconfigs: A value like the on... |
paths = list(
FilePath(p)
for p
in kubeconfigs.split(pathsep)
if p
)
config = _merge_configs(list(
KubeConfig.from_file(p.path)
for p
in paths
))
return 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 network_kubernetes_from_context( reactor, context=None, path=None, environ=None, default_config_path=FilePath(expanduser(u"~/.kube/config")), ):
""" Create a... |
if path is None:
if environ is None:
from os import environ
try:
kubeconfigs = environ[u"KUBECONFIG"]
except KeyError:
config = KubeConfig.from_file(default_config_path.path)
else:
config = _merge_configs_from_env(kubeconfigs)
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 collection_location(obj):
""" Get the URL for the collection of objects like ``obj``. :param obj: Either a type representing a Kubernetes object kind or an i... |
# TODO kind is not part of IObjectLoader and we should really be loading
# apiVersion off of this object too.
kind = obj.kind
apiVersion = obj.apiVersion
prefix = version_to_segments[apiVersion]
collection = kind.lower() + u"s"
if IObject.providedBy(obj):
# Actual objects *could*... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def execute(ctx):
""" execute story part at the current context and make one step further :param ctx: :return: """ |
tail_depth = len(ctx.stack()) - 1
story_part = ctx.get_current_story_part()
logger.debug('# going to call: {}'.format(story_part.__name__))
waiting_for = story_part(ctx.message)
if inspect.iscoroutinefunction(story_part):
waiting_for = await waiting_for
logger.debug('# got result {}'.f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterate_storyline(ctx):
""" iterate the last storyline from the last visited story part :param ctx: :return: """ |
logger.debug('# start iterate')
compiled_story = ctx.compiled_story()
if not compiled_story:
return
for step in range(ctx.current_step(),
len(compiled_story.story_line)):
ctx = ctx.clone()
tail = ctx.stack_tail()
ctx.message = modify_stack_in_messa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scope_in(ctx):
""" - build new scope on the top of stack - and current scope will wait for it result :param ctx: :return: """ |
logger.debug('# scope_in')
logger.debug(ctx)
ctx = ctx.clone()
compiled_story = None
if not ctx.is_empty_stack():
compiled_story = ctx.get_child_story()
logger.debug('# child')
logger.debug(compiled_story)
# we match child story loop once by message
# what 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 str2date(self, date_str):
""" Parse date from string. If there's no template matches your string, Please go https://github.com/MacHu-GWU/rolex-project/issues... |
# try default date template
try:
a_datetime = datetime.strptime(
date_str, self._default_date_template)
return a_datetime.date()
except:
pass
# try every date templates
for template in date_template_list:
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _str2datetime(self, datetime_str):
""" Parse datetime from string. If there's no template matches your string, Please go https://github.com/MacHu-GWU/rolex-p... |
# try default datetime template
try:
a_datetime = datetime.strptime(
datetime_str, self._default_datetime_template)
return a_datetime
except:
pass
# try every datetime templates
for template in datetime_template_list:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def define(self):
"""If DFA is empty, create a sink state""" |
if len(self.states) == 0:
for char in self.alphabet:
self.add_arc(0, 0, char)
self[0].final = False |
<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_state(self):
"""Adds a new state""" |
sid = len(self.states)
self.states.append(DFAState(sid))
return sid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _epsilon_closure(self, state):
""" Returns the \epsilon-closure for the state given as input. """ |
closure = set([state.stateid])
stack = [state]
while True:
if not stack:
break
s = stack.pop()
for arc in s:
if self.isyms.find(arc.ilabel) != EPSILON or \
arc.nextstate in closure:
c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invert(self):
"""Inverts the DFA final states""" |
for state in self.states:
if state.final:
state.final = False
else:
state.final = 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 as_list(self):
"""
returns a list version of the object, based on it's attributes
""" |
if hasattr(self, 'cust_list'):
return self.cust_list
if hasattr(self, 'attr_check'):
self.attr_check()
cls_bltns = set(dir(self.__class__))
ret = [a for a in dir(self) if a not in cls_bltns and getattr(self, a)]
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_dict(self):
"""
returns an dict version of the object, based on it's attributes
""" |
if hasattr(self, 'cust_dict'):
return self.cust_dict
if hasattr(self, 'attr_check'):
self.attr_check()
cls_bltns = set(dir(self.__class__))
return {a: getattr(self, a) for a in dir(self) if a not in cls_bltns} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_odict(self):
"""
returns an odict version of the object, based on it's attributes
""" |
if hasattr(self, 'cust_odict'):
return self.cust_odict
if hasattr(self, 'attr_check'):
self.attr_check()
odc = odict()
for attr in self.attrorder:
odc[attr] = getattr(self, attr)
return odc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_and_parse(url, bodyLines):
"""Takes a url, and returns a dictionary of data with 'bodyLines' lines""" |
pageHtml = fetch_page(url)
return parse(url, pageHtml, bodyLines) |
<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_rec(source, dest):
"""Copy files between diferent directories. Copy one or more files to an existing directory. This function is recursive, if the sourc... |
if os.path.isdir(source):
for child in os.listdir(source):
new_dest = os.path.join(dest, child)
os.makedirs(new_dest, exist_ok=True)
copy_rec(os.path.join(source, child), new_dest)
elif os.path.isfile(source):
logging.info(' Copy "{}" to "{}"'.format(source... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build(self):
""" Builds this object into the desired output information. """ |
signed = bool(self.options() & Builder.Options.Signed)
# remove previous build information
buildpath = self.buildPath()
if not buildpath:
raise errors.InvalidBuildPath(buildpath)
# setup the environment
for key, value in self.environment().items():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generateRevision(self):
""" Generates the revision file for this builder. """ |
revpath = self.sourcePath()
if not os.path.exists(revpath):
return
# determine the revision location
revfile = os.path.join(revpath, self.revisionFilename())
mode = ''
# test for svn revision
try:
args = ['svn', 'info', revpath]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generateSetupFile(self, outpath='.', egg=False):
""" Generates the setup file for this builder. """ |
outpath = os.path.abspath(outpath)
outfile = os.path.join(outpath, 'setup.py')
opts = {
'name': self.name(),
'distname': self.distributionName(),
'version': self.version(),
'author': self.author(),
'author_email': self.authorEmail(),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generateZipFile(self, outpath='.'):
""" Generates the zip file for this builder. """ |
fname = self.installName() + '.zip'
outfile = os.path.abspath(os.path.join(outpath, fname))
# clears out the exiting archive
if os.path.exists(outfile):
try:
os.remove(outfile)
except OSError:
log.warning('Could not remove zipfile... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def step_undefined_step_snippets_should_exist_for_table(context):
""" Checks if undefined-step snippets are provided. EXAMPLE: Then undefined-step snippets shoul... |
assert context.table, "REQUIRES: table"
for row in context.table.rows:
step = row["Step"]
step_undefined_step_snippet_should_exist_for(context, step) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def step_undefined_step_snippets_should_not_exist_for_table(context):
""" Checks if undefined-step snippets are not provided. EXAMPLE: Then undefined-step snippe... |
assert context.table, "REQUIRES: table"
for row in context.table.rows:
step = row["Step"]
step_undefined_step_snippet_should_not_exist_for(context, step) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mixin (cls):
""" A decorator which adds event methods to a class giving it the ability to bind to and trigger events :param cls: the class to add the event l... |
cls._events = {}
cls.bind = Pyevent.bind.__func__
cls.unbind = Pyevent.unbind.__func__
cls.trigger = Pyevent.trigger.__func__
return cls |
<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_options(paths,fname_def=None):
"""Builds a configuration reader function""" |
def reader_func(fname=fname_def, sect=None, sett=None, default=None):
"""Reads the configuration for trump"""
cur_dir = os.path.dirname(os.path.realpath(__file__))
config_dir = os.path.join(cur_dir, *paths)
config_files = [(f[:-4], f)
for f in os.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 returnLabelState(peptide, labelDescriptor, labelSymbols=None, labelAminoacids=None):
"""Calculates the label state of a given peptide for the label setup des... |
if labelSymbols is None:
labelSymbols = modSymbolsFromLabelInfo(labelDescriptor)
if labelAminoacids is None:
labelAminoacids = modAminoacidsFromLabelInfo(labelDescriptor)
sequence = maspy.peptidemethods.removeModifications(peptide)
modPositions = maspy.peptidemethods.returnModPositions... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modSymbolsFromLabelInfo(labelDescriptor):
"""Returns a set of all modiciation symbols which were used in the labelDescriptor :param labelDescriptor: :class:`... |
modSymbols = set()
for labelStateEntry in viewvalues(labelDescriptor.labels):
for labelPositionEntry in viewvalues(labelStateEntry['aminoAcidLabels']):
for modSymbol in aux.toList(labelPositionEntry):
if modSymbol != '':
modSymbols.add(modSymbol)
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modAminoacidsFromLabelInfo(labelDescriptor):
"""Returns a set of all amino acids and termini which can bear a label, as described in "labelDescriptor". :para... |
modAminoacids = set()
for labelStateEntry in viewvalues(labelDescriptor.labels):
for labelPositionEntry in viewkeys(labelStateEntry['aminoAcidLabels']):
for modAminoacid in aux.toList(labelPositionEntry):
if modAminoacid != '':
modAminoacids.add(modAminoa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expectedLabelPosition(peptide, labelStateInfo, sequence=None, modPositions=None):
"""Returns a modification description of a certain label state of a peptide... |
if modPositions is None:
modPositions = maspy.peptidemethods.returnModPositions(peptide,
indexStart=0
)
if sequence is None:
sequence = maspy.peptidemethods.removeModifi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addLabel(self, aminoAcidLabels, excludingModifications=None):
"""Adds a new labelstate. :param aminoAcidsLabels: Describes which amino acids can bear which l... |
if excludingModifications is not None:
self.excludingModifictions = True
labelEntry = {'aminoAcidLabels': aminoAcidLabels,
'excludingModifications': excludingModifications
}
self.labels[self._labelCounter] = labelEntry
self._label... |
<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_gen_slice(ctx=Bubble(), iterable=[], amount=-1, index=-1):
"""very crude way of slicing a generator""" |
ctx.gbc.say('get_gen_slice', stuff=iterable, verbosity=10)
i = -1
# TODO
# i = 0 #NATURAL INDEX, this will break all features with exports and -p
if amount > 0:
if index < 0:
index = 0
else:
for item in iterable:
i += 1
item[buts('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_scripts(self, scripts_path_rel, files_deployment, script_type, project_path):
""" Gets scripts from specified folders """ |
scripts_dict = {}
if scripts_path_rel:
self._logger.debug('Getting scripts with {0} definitions'.format(script_type))
scripts_dict = pgpm.lib.utils.misc.collect_scripts_from_sources(scripts_path_rel, files_deployment,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resolve_dependencies(self, cur, dependencies):
""" Function checks if dependant packages are installed in DB """ |
list_of_deps_ids = []
_list_of_deps_unresolved = []
_is_deps_resolved = True
for k, v in dependencies.items():
pgpm.lib.utils.db.SqlScriptsHelper.set_search_path(cur, self._pgpm_schema_name)
cur.execute("SELECT _find_schema('{0}', '{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 _reorder_types(self, types_script):
""" Takes type scripts and reorders them to avoid Type doesn't exist exception """ |
self._logger.debug('Running types definitions scripts')
self._logger.debug('Reordering types definitions scripts to avoid "type does not exist" exceptions')
_type_statements = sqlparse.split(types_script)
# TODO: move up to classes
_type_statements_dict = {} # dictionary that 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 find_table_links(self):
""" When given a url, this function will find all the available table names for that EPA dataset. """ |
html = urlopen(self.model_url).read()
doc = lh.fromstring(html)
href_list = [area.attrib['href'] for area in doc.cssselect('map area')]
tables = self._inception_table_links(href_list)
return tables |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_definition_urls(self, set_of_links):
"""Find the available definition URLs for the columns in a table.""" |
definition_dict = {}
re_link_name = re.compile('.*p_table_name=(\w+)&p_topic.*')
for link in set_of_links:
if link.startswith('http://'):
table_dict = {}
html = urlopen(link).read()
doc = lh.fromstring(html)
unordered_l... |
<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_agency(self):
"""Create an agency text file of definitions.""" |
agency = self.agency
links = self.find_table_links()
definition_dict = self.find_definition_urls(links)
with open(agency + '.txt', 'w') as f:
f.write(str(definition_dict)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loop_through_agency(self):
"""Loop through an agency to grab the definitions for its tables.""" |
agency = self.agency
with open(agency + '.txt') as f:
data = eval(f.read())
for table in data:
for column in data[table]:
value_link = data[table][column]
data[table][column] = self.grab_definition(value_link)
data = json.dumps(dat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grab_definition(self, url):
""" Grab the column definition of a table from the EPA using a combination of regular expressions and lxml. """ |
re_description = re.compile('Description:(.+?\\n)')
re_table_name = re.compile("(\w+ Table.+)")
if url.startswith('//'):
url = 'http:' + url
elif url.startswith('/'):
url = 'http://www.epa.gov' + url
try:
html = urlopen(url).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 main(*argv, filesystem=None, do_exit=True, stdout=None, stderr=None):
"""Main method for the cli. We allow the filesystem to be overridden for test purposes.... |
try:
mdcli = MdCLI()
mdcli.filesystem = filesystem
mdcli.stdout = stdout or sys.stdout
mdcli.stderr = stderr or sys.stderr
retval = mdcli.main(*argv, loop=LOOP_NEVER)
if do_exit:
sys.exit(retval)
else:
return retval
except Keyboard... |
<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_optparser(self):
"""Override to allow specification of the maildir""" |
p = Cmdln.get_optparser(self)
p.add_option(
"-M",
"--maildir",
action="store",
dest="maildir"
)
p.add_option(
"-V",
"--verbose",
action="store_true",
dest="verbose"
)
... |
<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(context, form, **kwargs):
""" The `form` template tag will render a tape-form enabled form using the template provided by `get_layout_template` method o... |
if not isinstance(form, (forms.BaseForm, TapeformFieldset)):
raise template.TemplateSyntaxError(
'Provided form should be a `Form` instance, actual type: {0}'.format(
form.__class__.__name__))
return render_to_string(
form.get_layout_template(kwargs.get('using', No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formfield(context, bound_field, **kwargs):
""" The `formfield` template tag will render a form field of a tape-form enabled form using the template provided ... |
if not isinstance(bound_field, forms.BoundField):
raise template.TemplateSyntaxError(
'Provided field should be a `BoundField` instance, actual type: {0}'.format(
bound_field.__class__.__name__))
return render_to_string(
bound_field.form.get_field_template(bound_fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def wrap_as_node(self, func):
'wrap a function as a node'
name = self.get_name(func)
@wraps(func)
def wrapped(*args, **kwargs):
'wrapped version of func'
message = self.get_message_from_call(*args, **kwargs)
self.logger.info('calling "%s" with %r', na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def node(self, fields, subscribe_to=None, entry_point=False, ignore=None,
**wrapper_options):
'''\
Decorate a function to make it a node.
.. note::
decorating as a node changes the function signature. Nodes should
accept a single argument, which will be a
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def resolve_node_modules(self):
'import the modules specified in init'
if not self.resolved_node_modules:
try:
self.resolved_node_modules = [
importlib.import_module(mod, self.node_package)
for mod in self.node_modules
]... |
<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_message_from_call(self, *args, **kwargs):
'''\
Get message object from a call.
:raises: :py:exc:`TypeError` (if the format is not what we expect)
This is where arguments to nodes are turned into Messages. Arguments
are parsed in the following order:
- A single... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def register(self, name, func, fields, subscribe_to, entry_point, ignore):
'''
Register a named function in the graph
:param name: name to register
:type name: :py:class:`str`
:param func: function to remember and call
:type func: callable
``fields``, ``subscrib... |
<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_entry_point(self, destination):
'''\
Add an entry point
:param destination: node to route to initially
:type destination: str
'''
self.routes.setdefault('__entry_point', set()).add(destination)
return self.routes['__entry_point'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def register_route(self, origins, destination):
'''
Add routes to the routing dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str` or None
:param destination: where the origins should point to
:type dest... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def register_ignore(self, origins, destination):
'''
Add routes to the ignore dictionary
:param origins: a number of origins to register
:type origins: :py:class:`str` or iterable of :py:class:`str`
:param destination: where the origins should point to
:type destination:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def regenerate_routes(self):
'regenerate the routes after a new route is added'
for destination, origins in self.regexes.items():
# we want only the names that match the destination regexes.
resolved = [
name for name in self.names
if name is not 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 route(self, origin, message):
'''\
Using the routing dictionary, dispatch a message to all subscribers
:param origin: name of the origin node
:type origin: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dispatch(self, origin, destination, message):
'''\
dispatch a message to a named function
:param destination: destination to dispatch to
:type destination: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def wrap_result(self, name, result):
'''
Wrap a result from a function with it's stated fields
:param name: fields to look up
:type name: :py:class:`str`
:param result: return value from function. Will be converted to tuple.
:type result: anything
:raises: :py: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 get_name(self, func):
'''
Get the name to reference a function by
:param func: function to get the name of
:type func: callable
'''
if hasattr(func, 'name'):
return func.name
return '%s.%s' % (
func.__module__,
func.__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 main():
""" Testing function for PDA - DFA Diff Operation """ |
if len(argv) < 2:
print 'Usage: '
print ' Get A String %s CFG_fileA FST_fileB' % argv[0]
return
alphabet = createalphabet()
cfgtopda = CfgPDA(alphabet)
print '* Parsing Grammar:',
mma = cfgtopda.yyparse(argv[1])
print 'OK'
flex_a = Flexparser(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _intesect(self):
"""The intesection of a PDA and a DFA""" |
p1automaton = self.mma
p2automaton = self.mmb
p3automaton = PDA(self.alphabet)
self._break_terms()
p1counter = 0
p3counter = 0
p2states = list(p2automaton.states)
print 'PDA States: ' + repr(p1automaton.n)
print 'DFA States: ' + repr(len(list(p2st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diff(self):
"""The Difference between a PDA and a DFA""" |
self.mmb.complement(self.alphabet)
self.mmb.minimize()
print 'start intersection'
self.mmc = self._intesect()
print 'end intersection'
return self.mmc |
<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_devices(self):
'''Queries hub for list of devices, and creates new device objects'''
try:
response = self.api.get("/api/v2/devices", {'properties':'all'})
for device_data in response['DeviceList']:
self.devices.append(Device(device_data, 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 refresh_details(self):
'''Query hub and refresh all details of a device,
but NOT status, includes grouplist not present in
refresh_all_devices'''
try:
return self.api_iface._api_get("/api/v2/devices/" + str(self.device_id))
except APIError as e:
print(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def send_command(self, command):
'''Send a command to a device'''
data = {"command": command, "device_id": self.device_id}
try:
response = self.api_iface._api_post("/api/v2/commands", data)
return Command(response, self)
except APIError as e:
print("AP... |
<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_details(self,data):
'''Intakes dict of details, and sets necessary properties
in device'''
# DeviceName, IconID, HouseID, DeviceID always present
self.device_id = data['DeviceID']
self.device_name = data['DeviceName']
self.properties = 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 _update_details(self,data):
'''Intakes dict of details, and sets necessary properties
in command'''
for api_name in self._properties:
if api_name in data:
setattr(self, "_" + api_name, data[api_name])
else:
# Only set to blank if not in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def query_status(self):
'''Query the hub for the status of this command'''
try:
data = self.api_iface._api_get(self.link)
self._update_details(data)
except APIError as e:
print("API error: ")
for key,value in e.data.iteritems:
print... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tracks(self):
""" Tracks list context :return: Tracks list context """ |
if self._tracks is None:
self._tracks = TrackList(self.version, self.id)
return self._tracks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extension(names):
"""Makes a function to be an extension.""" |
for name in names:
if not NAME_PATTERN.match(name):
raise ValueError('invalid extension name: %s' % name)
def decorator(f, names=names):
return Extension(f, names=names)
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 register(self, extensions):
"""Registers extensions.""" |
for ext in reversed(extensions):
for name in ext.names:
try:
self._extensions[name].appendleft(ext)
except KeyError:
self._extensions[name] = deque([ext]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eval_extensions(self, value, name, option, format):
"""Evaluates extensions in the registry. If some extension handles the format string, it returns a string... |
try:
exts = self._extensions[name]
except KeyError:
raise ValueError('no suitable extension: %s' % name)
for ext in exts:
rv = ext(self, value, name, option, format)
if rv is not None:
return rv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetShowDetails(self):
""" Extract show name, season number and episode number from file name. Supports formats S<NUM>E<NUM> or <NUM>x<NUM> for season and epi... |
fileName = os.path.splitext(os.path.basename(self.fileInfo.origPath))[0]
# Episode Number
episodeNumSubstring = set(re.findall("(?<=[0-9])[xXeE][0-9]+(?:[xXeE_.-][0-9]+)*", fileName))
if len(episodeNumSubstring) != 1:
goodlogging.Log.Info("TVFILE", "Incompatible filename no episode match detec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GenerateNewFilePath(self, fileDir = None):
""" Create new file path. If a fileDir is provided it will be used otherwise the original file path is used. Updat... |
newFileName = self.GenerateNewFileName()
if newFileName is not None:
if fileDir is None:
fileDir = os.path.dirname(self.fileInfo.origPath)
self.fileInfo.newPath = os.path.join(fileDir, newFileName) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Print(self):
""" Print contents of showInfo and FileInfo object """ |
goodlogging.Log.Info("TVFILE", "TV File details are:")
goodlogging.Log.IncreaseIndent()
goodlogging.Log.Info("TVFILE", "Original File Path = {0}".format(self.fileInfo.origPath))
if self.showInfo.showName is not None:
goodlogging.Log.Info("TVFILE", "Show Name (from guide) = {0}".format(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 connectProcess(connection, processProtocol, commandLine='', env={}, usePTY=None, childFDs=None, *args, **kwargs):
"""Opens a SSHSession channel and connects ... |
processOpenDeferred = defer.Deferred()
process = SSHProcess(processProtocol, commandLine, env, usePTY, childFDs,
*args, **kwargs)
process.processOpen = processOpenDeferred.callback
process.openFailed = processOpenDeferred.errback
connection.openChannel(process)
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 call_builder_init(cls, kb_app, sphinx_app: Sphinx):
""" On builder init event, commit registry and do callbacks """ |
# Find and commit docs project plugins
conf_dir = sphinx_app.confdir
plugins_dir = sphinx_app.config.kaybee_settings.plugins_dir
full_plugins_dir = os.path.join(conf_dir, plugins_dir)
if os.path.exists(full_plugins_dir):
sys.path.insert(0, conf_dir)
plu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_purge_doc(cls, kb_app, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, docname: str):
""" On env-purge-doc, do callbacks """ |
for callback in EventAction.get_callbacks(kb_app, SphinxEvent.EPD):
callback(kb_app, sphinx_app, sphinx_env, docname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_env_before_read_docs(cls, kb_app, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, docnames: List[str]):
""" On env-read-docs, do callbacks""" |
for callback in EventAction.get_callbacks(kb_app,
SphinxEvent.EBRD):
callback(kb_app, sphinx_app, sphinx_env, docnames) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_env_doctree_read(cls, kb_app, sphinx_app: Sphinx, doctree: doctree):
""" On doctree-read, do callbacks""" |
for callback in EventAction.get_callbacks(kb_app,
SphinxEvent.DREAD):
callback(kb_app, sphinx_app, doctree) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_env_updated(cls, kb_app, sphinx_app: Sphinx, sphinx_env: BuildEnvironment):
""" On the env-updated event, do callbacks """ |
for callback in EventAction.get_callbacks(kb_app, SphinxEvent.EU):
callback(kb_app, sphinx_app, sphinx_env) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_html_collect_pages(cls, kb_app, sphinx_app: Sphinx):
""" On html-collect-pages, do callbacks""" |
EventAction.get_callbacks(kb_app,
SphinxEvent.HCP)
for callback in EventAction.get_callbacks(kb_app,
SphinxEvent.HCP):
yield callback(kb_app, sphinx_app) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_env_check_consistency(cls, kb_app, builder: StandaloneHTMLBuilder, sphinx_env: BuildEnvironment):
""" On env-check-consistency, do callbacks""" |
for callback in EventAction.get_callbacks(kb_app,
SphinxEvent.ECC):
callback(kb_app, builder, sphinx_env) |
<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_layout_template(self, template_name=None):
""" Returns the layout template to use when rendering the form to HTML. Preference of template selection: 1. P... |
if template_name:
return template_name
if self.layout_template:
return self.layout_template
return defaults.LAYOUT_DEFAULT_TEMPLATE |
<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_layout_context(self):
""" Returns the context which is used when rendering the form to HTML. The generated template context will contain the following va... |
errors = self.non_field_errors()
for field in self.hidden_fields():
errors.extend(field.errors)
return {
'form': self,
'errors': errors,
'hidden_fields': self.hidden_fields(),
'visible_fields': self.visible_fields(),
} |
<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_field_template(self, bound_field, template_name=None):
""" Returns the field template to use when rendering a form field to HTML. Preference of template ... |
if template_name:
return template_name
templates = self.field_template_overrides or {}
template_name = templates.get(bound_field.name, None)
if template_name:
return template_name
template_name = templates.get(bound_field.field.__class__, None)
... |
<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_field_label_css_class(self, bound_field):
""" Returns the optional label CSS class to use when rendering a field template. By default, returns the Form c... |
class_name = self.field_label_css_class
if bound_field.errors and self.field_label_invalid_css_class:
class_name = join_css_class(
class_name, self.field_label_invalid_css_class)
return class_name or None |
<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_field_context(self, bound_field):
""" Returns the context which is used when rendering a form field to HTML. The generated template context will contain ... |
widget = bound_field.field.widget
widget_class_name = widget.__class__.__name__.lower()
# Check if we have an overwritten id in widget attrs,
# if not use auto_id of bound field.
field_id = widget.attrs.get('id') or bound_field.auto_id
if field_id:
field_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 apply_widget_template(self, field_name):
""" Applies widget template overrides if available. The method uses the `get_widget_template` method to determine if... |
field = self.fields[field_name]
template_name = self.get_widget_template(field_name, field)
if template_name:
field.widget.template_name = template_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_widget_template(self, field_name, field):
""" Returns the optional widget template to use when rendering the widget for a form field. Preference of templ... |
templates = self.widget_template_overrides or {}
template_name = templates.get(field_name, None)
if template_name:
return template_name
template_name = templates.get(field.widget.__class__, None)
if template_name:
return template_name
return No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_widget_css_class(self, field_name):
""" Applies CSS classes to widgets if available. The method uses the `get_widget_css_class` method to determine if ... |
field = self.fields[field_name]
class_name = self.get_widget_css_class(field_name, field)
if class_name:
field.widget.attrs['class'] = join_css_class(
field.widget.attrs.get('class', None), class_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 apply_widget_invalid_options(self, field_name):
""" Applies additional widget options for an invalid field. This method is called when there is some error on... |
field = self.fields[field_name]
class_name = self.get_widget_invalid_css_class(field_name, field)
if class_name:
field.widget.attrs['class'] = join_css_class(
field.widget.attrs.get('class', None), class_name)
field.widget.attrs['aria-invalid'] = '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 use_quandl_data(self, authtoken):
""" Use quandl data to build conversion table """ |
dfs = {}
st = self.start.strftime("%Y-%m-%d")
at = authtoken
for pair in self.pairs:
symbol = "".join(pair)
qsym = "CURRFX/{}".format(symbol)
dfs[symbol] = qdl.get(qsym,authtoken=at, trim_start=st)['Rate']
self.build_conversion_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 build_conversion_table(self, dataframes):
""" Build conversion table from a dictionary of dataframes """ |
self.data = pd.DataFrame(dataframes)
tmp_pairs = [s.split("/") for s in self.data.columns]
self.data.columns = pd.MultiIndex.from_tuples(tmp_pairs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.