MMP, 竟然没有个正常点的方式获取protocol
963540
function getProtocol(req) {
	if (req.raw.socket.encrypted) return 'https';
	const proto = req['X-Forwarded-Proto'] || '';
	return proto ? proto.split(/\s*,\s*/)[0] : 'http';
}
1126144
function compose(middlewares, ctx) {
    let i = middlewares.length;
    let next = async function(){};

    // 循环算出来next
    for (let i = middlewares.length - 1; i >=0; i--) {
        next = getCallback(middlewares[i], ctx, next);
    }

    return next;
}
235071
def cublasDtpmv(handle, uplo, trans, diag, n, AP, x, incx):
    

    status = _libcublas.cublasDtpmv_v2(handle,
                                       _CUBLAS_FILL_MODE[uplo], 
                                       _CUBLAS_OP[trans], 
                                       _CUBLAS_DIAG[diag], 
                                       n, int(AP), int(x), incx)
    cublasCheckStatus(status)
907828
private NetProtocol checkProtocol(String protocol)
    {
        //  First check out whether the protcol is something we are aware of.
        NetProtocol proto = NetProtocol.getProtocol(protocol);
        if (proto == null || !proto.valid) {
            errno.set(ZError.EPROTONOSUPPORT);
            return proto;
        }

        //  Check whether socket type and transport protocol match.
        //  Specifically, multicast protocols can't be combined with
        //  bi-directional messaging patterns (socket types).
        if (!proto.compatible(options.type)) {
            errno.set(ZError.ENOCOMPATPROTO);
            return null;
        }
        //  Protocol is available.
        return proto;
    }
977982
function send($mnet_peer) {
        global $CFG, $DB;


        if (!$this->permission_to_call($mnet_peer)) {
            mnet_debug("tried and wasn't allowed to call a method on $mnet_peer->wwwroot");
            return false;
        }

        $this->requesttext = xmlrpc_encode_request($this->method, $this->params, array("encoding" => "utf-8", "escaping" => "markup"));
        $this->signedrequest = mnet_sign_message($this->requesttext);
        $this->encryptedrequest = mnet_encrypt_message($this->signedrequest, $mnet_peer->public_key);

        $httprequest = $this->prepare_http_request($mnet_peer);
        curl_setopt($httprequest, CURLOPT_POSTFIELDS, $this->encryptedrequest);

        $timestamp_send    = time();
        mnet_debug("about to send the curl request");
        $this->rawresponse = curl_exec($httprequest);
        mnet_debug("managed to complete a curl request");
        $timestamp_receive = time();

        if ($this->rawresponse === false) {
            $this->error[] = curl_errno($httprequest) .':'. curl_error($httprequest);
            return false;
        }
        curl_close($httprequest);

        $this->rawresponse = trim($this->rawresponse);

        $mnet_peer->touch();

        $crypt_parser = new mnet_encxml_parser();
        $crypt_parser->parse($this->rawresponse);

        // If we couldn't parse the message, or it doesn't seem to have encrypted contents,
        // give the most specific error msg available & return
        if (!$crypt_parser->payload_encrypted) {
            if (! empty($crypt_parser->remoteerror)) {
                $this->error[] = '4: remote server error: ' . $crypt_parser->remoteerror;
            } else if (! empty($crypt_parser->error)) {
                $crypt_parser_error = $crypt_parser->error[0];

                $message = '3:XML Parse error in payload: '.$crypt_parser_error['string']."\n";
                if (array_key_exists('lineno', $crypt_parser_error)) {
                    $message .= 'At line number: '.$crypt_parser_error['lineno']."\n";
                }
                if (array_key_exists('line', $crypt_parser_error)) {
                    $message .= 'Which reads: '.$crypt_parser_error['line']."\n";
                }
                $this->error[] = $message;
            } else {
                $this->error[] = '1:Payload not encrypted ';
            }

            $crypt_parser->free_resource();
            return false;
        }

        $key  = array_pop($crypt_parser->cipher);
        $data = array_pop($crypt_parser->cipher);

        $crypt_parser->free_resource();

        // Initialize payload var
        $decryptedenvelope = '';

        //                                          &$decryptedenvelope
        $isOpen = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $this->mnet->get_private_key());

        if (!$isOpen) {
            // Decryption failed... let's try our archived keys
            $openssl_history = get_config('mnet', 'openssl_history');
            if(empty($openssl_history)) {
                $openssl_history = array();
                set_config('openssl_history', serialize($openssl_history), 'mnet');
            } else {
                $openssl_history = unserialize($openssl_history);
            }
            foreach($openssl_history as $keyset) {
                $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']);
                $isOpen      = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $keyresource);
                if ($isOpen) {
                    // It's an older code, sir, but it checks out
                    break;
                }
            }
        }

        if (!$isOpen) {
            trigger_error("None of our keys could open the payload from host {$mnet_peer->wwwroot} with id {$mnet_peer->id}.");
            $this->error[] = '3:No key match';
            return false;
        }

        if (strpos(substr($decryptedenvelope, 0, 100), '<signedMessage>')) {
            $sig_parser = new mnet_encxml_parser();
            $sig_parser->parse($decryptedenvelope);
        } else {
            $this->error[] = '2:Payload not signed: ' . $decryptedenvelope;
            return false;
        }

        // Margin of error is the time it took the request to complete.
        $margin_of_error  = $timestamp_receive - $timestamp_send;

        // Guess the time gap between sending the request and the remote machine
        // executing the time() function. Marginally better than nothing.
        $hysteresis       = ($margin_of_error) / 2;

        $remote_timestamp = $sig_parser->remote_timestamp - $hysteresis;
        $time_offset      = $remote_timestamp - $timestamp_send;
        if ($time_offset > 0) {
            $threshold = get_config('mnet', 'drift_threshold');
            if(empty($threshold)) {
                // We decided 15 seconds was a pretty good arbitrary threshold
                // for time-drift between servers, but you can customize this in
                // the config_plugins table. It's not advised though.
                set_config('drift_threshold', 15, 'mnet');
                $threshold = 15;
            }
            if ($time_offset > $threshold) {
                $this->error[] = '6:Time gap with '.$mnet_peer->name.' ('.$time_offset.' seconds) is greater than the permitted maximum of '.$threshold.' seconds';
                return false;
            }
        }

        $this->xmlrpcresponse = base64_decode($sig_parser->data_object);
        $this->response       = xmlrpc_decode($this->xmlrpcresponse);

        // xmlrpc errors are pushed onto the $this->error stack
        if (is_array($this->response) && array_key_exists('faultCode', $this->response)) {
            // The faultCode 7025 means we tried to connect with an old SSL key
            // The faultString is the new key - let's save it and try again
            // The re_key attribute stops us from getting into a loop
            if($this->response['faultCode'] == 7025 && empty($mnet_peer->re_key)) {
                mnet_debug('recieved an old-key fault, so trying to get the new key and update our records');
                // If the new certificate doesn't come thru clean_param() unmolested, error out
                if($this->response['faultString'] != clean_param($this->response['faultString'], PARAM_PEM)) {
                    $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
                }
                $record                     = new stdClass();
                $record->id                 = $mnet_peer->id;
                $record->public_key         = $this->response['faultString'];
                $details                    = openssl_x509_parse($record->public_key);
                if(!isset($details['validTo_time_t'])) {
                    $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
                }
                $record->public_key_expires = $details['validTo_time_t'];
                $DB->update_record('mnet_host', $record);

                // Create a new peer object populated with the new info & try re-sending the request
                $rekeyed_mnet_peer = new mnet_peer();
                $rekeyed_mnet_peer->set_id($record->id);
                $rekeyed_mnet_peer->re_key = true;
                return $this->send($rekeyed_mnet_peer);
            }
            if (!empty($CFG->mnet_rpcdebug)) {
                if (get_string_manager()->string_exists('error'.$this->response['faultCode'], 'mnet')) {
                    $guidance = get_string('error'.$this->response['faultCode'], 'mnet');
                } else {
                    $guidance = '';
                }
            } else {
                $guidance = '';
            }
            $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'] ."\n".$guidance;
        }

        // ok, it's signed, but is it signed with the right certificate ?
        // do this *after* we check for an out of date key
        $verified = openssl_verify($this->xmlrpcresponse, base64_decode($sig_parser->signature), $mnet_peer->public_key);
        if ($verified != 1) {
            $this->error[] = 'Invalid signature';
        }

        return empty($this->error);
    }
554714
def i2m(self, pkt, i):
        """""""
        mask, ip = i
        ip = socket.inet_aton(ip)
        return struct.pack(">B", mask) + ip[:self.mask2iplen(mask)]
275812
def get_host_finger(protocol, ip, port, timeout=5):
    
    client = None
    msg = b"Hello, Server\r\n"
    if protocol == 'tcp':
        # tcp 协议
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.settimeout(timeout)
        client.connect((ip, port))
        client.send(msg)
    elif protocol == 'udp':
        # udp 协议
        client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        client.settimeout(timeout)
        client.sendto(msg, (ip, port))
    else:
        raise Exception('协议不支持')

    serverFinger = client.recv(1024)
    client.close()
    return serverFinger
565210
function() {
        try {
          var server = {
            "host": params.host,
            "port": params.port,
            "timeout": params.timeout || 20000,
            "connectHeaders": {
              "host": "/",
              "login": params.username,
              "passcode": params.password,
              "heart-beat": "5000, 5000"
            }
          };

          var servers = [server];

          var reconnectOptions = {
            'maxReconnects': 20
          };

          var manager = new Stompit.ConnectFailover(servers, reconnectOptions);

          manager.connect(function(error, stompClient, reconnect) {
            if (error) {
              fireEvent("error", {
                errorCode: error.code,
                errorMessage: error.message,
                errorEvent: error
              });

              return;
            }

            client = stompClient;

            client.on('error', function(error) {
              fireEvent("error", {
                errorCode: 999,
                errorMessage: "ActiveMQ client has had an error",
                errorEvent: error
              });
              reconnect();
            });

            fireEvent("init");
          });

        } catch (error) {
          console.error(error);
        }
      }
784063
public static function handleMiddleware()
    {
        if (self::$handle_status != 0) {
            throw new \ErrorException("非法的QP框架使用方法 - 仅仅只能处理一次中间件，并且由框架底层自动处理！");
        }
        foreach (\Qp\Kernel\Http\Router\QpRouter::getMatchedData()['middleware'] as $middleware) {
            self::$response_message = "";
            self::$response_status = 200;
            (new $middleware())->handle();
            if (self::$handle_status == 2) {
                if (json_decode(self::$response_message, true) != []) {
                    \Qp\Kernel\Response::response()->setContentType('application/json');
                }
                \Qp\Kernel\Response::send(self::$response_message, self::$response_status);
                exit;
            }
        }
        self::$handle_status = 3;
    }
1369276
function replaceMatch(match,i) {
            /**
             * 匹配 url('path/to/image.png')
             * 中的 path/to/image.png
             */

            var reg = /\(\s*(['"]?)([^'"\)]*)\1\s*\)/,
                parsed = "",
                imgpath = match.match(reg)[2],
                parsed_url;

            /**
             * 若非相对路径则取得其相对路径进行parse
             */
            parsed = self.calculateImagePath(csspath,imgpath,!isRelative(imgpath));

            if(!parsed){
                return;
            }
            // image_paths.push((parsed.name+parsed.ext).substr(1));

            parsed_url = "url(" + self.connector(parsed) + ")";

            if(parsed_url !== match){
                matches[match] = parsed_url;
            }
        }
953745
private List<Object> reprocessFormParams(Method method, List<Object> origParams, Message m) {
        Form form = null;
        boolean hasFormParamAnnotations = false;
        Object[] newValues = new Object[origParams.size()];
        java.lang.reflect.Parameter[] methodParams = method.getParameters();
        for (int i = 0; i < methodParams.length; i++) {
            if (Form.class.equals(methodParams[i].getType())) {
                form = (Form) origParams.get(i);
            }
            if (methodParams[i].getAnnotation(FormParam.class) != null) {
                hasFormParamAnnotations = true;
            } else {
                newValues[i] = origParams.get(i);
            }
        }

        if (!hasFormParamAnnotations || form == null) {
            return origParams;
        }

        for (int i = 0; i < newValues.length; i++) {
            if (newValues[i] == null) {
                String formFieldName = methodParams[i].getAnnotation(FormParam.class).value();
                List<String> values = form.asMap().get(formFieldName);
                newValues[i] = InjectionUtils.createParameterObject(values, 
                                                                    methodParams[i].getType(),
                                                                    methodParams[i].getParameterizedType(),
                                                                    methodParams[i].getAnnotations(),
                                                                    (String) origParams.get(i),
                                                                    false,
                                                                    ParameterType.FORM,
                                                                    m);
                if (LOG.isLoggable(Level.FINEST)) {
                    LOG.log(Level.FINEST, "replacing @FormParam value of {0} with {1}",
                        new Object[]{origParams.get(i), newValues[i]});
                }
            }
        }
        return Arrays.asList(newValues);
    }
246336
function buildModelUrl (protocol, host, apiRoot, modelName, id) {
  var result

  try {
    result = url.format({
      protocol: protocol,
      host: host,
      pathname: url.resolve('/', [apiRoot, modelName, id].join('/'))
    })
  } catch (e) {
    return ''
  }

  return result
}
187777
private static ProtocolSigFingerprint getSigFingerprint(
      Class <? extends VersionedProtocol> protocol, long serverVersion) {
    String protocolName = protocol.getName();
    synchronized (PROTOCOL_FINGERPRINT_CACHE) {
      ProtocolSigFingerprint sig = PROTOCOL_FINGERPRINT_CACHE.get(protocolName);
      if (sig == null) {
        int[] serverMethodHashcodes = getFingerprints(protocol.getMethods());
        sig = new ProtocolSigFingerprint(
            new ProtocolSignature(serverVersion, serverMethodHashcodes),
            getFingerprint(serverMethodHashcodes));
        PROTOCOL_FINGERPRINT_CACHE.put(protocolName, sig);
      }
      return sig;
    }
  }
708813
def rmap(fn, coll, is_iterable=None):
    
    result = []
    for x in coll:
        if is_iterable is None:
            is_iterable = isiterable

        if is_iterable(x):
            y = rmap(fn, x)
        else:
            y = fn(x)
        result.append(y)
    return result
233578
function(socket, expectedCommand, expectedBodyLength, callback, headerOnly) {
        var oriCallback = callback
        // 收包完毕则关闭掉连接
        callback = function() {
            cleanup()
            if (is.function(oriCallback)) {
                oriCallback.apply(null, arguments)
            }
        }
        var headerBufferLen = protocol.HEADER_BYTE_LENGTH
        var headerBuffer = new Buffer(headerBufferLen)
        // 已填充的length
        var headerBufferFilled = 0
        // 解析后的header信息
        // {status: , bodyLength: }
        var header
        var bodyBuffer
        // 下1次要copy到bodyBuffer中的起始位置
        var bodyBufferStart = 0

        socket.on('data', listener)

        function listener(data) {
            // --------------- 收到服务器发来消息
            // -------- 解析header
            if (!header) {
                // header parsed
                if (headerBufferFilled + data.length >= headerBufferLen) {
                    var len = headerBufferFilled + data.length
                    // 只copy剩下的header部分
                    data.copy(headerBuffer, headerBufferFilled, 0, headerBufferLen - headerBufferFilled)
                    try {
                        header = _parseHeader(headerBuffer, expectedCommand, expectedBodyLength)
                        logger.debug('receive server packet header: %j', header)
                        // 无body时直接返回
                        if (header.bodyLength === 0) {
                            callback(null, header)
                            return
                        }

                        if (headerOnly) {
                            oriCallback(null, header)
                            if (len > headerBufferLen) {
                                oriCallback(null, data.slice(headerBufferLen - headerBufferFilled))
                            }
                            return
                        }

                        bodyBuffer = new Buffer(header.bodyLength)

                        // 还有body的数据则填充到body buffer中
                        if (len > headerBufferLen) {
                            data.copy(bodyBuffer, 0, headerBufferLen - headerBufferFilled)
                            bodyBufferStart = len - headerBufferLen
                            // 读取完毕
                            if (bodyBufferStart >= header.bodyLength) {
                                callback(null, bodyBuffer)
                            }
                        }

                    } catch (err) {
                        callback(err)
                    }

                } else {
                    data.copy(headerBuffer, headerBufferFilled)
                    headerBufferFilled += data.length
                }

            } else {
                // 交由外部处理
                if (headerOnly) {
                    oriCallback(null, data)
                    return
                }
                // ---------- 解析body
                data.copy(bodyBuffer, bodyBufferStart)
                bodyBufferStart += data.length
                // 读取完毕
                if (bodyBufferStart >= header.bodyLength) {
                    callback(null, bodyBuffer)
                }
            }
        }

        function cleanup() {
            socket.removeListener('data', listener)
            // 关闭连接
            protocol.closeSocket(socket)
        }
    }
1064133
function xCMP( value ) {
		var readValue = read(),
			t = ( value - readValue ) & 0xff;
		flagN = ( t & 0x80 ) && 1;
		flagC = +( value >= readValue );
		flagZ = +( t === 0 );
	}
802279
def regex(self, protocols, localhost=True):
        
        p = r"^"

        # protocol
        p += r"(?:(?:(?:{}):)?//)".format('|'.join(protocols))

        # basic auth (optional)
        p += r"(?:\S+(?::\S*)?@)?"

        p += r"(?:"

        # ip exclusion: private and local networks
        p += r"(?!(?:10|127)(?:\.\d{1,3}){3})"
        p += r"(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})"
        p += r"(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})"

        # ip excluding loopback (0.0.0.0), reserved space (244.0.0.0)
        # and network/broadcast addresses
        p += r"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])"
        p += r"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}"
        p += r"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))"
        p += r"|"

        # hostname
        p += r"(?:"
        p += r"(?:"
        p += r"[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?"
        p += r"[a-z0-9\u00a1-\uffff]"
        p += r"\." if not localhost else r"[\.]?|localhost"


        p += r")+"

        # tld
        p += r"(?:[a-z\u00a1-\uffff]{2,}\.?)"
        p += r")"

        # port (optional)
        p += r"(?::\d{2,5})?"

        # path (optional)
        p += r"(?:[/?#]\S*)?"

        p += r"$"
        return p