notice_types = NoticeType.objects.all()<EOL>settings_table = []<EOL>for notice_type in notice_types:<EOL><INDENT>settings_row = []<EOL>for medium_id, medium_display in NOTICE_MEDIA:<EOL><INDENT>form_label = "<STR_LIT>" % (notice_type.label, medium_id)<EOL>setting = NoticeSetting.for_user(request.user, notice_type, medium_id)<EOL>if request.method == "<STR_LIT:POST>":<EOL><INDENT>if request.POST.get(form_label) == "<STR_LIT>":<EOL><INDENT>if not setting.send:<EOL><INDENT>setting.send = True<EOL>setting.save()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if setting.send:<EOL><INDENT>setting.send = False<EOL>setting.save()<EOL><DEDENT><DEDENT><DEDENT>settings_row.append((form_label, setting.send))<EOL><DEDENT>settings_table.append({"<STR_LIT>": notice_type, "<STR_LIT>": settings_row})<EOL><DEDENT>if request.method == "<STR_LIT:POST>":<EOL><INDENT>next_page = request.POST.get("<STR_LIT>", "<STR_LIT:.>")<EOL>return HttpResponseRedirect(next_page)<EOL><DEDENT>settings = {<EOL>"<STR_LIT>": [medium_display for medium_id, medium_display in NOTICE_MEDIA],<EOL>"<STR_LIT>": settings_table,<EOL>}<EOL>return render_to_response("<STR_LIT>", {<EOL>"<STR_LIT>": notice_types,<EOL>"<STR_LIT>": settings,<EOL>}, context_instance=RequestContext(request))<EOL>

The notice settings view.

Template: :template:`notification/notice_settings.html`

Context:

    notice_types
        A list of all :model:`notification.NoticeType` objects.

    notice_settings
        A dictionary containing ``column_headers`` for each ``NOTICE_MEDIA``
        and ``rows`` containing a list of dictionaries: ``notice_type``, a
        :model:`notification.NoticeType` object and ``cells``, a list of
        tuples whose first value is suitable for use in forms and the second
        value is ``True`` or ``False`` depending on a ``request.POST``
        variable called ``form_label``, whose valid value is ``on``.


from notification.models import NoticeSetting<EOL>return NoticeSetting.for_user(user, notice_type, self.medium_id).send<EOL>

Determines whether this backend is allowed to send a notification to
the given user and notice_type.


def deliver(self, recipient, sender, notice_type, extra_context):

raise NotImplementedError()<EOL>

Deliver a notification to the given recipient.


def get_formatted_messages(self, formats, label, context):

format_templates = {}<EOL>for fmt in formats:<EOL><INDENT>if fmt.endswith("<STR_LIT>"):<EOL><INDENT>context.autoescape = False<EOL><DEDENT>format_templates[fmt] = render_to_string((<EOL>"<STR_LIT>" % (label, fmt),<EOL>"<STR_LIT>" % fmt), context_instance=context)<EOL><DEDENT>return format_templates<EOL>

Returns a dictionary with the format identifier as the key. The values are
are fully rendered templates with the given context.


def __init__(self, path, threaded=True):

self.path = path<EOL>self.lock_file = os.path.abspath(path) + "<STR_LIT>"<EOL>self.hostname = socket.gethostname()<EOL>self.pid = os.getpid()<EOL>if threaded:<EOL><INDENT>name = threading.current_thread().get_name()<EOL>tname = "<STR_LIT>" % quote(name, safe="<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>tname = "<STR_LIT>"<EOL><DEDENT>dirname = os.path.dirname(self.lock_file)<EOL>self.unique_name = os.path.join(dirname,<EOL>"<STR_LIT>" % (self.hostname,<EOL>tname,<EOL>self.pid))<EOL>

>>> lock = LockBase("somefile")
>>> lock = LockBase("somefile", threaded=False)


raise NotImplementedError("<STR_LIT>")<EOL>

Acquire the lock.

* If timeout is omitted (or None), wait forever trying to lock the
  file.

* If timeout > 0, try to acquire the lock for that many seconds.  If
  the lock period expires and the file is still locked, raise
  LockTimeout.

* If timeout <= 0, raise AlreadyLocked immediately if the file is
  already locked.


Release the lock.

If the file is not locked, raise NotLocked.


Return True if this object is locking the file.


Remove a lock.  Useful if a locking thread failed to unlock.


self.acquire()<EOL>return self<EOL>


self.release()<EOL>


LockBase.__init__(self, path, threaded)<EOL>if threaded:<EOL><INDENT>tname = "<STR_LIT>" % get_ident()<EOL><DEDENT>else:<EOL><INDENT>tname = "<STR_LIT>"<EOL><DEDENT>self.unique_name = os.path.join(<EOL>self.lock_file,<EOL>"<STR_LIT>".format(self.hostname, tname, self.pid)<EOL>)<EOL>

>>> lock = MkdirFileLock("somefile")
>>> lock = MkdirFileLock("somefile", threaded=False)


if getattr(settings, "<STR_LIT>", False):<EOL><INDENT>try:<EOL><INDENT>app_label, model_name = settings.NOTIFICATION_LANGUAGE_MODULE.split("<STR_LIT:.>")<EOL>model = models.get_model(app_label, model_name)<EOL>language_model = model._default_manager.get(user__id__exact=user.id)<EOL>if hasattr(language_model, "<STR_LIT>"):<EOL><INDENT>return language_model.language<EOL><DEDENT><DEDENT>except (ImportError, ImproperlyConfigured, model.DoesNotExist):<EOL><INDENT>raise LanguageStoreNotAvailable<EOL><DEDENT><DEDENT>raise LanguageStoreNotAvailable<EOL>

Returns site-specific notification language for this user. Raises
LanguageStoreNotAvailable if this site does not use translated
notifications.


def send_now(users, label, extra_context=None, sender=None):

sent = False<EOL>if extra_context is None:<EOL><INDENT>extra_context = {}<EOL><DEDENT>notice_type = NoticeType.objects.get(label=label)<EOL>current_language = get_language()<EOL>for user in users:<EOL><INDENT>try:<EOL><INDENT>language = get_notification_language(user)<EOL><DEDENT>except LanguageStoreNotAvailable:<EOL><INDENT>language = None<EOL><DEDENT>if language is not None:<EOL><INDENT>activate(language)<EOL><DEDENT>for backend in NOTIFICATION_BACKENDS.values():<EOL><INDENT>if backend.can_send(user, notice_type):<EOL><INDENT>backend.deliver(user, sender, notice_type, extra_context)<EOL>sent = True<EOL><DEDENT><DEDENT><DEDENT>activate(current_language)<EOL>return sent<EOL>

Creates a new notice.

This is intended to be how other apps create new notices.

notification.send(user, "friends_invite_sent", {
    "spam": "eggs",
    "foo": "bar",
)


queue_flag = kwargs.pop("<STR_LIT>", False)<EOL>now_flag = kwargs.pop("<STR_LIT>", False)<EOL>assert not (queue_flag and now_flag), "<STR_LIT>"<EOL>if queue_flag:<EOL><INDENT>return queue(*args, **kwargs)<EOL><DEDENT>elif now_flag:<EOL><INDENT>return send_now(*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>if QUEUE_ALL:<EOL><INDENT>return queue(*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>return send_now(*args, **kwargs)<EOL><DEDENT><DEDENT>

A basic interface around both queue and send_now. This honors a global
flag NOTIFICATION_QUEUE_ALL that helps determine whether all calls should
be queued or not. A per call ``queue`` or ``now`` keyword argument can be
used to always override the default global behavior.


def queue(users, label, extra_context=None, sender=None):

if extra_context is None:<EOL><INDENT>extra_context = {}<EOL><DEDENT>if isinstance(users, QuerySet):<EOL><INDENT>users = [row["<STR_LIT>"] for row in users.values("<STR_LIT>")]<EOL><DEDENT>else:<EOL><INDENT>users = [user.pk for user in users]<EOL><DEDENT>notices = []<EOL>for user in users:<EOL><INDENT>notices.append((user, label, extra_context, sender))<EOL><DEDENT>NoticeQueueBatch(pickled_data=base64.b64encode(pickle.dumps(notices))).save()<EOL>

Queue the notification in NoticeQueueBatch. This allows for large amounts
of user notifications to be deferred to a seperate process running outside
the webserver.


@classmethod<EOL><INDENT>def create(cls, label, display, description, default=<NUM_LIT:2>, verbosity=<NUM_LIT:1>):<DEDENT>

try:<EOL><INDENT>notice_type = cls._default_manager.get(label=label)<EOL>updated = False<EOL>if display != notice_type.display:<EOL><INDENT>notice_type.display = display<EOL>updated = True<EOL><DEDENT>if description != notice_type.description:<EOL><INDENT>notice_type.description = description<EOL>updated = True<EOL><DEDENT>if default != notice_type.default:<EOL><INDENT>notice_type.default = default<EOL>updated = True<EOL><DEDENT>if updated:<EOL><INDENT>notice_type.save()<EOL>if verbosity > <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>" % label)<EOL><DEDENT><DEDENT><DEDENT>except cls.DoesNotExist:<EOL><INDENT>cls(label=label, display=display, description=description, default=default).save()<EOL>if verbosity > <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>" % label)<EOL><DEDENT><DEDENT>

Creates a new NoticeType.

This is intended to be used by other apps as a post_syncdb manangement step.


@not_implemented_for('<STR_LIT>')<EOL>def divrank(G, alpha=<NUM_LIT>, d=<NUM_LIT>, personalization=None,<EOL>max_iter=<NUM_LIT:100>, tol=<NUM_LIT>, nstart=None, weight='<STR_LIT>',<EOL>dangling=None):

if len(G) == <NUM_LIT:0>:<EOL><INDENT>return {}<EOL><DEDENT>if not G.is_directed():<EOL><INDENT>D = G.to_directed()<EOL><DEDENT>else:<EOL><INDENT>D = G<EOL><DEDENT>W = nx.stochastic_graph(D, weight=weight)<EOL>N = W.number_of_nodes()<EOL>for n in W.nodes_iter():<EOL><INDENT>for n_ in W.nodes_iter():<EOL><INDENT>if n != n_ :<EOL><INDENT>if n_ in W[n]:<EOL><INDENT>W[n][n_][weight] *= alpha<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if n_ not in W[n]:<EOL><INDENT>W.add_edge(n, n_)<EOL><DEDENT>W[n][n_][weight] = <NUM_LIT:1.0> - alpha<EOL><DEDENT><DEDENT><DEDENT>if nstart is None:<EOL><INDENT>x = dict.fromkeys(W, <NUM_LIT:1.0> / N)<EOL><DEDENT>else:<EOL><INDENT>s = float(sum(nstart.values()))<EOL>x = dict((k, v / s) for k, v in list(nstart.items()))<EOL><DEDENT>if personalization is None:<EOL><INDENT>p = dict.fromkeys(W, <NUM_LIT:1.0> / N)<EOL><DEDENT>else:<EOL><INDENT>missing = set(G) - set(personalization)<EOL>if missing:<EOL><INDENT>raise NetworkXError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % missing)<EOL><DEDENT>s = float(sum(personalization.values()))<EOL>p = dict((k, v / s) for k, v in list(personalization.items()))<EOL><DEDENT>if dangling is None:<EOL><INDENT>dangling_weights = p<EOL><DEDENT>else:<EOL><INDENT>missing = set(G) - set(dangling)<EOL>if missing:<EOL><INDENT>raise NetworkXError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % missing)<EOL><DEDENT>s = float(sum(dangling.values()))<EOL>dangling_weights = dict((k, v/s) for k, v in list(dangling.items()))<EOL><DEDENT>dangling_nodes = [n for n in W if W.out_degree(n, weight=weight) == <NUM_LIT:0.0>]<EOL>for _ in range(max_iter):<EOL><INDENT>xlast = x<EOL>x = dict.fromkeys(list(xlast.keys()), <NUM_LIT:0>)<EOL>danglesum = d * sum(xlast[n] for n in dangling_nodes)<EOL>for n in x:<EOL><INDENT>D_t = sum(W[n][nbr][weight] * xlast[nbr] for nbr in W[n])<EOL>for nbr in W[n]:<EOL><INDENT>x[nbr] += (<EOL>d * (W[n][nbr][weight] * xlast[nbr] / D_t) * xlast[n]<EOL>)<EOL><DEDENT>x[n] += danglesum * dangling_weights[n] + (<NUM_LIT:1.0> - d) * p[n]<EOL><DEDENT>err = sum([abs(x[n] - xlast[n]) for n in x])<EOL>if err < N*tol:<EOL><INDENT>return x<EOL><DEDENT><DEDENT>raise NetworkXError('<STR_LIT>'<EOL>'<STR_LIT>' % max_iter)<EOL>

Returns the DivRank (Diverse Rank) of the nodes in the graph.
This code is based on networkx.pagerank.

Args: (diff from pagerank)
  alpha: controls strength of self-link [0.0-1.0]
  d: the damping factor

Reference:
  Qiaozhu Mei and Jian Guo and Dragomir Radev,
  DivRank: the Interplay of Prestige and Diversity in Information Networks,
  http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.174.7982


def divrank_scipy(G, alpha=<NUM_LIT>, d=<NUM_LIT>, personalization=None,<EOL>max_iter=<NUM_LIT:100>, tol=<NUM_LIT>, nstart=None, weight='<STR_LIT>',<EOL>dangling=None):

import scipy.sparse<EOL>N = len(G)<EOL>if N == <NUM_LIT:0>:<EOL><INDENT>return {}<EOL><DEDENT>nodelist = G.nodes()<EOL>M = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight,<EOL>dtype=float)<EOL>S = scipy.array(M.sum(axis=<NUM_LIT:1>)).flatten()<EOL>S[S != <NUM_LIT:0>] = <NUM_LIT:1.0> / S[S != <NUM_LIT:0>]<EOL>Q = scipy.sparse.spdiags(S.T, <NUM_LIT:0>, *M.shape, format='<STR_LIT>')<EOL>M = Q * M<EOL>M = scipy.sparse.lil_matrix(M)<EOL>M.setdiag(<NUM_LIT:0.0>)<EOL>M = alpha * M<EOL>M.setdiag(<NUM_LIT:1.0> - alpha)<EOL>x = scipy.repeat(<NUM_LIT:1.0> / N, N)<EOL>if personalization is None:<EOL><INDENT>p = scipy.repeat(<NUM_LIT:1.0> / N, N)<EOL><DEDENT>else:<EOL><INDENT>missing = set(nodelist) - set(personalization)<EOL>if missing:<EOL><INDENT>raise NetworkXError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % missing)<EOL><DEDENT>p = scipy.array([personalization[n] for n in nodelist],<EOL>dtype=float)<EOL>p = p / p.sum()<EOL><DEDENT>if dangling is None:<EOL><INDENT>dangling_weights = p<EOL><DEDENT>else:<EOL><INDENT>missing = set(nodelist) - set(dangling)<EOL>if missing:<EOL><INDENT>raise NetworkXError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % missing)<EOL><DEDENT>dangling_weights = scipy.array([dangling[n] for n in nodelist],<EOL>dtype=float)<EOL>dangling_weights /= dangling_weights.sum()<EOL><DEDENT>is_dangling = scipy.where(S == <NUM_LIT:0>)[<NUM_LIT:0>]<EOL>for _ in range(max_iter):<EOL><INDENT>xlast = x<EOL>D_t =  M * x<EOL>x = (<EOL>d * (x / D_t * M * x + sum(x[is_dangling]) * dangling_weights)<EOL>+ (<NUM_LIT:1.0> - d) * p<EOL>)<EOL>err = scipy.absolute(x - xlast).sum()<EOL>if err < N * tol:<EOL><INDENT>return dict(list(zip(nodelist, list(map(float, x)))))<EOL><DEDENT><DEDENT>raise NetworkXError('<STR_LIT>'<EOL>'<STR_LIT>' % max_iter)<EOL>

Returns the DivRank (Diverse Rank) of the nodes in the graph.
This code is based on networkx.pagerank_scipy


def lexrank(sentences, continuous=False, sim_threshold=<NUM_LIT:0.1>, alpha=<NUM_LIT>,<EOL>use_divrank=False, divrank_alpha=<NUM_LIT>):

<EOL>ranker_params = {'<STR_LIT>': <NUM_LIT:1000>}<EOL>if use_divrank:<EOL><INDENT>ranker = divrank_scipy<EOL>ranker_params['<STR_LIT>'] = divrank_alpha<EOL>ranker_params['<STR_LIT:d>'] = alpha<EOL><DEDENT>else:<EOL><INDENT>ranker = networkx.pagerank_scipy<EOL>ranker_params['<STR_LIT>'] = alpha<EOL><DEDENT>graph = networkx.DiGraph()<EOL>sent_tf_list = []<EOL>for sent in sentences:<EOL><INDENT>words = tools.word_segmenter_ja(sent)<EOL>tf = collections.Counter(words)<EOL>sent_tf_list.append(tf)<EOL><DEDENT>sent_vectorizer = DictVectorizer(sparse=True)<EOL>sent_vecs = sent_vectorizer.fit_transform(sent_tf_list)<EOL>sim_mat = <NUM_LIT:1> - pairwise_distances(sent_vecs, sent_vecs, metric='<STR_LIT>')<EOL>if continuous:<EOL><INDENT>linked_rows, linked_cols = numpy.where(sim_mat > <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>linked_rows, linked_cols = numpy.where(sim_mat >= sim_threshold)<EOL><DEDENT>graph.add_nodes_from(list(range(sent_vecs.shape[<NUM_LIT:0>])))<EOL>for i, j in zip(linked_rows, linked_cols):<EOL><INDENT>if i == j:<EOL><INDENT>continue<EOL><DEDENT>weight = sim_mat[i,j] if continuous else <NUM_LIT:1.0><EOL>graph.add_edge(i, j, {'<STR_LIT>': weight})<EOL><DEDENT>scores = ranker(graph, **ranker_params)<EOL>return scores, sim_mat<EOL>

compute centrality score of sentences.

Args:
  sentences: [u'こんにちは．', u'私の名前は飯沼です．', ... ]
  continuous: if True, apply continuous LexRank. (see reference)
  sim_threshold: if continuous is False and smilarity is greater or
    equal to sim_threshold, link the sentences.
  alpha: the damping factor of PageRank and DivRank
  divrank: if True, apply DivRank instead of PageRank
  divrank_alpha: strength of self-link [0.0-1.0]
    (it's not the damping factor, see divrank.py)

Returns: tuple
  (
    {
      # sentence index -> score
      0: 0.003,
      1: 0.002,
      ...
    },
    similarity_matrix
  )

Reference:
  Günes Erkan and Dragomir R. Radev.
  LexRank: graph-based lexical centrality as salience in text
  summarization. (section 3)
  http://www.cs.cmu.edu/afs/cs/project/jair/pub/volume22/erkan04a-html/erkan04a.html


def summarize(text, sent_limit=None, char_limit=None, imp_require=None,<EOL>debug=False, **lexrank_params):

debug_info = {}<EOL>sentences = list(tools.sent_splitter_ja(text))<EOL>scores, sim_mat = lexrank(sentences, **lexrank_params)<EOL>sum_scores = sum(scores.values())<EOL>acc_scores = <NUM_LIT:0.0><EOL>indexes = set()<EOL>num_sent, num_char = <NUM_LIT:0>, <NUM_LIT:0><EOL>for i in sorted(scores, key=lambda i: scores[i], reverse=True):<EOL><INDENT>num_sent += <NUM_LIT:1><EOL>num_char += len(sentences[i])<EOL>if sent_limit is not None and num_sent > sent_limit:<EOL><INDENT>break<EOL><DEDENT>if char_limit is not None and num_char > char_limit:<EOL><INDENT>break<EOL><DEDENT>if imp_require is not None and acc_scores / sum_scores >= imp_require:<EOL><INDENT>break<EOL><DEDENT>indexes.add(i)<EOL>acc_scores += scores[i]<EOL><DEDENT>if len(indexes) > <NUM_LIT:0>:<EOL><INDENT>summary_sents = [sentences[i] for i in sorted(indexes)]<EOL><DEDENT>else:<EOL><INDENT>summary_sents = sentences<EOL><DEDENT>if debug:<EOL><INDENT>debug_info.update({<EOL>'<STR_LIT>': sentences, '<STR_LIT>': scores<EOL>})<EOL><DEDENT>return summary_sents, debug_info<EOL>

Args:
  text: text to be summarized (unicode string)
  sent_limit: summary length (the number of sentences)
  char_limit: summary length (the number of characters)
  imp_require: cumulative LexRank score [0.0-1.0]

Returns:
  list of extracted sentences


if name in self.summarizers:<EOL><INDENT>pass<EOL><DEDENT>elif name == '<STR_LIT>':<EOL><INDENT>from . import lexrank<EOL>self.summarizers[name] = lexrank.summarize<EOL><DEDENT>elif name == '<STR_LIT>':<EOL><INDENT>from . import mcp_summ<EOL>self.summarizers[name] = mcp_summ.summarize<EOL><DEDENT>return self.summarizers[name]<EOL>


@cherrypy.expose<EOL><INDENT>def summarize(self, text=None, algo='<STR_LIT>', **summarizer_params):<DEDENT>

try:  <EOL><INDENT>for param, value in list(summarizer_params.items()):<EOL><INDENT>if value == '<STR_LIT>':<EOL><INDENT>del summarizer_params[param]<EOL>continue<EOL><DEDENT>elif re.match(r'<STR_LIT>', value):<EOL><INDENT>value = float(value)<EOL><DEDENT>elif re.match(r'<STR_LIT>', value):<EOL><INDENT>value = int(value)<EOL><DEDENT>elif value == '<STR_LIT:true>':<EOL><INDENT>value = True<EOL><DEDENT>elif value == '<STR_LIT:false>':<EOL><INDENT>value = False<EOL><DEDENT>summarizer_params[param] = value<EOL><DEDENT>if algo in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>summarizer = self.get_summarizer('<STR_LIT>')<EOL>if algo == '<STR_LIT>':<EOL><INDENT>summarizer_params['<STR_LIT>'] = True<EOL><DEDENT>if algo == '<STR_LIT>':<EOL><INDENT>summarizer_params['<STR_LIT>'] = True<EOL><DEDENT><DEDENT>elif algo == '<STR_LIT>':<EOL><INDENT>summarizer = self.get_summarizer('<STR_LIT>')<EOL><DEDENT>summary, debug_info = summarizer(text, **summarizer_params)<EOL><DEDENT>except Exception as e:<EOL><INDENT>return json.dumps({'<STR_LIT:error>': str(e)}, ensure_ascii=False, indent=<NUM_LIT:2>)<EOL><DEDENT>else:<EOL><INDENT>res = json.dumps(<EOL>tools.tree_encode({<EOL>'<STR_LIT>': summary, '<STR_LIT>': debug_info<EOL>}),<EOL>ensure_ascii=False, indent=<NUM_LIT:2><EOL>)<EOL>return res<EOL><DEDENT>

Args:
  text: text to be summarized
  algo: summarizaion algorithm
      - 'lexrank' (default) graph-based
      - 'clexrank' Continuous LexRank
      - 'divrank' DivRank (Diverse Rank)
      - 'mcp' select sentences in terms of maximum coverage problem

  summarizer_params examples:
    char_limit: summary length (the number of characters)
    sent_limit: (not supported with mcp)
      summary length (the number of sentences)
    imp_require: (lexrank only)
      cumulative LexRank score [0.0-1.0]


paren_chars = set(parenthesis)<EOL>close2open = dict(zip(parenthesis[<NUM_LIT:1>::<NUM_LIT:2>], parenthesis[<NUM_LIT:0>::<NUM_LIT:2>]))<EOL>pstack = []<EOL>buff = []<EOL>for i, c in enumerate(text):<EOL><INDENT>c_next = text[i+<NUM_LIT:1>] if i+<NUM_LIT:1> < len(text) else None<EOL>if c in paren_chars:<EOL><INDENT>if c in close2open:  <EOL><INDENT>if len(pstack) > <NUM_LIT:0> and pstack[-<NUM_LIT:1>] == close2open[c]:<EOL><INDENT>pstack.pop()<EOL><DEDENT><DEDENT>else:  <EOL><INDENT>pstack.append(c)<EOL><DEDENT><DEDENT>buff.append(c)<EOL>if c in delimiters:<EOL><INDENT>if len(pstack) == <NUM_LIT:0> and c_next not in delimiters:<EOL><INDENT>yield '<STR_LIT>'.join(buff)<EOL>buff = []<EOL><DEDENT><DEDENT><DEDENT>if len(buff) > <NUM_LIT:0>:<EOL><INDENT>yield '<STR_LIT>'.join(buff)<EOL><DEDENT>

Args:
  text: unicode string that contains multiple Japanese sentences.
  delimiters: set() of sentence delimiter characters.
  parenthesis: to be checked its correspondence.
Returns:
  generator that yields sentences.


def summarize(text, char_limit, sentence_filter=None, debug=False):

debug_info = {}<EOL>sents = list(tools.sent_splitter_ja(text))<EOL>words_list = [<EOL>w.encode('<STR_LIT:utf-8>') for s in sents for w in tools.word_segmenter_ja(s)<EOL>]<EOL>tf = collections.Counter()<EOL>for words in words_list:<EOL><INDENT>for w in words:<EOL><INDENT>tf[w] += <NUM_LIT:1.0><EOL><DEDENT><DEDENT>if sentence_filter is not None:<EOL><INDENT>valid_indices = [i for i, s in enumerate(sents) if sentence_filter(s)]<EOL>sents = [sents[i] for i in valid_indices]<EOL>words_list = [words_list[i] for i in valid_indices]<EOL><DEDENT>sent_ids = [str(i) for i in range(len(sents))]  <EOL>sent_id2len = dict((id_, len(s)) for id_, s in zip(sent_ids, sents))  <EOL>word_contain = dict()  <EOL>for id_, words in zip(sent_ids, words_list):<EOL><INDENT>word_contain[id_] = collections.defaultdict(lambda: <NUM_LIT:0>)<EOL>for w in words:<EOL><INDENT>word_contain[id_][w] = <NUM_LIT:1><EOL><DEDENT><DEDENT>prob = pulp.LpProblem('<STR_LIT>', pulp.LpMaximize)<EOL>sent_vars = pulp.LpVariable.dicts('<STR_LIT>', sent_ids, <NUM_LIT:0>, <NUM_LIT:1>, pulp.LpBinary)<EOL>word_vars = pulp.LpVariable.dicts('<STR_LIT>', list(tf.keys()), <NUM_LIT:0>, <NUM_LIT:1>, pulp.LpBinary)<EOL>prob += pulp.lpSum([tf[w] * word_vars[w] for w in tf])<EOL>prob += pulp.lpSum(<EOL>[sent_id2len[id_] * sent_vars[id_] for id_ in sent_ids]<EOL>) <= char_limit, '<STR_LIT>'<EOL>for w in tf:<EOL><INDENT>prob += pulp.lpSum(<EOL>[word_contain[id_][w] * sent_vars[id_] for id_ in sent_ids]<EOL>) >= word_vars[w], '<STR_LIT>'.format(w)<EOL><DEDENT>prob.solve()<EOL>sent_indices = []<EOL>for v in prob.variables():<EOL><INDENT>if v.name.startswith('<STR_LIT>') and v.varValue == <NUM_LIT:1>:<EOL><INDENT>sent_indices.append(int(v.name.split('<STR_LIT:_>')[-<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>return [sents[i] for i in sent_indices], debug_info<EOL>

select sentences in terms of maximum coverage problem

Args:
  text: text to be summarized (unicode string)
  char_limit: summary length (the number of characters)

Returns:
  list of extracted sentences

Reference:
  Hiroya Takamura, Manabu Okumura.
  Text summarization model based on maximum coverage problem and its
  variant. (section 3)
  http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.222.6945


def __init__(self, i2c, device_address, *, debug=False):

while not i2c.try_lock():<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>i2c.writeto(device_address, b'<STR_LIT>')<EOL><DEDENT>except OSError:<EOL><INDENT>try:<EOL><INDENT>result = bytearray(<NUM_LIT:1>)<EOL>i2c.readfrom_into(device_address, result)<EOL><DEDENT>except OSError:<EOL><INDENT>raise ValueError("<STR_LIT>" % device_address)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>i2c.unlock()<EOL><DEDENT>self.i2c = i2c<EOL>self.device_address = device_address<EOL>self._debug = debug<EOL>

Try to read a byte from an address,
if you get an OSError it means the device is not there


self.i2c.readfrom_into(self.device_address, buf, **kwargs)<EOL>if self._debug:<EOL><INDENT>print("<STR_LIT>", [hex(i) for i in buf])<EOL><DEDENT>

Read into ``buf`` from the device. The number of bytes read will be the
length of ``buf``.

If ``start`` or ``end`` is provided, then the buffer will be sliced
as if ``buf[start:end]``. This will not cause an allocation like
``buf[start:end]`` will so it saves memory.

:param bytearray buffer: buffer to write into
:param int start: Index to start writing at
:param int end: Index to write up to but not include


self.i2c.writeto(self.device_address, buf, **kwargs)<EOL>if self._debug:<EOL><INDENT>print("<STR_LIT>", [hex(i) for i in buf])<EOL><DEDENT>

Write the bytes from ``buffer`` to the device. Transmits a stop bit if
``stop`` is set.

If ``start`` or ``end`` is provided, then the buffer will be sliced
as if ``buffer[start:end]``. This will not cause an allocation like
``buffer[start:end]`` will so it saves memory.

:param bytearray buffer: buffer containing the bytes to write
:param int start: Index to start writing from
:param int end: Index to read up to but not include
:param bool stop: If true, output an I2C stop condition after the buffer is written


def write_then_readinto(self, out_buffer, in_buffer, *,<EOL>out_start=<NUM_LIT:0>, out_end=None, in_start=<NUM_LIT:0>, in_end=None, stop=True):

if out_end is None:<EOL><INDENT>out_end = len(out_buffer)<EOL><DEDENT>if in_end is None:<EOL><INDENT>in_end = len(in_buffer)<EOL><DEDENT>if hasattr(self.i2c, '<STR_LIT>'):<EOL><INDENT>if self._debug:<EOL><INDENT>print("<STR_LIT>",<EOL>[hex(i) for i in out_buffer[out_start:out_end]])<EOL><DEDENT>self.i2c.writeto_then_readfrom(self.device_address, out_buffer, in_buffer,<EOL>out_start=out_start, out_end=out_end,<EOL>in_start=in_start, in_end=in_end, stop=stop)<EOL>if self._debug:<EOL><INDENT>print("<STR_LIT>",<EOL>[hex(i) for i in in_buffer[in_start:in_end]])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.write(out_buffer, start=out_start, end=out_end, stop=stop)<EOL>if self._debug:<EOL><INDENT>print("<STR_LIT>",<EOL>[hex(i) for i in out_buffer[out_start:out_end]])<EOL><DEDENT>self.readinto(in_buffer, start=in_start, end=in_end)<EOL>if self._debug:<EOL><INDENT>print("<STR_LIT>",<EOL>[hex(i) for i in in_buffer[in_start:in_end]])<EOL><DEDENT><DEDENT>

Write the bytes from ``out_buffer`` to the device, then immediately
reads into ``in_buffer`` from the device. The number of bytes read
will be the length of ``in_buffer``.
Transmits a stop bit after the write, if ``stop`` is set.

If ``out_start`` or ``out_end`` is provided, then the output buffer
will be sliced as if ``out_buffer[out_start:out_end]``. This will
not cause an allocation like ``buffer[out_start:out_end]`` will so
it saves memory.

If ``in_start`` or ``in_end`` is provided, then the input buffer
will be sliced as if ``in_buffer[in_start:in_end]``. This will not
cause an allocation like ``in_buffer[in_start:in_end]`` will so
it saves memory.

:param bytearray out_buffer: buffer containing the bytes to write
:param bytearray in_buffer: buffer containing the bytes to read into
:param int out_start: Index to start writing from
:param int out_end: Index to read up to but not include
:param int in_start: Index to start writing at
:param int in_end: Index to write up to but not include
:param bool stop: If true, output an I2C stop condition after the buffer is written


rows_before = {}  <EOL>free_rows = []<EOL>walk = []<EOL>for row in knitting_pattern.rows:<EOL><INDENT>rows_before_ = row.rows_before[:]<EOL>if rows_before_:<EOL><INDENT>rows_before[row] = rows_before_<EOL><DEDENT>else:<EOL><INDENT>free_rows.append(row)<EOL><DEDENT><DEDENT>assert free_rows<EOL>while free_rows:<EOL><INDENT>row = free_rows.pop(<NUM_LIT:0>)<EOL>walk.append(row)<EOL>assert row not in rows_before<EOL>for freed_row in reversed(row.rows_after):<EOL><INDENT>todo = rows_before[freed_row]<EOL>todo.remove(row)<EOL>if not todo:<EOL><INDENT>del rows_before[freed_row]<EOL>free_rows.insert(<NUM_LIT:0>, freed_row)<EOL><DEDENT><DEDENT><DEDENT>assert not rows_before, "<STR_LIT>"<EOL>return walk<EOL>

Walk the knitting pattern in a right-to-left fashion.

    :return: an iterable to walk the rows
    :rtype: list
    :param knittingpattern.KnittingPattern.KnittingPattern knitting_pattern: a
      knitting pattern to take the rows from


self._items = OrderedDict()<EOL>

Create a new :class:`IdCollection` with no arguments.

        You can add objects later using the method :meth:`append`.


self._items[item.id] = item<EOL>

Add an object to the end of the :class:`IdCollection`.

        :param item: an object that has an id


keys = list(self._items.keys())<EOL>key = keys[index]<EOL>return self[key]<EOL>

Get the object at an :paramref:`index`.

        :param int index: the index of the object
        :return: the object at :paramref:`index`


return self._items[id_]<EOL>

Get the object with the :paramref:`id`

        .. code:: python

            ic = IdCollection()
            ic.append(object_1)
            ic.append(object_2)
            assert ic[object_1.id] == object_1
            assert ic[object_2.id] == object_1

        :param id_: the id of an object
        :return: the object with the :paramref:`id`
        :raises KeyError: if no object with :paramref:`id` was found


return bool(self._items)<EOL>

:return: whether there is anything in the collection.
        :rtype: bool


for id_ in self._items:<EOL><INDENT>yield self[id_]<EOL><DEDENT>

allows you to iterate and use for-loops

        The objects in the iterator have the order in which they were appended.


return len(self._items)<EOL>

:return: the number of objects in this collection


return self.at(<NUM_LIT:0>)<EOL>

The first element in this collection.

        :return: the first element in this collection
        :raises IndexError: if this collection is empty


return object_<EOL>

:return: the argument
    :param object_: the object to be returned


return True<EOL>

:return: :obj:`True`
    :param _: can be ignored


def __init__(self, process=identity, chooses_path=true):

self._process = process<EOL>self._chooses_path = chooses_path<EOL>

Create a PathLoader object.

        :param process: ``process(path)`` is called with the `path` to load.
          The result of :paramref:`process` is returned to the caller. The
          default value is :func:`identity`, so the paths are returned when
          loaded.
        :param chooses_path: ``chooses_path(path)`` is called before
          :paramref:`process` and returns :obj:`True` or :obj:`False`
          depending on whether a specific path should be loaded and passed to
          :paramref:`process`.


result = []<EOL>for root, _, files in os.walk(folder):<EOL><INDENT>for file in files:<EOL><INDENT>path = os.path.join(root, file)<EOL>if self._chooses_path(path):<EOL><INDENT>result.append(self.path(path))<EOL><DEDENT><DEDENT><DEDENT>return result<EOL>

Load all files from a folder recursively.

        Depending on :meth:`chooses_path` some paths may not be loaded.
        Every loaded path is processed and returned part of the returned list.

        :param str folder: the folder to load the files from
        :rtype: list
        :return: a list of the results of the processing steps of the loaded
          files


return self._chooses_path(path)<EOL>

:return: whether the path should be loaded
        :rtype: bool

        :param str path: the path to the file to be tested


return self._process(path)<EOL>

load a :paramref:`path` and return the processed result

        :param str path: the path to the file to be processed
        :return: the result of processing step


def _relative_to_absolute(self, module_location, folder):

if os.path.isfile(module_location):<EOL><INDENT>path = os.path.dirname(module_location)<EOL><DEDENT>elif os.path.isdir(module_location):<EOL><INDENT>path = module_location<EOL><DEDENT>else:<EOL><INDENT>module_folder = os.path.dirname(module_location)<EOL>if module_folder:<EOL><INDENT>path = module_folder<EOL><DEDENT>else:<EOL><INDENT>__import__(module_location)<EOL>module = sys.modules[module_location]<EOL>path = os.path.dirname(module.__file__)<EOL><DEDENT><DEDENT>absolute_path = os.path.join(path, folder)<EOL>return absolute_path<EOL>

:return: the absolute path for the `folder` relative to
        the module_location.
        :rtype: str


def relative_folder(self, module, folder):

folder = self._relative_to_absolute(module, folder)<EOL>return self.folder(folder)<EOL>

Load a folder located relative to a module and return the processed
        result.

        :param str module: can be

          - a path to a folder
          - a path to a file
          - a module name

        :param str folder: the path of a folder relative to :paramref:`module`
        :return: a list of the results of the processing
        :rtype: list

        Depending on :meth:`chooses_path` some paths may not be loaded.
        Every loaded path is processed and returned part of the returned list.
        You can use :meth:`choose_paths` to find out which paths are chosen to
        load.


path = self._relative_to_absolute(module, file)<EOL>return self.path(path)<EOL>

Load a file relative to a module.

        :param str module: can be

          - a path to a folder
          - a path to a file
          - a module name

        :param str folder: the path of a folder relative to :paramref:`module`
        :return: the result of the processing


return [path for path in paths if self._chooses_path(path)]<EOL>

:return: the paths that are chosen by :meth:`chooses_path`
        :rtype: list


example_path = os.path.join("<STR_LIT>", relative_path)<EOL>return self.relative_file(__file__, example_path)<EOL>

Load an example from the knitting pattern examples.

        :param str relative_path: the path to load
        :return: the result of the processing

        You can use :meth:`knittingpattern.Loader.PathLoader.examples`
        to find out the paths of all examples.


return self.relative_folder(__file__, "<STR_LIT>")<EOL>

Load all examples form the examples folder of this packge.

        :return: a list of processed examples
        :rtype: list

        Depending on :meth:`chooses_path` some paths may not be loaded.
        Every loaded path is processed and returned part of the returned list.


return self._process(string)<EOL>

:return: the processed result of a string
        :param str string: the string to load the ocntent from


string = file.read()<EOL>return self.string(string)<EOL>

:return: the processed result of the content of a file-like object.

        :param file: the file-like object to load the content from.
          It should support the ``read`` method.


with open(path) as file:<EOL><INDENT>return self.file(file)<EOL><DEDENT>

:return: the processed result of a :paramref:`path's <path>` content.
        :param str path: the path where to load the content from.
          It should exist on the local file system.


def url(self, url, encoding="<STR_LIT>"):

import urllib.request<EOL>with urllib.request.urlopen(url) as file:<EOL><INDENT>webpage_content = file.read()<EOL><DEDENT>webpage_content = webpage_content.decode(encoding)<EOL>return self.string(webpage_content)<EOL>

load and process the content behind a url

        :return: the processed result of the :paramref:`url's <url>` content
        :param str url: the url to retrieve the content from
        :param str encoding: the encoding of the retrieved content.
          The default encoding is UTF-8.


return self._process(object_)<EOL>

Processes an already loaded object.

        :return: the result of the processing step
        :param object: the object to be loaded


object_ = json.loads(string)<EOL>return self.object(object_)<EOL>

Load an object from a string and return the processed JSON content

        :return: the result of the processing step
        :param str string: the string to load the JSON from


def __init__(self, id_, name, rows, parser):

self._id = id_<EOL>self._name = name<EOL>self._rows = rows<EOL>self._parser = parser<EOL>

Create a new instance.

        :param id_: the id of this pattern
        :param name: the human readable name of this pattern
        :param rows: a collection of rows of instructions
        :param knittingpattern.Parser.Parser parser: the parser to use to new
          content

        .. seealso:: :func:`knittingpattern.new_knitting_pattern`


return self._id<EOL>

the identifier within a :class:`set of knitting patterns
        <knittingpattern.KnittingPatternSet.KnittingPatternSet>`


return self._name<EOL>


return self._rows<EOL>

a collection of rows that this pattern is made of

        Usually this should be a
        :class:`knittingpattern.IdCollection.IdCollection` of
        :class:`knittingpattern.Row.Row`.


row = self._parser.new_row(id_)<EOL>self._rows.append(row)<EOL>return row<EOL>

Add a new row to the pattern.

        :param id_: the id of the row


return walk(self)<EOL>

Return the rows in the order that they should be knit.

        :rtype: list
        :return: the :attr:`rows` in the order that they should be knit

        .. seealso:: :mod:`knittingpattern.walk`


return unique([row.instruction_colors<EOL>for row in self.rows_in_knit_order()])<EOL>

The colors of the instructions.

        :return: the colors of the instructions listed in first appearance in
          knit order
        :rtype: list


global _default_instructions<EOL>if _default_instructions is None:<EOL><INDENT>_default_instructions = DefaultInstructions()<EOL><DEDENT>return _default_instructions<EOL>

:return: a default instruction library
    :rtype: DefaultInstructions

    .. warning:: The return value is mutable and you should not add new
      instructions to it. If you would like to add instructions to it,
      create a new
      :class:`~knittingpattern.InstructionLibrary.DefaultInstructions`
      instance.


return JSONLoader<EOL>

:return: the class for loading the specifications with
          :attr:`load`


return Instruction<EOL>

:return: the class for the specifications


self._type_to_instruction = {}<EOL>

Create a new :class:`InstructionLibrary
        <knittingpattern.InstructionLibrary.InstructionLibrary>` without
        arguments.

        Use :attr:`load` to load specifications.


return self._loader_class(self._process_loaded_object)<EOL>

:return: a loader that can be used to load specifications
        :rtype: knittingpattern.Loader.JSONLoader

        A file to load is a list of instructions in JSON format.

        .. code:: json

            [
                {
                    "type" : "knit",
                    "another" : "attribute"
                },
                {
                    "type" : "purl"
                }
            ]


for instruction in obj:<EOL><INDENT>self.add_instruction(instruction)<EOL><DEDENT>return self<EOL>

add the loaded instructions from :attr:`load`


instruction = self.as_instruction(specification)<EOL>self._type_to_instruction[instruction.type] = instruction<EOL>

Add an instruction specification

        :param specification: a specification with a key
          :data:`knittingpattern.Instruction.TYPE`

        .. seealso:: :meth:`as_instruction`


instruction = self._instruction_class(specification)<EOL>type_ = instruction.type<EOL>if type_ in self._type_to_instruction:<EOL><INDENT>instruction.inherit_from(self._type_to_instruction[type_])<EOL><DEDENT>return instruction<EOL>

Convert the specification into an instruction

        :param specification: a specification with a key
          :data:`knittingpattern.Instruction.TYPE`

        The instruction is not added.

        .. seealso:: :meth:`add_instruction`


return self.as_instruction({TYPE: instruction_type})<EOL>

:return: the specification for :paramref:`instruction_type`

        .. seealso:: :meth:`as_instruction`


return list(self._type_to_instruction)<EOL>

The types loaded in this library.

        :return: a list of types, preferably as :class:`string <str>`
        :rtype: list


super().__init__()<EOL>self.load.relative_folder(__file__, self.INSTRUCTIONS_FOLDER)<EOL>

Create the default instruction library without arguments.

        The default specifications are loaded automatically form this package.


return charlotte.patterns["<STR_LIT>"]<EOL>

:return: the pattern ``"A.1"`` in charlotte


:return: the pattern ``"A.2"`` in charlotte


patterns = load_from_relative_file(__name__, "<STR_LIT>")<EOL>return patterns.patterns["<STR_LIT>"]<EOL>

The pattern with one colored line and a uncolored line.


return _charlotte().patterns["<STR_LIT>"]<EOL>


return load_from_relative_file(HERE, "<STR_LIT>")<EOL>

Load the pattern set with only one instruction.


return single_instruction_pattern_set.patterns["<STR_LIT>"]<EOL>

The pattern which has only one instruction.


return pattern.rows[<NUM_LIT:1>]<EOL>


return pattern.rows[<NUM_LIT:2>]<EOL>


return row.instructions[<NUM_LIT:0>]<EOL>


return row2.instructions[<NUM_LIT:0>]<EOL>


assert instruction<EOL>row.instructions.pop()<EOL>return row<EOL>


parser = specification.new_parser(specification)<EOL>loader = specification.new_loader(parser.knitting_pattern_set)<EOL>return loader<EOL>

Create a loader for a knitting pattern set.

    :param specification: a :class:`specification
      <knittingpattern.ParsingSpecification.ParsingSpecification>`
      for the knitting pattern set, default
      :class:`DefaultSpecification`


self.new_loader = new_loader<EOL>self.new_parser = new_parser<EOL>self.new_parsing_error = new_parsing_error<EOL>self.new_pattern_set = new_pattern_set<EOL>self.new_pattern_collection = new_pattern_collection<EOL>self.new_row_collection = new_row_collection<EOL>self.new_pattern = new_pattern<EOL>self.new_row = new_row<EOL>self.new_default_instructions = new_default_instructions<EOL>self.new_instruction_in_row = new_instruction_in_row<EOL>


Initialize the default specification with no arguments.


return "<STR_LIT>".format(cls.__module__, cls.__qualname__)<EOL>

The string representation of the object.

        :return: the string representation
        :rtype: str


from .ParsingSpecification import new_knitting_pattern_set_loader<EOL>return new_knitting_pattern_set_loader()<EOL>

Create a loader to load knitting patterns with.

    :return: the loader to load objects with
    :rtype: knittingpattern.Loader.JSONLoader

    Example:

    .. code:: python

       import knittingpattern, webbrowser
       k = knittingpattern.load_from().example("Cafe.json")
       webbrowser.open(k.to_svg(25).temporary_path(".svg"))


return load_from().object(object_)<EOL>

Load a knitting pattern from an object.

    :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet


return load_from().string(string)<EOL>

Load a knitting pattern from a string.

    :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet


return load_from().file(file)<EOL>

Load a knitting pattern from a file-like object.

    :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet


return load_from().path(path)<EOL>

Load a knitting pattern from a file behind located at `path`.

    :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet


return load_from().url(url)<EOL>

Load a knitting pattern from a url.

    :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet


return load_from().relative_file(module, path_relative_to)<EOL>

Load a knitting pattern from a path relative to a module.

    :param str module: can be a module's file, a module's name or
      a module's path.
    :param str path_relative_to: is the path relative to the modules location.
      The result is loaded from this.

    :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet


from .convert.image_to_knittingpattern importconvert_image_to_knitting_pattern<EOL>return convert_image_to_knitting_pattern(colors=colors)<EOL>

Convert and image to a knitting pattern.

    :return: a loader
    :rtype: knittingpattern.Loader.PathLoader
    :param tuple colors: the colors to convert to

    .. code:: python

        convert_from_image().path("pattern.png").path("pattern.json")
        convert_from_image().path("pattern.png").knitting_pattern()

    .. seealso:: :mod:`knittingoattern.convert.image_to_knitting_pattern`


knitting_pattern_set = new_knitting_pattern_set()<EOL>return knitting_pattern_set.add_new_pattern(id_, name)<EOL>

Create a new knitting pattern.

    :return: a new empty knitting pattern.
    :param id_: the id of the knitting pattern
    :param name: the name of the knitting pattern or :obj:`None` if the
      :paramref:`id_` should be used
    :rtype: knittingpattern.KnittingPattern.KnittingPattern

    .. seealso:: :meth:`KnittingPatternSet.add_new_pattern()
      <knittingpattern.KnittingPatternSet.KnittingPatternSet.add_new_pattern>`


return load_from_object(EMPTY_KNITTING_PATTERN_SET)<EOL>

Create a new, empty knitting pattern set.

    :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet
    :return: a new, empty knitting pattern set


def __init__(self, row_id, values, parser):

super().__init__(values)<EOL>self._id = row_id<EOL>self._instructions = ObservableList()<EOL>self._instructions.register_observer(self._instructions_changed)<EOL>self._parser = parser<EOL>

Create a new row.

        :param row_id: an identifier for the row
        :param values: the values from the specification
        :param list inheriting_from: a list of specifications to inherit values
          from, see :class:`knittingpattern.Prototype.Prototype`

        .. note:: Seldomly, you need to create this row on your own. You can
          load it with the :mod:`knittingpattern` or the
          :class:`knittingpattern.Parser.Parser`.


if change.adds():<EOL><INDENT>for index, instruction in change.items():<EOL><INDENT>if isinstance(instruction, dict):<EOL><INDENT>in_row = self._parser.instruction_in_row(self, instruction)<EOL>self.instructions[index] = in_row<EOL><DEDENT>else:<EOL><INDENT>instruction.transfer_to_row(self)<EOL><DEDENT><DEDENT><DEDENT>

Call when there is a change in the instructions.


return self._id<EOL>

The id of the row.

        :return: the id of the row


return self._instructions<EOL>

The instructions in this row.

        :return: a collection of :class:`instructions inside the row
          <knittingpattern.Instruction.InstructionInRow>`
        :rtype: ObservableList.ObservableList


return sum(instruction.number_of_produced_meshes<EOL>for instruction in self.instructions)<EOL>

The number of meshes that this row produces.

        :return: the number of meshes that this row produces
        :rtype: int

        .. seealso::
          :meth:`Instruction.number_of_produced_meshes()
          <knittingpattern.Instruction.Instruction.number_of_produced_meshes>`,
          :meth:`number_of_consumed_meshes`


return sum(instruction.number_of_consumed_meshes<EOL>for instruction in self.instructions)<EOL>

The number of meshes that this row consumes.

        :return: the number of meshes that this row consumes
        :rtype: int

        .. seealso::
          :meth:`Instruction.number_of_consumed_meshes()
          <knittingpattern.Instruction.Instruction.number_of_consumed_meshes>`,
          :meth:`number_of_produced_meshes`


return list(chain(*(instruction.produced_meshes<EOL>for instruction in self.instructions)))<EOL>

The meshes that this row produces with its instructions.

        :return: a collection of :class:`meshes <knittingpattern.Mesh.Mesh>`
          that this instruction produces


return list(chain(*(instruction.consumed_meshes<EOL>for instruction in self.instructions)))<EOL>

Same as :attr:`produced_meshes` but for consumed meshes.


return "<STR_LIT>".format(self.__class__.__qualname__, self.id)<EOL>

The string representation of this row.

        :return: a string representation of this row
        :rtype: str


return self.get(COLOR)<EOL>

The color of the row.

        :return: the color of the row as specified or :obj:`None`


return unique(instruction.colors for instruction in self.instructions)<EOL>

The colors of the instructions in the row in the order tehy appear.

        :return: a list of colors of the knitting pattern in the order that
          they appear in
        :rtype: list


for instruction in reversed(self.instructions):<EOL><INDENT>if instruction.produces_meshes():<EOL><INDENT>return instruction.last_produced_mesh<EOL><DEDENT><DEDENT>raise IndexError("<STR_LIT>".format(self))<EOL>

The last produced mesh.

        :return: the last produced mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is produced

        .. seealso:: :attr:`number_of_produced_meshes`


for instruction in reversed(self.instructions):<EOL><INDENT>if instruction.consumes_meshes():<EOL><INDENT>return instruction.last_consumed_mesh<EOL><DEDENT><DEDENT>raise IndexError("<STR_LIT>".format(self))<EOL>

The last consumed mesh.

        :return: the last consumed mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is consumed

        .. seealso:: :attr:`number_of_consumed_meshes`


for instruction in self.instructions:<EOL><INDENT>if instruction.produces_meshes():<EOL><INDENT>return instruction.first_produced_mesh<EOL><DEDENT><DEDENT>raise IndexError("<STR_LIT>".format(self))<EOL>

The first produced mesh.

        :return: the first produced mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is produced

        .. seealso:: :attr:`number_of_produced_meshes`


for instruction in self.instructions:<EOL><INDENT>if instruction.consumes_meshes():<EOL><INDENT>return instruction.first_consumed_mesh<EOL><DEDENT><DEDENT>raise IndexError("<STR_LIT>".format(self))<EOL>

The first consumed mesh.

        :return: the first consumed mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is consumed

        .. seealso:: :attr:`number_of_consumed_meshes`


rows_before = []<EOL>for mesh in self.consumed_meshes:<EOL><INDENT>if mesh.is_produced():<EOL><INDENT>row = mesh.producing_row<EOL>if rows_before not in rows_before:<EOL><INDENT>rows_before.append(row)<EOL><DEDENT><DEDENT><DEDENT>return rows_before<EOL>

The rows that produce meshes for this row.

        :rtype: list
        :return: a list of rows that produce meshes for this row. Each row
          occurs only once. They are sorted by the first occurrence in the
          instructions.


rows_after = []<EOL>for mesh in self.produced_meshes:<EOL><INDENT>if mesh.is_consumed():<EOL><INDENT>row = mesh.consuming_row<EOL>if rows_after not in rows_after:<EOL><INDENT>rows_after.append(row)<EOL><DEDENT><DEDENT><DEDENT>return rows_after<EOL>

The rows that consume meshes from this row.

        :rtype: list
        :return: a list of rows that consume meshes from this row. Each row
          occurs only once. They are sorted by the first occurrence in the
          instructions.


return self.instructions[<NUM_LIT:0>]<EOL>

The first instruction of the rows instructions.

        :rtype: knittingpattern.Instruction.InstructionInRow
        :return: the first instruction in this row's :attr:`instructions`


return self.instructions[-<NUM_LIT:1>]<EOL>

The last instruction of the rows instructions.

        :rtype: knittingpattern.Instruction.InstructionInRow
        :return: the last instruction in this row's :attr:`instructions`


def __init__(self, knittingpattern, layout, instruction_to_svg, builder,<EOL>zoom):

self._knittingpattern = knittingpattern<EOL>self._layout = layout<EOL>self._instruction_to_svg = instruction_to_svg<EOL>self._builder = builder<EOL>self._zoom = zoom<EOL>self._instruction_type_color_to_symbol = OrderedDict()<EOL>self._symbol_id_to_scale = {}<EOL>

:param knittingpattern.KnittingPattern.KnittingPattern knittingpattern:
  a knitting pattern
:param knittingpattern.convert.Layout.GridLayout layout:
:param instruction_to_svg: an
  :class:`~knittingpattern.convert.InstructionToSVG.InstructionToSVG`
  :class:`
  ~knittingpattern.convert.InstructionToSVGCache.InstructionSVGCache`,
  both with instructions already loaded.
:param knittingpattern.convert.SVGBuilder.SVGBuilder builder:
:param float zoom: the height and width of a knit instruction


zoom = self._zoom<EOL>layout = self._layout<EOL>builder = self._builder<EOL>bbox = list(map(lambda f: f * zoom, layout.bounding_box))<EOL>builder.bounding_box = bbox<EOL>flip_x = bbox[<NUM_LIT:2>] + bbox[<NUM_LIT:0>] * <NUM_LIT:2><EOL>flip_y = bbox[<NUM_LIT:3>] + bbox[<NUM_LIT:1>] * <NUM_LIT:2><EOL>instructions = list(layout.walk_instructions(<EOL>lambda i: (flip_x - (i.x + i.width) * zoom,<EOL>flip_y - (i.y + i.height) * zoom,<EOL>i.instruction)))<EOL>instructions.sort(key=lambda x_y_i: x_y_i[<NUM_LIT:2>].render_z)<EOL>for x, y, instruction in instructions:<EOL><INDENT>render_z = instruction.render_z<EOL>z_id = ("<STR_LIT>" if not render_z else "<STR_LIT>".format(render_z))<EOL>layer_id = "<STR_LIT>".format(instruction.row.id, z_id)<EOL>def_id = self._register_instruction_in_defs(instruction)<EOL>scale = self._symbol_id_to_scale[def_id]<EOL>group = {<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>".format(instruction.id),<EOL>"<STR_LIT>": "<STR_LIT>".format(<EOL>x, y, scale)<EOL>}<EOL>builder.place_svg_use(def_id, layer_id, group)<EOL><DEDENT>builder.insert_defs(self._instruction_type_color_to_symbol.values())<EOL>return builder.get_svg_dict()<EOL>

Go through the layout and build the SVG.

        :return: an xml dict that can be exported using a
          :class:`~knittingpattern.Dumper.XMLDumper`
        :rtype: dict


type_ = instruction.type<EOL>color_ = instruction.color<EOL>instruction_to_svg_dict =self._instruction_to_svg.instruction_to_svg_dict<EOL>instruction_id = "<STR_LIT>".format(type_, color_)<EOL>defs_id = instruction_id + "<STR_LIT>"<EOL>if instruction_id not in self._instruction_type_color_to_symbol:<EOL><INDENT>svg_dict = instruction_to_svg_dict(instruction)<EOL>self._compute_scale(instruction_id, svg_dict)<EOL>symbol = self._make_definition(svg_dict, instruction_id)<EOL>self._instruction_type_color_to_symbol[defs_id] =symbol[DEFINITION_HOLDER].pop("<STR_LIT>", {})<EOL>self._instruction_type_color_to_symbol[instruction_id] = symbol<EOL><DEDENT>return instruction_id<EOL>

Create a definition for the instruction.

        :return: the id of a symbol in the defs for the specified
          :paramref:`instruction`
        :rtype: str

        If no symbol yet exists in the defs for the :paramref:`instruction` a
        symbol is created and saved using :meth:`_make_symbol`.


def _make_definition(self, svg_dict, instruction_id):

instruction_def = svg_dict["<STR_LIT>"]<EOL>blacklisted_elements = ["<STR_LIT>", "<STR_LIT>"]<EOL>whitelisted_attributes = ["<STR_LIT>"]<EOL>symbol = OrderedDict({"<STR_LIT>": instruction_id})<EOL>for content, value in instruction_def.items():<EOL><INDENT>if content.startswith('<STR_LIT:@>'):<EOL><INDENT>if content in whitelisted_attributes:<EOL><INDENT>symbol[content] = value<EOL><DEDENT><DEDENT>elif content not in blacklisted_elements:<EOL><INDENT>symbol[content] = value<EOL><DEDENT><DEDENT>return {DEFINITION_HOLDER: symbol}<EOL>

Create a symbol out of the supplied :paramref:`svg_dict`.

        :param dict svg_dict: dictionary containing the SVG for the
          instruction currently processed
        :param str instruction_id: id that will be assigned to the symbol


def _compute_scale(self, instruction_id, svg_dict):

bbox = list(map(float, svg_dict["<STR_LIT>"]["<STR_LIT>"].split()))<EOL>scale = self._zoom / (bbox[<NUM_LIT:3>] - bbox[<NUM_LIT:1>])<EOL>self._symbol_id_to_scale[instruction_id] = scale<EOL>

Compute the scale of an instruction svg.

        Compute the scale using the bounding box stored in the
        :paramref:`svg_dict`. The scale is saved in a dictionary using
        :paramref:`instruction_id` as key.

        :param str instruction_id: id identifying a symbol in the defs
        :param dict svg_dict: dictionary containing the SVG for the
          instruction currently processed


self._structure = xmltodict.parse(SVG_FILE)<EOL>self._layer_id_to_layer = {}<EOL>self._svg = self._structure["<STR_LIT>"]<EOL>self._min_x = None<EOL>self._min_y = None<EOL>self._max_x = None<EOL>self._max_y = None<EOL>

Initialize this object without arguments.


return (self._min_x, self._min_y, self._max_x, self._max_y)<EOL>

the bounding box of this SVG
        ``(min_x, min_y, max_x, max_y)``.

        .. code:: python

            svg_builder10x10.bounding_box = (0, 0, 10, 10)
            assert svg_builder10x10.bounding_box == (0, 0, 10, 10)

        ``viewBox``, ``width`` and ``height`` are computed from this.

        If the bounding box was never set, the result is a tuple of four
        :obj:`None`.


content = xmltodict.parse(svg)<EOL>self.place_svg_dict(x, y, content, layer_id)<EOL>

Place the :paramref:`svg` content at ``(x, y)`` position
        in the SVG, in a layer with the id :paramref:`layer_id`.

        :param float x: the x position of the svg
        :param float y: the y position of the svg
        :param str svg: the SVG to place at ``(x, y)``
        :param str layer_id: the id of the layer that this
          :paramref:`svg` should be placed inside


def place_svg_dict(self, x, y, svg_dict, layer_id, group=None):

if group is None:<EOL><INDENT>group = {}<EOL><DEDENT>group_ = {<EOL>"<STR_LIT>": "<STR_LIT>".format(x, y),<EOL>"<STR_LIT:g>": list(svg_dict.values())<EOL>}<EOL>group_.update(group)<EOL>layer = self._get_layer(layer_id)<EOL>layer["<STR_LIT:g>"].append(group_)<EOL>

Same as :meth:`place` but with a dictionary as :paramref:`svg_dict`.

        :param dict svg_dict: a dictionary returned by `xmltodict.parse()
          <https://github.com/martinblech/xmltodict>`__
        :param dict group: a dictionary of values to add to the group the
          :paramref:`svg_dict` will be added to or :obj:`None` if nothing
          should be added


def place_svg_use_coords(self, x, y, symbol_id, layer_id, group=None):

if group is None:<EOL><INDENT>group = {}<EOL><DEDENT>use = {"<STR_LIT>": x, "<STR_LIT>": y, "<STR_LIT>": "<STR_LIT>".format(symbol_id)}<EOL>group_ = {"<STR_LIT>": use}<EOL>group_.update(group)<EOL>layer = self._get_layer(layer_id)<EOL>layer["<STR_LIT:g>"].append(group_)<EOL>

Similar to :meth:`place` but with an id as :paramref:`symbol_id`.

        :param str symbol_id: an id which identifies an svg object defined in
          the defs
        :param dict group: a dictionary of values to add to the group the
          use statement will be added to or :obj:`None` if nothing
          should be added


def place_svg_use(self, symbol_id, layer_id, group=None):

self.place_svg_use_coords(<NUM_LIT:0>, <NUM_LIT:0>, symbol_id, layer_id, group)<EOL>

Same as :meth:`place_svg_use_coords`.

        With implicit `x`  and `y` which are set to `0` in this method and then
        :meth:`place_svg_use_coords` is called.


if layer_id not in self._layer_id_to_layer:<EOL><INDENT>self._svg.setdefault("<STR_LIT:g>", [])<EOL>layer = {<EOL>"<STR_LIT:g>": [],<EOL>"<STR_LIT>": layer_id,<EOL>"<STR_LIT>": layer_id,<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>}<EOL>self._layer_id_to_layer[layer_id] = layer<EOL>self._svg["<STR_LIT:g>"].append(layer)<EOL><DEDENT>return self._layer_id_to_layer[layer_id]<EOL>

:return: the layer with the :paramref:`layer_id`. If the layer
  does not exist, it is created.
:param str layer_id: the id of the layer


if self._svg["<STR_LIT>"] is None:<EOL><INDENT>self._svg["<STR_LIT>"] = {}<EOL><DEDENT>for def_ in defs:<EOL><INDENT>for key, value in def_.items():<EOL><INDENT>if key.startswith("<STR_LIT:@>"):<EOL><INDENT>continue<EOL><DEDENT>if key not in self._svg["<STR_LIT>"]:<EOL><INDENT>self._svg["<STR_LIT>"][key] = []<EOL><DEDENT>if not isinstance(value, list):<EOL><INDENT>value = [value]<EOL><DEDENT>self._svg["<STR_LIT>"][key].extend(value)<EOL><DEDENT><DEDENT>

Adds the defs to the SVG structure.

        :param defs: a list of SVG dictionaries, which contain the defs,
          which should be added to the SVG structure.


return self._structure<EOL>


xmltodict.unparse(self._structure, file, pretty=True)<EOL>

Writes the current SVG to the :paramref:`file`.

        :param file: a file-like object


def load_and_dump(create_loader, create_dumper, load_and_dump_):

@wraps(load_and_dump_)<EOL>def load_and_dump__(*args1, **kw):<EOL><INDENT>"""<STR_LIT>"""<EOL>def load(*args2):<EOL><INDENT>"""<STR_LIT>"""<EOL>def dump(*args3):<EOL><INDENT>"""<STR_LIT>"""<EOL>return load_and_dump_(*(args2 + args3 + args1), **kw)<EOL><DEDENT>return create_dumper(dump)<EOL><DEDENT>return create_loader(load)<EOL><DEDENT>return load_and_dump__<EOL>

:return: a function that has the doc string of
      :paramref:`load_and_dump_`
      additional arguments to this function are passed on to
      :paramref:`load_and_dump_`.

    :param create_loader: a loader, e.g.
      :class:`knittingpattern.Loader.PathLoader`
    :param create_dumper: a dumper, e.g.
      :class:`knittingpattern.Dumper.ContentDumper`
    :param load_and_dump_: a function to call with the loaded content.
      The arguments to both, :paramref:`create_dumper` and,
      :paramref:`create_loader`
      will be passed to :paramref:`load_and_dump_`.
      Any additional arguments to the return value are also passed to
      :paramref:`load_and_dump_`.
      The return value of :paramref:`load_and_dump_` is passed back to the
      :paramref:`Dumper`.

    .. seealso:: :func:`decorate_load_and_dump`


return lambda func: load_and_dump(create_loader, create_dumper, func)<EOL>

Same as :func:`load_and_dump` but returns a function to enable decorator
    syntax.

    Examples:

    .. code:: Python

        @decorate_load_and_dump(ContentLoader, JSONDumper)
        def convert_from_loader_to_dumper(loaded_stuff, other="arguments"):
            # convert
            return converted_stuff

        @decorate_load_and_dump(PathLoader, lambda dump: ContentDumper(dump,
            encoding=None))
        def convert_from_loader_to_dumper(loaded_stuff, to_file):
            # convert
            to_file.write(converted_stuff)


if isinstance(content, str):<EOL><INDENT>return re.findall("<STR_LIT>", content)[-<NUM_LIT:1>]<EOL><DEDENT>return content.title.cdata<EOL>


return list(layout.walk_instructions(lambda point: (point.x, point.y)))<EOL>


return list(layout.walk_instructions(lambda p: (p.width, p.height)))<EOL>

The sizes of the instructions of the layout.


return list(layout.walk_instructions(lambda point: point.instruction))<EOL>


return list(layout.walk_rows(lambda row: row.id))<EOL>


return list(layout.walk_connections(lambda c: (c.start.xy, c.stop.xy)))<EOL>

The connections between the rows of the leyout.


path = os.path.join("<STR_LIT>", self.FILE)<EOL>pattern_set = load_from_relative_file(__name__, path)<EOL>return pattern_set.patterns[self.PATTERN]<EOL>


return GridLayout(pattern)<EOL>


def __init__(self, min_x, min_y, max_x, max_y,<EOL>default_color="<STR_LIT>"):

self._min_x = min_x<EOL>self._min_y = min_y<EOL>self._max_x = max_x<EOL>self._max_y = max_y<EOL>self._default_color = default_color<EOL>self._image = PIL.Image.new(<EOL>"<STR_LIT>", (max_x - min_x, max_y - min_y),<EOL>self._convert_to_image_color(default_color))<EOL>

Initialize the builder with the bounding box and a default color.

        .. _png-builder-bounds:

        ``min_x <= x < max_x`` and ``min_y <= y < max_y`` are the bounds of the
        instructions.
        Instructions outside the bounds are not rendered.
        Any Pixel that is not set has the :paramref:`default_color`.

        :param int min_x: the lower bound of the x coordinates
        :param int max_x: the upper bound of the x coordinates
        :param int min_y: the lower bound of the y coordinates
        :param int max_y: the upper bound of the y coordinates
        :param default_color: a valid :ref:`color <png-color>`


self._image.save(file, format="<STR_LIT>")<EOL>

write the png to the file

        :param file: a file-like object


return convert_color_to_rrggbb(color)<EOL>

takes a :ref:`color <png-color>` and converts it into a 24 bit
        color "#RRGGBB"


return webcolors.hex_to_rgb(rrggbb)<EOL>

:return: the color that is used by the image


rgb = self._convert_color_to_rrggbb(color)<EOL>return self._convert_rrggbb_to_image_color(rgb)<EOL>

:return: a color that can be used by the image


def _set_pixel_and_convert_color(self, x, y, color):

if color is None:<EOL><INDENT>return<EOL><DEDENT>color = self._convert_color_to_rrggbb(color)<EOL>self._set_pixel(x, y, color)<EOL>

set the pixel but convert the color before.


if not self.is_in_bounds(x, y):<EOL><INDENT>return<EOL><DEDENT>rgb = self._convert_rrggbb_to_image_color(color)<EOL>x -= self._min_x<EOL>y -= self._min_y<EOL>self._image.putpixel((x, y), rgb)<EOL>

set the color of the pixel.

        :param color: must be a valid color in the form of "#RRGGBB".
          If you need to convert color, use `_set_pixel_and_convert_color()`.


self._set_pixel_and_convert_color(x, y, color)<EOL>

set the pixel at ``(x, y)`` position to :paramref:`color`

        If ``(x, y)`` is out of the :ref:`bounds <png-builder-bounds>`
        this does not change the image.

        .. seealso:: :meth:`set_color_in_grid`


lower = self._min_x <= x and self._min_y <= y<EOL>upper = self._max_x > x and self._max_y > y<EOL>return lower and upper<EOL>

:return: whether ``(x, y)`` is inside the :ref:`bounds
  <png-builder-bounds>`
:rtype: bool


self._set_pixel_and_convert_color(<EOL>color_in_grid.x, color_in_grid.y, color_in_grid.color)<EOL>

Set the pixel at the position of the :paramref:`color_in_grid`
        to its color.

        :param color_in_grid: must have the following attributes:

          - ``color`` is the :ref:`color <png-color>` to set the pixel to
          - ``x`` is the x position of the pixel
          - ``y`` is the y position of the pixel

        .. seealso:: :meth:`set_pixel`, :meth:`set_colors_in_grid`


for color_in_grid in some_colors_in_grid:<EOL><INDENT>self._set_pixel_and_convert_color(<EOL>color_in_grid.x, color_in_grid.y, color_in_grid.color)<EOL><DEDENT>

Same as :meth:`set_color_in_grid` but with a collection of
        colors in grid.

        :param iterable some_colors_in_grid: a collection of colors in grid for
          :meth:`set_color_in_grid`


return self._default_color<EOL>

:return: the :ref:`color <png-color>` of the pixels that are not set

        You can set this color by passing it to the :meth:`constructor
        <__init__>`.


super().__init__(self._dump_knitting_pattern,<EOL>text_is_expected=False, encoding=None)<EOL>self.__on_dump = function_that_returns_a_knitting_pattern_set<EOL>

Initialize the Dumper with a
        :paramref:`function_that_returns_a_knitting_pattern_set`.

        :param function_that_returns_a_knitting_pattern_set: a function that
          takes no arguments but returns a
          :class:`knittinpattern.KnittingPatternSet.KnittingPatternSet`

        When a dump is requested, the
        :paramref:`function_that_returns_a_knitting_pattern_set`
        is called and the knitting pattern set is converted and saved to the
        specified location.


knitting_pattern_set = self.__on_dump()<EOL>knitting_pattern = knitting_pattern_set.patterns.at(<NUM_LIT:0>)<EOL>layout = GridLayout(knitting_pattern)<EOL>builder = AYABPNGBuilder(*layout.bounding_box)<EOL>builder.set_colors_in_grid(layout.walk_instructions())<EOL>builder.write_to_file(file)<EOL>


return object_<EOL>


self._position = position<EOL>


return self._position.x<EOL>

:return: x coordinate in the grid
        :rtype: float


return self._position.y<EOL>

:return: y coordinate in the grid
        :rtype: float


return self._position<EOL>

:return: ``(x, y)`` coordinate in the grid
        :rtype: tuple


return self._position.y, self._position.x<EOL>

:return: ``(y, x)`` coordinate in the grid
        :rtype: tuple


return self._width<EOL>

:return: width of the object on the grid
        :rtype: float


return INSTRUCTION_HEIGHT<EOL>

:return: height of the object on the grid
        :rtype: float


return self._row<EOL>

:return: row of the object on the grid
        :rtype: knittingpattern.Row.Row


return self._bounding_box<EOL>

The bounding box of this object.

        :return: (min x, min y, max x, max y)
        :rtype: tuple


return self._id<EOL>


def __init__(self, instruction, position):

self._instruction = instruction<EOL>super().__init__(position)<EOL>

:param instruction: an :class:`instruction
  <knittingpattern.Instruction.InstructionInRow>`
:param Point position: the position of the :paramref:`instruction`


layout = self._instruction.get(GRID_LAYOUT)<EOL>if layout is not None:<EOL><INDENT>width = layout.get(WIDTH)<EOL>if width is not None:<EOL><INDENT>return width<EOL><DEDENT><DEDENT>return self._instruction.number_of_consumed_meshes<EOL>


return self._instruction<EOL>

The instruction.

        :return: instruction that is placed on the grid
        :rtype: knittingpattern.Instruction.InstructionInRow


return self._instruction.color<EOL>

The color of the instruction.

        :return: the color of the :attr:`instruction`


return self._instruction.row<EOL>


super().__init__(position)<EOL>self._row = row<EOL>


return sum(map(lambda i: i.width, self.instructions))<EOL>


x = self.x<EOL>y = self.y<EOL>result = []<EOL>for instruction in self._row.instructions:<EOL><INDENT>instruction_in_grid = InstructionInGrid(instruction, Point(x, y))<EOL>x += instruction_in_grid.width<EOL>result.append(instruction_in_grid)<EOL><DEDENT>return result<EOL>

The instructions in a grid.

        :return: the :class:`instructions in a grid <InstructionInGrid>` of
          this row
        :rtype: list


self._rows_in_grid = {}<EOL>self._todo = []<EOL>self._expand(first_instruction.row, Point(<NUM_LIT:0>, <NUM_LIT:0>), [])<EOL>self._walk()<EOL>

Start walking the knitting pattern starting from first_instruction.


def _expand(self, row, consumed_position, passed):

self._todo.append((row, consumed_position, passed))<EOL>

Add the arguments `(args, kw)` to `_walk` to the todo list.


if row in passed or not self._row_should_be_placed(row, position):<EOL><INDENT>return<EOL><DEDENT>self._place_row(row, position)<EOL>passed = [row] + passed<EOL>for i, produced_mesh in enumerate(row.produced_meshes):<EOL><INDENT>self._expand_produced_mesh(produced_mesh, i, position, passed)<EOL><DEDENT>for i, consumed_mesh in enumerate(row.consumed_meshes):<EOL><INDENT>self._expand_consumed_mesh(consumed_mesh, i, position, passed)<EOL><DEDENT>

Walk through the knitting pattern by expanding an row.


def _expand_consumed_mesh(self, mesh, mesh_index, row_position, passed):

if not mesh.is_produced():<EOL><INDENT>return<EOL><DEDENT>row = mesh.producing_row<EOL>position = Point(<EOL>row_position.x + mesh.index_in_producing_row - mesh_index,<EOL>row_position.y - INSTRUCTION_HEIGHT<EOL>)<EOL>self._expand(row, position, passed)<EOL>


def _expand_produced_mesh(self, mesh, mesh_index, row_position, passed):

if not mesh.is_consumed():<EOL><INDENT>return<EOL><DEDENT>row = mesh.consuming_row<EOL>position = Point(<EOL>row_position.x - mesh.index_in_consuming_row + mesh_index,<EOL>row_position.y + INSTRUCTION_HEIGHT<EOL>)<EOL>self._expand(row, position, passed)<EOL>


def _row_should_be_placed(self, row, position):

placed_row = self._rows_in_grid.get(row)<EOL>return placed_row is None or placed_row.y < position.y<EOL>

:return: whether to place this instruction


self._rows_in_grid[row] = RowInGrid(row, position)<EOL>


while self._todo:<EOL><INDENT>args = self._todo.pop(<NUM_LIT:0>)<EOL>self._step(*args)<EOL><DEDENT>

Loop through all the instructions that are `_todo`.


row_position = self._rows_in_grid[instruction.row].xy<EOL>x = instruction.index_of_first_consumed_mesh_in_row<EOL>position = Point(row_position.x + x, row_position.y)<EOL>return InstructionInGrid(instruction, position)<EOL>

Returns an `InstructionInGrid` object for the `instruction`


return self._rows_in_grid[row]<EOL>

Returns an `RowInGrid` object for the `row`


self._start = start<EOL>self._stop = stop<EOL>

:param InstructionInGrid start: the start of the connection
:param InstructionInGrid stop: the end of the connection


return self._start<EOL>

:return: the start of the connection
        :rtype: InstructionInGrid


return self._stop<EOL>

:return: the end of the connection
        :rtype: InstructionInGrid


if self._start.y + <NUM_LIT:1> < self._stop.y:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

:return: is this connection is visible
        :rtype: bool

        A connection is visible if it is longer that 0.


self._pattern = pattern<EOL>self._rows = list(pattern.rows)<EOL>self._walk = _RecursiveWalk(self._rows[<NUM_LIT:0>].instructions[<NUM_LIT:0>])<EOL>self._rows.sort(key=lambda row: self._walk.row_in_grid(row).yx)<EOL>

:param knittingpattern.KnittingPattern.KnittingPattern pattern: the
  pattern to layout


instructions = chain(*self.walk_rows(lambda row: row.instructions))<EOL>return map(mapping, instructions)<EOL>

Iterate over instructions.

        :return: an iterator over :class:`instructions in grid
          <InstructionInGrid>`
        :param mapping: funcion to map the result

        .. code:: python

            for pos, c in layout.walk_instructions(lambda i: (i.xy, i.color)):
                print("color {} at {}".format(c, pos))


row_in_grid = self._walk.row_in_grid<EOL>return map(lambda row: mapping(row_in_grid(row)), self._rows)<EOL>

Iterate over rows.

        :return: an iterator over :class:`rows <RowsInGrid>`
        :param mapping: funcion to map the result, see
          :meth:`walk_instructions` for an example usage


for start in self.walk_instructions():<EOL><INDENT>for stop_instruction in start.instruction.consuming_instructions:<EOL><INDENT>if stop_instruction is None:<EOL><INDENT>continue<EOL><DEDENT>stop = self._walk.instruction_in_grid(stop_instruction)<EOL>connection = Connection(start, stop)<EOL>if connection.is_visible():<EOL><INDENT>yield mapping(connection)<EOL><DEDENT><DEDENT><DEDENT>

Iterate over connections between instructions.

        :return: an iterator over :class:`connections <Connection>` between
          :class:`instructions in grid <InstructionInGrid>`
        :param mapping: funcion to map the result, see
          :meth:`walk_instructions` for an example usage


min_x, min_y, max_x, max_y = zip(*list(self.walk_rows(<EOL>lambda row: row.bounding_box)))<EOL>return min(min_x), min(min_y), max(max_x), max(max_y)<EOL>

The minimum and maximum bounds of this layout.

        :return: ``(min_x, min_y, max_x, max_y)`` the bounding box
          of this layout
        :rtype: tuple


return self._walk.row_in_grid(row)<EOL>

The a RowInGrid for the row with position information.

        :return: a row in the grid
        :rtype: RowInGrid


global _default_instruction_svg_cache<EOL>if _default_instruction_svg_cache is None:<EOL><INDENT>_default_instruction_svg_cache = InstructionSVGCache()<EOL><DEDENT>return _default_instruction_svg_cache<EOL>

Return the default InstructionSVGCache.

    :rtype: knittingpattern.convert.InstructionSVGCache.InstructionSVGCache


if instruction_to_svg is None:<EOL><INDENT>instruction_to_svg = default_instructions_to_svg()<EOL><DEDENT>self._instruction_to_svg_dict =instruction_to_svg.instruction_to_svg_dict<EOL>self._cache = {}<EOL>

Create the InstructionSVGCache.

        :param instruction_to_svg: an
         :class:`~knittingpattern.convert.InstructionToSVG.InstructionToSVG`
         object. If :obj:`None` is given, the
         :func:`default_instructions_to_svg
         <knittingpattern.convert.InstructionToSVG.default_instructions_to_svg>`
         is used.


if isinstance(instruction_or_id, tuple):<EOL><INDENT>return _InstructionId(instruction_or_id)<EOL><DEDENT>return _InstructionId(instruction_or_id.type,<EOL>instruction_or_id.hex_color)<EOL>

The id that identifies the instruction in this cache.

        :param instruction_or_id: an :class:`instruction
          <knittingpattern.Instruction.Instruction>` or an instruction id
        :return: a :func:`hashable <hash>` object
        :rtype: tuple


return SVGDumper(on_dump)<EOL>

Create a new SVGDumper with the function ``on_dump``.

        :rtype: knittingpattern.Dumper.SVGDumper


return self._new_svg_dumper(lambda: self.instruction_to_svg_dict(<EOL>instruction_or_id, not i_promise_not_to_change_the_result))<EOL>

Return the SVG for an instruction.

        :param instruction_or_id: either an
          :class:`~knittingpattern.Instruction.Instruction` or an id
          returned by :meth:`get_instruction_id`
        :param bool i_promise_not_to_change_the_result:

          - :obj:`False`: the result is copied, you can alter it.
          - :obj:`True`: the result is directly from the cache. If you change
            the result, other calls of this function get the changed result.

        :return: an SVGDumper
        :rtype: knittingpattern.Dumper.SVGDumper


def instruction_to_svg_dict(self, instruction_or_id, copy_result=True):

instruction_id = self.get_instruction_id(instruction_or_id)<EOL>if instruction_id in self._cache:<EOL><INDENT>result = self._cache[instruction_id]<EOL><DEDENT>else:<EOL><INDENT>result = self._instruction_to_svg_dict(instruction_id)<EOL>self._cache[instruction_id] = result<EOL><DEDENT>if copy_result:<EOL><INDENT>result = deepcopy(result)<EOL><DEDENT>return result<EOL>

Return the SVG dict for the SVGBuilder.

        :param instruction_or_id: the instruction or id, see
          :meth:`get_instruction_id`
        :param bool copy_result: whether to copy the result
        :rtype: dict

        The result is cached.


instruction_to_svg = InstructionToSVG()<EOL>instruction_to_svg.load.relative_folder(__name__, DEFAULT_SVG_FOLDER)<EOL>return instruction_to_svg<EOL>

load the default set of svg files for instructions

    :return: the default svg files for the instructions in this package
    :rtype: knittingpattern.InstructionToSVG.InstructionToSVG


return PathLoader<EOL>

:return: the loader to load svgs from different locations
        :rtype: knittingpattern.Loader.PathLoader .


self._instruction_type_to_file_content = {}<EOL>

create a InstructionToSVG object without arguments.


return self._loader_class(self._process_loaded_object)<EOL>

:return: a loader object that allows loading SVG files from
          various sources such as files and folders.
        :rtype: knittingpattern.Loader.PathLoader

        Examples:

        - ``instruction_to_svg.load.path(path)`` loads an SVG from a file named
          path
        - ``instruction_to_svg.load.folder(path)`` loads all SVG files for
          instructions in the folder recursively.
          If multiple files have the same name, the last occurrence is used.


file_name = os.path.basename(path)<EOL>name = os.path.splitext(file_name)[<NUM_LIT:0>]<EOL>with open(path) as file:<EOL><INDENT>string = file.read()<EOL>self._instruction_type_to_file_content[name] = string<EOL><DEDENT>

process the :paramref:`path`.

        :param str path: the path to load an svg from


instruction_type = instruction.type<EOL>if instruction_type in self._instruction_type_to_file_content:<EOL><INDENT>svg = self._instruction_type_to_file_content[instruction_type]<EOL>return self._set_fills_in_color_layer(svg, instruction.hex_color)<EOL><DEDENT>return self.default_instruction_to_svg_dict(instruction)<EOL>

:return: an xml-dictionary with the same content as
  :meth:`instruction_to_svg`.


return xmltodict.unparse(self.instruction_to_svg_dict(instruction))<EOL>

:return: an SVG representing the instruction.

        The SVG file is determined by the type attribute of the instruction.
        An instruction of type ``"knit"`` is looked for in a file named
        ``"knit.svg"``.

        Every element inside a group labeled ``"color"`` of mode ``"layer"``
        that has a ``"fill"`` style gets this fill replaced by the color of
        the instruction.
        Example of a recangle that gets filled like the instruction:

        .. code:: xml

            <g inkscape:label="color" inkscape:groupmode="layer">
                <rect style="fill:#ff0000;fill-opacity:1;fill-rule:nonzero"
                      id="rectangle1" width="10" height="10" x="0" y="0" />
            </g>

        If nothing was loaded to display this instruction, a default image is
        be generated by :meth:`default_instruction_to_svg`.


def _set_fills_in_color_layer(self, svg_string, color):

structure = xmltodict.parse(svg_string)<EOL>if color is None:<EOL><INDENT>return structure<EOL><DEDENT>layers = structure["<STR_LIT>"]["<STR_LIT:g>"]<EOL>if not isinstance(layers, list):<EOL><INDENT>layers = [layers]<EOL><DEDENT>for layer in layers:<EOL><INDENT>if not isinstance(layer, dict):<EOL><INDENT>continue<EOL><DEDENT>if layer.get("<STR_LIT>") == "<STR_LIT>" andlayer.get("<STR_LIT>") == "<STR_LIT>":<EOL><INDENT>for key, elements in layer.items():<EOL><INDENT>if key.startswith("<STR_LIT:@>") or key.startswith("<STR_LIT:#>"):<EOL><INDENT>continue<EOL><DEDENT>if not isinstance(elements, list):<EOL><INDENT>elements = [elements]<EOL><DEDENT>for element in elements:<EOL><INDENT>style = element.get("<STR_LIT>", None)<EOL>if style:<EOL><INDENT>style = style.split("<STR_LIT:;>")<EOL>processed_style = []<EOL>for style_element in style:<EOL><INDENT>if style_element.startswith("<STR_LIT>"):<EOL><INDENT>style_element = "<STR_LIT>" + color<EOL><DEDENT>processed_style.append(style_element)<EOL><DEDENT>style = "<STR_LIT:;>".join(processed_style)<EOL>element["<STR_LIT>"] = style<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return structure<EOL>

replaces fill colors in ``<g inkscape:label="color"
        inkscape:groupmode="layer">`` with :paramref:`color`

        :param color: a color fill the objects in the layer with


instruction_type = instruction.type<EOL>return instruction_type in self._instruction_type_to_file_content<EOL>

:return: whether there is an image for the instruction
        :rtype: bool

        This can be used before :meth:`instruction_to_svg` as it determines
        whether

        - the default value is used (:obj:`False`)
        - or there is a dedicated svg representation (:obj:`True`).


svg_dict = self.default_instruction_to_svg_dict(instruction)<EOL>return xmltodict.unparse(svg_dict)<EOL>

As :meth:`instruction_to_svg` but it only takes the ``default.svg``
        file into account.

        In case no file is found for an instruction in
        :meth:`instruction_to_svg`,
        this method is used to determine the default svg for it.

        The content is created by replacing the text ``{instruction.type}`` in
        the whole svg file named ``default.svg``.

        If no file ``default.svg`` was loaded, an empty string is returned.


instruction_type = instruction.type<EOL>default_type = "<STR_LIT:default>"<EOL>rep_str = "<STR_LIT>"<EOL>if default_type not in self._instruction_type_to_file_content:<EOL><INDENT>return {"<STR_LIT>": "<STR_LIT>"}<EOL><DEDENT>default_svg = self._instruction_type_to_file_content[default_type]<EOL>default_svg = default_svg.replace(rep_str, instruction_type)<EOL>colored_svg = self._set_fills_in_color_layer(default_svg,<EOL>instruction.hex_color)<EOL>return colored_svg<EOL>

Returns an xml-dictionary with the same content as
        :meth:`default_instruction_to_svg`

        If no file ``default.svg`` was loaded, an empty svg-dict is returned.


@decorate_load_and_dump(PathLoader, JSONDumper)<EOL>def convert_image_to_knitting_pattern(path, colors=("<STR_LIT>", "<STR_LIT>")):

image = PIL.Image.open(path)<EOL>pattern_id = os.path.splitext(os.path.basename(path))[<NUM_LIT:0>]<EOL>rows = []<EOL>connections = []<EOL>pattern_set = {<EOL>"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:source>": path<EOL>},<EOL>"<STR_LIT>": [<EOL>{<EOL>"<STR_LIT:name>": pattern_id,<EOL>"<STR_LIT:id>": pattern_id,<EOL>"<STR_LIT>": rows,<EOL>"<STR_LIT>": connections<EOL>}<EOL>]}<EOL>bbox = image.getbbox()<EOL>if not bbox:<EOL><INDENT>return pattern_set<EOL><DEDENT>white = image.getpixel((<NUM_LIT:0>, <NUM_LIT:0>))<EOL>min_x, min_y, max_x, max_y = bbox<EOL>last_row_y = None<EOL>for y in reversed(range(min_y, max_y)):<EOL><INDENT>instructions = []<EOL>row = {"<STR_LIT:id>": y, "<STR_LIT>": instructions}<EOL>rows.append(row)<EOL>for x in range(min_x, max_x):<EOL><INDENT>if image.getpixel((x, y)) == white:<EOL><INDENT>color = colors[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>color = colors[<NUM_LIT:1>]<EOL><DEDENT>instruction = {"<STR_LIT>": color}<EOL>instructions.append(instruction)<EOL><DEDENT>if last_row_y is not None:<EOL><INDENT>connections.append({"<STR_LIT>": {"<STR_LIT:id>": last_row_y}, "<STR_LIT:to>": {"<STR_LIT:id>": y}})<EOL><DEDENT>last_row_y = y<EOL><DEDENT>return pattern_set<EOL>

Load a image file such as a png bitmap of jpeg file and convert it
    to a :ref:`knitting pattern file <FileFormatSpecification>`.

    :param list colors: a list of strings that should be used as
      :ref:`colors <png-color>`.
    :param str path: ignore this. It is fulfilled by the loeder.

    Example:

    .. code:: python

        convert_image_to_knitting_pattern().path("image.png").path("image.json")


if not color.startswith("<STR_LIT:#>"):<EOL><INDENT>rgb = webcolors.html5_parse_legacy_color(color)<EOL>hex_color = webcolors.html5_serialize_simple_color(rgb)<EOL><DEDENT>else:<EOL><INDENT>hex_color = color<EOL><DEDENT>return webcolors.normalize_hex(hex_color)<EOL>

The color in "#RRGGBB" format.

    :return: the :attr:`color` in "#RRGGBB" format


return self.get(ID)<EOL>

The id of the instruction.

        :return: the :data:`id <ID>` of the instruction or
          :obj:`None` if none is specified.


return self.get(TYPE, DEFAULT_TYPE)<EOL>

The type of the instruction.

        :return: the :data:`type <TYPE>` of the instruction or
          :data:`DEFAULT_TYPE` if none is specified.
        :rtype: str

        The type should be a string.
        Depending on the type, the instruction can receive additional
        attributes.

        .. seealso:: :mod:`knittingpattern.InstructionLibrary`


return self.get(COLOR)<EOL>

The color of the instruction.

        :return: the :data:`color <COLOR>` of the instruction or
          :obj:`None` if none is specified.


return [self.color]<EOL>

All the colors that an instruction has.

        :return: a list of colors of the instruction. If the instruction has
          no color, this is ``[None]``.
        :rtype: list


return self.get(DESCRIPTION)<EOL>

The description of the instruction.

        :return: the :data:`description <DESCRIPTION>` of the instruction or
          :obj:`None` if none is specified.


return self.get(NUMBER_OF_CONSUMED_MESHES,<EOL>DEFAULT_NUMBER_OF_CONSUMED_MESHES)<EOL>

The number of meshes that this instruction consumes.

        :return: the :data:`number of consumed meshes
          <NUMBER_OF_CONSUMED_MESHES>` of the instruction or
          :data:`DEFAULT_NUMBER_OF_CONSUMED_MESHES` if none is specified.


return self.get(NUMBER_OF_PRODUCED_MESHES,<EOL>DEFAULT_NUMBER_OF_PRODUCED_MESHES)<EOL>

The number of meshes that this instruction produces.

        :return: the :data:`number of produced meshes
          <NUMBER_OF_PRODUCED_MESHES>` of the instruction or
          :data:`DEFAULT_NUMBER_OF_PRODUCED_MESHES` if none is specified.


return self.color is not None<EOL>

Whether this instruction has a color.

        :return: whether a :data:`color <COLOR>` is specified
        :rtype: bool


return self.type == KNIT_TYPE<EOL>

Whether this instruction is a knit instruction.

        :return: whether this instruction is a knit instruction
        :rtype: bool


return self.type == PURL_TYPE<EOL>

Whether this instruction is a purl instruction.

        :return: whether this instruction is a purl instruction
        :rtype: bool


return self.number_of_produced_meshes != <NUM_LIT:0><EOL>

Whether this institution produces meshes.

        :return: whether this instruction produces any meshes
        :rtype: bool

        .. seealso:: :attr:`number_of_produced_meshes`


return self.number_of_consumed_meshes != <NUM_LIT:0><EOL>

Whether this instruction consumes meshes.

        :return: whether this instruction consumes any meshes
        :rtype: bool

        .. seealso:: :attr:`number_of_consumed_meshes`


return self.get(RENDER, {}).get(RENDER_Z, DEFAULT_Z)<EOL>

The z-index of the instruction when rendered.

        :return: the z-index of the instruction. Instructions with a higher
          z-index are displayed in front of instructions with lower z-index.
        :rtype: float


if self.has_color():<EOL><INDENT>return convert_color_to_rrggbb(self.color)<EOL><DEDENT>return None<EOL>

The color in "#RRGGBB" format.

        :return: the :attr:`color` in "#RRGGBB" format or none if no color is
          given


if converter is None:<EOL><INDENT>from knittingpattern.convert.InstructionSVGCache importdefault_svg_cache<EOL>converter = default_svg_cache()<EOL><DEDENT>return converter.to_svg(self)<EOL>

Return a SVGDumper for this instruction.

        :param converter: a :class:`
          knittingpattern.convert.InstructionSVGCache.InstructionSVGCache` or
          :obj:`None`. If :obj:`None` is given, the :func:`
          knittingpattern.convert.InstructionSVGCache.default_svg_cache` is
          used.
        :rtype: knittingpattern.Dumper.SVGDumper


super().__init__(spec)<EOL>self._row = row<EOL>self._produced_meshes = [<EOL>self._new_produced_mesh(self, index)<EOL>for index in range(self.number_of_produced_meshes)<EOL>]<EOL>self._consumed_meshes = [<EOL>self._new_consumed_mesh(self, index)<EOL>for index in range(self.number_of_consumed_meshes)<EOL>]<EOL>self._cached_index_in_row = None<EOL>

Create a new instruction in a row with a specification.

        :param knittingpattern.Row.Row row: the row the instruction is placed
          in
        :param spec: specification of the instruction


if new_row != self._row:<EOL><INDENT>index = self.get_index_in_row()<EOL>if index is not None:<EOL><INDENT>self._row.instructions.pop(index)<EOL><DEDENT>self._row = new_row<EOL><DEDENT>

Transfer this instruction to a new row.

        :param knittingpattern.Row.Row new_row: the new row the instruction is
          in.


return ProducedMesh<EOL>

:return: the class of the produced meshes.


return ConsumedMesh<EOL>

:return: the class of the consumed meshes.


return self._row<EOL>

The row this instruction is in.

        :return: the row the instruction is placed in
        :rtype: knittingpattern.Row.Row


return self.get_index_in_row() is not None<EOL>

Whether the instruction can be found in its row.

        :return: whether the instruction is in its row
        :rtype: bool

        Use this to avoid raising and :class:`InstructionNotFoundInRow`.


expected_index = self._cached_index_in_row<EOL>instructions = self._row.instructions<EOL>if expected_index is not None and<NUM_LIT:0> <= expected_index < len(instructions) andinstructions[expected_index] is self:<EOL><INDENT>return expected_index<EOL><DEDENT>for index, instruction_in_row in enumerate(instructions):<EOL><INDENT>if instruction_in_row is self:<EOL><INDENT>self._cached_index_in_row = index<EOL>return index<EOL><DEDENT><DEDENT>return None<EOL>

Index of the instruction in the instructions of the row or None.

        :return: index in the :attr:`row`'s instructions or None, if the
          instruction is not in the row
        :rtype: int

        .. seealso:: :attr:`row_instructions`, :attr:`index_in_row`,
          :meth:`is_in_row`


index = self.get_index_in_row()<EOL>if index is None:<EOL><INDENT>self._raise_not_found_error()<EOL><DEDENT>return index<EOL>

Index of the instruction in the instructions of the row.

        :return: index in the :attr:`row`'s instructions
        :rtype: int
        :raises knittingpattern.Instruction.InstructionNotFoundInRow:
          if the instruction is not found at the index

        .. code:: python

            index = instruction.index_in_row
            assert instruction.row.instructions[index] == instruction

        .. seealso:: :attr:`row_instructions`, :meth:`get_index_in_row`,
          :meth:`is_in_row`


return self.row.instructions<EOL>

Shortcut for ``instruction.row.instructions``.

        :return: the instructions of the :attr:`row` the instruction is in

        .. seealso:: :attr:`index_in_row`


index = self.index_in_row + <NUM_LIT:1><EOL>if index >= len(self.row_instructions):<EOL><INDENT>return None<EOL><DEDENT>return self.row_instructions[index]<EOL>

The instruction after this one or None.

        :return: the instruction in :attr:`row_instructions` after this or
          :obj:`None` if this is the last
        :rtype: knittingpattern.Instruction.InstructionInRow

        This can be used to traverse the instructions.

        .. seealso:: :attr:`previous_instruction_in_row`


index = self.index_in_row - <NUM_LIT:1><EOL>if index < <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return self.row_instructions[index]<EOL>

The instruction before this one or None.

        :return: the instruction in :attr:`row_instructions` before this or
          :obj:`None` if this is the first
        :rtype: knittingpattern.Instruction.InstructionInRow

        This can be used to traverse the instructions.

        .. seealso:: :attr:`next_instruction_in_row`


return INSTRUCTION_NOT_FOUND_MESSAGE.format(<EOL>instruction=self, row=self.row<EOL>)<EOL>

The message for the error.

        :return: an error message
        :rtype: str

        .. warning: private, do not use


raise InstructionNotFoundInRow(self._instruction_not_found_message)<EOL>

Raise an error that this instruction is in its row no longer.

        :raises knittingpattern.Instruction.InstructionNotFoundInRow:
          the instruction was not found

        .. warning: private, do not use


index = <NUM_LIT:0><EOL>for instruction in self.row_instructions:<EOL><INDENT>if instruction is self:<EOL><INDENT>break<EOL><DEDENT>index += instruction.number_of_produced_meshes<EOL><DEDENT>else:<EOL><INDENT>self._raise_not_found_error()<EOL><DEDENT>return index<EOL>

Index of the first produced mesh in the row that consumes it.

        :return: an index of the first produced mesh of rows produced meshes
        :rtype: int

        .. note:: If the instruction :meth:`produces meshes
          <Instruction.produces_meshes>`, this is the index of the first
          mesh the instruction produces in all the meshes of the row.
          If the instruction does not produce meshes, the index of the mesh is
          returned as if the instruction had produced a mesh.

        .. code::

            if instruction.produces_meshes():
                index = instruction.index_of_first_produced_mesh_in_row


index = self.index_of_first_produced_mesh_in_row<EOL>return index + self.number_of_produced_meshes - <NUM_LIT:1><EOL>

Index of the last mesh produced by this instruction in its row.

        :return: an index of the last produced mesh of rows produced meshes
        :rtype: int

        .. note:: If this instruction :meth:`produces meshes
          <Instruction.produces_meshes>`, this is the index of
          its last produces mesh in the row. However, if this instruction does
          not produce meshes, this is the index **before** the first mesh of
          the instruction if it produced meshes.

        .. seealso:: :attr:`index_of_first_produced_mesh_in_row`


index = <NUM_LIT:0><EOL>for instruction in self.row_instructions:<EOL><INDENT>if instruction is self:<EOL><INDENT>break<EOL><DEDENT>index += instruction.number_of_consumed_meshes<EOL><DEDENT>else:<EOL><INDENT>self._raise_not_found_error()<EOL><DEDENT>return index<EOL>

The index of the first consumed mesh of this instruction in its row.

        Same as :attr:`index_of_first_produced_mesh_in_row`
        but for consumed meshes.


index = self.index_of_first_consumed_mesh_in_row<EOL>return index + self.number_of_consumed_meshes - <NUM_LIT:1><EOL>

The index of the last consumed mesh of this instruction in its row.

        Same as :attr:`index_of_last_produced_mesh_in_row`
        but for the last consumed mesh.


return self._produced_meshes<EOL>

The meshes produced by this instruction

        :return: a :class:`list` of :class:`meshes
          <knittingpattern.Mesh.Mesh>` that this instruction produces
        :rtype: list

        .. code:: python

            assert len(inst.produced_meshes) == inst.number_of_produced_meshes
            assert all(mesh.is_produced() for mesh in inst.produced_meshes)

        .. seealso:: :attr:`consumed_meshes`, :attr:`consuming_instructions`


return self._consumed_meshes<EOL>

The meshes consumed by this instruction

        :return: a :class:`list` of :class:`meshes
          <knittingpattern.Mesh.Mesh>` that this instruction consumes
        :rtype: list

        .. code:: python

            assert len(inst.consumed_meshes) == inst.number_of_consumed_meshes
            assert all(mesh.is_consumed() for mesh in inst.consumed_meshes)

        .. seealso:: :attr:`produced_meshes`, :attr:`producing_instructions`


index = self.get_index_in_row()<EOL>if index is None:<EOL><INDENT>position = "<STR_LIT>".format(self.row)<EOL><DEDENT>else:<EOL><INDENT>position = "<STR_LIT>".format(self.row, index)<EOL><DEDENT>return "<STR_LIT>".format(<EOL>self.__class__.__name__,<EOL>("<STR_LIT>".format(self.id) if self.id is not None else "<STR_LIT>"),<EOL>self.type,<EOL>position<EOL>)<EOL>

:obj:`repr(instruction) <repr>` used for :func:`print`.

        :return: the string representation of this object
        :rtype: str


return [(mesh.producing_instruction if mesh.is_produced() else None)<EOL>for mesh in self.consumed_meshes]<EOL>

Instructions that produce the meshes that this instruction consumes.

        :return: a list of :class:`instructions
          <knittingpattern.Instruction.InstructionInRow>`
        :rtype: list

        .. seealso:: :attr:`consuming_instructions`, :attr:`consumed_meshes`


return [(mesh.consuming_instruction if mesh.is_consumed() else None)<EOL>for mesh in self.produced_meshes]<EOL>

Instructions that consume the meshes that this instruction produces.

        :return: a list of :class:`instructions
          <knittingpattern.Instruction.InstructionInRow>`
        :rtype: list

        .. seealso:: :attr:`producing_instructions`, :attr:`produced_meshes`


return self.get(COLOR, self.row.color)<EOL>

The color of the instruction.

        :return: the :data:`color <COLOR>` of the instruction or
          :obj:`None` if none is specified.

        If no color is specified in the instruction, it is inherited form the
        row.


return self._produced_meshes[-<NUM_LIT:1>]<EOL>

The last produced mesh.

        :return: the last produced mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is produced

        .. seealso:: :attr:`Instruction.number_of_produced_meshes`


return self._consumed_meshes[-<NUM_LIT:1>]<EOL>

The last consumed mesh.

        :return: the last consumed mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is consumed

        .. seealso:: :attr:`Instruction.number_of_consumed_meshes`


return self._produced_meshes[<NUM_LIT:0>]<EOL>

The first produced mesh.

        :return: the first produced mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is produced

        .. seealso:: :attr:`Instruction.number_of_produced_meshes`


return self._consumed_meshes[<NUM_LIT:0>]<EOL>

The first consumed mesh.

        :return: the first consumed mesh
        :rtype: knittingpattern.Mesh.Mesh
        :raises IndexError: if no mesh is consumed

        .. seealso:: :attr:`Instruction.number_of_consumed_meshes`


included_elements = set()<EOL>def included(element):<EOL><INDENT>result = element in included_elements<EOL>included_elements.add(element)<EOL>return result<EOL><DEDENT>return [element for elements in iterables for element in elements<EOL>if not included(element)]<EOL>

Create an iterable from the iterables that contains each element once.

    :return: an iterable over the iterables. Each element of the result
      appeared only once in the result. They are ordered by the first
      occurrence in the iterables.