text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Returns an iterator over the lines in the file at the given path, <END_TASK> <USER_TASK:> Description: def _read(path, encoding="utf-8", comment=";;;"): """ Returns an iterator over the lines in the file at the given path, strippping comments and decoding each line to Unicode. """
if path: if isinstance(path, basestring) and os.path.exists(path): # From file path. if PY2: f = codecs.open(path, 'r', encoding='utf-8') else: f = open(path, 'r', encoding='utf-8') elif isinstance(path, basestring): # From string. f = path.splitlines() else: # From file or buffer. f = path for i, line in enumerate(f): line = line.strip(codecs.BOM_UTF8) if i == 0 and isinstance(line, binary_type) else line line = line.strip() line = decode_utf8(line, encoding) if not line or (comment and line.startswith(comment)): continue yield line return
<SYSTEM_TASK:> Default morphological tagging rules for English, based on word suffixes. <END_TASK> <USER_TASK:> Description: def _suffix_rules(token, tag="NN"): """ Default morphological tagging rules for English, based on word suffixes. """
if isinstance(token, (list, tuple)): token, tag = token if token.endswith("ing"): tag = "VBG" if token.endswith("ly"): tag = "RB" if token.endswith("s") and not token.endswith(("is", "ous", "ss")): tag = "NNS" if token.endswith(("able", "al", "ful", "ible", "ient", "ish", "ive", "less", "tic", "ous")) or "-" in token: tag = "JJ" if token.endswith("ed"): tag = "VBN" if token.endswith(("ate", "ify", "ise", "ize")): tag = "VBP" return [token, tag]
<SYSTEM_TASK:> Returns the value from the function with the given name in the given language module. <END_TASK> <USER_TASK:> Description: def _multilingual(function, *args, **kwargs): """ Returns the value from the function with the given name in the given language module. By default, language="en". """
return getattr(_module(kwargs.pop("language", "en")), function)(*args, **kwargs)
<SYSTEM_TASK:> Returns a list of sentences from the given string. <END_TASK> <USER_TASK:> Description: def find_tokens(self, string, **kwargs): """ Returns a list of sentences from the given string. Punctuation marks are separated from each word by a space. """
# "The cat purs." => ["The cat purs ."] return find_tokens(string, punctuation = kwargs.get( "punctuation", PUNCTUATION), abbreviations = kwargs.get("abbreviations", ABBREVIATIONS), replace = kwargs.get( "replace", replacements), linebreak = r"\n{2,}")
<SYSTEM_TASK:> Annotates the given list of tokens with chunk tags. <END_TASK> <USER_TASK:> Description: def find_chunks(self, tokens, **kwargs): """ Annotates the given list of tokens with chunk tags. Several tags can be added, for example chunk + preposition tags. """
# [["The", "DT"], ["cat", "NN"], ["purs", "VB"]] => # [["The", "DT", "B-NP"], ["cat", "NN", "I-NP"], ["purs", "VB", "B-VP"]] return find_prepositions( find_chunks(tokens, language = kwargs.get("language", self.language)))
<SYSTEM_TASK:> Returns a list of sentences, where each sentence is a list of tokens, <END_TASK> <USER_TASK:> Description: def split(self, sep=TOKENS): """ Returns a list of sentences, where each sentence is a list of tokens, where each token is a list of word + tags. """
if sep != TOKENS: return unicode.split(self, sep) if len(self) == 0: return [] return [[[x.replace("&slash;", "/") for x in token.split("/")] for token in sentence.split(" ")] for sentence in unicode.split(self, "\n")]
<SYSTEM_TASK:> Returns the infinitive form of the given verb, or None. <END_TASK> <USER_TASK:> Description: def lemma(self, verb, parse=True): """ Returns the infinitive form of the given verb, or None. """
if dict.__len__(self) == 0: self.load() if verb.lower() in self._inverse: return self._inverse[verb.lower()] if verb in self._inverse: return self._inverse[verb] if parse is True: # rule-based return self.find_lemma(verb)
<SYSTEM_TASK:> Returns a list of all possible inflections of the given verb. <END_TASK> <USER_TASK:> Description: def lexeme(self, verb, parse=True): """ Returns a list of all possible inflections of the given verb. """
a = [] b = self.lemma(verb, parse=parse) if b in self: a = [x for x in self[b] if x != ""] elif parse is True: # rule-based a = self.find_lexeme(b) u = []; [u.append(x) for x in a if x not in u] return u
<SYSTEM_TASK:> Returns a set of words with edit distance 1 from the given word. <END_TASK> <USER_TASK:> Description: def _edit1(self, w): """ Returns a set of words with edit distance 1 from the given word. """
# Of all spelling errors, 80% is covered by edit distance 1. # Edit distance 1 = one character deleted, swapped, replaced or inserted. split = [(w[:i], w[i:]) for i in range(len(w) + 1)] delete, transpose, replace, insert = ( [a + b[1:] for a, b in split if b], [a + b[1] + b[0] + b[2:] for a, b in split if len(b) > 1], [a + c + b[1:] for a, b in split for c in Spelling.ALPHA if b], [a + c + b[0:] for a, b in split for c in Spelling.ALPHA] ) return set(delete + transpose + replace + insert)
<SYSTEM_TASK:> Returns a set of words with edit distance 2 from the given word <END_TASK> <USER_TASK:> Description: def _edit2(self, w): """ Returns a set of words with edit distance 2 from the given word """
# Of all spelling errors, 99% is covered by edit distance 2. # Only keep candidates that are actually known words (20% speedup). return set(e2 for e1 in self._edit1(w) for e2 in self._edit1(e1) if e2 in self)
<SYSTEM_TASK:> Returns the string with XML-safe special characters. <END_TASK> <USER_TASK:> Description: def xml_encode(string): """ Returns the string with XML-safe special characters. """
string = string.replace("&", "&amp;") string = string.replace("<", "&lt;") string = string.replace(">", "&gt;") string = string.replace("\"","&quot;") string = string.replace(SLASH, "/") return string
<SYSTEM_TASK:> Returns the string with special characters decoded. <END_TASK> <USER_TASK:> Description: def xml_decode(string): """ Returns the string with special characters decoded. """
string = string.replace("&amp;", "&") string = string.replace("&lt;", "<") string = string.replace("&gt;", ">") string = string.replace("&quot;","\"") string = string.replace("/", SLASH) return string
<SYSTEM_TASK:> Returns an NLTK nltk.tree.Tree object from the given Sentence. <END_TASK> <USER_TASK:> Description: def nltk_tree(sentence): """ Returns an NLTK nltk.tree.Tree object from the given Sentence. The NLTK module should be on the search path somewhere. """
from nltk import tree def do_pnp(pnp): # Returns the PNPChunk (and the contained Chunk objects) in NLTK bracket format. s = ' '.join([do_chunk(ch) for ch in pnp.chunks]) return '(PNP %s)' % s def do_chunk(ch): # Returns the Chunk in NLTK bracket format. Recurse attached PNP's. s = ' '.join(['(%s %s)' % (w.pos, w.string) for w in ch.words]) s+= ' '.join([do_pnp(pnp) for pnp in ch.attachments]) return '(%s %s)' % (ch.type, s) T = ['(S'] v = [] # PNP's already visited. for ch in sentence.chunked(): if not ch.pnp and isinstance(ch, Chink): T.append('(%s %s)' % (ch.words[0].pos, ch.words[0].string)) elif not ch.pnp: T.append(do_chunk(ch)) #elif ch.pnp not in v: elif ch.pnp.anchor is None and ch.pnp not in v: # The chunk is part of a PNP without an anchor. T.append(do_pnp(ch.pnp)) v.append(ch.pnp) T.append(')') return tree.bracket_parse(' '.join(T))
<SYSTEM_TASK:> Returns a dot-formatted string that can be visualized as a graph in GraphViz. <END_TASK> <USER_TASK:> Description: def graphviz_dot(sentence, font="Arial", colors=BLUE): """ Returns a dot-formatted string that can be visualized as a graph in GraphViz. """
s = 'digraph sentence {\n' s += '\tranksep=0.75;\n' s += '\tnodesep=0.15;\n' s += '\tnode [penwidth=1, fontname="%s", shape=record, margin=0.1, height=0.35];\n' % font s += '\tedge [penwidth=1];\n' s += '\t{ rank=same;\n' # Create node groups for words, chunks and PNP chunks. for w in sentence.words: s += '\t\tword%s [label="<f0>%s|<f1>%s"%s];\n' % (w.index, w.string, w.type, _colorize(w, colors)) for w in sentence.words[:-1]: # Invisible edges forces the words into the right order: s += '\t\tword%s -> word%s [color=none];\n' % (w.index, w.index+1) s += '\t}\n' s += '\t{ rank=same;\n' for i, ch in enumerate(sentence.chunks): s += '\t\tchunk%s [label="<f0>%s"%s];\n' % (i+1, "-".join([x for x in ( ch.type, ch.role, str(ch.relation or '')) if x]) or '-', _colorize(ch, colors)) for i, ch in enumerate(sentence.chunks[:-1]): # Invisible edges forces the chunks into the right order: s += '\t\tchunk%s -> chunk%s [color=none];\n' % (i+1, i+2) s += '}\n' s += '\t{ rank=same;\n' for i, ch in enumerate(sentence.pnp): s += '\t\tpnp%s [label="<f0>PNP"%s];\n' % (i+1, _colorize(ch, colors)) s += '\t}\n' s += '\t{ rank=same;\n S [shape=circle, margin=0.25, penwidth=2]; }\n' # Connect words to chunks. # Connect chunks to PNP or S. for i, ch in enumerate(sentence.chunks): for w in ch: s += '\tword%s -> chunk%s;\n' % (w.index, i+1) if ch.pnp: s += '\tchunk%s -> pnp%s;\n' % (i+1, sentence.pnp.index(ch.pnp)+1) else: s += '\tchunk%s -> S;\n' % (i+1) if ch.type == 'VP': # Indicate related chunks with a dotted for r in ch.related: s += '\tchunk%s -> chunk%s [style=dotted, arrowhead=none];\n' % ( i+1, sentence.chunks.index(r)+1) # Connect PNP to anchor chunk or S. for i, ch in enumerate(sentence.pnp): if ch.anchor: s += '\tpnp%s -> chunk%s;\n' % (i+1, sentence.chunks.index(ch.anchor)+1) s += '\tpnp%s -> S [color=none];\n' % (i+1) else: s += '\tpnp%s -> S;\n' % (i+1) s += "}" return s
<SYSTEM_TASK:> Returns the next word in the sentence with the given type. <END_TASK> <USER_TASK:> Description: def next(self, type=None): """ Returns the next word in the sentence with the given type. """
i = self.index + 1 s = self.sentence while i < len(s): if type in (s[i].type, None): return s[i] i += 1
<SYSTEM_TASK:> Returns the next previous word in the sentence with the given type. <END_TASK> <USER_TASK:> Description: def previous(self, type=None): """ Returns the next previous word in the sentence with the given type. """
i = self.index - 1 s = self.sentence while i > 0: if type in (s[i].type, None): return s[i] i -= 1
<SYSTEM_TASK:> Yields a list of all chunks in the sentence with the same relation id. <END_TASK> <USER_TASK:> Description: def related(self): """ Yields a list of all chunks in the sentence with the same relation id. """
return [ch for ch in self.sentence.chunks if ch != self and intersects(unzip(0, ch.relations), unzip(0, self.relations))]
<SYSTEM_TASK:> Returns the next chunk in the sentence with the given type. <END_TASK> <USER_TASK:> Description: def next(self, type=None): """ Returns the next chunk in the sentence with the given type. """
i = self.stop s = self.sentence while i < len(s): if s[i].chunk is not None and type in (s[i].chunk.type, None): return s[i].chunk i += 1
<SYSTEM_TASK:> Returns the next previous chunk in the sentence with the given type. <END_TASK> <USER_TASK:> Description: def previous(self, type=None): """ Returns the next previous chunk in the sentence with the given type. """
i = self.start - 1 s = self.sentence while i > 0: if s[i].chunk is not None and type in (s[i].chunk.type, None): return s[i].chunk i -= 1
<SYSTEM_TASK:> Attaches prepositional noun phrases. <END_TASK> <USER_TASK:> Description: def _do_pnp(self, pnp, anchor=None): """ Attaches prepositional noun phrases. Identifies PNP's from either the PNP tag or the P-attachment tag. This does not determine the PP-anchor, it only groups words in a PNP chunk. """
if anchor or pnp and pnp.endswith("PNP"): if anchor is not None: m = find(lambda x: x.startswith("P"), anchor) else: m = None if self.pnp \ and pnp \ and pnp != OUTSIDE \ and pnp.startswith("B-") is False \ and self.words[-2].pnp is not None: self.pnp[-1].append(self.words[-1]) elif m is not None and m == self._attachment: self.pnp[-1].append(self.words[-1]) else: ch = PNPChunk(self, [self.words[-1]], type="PNP") self.pnp.append(ch) self._attachment = m
<SYSTEM_TASK:> Collects preposition anchors and attachments in a dictionary. <END_TASK> <USER_TASK:> Description: def _do_anchor(self, anchor): """ Collects preposition anchors and attachments in a dictionary. Once the dictionary has an entry for both the anchor and the attachment, they are linked. """
if anchor: for x in anchor.split("-"): A, P = None, None if x.startswith("A") and len(self.chunks) > 0: # anchor A, P = x, x.replace("A","P") self._anchors[A] = self.chunks[-1] if x.startswith("P") and len(self.pnp) > 0: # attachment (PNP) A, P = x.replace("P","A"), x self._anchors[P] = self.pnp[-1] if A in self._anchors and P in self._anchors and not self._anchors[P].anchor: pnp = self._anchors[P] pnp.anchor = self._anchors[A] pnp.anchor.attachments.append(pnp)
<SYSTEM_TASK:> Attach conjunctions. <END_TASK> <USER_TASK:> Description: def _do_conjunction(self, _and=("and", "e", "en", "et", "und", "y")): """ Attach conjunctions. CC-words like "and" and "or" between two chunks indicate a conjunction. """
w = self.words if len(w) > 2 and w[-2].type == "CC" and w[-2].chunk is None: cc = w[-2].string.lower() in _and and AND or OR ch1 = w[-3].chunk ch2 = w[-1].chunk if ch1 is not None and \ ch2 is not None: ch1.conjunctions.append(ch2, cc) ch2.conjunctions.append(ch1, cc)
<SYSTEM_TASK:> Returns a tag for the word at the given index. <END_TASK> <USER_TASK:> Description: def get(self, index, tag=LEMMA): """ Returns a tag for the word at the given index. The tag can be WORD, LEMMA, POS, CHUNK, PNP, RELATION, ROLE, ANCHOR or a custom word tag. """
if tag == WORD: return self.words[index] if tag == LEMMA: return self.words[index].lemma if tag == POS: return self.words[index].type if tag == CHUNK: return self.words[index].chunk if tag == PNP: return self.words[index].pnp if tag == REL: ch = self.words[index].chunk; return ch and ch.relation if tag == ROLE: ch = self.words[index].chunk; return ch and ch.role if tag == ANCHOR: ch = self.words[index].pnp; return ch and ch.anchor if tag in self.words[index].custom_tags: return self.words[index].custom_tags[tag] return None
<SYSTEM_TASK:> Returns a portion of the sentence from word start index to word stop index. <END_TASK> <USER_TASK:> Description: def slice(self, start, stop): """ Returns a portion of the sentence from word start index to word stop index. The returned slice is a subclass of Sentence and a deep copy. """
s = Slice(token=self.token, language=self.language) for i, word in enumerate(self.words[start:stop]): # The easiest way to copy (part of) a sentence # is by unpacking all of the token tags and passing them to Sentence.append(). p0 = word.string # WORD p1 = word.lemma # LEMMA p2 = word.type # POS p3 = word.chunk is not None and word.chunk.type or None # CHUNK p4 = word.pnp is not None and "PNP" or None # PNP p5 = word.chunk is not None and unzip(0, word.chunk.relations) or None # REL p6 = word.chunk is not None and unzip(1, word.chunk.relations) or None # ROLE p7 = word.chunk and word.chunk.anchor_id or None # ANCHOR p8 = word.chunk and word.chunk.start == start+i and BEGIN or None # IOB p9 = word.custom_tags # User-defined tags. # If the given range does not contain the chunk head, remove the chunk tags. if word.chunk is not None and (word.chunk.stop > stop): p3, p4, p5, p6, p7, p8 = None, None, None, None, None, None # If the word starts the preposition, add the IOB B-prefix (i.e., B-PNP). if word.pnp is not None and word.pnp.start == start+i: p4 = BEGIN+"-"+"PNP" # If the given range does not contain the entire PNP, remove the PNP tags. # The range must contain the entire PNP, # since it starts with the PP and ends with the chunk head (and is meaningless without these). if word.pnp is not None and (word.pnp.start < start or word.chunk.stop > stop): p4, p7 = None, None s.append(word=p0, lemma=p1, type=p2, chunk=p3, pnp=p4, relation=p5, role=p6, anchor=p7, iob=p8, custom=p9) s.parent = self s._start = start return s
<SYSTEM_TASK:> Returns an in-order list of mixed Chunk and Word objects. <END_TASK> <USER_TASK:> Description: def constituents(self, pnp=False): """ Returns an in-order list of mixed Chunk and Word objects. With pnp=True, also contains PNPChunk objects whenever possible. """
a = [] for word in self.words: if pnp and word.pnp is not None: if len(a) == 0 or a[-1] != word.pnp: a.append(word.pnp) elif word.chunk is not None: if len(a) == 0 or a[-1] != word.chunk: a.append(word.chunk) else: a.append(word) return a
<SYSTEM_TASK:> Solve system for a set of parameters in which one is varied <END_TASK> <USER_TASK:> Description: def solve_series(self, x0, params, varied_data, varied_idx, internal_x0=None, solver=None, propagate=True, **kwargs): """ Solve system for a set of parameters in which one is varied Parameters ---------- x0 : array_like Guess (subject to ``self.post_processors``) params : array_like Parameter values vaired_data : array_like Numerical values of the varied parameter. varied_idx : int or str Index of the varied parameter (indexing starts at 0). If ``self.par_by_name`` this should be the name (str) of the varied parameter. internal_x0 : array_like (default: None) Guess (*not* subject to ``self.post_processors``). Overrides ``x0`` when given. solver : str or callback See :meth:`solve`. propagate : bool (default: True) Use last successful solution as ``x0`` in consecutive solves. \\*\\*kwargs : Keyword arguments pass along to :meth:`solve`. Returns ------- xout : array Of shape ``(varied_data.size, x0.size)``. info_dicts : list of dictionaries Dictionaries each containing keys such as containing 'success', 'nfev', 'njev' etc. """
if self.x_by_name and isinstance(x0, dict): x0 = [x0[k] for k in self.names] if self.par_by_name: if isinstance(params, dict): params = [params[k] for k in self.param_names] if isinstance(varied_idx, str): varied_idx = self.param_names.index(varied_idx) new_params = np.atleast_1d(np.array(params, dtype=np.float64)) xout = np.empty((len(varied_data), len(x0))) self.internal_xout = np.empty_like(xout) self.internal_params_out = np.empty((len(varied_data), len(new_params))) info_dicts = [] new_x0 = np.array(x0, dtype=np.float64) # copy conds = kwargs.get('initial_conditions', None) # see ConditionalNeqSys for idx, value in enumerate(varied_data): try: new_params[varied_idx] = value except TypeError: new_params = value # e.g. type(new_params) == int if conds is not None: kwargs['initial_conditions'] = conds x, info_dict = self.solve(new_x0, new_params, internal_x0, solver, **kwargs) if propagate: if info_dict['success']: try: # See ChainedNeqSys.solve new_x0 = info_dict['x_vecs'][0] internal_x0 = info_dict['internal_x_vecs'][0] conds = info_dict['intermediate_info'][0].get( 'conditions', None) except: new_x0 = x internal_x0 = None conds = info_dict.get('conditions', None) xout[idx, :] = x self.internal_xout[idx, :] = self.internal_x self.internal_params_out[idx, :] = self.internal_params info_dicts.append(info_dict) return xout, info_dicts
<SYSTEM_TASK:> Solve and plot for a series of a varied parameter. <END_TASK> <USER_TASK:> Description: def solve_and_plot_series(self, x0, params, varied_data, varied_idx, solver=None, plot_kwargs=None, plot_residuals_kwargs=None, **kwargs): """ Solve and plot for a series of a varied parameter. Convenience method, see :meth:`solve_series`, :meth:`plot_series` & :meth:`plot_series_residuals_internal` for more information. """
sol, nfo = self.solve_series( x0, params, varied_data, varied_idx, solver=solver, **kwargs) ax_sol = self.plot_series(sol, varied_data, varied_idx, info=nfo, **(plot_kwargs or {})) extra = dict(ax_sol=ax_sol, info=nfo) if plot_residuals_kwargs: extra['ax_resid'] = self.plot_series_residuals_internal( varied_data, varied_idx, info=nfo, **(plot_residuals_kwargs or {}) ) return sol, extra
<SYSTEM_TASK:> Solve with user specified ``solver`` choice. <END_TASK> <USER_TASK:> Description: def solve(self, x0, params=(), internal_x0=None, solver=None, attached_solver=None, **kwargs): """ Solve with user specified ``solver`` choice. Parameters ---------- x0: 1D array of floats Guess (subject to ``self.post_processors``) params: 1D array_like of floats Parameters (subject to ``self.post_processors``) internal_x0: 1D array of floats When given it overrides (processed) ``x0``. ``internal_x0`` is not subject to ``self.post_processors``. solver: str or callable or None or iterable of such if str: uses _solve_``solver``(\*args, \*\*kwargs). if ``None``: chooses from PYNEQSYS_SOLVER environment variable. if iterable: chain solving. attached_solver: callable factory Invokes: solver = attached_solver(self). Returns ------- array: solution vector (post-processed by self.post_processors) dict: info dictionary containing 'success', 'nfev', 'njev' etc. Examples -------- >>> neqsys = NeqSys(2, 2, lambda x, p: [ ... (x[0] - x[1])**p[0]/2 + x[0] - 1, ... (x[1] - x[0])**p[0]/2 + x[1] ... ]) >>> x, sol = neqsys.solve([1, 0], [3], solver=(None, 'mpmath')) >>> assert sol['success'] >>> print(x) [0.841163901914009663684741869855] [0.158836098085990336315258130144] """
if not isinstance(solver, (tuple, list)): solver = [solver] if not isinstance(attached_solver, (tuple, list)): attached_solver = [attached_solver] + [None]*(len(solver) - 1) _x0, self.internal_params = self.pre_process(x0, params) for solv, attached_solv in zip(solver, attached_solver): if internal_x0 is not None: _x0 = internal_x0 elif self.internal_x0_cb is not None: _x0 = self.internal_x0_cb(x0, params) nfo = self._get_solver_cb(solv, attached_solv)(_x0, **kwargs) _x0 = nfo['x'].copy() self.internal_x = _x0 x0 = self.post_process(self.internal_x, self.internal_params)[0] return x0, nfo
<SYSTEM_TASK:> Constructs a pyneqsys.symbolic.SymbolicSys instance and returns from its ``solve`` method. <END_TASK> <USER_TASK:> Description: def solve(guess_a, guess_b, power, solver='scipy'): """ Constructs a pyneqsys.symbolic.SymbolicSys instance and returns from its ``solve`` method. """
# The problem is 2 dimensional so we need 2 symbols x = sp.symbols('x:2', real=True) # There is a user specified parameter ``p`` in this problem: p = sp.Symbol('p', real=True, negative=False, integer=True) # Our system consists of 2-non-linear equations: f = [x[0] + (x[0] - x[1])**p/2 - 1, (x[1] - x[0])**p/2 + x[1]] # We construct our ``SymbolicSys`` instance by passing variables, equations and parameters: neqsys = SymbolicSys(x, f, [p]) # (this will derive the Jacobian symbolically) # Finally we solve the system using user-specified ``solver`` choice: return neqsys.solve([guess_a, guess_b], [power], solver=solver)
<SYSTEM_TASK:> Example demonstrating how to solve a system of non-linear equations defined as SymPy expressions. <END_TASK> <USER_TASK:> Description: def main(guess_a=1., guess_b=0., power=3, savetxt='None', verbose=False): """ Example demonstrating how to solve a system of non-linear equations defined as SymPy expressions. The example shows how a non-linear problem can be given a command-line interface which may be preferred by end-users who are not familiar with Python. """
x, sol = solve(guess_a, guess_b, power) # see function definition above assert sol.success if savetxt != 'None': np.savetxt(x, savetxt) else: if verbose: print(sol) else: print(x)
<SYSTEM_TASK:> Plot the values of the solution vector vs the varied parameter. <END_TASK> <USER_TASK:> Description: def plot_series(xres, varied_data, indices=None, info=None, fail_vline=None, plot_kwargs_cb=None, ls=('-', '--', ':', '-.'), c=('k', 'r', 'g', 'b', 'c', 'm', 'y'), labels=None, ax=None, names=None, latex_names=None): """ Plot the values of the solution vector vs the varied parameter. Parameters ---------- xres : array Solution vector of shape ``(varied_data.size, x0.size)``. varied_data : array Numerical values of the varied parameter. indices : iterable of integers, optional Indices of variables to be plotted. default: all fail_vline : bool Show vertical lines where the solver failed. plot_kwargs_cb : callable Takes the index as single argument, returns a dict passed to the plotting function ls : iterable of str Linestyles. c : iterable of str Colors. labels : iterable of str ax : matplotlib Axes instance names : iterable of str latex_names : iterable of str """
import matplotlib.pyplot as plt if indices is None: indices = range(xres.shape[1]) if fail_vline is None: if info is None: fail_vline = False else: fail_vline = True if ax is None: ax = plt.subplot(1, 1, 1) if labels is None: labels = names if latex_names is None else ['$%s$' % ln.strip('$') for ln in latex_names] if plot_kwargs_cb is None: def plot_kwargs_cb(idx, labels=None): kwargs = {'ls': ls[idx % len(ls)], 'c': c[idx % len(c)]} if labels: kwargs['label'] = labels[idx] return kwargs else: plot_kwargs_cb = plot_kwargs_cb or (lambda idx: {}) for idx in indices: ax.plot(varied_data, xres[:, idx], **plot_kwargs_cb(idx, labels=labels)) if fail_vline: for i, nfo in enumerate(info): if not nfo['success']: ax.axvline(varied_data[i], c='k', ls='--') return ax
<SYSTEM_TASK:> Places a legend box outside a matplotlib Axes instance. <END_TASK> <USER_TASK:> Description: def mpl_outside_legend(ax, **kwargs): """ Places a legend box outside a matplotlib Axes instance. """
box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.75, box.height]) # Put a legend to the right of the current axis ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)
<SYSTEM_TASK:> Transform a linear system to reduced row-echelon form <END_TASK> <USER_TASK:> Description: def linear_rref(A, b, Matrix=None, S=None): """ Transform a linear system to reduced row-echelon form Transforms both the matrix and right-hand side of a linear system of equations to reduced row echelon form Parameters ---------- A : Matrix-like Iterable of rows. b : iterable Returns ------- A', b' - transformed versions """
if Matrix is None: from sympy import Matrix if S is None: from sympy import S mat_rows = [_map2l(S, list(row) + [v]) for row, v in zip(A, b)] aug = Matrix(mat_rows) raug, pivot = aug.rref() nindep = len(pivot) return raug[:nindep, :-1], raug[:nindep, -1]
<SYSTEM_TASK:> Returns Ax - b <END_TASK> <USER_TASK:> Description: def linear_exprs(A, x, b=None, rref=False, Matrix=None): """ Returns Ax - b Parameters ---------- A : matrix_like of numbers Of shape (len(b), len(x)). x : iterable of symbols b : array_like of numbers (default: None) When ``None``, assume zeros of length ``len(x)``. Matrix : class When ``rref == True``: A matrix class which supports slicing, and methods ``__mul__`` and ``rref``. Defaults to ``sympy.Matrix``. rref : bool Calculate the reduced row echelon form of (A | -b). Returns ------- A list of the elements in the resulting column vector. """
if b is None: b = [0]*len(x) if rref: rA, rb = linear_rref(A, b, Matrix) if Matrix is None: from sympy import Matrix return [lhs - rhs for lhs, rhs in zip(rA * Matrix(len(x), 1, x), rb)] else: return [sum([x0*x1 for x0, x1 in zip(row, x)]) - v for row, v in zip(A, b)]
<SYSTEM_TASK:> Generate a SymbolicSys instance from a callback. <END_TASK> <USER_TASK:> Description: def from_callback(cls, cb, nx=None, nparams=None, **kwargs): """ Generate a SymbolicSys instance from a callback. Parameters ---------- cb : callable Should have the signature ``cb(x, p, backend) -> list of exprs``. nx : int Number of unknowns, when not given it is deduced from ``kwargs['names']``. nparams : int Number of parameters, when not given it is deduced from ``kwargs['param_names']``. \\*\\*kwargs : Keyword arguments passed on to :class:`SymbolicSys`. See also :class:`pyneqsys.NeqSys`. Examples -------- >>> symbolicsys = SymbolicSys.from_callback(lambda x, p, be: [ ... x[0]*x[1] - p[0], ... be.exp(-x[0]) + be.exp(-x[1]) - p[0]**-2 ... ], 2, 1) ... """
if kwargs.get('x_by_name', False): if 'names' not in kwargs: raise ValueError("Need ``names`` in kwargs.") if nx is None: nx = len(kwargs['names']) elif nx != len(kwargs['names']): raise ValueError("Inconsistency between nx and length of ``names``.") if kwargs.get('par_by_name', False): if 'param_names' not in kwargs: raise ValueError("Need ``param_names`` in kwargs.") if nparams is None: nparams = len(kwargs['param_names']) elif nparams != len(kwargs['param_names']): raise ValueError("Inconsistency between ``nparam`` and length of ``param_names``.") if nparams is None: nparams = 0 if nx is None: raise ValueError("Need ``nx`` of ``names`` together with ``x_by_name==True``.") be = Backend(kwargs.pop('backend', None)) x = be.real_symarray('x', nx) p = be.real_symarray('p', nparams) _x = dict(zip(kwargs['names'], x)) if kwargs.get('x_by_name', False) else x _p = dict(zip(kwargs['param_names'], p)) if kwargs.get('par_by_name', False) else p try: exprs = cb(_x, _p, be) except TypeError: exprs = _ensure_3args(cb)(_x, _p, be) return cls(x, exprs, p, backend=be, **kwargs)
<SYSTEM_TASK:> Return the jacobian of the expressions <END_TASK> <USER_TASK:> Description: def get_jac(self): """ Return the jacobian of the expressions """
if self._jac is True: if self.band is None: f = self.be.Matrix(self.nf, 1, self.exprs) _x = self.be.Matrix(self.nx, 1, self.x) return f.jacobian(_x) else: # Banded return self.be.Matrix(banded_jacobian( self.exprs, self.x, *self.band)) elif self._jac is False: return False else: return self._jac
<SYSTEM_TASK:> Generate a TransformedSys instance from a callback <END_TASK> <USER_TASK:> Description: def from_callback(cls, cb, transf_cbs, nx, nparams=0, pre_adj=None, **kwargs): """ Generate a TransformedSys instance from a callback Parameters ---------- cb : callable Should have the signature ``cb(x, p, backend) -> list of exprs``. The callback ``cb`` should return *untransformed* expressions. transf_cbs : pair or iterable of pairs of callables Callables for forward- and backward-transformations. Each callable should take a single parameter (expression) and return a single expression. nx : int Number of unkowns. nparams : int Number of parameters. pre_adj : callable, optional To tweak expression prior to transformation. Takes a sinlge argument (expression) and return a single argument rewritten expression. \\*\\*kwargs : Keyword arguments passed on to :class:`TransformedSys`. See also :class:`SymbolicSys` and :class:`pyneqsys.NeqSys`. Examples -------- >>> import sympy as sp >>> transformed = TransformedSys.from_callback(lambda x, p, be: [ ... x[0]*x[1] - p[0], ... be.exp(-x[0]) + be.exp(-x[1]) - p[0]**-2 ... ], (sp.log, sp.exp), 2, 1) ... """
be = Backend(kwargs.pop('backend', None)) x = be.real_symarray('x', nx) p = be.real_symarray('p', nparams) try: transf = [(transf_cbs[idx][0](xi), transf_cbs[idx][1](xi)) for idx, xi in enumerate(x)] except TypeError: transf = zip(_map2(transf_cbs[0], x), _map2(transf_cbs[1], x)) try: exprs = cb(x, p, be) except TypeError: exprs = _ensure_3args(cb)(x, p, be) return cls(x, _map2l(pre_adj, exprs), transf, p, backend=be, **kwargs)
<SYSTEM_TASK:> Replace vector images with fake ones. <END_TASK> <USER_TASK:> Description: def _workaround_no_vector_images(project): """Replace vector images with fake ones."""
RED = (255, 0, 0) PLACEHOLDER = kurt.Image.new((32, 32), RED) for scriptable in [project.stage] + project.sprites: for costume in scriptable.costumes: if costume.image.format == "SVG": yield "%s - %s" % (scriptable.name, costume.name) costume.image = PLACEHOLDER
<SYSTEM_TASK:> Returns the first format plugin whose attributes match kwargs. <END_TASK> <USER_TASK:> Description: def get_plugin(cls, name=None, **kwargs): """Returns the first format plugin whose attributes match kwargs. For example:: get_plugin(extension="scratch14") Will return the :class:`KurtPlugin` whose :attr:`extension <KurtPlugin.extension>` attribute is ``"scratch14"``. The :attr:`name <KurtPlugin.name>` is used as the ``format`` parameter to :attr:`Project.load` and :attr:`Project.save`. :raises: :class:`ValueError` if the format doesn't exist. :returns: :class:`KurtPlugin` """
if isinstance(name, KurtPlugin): return name if 'extension' in kwargs: kwargs['extension'] = kwargs['extension'].lower() if name: kwargs["name"] = name if not kwargs: raise ValueError, "No arguments" for plugin in cls.plugins.values(): for name in kwargs: if getattr(plugin, name) != kwargs[name]: break else: return plugin raise ValueError, "Unknown format %r" % kwargs
<SYSTEM_TASK:> Clean up the given list of scripts in-place so none of the scripts <END_TASK> <USER_TASK:> Description: def clean_up(scripts): """Clean up the given list of scripts in-place so none of the scripts overlap. """
scripts_with_pos = [s for s in scripts if s.pos] scripts_with_pos.sort(key=lambda s: (s.pos[1], s.pos[0])) scripts = scripts_with_pos + [s for s in scripts if not s.pos] y = 20 for script in scripts: script.pos = (20, y) if isinstance(script, kurt.Script): y += stack_height(script.blocks) elif isinstance(script, kurt.Comment): y += 14 y += 15
<SYSTEM_TASK:> Return a list of classes in a module that have a 'classID' attribute. <END_TASK> <USER_TASK:> Description: def obj_classes_from_module(module): """Return a list of classes in a module that have a 'classID' attribute."""
for name in dir(module): if not name.startswith('_'): cls = getattr(module, name) if getattr(cls, 'classID', None): yield (name, cls)
<SYSTEM_TASK:> Return root object from ref-containing obj table entries <END_TASK> <USER_TASK:> Description: def decode_network(objects): """Return root object from ref-containing obj table entries"""
def resolve_ref(obj, objects=objects): if isinstance(obj, Ref): # first entry is 1 return objects[obj.index - 1] else: return obj # Reading the ObjTable backwards somehow makes more sense. for i in xrange(len(objects)-1, -1, -1): obj = objects[i] if isinstance(obj, Container): obj.update((k, resolve_ref(v)) for (k, v) in obj.items()) elif isinstance(obj, Dictionary): obj.value = dict( (resolve_ref(field), resolve_ref(value)) for (field, value) in obj.value.items() ) elif isinstance(obj, dict): obj = dict( (resolve_ref(field), resolve_ref(value)) for (field, value) in obj.items() ) elif isinstance(obj, list): obj = [resolve_ref(field) for field in obj] elif isinstance(obj, Form): for field in obj.value: value = getattr(obj, field) value = resolve_ref(value) setattr(obj, field, value) elif isinstance(obj, ContainsRefs): obj.value = [resolve_ref(field) for field in obj.value] objects[i] = obj for obj in objects: if isinstance(obj, Form): obj.built() root = objects[0] return root
<SYSTEM_TASK:> Encodes a class to a lower-level object using the class' own <END_TASK> <USER_TASK:> Description: def _encode(self, obj, context): """Encodes a class to a lower-level object using the class' own to_construct function. If no such function is defined, returns the object unchanged. """
func = getattr(obj, 'to_construct', None) if callable(func): return func(context) else: return obj
<SYSTEM_TASK:> Initialises a new Python class from a construct using the mapping <END_TASK> <USER_TASK:> Description: def _decode(self, obj, context): """Initialises a new Python class from a construct using the mapping passed to the adapter. """
cls = self._get_class(obj.classID) return cls.from_construct(obj, context)
<SYSTEM_TASK:> Returns a Form with 32-bit RGBA pixels <END_TASK> <USER_TASK:> Description: def from_string(cls, width, height, rgba_string): """Returns a Form with 32-bit RGBA pixels Accepts string containing raw RGBA color values """
# Convert RGBA string to ARGB raw = "" for i in range(0, len(rgba_string), 4): raw += rgba_string[i+3] # alpha raw += rgba_string[i:i+3] # rgb assert len(rgba_string) == width * height * 4 return Form( width = width, height = height, depth = 32, bits = Bitmap(raw), )
<SYSTEM_TASK:> Load project from file. <END_TASK> <USER_TASK:> Description: def load(cls, path, format=None): """Load project from file. Use ``format`` to specify the file format to use. Path can be a file-like object, in which case format is required. Otherwise, can guess the appropriate format from the extension. If you pass a file-like object, you're responsible for closing the file. :param path: Path or file pointer. :param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``. Overrides the extension. :raises: :class:`UnknownFormat` if the extension is unrecognised. :raises: :py:class:`ValueError` if the format doesn't exist. """
path_was_string = isinstance(path, basestring) if path_was_string: (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) if format is None: plugin = kurt.plugin.Kurt.get_plugin(extension=extension) if not plugin: raise UnknownFormat(extension) fp = open(path, "rb") else: fp = path assert format, "Format is required" plugin = kurt.plugin.Kurt.get_plugin(format) if not plugin: raise ValueError, "Unknown format %r" % format project = plugin.load(fp) if path_was_string: fp.close() project.convert(plugin) if isinstance(path, basestring): project.path = path if not project.name: project.name = name return project
<SYSTEM_TASK:> Return a new Project instance, deep-copying all the attributes. <END_TASK> <USER_TASK:> Description: def copy(self): """Return a new Project instance, deep-copying all the attributes."""
p = Project() p.name = self.name p.path = self.path p._plugin = self._plugin p.stage = self.stage.copy() p.stage.project = p for sprite in self.sprites: s = sprite.copy() s.project = p p.sprites.append(s) for actor in self.actors: if isinstance(actor, Sprite): p.actors.append(p.get_sprite(actor.name)) else: a = actor.copy() if isinstance(a, Watcher): if isinstance(a.target, Project): a.target = p elif isinstance(a.target, Stage): a.target = p.stage else: a.target = p.get_sprite(a.target.name) p.actors.append(a) p.variables = dict((n, v.copy()) for (n, v) in self.variables.items()) p.lists = dict((n, l.copy()) for (n, l) in self.lists.items()) p.thumbnail = self.thumbnail p.tempo = self.tempo p.notes = self.notes p.author = self.author return p
<SYSTEM_TASK:> Convert the project in-place to a different file format. <END_TASK> <USER_TASK:> Description: def convert(self, format): """Convert the project in-place to a different file format. Returns a list of :class:`UnsupportedFeature` objects, which may give warnings about the conversion. :param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``. :raises: :class:`ValueError` if the format doesn't exist. """
self._plugin = kurt.plugin.Kurt.get_plugin(format) return list(self._normalize())
<SYSTEM_TASK:> Save project to file. <END_TASK> <USER_TASK:> Description: def save(self, path=None, debug=False): """Save project to file. :param path: Path or file pointer. If you pass a file pointer, you're responsible for closing it. If path is not given, the :attr:`path` attribute is used, usually the original path given to :attr:`load()`. If `path` has the extension of an existing plugin, the project will be converted using :attr:`convert`. Otherwise, the extension will be replaced with the extension of the current plugin. (Note that log output for the conversion will be printed to stdout. If you want to deal with the output, call :attr:`convert` directly.) If the path ends in a folder instead of a file, the filename is based on the project's :attr:`name`. :param debug: If true, return debugging information from the format plugin instead of the path. :raises: :py:class:`ValueError` if there's no path or name. :returns: path to the saved file. """
p = self.copy() plugin = p._plugin # require path p.path = path or self.path if not p.path: raise ValueError, "path is required" if isinstance(p.path, basestring): # split path (folder, filename) = os.path.split(p.path) (name, extension) = os.path.splitext(filename) # get plugin from extension if path: # only if not using self.path try: plugin = kurt.plugin.Kurt.get_plugin(extension=extension) except ValueError: pass # build output path if not name: name = _clean_filename(self.name) if not name: raise ValueError, "name is required" filename = name + plugin.extension p.path = os.path.join(folder, filename) # open fp = open(p.path, "wb") else: fp = p.path path = None if not plugin: raise ValueError, "must convert project to a format before saving" for m in p.convert(plugin): print m result = p._save(fp) if path: fp.close() return result if debug else p.path
<SYSTEM_TASK:> Returns the color value in hexcode format. <END_TASK> <USER_TASK:> Description: def stringify(self): """Returns the color value in hexcode format. eg. ``'#ff1056'`` """
hexcode = "#" for x in self.value: part = hex(x)[2:] if len(part) < 2: part = "0" + part hexcode += part return hexcode
<SYSTEM_TASK:> Return a list of valid options to a menu insert, given a <END_TASK> <USER_TASK:> Description: def options(self, scriptable=None): """Return a list of valid options to a menu insert, given a Scriptable for context. Mostly complete, excepting 'attribute'. """
options = list(Insert.KIND_OPTIONS.get(self.kind, [])) if scriptable: if self.kind == 'var': options += scriptable.variables.keys() options += scriptable.project.variables.keys() elif self.kind == 'list': options += scriptable.lists.keys() options += scriptable.project.lists.keys() elif self.kind == 'costume': options += [c.name for c in scriptable.costumes] elif self.kind == 'backdrop': options += [c.name for c in scriptable.project.stage.costumes] elif self.kind == 'sound': options += [c.name for c in scriptable.sounds] options += [c.name for c in scriptable.project.stage.sounds] elif self.kind in ('spriteOnly', 'spriteOrMouse', 'spriteOrStage', 'touching'): options += [s.name for s in scriptable.project.sprites] elif self.kind == 'attribute': pass # TODO elif self.kind == 'broadcast': options += list(set(scriptable.project.get_broadcasts())) return options
<SYSTEM_TASK:> The text displayed on the block. <END_TASK> <USER_TASK:> Description: def text(self): """The text displayed on the block. String containing ``"%s"`` in place of inserts. eg. ``'say %s for %s secs'`` """
parts = [("%s" if isinstance(p, Insert) else p) for p in self.parts] parts = [("%%" if p == "%" else p) for p in parts] # escape percent return "".join(parts)
<SYSTEM_TASK:> Returns True if any of the inserts have the given shape. <END_TASK> <USER_TASK:> Description: def has_insert(self, shape): """Returns True if any of the inserts have the given shape."""
for insert in self.inserts: if insert.shape == shape: return True return False
<SYSTEM_TASK:> Return True if the plugin supports this block. <END_TASK> <USER_TASK:> Description: def has_conversion(self, plugin): """Return True if the plugin supports this block."""
plugin = kurt.plugin.Kurt.get_plugin(plugin) return plugin.name in self._plugins
<SYSTEM_TASK:> Returns True if any of the plugins have the given command. <END_TASK> <USER_TASK:> Description: def has_command(self, command): """Returns True if any of the plugins have the given command."""
for pbt in self._plugins.values(): if pbt.command == command: return True return False
<SYSTEM_TASK:> Return a new Block instance with the same attributes. <END_TASK> <USER_TASK:> Description: def copy(self): """Return a new Block instance with the same attributes."""
args = [] for arg in self.args: if isinstance(arg, Block): arg = arg.copy() elif isinstance(arg, list): arg = [b.copy() for b in arg] args.append(arg) return Block(self.type, *args)
<SYSTEM_TASK:> Load costume from image file. <END_TASK> <USER_TASK:> Description: def load(self, path): """Load costume from image file. Uses :attr:`Image.load`, but will set the Costume's name based on the image filename. """
(folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Costume(name, Image.load(path))
<SYSTEM_TASK:> The format of the image file. <END_TASK> <USER_TASK:> Description: def format(self): """The format of the image file. An uppercase string corresponding to the :attr:`PIL.ImageFile.ImageFile.format` attribute. Valid values include ``"JPEG"`` and ``"PNG"``. """
if self._format: return self._format elif self.pil_image: return self.pil_image.format
<SYSTEM_TASK:> Return an Image instance with the first matching format. <END_TASK> <USER_TASK:> Description: def convert(self, *formats): """Return an Image instance with the first matching format. For each format in ``*args``: If the image's :attr:`format` attribute is the same as the format, return self, otherwise try the next format. If none of the formats match, return a new Image instance with the last format. """
for format in formats: format = Image.image_format(format) if self.format == format: return self else: return self._convert(format)
<SYSTEM_TASK:> Return a new Image instance with the given format. <END_TASK> <USER_TASK:> Description: def _convert(self, format): """Return a new Image instance with the given format. Returns self if the format is already the same. """
if self.format == format: return self else: image = Image(self.pil_image) image._format = format return image
<SYSTEM_TASK:> Save image to file path. <END_TASK> <USER_TASK:> Description: def save(self, path): """Save image to file path. The image format is guessed from the extension. If path has no extension, the image's :attr:`format` is used. :returns: Path to the saved file. """
(folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) if not name: raise ValueError, "name is required" if extension: format = Image.image_format(extension) else: format = self.format filename = name + self.extension path = os.path.join(folder, filename) image = self.convert(format) if image._contents: f = open(path, "wb") f.write(image._contents) f.close() else: image.pil_image.save(path, format) return path
<SYSTEM_TASK:> Return a new Image instance filled with a color. <END_TASK> <USER_TASK:> Description: def new(self, size, fill): """Return a new Image instance filled with a color."""
return Image(PIL.Image.new("RGB", size, fill))
<SYSTEM_TASK:> Return a new Image instance with the given size. <END_TASK> <USER_TASK:> Description: def resize(self, size): """Return a new Image instance with the given size."""
return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS))
<SYSTEM_TASK:> Return a new Image with the given image pasted on top. <END_TASK> <USER_TASK:> Description: def paste(self, other): """Return a new Image with the given image pasted on top. This image will show through transparent areas of the given image. """
r, g, b, alpha = other.pil_image.split() pil_image = self.pil_image.copy() pil_image.paste(other.pil_image, mask=alpha) return kurt.Image(pil_image)
<SYSTEM_TASK:> Load sound from wave file. <END_TASK> <USER_TASK:> Description: def load(self, path): """Load sound from wave file. Uses :attr:`Waveform.load`, but will set the Waveform's name based on the sound filename. """
(folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Sound(name, Waveform.load(path))
<SYSTEM_TASK:> Save the sound to a wave file at the given path. <END_TASK> <USER_TASK:> Description: def save(self, path): """Save the sound to a wave file at the given path. Uses :attr:`Waveform.save`, but if the path ends in a folder instead of a file, the filename is based on the project's :attr:`name`. :returns: Path to the saved file. """
(folder, filename) = os.path.split(path) if not filename: filename = _clean_filename(self.name) path = os.path.join(folder, filename) return self.waveform.save(path)
<SYSTEM_TASK:> Save waveform to file path as a WAV file. <END_TASK> <USER_TASK:> Description: def save(self, path): """Save waveform to file path as a WAV file. :returns: Path to the saved file. """
(folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) if not name: raise ValueError, "name is required" path = os.path.join(folder, name + self.extension) f = open(path, "wb") f.write(self.contents) f.close() return path
<SYSTEM_TASK:> Open a new channel on this connection. <END_TASK> <USER_TASK:> Description: def open_channel(self): """ Open a new channel on this connection. This method is a :ref:`coroutine <coroutine>`. :return: The new :class:`Channel` object. """
if self._closing: raise ConnectionClosed("Closed by application") if self.closed.done(): raise self.closed.exception() channel = yield from self.channel_factory.open() return channel
<SYSTEM_TASK:> Close the connection by handshaking with the server. <END_TASK> <USER_TASK:> Description: def close(self): """ Close the connection by handshaking with the server. This method is a :ref:`coroutine <coroutine>`. """
if not self.is_closed(): self._closing = True # Let the ConnectionActor do the actual close operations. # It will do the work on CloseOK self.sender.send_Close( 0, 'Connection closed by application', 0, 0) try: yield from self.synchroniser.wait(spec.ConnectionCloseOK) except AMQPConnectionError: # For example if both sides want to close or the connection # is closed. pass else: if self._closing: log.warn("Called `close` on already closing connection...") # finish all pending tasks yield from self.protocol.heartbeat_monitor.wait_closed()
<SYSTEM_TASK:> Is sent in case protocol lost connection to server. <END_TASK> <USER_TASK:> Description: def handle_PoisonPillFrame(self, frame): """ Is sent in case protocol lost connection to server."""
# Will be delivered after Close or CloseOK handlers. It's for channels, # so ignore it. if self.connection.closed.done(): return # If connection was not closed already - we lost connection. # Protocol should already be closed self._close_all(frame.exception)
<SYSTEM_TASK:> Publish a message on the exchange, to be asynchronously delivered to queues. <END_TASK> <USER_TASK:> Description: def publish(self, message, routing_key, *, mandatory=True): """ Publish a message on the exchange, to be asynchronously delivered to queues. :param asynqp.Message message: the message to send :param str routing_key: the routing key with which to publish the message :param bool mandatory: if True (the default) undeliverable messages result in an error (see also :meth:`Channel.set_return_handler`) """
self.sender.send_BasicPublish(self.name, routing_key, mandatory, message)
<SYSTEM_TASK:> Delete the exchange. <END_TASK> <USER_TASK:> Description: def delete(self, *, if_unused=True): """ Delete the exchange. This method is a :ref:`coroutine <coroutine>`. :keyword bool if_unused: If true, the exchange will only be deleted if it has no queues bound to it. """
self.sender.send_ExchangeDelete(self.name, if_unused) yield from self.synchroniser.wait(spec.ExchangeDeleteOK) self.reader.ready()
<SYSTEM_TASK:> Reject the message. <END_TASK> <USER_TASK:> Description: def reject(self, *, requeue=True): """ Reject the message. :keyword bool requeue: if true, the broker will attempt to requeue the message and deliver it to an alternate consumer. """
self.sender.send_BasicReject(self.delivery_tag, requeue)
<SYSTEM_TASK:> Declare a queue on the broker. If the queue does not exist, it will be created. <END_TASK> <USER_TASK:> Description: def declare_queue(self, name='', *, durable=True, exclusive=False, auto_delete=False, passive=False, nowait=False, arguments=None): """ Declare a queue on the broker. If the queue does not exist, it will be created. This method is a :ref:`coroutine <coroutine>`. :param str name: the name of the queue. Supplying a name of '' will create a queue with a unique name of the server's choosing. :keyword bool durable: If true, the queue will be re-created when the server restarts. :keyword bool exclusive: If true, the queue can only be accessed by the current connection, and will be deleted when the connection is closed. :keyword bool auto_delete: If true, the queue will be deleted when the last consumer is cancelled. If there were never any conusmers, the queue won't be deleted. :keyword bool passive: If true and queue with such a name does not exist it will raise a :class:`exceptions.NotFound` instead of creating it. Arguments ``durable``, ``auto_delete`` and ``exclusive`` are ignored if ``passive=True``. :keyword bool nowait: If true, will not wait for a declare-ok to arrive. :keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`. :return: The new :class:`Queue` object. """
q = yield from self.queue_factory.declare( name, durable, exclusive, auto_delete, passive, nowait, arguments if arguments is not None else {}) return q
<SYSTEM_TASK:> Specify quality of service by requesting that messages be pre-fetched <END_TASK> <USER_TASK:> Description: def set_qos(self, prefetch_size=0, prefetch_count=0, apply_globally=False): """ Specify quality of service by requesting that messages be pre-fetched from the server. Pre-fetching means that the server will deliver messages to the client while the client is still processing unacknowledged messages. This method is a :ref:`coroutine <coroutine>`. :param int prefetch_size: Specifies a prefetch window in bytes. Messages smaller than this will be sent from the server in advance. This value may be set to 0, which means "no specific limit". :param int prefetch_count: Specifies a prefetch window in terms of whole messages. :param bool apply_globally: If true, apply these QoS settings on a global level. The meaning of this is implementation-dependent. From the `RabbitMQ documentation <https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.qos.global>`_: RabbitMQ has reinterpreted this field. The original specification said: "By default the QoS settings apply to the current channel only. If this field is set, they are applied to the entire connection." Instead, RabbitMQ takes global=false to mean that the QoS settings should apply per-consumer (for new consumers on the channel; existing ones being unaffected) and global=true to mean that the QoS settings should apply per-channel. """
self.sender.send_BasicQos(prefetch_size, prefetch_count, apply_globally) yield from self.synchroniser.wait(spec.BasicQosOK) self.reader.ready()
<SYSTEM_TASK:> Close the channel by handshaking with the server. <END_TASK> <USER_TASK:> Description: def close(self): """ Close the channel by handshaking with the server. This method is a :ref:`coroutine <coroutine>`. """
# If we aren't already closed ask for server to close if not self.is_closed(): self._closing = True # Let the ChannelActor do the actual close operations. # It will do the work on CloseOK self.sender.send_Close( 0, 'Channel closed by application', 0, 0) try: yield from self.synchroniser.wait(spec.ChannelCloseOK) except AMQPError: # For example if both sides want to close or the connection # is closed. pass else: if self._closing: log.warn("Called `close` on already closing channel...")
<SYSTEM_TASK:> AMQP server closed channel as per our request <END_TASK> <USER_TASK:> Description: def handle_ChannelCloseOK(self, frame): """ AMQP server closed channel as per our request """
assert self.channel._closing, "received a not expected CloseOk" # Release the `close` method's future self.synchroniser.notify(spec.ChannelCloseOK) exc = ChannelClosed() self._close_all(exc)
<SYSTEM_TASK:> Bind a queue to an exchange, with the supplied routing key. <END_TASK> <USER_TASK:> Description: def bind(self, exchange, routing_key, *, arguments=None): """ Bind a queue to an exchange, with the supplied routing key. This action 'subscribes' the queue to the routing key; the precise meaning of this varies with the exchange type. This method is a :ref:`coroutine <coroutine>`. :param asynqp.Exchange exchange: the :class:`Exchange` to bind to :param str routing_key: the routing key under which to bind :keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`. :return: The new :class:`QueueBinding` object """
if self.deleted: raise Deleted("Queue {} was deleted".format(self.name)) if not exchange: raise InvalidExchangeName("Can't bind queue {} to the default exchange".format(self.name)) self.sender.send_QueueBind(self.name, exchange.name, routing_key, arguments or {}) yield from self.synchroniser.wait(spec.QueueBindOK) b = QueueBinding(self.reader, self.sender, self.synchroniser, self, exchange, routing_key) self.reader.ready() return b
<SYSTEM_TASK:> Start a consumer on the queue. Messages will be delivered asynchronously to the consumer. <END_TASK> <USER_TASK:> Description: def consume(self, callback, *, no_local=False, no_ack=False, exclusive=False, arguments=None): """ Start a consumer on the queue. Messages will be delivered asynchronously to the consumer. The callback function will be called whenever a new message arrives on the queue. Advanced usage: the callback object must be callable (it must be a function or define a ``__call__`` method), but may also define some further methods: * ``callback.on_cancel()``: called with no parameters when the consumer is successfully cancelled. * ``callback.on_error(exc)``: called when the channel is closed due to an error. The argument passed is the exception which caused the error. This method is a :ref:`coroutine <coroutine>`. :param callable callback: a callback to be called when a message is delivered. The callback must accept a single argument (an instance of :class:`~asynqp.message.IncomingMessage`). :keyword bool no_local: If true, the server will not deliver messages that were published by this connection. :keyword bool no_ack: If true, messages delivered to the consumer don't require acknowledgement. :keyword bool exclusive: If true, only this consumer can access the queue. :keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`. :return: The newly created :class:`Consumer` object. """
if self.deleted: raise Deleted("Queue {} was deleted".format(self.name)) self.sender.send_BasicConsume(self.name, no_local, no_ack, exclusive, arguments or {}) tag = yield from self.synchroniser.wait(spec.BasicConsumeOK) consumer = Consumer( tag, callback, self.sender, self.synchroniser, self.reader, loop=self._loop) self.consumers.add_consumer(consumer) self.reader.ready() return consumer
<SYSTEM_TASK:> Synchronously get a message from the queue. <END_TASK> <USER_TASK:> Description: def get(self, *, no_ack=False): """ Synchronously get a message from the queue. This method is a :ref:`coroutine <coroutine>`. :keyword bool no_ack: if true, the broker does not require acknowledgement of receipt of the message. :return: an :class:`~asynqp.message.IncomingMessage`, or ``None`` if there were no messages on the queue. """
if self.deleted: raise Deleted("Queue {} was deleted".format(self.name)) self.sender.send_BasicGet(self.name, no_ack) tag_msg = yield from self.synchroniser.wait(spec.BasicGetOK, spec.BasicGetEmpty) if tag_msg is not None: consumer_tag, msg = tag_msg assert consumer_tag is None else: msg = None self.reader.ready() return msg
<SYSTEM_TASK:> Purge all undelivered messages from the queue. <END_TASK> <USER_TASK:> Description: def purge(self): """ Purge all undelivered messages from the queue. This method is a :ref:`coroutine <coroutine>`. """
self.sender.send_QueuePurge(self.name) yield from self.synchroniser.wait(spec.QueuePurgeOK) self.reader.ready()
<SYSTEM_TASK:> Delete the queue. <END_TASK> <USER_TASK:> Description: def delete(self, *, if_unused=True, if_empty=True): """ Delete the queue. This method is a :ref:`coroutine <coroutine>`. :keyword bool if_unused: If true, the queue will only be deleted if it has no consumers. :keyword bool if_empty: If true, the queue will only be deleted if it has no unacknowledged messages. """
if self.deleted: raise Deleted("Queue {} was already deleted".format(self.name)) self.sender.send_QueueDelete(self.name, if_unused, if_empty) yield from self.synchroniser.wait(spec.QueueDeleteOK) self.deleted = True self.reader.ready()
<SYSTEM_TASK:> Unbind the queue from the exchange. <END_TASK> <USER_TASK:> Description: def unbind(self, arguments=None): """ Unbind the queue from the exchange. This method is a :ref:`coroutine <coroutine>`. """
if self.deleted: raise Deleted("Queue {} was already unbound from exchange {}".format(self.queue.name, self.exchange.name)) self.sender.send_QueueUnbind(self.queue.name, self.exchange.name, self.routing_key, arguments or {}) yield from self.synchroniser.wait(spec.QueueUnbindOK) self.deleted = True self.reader.ready()
<SYSTEM_TASK:> Cancel the consumer and stop recieving messages. <END_TASK> <USER_TASK:> Description: def cancel(self): """ Cancel the consumer and stop recieving messages. This method is a :ref:`coroutine <coroutine>`. """
self.sender.send_BasicCancel(self.tag) try: yield from self.synchroniser.wait(spec.BasicCancelOK) except AMQPError: pass else: # No need to call ready if channel closed. self.reader.ready() self.cancelled = True self.cancelled_future.set_result(self) if hasattr(self.callback, 'on_cancel'): self.callback.on_cancel()
<SYSTEM_TASK:> Sends a 'hello world' message and then reads it from the queue. <END_TASK> <USER_TASK:> Description: def hello_world(): """ Sends a 'hello world' message and then reads it from the queue. """
# connect to the RabbitMQ broker connection = yield from asynqp.connect('localhost', 5672, username='guest', password='guest') # Open a communications channel channel = yield from connection.open_channel() # Create a queue and an exchange on the broker exchange = yield from channel.declare_exchange('test.exchange', 'direct') queue = yield from channel.declare_queue('test.queue') # Bind the queue to the exchange, so the queue will get messages published to the exchange yield from queue.bind(exchange, 'routing.key') # If you pass in a dict it will be automatically converted to JSON msg = asynqp.Message({'hello': 'world'}) exchange.publish(msg, 'routing.key') # Synchronously get a message from the queue received_message = yield from queue.get() print(received_message.json()) # get JSON from incoming messages easily # Acknowledge a delivered message received_message.ack() yield from channel.close() yield from connection.close()
<SYSTEM_TASK:> Connect to an AMQP server on the given host and port. <END_TASK> <USER_TASK:> Description: def connect(host='localhost', port=5672, username='guest', password='guest', virtual_host='/', on_connection_close=None, *, loop=None, sock=None, **kwargs): """ Connect to an AMQP server on the given host and port. Log in to the given virtual host using the supplied credentials. This function is a :ref:`coroutine <coroutine>`. :param str host: the host server to connect to. :param int port: the port which the AMQP server is listening on. :param str username: the username to authenticate with. :param str password: the password to authenticate with. :param str virtual_host: the AMQP virtual host to connect to. :param func on_connection_close: function called after connection lost. :keyword BaseEventLoop loop: An instance of :class:`~asyncio.BaseEventLoop` to use. (Defaults to :func:`asyncio.get_event_loop()`) :keyword socket sock: A :func:`~socket.socket` instance to use for the connection. This is passed on to :meth:`loop.create_connection() <asyncio.BaseEventLoop.create_connection>`. If ``sock`` is supplied then ``host`` and ``port`` will be ignored. Further keyword arguments are passed on to :meth:`loop.create_connection() <asyncio.BaseEventLoop.create_connection>`. This function will set TCP_NODELAY on TCP and TCP6 sockets either on supplied ``sock`` or created one. :return: the :class:`Connection` object. """
from .protocol import AMQP from .routing import Dispatcher from .connection import open_connection loop = asyncio.get_event_loop() if loop is None else loop if sock is None: kwargs['host'] = host kwargs['port'] = port else: kwargs['sock'] = sock dispatcher = Dispatcher() def protocol_factory(): return AMQP(dispatcher, loop, close_callback=on_connection_close) transport, protocol = yield from loop.create_connection(protocol_factory, **kwargs) # RPC-like applications require TCP_NODELAY in order to acheive # minimal response time. Actually, this library send data in one # big chunk and so this will not affect TCP-performance. sk = transport.get_extra_info('socket') # 1. Unfortunatelly we cannot check socket type (sk.type == socket.SOCK_STREAM). https://bugs.python.org/issue21327 # 2. Proto remains zero, if not specified at creation of socket if (sk.family in (socket.AF_INET, socket.AF_INET6)) and (sk.proto in (0, socket.IPPROTO_TCP)): sk.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) connection_info = { 'username': username, 'password': password, 'virtual_host': virtual_host } connection = yield from open_connection( loop, transport, protocol, dispatcher, connection_info) return connection
<SYSTEM_TASK:> Called by heartbeat_monitor on timeout <END_TASK> <USER_TASK:> Description: def heartbeat_timeout(self): """ Called by heartbeat_monitor on timeout """
assert not self._closed, "Did we not stop heartbeat_monitor on close?" log.error("Heartbeat time out") poison_exc = ConnectionLostError('Heartbeat timed out') poison_frame = frames.PoisonPillFrame(poison_exc) self.dispatcher.dispatch_all(poison_frame) # Spec says to just close socket without ConnectionClose handshake. self.close()
<SYSTEM_TASK:> Take a python object and convert it to the format Imgur expects. <END_TASK> <USER_TASK:> Description: def convert_general(value): """Take a python object and convert it to the format Imgur expects."""
if isinstance(value, bool): return "true" if value else "false" elif isinstance(value, list): value = [convert_general(item) for item in value] value = convert_to_imgur_list(value) elif isinstance(value, Integral): return str(value) elif 'pyimgur' in str(type(value)): return str(getattr(value, 'id', value)) return value
<SYSTEM_TASK:> Convert the parameters to the format Imgur expects. <END_TASK> <USER_TASK:> Description: def to_imgur_format(params): """Convert the parameters to the format Imgur expects."""
if params is None: return None return dict((k, convert_general(val)) for (k, val) in params.items())
<SYSTEM_TASK:> Handle a few expected values for rendering the current choice. <END_TASK> <USER_TASK:> Description: def render(self, name, value, attrs=None, *args, **kwargs): """Handle a few expected values for rendering the current choice. Extracts the state name from StateWrapper and State object. """
if isinstance(value, base.StateWrapper): state_name = value.state.name elif isinstance(value, base.State): state_name = value.name else: state_name = str(value) return super(StateSelect, self).render(name, state_name, attrs, *args, **kwargs)
<SYSTEM_TASK:> Contribute the state to a Model. <END_TASK> <USER_TASK:> Description: def contribute_to_class(self, cls, name): """Contribute the state to a Model. Attaches a StateFieldProperty to wrap the attribute. """
super(StateField, self).contribute_to_class(cls, name) parent_property = getattr(cls, self.name, None) setattr(cls, self.name, StateFieldProperty(self, parent_property))
<SYSTEM_TASK:> Converts the DB-stored value into a Python value. <END_TASK> <USER_TASK:> Description: def to_python(self, value): """Converts the DB-stored value into a Python value."""
if isinstance(value, base.StateWrapper): res = value else: if isinstance(value, base.State): state = value elif value is None: state = self.workflow.initial_state else: try: state = self.workflow.states[value] except KeyError: raise exceptions.ValidationError(self.error_messages['invalid']) res = base.StateWrapper(state, self.workflow) if res.state not in self.workflow.states: raise exceptions.ValidationError(self.error_messages['invalid']) return res
<SYSTEM_TASK:> Convert a value to DB storage. <END_TASK> <USER_TASK:> Description: def get_db_prep_value(self, value, connection, prepared=False): """Convert a value to DB storage. Returns the state name. """
if not prepared: value = self.get_prep_value(value) return value.state.name
<SYSTEM_TASK:> Convert a field value to a string. <END_TASK> <USER_TASK:> Description: def value_to_string(self, obj): """Convert a field value to a string. Returns the state name. """
statefield = self.to_python(self.value_from_object(obj)) return statefield.state.name
<SYSTEM_TASK:> Validate that a given value is a valid option for a given model instance. <END_TASK> <USER_TASK:> Description: def validate(self, value, model_instance): """Validate that a given value is a valid option for a given model instance. Args: value (xworkflows.base.StateWrapper): The base.StateWrapper returned by to_python. model_instance: A WorkflowEnabled instance """
if not isinstance(value, base.StateWrapper): raise exceptions.ValidationError(self.error_messages['wrong_type'] % value) elif not value.workflow == self.workflow: raise exceptions.ValidationError(self.error_messages['wrong_workflow'] % value.workflow) elif value.state not in self.workflow.states: raise exceptions.ValidationError(self.error_messages['invalid_state'] % value.state)
<SYSTEM_TASK:> Deconstruction for migrations. <END_TASK> <USER_TASK:> Description: def deconstruct(self): """Deconstruction for migrations. Return a simpler object (_SerializedWorkflow), since our Workflows are rather hard to serialize: Django doesn't like deconstructing metaclass-built classes. """
name, path, args, kwargs = super(StateField, self).deconstruct() # We want to display the proper class name, which isn't available # at the same point for _SerializedWorkflow and Workflow. if isinstance(self.workflow, _SerializedWorkflow): workflow_class_name = self.workflow._name else: workflow_class_name = self.workflow.__class__.__name__ kwargs['workflow'] = _SerializedWorkflow( name=workflow_class_name, initial_state=str(self.workflow.initial_state.name), states=[str(st.name) for st in self.workflow.states], ) del kwargs['choices'] del kwargs['default'] return name, path, args, kwargs
<SYSTEM_TASK:> Cache for fetching the actual log model object once django is loaded. <END_TASK> <USER_TASK:> Description: def _get_log_model_class(self): """Cache for fetching the actual log model object once django is loaded. Otherwise, import conflict occur: WorkflowEnabled imports <log_model> which tries to import all models to retrieve the proper model class. """
if self.log_model_class is not None: return self.log_model_class app_label, model_label = self.log_model.rsplit('.', 1) self.log_model_class = apps.get_model(app_label, model_label) return self.log_model_class
<SYSTEM_TASK:> Logs the transition into the database. <END_TASK> <USER_TASK:> Description: def db_log(self, transition, from_state, instance, *args, **kwargs): """Logs the transition into the database."""
if self.log_model: model_class = self._get_log_model_class() extras = {} for db_field, transition_arg, default in model_class.EXTRA_LOG_ATTRIBUTES: extras[db_field] = kwargs.get(transition_arg, default) return model_class.log_transition( modified_object=instance, transition=transition.name, from_state=from_state.name, to_state=transition.target.name, **extras)
<SYSTEM_TASK:> Cleanup README.rst for proper PyPI formatting. <END_TASK> <USER_TASK:> Description: def clean_readme(fname): """Cleanup README.rst for proper PyPI formatting."""
with codecs.open(fname, 'r', 'utf-8') as f: return ''.join( re.sub(r':\w+:`([^`]+?)( <[^<>]+>)?`', r'``\1``', line) for line in f if not (line.startswith('.. currentmodule') or line.startswith('.. toctree')) )
<SYSTEM_TASK:> Refresh this objects attributes to the newest values. <END_TASK> <USER_TASK:> Description: def refresh(self): """ Refresh this objects attributes to the newest values. Attributes that weren't added to the object before, due to lazy loading, will be added by calling refresh. """
resp = self._imgur._send_request(self._INFO_URL) self._populate(resp) self._has_fetched = True