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 _add_filter_node(root, filter_, value):
"""Adds filter xml node to root.""" |
filter_el = ElementTree.SubElement(root, 'Filter')
filter_el.set('name', filter_.name)
# Set filter value depending on type.
if filter_.type == 'boolean':
# Boolean case.
if value is True or value.lower() in {'included', 'only'}:
filter_el.set('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_potential_markables(docgraph):
""" returns a list of all NPs and PPs in the given docgraph. Parameters docgraph : DiscourseDocumentGraph a document graph... |
potential_markables = []
for node_id, nattr in dg.select_nodes_by_layer(docgraph, 'tiger:syntax', data=True):
if nattr['tiger:cat'] == 'NP':
# if an NP is embedded into a PP, only print the PP
pp_parent = False
for source, target in docgraph.in_edges(node_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 _parse_common_paths_file(project_path):
""" Parses a common_paths.xml file and returns a dictionary of paths, a dictionary of annotation level descriptions a... |
common_paths_file = os.path.join(project_path, 'common_paths.xml')
tree = etree.parse(common_paths_file)
paths = {}
path_vars = ['basedata', 'scheme', 'style', 'style', 'customization',
'markable']
for path_var in path_vars:
specific_path = tree... |
<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_sentences_and_token_nodes(self):
""" Returns a list of sentence root node IDs and a list of sentences, where each list contains the token node IDs of tha... |
token_nodes = []
# if sentence annotations were ignored during MMAXDocumentGraph
# construction, we need to extract sentence/token node IDs manually
if self.ignore_sentence_annotations:
mp = self.mmax_project
layer_dict = mp.annotations['sentence']
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 get_token_nodes_from_sentence(self, sentence_root_node):
"""returns a list of token node IDs belonging to the given sentence""" |
return spanstring2tokens(self, self.node[sentence_root_node][self.ns+':span']) |
<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_token_layer(self, words_file, connected):
""" parses a _words.xml file, adds every token to the document graph and adds an edge from the MMAX root node t... |
for word in etree.parse(words_file).iterfind('//word'):
token_node_id = word.attrib['id']
self.tokens.append(token_node_id)
token_str = ensure_unicode(word.text)
self.add_node(token_node_id,
layers={self.ns, self.ns+':token'},
... |
<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_annotation_layer(self, annotation_file, layer_name):
""" adds all markables from the given annotation layer to the discourse graph. """ |
assert os.path.isfile(annotation_file), \
"Annotation file doesn't exist: {}".format(annotation_file)
tree = etree.parse(annotation_file)
root = tree.getroot()
default_layers = {self.ns, self.ns+':markable', self.ns+':'+layer_name}
# avoids eml.org namespace handli... |
<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_edu_text(text_subtree):
"""return the text of the given EDU subtree, with '_!'-delimiters removed.""" |
assert text_subtree.label() == 'text', "text_subtree: {}".format(text_subtree)
edu_str = u' '.join(word for word in text_subtree.leaves())
return re.sub('_!(.*?)_!', '\g<1>', edu_str) |
<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_node_id(nuc_or_sat, namespace=None):
"""return the node ID of the given nucleus or satellite""" |
node_type = get_node_type(nuc_or_sat)
if node_type == 'leaf':
leaf_id = nuc_or_sat[0].leaves()[0]
if namespace is not None:
return '{0}:{1}'.format(namespace, leaf_id)
else:
return string(leaf_id)
#else: node_type == 'span'
span_start = nuc_or_sat[0].lea... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datasets(self):
"""List of datasets in this mart.""" |
if self._datasets is None:
self._datasets = self._fetch_datasets()
return self._datasets |
<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_datasets(self):
"""Lists available datasets in a readable DataFrame format. Returns: pd.DataFrame: Frame listing available datasets. """ |
def _row_gen(attributes):
for attr in attributes.values():
yield (attr.name, attr.display_name)
return pd.DataFrame.from_records(
_row_gen(self.datasets),
columns=['name', 'display_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 extract_relationtypes(rs3_xml_tree):
""" extracts the allowed RST relation names and relation types from an RS3 XML file. Parameters rs3_xml_tree : lxml.etre... |
return {rel.attrib['name']: rel.attrib['type']
for rel in rs3_xml_tree.iter('rel')
if 'type' in rel.attrib} |
<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_node_id(edge, node_type):
""" returns the source or target node id of an edge, depending on the node_type given. """ |
assert node_type in ('source', 'target')
_, node_id_str = edge.attrib[node_type].split('.') # e.g. //@nodes.251
return int(node_id_str) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def traverse_dependencies_up(docgraph, node_id, node_attr=None):
""" starting from the given node, traverse ingoing edges up to the root element of the sentence.... |
# there's only one, but we're in a multidigraph
source, target = docgraph.in_edges(node_id)[0]
traverse_attr = node_attr if node_attr else docgraph.lemma_attr
attrib_value = docgraph.node[source].get(traverse_attr)
if attrib_value:
yield attrib_value
if istoken(docgraph, source) is 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 __add_dependency(self, word_instance, sent_id):
""" adds an ingoing dependency relation from the projected head of a token to the token itself. """ |
# 'head_attr': (projected) head
head = word_instance.__getattribute__(self.head_attr)
deprel = word_instance.__getattribute__(self.deprel_attr)
if head == '0':
# word represents the sentence root
source_id = sent_id
else:
source_id = '{0}_t{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 __build_markable_token_mapper(self, coreference_layer=None, markable_layer=None):
""" Creates mappings from tokens to the markable spans they belong to and t... |
tok2markables = defaultdict(set)
markable2toks = defaultdict(list)
markable2chains = defaultdict(list)
coreference_chains = get_pointing_chains(self.docgraph,
layer=coreference_layer)
for chain_id, chain in enumerate(coreference_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __gen_coref_str(self, token_id, markable_id, target_id):
""" generates the string that represents the markables and coreference chains that a token is part o... |
span = self.markable2toks[markable_id]
coref_str = str(target_id)
if span.index(token_id) == 0:
# token is the first element of a markable span
coref_str = '(' + coref_str
if span.index(token_id) == len(span)-1:
# token is the last element of a markab... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_sentences(nodes, token_node_indices):
""" given a list of ``SaltNode``\s, returns a list of lists, where each list contains the indices of the nodes ... |
sents = []
tokens = []
for i, node in enumerate(nodes):
if i in token_node_indices:
if node.features['tiger.pos'] != '$.':
tokens.append(i)
else: # start a new sentence, if 'tiger.pos' is '$.'
tokens.append(i)
sents.append(tok... |
<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_gexf(docgraph, output_file):
""" takes a document graph, converts it into GEXF format and writes it to a file. """ |
dg_copy = deepcopy(docgraph)
remove_root_metadata(dg_copy)
layerset2str(dg_copy)
attriblist2str(dg_copy)
nx_write_gexf(dg_copy, output_file) |
<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_child_nodes(docgraph, parent_node_id, data=False):
"""Yield all nodes that the given node dominates or spans.""" |
return select_neighbors_by_edge_attribute(
docgraph=docgraph,
source=parent_node_id,
attribute='edge_type',
value=[EdgeTypes.dominance_relation],
data=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 get_parents(docgraph, child_node, strict=True):
"""Return a list of parent nodes that dominate this child. In a 'syntax tree' a node never has more than one ... |
parents = []
for src, _, edge_attrs in docgraph.in_edges(child_node, data=True):
if edge_attrs['edge_type'] == EdgeTypes.dominance_relation:
parents.append(src)
if strict and len(parents) > 1:
raise ValueError(("In a syntax tree, a node can't be "
"dom... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sorted_bfs_edges(G, source=None):
"""Produce edges in a breadth-first-search starting at source. Neighbors appear in the order a linguist would expect in a s... |
if source is None:
source = G.root
xpos = horizontal_positions(G, source)
visited = set([source])
source_children = get_child_nodes(G, source)
queue = deque([(source, iter(sorted(source_children,
key=lambda x: xpos[x])))])
while queue:
pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sorted_bfs_successors(G, source=None):
"""Return dictionary of successors in breadth-first-search from source. Parameters G : DiscourseDocumentGraph graph so... |
if source is None:
source = G.root
successors = defaultdict(list)
for src, target in sorted_bfs_edges(G, source):
successors[src].append(target)
return dict(successors) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node2bracket(docgraph, node_id, child_str=''):
"""convert a docgraph node into a PTB-style string.""" |
node_attrs = docgraph.node[node_id]
if istoken(docgraph, node_id):
pos_str = node_attrs.get(docgraph.ns+':pos', '')
token_str = node_attrs[docgraph.ns+':token']
return u"({pos}{space1}{token}{space2}{child})".format(
pos=pos_str, space1=bool(pos_str)*' ', token=token_str,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tree2bracket(docgraph, root=None, successors=None):
"""convert a docgraph into a PTB-style string. If root (a node ID) is given, only convert the subgraph th... |
if root is None:
root = docgraph.root
if successors is None:
successors = sorted_bfs_successors(docgraph, root)
if root in successors:
embed_str = u" ".join(tree2bracket(docgraph, child, successors)
for child in successors[root])
return node2br... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def word_wrap_tree(parented_tree, width=0):
"""line-wrap an NLTK ParentedTree for pretty-printing""" |
if width != 0:
for i, leaf_text in enumerate(parented_tree.leaves()):
dedented_text = textwrap.dedent(leaf_text).strip()
parented_tree[parented_tree.leaf_treeposition(i)] = textwrap.fill(dedented_text, width=width)
return parented_tree |
<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(self, rst_tree, node_id=None):
"""Get the linear position of an element of this DGParentedTree in an RSTTree. If ``node_id`` is given, this will... |
if node_id is None:
node_id = self.root_id
if node_id in rst_tree.edu_set:
return rst_tree.edus.index(node_id)
return min(self.get_position(rst_tree, child_node_id)
for child_node_id in rst_tree.child_dict[node_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 get(self, **params):
"""Performs get request to the biomart service. Args: **params (dict of str: any):
Arbitrary keyword arguments, which are added as para... |
if self._use_cache:
r = requests.get(self.url, params=params)
else:
with requests_cache.disabled():
r = requests.get(self.url, params=params)
r.raise_for_status()
return 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 fromstring(cls, ptb_string, namespace='ptb', precedence=False, ignore_traces=True):
"""create a PTBDocumentGraph from a string containing PTB parses.""" |
temp = tempfile.NamedTemporaryFile(delete=False)
temp.write(ptb_string)
temp.close()
ptb_docgraph = cls(ptb_filepath=temp.name, namespace=namespace,
precedence=precedence, ignore_traces=ignore_traces)
os.unlink(temp.name)
return ptb_docgraph |
<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_sentence(self, sentence, ignore_traces=True):
""" add a sentence from the input document to the document graph. Parameters sentence : nltk.tree.Tree a s... |
self.sentences.append(self._node_id)
# add edge from document root to sentence root
self.add_edge(self.root, self._node_id, edge_type=dg.EdgeTypes.dominance_relation)
self._parse_sentencetree(sentence, ignore_traces=ignore_traces)
self._node_id += 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 _parse_sentencetree(self, tree, parent_node_id=None, ignore_traces=True):
"""parse a sentence Tree into this document graph""" |
def get_nodelabel(node):
if isinstance(node, nltk.tree.Tree):
return node.label()
elif isinstance(node, unicode):
return node.encode('utf-8')
else:
raise ValueError("Unexpected node type: {0}, {1}".format(type(node), node))
... |
<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_class_instance(element, element_id, doc_id):
""" given an Salt XML element, returns a corresponding `SaltElement` class instance, i.e. a SaltXML `STok... |
xsi_type = get_xsi_type(element)
element_class = XSI_TYPE_CLASSES[xsi_type]
return element_class.from_etree(element) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abslistdir(directory):
""" returns a list of absolute filepaths for all files found in the given directory. """ |
abs_dir = os.path.abspath(directory)
filenames = os.listdir(abs_dir)
return [os.path.join(abs_dir, filename) for filename in filenames] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_elements(self, tree, element_type):
""" extracts all element of type `element_type from the `_ElementTree` representation of a SaltXML document and ... |
# creates a new attribute, e.g. 'self.nodes' and assigns it an
# empty list
setattr(self, element_type, [])
etree_elements = get_elements(tree, element_type)
for i, etree_element in enumerate(etree_elements):
# create an instance of an element class (e.g. TokenNode)
... |
<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_sentence(self, sent_index):
""" returns the string representation of a sentence. :param sent_index: the index of a sentence (from ``self.sentences``) :... |
tokens = [self.print_token(tok_idx)
for tok_idx in self.sentences[sent_index]]
return ' '.join(tokens) |
<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_token(self, token_node_index):
"""returns the string representation of a token.""" |
err_msg = "The given node is not a token node."
assert isinstance(self.nodes[token_node_index], TokenNode), err_msg
onset = self.nodes[token_node_index].onset
offset = self.nodes[token_node_index].offset
return self.text[onset:offset] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def detect_stream_mode(stream):
'''
detect_stream_mode - Detect the mode on a given stream
@param stream <object> - A stream object
If "mode" is present, that will be used.
@return <type> - "Bytes" type or "str" type
'''
# If "Mode" is present, pull from that
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 node2freqt(docgraph, node_id, child_str='', include_pos=False, escape_func=FREQT_ESCAPE_FUNC):
"""convert a docgraph node into a FREQT string.""" |
node_attrs = docgraph.node[node_id]
if istoken(docgraph, node_id):
token_str = escape_func(node_attrs[docgraph.ns+':token'])
if include_pos:
pos_str = escape_func(node_attrs.get(docgraph.ns+':pos', ''))
return u"({pos}({token}){child})".format(
pos=pos_st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sentence2freqt(docgraph, root, successors=None, include_pos=False, escape_func=FREQT_ESCAPE_FUNC):
"""convert a sentence subgraph into a FREQT string.""" |
if successors is None:
successors = sorted_bfs_successors(docgraph, root)
if root in successors: # root node has children / subgraphs
embed_str = u"".join(sentence2freqt(docgraph, child, successors,
include_pos=include_pos,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def docgraph2freqt(docgraph, root=None, include_pos=False, escape_func=FREQT_ESCAPE_FUNC):
"""convert a docgraph into a FREQT string.""" |
if root is None:
return u"\n".join(
sentence2freqt(docgraph, sentence, include_pos=include_pos,
escape_func=escape_func)
for sentence in docgraph.sentences)
else:
return sentence2freqt(docgraph, root, include_pos=include_pos,
... |
<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, stream):
""" Output code coverage report. """ |
if not self.xcoverageToStdout:
# This will create a false stream where output will be ignored
stream = StringIO()
super(XCoverage, self).report(stream)
if not hasattr(self, 'coverInstance'):
# nose coverage plugin 1.0 and earlier
impo... |
<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_etree(cls, etree_element):
""" creates a `SaltElement` from an `etree._Element` representing an element in a SaltXMI file. """ |
label_elements = get_subelements(etree_element, 'labels')
labels = [SaltLabel.from_etree(elem) for elem in label_elements]
return cls(name=get_element_name(etree_element),
element_id=get_graph_element_id(etree_element),
xsi_type=get_xsi_type(etree_element),... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grant_sudo_privileges(request, max_age=COOKIE_AGE):
""" Assigns a random token to the user's session that allows them to have elevated permissions """ |
user = getattr(request, 'user', None)
# If there's not a user on the request, just noop
if user is None:
return
if not user.is_authenticated():
raise ValueError('User needs to be logged in to be elevated to sudo')
# Token doesn't need to be unique,
# just needs to be unpredic... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def revoke_sudo_privileges(request):
""" Revoke sudo privileges from a request explicitly """ |
request._sudo = False
if COOKIE_NAME in request.session:
del request.session[COOKIE_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 has_sudo_privileges(request):
""" Check if a request is allowed to perform sudo actions """ |
if getattr(request, '_sudo', None) is None:
try:
request._sudo = (
request.user.is_authenticated() and
constant_time_compare(
request.get_signed_cookie(COOKIE_NAME, salt=COOKIE_SALT, max_age=COOKIE_AGE),
request.session[COO... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hildatree2dgparentedtree(self):
"""Convert the tree from HILDA's format into a conventional binary tree, which can be easily converted into output formats li... |
def transform(hilda_tree):
"""Transform a HILDA parse tree into a more conventional parse tree.
The input tree::
Contrast[S][N]
_______________|______________
Although they they accepted
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def marts(self):
"""List of available marts.""" |
if self._marts is None:
self._marts = self._fetch_marts()
return self._marts |
<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_marts(self):
"""Lists available marts in a readable DataFrame format. Returns: pd.DataFrame: Frame listing available marts. """ |
def _row_gen(attributes):
for attr in attributes.values():
yield (attr.name, attr.display_name)
return pd.DataFrame.from_records(
_row_gen(self.marts), columns=['name', 'display_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 bgread(stream, blockSizeLimit=65535, pollTime=.03, closeStream=True):
'''
bgread - Start a thread which will read from the given stream in a non-blocking fashion, and automatically populate data in the returned object.
@param stream <object> - A stream on which to read. Socket, file, etc.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _do_bgread(stream, blockSizeLimit, pollTime, closeStream, results):
'''
_do_bgread - Worker functon for the background read thread.
@param stream <object> - Stream to read until closed
@param results <BackgroundReadData>
'''
# Put the whole function in a try instead of just the... |
<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_theme(request):
""" Redirect to a given url while setting the chosen theme in the session or cookie. The url and the theme identifier need to be specifie... |
next = request.POST.get('next', request.GET.get('next'))
if not is_safe_url(url=next, host=request.get_host()):
next = request.META.get('HTTP_REFERER')
if not is_safe_url(url=next, host=request.get_host()):
next = '/'
response = http.HttpResponseRedirect(next)
if 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 make_ui(self, path='hgwebdir.config'):
""" A funcion that will read python rc files and make an ui from read options :param path: path to mercurial config fi... |
#propagated from mercurial documentation
sections = [
'alias',
'auth',
'decode/encode',
'defaults',
'diff',
'email',
'extensions',
'format',
'merge-patterns',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(self):
""" Returns modified, added, removed, deleted files for current changeset """ |
return self.repository._repo.status(self._ctx.p1().node(),
self._ctx.node()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fix_path(self, path):
""" Paths are stored without trailing slash so we need to get rid off it if needed. Also mercurial keeps filenodes as str so we need t... |
if path.endswith('/'):
path = path.rstrip('/')
return safe_str(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 get_nodes(self, path):
""" Returns combined ``DirNode`` and ``FileNode`` objects list representing state of changeset at the given ``path``. If node at the g... |
if self._get_kind(path) != NodeKind.DIR:
raise ChangesetError("Directory does not exist for revision %s at "
" '%s'" % (self.revision, path))
path = self._fix_path(path)
filenodes = [FileNode(f, changeset=self) for f in self._file_paths
if os.path.dirna... |
<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_node(self, path):
""" Returns ``Node`` object from the given ``path``. If there is no node at the given ``path``, ``ChangesetError`` would be raised. """ |
path = self._fix_path(path)
if not path in self.nodes:
if path in self._file_paths:
node = FileNode(path, changeset=self)
elif path in self._dir_paths or path in self._dir_paths:
if path == '':
node = RootNode(changeset=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 content(self):
""" Returns lazily content of the FileNode. If possible, would try to decode content from UTF-8. """ |
content = self._get_content()
if bool(content and '\0' in content):
return content
return safe_unicode(content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lexer(self):
""" Returns pygment's lexer class. Would try to guess lexer taking file's content, name and mimetype. """ |
try:
lexer = lexers.guess_lexer_for_filename(self.name, self.content, stripnl=False)
except lexers.ClassNotFound:
lexer = lexers.TextLexer(stripnl=False)
# returns first alias
return lexer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def history(self):
""" Returns a list of changeset for this file in which the file was changed """ |
if self.changeset is None:
raise NodeError('Unable to get changeset for this FileNode')
return self.changeset.get_file_history(self.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 annotate(self):
""" Returns a list of three element tuples with lineno,changeset and line """ |
if self.changeset is None:
raise NodeError('Unable to get changeset for this FileNode')
return self.changeset.get_file_annotate(self.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 name(self):
""" Returns name of the node so if its path then only last part is returned. """ |
org = safe_unicode(self.path.rstrip('/').split('/')[-1])
return u'%s @ %s' % (org, self.changeset.short_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 predict(self, X, nsamples=200, likelihood_args=()):
""" Predict target values from Bayesian generalized linear regression. Parameters X : ndarray (N*,d) arra... |
Ey, _ = self.predict_moments(X, nsamples, likelihood_args)
return Ey |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict_moments(self, X, nsamples=200, likelihood_args=()):
r""" Predictive moments, in particular mean and variance, of a Bayesian GLM. This function uses M... |
# Get latent function samples
N = X.shape[0]
ys = np.empty((N, nsamples))
fsamples = self._sample_func(X, nsamples)
# Push samples though likelihood expected value
Eyargs = tuple(chain(atleast_list(self.like_hypers_), likelihood_args))
for i, f in enumerate(fsam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict_logpdf(self, X, y, nsamples=200, likelihood_args=()):
r""" Predictive log-probability density function of a Bayesian GLM. Parameters X : ndarray (N*,... |
X, y = check_X_y(X, y)
# Get latent function samples
N = X.shape[0]
ps = np.empty((N, nsamples))
fsamples = self._sample_func(X, nsamples)
# Push samples though likelihood pdf
llargs = tuple(chain(atleast_list(self.like_hypers_), likelihood_args))
for 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 predict_cdf(self, X, quantile, nsamples=200, likelihood_args=()):
r""" Predictive cumulative density function of a Bayesian GLM. Parameters X : ndarray (N*,d... |
# Get latent function samples
N = X.shape[0]
ps = np.empty((N, nsamples))
fsamples = self._sample_func(X, nsamples)
# Push samples though likelihood cdf
cdfarg = tuple(chain(atleast_list(self.like_hypers_), likelihood_args))
for i, f in enumerate(fsamples):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_generate(args):
"""Generate images. Parameters args : `argparse.Namespace` Command arguments. """ |
check_output_format(args.output, args.count)
markov = load(MarkovImage, args.state, args)
if args.size is None:
if markov.scanner.resize is None:
print('Unknown output image size', file=stderr)
exit(1)
width, height = markov.scanner.resize
else:
width, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_filter(args):
"""Filter an image. Parameters args : `argparse.Namespace` Command arguments. """ |
check_output_format(args.output, args.count)
img = Image.open(args.input)
width, height = img.size
if args.state is not None:
markov = load(MarkovImage, args.state, args)
else:
args.state = ()
if args.type == JSON:
storage = JsonStorage(settings=args.settings)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lstrip_ws_and_chars(string, chars):
"""Remove leading whitespace and characters from a string. Parameters string : `str` String to strip. chars : `str` Chara... |
res = string.lstrip().lstrip(chars)
while len(res) != len(string):
string = res
res = string.lstrip().lstrip(chars)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def capitalize(string):
"""Capitalize a sentence. Parameters string : `str` String to capitalize. Returns ------- `str` Capitalized string. Examples -------- 'Wo... |
if not string:
return string
if len(string) == 1:
return string.upper()
return string[0].upper() + string[1:].lower() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def re_flags(flags, custom=ReFlags):
"""Parse regexp flag string. Parameters flags: `str` Flag string. custom: `IntEnum`, optional Custom flag enum (default: Non... |
re_, custom_ = 0, 0
for flag in flags.upper():
try:
re_ |= getattr(re, flag)
except AttributeError:
if custom is not None:
try:
custom_ |= getattr(custom, flag)
except AttributeError:
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 re_flags_str(flags, custom_flags):
"""Convert regexp flags to string. Parameters flags : `int` Flags. custom_flags : `int` Custom flags. Returns ------- `str... |
res = ''
for flag in RE_FLAGS:
if flags & getattr(re, flag):
res += flag
for flag in RE_CUSTOM_FLAGS:
if custom_flags & getattr(ReFlags, flag):
res += flag
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def re_sub(pattern, repl, string, count=0, flags=0, custom_flags=0):
"""Replace regular expression. Parameters pattern : `str` or `_sre.SRE_Pattern` Compiled reg... |
if custom_flags & ReFlags.OVERLAP:
prev_string = None
while string != prev_string:
prev_string = string
string = re.sub(pattern, repl, string, count, flags)
return string
return re.sub(pattern, repl, string, count, flags) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert(self, string):
"""Return a copy of string converted to case. Parameters string : `str` Returns ------- `str` Examples -------- 'str ing' 'STR ING' 'S... |
if self == self.__class__.TITLE:
return capitalize(string)
if self == self.__class__.UPPER:
return string.upper()
if self == self.__class__.LOWER:
return string.lower()
return string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def endless_permutations(N, random_state=None):
""" Generate an endless sequence of random integers from permutations of the If we call this N times, we will swe... |
generator = check_random_state(random_state)
while True:
batch_inds = generator.permutation(N)
for b in batch_inds:
yield b |
<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_repo(path=None, alias=None, create=False):
""" Returns ``Repository`` object of type linked with given ``alias`` at the specified ``path``. If ``alias`` ... |
if create:
if not (path or alias):
raise TypeError("If create is specified, we need path and scm type")
return get_backend(alias)(path, create=True)
if path is None:
path = abspath(os.path.curdir)
try:
scm, path = get_scm(path, search_up=True)
path = absp... |
<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_backend(alias):
""" Returns ``Repository`` class identified by the given alias or raises VCSError if alias is not recognized or backend class cannot be i... |
if alias not in settings.BACKENDS:
raise VCSError("Given alias '%s' is not recognized! Allowed aliases:\n"
"%s" % (alias, pformat(settings.BACKENDS.keys())))
backend_path = settings.BACKENDS[alias]
klass = import_class(backend_path)
return klass |
<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_scms_for_path(path):
""" Returns all scm's found at the given path. If no scm is recognized - empty list is returned. :param path: path to directory whic... |
from vcs.backends import get_backend
if hasattr(path, '__call__'):
path = path()
if not os.path.isdir(path):
raise VCSError("Given path %r is not a directory" % path)
result = []
for key in ALIASES:
dirname = os.path.join(path, '.' + key)
if os.path.isdir(dirname):
... |
<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_repo_paths(path):
""" Returns path's subdirectories which seems to be a repository. """ |
repo_paths = []
dirnames = (os.path.abspath(dirname) for dirname in os.listdir(path))
for dirname in dirnames:
try:
get_scm(dirname)
repo_paths.append(dirname)
except VCSError:
pass
return repo_paths |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_command(cmd, *args):
""" Runs command on the system with given ``args``. """ |
command = ' '.join((cmd, args))
p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
return p.retcode, stdout, stderr |
<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_highlighted_code(name, code, type='terminal'):
""" If pygments are available on the system then returned output is colored. Otherwise unchanged content i... |
import logging
try:
import pygments
pygments
except ImportError:
return code
from pygments import highlight
from pygments.lexers import guess_lexer_for_filename, ClassNotFound
from pygments.formatters import TerminalFormatter
try:
lexer = guess_lexer_for_fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_datetime(text):
""" Parses given text and returns ``datetime.datetime`` instance or raises ``ValueError``. :param text: string of desired date/datetime... |
text = text.strip().lower()
INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M',
'%Y-%m-%d',
'%m/%d/%Y %H:%M:%S',
'%m/%d/%Y %H:%M',
'%m/%d/%Y',
'%m/%d/%y %H:%M:%S',
'%m/%d/%y %H:%M',
'%m/%d/%y',
)
for format in INPUT_FORMATS:... |
<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_dict_for_attrs(obj, attrs):
""" Returns dictionary for each attribute from given ``obj``. """ |
data = {}
for attr in attrs:
data[attr] = getattr(obj, attr)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loglike(self, y, f):
r""" Bernoulli log likelihood. Parameters y: ndarray array of 0, 1 valued integers of targets f: ndarray latent function from the GLM pr... |
# way faster than calling bernoulli.logpmf
y, f = np.broadcast_arrays(y, f)
ll = y * f - softplus(f)
return ll |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loglike(self, y, f, n):
r""" Binomial log likelihood. Parameters y: ndarray array of 0, 1 valued integers of targets f: ndarray latent function from the GLM ... |
ll = binom.logpmf(y, n=n, p=expit(f))
return ll |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def df(self, y, f, n):
r""" Derivative of Binomial log likelihood w.r.t.\ f. Parameters y: ndarray array of 0, 1 valued integers of targets f: ndarray latent fun... |
y, f, n = np.broadcast_arrays(y, f, n)
return y - expit(f) * 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 loglike(self, y, f, var=None):
r""" Gaussian log likelihood. Parameters y: ndarray array of 0, 1 valued integers of targets f: ndarray latent function from t... |
# way faster than calling norm.logpdf
var = self._check_param(var)
y, f = np.broadcast_arrays(y, f)
ll = - 0.5 * (np.log(2 * np.pi * var) + (y - f)**2 / var)
return ll |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def df(self, y, f, var):
r""" Derivative of Gaussian log likelihood w.r.t.\ f. Parameters y: ndarray array of 0, 1 valued integers of targets f: ndarray latent f... |
var = self._check_param(var)
y, f = np.broadcast_arrays(y, f)
return (y - f) / var |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loglike(self, y, f):
r""" Poisson log likelihood. Parameters y: ndarray array of integer targets f: ndarray latent function from the GLM prior (:math:`\mathb... |
y, f = np.broadcast_arrays(y, f)
if self.tranfcn == 'exp':
g = np.exp(f)
logg = f
else:
g = softplus(f)
logg = np.log(g)
return y * logg - g - gammaln(y + 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 Ey(self, f):
r""" Expected value of the Poisson likelihood. Parameters f: ndarray latent function from the GLM prior (:math:`\mathbf{f} = \boldsymbol\Phi \ma... |
return np.exp(f) if self.tranfcn == 'exp' else softplus(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 df(self, y, f):
r""" Derivative of Poisson log likelihood w.r.t.\ f. Parameters y: ndarray array of 0, 1 valued integers of targets f: ndarray latent functio... |
y, f = np.broadcast_arrays(y, f)
if self.tranfcn == 'exp':
return y - np.exp(f)
else:
return expit(f) * (y / safesoftplus(f) - 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 reset(self, state_size_changed=False):
"""Reset parser state. Parameters state_size_changed : `bool`, optional `True` if maximum state size changed (default:... |
if state_size_changed:
self.state = deque(repeat('', self.state_size),
maxlen=self.state_size)
else:
self.state.extend(repeat('', self.state_size))
self.end = 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 convert(ctype, img, palette_img, dither=False):
"""Convert an image to palette type. Parameters ctype : `int` Conversion type. img : `PIL.Image` Image to con... |
if ctype == 0:
img2 = img.convert(mode='P')
img2.putpalette(palette_img.getpalette())
return img2
img.load()
palette_img.load()
if palette_img.palette is None:
raise ValueError('invalid palette image')
im = img.im.convert('P', int(dither), palette_img.im)
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 _unescape_value(value):
"""Unescape a value.""" |
def unescape(c):
return {
"\\\\": "\\",
"\\\"": "\"",
"\\n": "\n",
"\\t": "\t",
"\\b": "\b",
}[c.group(0)]
return re.sub(r"(\\.)", unescape, 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 get_boolean(self, section, name, default=None):
"""Retrieve a configuration setting as boolean. :param section: Tuple with section name and optional subsecti... |
try:
value = self.get(section, name)
except KeyError:
return default
if value.lower() == "true":
return True
elif value.lower() == "false":
return False
raise ValueError("not a valid boolean string: %r" % 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 from_file(cls, f):
"""Read configuration from a file-like object.""" |
ret = cls()
section = None
setting = None
for lineno, line in enumerate(f.readlines()):
line = line.lstrip()
if setting is None:
if _strip_comments(line).strip() == "":
continue
if line[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 from_path(cls, path):
"""Read configuration from a file on disk.""" |
f = GitFile(path, 'rb')
try:
ret = cls.from_file(f)
ret.path = path
return ret
finally:
f.close() |
<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_to_path(self, path=None):
"""Write configuration to a file on disk.""" |
if path is None:
path = self.path
f = GitFile(path, 'wb')
try:
self.write_to_file(f)
finally:
f.close() |
<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_to_file(self, f):
"""Write configuration to a file-like object.""" |
for section, values in self._values.iteritems():
try:
section_name, subsection_name = section
except ValueError:
(section_name, ) = section
subsection_name = None
if subsection_name is None:
f.write("[%s]\n" % 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 default_backends(cls):
"""Retrieve the default configuration. This will look in the repository configuration (if for_path is specified), the users' home dire... |
paths = []
paths.append(os.path.expanduser("~/.gitconfig"))
paths.append("/etc/gitconfig")
backends = []
for path in paths:
try:
cf = ConfigFile.from_path(path)
except (IOError, OSError), e:
if e.errno != errno.ENOENT:
... |
<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_regression(func, n_samples=100, n_features=1, bias=0.0, noise=0.0, random_state=None):
""" Make dataset for a regression problem. Examples -------- (100... |
generator = check_random_state(random_state)
X = generator.randn(n_samples, n_features)
# unpack the columns of X
y = func(*X.T) + bias
if noise > 0.0:
y += generator.normal(scale=noise, size=y.shape)
return X, y |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.