Add a display name for all known CIDRs
    :param aws_config:
    :param current_config:
    :param path:
    :param current_path:
    :param resource_id:
    :param callback_args:
    :return:
550754
def put_cidr_name(aws_config, current_config, path, current_path, resource_id, callback_args):
    
    if 'cidrs' in current_config:
        cidr_list = []
        for cidr in current_config['cidrs']:
            if type(cidr) == dict:
                cidr = cidr['CIDR']
            if cidr in known_cidrs:
                cidr_name = known_cidrs[cidr]
            else:
                cidr_name = get_cidr_name(cidr, callback_args['ip_ranges'], callback_args['ip_ranges_name_key'])
                known_cidrs[cidr] = cidr_name
            cidr_list.append({'CIDR': cidr, 'CIDRName': cidr_name})
        current_config['cidrs'] = cidr_list
752786
def preprocessing(aws_config, ip_ranges = [], ip_ranges_name_key = None):
    

    map_all_sgs(aws_config)
    map_all_subnets(aws_config)
    set_emr_vpc_ids(aws_config)
    #parse_elb_policies(aws_config)

    # Various data processing calls
    add_security_group_name_to_ec2_grants(aws_config['services']['ec2'], aws_config['aws_account_id'])
    process_cloudtrail_trails(aws_config['services']['cloudtrail'])
    add_cidr_display_name(aws_config, ip_ranges, ip_ranges_name_key)
    merge_route53_and_route53domains(aws_config)
    match_instances_and_roles(aws_config)
    match_iam_policies_and_buckets(aws_config)

    # Preprocessing dictated by metadata
    process_metadata_callbacks(aws_config)
1353296
def update_urls(self, request, resource_name=None, ids=None):
        
        http_host = request.META.get('HTTP_HOST', None)

        if http_host is None:
            http_host = request.META['SERVER_NAME']
            if request.META['SERVER_PORT'] not in ('80', '443'):
                http_host = "{}:{}".format(
                    http_host, request.META['SERVER_PORT'])

        self.base_url = "{}://{}".format(
            request.META['wsgi.url_scheme'],
            http_host
        )
        self.api_url = "{}{}".format(self.base_url, request.path)
        self.api_url = self.api_url.rstrip("/")

        if ids is not None:
            self.api_url = self.api_url.rsplit("/", 1)[0]

        if resource_name is not None:
            self.api_url = self.api_url.rsplit("/", 1)[0]
1133323
function buildVpc(cidrBlock = '10.0.0.0/16', { name = 'VPC' } = {}) {
  return {
    [name]: {
      Type: 'AWS::EC2::VPC',
      Properties: {
        CidrBlock: cidrBlock,
        EnableDnsSupport: true,
        EnableDnsHostnames: true,
        InstanceTenancy: 'default',
        Tags: [
          {
            Key: 'Name',
            Value: {
              Ref: 'AWS::StackName',
            },
          },
        ],
      },
    },
  };
}
152636
def set_parameter_label(self, parameter, label):
        
        labels = self.metadata\
            .setdefault("AWS::CloudFormation::Interface", {})\
            .setdefault("ParameterLabels", {})

        if isinstance(parameter, BaseAWSObject):
            parameter = parameter.title

        labels[parameter] = {"default": label}
357822
def add_lambda_integration(self, path, method, integration_uri,
                               method_auth_config=None, api_auth_config=None, condition=None):
        

        method = self._normalize_method_name(method)
        if self.has_integration(path, method):
            raise ValueError("Lambda integration already exists on Path={}, Method={}".format(path, method))

        self.add_path(path, method)

        # Wrap the integration_uri in a Condition if one exists on that function
        # This is necessary so CFN doesn't try to resolve the integration reference.
        if condition:
            integration_uri = make_conditional(condition, integration_uri)

        path_dict = self.get_path(path)
        path_dict[method][self._X_APIGW_INTEGRATION] = {
                'type': 'aws_proxy',
                'httpMethod': 'POST',
                'uri': integration_uri
        }

        method_auth_config = method_auth_config or {}
        api_auth_config = api_auth_config or {}
        if method_auth_config.get('Authorizer') == 'AWS_IAM' \
           or api_auth_config.get('DefaultAuthorizer') == 'AWS_IAM' and not method_auth_config:
            self.paths[path][method][self._X_APIGW_INTEGRATION]['credentials'] = self._generate_integration_credentials(
                method_invoke_role=method_auth_config.get('InvokeRole'),
                api_invoke_role=api_auth_config.get('InvokeRole')
            )

        # If 'responses' key is *not* present, add it with an empty dict as value
        path_dict[method].setdefault('responses', {})

        # If a condition is present, wrap all method contents up into the condition
        if condition:
            path_dict[method] = make_conditional(condition, path_dict[method])
97343
def _path_condition_name(self, api_id, path):
        
        # only valid characters for CloudFormation logical id are [A-Za-z0-9], but swagger paths can contain
        # slashes and curly braces for templated params, e.g., /foo/{customerId}. So we'll replace
        # non-alphanumeric characters.
        path_logical_id = path.replace('/', 'SLASH').replace('{', 'OB').replace('}', 'CB')
        return '{}{}PathCondition'.format(api_id, path_logical_id)
1276611
def add_signaling_arguments(parser):
    
    parser.add_argument('--signaling', '-s', choices=[
        'copy-and-paste', 'tcp-socket', 'unix-socket'])
    parser.add_argument('--signaling-host', default='127.0.0.1',
                        help='Signaling host (tcp-socket only)')
    parser.add_argument('--signaling-port', default=1234,
                        help='Signaling port (tcp-socket only)')
    parser.add_argument('--signaling-path', default='aiortc.socket',
                        help='Signaling socket path (unix-socket only)')
57561
def name_url(provider, cloud, method_name):
    
    snake_parts = method_name.split('_')
    if len(snake_parts) <= 1:
        return False

    # Convention for libcloud is ex_ are extended methods
    if snake_parts[0] == 'ex':
        extra = True
        method_name = method_name.replace('ex_', '', 1)
    else:
        extra = False
    snake_parts = method_name.split('_')
    # Try to semantically match the method name to a REST action
    if snake_parts[0] in get_sem_verbs:
        method = 'GET'
        for verb in get_sem_verbs:
            method_name = method_name.replace('%s_' % verb, '', 1)
    elif snake_parts[0] in delete_sem_verbs:
        method = 'DELETE'
    elif snake_parts[0] in put_sem_verbs:
        method = 'PUT'
    else:
        method = 'POST'

    uri = '/%s/%s/%s%s' % (provider,
                           cloud,
                           'extensions/' if extra else '',
                           method_name)
    return (method, uri)
1041966
def add_parameter_to_group(self, parameter, group_name):
        
        groups = self.metadata \
            .setdefault("AWS::CloudFormation::Interface", {}) \
            .setdefault("ParameterGroups", [])

        if isinstance(parameter, BaseAWSObject):
            parameter = parameter.title

        # Check if group_name already exists
        existing_group = None
        for group in groups:
            if group["Label"]["default"] == group_name:
                existing_group = group
                break

        if existing_group is None:
            existing_group = {
                "Label": {"default": group_name},
                "Parameters": [],
            }
            groups.append(existing_group)

        existing_group["Parameters"].append(parameter)

        return group_name
774487
def update_user_display_name(user,**kwargs):
    
    #check_perm(kwargs.get('user_id'), 'edit_user')
    try:
        user_i = db.DBSession.query(User).filter(User.id==user.id).one()
        user_i.display_name = user.display_name
        return user_i
    except NoResultFound:
        raise ResourceNotFoundError("User (id=%s) not found"%(user.id))
874115
def set_display_name(self, display_name):
        '''
        
        '''
        if self.config.legacy_upload:
            return self._legacy_set_display_name(display_name)

        system = self._fetch_system_by_machine_id()
        if not system:
            return system
        inventory_id = system[0]['id']
        req_url = self.base_url + '/inventory/v1/hosts/' + inventory_id
        try:
            net_logger.info("PATCH %s", req_url)
            res = self.session.patch(req_url, json={'display_name': display_name})
        except (requests.ConnectionError, requests.Timeout) as e:
            logger.error(e)
            logger.error('The Insights API could not be reached.')
            return False
        if (self.handle_fail_rcs(res)):
            logger.error('Could not update display name.')
            return False
        logger.info('Display name updated to ' + display_name + '.')
        return True
1190958
def list_cidr_ips(cidr):
    '''
    
    '''
    ips = netaddr.IPNetwork(cidr)
    return [six.text_type(ip) for ip in list(ips)]
958472
def _add_new_route(dcidr, router_ip, vpc_info, con, route_table_id):
    
    try:
        instance, eni = find_instance_and_eni_by_ip(vpc_info, router_ip)
        # Only set the route if the RT is associated with any of the subnets
        # used for the cluster.
        rt_subnets           = \
                    set(vpc_info['rt_subnet_lookup'].get(route_table_id, []))
        cluster_node_subnets = \
                    set(vpc_info['cluster_node_subnets'])
        if not rt_subnets or not rt_subnets.intersection(cluster_node_subnets):
            logging.debug("--- skipping adding route in RT '%s' "
                          "%s -> %s (%s, %s) since RT's subnets (%s) are not "
                          "part of the cluster (%s)." %
                          (route_table_id, dcidr, router_ip, instance.id,
                           eni.id,
                           ", ".join(rt_subnets) if rt_subnets else "none",
                           ", ".join(cluster_node_subnets)))
            return

        logging.info("--- adding route in RT '%s' "
                     "%s -> %s (%s, %s)" %
                     (route_table_id, dcidr, router_ip, instance.id, eni.id))
        con.create_route(route_table_id         = route_table_id,
                         destination_cidr_block = dcidr,
                         instance_id            = instance.id,
                         interface_id           = eni.id)
        CURRENT_STATE.routes[dcidr] = \
                                    (router_ip, str(instance.id), str(eni.id))
        _rt_state_update(route_table_id, dcidr, router_ip, instance.id, eni.id,
                         msg="Added route")

    except Exception as e:
        logging.error("*** failed to add route in RT '%s' "
                      "%s -> %s (%s)" %
                      (route_table_id, dcidr, router_ip, e.message))
        _rt_state_update(route_table_id, dcidr,
                         msg="[ERROR add route: %s]" % e.message)
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)
929078
def name(self, new_name):
        

        if self.startup_config_file:
            content = self.startup_config_content
            content = re.sub(r"^hostname .+$", "hostname " + new_name, content, flags=re.MULTILINE)
            self.startup_config_content = content

        super(IOUVM, IOUVM).name.__set__(self, new_name)
1162306
def _set_static_ip(name, session, vm_):
    '''
    
    '''
    ipv4_cidr = ''
    ipv4_gw = ''
    if 'ipv4_gw' in vm_.keys():
        log.debug('ipv4_gw is found in keys')
        ipv4_gw = vm_['ipv4_gw']
    if 'ipv4_cidr' in vm_.keys():
        log.debug('ipv4_cidr is found in keys')
        ipv4_cidr = vm_['ipv4_cidr']
        log.debug('attempting to set IP in instance')
        set_vm_ip(name, ipv4_cidr, ipv4_gw, session, None)