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 accuracy(self, test_set, format=None): """Compute the accuracy on a test set. :param test_set: A list of tuples of the form ``(text, label)``, or a filename....
if isinstance(test_set, basestring): # test_set is a filename test_data = self._read_data(test_set) else: # test_set is a list of tuples test_data = test_set test_features = [(self.extract_features(d), c) for d, c in test_data] return nltk.classify.accuracy(sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update(self, new_data, *args, **kwargs): '''Update the classifier with new training data and re-trains the classifier. :param new_data: New data as a list of tuples of the form ``(text, label)``. ''' self.train_set += new_data self.train_features = [(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 train(self, *args, **kwargs): """Train the classifier with a labeled and unlabeled feature sets and return the classifier. Takes the same arguments as the wr...
self.classifier = self.nltk_class.train(self.positive_features, self.unlabeled_features, self.positive_prob_prior) return self.classifier
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update(self, new_positive_data=None, new_unlabeled_data=None, positive_prob_prior=0.5, *args, **kwargs): '''Update the classifier with new data and re-trains the classifier. :param new_positive_data: List of new, labeled strings. :param new_unlabeled_da...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def variations(iterable, optional=lambda x: False): """ Returns all possible variations of a sequence with optional items. """
# For example: variations(["A?", "B?", "C"], optional=lambda s: s.endswith("?")) # defines a sequence where constraint A and B are optional: # [("A?", "B?", "C"), ("B?", "C"), ("A?", "C"), ("C")] iterable = tuple(iterable) # Create a boolean sequence where True means optional: # ("A?", "B?", "C...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parents(self, term, recursive=False, **kwargs): """ Returns a list of all semantic types for the given term. If recursive=True, traverses parents up to the r...
def dfs(term, recursive=False, visited={}, **kwargs): if term in visited: # Break on cyclic relations. return [] visited[term], a = True, [] if dict.__contains__(self, term): a = self[term][0].keys() for classifier in self.classifi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constraint(self, word): """ Returns the constraint that matches the given Word, or None. """
if word.index in self._map1: return self._map1[word.index]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constraints(self, chunk): """ Returns a list of constraints that match the given Chunk. """
a = [self._map1[w.index] for w in chunk.words if w.index in self._map1] b = []; [b.append(constraint) for constraint in a if constraint not in b] return b
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tree(s, token=[WORD, POS, CHUNK, PNP, REL, LEMMA]): """ Returns a parsed Text from the given parsed string. """
return Text(s, token)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def word_tokenize(text, tokenizer=None, include_punc=True, *args, **kwargs): """Convenience function for tokenizing text into words. NOTE: NLTK's word tokenizer ...
_tokenizer = tokenizer if tokenizer is not None else NLTKPunktTokenizer() words = chain.from_iterable( WordTokenizer(tokenizer=_tokenizer).itokenize(sentence, include_punc, *args, **kwargs) for sentence in sent_tokenize(text, tokenizer=_toke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def word_tokenize(self, text, include_punc=True): """The Treebank tokenizer uses regular expressions to tokenize text as in Penn Treebank. It assumes that the te...
#: Do not process empty strings (Issue #3) if text.strip() == "": return [] _tokens = self.word_tok.tokenize(text) #: Handle strings consisting of a single punctuation mark seperately (Issue #4) if len(_tokens) == 1: if _tokens[0] in PUNCTUATION: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sent_tokenize(self, text, **kwargs): """Returns a list of sentences. Each sentence is a space-separated string of tokens (words). Punctuation marks are split...
sentences = find_sentences(text, punctuation=kwargs.get( "punctuation", PUNCTUATION), abbreviations=kwargs.get( "abbreviati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, text): """Parses the text. ``pattern.de.parse(**kwargs)`` can be passed to the parser instance and are documented in the main docstring of :class...
#: Do not process empty strings (Issue #3) if text.strip() == "": return "" #: Do not process strings consisting of a single punctuation mark (Issue #4) elif text.strip() in PUNCTUATION: _sym = text.strip() if _sym in tuple('.?!'): _ta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _filter_extracted(self, extracted_list): """Filter insignificant words for key noun phrase extraction. determiners, relative pronouns, reflexive pronouns In ...
_filtered = [] for np in extracted_list: _np = np.split() if _np[0] in INSIGNIFICANT: _np.pop(0) try: if _np[-1] in INSIGNIFICANT: _np.pop(-1) # e.g. 'welcher die ...' if _np[0] in IN...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tag(self, sentence, tokenize=True): """Tag a string `sentence`. :param str or list sentence: A string or a list of sentence strings. :param tokenize: (option...
#: Do not process empty strings (Issue #3) if sentence.strip() == "": return [] #: Do not process strings consisting of a single punctuation mark (Issue #4) elif sentence.strip() in PUNCTUATION: if self.include_punc: _sym = sentence.strip() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the P...
# Check that a given file can be accessed with the correct mode. # Additionally check that `file` is not a directory, as on Windows # directories pass the os.access check. def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate(self, from_lang=None, to="de"): """Translate the word to another language using Google's Translate API. .. versionadded:: 0.5.0 (``textblob``) """
if from_lang is None: from_lang = self.translator.detect(self.string) return self.translator.translate(self.string, from_lang=from_lang, to_lang=to)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lemmatize(self): """Return the lemma of each word in this WordList. Currently using NLTKPunktTokenizer() for all lemmatization tasks. This might cause slight...
_lemmatizer = PatternParserLemmatizer(tokenizer=NLTKPunktTokenizer()) # WordList object --> Sentence.string # add a period (improves parser accuracy) _raw = " ".join(self) + "." _lemmas = _lemmatizer.lemmatize(_raw) return self.__class__([Word(l, t) for l, t in _lemmas])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize(self, tokenizer=None): """Return a list of tokens, using ``tokenizer``. :param tokenizer: (optional) A tokenizer object. If None, defaults to this b...
t = tokenizer if tokenizer is not None else self.tokenizer return WordList(t.tokenize(self.raw))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def noun_phrases(self): """Returns a list of noun phrases for this blob."""
return WordList([phrase.strip() for phrase in self.np_extractor.extract(self.raw) if len(phrase.split()) > 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 words(self): """Return a list of word tokens. This excludes punctuation characters. If you want to include punctuation characters, access the ``tokens`` prop...
return WordList( word_tokenize(self.raw, self.tokenizer, include_punc=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 _read(path, encoding="utf-8", comment=";;;"): """ Returns an iterator over the lines in the file at the given path, strippping comments and decoding each lin...
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): # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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", "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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], [...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 det...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _do_anchor(self, anchor): """ Collects preposition anchors and attachments in a dictionary. Once the dictionary has an entry for both the anchor and the atta...
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....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _do_conjunction(self, _and=("and", "e", "en", "et", "und", "y")): """ Attach conjunctions. CC-words like "and" and "or" between two chunks indicate a conjunc...
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.app...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 cust...
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[inde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
<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_xml(cls, xml): """ Returns a new Text from the given XML string. """
s = parse_string(xml) return Sentence(s.split("\n")[0], token=s.tags, language=s.language)
<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_credits(): """Extract credits from `AUTHORS.rst`"""
credits = read(os.path.join(_HERE, "AUTHORS.rst")).split("\n") from_index = credits.index("Active Contributors") credits = "\n".join(credits[from_index + 2:]) return credits
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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_kwa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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(s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _solve_scipy(self, intern_x0, tol=1e-8, method=None, **kwargs): """ Uses ``scipy.optimize.root`` See: http://docs.scipy.org/doc/scipy/reference/generated/sci...
from scipy.optimize import root if method is None: if self.nf > self.nx: method = 'lm' elif self.nf == self.nx: method = 'hybr' else: raise ValueError('Underdetermined problem') if 'band' in kwargs: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(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 SymP...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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')...
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: label...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 symb...
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 ...
<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_callback(cls, cb, nx=None, nparams=None, **kwargs): """ Generate a SymbolicSys instance from a callback. Parameters cb : callable Should have the signat...
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...
<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_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( ...
<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_callback(cls, cb, transf_cbs, nx, nparams=0, pre_adj=None, **kwargs): """ Generate a TransformedSys instance from a callback Parameters cb : callable Sh...
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def write(self, handle): '''Write binary header data to a file handle. This method writes exactly 512 bytes to the beginning of the given file handle. Parameters ---------- handle : file handle The given handle will be reset to 0 using `seek` and then 512 by...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def read(self, handle): '''Read and parse binary header data from a file handle. This method reads exactly 512 bytes from the beginning of the given file handle. Parameters ---------- handle : file handle The given handle will be reset to 0 using `seek` and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def binary_size(self): '''Return the number of bytes needed to store this parameter.''' return ( 1 + # group_id 2 + # next offset marker 1 + len(self.name.encode('utf-8')) + # size of name and name bytes 1 + # data size 1 + len(self.dimensions)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def write(self, group_id, handle): '''Write binary data for this parameter to a file handle. Parameters ---------- group_id : int The numerical ID of the group that holds this parameter. handle : file handle An open, writable, binary file handle. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def read(self, handle): '''Read binary data for this parameter from a file handle. This reads exactly enough data from the current position in the file to initialize the parameter. ''' self.bytes_per_element, = struct.unpack('b', handle.read(1)) dims, = struct.unpack('B'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _as_array(self, fmt): '''Unpack the raw bytes of this param using the given data format.''' assert self.dimensions, \ '{}: cannot get value as {} array!'.format(self.name, fmt) elems = array.array(fmt) elems.fromstring(self.bytes) return np.array(elems).reshape(se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bytes_array(self): '''Get the param as an array of raw byte strings.''' assert len(self.dimensions) == 2, \ '{}: cannot get value as bytes array!'.format(self.name) l, n = self.dimensions return [self.bytes[i*l:(i+1)*l] for i in range(n)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def string_array(self): '''Get the param as a array of unicode strings.''' assert len(self.dimensions) == 2, \ '{}: cannot get value as string array!'.format(self.name) l, n = self.dimensions return [self.bytes[i*l:(i+1)*l].decode('utf-8') for i in range(n)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_param(self, name, **kwargs): '''Add a parameter to this group. Parameters ---------- name : str Name of the parameter to add to this group. The name will automatically be case-normalized. Additional keyword arguments will be passed to the `Param`...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def binary_size(self): '''Return the number of bytes to store this group and its parameters.''' return ( 1 + # group_id 1 + len(self.name.encode('utf-8')) + # size of name and name bytes 2 + # next offset marker 1 + len(self.desc.encode('utf-8')) + # size ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def write(self, group_id, handle): '''Write this parameter group, with parameters, to a file handle. Parameters ---------- group_id : int The numerical ID of the group. handle : file handle An open, writable, binary file handle. ''' name =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check_metadata(self): '''Ensure that the metadata in our file is self-consistent.''' assert self.header.point_count == self.point_used, ( 'inconsistent point count! {} header != {} POINT:USED'.format( self.header.point_count, self.point_used, )...
<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_group(self, group_id, name, desc): '''Add a new parameter group. Parameters ---------- group_id : int The numeric ID for a group to check or create. name : str, optional If a group is created, assign this name to the group. desc : str, opt...
<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, group, default=None): '''Get a group or parameter. Parameters ---------- group : str If this string contains a period (.), then the part before the period will be used to retrieve a group, and the part after the period will be used to 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 _pad_block(self, handle): '''Pad the file with 0s to the end of the next block boundary.''' extra = handle.tell() % 512 if extra: handle.write(b'\x00' * (512 - extra))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _write_metadata(self, handle): '''Write metadata to a file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle. ''' self.check_metadata() # he...
<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_frames(self, handle): '''Write our frame data to the given file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle. ''' assert handle.tell() ==...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 = PLAC...
<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_plugin(cls, name=None, **kwargs): """Returns the first format plugin whose attributes match kwargs. For example:: get_plugin(extension="scratch14") Will ...
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.val...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_he...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_obj_table(table_entries, plugin): """Return root of obj table. Converts user-class objects"""
entries = [] for entry in table_entries: if isinstance(entry, Container): assert not hasattr(entry, '__recursion_lock__') user_obj_def = plugin.user_objects[entry.classID] assert entry.version == user_obj_def.version entry = Container(class_name=entry.cla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_obj_table(root, plugin): """Return list of obj table entries. Converts user-class objects"""
entries = encode_network(root) table_entries = [] for entry in entries: if isinstance(entry, Container): assert not hasattr(entry, '__recursion_lock__') user_obj_def = plugin.user_objects[entry.class_name] attrs = OrderedDict() for (key, default) in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 t...
func = getattr(obj, 'to_construct', None) if callable(func): return func(context) else: return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_file(self, name, contents): """Write file contents string into archive."""
# TODO: find a way to make ZipFile accept a file object. zi = zipfile.ZipInfo(name) zi.date_time = time.localtime(time.time())[:6] zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = 0777 << 16L self.zip_file.writestr(zi, contents)
<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_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 = h...
<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_file_path(self, path): """Update the file_path Entry widget"""
self.file_path.delete(0, END) self.file_path.insert(0, path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 form...
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 ...
<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(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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert(self, format): """Convert the project in-place to a different file format. Returns a list of :class:`UnsupportedFeature` objects, which may give warn...
self._plugin = kurt.plugin.Kurt.get_plugin(format) return list(self._normalize())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(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...
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) ...
<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(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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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.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 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _strip_text(text): """Returns text with spaces and inserts removed."""
text = re.sub(r'[ ,?:]|%s', "", text.lower()) for chr in "-%": new_text = text.replace(chr, "") if new_text: text = new_text return text.lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_conversion(self, plugin, pbt): """Add a new PluginBlockType conversion. If the plugin already exists, do nothing. """
assert self.shape == pbt.shape assert len(self.inserts) == len(pbt.inserts) for (i, o) in zip(self.inserts, pbt.inserts): assert i.shape == o.shape assert i.kind == o.kind assert i.unevaluated == o.unevaluated if plugin not in self._plugins: ...