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 equivalent_vertices(self): """A dictionary with symmetrically equivalent vertices."""
level1 = {} for i, row in enumerate(self.vertex_fingerprints): key = row.tobytes() l = level1.get(key) if l is None: l = set([i]) level1[key] = l else: l.add(i) level2 = {} for key, vertices ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symmetry_cycles(self): """The cycle representations of the graph symmetries"""
result = set([]) for symmetry in self.symmetries: result.add(symmetry.cycles) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def canonical_order(self): """The vertices in a canonical or normalized order. This routine will return a list of vertices in an order that does not depend on th...
# A) find an appropriate starting vertex. # Here we take a central vertex that has a minimal number of symmetrical # equivalents, 'the highest atom number', and the highest fingerprint. # Note that the symmetrical equivalents are computed from the vertex # fingerprints, i.e. wit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_breadth_first(self, start=None, do_paths=False, do_duplicates=False): """Iterate over the vertices with the breadth first algorithm. See http://en.wikip...
if start is None: start = self.central_vertex else: try: start = int(start) except ValueError: raise TypeError("First argument (start) must be an integer.") if start < 0 or start >= self.num_vertices: raise ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_breadth_first_edges(self, start=None): """Iterate over the edges with the breadth first convention. We need this for the pattern matching algorithms, bu...
if start is None: start = self.central_vertex else: try: start = int(start) except ValueError: raise TypeError("First argument (start) must be an integer.") if start < 0 or start >= self.num_vertices: raise ...
<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_subgraph(self, subvertices, normalize=False): """Constructs a subgraph of the current graph Arguments: | ``subvertices`` -- The vertices that should be r...
if normalize: revorder = dict((j, i) for i, j in enumerate(subvertices)) new_edges = [] old_edge_indexes = [] for counter, (i, j) in enumerate(self.edges): new_i = revorder.get(i) if new_i is None: continue ...
<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_vertex_fingerprints(self, vertex_strings, edge_strings, num_iter=None): """Return an array with fingerprints for each vertex"""
import hashlib def str2array(x): """convert a hash string to a numpy array of bytes""" if len(x) == 0: return np.zeros(0, np.ubyte) elif sys.version_info[0] == 2: return np.frombuffer(x, np.ubyte) else: 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 get_part(self, vertex_in, vertices_border): """List all vertices that are connected to vertex_in, but are not included in or 'behind' vertices_border. """
vertices_new = set(self.neighbors[vertex_in]) vertices_part = set([vertex_in]) while len(vertices_new) > 0: pivot = vertices_new.pop() if pivot in vertices_border: continue vertices_part.add(pivot) pivot_neighbors = set(self.neigh...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full_match(self, other): """Find the mapping between vertex indexes in self and other. This also works on disconnected graphs. Derived classes should just im...
# we need normalize subgraphs because these graphs are used as patterns. graphs0 = [ self.get_subgraph(group, normalize=True) for group in self.independent_vertices ] graphs1 = [ other.get_subgraph(group) for group in other.independent_ver...
<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_relation(self, source, destination): """Add new a relation to the bejection"""
if self.in_sources(source): if self.forward[source] != destination: raise ValueError("Source is already in use. Destination does " "not match.") else: raise ValueError("Source-Destination relation already exists.") ...
<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_relations(self, relations): """Add multiple relations to a bijection"""
for source, destination in relations: self.add_relation(source, 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 inverse(self): """Returns the inverse bijection."""
result = self.__class__() result.forward = copy.copy(self.reverse) result.reverse = copy.copy(self.forward) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_first_relation(cls, vertex0, vertex1): """Intialize a fresh match based on the first relation"""
result = cls([(vertex0, vertex1)]) result.previous_ends1 = set([vertex1]) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_new_edges(self, subject_graph): """Get new edges from the subject graph for the graph search algorithm The Graph search algorithm extends the matches ite...
result = [] #print "Match.get_new_edges self.previous_ends1", self.previous_ends1 for vertex in self.previous_ends1: for neighbor in subject_graph.neighbors[vertex]: if neighbor not in self.reverse: result.append((vertex, neighbor)) 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 copy_with_new_relations(self, new_relations): """Create a new match object extended with new relations"""
result = self.__class__(self.forward.items()) result.add_relations(new_relations.items()) result.previous_ends1 = set(new_relations.values()) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_pattern_graph(self, pattern_graph): """Initialize the pattern_graph"""
self.pattern_graph = pattern_graph self.level_edges = {} self.level_constraints = {} self.duplicate_checks = set([]) if pattern_graph is None: return if len(pattern_graph.independent_vertices) != 1: raise ValueError("A pattern_graph must not 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 iter_final_matches(self, canonical_match, subject_graph, one_match): """Given a match, iterate over all related equivalent matches When criteria sets are def...
if self.criteria_sets is None or one_match: yield canonical_match else: for criteria_set in self.criteria_sets: satisfied_match_tags = set([]) for symmetry in self.pattern_graph.symmetries: final_match = canonical_match * symme...
<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_closed_cycles(self): """Return the closed cycles corresponding to this permutation The cycle will be normalized to facilitate the elimination of duplicat...
# A) construct all the cycles closed_cycles = [] todo = set(self.forward.keys()) if todo != set(self.forward.values()): raise GraphError("The subject and pattern graph must have the same " "numbering.") current_vertex = None while...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(self, vertex0, vertex1, subject_graph): """Returns true when the two vertices are of the same kind"""
return ( self.pattern_graph.vertex_fingerprints[vertex0] == subject_graph.vertex_fingerprints[vertex1] ).all()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def complete(self, match, subject_graph): """Check the completeness of a ring match"""
size = len(match) # check whether we have an odd strong ring if match.forward[size-1] in subject_graph.neighbors[match.forward[size-2]]: # we have an odd closed cycle. check if this is a strong ring order = list(range(0, size, 2)) + list(range(1, size-1, 2))[::-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 print_debug(self, text, indent=0): """Only prints debug info on screen when self.debug == True."""
if self.debug: if indent > 0: print(" "*self.debug, text) self.debug += indent if indent <= 0: print(" "*self.debug, text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _iter_candidate_groups(self, init_match, edges0, edges1): """Divide the edges into groups"""
# collect all end vertices0 and end vertices1 that belong to the same # group. sources = {} for start_vertex0, end_vertex0 in edges0: l = sources.setdefault(start_vertex0, []) l.append(end_vertex0) dests = {} for start_vertex1, end_vertex1 in edge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _iter_new_relations(self, init_match, subject_graph, edges0, constraints0, edges1): """Given an onset for a match, iterate over all possible new key-value pa...
# Count the number of unique edges0[i][1] values. This is also # the number of new relations. num_new_relations = len(set(j for i, j in edges0)) def combine_small(relations, num): """iterate over all compatible combinations within one set of relations""" if len(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _iter_matches(self, input_match, subject_graph, one_match, level=0): """Given an onset for a match, iterate over all completions of that match This iterator ...
self.print_debug("ENTERING _ITER_MATCHES", 1) self.print_debug("input_match: %s" % input_match) # A) collect the new edges in the pattern graph and the subject graph # to extend the match. # # Note that the edges are ordered. edge[0] is always in the match. # edg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_pdb(filename, molecule, atomnames=None, resnames=None, chain_ids=None, occupancies=None, betas=None): """Writes a single molecule to a pdb file. This fu...
with open(filename, "w") as f: res_id = 1 old_resname = None for i in range(molecule.size): symbol = periodic[molecule.numbers[i]].symbol if atomnames is None: atomname = symbol else: atomname = atomnames[i] 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 load_pdb(filename): """Loads a single molecule from a pdb file. This function does support only a small fragment from the pdb specification. It assumes that ...
with open(filename) as f: numbers = [] coordinates = [] occupancies = [] betas = [] for line in f: if line.startswith("ATOM"): symbol = line[76:78].strip() numbers.append(periodic[symbol].number) coordinates.append(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zmat_to_cart(zmat): """Converts a ZMatrix back to cartesian coordinates."""
numbers = zmat["number"] N = len(numbers) coordinates = np.zeros((N, 3), float) # special cases for the first coordinates coordinates[1, 2] = zmat["distance"][1] if zmat["rel1"][2] == 1: sign = -1 else: sign = 1 coordinates[2, 2] = zmat["distance"][2]*sign*np.cos(zmat[...
<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_new_ref(self, existing_refs): """Get a new reference atom for a row in the ZMatrix The reference atoms should obey the following conditions: - They must...
# ref0 is the atom whose position is defined by the current row in the # zmatrix. ref0 = existing_refs[0] for ref in existing_refs: # try to find a neighbor of the ref that can serve as the new ref result = None for n in sorted(self.graph.neighbors[re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cart_to_zmat(self, coordinates): """Convert cartesian coordinates to ZMatrix format Argument: coordinates -- Cartesian coordinates (numpy array Nx3) The coor...
N = len(self.graph.numbers) if coordinates.shape != (N, 3): raise ValueError("The shape of the coordinates must be (%i, 3)" % N) result = np.zeros(N, dtype=self.dtype) for i in range(N): ref0 = self.old_index[i] rel1 = -1 rel2 = -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 can_map_ipa_string(self, ipa_string): """ Return ``True`` if the mapper can map all the IPA characters in the given IPA string. :param IPAString ipa_string: ...
canonical = [(c.canonical_representation, ) for c in ipa_string] split = split_using_dictionary(canonical, self, self.max_key_length, single_char_parsing=False) for sub in split: if not sub in self.ipa_canonical_representation_to_mapped_str: return False 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 map_ipa_string(self, ipa_string, ignore=False, return_as_list=False, return_can_map=False): """ Convert the given IPAString to a string containing the corres...
acc = [] can_map = True canonical = [(c.canonical_representation, ) for c in ipa_string] split = split_using_dictionary(canonical, self, self.max_key_length, single_char_parsing=False) for sub in split: try: acc.append(self.ipa_canonical_representatio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_unicode_string(self, unicode_string, ignore=False, single_char_parsing=False, return_as_list=False, return_can_map=False): """ Convert the given Unicode ...
if unicode_string is None: return None ipa_string = IPAString(unicode_string=unicode_string, ignore=ignore, single_char_parsing=single_char_parsing) return self.map_ipa_string( ipa_string=ipa_string, ignore=ignore, return_as_list=return_as_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 print_invalid_chars(invalid_chars, vargs): """ Print Unicode characterss that are not IPA valid, if requested by the user. :param list invalid_chars: a list ...
if len(invalid_chars) > 0: if vargs["print_invalid"]: print(u"".join(invalid_chars)) if vargs["unicode"]: for u_char in sorted(set(invalid_chars)): print(u"'%s'\t%s\t%s" % (u_char, hex(ord(u_char)), unicodedata.name(u_char, "UNKNOWN")))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_canonize(string, vargs): """ Print the canonical representation of the given string. It will replace non-canonical compound characters with their can...
try: ipa_string = IPAString( unicode_string=string, ignore=vargs["ignore"], single_char_parsing=vargs["single_char_parsing"] ) print(vargs["separator"].join([(u"%s" % c) for c in ipa_string])) except ValueError as exc: print_error(str(exc))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_chars(string, vargs): """ Print a list of all IPA characters in the given string. It will print the Unicode representation, the full IPA name, and th...
try: ipa_string = IPAString( unicode_string=string, ignore=vargs["ignore"], single_char_parsing=vargs["single_char_parsing"] ) for c in ipa_string: print(u"'%s'\t%s (%s)" % (c.unicode_repr, c.name, unicode_to_hex(c.unicode_repr))) except V...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_check(string, vargs): """ Check if the given string is IPA valid. If the given string is not IPA valid, print the invalid characters. :param str stri...
is_valid = is_valid_ipa(string) print(is_valid) if not is_valid: valid_chars, invalid_chars = remove_invalid_ipa_characters( unicode_string=string, return_invalid=True ) print_invalid_chars(invalid_chars, vargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_clean(string, vargs): """ Remove characters that are not IPA valid from the given string, and print the remaining string. :param str string: the stri...
valid_chars, invalid_chars = remove_invalid_ipa_characters( unicode_string=string, return_invalid=True, single_char_parsing=vargs["single_char_parsing"] ) print(u"".join(valid_chars)) print_invalid_chars(invalid_chars, vargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_u2a(string, vargs): """ Print the ARPABEY ASCII string corresponding to the given Unicode IPA string. :param str string: the string to act upon :para...
try: l = ARPABETMapper().map_unicode_string( unicode_string=string, ignore=vargs["ignore"], single_char_parsing=vargs["single_char_parsing"], return_as_list=True ) print(vargs["separator"].join(l)) except ValueError as exc: print_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 command_u2k(string, vargs): """ Print the Kirshenbaum ASCII string corresponding to the given Unicode IPA string. :param str string: the string to act upon :...
try: l = KirshenbaumMapper().map_unicode_string( unicode_string=string, ignore=vargs["ignore"], single_char_parsing=vargs["single_char_parsing"], return_as_list=True ) print(vargs["separator"].join(l)) except ValueError as exc: pri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ipa_chars(self, value): """ Set the list of IPAChar objects composing the IPA string :param list value: list of IPAChar objects """
if value is None: self.__ipa_chars = [] else: if is_list_of_ipachars(value): self.__ipa_chars = value else: raise TypeError("ipa_chars only accepts a list of IPAChar objects")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_equivalent(self, other, ignore=False): """ Return ``True`` if the IPA string is equivalent to the ``other`` object. The ``other`` object can be: 1. a Unic...
def is_equivalent_to_list_of_ipachars(other): """ Return ``True`` if the list of IPAChar objects in the canonical representation of the string is the same as the given list. :param list other: list of IPAChar objects :rtype: bool ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_chars(self, chars=u""): """ Return a new IPAString, containing only the IPA characters specified by the ``chars`` string. Valid values for ``chars`` a...
if chars in [u"cns", u"consonants"]: return self.consonants elif chars in [u"vwl", u"vowels"]: return self.vowels elif chars in [u"cns_vwl", u"letters"]: return self.letters elif chars in [u"cns_vwl_pstr", u"cvp"]: return self.cns_vwl_pstr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consonants(self): """ Return a new IPAString, containing only the consonants in the current string. :rtype: IPAString """
return IPAString(ipa_chars=[c for c in self.ipa_chars if c.is_consonant])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vowels(self): """ Return a new IPAString, containing only the vowels in the current string. :rtype: IPAString """
return IPAString(ipa_chars=[c for c in self.ipa_chars if c.is_vowel])
<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_unicode_field(string): """ Convert a Unicode field into the corresponding list of Unicode strings. The (input) Unicode field is a Unicode string cont...
values = [] for codepoint in [s for s in string.split(DATA_FILE_CODEPOINT_SEPARATOR) if (s != DATA_FILE_VALUE_NOT_AVAILABLE) and (len(s) > 0)]: values.append(u"".join([hex_to_unichr(c) for c in codepoint.split(DATA_FILE_CODEPOINT_JOINER)])) return values
<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_ascii_field(string): """ Convert an ASCII field into the corresponding list of Unicode strings. The (input) ASCII field is a Unicode string containin...
values = [] for codepoint in [s for s in string.split(DATA_FILE_CODEPOINT_SEPARATOR) if (s != DATA_FILE_VALUE_NOT_AVAILABLE) and (len(s) > 0)]: #if DATA_FILE_CODEPOINT_JOINER in codepoint: # values.append(u"".join([hex_to_unichr(c) for c in codepoint.split(DATA_FILE_CODEPOINT_JOINER)])) ...
<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_raw_tuple(value_tuple, format_string): """ Convert a tuple of raw values, according to the given line format. :param tuple value_tuple: the tuple of ...
values = [] for v, c in zip(value_tuple, format_string): if v is None: # append None values.append(v) elif c == u"s": # string values.append(v) elif c == u"S": # string, split using space as delimiter values.append...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_data_file( file_path, file_path_is_relative=False, comment_string=DATA_FILE_COMMENT, field_separator=DATA_FILE_FIELD_SEPARATOR, line_format=None ): """ ...
raw_tuples = [] if file_path_is_relative: file_path = os.path.join(os.path.dirname(__file__), file_path) with io.open(file_path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if (len(line) > 0) and (not line.startswith(comment_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 invalid_ipa_characters(unicode_string, indices=False): """ Return the list of Unicode characters in the given Unicode string that are not IPA valid. Return `...
if unicode_string is None: return None if indices: return [(i, unicode_string[i]) for i in range(len(unicode_string)) if unicode_string[i] not in UNICODE_TO_IPA] return set([c for c in unicode_string if c not in UNICODE_TO_IPA])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def variant_to_list(obj): """ Return a list containing the descriptors in the given object. The ``obj`` can be a list or a set of descriptor strings, or a Unicod...
if isinstance(obj, list): return obj elif is_unicode_string(obj): return [s for s in obj.split() if len(s) > 0] elif isinstance(obj, set) or isinstance(obj, frozenset): return list(obj) raise TypeError("The given value must be a list or a set of descriptor strings, or a Unicode ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def variant_to_canonical_string(obj): """ Return a list containing the canonical string for the given object. The ``obj`` can be a list or a set of descriptor st...
acc = [DG_ALL_DESCRIPTORS.canonical_value(p) for p in variant_to_list(obj)] acc = sorted([a for a in acc if a is not None]) return u" ".join(acc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_list_of_ipachars(obj): """ Return ``True`` if the given object is a list of IPAChar objects. :param object obj: the object to test :rtype: bool """
if isinstance(obj, list): for e in obj: if not isinstance(e, IPAChar): return False return True 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 is_equivalent(self, other): """ Return ``True`` if the IPA character is equivalent to the ``other`` object. The ``other`` object can be: 1. a Unicode string,...
if (self.unicode_repr is not None) and (is_unicode_string(other)) and (self.unicode_repr == other): return True if isinstance(other, IPAChar): return self.canonical_representation == other.canonical_representation try: return self.canonical_representation == ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dg_value(self, descriptor_group): """ Return the canonical value of a descriptor of the character, provided it is present in the given descriptor group. If n...
for p in self.descriptors: if p in descriptor_group: return descriptor_group.canonical_value(p) return 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 has_descriptor(self, descriptor): """ Return ``True`` if the character has the given descriptor. :param IPADescriptor descriptor: the descriptor to be checke...
for p in self.descriptors: if p in descriptor: return True 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 voicing(self, value): """ Set the voicing of the consonant. :param str value: the value to be set """
if (value is not None) and (not value in DG_C_VOICING): raise ValueError("Unrecognized value for voicing: '%s'" % value) self.__voicing = 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 place(self, value): """ Set the place of articulation of the consonant. :param str value: the value to be set """
if (value is not None) and (not value in DG_C_PLACE): raise ValueError("Unrecognized value for place: '%s'" % value) self.__place = 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 manner(self, value): """ Set the manner of articulation of the consonant. :param str value: the value to be set """
if (value is not None) and (not value in DG_C_MANNER): raise ValueError("Unrecognized value for manner: '%s'" % value) self.__manner = 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 height(self, value): """ Set the height of the vowel. :param str value: the value to be set """
if (value is not None) and (not value in DG_V_HEIGHT): raise ValueError("Unrecognized value for height: '%s'" % value) self.__height = 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 backness(self, value): """ Set the backness of the vowel. :param str value: the value to be set """
if (value is not None) and (not value in DG_V_BACKNESS): raise ValueError("Unrecognized value for backness: '%s'" % value) self.__backness = 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 roundness(self, value): """ Set the roundness of the vowel. :param str value: the value to be set """
if (value is not None) and (not value in DG_V_ROUNDNESS): raise ValueError("Unrecognized value for roundness: '%s'" % value) self.__roundness = 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 _load_data(self): """ Load the Kirshenbaum ASCII IPA data from the built-in database. """
ipa_canonical_string_to_ascii_str = dict() for line in load_data_file( file_path=self.DATA_FILE_PATH, file_path_is_relative=True, line_format=u"sxA" ): i_desc, i_ascii = line if len(i_ascii) == 0: raise ValueError("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 canonical_value(self, query): """ Return the canonical value corresponding to the given query value. Return ``None`` if the query value is not present in any...
for d in self.descriptors: if query in d: return d.canonical_label return 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 _load_data(self): """ Load the ARPABET ASCII IPA data from the built-in database. """
ipa_canonical_string_to_ascii_str = dict() for line in load_data_file( file_path=self.DATA_FILE_PATH, file_path_is_relative=True, line_format=u"UA" ): i_unicode, i_ascii = line if (len(i_unicode) == 0) or (len(i_ascii) == 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 is_unicode_string(string): """ Return ``True`` if the given string is a Unicode string, that is, of type ``unicode`` in Python 2 or ``str`` in Python 3. Retu...
if string is None: return None if PY2: return isinstance(string, unicode) return isinstance(string, 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 to_unicode_string(string): """ Return a Unicode string out of the given string. On Python 2, it calls ``unicode`` with ``utf-8`` encoding. On Python 3, it ju...
if string is None: return None if is_unicode_string(string): return string # if reached here, string is a byte string if PY2: return unicode(string, encoding="utf-8") return string.decode(encoding="utf-8")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hex_to_unichr(hex_string): """ Return the Unicode character with the given codepoint, given as an hexadecimal string. Return ``None`` if ``hex_string`` is ``...
if (hex_string is None) or (len(hex_string) < 1): return None if hex_string.startswith("U+"): hex_string = hex_string[2:] return int_to_unichr(int(hex_string, base=16))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unicode_to_hex(unicode_string): """ Return a string containing the Unicode hexadecimal codepoint of each Unicode character in the given Unicode string. Retur...
if unicode_string is None: return None acc = [] for c in unicode_string: s = hex(ord(c)).replace("0x", "").upper() acc.append("U+" + ("0" * (4 - len(s))) + s) return u" ".join(acc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def etree_to_text(tree, guess_punct_space=True, guess_layout=True, newline_tags=NEWLINE_TAGS, double_newline_tags=DOUBLE_NEWLINE_TAGS): """ Convert a html tree t...
chunks = [] _NEWLINE = object() _DOUBLE_NEWLINE = object() class Context: """ workaround for missing `nonlocal` in Python 2 """ # _NEWLINE, _DOUBLE_NEWLINE or content of the previous chunk (str) prev = _DOUBLE_NEWLINE def should_add_space(text, prev): """ Return T...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def selector_to_text(sel, guess_punct_space=True, guess_layout=True): """ Convert a cleaned parsel.Selector to text. See html_text.extract_text docstring for des...
import parsel if isinstance(sel, parsel.SelectorList): # if selecting a specific xpath text = [] for s in sel: extracted = etree_to_text( s.root, guess_punct_space=guess_punct_space, guess_layout=guess_layout) if ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleaned_selector(html): """ Clean parsel.selector. """
import parsel try: tree = _cleaned_html_tree(html) sel = parsel.Selector(root=tree, type='html') except (lxml.etree.XMLSyntaxError, lxml.etree.ParseError, lxml.etree.ParserError, UnicodeEncodeError): # likely plain text sel = parsel.Select...
<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_text(html, guess_punct_space=True, guess_layout=True, newline_tags=NEWLINE_TAGS, double_newline_tags=DOUBLE_NEWLINE_TAGS): """ Convert html to text, ...
if html is None: return '' cleaned = _cleaned_html_tree(html) return etree_to_text( cleaned, guess_punct_space=guess_punct_space, guess_layout=guess_layout, newline_tags=newline_tags, double_newline_tags=double_newline_tags, )
<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_json(self, layer, where="1 = 1", fields=[], count_only=False, srid='4326'): """ Gets the JSON file from ArcGIS """
params = { 'where': where, 'outFields': ", ".join(fields), 'returnGeometry': True, 'outSR': srid, 'f': "pjson", 'orderByFields': self.object_id_field, 'returnCountOnly': count_only } ...
<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_layer(self, layer): """ Returns the standard JSON descriptor for the layer. There is a lot of usefule information in there. """
if not layer in self._layer_descriptor_cache: params = {'f': 'pjson'} if self.token: params['token'] = self.token response = requests.get(self._build_request(layer), params=params) self._layer_descriptor_cache[layer] = response.json() 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 enumerate_layer_fields(self, layer): """ Pulls out all of the field names for a layer. """
descriptor = self.get_descriptor_for_layer(layer) return [field['name'] for field in descriptor['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(self, layer, where="1 = 1", fields=[], count_only=False, srid='4326'): """ Gets a layer and returns it as honest to God GeoJSON. WHERE 1 = 1 causes us to...
base_where = where # By default we grab all of the fields. Technically I think # we can just do "*" for all fields, but I found this was buggy in # the KMZ mode. I'd rather be explicit. fields = fields or self.enumerate_layer_fields(layer) jsobj = self.get_json(layer, w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getMultiple(self, layers, where="1 = 1", fields=[], srid='4326', layer_name_field=None): """ Get a bunch of layers and concatenate them together into one. Th...
features = [] for layer in layers: get_fields = fields or self.enumerate_layer_fields(layer) this_layer = self.get(layer, where, get_fields, False, srid).get('features') if layer_name_field: descriptor = self.get_descriptor_for_layer(layer) ...
<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_version(extension, workflow_file): '''Determines the version of a .py, .wdl, or .cwl file.''' if extension == 'py' and two_seven_compatible(workflow_file): return '2.7' elif extension == 'cwl': return yaml.load(open(workflow_file))['cwlVersion'] else: # Must be a wdl 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 wf_info(workflow_path): """ Returns the version of the file and the file extension. Assumes that the file path is to the file directly ie, ends with a valid ...
supported_formats = ['py', 'wdl', 'cwl'] file_type = workflow_path.lower().split('.')[-1] # Grab the file extension workflow_path = workflow_path if ':' in workflow_path else 'file://' + workflow_path if file_type in supported_formats: if workflow_path.startswith('file://'): vers...
<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(self, wf, jsonyaml, attachments): """ Composes and sends a post request that signals the wes server to run a workflow. :param str workflow_file: A local/...
attachments = list(expand_globs(attachments)) parts = build_wes_request(wf, jsonyaml, attachments) postresult = requests.post("%s://%s/ga4gh/wes/v1/runs" % (self.proto, self.host), files=parts, headers=self.auth) 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 cancel(self, run_id): """ Cancel a running workflow. :param run_id: String (typically a uuid) identifying the run. :param str auth: String to send in the aut...
postresult = requests.post("%s://%s/ga4gh/wes/v1/runs/%s/cancel" % (self.proto, self.host, run_id), headers=self.auth) return wes_reponse(postresult)
<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_run_log(self, run_id): """ Get detailed info about a running workflow. :param run_id: String (typically a uuid) identifying the run. :param str auth: Str...
postresult = requests.get("%s://%s/ga4gh/wes/v1/runs/%s" % (self.proto, self.host, run_id), headers=self.auth) return wes_reponse(postresult)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getstate(self): """ Returns RUNNING, -1 COMPLETE, 0 or EXECUTOR_ERROR, 255 """
state = "RUNNING" exit_code = -1 exitcode_file = os.path.join(self.workdir, "exit_code") pid_file = os.path.join(self.workdir, "pid") if os.path.exists(exitcode_file): with open(exitcode_file) as f: exit_code = int(f.read()) elif os.path.exi...
<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_workflow(self, request, opts, cwd, wftype='cwl'): """Writes a cwl, wdl, or python file as appropriate from the request dictionary."""
workflow_url = request.get("workflow_url") # link the cwl and json into the cwd if workflow_url.startswith('file://'): os.link(workflow_url[7:], os.path.join(cwd, "wes_workflow." + wftype)) workflow_url = os.path.join(cwd, "wes_workflow." + wftype) os.link(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 call_cmd(self, cmd, cwd): """ Calls a command with Popen. Writes stdout, stderr, and the command to separate files. :param cmd: A string or array of strings....
with open(self.cmdfile, 'w') as f: f.write(str(cmd)) stdout = open(self.outfile, 'w') stderr = open(self.errfile, 'w') logging.info('Calling: ' + ' '.join(cmd)) process = subprocess.Popen(cmd, stdout=stdout, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getstate(self): """ Returns QUEUED, -1 INITIALIZING, -1 RUNNING, -1 COMPLETE, 0 or EXECUTOR_ERROR, 255 """
# the jobstore never existed if not os.path.exists(self.jobstorefile): logging.info('Workflow ' + self.run_id + ': QUEUED') return "QUEUED", -1 # completed earlier if os.path.exists(self.statcompletefile): logging.info('Workflow ' + self.run_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 getopt(self, p, default=None): """Returns the first option value stored that matches p or default."""
for k, v in self.pairs: if k == p: return v return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getoptlist(self, p): """Returns all option values stored that match p as a list."""
optlist = [] for k, v in self.pairs: if k == p: optlist.append(v) return optlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def catch_exceptions(orig_func): """Catch uncaught exceptions and turn them into http errors"""
@functools.wraps(orig_func) def catch_exceptions_wrapper(self, *args, **kwargs): try: return orig_func(self, *args, **kwargs) except arvados.errors.ApiError as e: logging.exception("Failure") return {"msg": e._get_reason(), "status_code": e.resp.status}, int...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _safe_name(file_name, sep): """Convert the file name to ASCII and normalize the string."""
file_name = stringify(file_name) if file_name is None: return file_name = ascii_text(file_name) file_name = category_replace(file_name, UNICODE_CATEGORIES) file_name = collapse_spaces(file_name) if file_name is None or not len(file_name): return return file_name.replace(WS, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_filename(file_name, sep='_', default=None, extension=None): """Create a secure filename for plain file system storage."""
if file_name is None: return decode_path(default) file_name = decode_path(file_name) file_name = os.path.basename(file_name) file_name, _extension = os.path.splitext(file_name) file_name = _safe_name(file_name, sep=sep) if file_name is None: return decode_path(default) 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 stringify(value, encoding_default='utf-8', encoding=None): """Brute-force convert a given object to a string. This will attempt an increasingly mean set of c...
if value is None: return None if not isinstance(value, six.text_type): if isinstance(value, (date, datetime)): return value.isoformat() elif isinstance(value, (float, Decimal)): return Decimal(value).to_eng_string() elif isinstance(value, six.binary_type...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_result(result, default, threshold=0.2): """Interpret a chardet result."""
if result is None: return default if result.get('confidence') is None: return default if result.get('confidence') < threshold: return default return normalize_encoding(result.get('encoding'), default=default)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def guess_encoding(text, default=DEFAULT_ENCODING): """Guess string encoding. Given a piece of text, apply character encoding detection to guess the appropriate ...
result = chardet.detect(text) return normalize_result(result, default=default)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def guess_file_encoding(fh, default=DEFAULT_ENCODING): """Guess encoding from a file handle."""
start = fh.tell() detector = chardet.UniversalDetector() while True: data = fh.read(1024 * 10) if not data: detector.close() break detector.feed(data) if detector.done: break fh.seek(start) return normalize_result(detector.result,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def guess_path_encoding(file_path, default=DEFAULT_ENCODING): """Wrapper to open that damn file for you, lazy bastard."""
with io.open(file_path, 'rb') as fh: return guess_file_encoding(fh, default=default)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decompose_nfkd(text): """Perform unicode compatibility decomposition. This will replace some non-standard value representations in unicode and normalise them...
if text is None: return None if not hasattr(decompose_nfkd, '_tr'): decompose_nfkd._tr = Transliterator.createInstance('Any-NFKD') return decompose_nfkd._tr.transliterate(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compose_nfc(text): """Perform unicode composition."""
if text is None: return None if not hasattr(compose_nfc, '_tr'): compose_nfc._tr = Transliterator.createInstance('Any-NFC') return compose_nfc._tr.transliterate(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def category_replace(text, replacements=UNICODE_CATEGORIES): """Remove characters from a string based on unicode classes. This is a method for removing non-text ...
if text is None: return None characters = [] for character in decompose_nfkd(text): cat = category(character) replacement = replacements.get(cat, character) if replacement is not None: characters.append(replacement) return u''.join(characters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_unsafe_chars(text): """Remove unsafe unicode characters from a piece of text."""
if isinstance(text, six.string_types): text = UNSAFE_RE.sub('', text) return text