md code AND ``` style fenced raw code ends here
977342
def code(_, s, from_fenced_block = None, **kw):
        
        lang = kw.get('lang')

        raw_code = s
        if have_pygments:
            s = style_ansi(raw_code, lang=lang)


        # outest hir is 2, use it for fenced:
        ind = ' ' * kw.get('hir', 2)
        #if from_fenced_block: ... WE treat equal.

        # shift to the far left, no matter the indent (screenspace matters):
        firstl = s.split('\n')[0]
        del_spaces = ' ' * (len(firstl) - len(firstl.lstrip()))
        s = ('\n' + s).replace('\n%s' % del_spaces, '\n')[1:]

        # we want an indent of one and low vis prefix. this does it:
        code_lines = ('\n' + s).splitlines()
        prefix = ('\n%s%s %s' % (ind, low(code_pref), col('', C, no_reset=1)))
        code = prefix.join(code_lines)
        return code + '\n' + reset_col
705181
def MDS(D, dim, method='simple', theta=False):
    
    N = D.shape[0]
    if method == 'simple':
        d1 = D[0, :]
        # buf_ = d1 * np.ones([1, N]).T + (np.ones([N, 1]) * d1).T
        buf_ = np.broadcast_to(d1, D.shape) + np.broadcast_to(d1[:, np.newaxis], D.shape)
        np.subtract(D, buf_, out=buf_)
        G = buf_ # G = (D - d1 * np.ones([1, N]).T - (np.ones([N, 1]) * d1).T)
    elif method == 'advanced':
        # s1T = np.vstack([np.ones([1, N]), np.zeros([N - 1, N])])
        s1T = np.zeros_like(D)
        s1T[0, :] = 1
        np.subtract(np.identity(N), s1T, out = s1T)
        G = np.dot(np.dot(s1T.T, D), s1T)
    elif method == 'geometric':
        J = np.identity(N) + np.full((N, N), -1.0 / float(N))
        G = np.dot(np.dot(J, D), J)
    else:
        print('Unknown method {} in MDS'.format(method))
    G *= -0.5
    factor, u = eigendecomp(G, dim)
    if (theta):
        return theta_from_eigendecomp(factor, u)
    else:
        return x_from_eigendecomp(factor, u, dim)
1331463
function (md) {
            var html = marked(md, this.options.markdown);
            //Only reprocess if helpers were asked for
            if (this.options.helpers || (html.indexOf('{{#crossLink') > -1)) {
                //console.log('MD: ', html);
                try {
                    // marked auto-escapes quotation marks (and unfortunately
                    // does not expose the escaping function)
                    html = html.replace(/&quot;/g, "\"");
                    html = (Y.Handlebars.compile(html))({});
                } catch (hError) {
                    //Remove all the extra escapes
                    html = html.replace(/\\{/g, '{').replace(/\\}/g, '}');
                    Y.log('Failed to parse Handlebars, probably an unknown helper, skipping..', 'warn', 'builder');
                }
                //console.log('HB: ', html);
            }
            return html;
        }
477928
def compile(self, code):
        
        is_plain_text = True
        compiled_regex = r""
        for chunk in self.delimiter_regex().split(code):
            if is_plain_text:
                compiled_regex = compiled_regex + simex_escape(chunk, flexible_whitespace=self._flexible_whitespace)
            else:
                stripped_chunk = chunk.strip()
                if stripped_chunk in self._regexes.keys():
                    compiled_regex = u"{0}{1}".format(
                        compiled_regex,
                        self._regexes[stripped_chunk]
                    )
                else:
                    raise KeyNotFound("'{0}' not found in keys")
            is_plain_text = not is_plain_text
        if self._exact:
            compiled_regex = r"^" + compiled_regex + r"$"
        return compile(compiled_regex)
262355
function detectDelimiter(code) {
  code = trimKeepingTabs(code);

  // chunk first max 10 lines to detect
  const chunk = code.split(REGEX_LINE_ENDING).slice(0, 10).join('\n');

  // calc delta for each delimiters
  // then pick a delimiter having the minimum value delta
  return DSV_DELIMITERS.map(delimiter => ({
    delimiter,
    delta: calcDSVDelta(chunk, delimiter)
  })).sort((a, b) => (
    a.delta - b.delta
  ))[0].delimiter;
}
1157465
def _clean_code(self, code):
        
        lines = code.split("\n")
        min_indent = 100
        for line in lines:
            if line.strip() != "":
                indent = len(line) - len(line.lstrip())
                min_indent = min(indent, min_indent)
        if min_indent > 0:
            lines = [line[min_indent:] for line in lines]
        code = "\n".join(lines)
        return code
1063186
function (mode, code, tokens, flags, scope, parseMode) {
    var index = code.index + 2,
        length = code.length;

    if ( /* ! */
        code.codePointAt(index) === 0x0021
    ) {
        if (
            code.codePointAt(++index) === 0x002d &&
            code.codePointAt(++index) === 0x002d
        ) {
            index++;

            for (; index < length; index++) {
                if ( /* --}} */
                    code.codePointAt(index) === 0x002d &&
                    code.codePointAt(index + 1) === 0x002d &&
                    code.codePointAt(index + 2) === 0x007d &&
                    code.codePointAt(index + 3) === 0x007d
                ) {
                    index += 4; /* for --}} */
                    code.index = index;

                    parseMode.close();

                    if (flags.keepComments) {
                        // make a CommentToken and return that.
                    }

                    return true;
                }
            }

            throw code.makeError(
                'Unclosed Comment: Expected "--}}" to fallow "{{!--".',
                5
            );
        }

        index++;

        for (; index < length; index++) {

            if ( /* }} */
                code.codePointAt(index) === 0x007d &&
                code.codePointAt(index + 1) === 0x007d
            ) {
                index += 2; /* for }} */
                code.index = index;

                parseMode.close();

                if (flags.keepComments) {
                    // make a CommentToken and return that.
                }

                return true;
            }
        }

        throw code.makeError(
            code.index, code.index + 3,
            'Unclosed Comment: Expected "}}" to fallow "{{!".'
        );
    }

    return null;
}
789153
function md2html( file ){
  file = file.substr( file.length - 3 ) === '.md' ? file : file + '.md'; // add extension if need be

  var md;
  try{
    md = fs.readFileSync('./md/' + file, 'utf8');
  } catch(e){
    throw 'A markdown file named `' + file + '` was referenced but could not be read';
  }

  // var html = converter.makeHtml( md );
  //var html = mdConvertor( md );
  var html = marked( md, {
    highlight: function(code, lang){
      var ret;

      if( lang ){
        ret = hljs.highlight(lang, code).value;
      } else {
        ret = hljs.highlightAuto(code).value;
      }

      return ret;
      
    },

    renderer: mdRend
  } );


  return html;
}
550095
def term_code(mu, nu, coef, matrix_form, rhouv_isconjugated, linear=True):
    

    """
    if coef == 0:
        return ""
    coef = str(coef)

    # We change E_{0i} -> E0[i-1]
    ini = coef.find("E_{0")
    fin = coef.find("}")
    if ini != -1:
        l = int(coef[ini+4: fin])
        coef = coef[:ini]+"Ep["+str(l-1)+"]"+coef[fin+1:]

    # We change r[i, j] -> r[:, i, j]
    coef = coef.replace("rp[", "rp[:, ")
    coef = coef.replace("rm[", "rm[:, ")

    # We change symbolic complex-operations into fast numpy functions.
    coef = coef.replace("conjugate(", "np.conjugate(")
    coef = coef.replace("re(", "np.real(")
    coef = coef.replace("im(", "np.imag(")

    coef = coef.replace("*I", "j")

    if not linear:
        if matrix_form:
            s = "    b["+str(mu)+"] += "+coef+"\n"
        else:
            s = "    rhs["+str(mu)+"] += "+coef+"\n"
        return s

    # We add the syntax to calculate the term and store it in memory.
    s = "    "
    if matrix_form:
        s += "A["+str(mu)+", "+str(nu)+"] += "+coef+"\n"
    else:
        s += "rhs["+str(mu)+"] += ("+coef+")"
        if rhouv_isconjugated:
            s += "*np.conjugate(rho["+str(nu)+'])\n'
        else:
            s += "*rho["+str(nu)+']\n'

    return s
134585
function base32DecodeLastCharacter(chunk, characterIndex, buffer, index) {
    const byteIndex = Math.floor(index + (characterIndex * 5) / 8);
    const offset = characterIndex % 8;
    switch (offset) {
        case 1:
            buffer[byteIndex] |= chunk >>> 2;
            break;
        case 3:
            buffer[byteIndex] |= chunk >>> 4;
            break;
        case 4:
            buffer[byteIndex] |= chunk >>> 1;
            break;
        case 6:
            buffer[byteIndex] |= chunk >>> 3;
            break;
        case 7:
            buffer[byteIndex] |= chunk;
            break;
    }
}
725558
function parseHTML(html) {
	var temp = [];

	function push(code, type, padding) {
		code = code.replace(/\n/g, '');
		if (padding) {
			temp.push({code: code, type: type, padding: padding});
		} else {
			temp.push({code: code, type: type});
		}
	}

	function dig(nodes) {
		for (var i = 0; i < nodes.length; i ++) {
			var node = nodes[i];
			switch (node.type) {
				case 'comment':
				break;

				case 'text':
				var words = trim(node.raw).split(' ');
				for (var j = 0, jj = words.length; j < jj; j++) {
					push(words[j] + (j + 1 == jj ? '' : ' '), 'text');
				}
				break;

				case 'directive':
				push('<' + node.raw + '>', 'tag');
				break;

				default:
				var tag = node.name;
				var attribs = node.attribs || {};

				push('<' + tag, 'tag', paddingHTML);
				for (var key in attribs) {
					push(' ' + key + '="' + attribs[key] + '"', 'tag', paddingHTML);
				}
				push('>', 'tag');

				switch (tag) {
					case 'br':
					case 'input':
					case 'hr':
					case 'link':
					case 'meta':
					case 'img':
					case 'embed':
					case 'param':
					case 'area':
					case 'base':
					case 'col':
					case 'keygen':
					case 'source':
					continue;

					case 'script':
					if ((!attribs.type || attribs.type == 'text/javascript') && node.children && node.children[0]) {
						temp = temp.concat(parseJS(node.children[0].raw));
					}
					break;

					case 'style':
					if ((!attribs.type || attribs.type == 'text/css') && node.children && node.children[0]) {
						temp = temp.concat(parseCSS(node.children[0].raw));
					}
					break;

					default:
					if (node.children) dig(node.children);
				}

				push('</' + tag + '>', 'tag')
			}
		}
	}

	var handler = new htmlparser.DefaultHandler(function (error, dom) {});
	new htmlparser.Parser(handler).parseComplete(html);
	dig(handler.dom);

	var nodes = [];
	for (var i = 0, j = 0, ii = temp.length, lastType; i < ii; i++) {
		var tmp = temp[i];
		if (i && (lastType == tmp.type || !tmp.type)) {
			nodes[++j] = tmp;
		} else {
			if (!nodes[j]) {
				nodes[j] = tmp;
			} else {
				nodes[j].code += tmp.code;
				nodes[j].padding = tmp.padding;
			}
		}
		lastType = tmp.type;
	}
	return nodes;
}
527561
def md2tvd(self, kind='linear'):
        
        if self.position is None:
            return lambda x: x
        return interp1d(self.md, self.tvd,
                        kind=kind,
                        assume_sorted=True,
                        fill_value="extrapolate",
                        bounds_error=False)
1256336
function _md2($m)
    {
        static $s = array(
             41,  46,  67, 201, 162, 216, 124,   1,  61,  54,  84, 161, 236, 240, 6,
             19,  98, 167,   5, 243, 192, 199, 115, 140, 152, 147,  43, 217, 188,
             76, 130, 202,  30, 155,  87,  60, 253, 212, 224,  22, 103,  66, 111, 24,
            138,  23, 229,  18, 190,  78, 196, 214, 218, 158, 222,  73, 160, 251,
            245, 142, 187,  47, 238, 122, 169, 104, 121, 145,  21, 178,   7,  63,
            148, 194,  16, 137,  11,  34,  95,  33, 128, 127,  93, 154,  90, 144, 50,
             39,  53,  62, 204, 231, 191, 247, 151,   3, 255,  25,  48, 179,  72, 165,
            181, 209, 215,  94, 146,  42, 172,  86, 170, 198,  79, 184,  56, 210,
            150, 164, 125, 182, 118, 252, 107, 226, 156, 116,   4, 241,  69, 157,
            112,  89, 100, 113, 135,  32, 134,  91, 207, 101, 230,  45, 168,   2, 27,
             96,  37, 173, 174, 176, 185, 246,  28,  70,  97, 105,  52,  64, 126, 15,
             85,  71, 163,  35, 221,  81, 175,  58, 195,  92, 249, 206, 186, 197,
            234,  38,  44,  83,  13, 110, 133,  40, 132,   9, 211, 223, 205, 244, 65,
            129,  77,  82, 106, 220,  55, 200, 108, 193, 171, 250,  36, 225, 123,
              8,  12, 189, 177,  74, 120, 136, 149, 139, 227,  99, 232, 109, 233,
            203, 213, 254,  59,   0,  29,  57, 242, 239, 183,  14, 102,  88, 208, 228,
            166, 119, 114, 248, 235, 117,  75,  10,  49,  68,  80, 180, 143, 237,
             31,  26, 219, 153, 141,  51, 159,  17, 131, 20
        );

        // Step 1. Append Padding Bytes
        $pad = 16 - (strlen($m) & 0xF);
        $m.= str_repeat(chr($pad), $pad);

        $length = strlen($m);

        // Step 2. Append Checksum
        $c = str_repeat(chr(0), 16);
        $l = chr(0);
        for ($i = 0; $i < $length; $i+= 16) {
            for ($j = 0; $j < 16; $j++) {
                // RFC1319 incorrectly states that C[j] should be set to S[c xor L]
                //$c[$j] = chr($s[ord($m[$i + $j] ^ $l)]);
                // per <http://www.rfc-editor.org/errata_search.php?rfc=1319>, however, C[j] should be set to S[c xor L] xor C[j]
                $c[$j] = chr($s[ord($m[$i + $j] ^ $l)] ^ ord($c[$j]));
                $l = $c[$j];
            }
        }
        $m.= $c;

        $length+= 16;

        // Step 3. Initialize MD Buffer
        $x = str_repeat(chr(0), 48);

        // Step 4. Process Message in 16-Byte Blocks
        for ($i = 0; $i < $length; $i+= 16) {
            for ($j = 0; $j < 16; $j++) {
                $x[$j + 16] = $m[$i + $j];
                $x[$j + 32] = $x[$j + 16] ^ $x[$j];
            }
            $t = chr(0);
            for ($j = 0; $j < 18; $j++) {
                for ($k = 0; $k < 48; $k++) {
                    $x[$k] = $t = $x[$k] ^ chr($s[ord($t)]);
                    //$t = $x[$k] = $x[$k] ^ chr($s[ord($t)]);
                }
                $t = chr(ord($t) + $j);
            }
        }

        // Step 5. Output
        return substr($x, 0, 16);
    }
1320414
def to_md
      # Usually ruby is extremely readable, but I think "-1" means "give me all the 
      # trailing blank lines" is surprisingly opaque.  That's what the -1 does...
      lines = @text.split("\n", -1)
      lines.collect do |line|
        result = line
 
        # Leave lines that start with 4 spaces alone.  These are code blocks and
        # should pass through unchanged.
        unless result =~ /^\s{4,}/
 
          # Convert headers
          result.sub!(/^(=){1,6}/) { |s| "#" * s.length} unless result =~ /^={7,}/
 
          # Convert strong to have two stars
          # The matching pair of stars should start with a single star that is either at
          # the beginning of the line or not following a backslash, have at least one
          # non-star and non-backslash in between, then end in one star
          result.gsub!(/(\A|[^\\\*])\*([^\*]*[^\*\\])\*/, '\1**\2**')

          # Convert inline code spans to use backticks
          result.gsub!(/(\A|[^\\])\+([^\+]+)\+/, '\1`\2`')

          # Convert bare http:, mailto: and ftp: links
          result.gsub!(/(\A|\s)(http:|https:|mailto:|ftp:)(\S*)/, '\1[\2\3](\2\3)')

          # Convert bare www to an http: link
          result.gsub!(/(\A|\s)www\.(\S*)/, '\1[www.\2](http://www.\2)')

          # Convert link: links to refer to local files
          result.gsub!(/(\A|\s)link:(\S*)/, '\1[\2](\2)')

          # Convert multi word labels surrounded by {} with a url
          result.gsub!(/\{([^\}]*)\}\[(\S*)\]/, '[\1](\2)')

          # Convert one word labels with a url
          result.gsub!(/(\A|\s)([^\{\s]\S*)\[(\S*)\]/, '\1[\2](\3)')

        end
        
        result
      end.join("\n")
    end
837930
function codeWrap(){
  "use strict";

  var DEFAULT_TYPE = 'promise';

  var $codes = $('[data-code-id]').get();

  var codeIds =
    $codes
      .map(function(div){
          return div.attributes["data-code-id"].value
      })
      .filter(function(item, index, inputArray){
          // Each code block has multiple versions so let's only grab one.
          return inputArray.indexOf(item) == index;
      });

  wrap();
  setAll();

  $('[data-code-tablist] [href]').on('click', function(e){
    var href = $(this).attr('href');

    setAll(href.replace('#', ''));

    setEqualHeights();

    e.preventDefault();
  });

  function wrap(){
    var codeTpl = '' +
      '<ul class="nav nav-tabs nav-code" data-code-tablist="{{codeId}}">' +
        '<li>' +
            '<a href="#async">Async functions</a>' +
        '</li>' +
        '<li class="active">' +
            '<a href="#promise">Promises</a>' +
        '</li>' +
        '<li>' +
            '<a href="#callback">Callbacks</a>' +
        '</li>' +
      '</ul>' +
      '<div class="tab-content">{{tapPanes}}</div>';
    codeIds
      .forEach(function(id){
        var $code = $("[data-code-id='" + id + "']");

        var paneHtml = $code.get().map(function(div){
          return div.outerHTML;
        }).join('');

        var codeHtml = codeTpl
                          .replace(/{{tapPanes}}/g, paneHtml)
                          .replace(/{{codeId}}/g, id);
        $code
          .first()
          .replaceWith(codeHtml);
        $code.remove();
      });
    // Remove items that are only useful for non-JS users.
    $('[data-code-hide]').addClass('hide');
  }

  function setAll(type){

    // We default to callback so no need to do anything the first time.
    var firstTime = !localStorage.getItem('codeStyle');
    if(firstTime){
      localStorage.setItem('codeStyle', DEFAULT_TYPE);
    }

    type = type || localStorage.getItem('codeStyle');
    if(typeof type === "undefined" || type === null) {
      return;
    }

    var $tablist = $('[data-code-tablist] [href="#' + type + '"]').parent();
    $('[data-code-tablist] li').removeClass('active');
    $tablist.addClass('active');

    $('.tab-pane').removeClass('active');
    $('.tab-pane[id="' + type + '"]').addClass('active');
    localStorage.setItem('codeStyle', type);
  }


  var setHeights = [];
  function setEqualHeights(){
    if(setHeights.length > 0){
      return;
    }
    codeIds
      .forEach(function(id){
        var $code = $("[data-code-id='" + id + "']");

        var paneHeight = 0;

        $code.get().forEach(function(div){
          var originalDisplay = div.style.display;
          div.style.display = 'block';
          var clientHeight = div.clientHeight;
          div.style.display = originalDisplay;
          if(clientHeight > paneHeight){
            paneHeight = clientHeight;
          }
        });
        $code.find('pre').css('height', paneHeight);
        setHeights.push(id);
      });
  }
}
1186682
function(code){
    // Wrap code blocks with {}.
    // we only wrap unbuffered code blocks ATM
    // since they are usually flow control

    // Buffer code
    if (code.buffer) {
      var val = code.val.trim();
      val = 'null == (pug_interp = '+val+') ? "" : pug_interp';
      if (code.mustEscape !== false) val = this.runtime('escape') + '(' + val + ')';
      this.bufferExpression(val);
    } else {
      this.buf.push(code.val);
    }

    // Block support
    if (code.block) {
      if (!code.buffer) this.buf.push('{');
      this.visit(code.block, code);
      if (!code.buffer) this.buf.push('}');
    }
  }
4602
private function _buildRaw()
    {
        $boundary = md5(uniqid(rand(), true));
        $raw_message = 'From: ' . $this->_encodeHeader($this->_source) . "\n";
        if (!empty($this->_to)) {
            $raw_message .= 'To: ' . $this->_encodeHeader($this->_to) . "\n";
        }
        if (!empty($this->_cc)) {
            $raw_message .= 'cc: ' . $this->_encodeHeader($this->_cc) . "\n";
        }
        if (!empty($this->_bcc)) {
            $raw_message .= 'Bcc: ' . $this->_encodeHeader($this->_cc) . "\n";
        }
        if (!empty($this->_replyTo)) {
            $raw_message .= 'Reply-To: ' . $this->_encodeHeader($this->_replyTo) . "\n";
        }

        $raw_message .= 'Subject: =?' . $this->_charset . '?B?' . base64_encode($this->_subject) . "?=\n";
        $raw_message .= 'MIME-Version: 1.0' . "\n";

        $raw_message .= 'Content-Type: multipart/mixed; boundary="' . $boundary . '"' . "\n"; 
        $raw_message .= "\n--{$boundary}\n";
        $raw_message .= 'Content-Type: multipart/alternative; boundary="alt-' . $boundary . '"' . "\n";

        if (strlen($this->_body) > 0) {
            $raw_message .= "\n--alt-{$boundary}\n";
            $raw_message .= 'Content-Type: text/plain; charset="' . $this->_charset . '"' . "\n\n";
            $raw_message .= $this->_body . "\n";
        }

        if (strlen($this->_htmlBody) > 0) {
            $raw_message .= "\n--alt-{$boundary}\n";
            $raw_message .= 'Content-Type: text/html; charset="' . $this->_charset . '"' . "\n\n";
            $raw_message .= $this->_htmlBody . "\n";
        }
        $raw_message .= "\n--alt-{$boundary}--\n";

        foreach ($this->_attachments as $attachment) {
            $raw_message .= "\n--{$boundary}\n";
            $raw_message .= 'Content-Type: ' . $attachment['mimeType'] . '; name="' . $attachment['name'] . '"' . "\n";
            if (!empty($attachment['contentId'])) {
                $raw_message .= 'Content-ID' . $attachment['contentId'] . "\n";
            }
            $raw_message .= 'Content-Transfer-Encoding: base64' . "\n";
            $raw_message .= "\n" . chunk_split(base64_encode($attachment['data']), 76, "\n") . "\n";
        }

        $raw_message .= "\n--{$boundary}--\n";

        return base64_encode($raw_message);
    }