Generates a span name based off of the gRPC server rpc_request_info
198824
def _get_span_name(servicer_context):
    """"""
    method_name = servicer_context._rpc_event.call_details.method[1:]
    if isinstance(method_name, bytes):
        method_name = method_name.decode('utf-8')
    method_name = method_name.replace('/', '.')
    return '{}.{}'.format(RECV_PREFIX, method_name)
685365
def srv_name(svc, proto='tcp', domain=None):
    '''
    
    '''
    proto = RFC.validate(proto, RFC.SRV_PROTO)
    if isinstance(svc, int) or svc.isdigit():
        svc = _to_port(svc)

    if domain:
        domain = '.' + domain
    return '_{0}._{1}{2}'.format(svc, proto, domain)
1065948
def gen_opt_str(ser_rec: pd.Series)->str:
    '''
    '''

    name = ser_rec.name
    indent = r'    '
    str_opt = f'.. option:: {name}'+'\n\n'
    for spec in ser_rec.sort_index().index:
        str_opt += indent+f':{spec}:'+'\n'
        spec_content = ser_rec[spec]
        str_opt += indent+indent+f'{spec_content}'+'\n'
    return str_opt
436230
public String getPageAnnoForGridEvent(SSpan span) {
    int left = getLeftIndexFromSNode(span);
    int right = getRightIndexFromSNode(span);

    if (sspans == null) {
      log.warn("no page annos found");
      return null;
    }

    // lookup left index
    int leftIdx = -1;
    for (Integer i : sspans.keySet()) {
      if (i <= left) {
        leftIdx = i;
      }
    }

    if (leftIdx == -1) {
      log.debug("no left index found");
      return null;
    }

    // lookup right key
    int rightIdx = -1;
    for (Integer i : sspans.get(leftIdx).keySet()) {
      if (i >= right) {
        rightIdx = i;
      }
    }

    if (rightIdx == -1) {
      log.debug("no right index found");
      return null;
    }

    return getPageFromAnnotation(span);
  }
580018
def GetGRRVersionString(self):
    """"""
    client_info = self.startup_info.client_info
    client_name = client_info.client_description or client_info.client_name
    if client_info.client_version > 0:
      client_version = str(client_info.client_version)
    else:
      client_version = _UNKNOWN_GRR_VERSION
    return " ".join([client_name, client_version])
43741
def create_rpc_request_header(self):
        ''''''
        rpcheader = RpcRequestHeaderProto()
        rpcheader.rpcKind = 2  # rpcheaderproto.RpcKindProto.Value('RPC_PROTOCOL_BUFFER')
        rpcheader.rpcOp = 0  # rpcheaderproto.RpcPayloadOperationProto.Value('RPC_FINAL_PACKET')
        rpcheader.callId = self.call_id
        rpcheader.retryCount = -1
        rpcheader.clientId = self.client_id[0:16]

        if self.call_id == -3:
            self.call_id = 0
        else:
            self.call_id += 1

        # Serialize delimited
        s_rpcHeader = rpcheader.SerializeToString()
        log_protobuf_message("RpcRequestHeaderProto (len: %d)" % (len(s_rpcHeader)), rpcheader)
        return s_rpcHeader
1331162
def gen_url_regex(resource):
    "  "

    if resource._meta.parent:
        yield resource._meta.parent._meta.url_regex.rstrip('/$').lstrip('^')

    for p in resource._meta.url_params:
        yield '%(name)s/(?P<%(name)s>[^/]+)' % dict(name=p)

    if resource._meta.prefix:
        yield resource._meta.prefix

    yield '%(name)s/(?P<%(name)s>[^/]+)?' % dict(name=resource._meta.name)
931298
def _generate_minion_id():
    '''
    
    '''
    # There are three types of hostnames:
    # 1. Network names. How host is accessed from the network.
    # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts)
    # 3. Convention names, an internal nodename.

    class DistinctList(list):
        '''
        List, which allows one to append only distinct objects.
        Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version.
        Override 'filter()' for custom filtering.
        '''
        localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0',
                              r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa']

        def append(self, p_object):
            if p_object and p_object not in self and not self.filter(p_object):
                super(DistinctList, self).append(p_object)
            return self

        def extend(self, iterable):
            for obj in iterable:
                self.append(obj)
            return self

        def filter(self, element):
            'Returns True if element needs to be filtered'
            for rgx in self.localhost_matchers:
                if re.match(rgx, element):
                    return True

        def first(self):
            return self and self[0] or None

    hostname = socket.gethostname()

    hosts = DistinctList().append(
        salt.utils.stringutils.to_unicode(socket.getfqdn(salt.utils.stringutils.to_bytes(hostname)))
    ).append(platform.node()).append(hostname)
    if not hosts:
        try:
            for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET,
                                            socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME):
                if len(a_nfo) > 3:
                    hosts.append(a_nfo[3])
        except socket.gaierror:
            log.warning('Cannot resolve address %s info via socket: %s',
                        hosts.first() or 'localhost (N/A)', socket.gaierror)
    # Universal method for everywhere (Linux, Slowlaris, Windows etc)
    for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts',
                   r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))):
        try:
            with salt.utils.files.fopen(f_name) as f_hdl:
                for line in f_hdl:
                    line = salt.utils.stringutils.to_unicode(line)
                    hst = line.strip().split('#')[0].strip().split()
                    if hst:
                        if hst[0][:4] in ('127.', '::1') or len(hst) == 1:
                            hosts.extend(hst)
        except IOError:
            pass

    # include public and private ipaddresses
    return hosts.extend([addr for addr in ip_addrs()
                         if not ipaddress.ip_address(addr).is_loopback])
66854
def rm_prefix(name):
    
    if name.startswith('nova_'):
        return name[5:]
    elif name.startswith('novaclient_'):
        return name[11:]
    elif name.startswith('os_'):
        return name[3:]
    else:
        return name
1199289
function generateHoistNameBasedOn(path, suffix = "") {
  const names = [];
  if (suffix) {
    names.push(suffix);
  }

  let current = path;
  while (!(current.isIdentifier() || current.isJSXIdentifier())) {
    names.push(current.node.property.name);
    current = current.get("object");
  }
  names.push(current.node.name);

  return path.scope.generateUidIdentifier(names.reverse().join("$"));
}
1253667
public static void addTags(Span span, RequestLog log) {
        final String host = log.requestHeaders().authority();
        assert host != null;
        span.tag("http.host", host);
        final StringBuilder uriBuilder = new StringBuilder()
                .append(log.scheme().uriText())
                .append("://")
                .append(host)
                .append(log.path());
        if (log.query() != null) {
            uriBuilder.append('?').append(log.query());
        }
        span.tag("http.method", log.method().name())
            .tag("http.path", log.path())
            .tag("http.url", uriBuilder.toString())
            .tag("http.status_code", log.status().codeAsText());
        final Throwable responseCause = log.responseCause();
        if (responseCause != null) {
            span.tag("error", responseCause.toString());
        }

        final SocketAddress raddr = log.context().remoteAddress();
        if (raddr != null) {
            span.tag("address.remote", raddr.toString());
        }
        final SocketAddress laddr = log.context().localAddress();
        if (laddr != null) {
            span.tag("address.local", laddr.toString());
        }

        final Object requestContent = log.requestContent();
        if (requestContent instanceof RpcRequest) {
            span.name(((RpcRequest) requestContent).method());
        }
    }
1286708
@VisibleForTesting
  static String generateTraceSpanName(boolean isServer, String fullMethodName) {
    String prefix = isServer ? "Recv" : "Sent";
    return prefix + "." + fullMethodName.replace('/', '.');
  }
684728
def format_name(net: str) -> str:
        ''''''

        if net.startswith('t') or 'testnet' in net:
            net = net[1:] + '-test'
        else:
            net = net

        return net
89136
def GET_namespace_names( self, path_info, namespace_id ):
        
        if not check_namespace(namespace_id):
            return self._reply_json({'error': 'Invalid namespace'}, status_code=400)

        qs_values = path_info['qs_values']
        page = qs_values.get('page', None)
        if page is None:
            log.error("Page required")
            return self._reply_json({'error': 'page= argument required'}, status_code=400)

        try:
            page = int(page)
            if page < 0:
                raise ValueError()

        except ValueError:
            log.error("Invalid page")
            return self._reply_json({'error': 'Invalid page= value'}, status_code=400)

        offset = page * 100
        count = 100

        blockstackd_url = get_blockstackd_url()
        namespace_names = blockstackd_client.get_names_in_namespace(namespace_id, offset=offset, count=count, hostport=blockstackd_url)
        if json_is_error(namespace_names):
            # error
            status_code = namespace_names.get('http_status', 502)
            return self._reply_json({'error': namespace_names['error']}, status_code=status_code)

        self._reply_json(namespace_names)
        return
743879
def hostname_for_event(self, clean_server_name):
        """"""
        uri = urlsplit(clean_server_name)
        if '@' in uri.netloc:
            hostname = uri.netloc.split('@')[1].split(':')[0]
        else:
            hostname = uri.netloc.split(':')[0]
        if hostname == 'localhost':
            hostname = self.hostname
        return hostname
1065247
def ConfigureHostnames(config, external_hostname = None):
  """"""
  if not external_hostname:
    try:
      external_hostname = socket.gethostname()
    except (OSError, IOError):
      print("Sorry, we couldn't guess your hostname.\n")

    external_hostname = RetryQuestion(
        "Please enter your hostname e.g. "
        "grr.example.com", "^[\\.A-Za-z0-9-]+$", external_hostname)

  print("""\n\n-=Server URL=-
The Server URL specifies the URL that the clients will connect to
communicate with the server. For best results this should be publicly
accessible. By default this will be port 8080 with the URL ending in /control.
""")
  frontend_url = RetryQuestion("Frontend URL", "^http://.*/$",
                               "http://%s:8080/" % external_hostname)
  config.Set("Client.server_urls", [frontend_url])

  frontend_port = urlparse.urlparse(frontend_url).port or grr_config.CONFIG.Get(
      "Frontend.bind_port")
  config.Set("Frontend.bind_port", frontend_port)

  print("""\n\n-=AdminUI URL=-:
The UI URL specifies where the Administrative Web Interface can be found.
""")
  ui_url = RetryQuestion("AdminUI URL", "^http[s]*://.*$",
                         "http://%s:8000" % external_hostname)
  config.Set("AdminUI.url", ui_url)
  ui_port = urlparse.urlparse(ui_url).port or grr_config.CONFIG.Get(
      "AdminUI.port")
  config.Set("AdminUI.port", ui_port)
666786
def rpc_get_name_at( self, name, block_height, **con_info ):
        
        if not check_name(name):
            return {'error': 'invalid name', 'http_status': 400}

        if not check_block(block_height):
            return self.success_response({'record': None})

        db = get_db_state(self.working_dir)
        names_at = db.get_name_at( name, block_height, include_expired=False )
        db.close()
        
        ret = []
        for name_rec in names_at:
            if 'opcode' not in name_rec:
                name_rec['opcode'] = op_get_opcode_name(name_rec['op'])
            
            ret.append(self.sanitize_rec(name_rec))

        return self.success_response( {'records': ret} )