Python convert list

60 Python code examples are found related to " convert list". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: _op_translations.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def convert_string_to_list(string_val):
    """Helper function to convert string to list.
     Used to convert shape attribute string to list format.
    """
    result_list = []

    list_string = string_val.split(',')
    for val in list_string:
        val = str(val.strip())
        val = val.replace("(", "")
        val = val.replace(")", "")
        val = val.replace("L", "")
        val = val.replace("[", "")
        val = val.replace("]", "")
        if val not in ("", "None"):
            result_list.append(int(val))

    return result_list 
Example 2
Source File: score.py    From xview-yolov3 with MIT License 6 votes vote down vote up
def convert_to_rectangle_list(coordinates):
    """
      Converts a list of coordinates to a list of rectangles

      Args:
          coordinates: a flattened list of bounding box coordinates in format
            (xmin,ymin,xmax,ymax)

      Outputs:
        A list of rectangles

    """
    rectangle_list = []
    number_of_rects = int(len(coordinates) / 4)
    for i in range(number_of_rects):
        rectangle_list.append(Rectangle(
            coordinates[4 * i], coordinates[4 * i + 1], coordinates[4 * i + 2],
            coordinates[4 * i + 3]))
    return rectangle_list 
Example 3
Source File: utils.py    From onnxconverter-common with MIT License 6 votes vote down vote up
def convert_to_list(var):
    if isinstance(var, numbers.Real) or isinstance(var, str):
        return [convert_to_python_value(var)]
    elif isinstance(var, np.ndarray) and len(var.shape) == 1:
        return [convert_to_python_value(v) for v in var]
    elif isinstance(var, list):
        flattened = []
        if all(isinstance(ele, np.ndarray) and len(ele.shape) == 1 for ele in var):
            max_classes = max([ele.shape[0] for ele in var])
            flattened_one = []
            for ele in var:
                for i in range(max_classes):
                    if i < ele.shape[0]:
                        flattened_one.append(convert_to_python_value(ele[i]))
                    else:
                        flattened_one.append(convert_to_python_default_value(ele[0]))
            flattened += flattened_one
            return flattened
        elif all(isinstance(v, numbers.Real) or isinstance(v, str) for v in var):
            return [convert_to_python_value(v) for v in var]
        else:
            raise TypeError('Unable to flatten variable')
    else:
        raise TypeError('Unable to flatten variable') 
Example 4
Source File: converters.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def convert_kvp_list_to_dict(kvp_list):
    """Convert a list of 'key=value' strings to a dict.

    :param kvp_list: A list of key value pair strings. For more info on the
        format see; convert_kvp_str_to_list().
    :returns: A dict who's key value pairs are populated by parsing 'kvp_list'.
    :raises InvalidInput: If any of the key value strings are malformed.
    """
    if kvp_list == ['True']:
        # No values were provided (i.e. '--flag-name')
        return {}
    kvp_map = {}
    for kvp_str in kvp_list:
        key, value = convert_kvp_str_to_list(kvp_str)
        kvp_map.setdefault(key, set())
        kvp_map[key].add(value)
    return dict((x, list(y)) for x, y in kvp_map.items()) 
Example 5
Source File: feature_extraction.py    From nlp-architect with Apache License 2.0 6 votes vote down vote up
def convert_string_to_list_of_words(string_list_of_words):
    """
    convert string to list of words

    Args:
        string_list_of_words(str): input sentence

    Returns:
        list(str): vector of words

    """
    string_list_of_words = re.sub(r"[-+.^:,\[\]()]", "", str(string_list_of_words))
    tokens = nltk.word_tokenize(string_list_of_words)

    words_vec = []
    cntr = 0
    for word in tokens:
        words_vec.insert(cntr, word)
        cntr += 1

    return words_vec 
Example 6
Source File: Chemputer_Device_API.py    From ChemputerSoftware with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def convert_list_to_address(self, addr_list, mac=False):
        """
        Converts a list into an address
        Will also convert the decimal mac address into the appropriate hex format

        Args:
            addr_list (List): List containing the elements of the address
            mac (bool): Flag for determining if the address is a mac address

        Returns:
            addr (str): The string representation of the address
        """
        addr = ""
        for elem in addr_list:
            if mac:
                mac_seg = hex(int(elem)).strip("0x").upper()
                addr += (mac_seg + ":")
            else:
                addr += (elem + ".")
        return addr[:-1] 
Example 7
Source File: Chemputer_Device_API.py    From ChemputerSoftware with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def convert_network_address_to_list(self, address, split_delimiter):
        """
        Converts a network address to a python list
        Splits the address based off of a delimiter and adds the elements as string to a list

        Args:
            address (str): Address to convert
            split_delimiter (str): Delimiting character used to split the address ("." for IP addresses, ":" for MAC Addresses)

        Returns:
            addr_split (List): List of strings containing the values of the address minus the delimiting character
        """
        addr_split = address.split(split_delimiter)
        for pos, val in enumerate(addr_split):
            if split_delimiter == ":":
                mac_seg = int(val, 16)
                addr_split[pos] = str(mac_seg)
            else:
                addr_split[pos] = val

        return addr_split 
Example 8
Source File: derive_params.py    From tripleo-common with Apache License 2.0 6 votes vote down vote up
def convert_number_to_range_list(self, num_list):
        num_list.sort()
        range_list = []
        range_min = num_list[0]
        for num in num_list:
            next_val = num + 1
            if next_val not in num_list:
                if range_min != num:
                    range_list.append(str(range_min) + '-' + str(num))
                else:
                    range_list.append(str(range_min))
                next_index = num_list.index(num) + 1
                if next_index < len(num_list):
                    range_min = num_list[next_index]

        # here, range_list is a list of strings
        return range_list 
Example 9
Source File: derive_params.py    From tripleo-common with Apache License 2.0 6 votes vote down vote up
def convert_range_to_number_list(self, range_list):
        num_list = []
        exclude_num_list = []
        try:
            for val in range_list:
                val = val.strip(' ')
                if '^' in val:
                    exclude_num_list.append(int(val[1:]))
                elif '-' in val:
                    split_list = val.split("-")
                    range_min = int(split_list[0])
                    range_max = int(split_list[1])
                    num_list.extend(range(range_min, (range_max + 1)))
                else:
                    num_list.append(int(val))
        except ValueError as exc:
            err_msg = ("Invalid number in input param "
                       "'range_list': %s" % exc)
            raise exception.DeriveParamsError(err_msg)

        # here, num_list is a list of integers
        return [num for num in num_list if num not in exclude_num_list] 
Example 10
Source File: evaluation.py    From IMN-E2E-ABSA with Apache License 2.0 6 votes vote down vote up
def convert_to_list(y_aspect, y_sentiment, mask):
    y_aspect_list = []
    y_sentiment_list = []
    for seq_aspect, seq_sentiment, seq_mask in zip(y_aspect, y_sentiment, mask):
        l_a = []
        l_s = []
        for label_dist_a, label_dist_s, m in zip(seq_aspect, seq_sentiment, seq_mask):
            if m == 0:
                break
            else:
                l_a.append(np.argmax(label_dist_a))
                ### all entries are zeros means that it is a background word or word with conflict sentiment
                ### which are not counted for training AS
                ### also when evaluating, we do not count conflict examples
                if not np.any(label_dist_s):
                    l_s.append(0)
                else:
                    l_s.append(np.argmax(label_dist_s)+1)
        y_aspect_list.append(l_a)
        y_sentiment_list.append(l_s)
    return y_aspect_list, y_sentiment_list 
Example 11
Source File: utils.py    From har2case with Apache License 2.0 6 votes vote down vote up
def convert_list_to_dict(origin_list):
    """ convert HAR data list to mapping

    Args:
        origin_list (list)
            [
                {"name": "v", "value": "1"},
                {"name": "w", "value": "2"}
            ]

    Returns:
        dict:
            {"v": "1", "w": "2"}

    """
    return {
        item["name"]: item.get("value")
        for item in origin_list
    } 
Example 12
Source File: convert_camel.py    From python-bandwidth with MIT License 6 votes vote down vote up
def convert_list_to_snake_case(a):
    """
    Iterates over a list and changes the key values
    from camelCase to snake_case
    :param a: List of dictionaries to convert
    :rtype: list
    :rertuns: list with each key converted to snake_case
    """
    new_arr = []
    for i in a:
        if isinstance(i, list):
            new_arr.append(convert_list_to_snake_case(i))
        elif isinstance(i, dict):
            new_arr.append(convert_dict_to_snake_case(i))
        else:
            new_arr.append(i)
    return new_arr 
Example 13
Source File: mpi.py    From pilot with Apache License 2.0 6 votes vote down vote up
def convertNodeList(self, nodelist):
        try:
            if '[' in nodelist:
                numNames = []
                tmp = nodelist
                preName, numList = tmp.split('[')
                numList,postName = numList.split(']')
                for items in numList.split(","):
                    if not '-' in items:
                        numNames.append(preName + items + postName)
                    else:
                        start, end = items.split('-')
                        numLen = len(start)
                        for i in range(int(start), int(end) + 1):
                            num = str(i).zfill(numLen)
                            numNames.append(preName + str(num) + postName)
                return ','.join(numNames)
            else:
                return nodelist
        except:
            self.__log.debug(traceback.format_exc())
            return nodelist 
Example 14
Source File: attributes.py    From tacker with Apache License 2.0 6 votes vote down vote up
def convert_kvp_list_to_dict(kvp_list):
    """Convert a list of 'key=value' strings to a dict.

    :raises n_exc.InvalidInput: if any of the strings are malformed
                                (e.g. do not contain a key) or if any
                                of the keys appear more than once.
    """
    if kvp_list == ['True']:
        # No values were provided (i.e. '--flag-name')
        return {}
    kvp_map = {}
    for kvp_str in kvp_list:
        key, value = convert_kvp_str_to_list(kvp_str)
        kvp_map.setdefault(key, set())
        kvp_map[key].add(value)
    return dict((x, list(y)) for x, y in (kvp_map).items()) 
Example 15
Source File: checkdata.py    From predictatops with MIT License 6 votes vote down vote up
def convertSiteIDListToUWIList(self):
        """
        Converts the list of wells by to list of wells by UWI. May not work well if your data is structured differently, so look at the actual code.
        """
        if self.input.wells_df is not None:
            wells = self.input.load_wells_file()
        else:
            wells = self.input.wells_df
        if self.wells_with_all_given_tops is not None:
            wells_with_all_given_tops = self.findWellsWithAllTopsGive()
        else:
            wells_with_all_given_tops = self.wells_with_all_given_tops

        new_wells = wells.set_index("SitID").T.to_dict("list")
        for key in new_wells:
            new_wells[key].append(new_wells[key][1].replace("/", "-") + ".LAS")
            #         print("new_wells",new_wells)
            #         print(len(new_wells))

        new_wells_with_all_given_tops = []
        for well in wells_with_all_given_tops:
            new_wells_with_all_given_tops.append(new_wells[well][2])
        self.new_wells_with_all_given_tops = new_wells_with_all_given_tops
        return new_wells_with_all_given_tops 
Example 16
Source File: xml_Utils.py    From warriorframework with Apache License 2.0 6 votes vote down vote up
def convert_xml_to_list_of_dict(file_name):
    """
        Takes xml file path as input and
        converts to list of dictionaries
        Arguments:
            file_name : It takes xml file path as input
        Returns:
            list_of_dict: list of dictionaries where keys
            are tag names and values are respective text of the tag.
    """
    tree = ElementTree.parse(file_name)
    root = tree.getroot()
    list_of_dict = []
    for child in root:
        subchild_dict = OrderedDict()
        for subchild in child:
            subchild_dict[subchild.tag] = subchild.text
        list_of_dict.append(subchild_dict)

    return list_of_dict

#2016/06/22 ymizugaki add begin 
Example 17
Source File: traversal.py    From stolos with Apache License 2.0 6 votes vote down vote up
def convert_dep_grp_to_parsed_list(app_name, dep_group):
    """Convert depends_on data into an expanded list of depends_on dicts, where
    the "all" values have been populated with a list of values determined by
    each parent app_name

    `dep_group` either a dict or a list of dicts in form:
        [{"app_name": ["a", "b"], "testID": "all", ...}]
        --> this input would return
            [{"app_name": ["a"], "testID": ["a's testID values"]},
            {"app_name": ["b"], "testID", ["b's testID values"]}]

    """
    if isinstance(dep_group, cb.TasksConfigBaseMapping):
        dep_group = parse_values(app_name, dep_group)
    elif isinstance(dep_group, cb.TasksConfigBaseSequence):
        dep_group = [
            lst for grp in dep_group for lst in parse_values(app_name, grp)]
    else:
        raise Exception(
            "Expected TasksConfigBaseMapping or TasksConfigBaseSequence."
            " got: %s" % type(dep_group))
    return dep_group 
Example 18
Source File: view_convert_dataset.py    From costar_plan with Apache License 2.0 6 votes vote down vote up
def ConvertImageListToNumpy(data, format='numpy', data_format='NHWC', dtype=np.uint8):
    """ Convert a list of binary jpeg or png files to numpy format.

    # Arguments

    data: a list of binary jpeg images to convert
    format: default 'numpy' returns a 4d numpy array,
        'list' returns a list of 3d numpy arrays
    """
    images = []
    for raw in data:
        img = JpegToNumpy(raw)
        if data_format == 'NCHW':
            img = np.transpose(img, [2, 0, 1])
        images.append(img)
    if format == 'numpy':
        images = np.array(images, dtype=dtype)
    return images 
Example 19
Source File: utils.py    From fake-voice-detection with Apache License 2.0 6 votes vote down vote up
def convert_audio_to_processed_list(input_audio_array_list, filename, dirpath):
    label_name = filename.split('_')[-1].split('.')[0]
    out_list = []
    if (label_name == 'spoof'):
        audio_array_list = [input_audio_array_list[0]]
        choose_random_one_ind = np.random.choice(np.arange(1,len(input_audio_array_list)))
        audio_array_list.append(input_audio_array_list[choose_random_one_ind])
        label = 0
    elif (label_name == 'bonafide') or ('target' in label_name):
        audio_array_list = input_audio_array_list
        label = 1
    else:
        audio_array_list = [input_audio_array_list[0]]
        label = None

    for audio_array in audio_array_list:
        trim_audio_array, index = librosa.effects.trim(audio_array)
        mel_spec_array = melspectrogram(trim_audio_array, hparams=hparams).T
        # mel_spec_array = librosa.feature.melspectrogram(y=trim_audio_array, sr=sample_rate, n_mels=model_params['num_freq_bin']).T
        if label is None:
            print(f"Removing {filename} since it does not have label")
            os.remove(os.path.join(dirpath, 'flac', filename))
        out_list.append([mel_spec_array, label])
    return out_list 
Example 20
Source File: add_two_numbers.py    From algorithms with MIT License 6 votes vote down vote up
def convert_to_list(number: int) -> Node:
    """
        converts a positive integer into a (reversed) linked list.
        for example: give 112
        result 2 -> 1 -> 1
    """
    if number >= 0:
        head = Node(0)
        current = head
        remainder = number % 10
        quotient = number // 10

        while quotient != 0:
            current.next = Node(remainder)
            current = current.next
            remainder = quotient % 10
            quotient //= 10
        current.next = Node(remainder)
        return head.next
    else:
        print("number must be positive!") 
Example 21
Source File: sct_maths.py    From spinalcordtoolbox with MIT License 6 votes vote down vote up
def convert_list_str(string_list, type='int'):
    """
    Receive a string and then converts it into a list of selected type.
    Example: "2,2,3" --> [2, 2, 3]
    :param string_list: List of comma-separated string
    :param type: string: int, float
    :return:
    """
    new_type_list = (string_list).split(",")
    for inew_type_list, ele in enumerate(new_type_list):
        if type is "int":
            new_type_list[inew_type_list] = int(ele)
        elif type is "float":
            new_type_list[inew_type_list] = float(ele)

    return new_type_list 
Example 22
Source File: prf_utils.py    From raster-deep-learning with Apache License 2.0 6 votes vote down vote up
def convert_bounding_boxes_to_coord_list(bounding_boxes):
    """
    convert bounding box numpy array to python list of point arrays
    :param bounding_boxes: numpy array of shape [n, 4]
    :return: python array of point numpy arrays, each point array is in shape [4,2]
    """
    num_bounding_boxes = bounding_boxes.shape[0]
    bounding_box_coord_list = []
    for i in range(num_bounding_boxes):
        coord_array = np.empty(shape=(4, 2), dtype=np.float)
        coord_array[0][0] = bounding_boxes[i][0]
        coord_array[0][1] = bounding_boxes[i][1]

        coord_array[1][0] = bounding_boxes[i][0]
        coord_array[1][1] = bounding_boxes[i][3]

        coord_array[2][0] = bounding_boxes[i][2]
        coord_array[2][1] = bounding_boxes[i][3]

        coord_array[3][0] = bounding_boxes[i][2]
        coord_array[3][1] = bounding_boxes[i][1]

        bounding_box_coord_list.append(coord_array)

    return bounding_box_coord_list 
Example 23
Source File: score.py    From xView1_baseline with Apache License 2.0 6 votes vote down vote up
def convert_to_rectangle_list(coordinates):
  """
    Converts a list of coordinates to a list of rectangles

    Args:
        coordinates: a flattened list of bounding box coordinates in format
          (xmin,ymin,xmax,ymax)

    Outputs:
      A list of rectangles

  """
  rectangle_list = []
  number_of_rects = int(len(coordinates) / 4)
  for i in range(number_of_rects):
    rectangle_list.append(Rectangle(
        coordinates[4 * i], coordinates[4 * i + 1], coordinates[4 * i + 2],
        coordinates[4 * i + 3]))
  return rectangle_list 
Example 24
Source File: General.py    From Scrummage with GNU General Public License v3.0 6 votes vote down vote up
def Convert_to_List(String):

    try:

        if ', ' in String:
            List = String.split(', ')
            return List

        elif ',' in String:
            List = String.split(',')
            return List

        else:
            List = [String]
            return List

    except:
        logging.warning(f"{Date()} General Library - Failed to convert the provided query to a list.") 
Example 25
Source File: gibbsMethod.py    From orbitdeterminator with MIT License 6 votes vote down vote up
def convert_list(self, vec):
        '''
        Type casts the input data for the ease of use.

        Converts the values of the input list with string datatype into float
        for the ease of furthur computation.

        Args:
            vec (list): input vector

        Returns:
            list: vector converted to float values
        '''
        a = 0.0
        b = 0.0
        c = 0.0
        try:
            a = float(vec[1])
            b = float(vec[2])
            c = float(vec[3])
        except ValueError:
            print("Double check file format!")
        return([a, b, c]) 
Example 26
Source File: metric_learning_test.py    From tf-slim with Apache License 2.0 6 votes vote down vote up
def convert_to_list_of_sparse_tensor(np_matrix):
  list_of_sparse_tensors = []
  nrows, ncols = np_matrix.shape
  for i in range(nrows):
    sp_indices = []
    for j in range(ncols):
      if np_matrix[i][j] == 1:
        sp_indices.append([j])

    num_non_zeros = len(sp_indices)
    list_of_sparse_tensors.append(sparse_tensor.SparseTensor(
        indices=np.array(sp_indices),
        values=np.ones((num_non_zeros,)),
        dense_shape=np.array([ncols,])))

  return list_of_sparse_tensors 
Example 27
Source File: mazeGen.py    From omnitool with MIT License 6 votes vote down vote up
def convertList(self, tilelist):
        tileColorDict = dict([(v,k) for (k,v) in clib.data.items()])
        wallColorDict = dict([(v,k) for (k,v) in clib.walldata.items()])
        tiles = []
        for col in tilelist:
            column = []
            for tile in col:
                tile = (tile[0],tile[1],tile[2])
                if tile in tileColorDict:
                    if db.ntiles[db.tiles[tileColorDict[tile]]] == 130:
                        column.append((1, None, 0, None, 0))
                        self.mapTile = 1
                    else:
                        column.append(((db.ntiles[db.tiles[tileColorDict[tile]]]), None, 0, None, 0))
                        self.mapTile = (db.ntiles[db.tiles[tileColorDict[tile]]])
                else:
                    column.append((None, (db.nwalls[db.walls[wallColorDict[tile]]]), 0, None, 0))
                    self.mapWall = (db.nwalls[db.walls[wallColorDict[tile]]])
            tiles.append(column)
        return tiles 
Example 28
Source File: datamodels.py    From JapaneseTokenizers with MIT License 6 votes vote down vote up
def convert_list_object(self,
                            is_denormalize=True,
                            func_denormalizer=denormalize_text):
        # type: (bool,Callable[[str],str])->List[Union[str, Tuple[str,...]]]
        """* What you can do
        - You extract string object from TokenizedResult object

        * Args
        - is_denormalize: boolen object. True; it makes denormalize string
        - func_denormalizer: callable object. de-normalization function.
        """
        sentence_in_list_obj = [
            self.__extend_token_object(token_object,is_denormalize,func_denormalizer)
            for token_object
            in self.tokenized_objects
        ]

        return sentence_in_list_obj 
Example 29
Source File: wwSVG.py    From WonderPy with MIT License 6 votes vote down vote up
def convert_path_to_list_of_lists_of_robot_coords(path, units_per_point):
        """
        converts all the sub-paths in the svg path into a list of lists of points.
        each sub-list represents a continuous sub-path.
        See convert_to_list_of_lists_of_robot_points() for more discussion.
        """
        ret = []
        for sp in path.continuous_subpaths():
            robot_points = []
            num_points = int(math.ceil(sp.length() / units_per_point)) + 1
            for n in xrange(num_points):
                t = float(n) / float(num_points - 1)
                robot_points.append(WWSVG.convert_svg_point_to_robot_point(sp.point(t)))

            ret.append(robot_points)

        return ret 
Example 30
Source File: zun_services.py    From zun with Apache License 2.0 6 votes vote down vote up
def convert_db_rec_list_to_collection(servicegroup_api,
                                          rpc_hsvcs, **kwargs):
        collection = ZunServiceCollection()
        collection.services = []
        for p in rpc_hsvcs:
            service = p.as_dict()
            alive = servicegroup_api.service_is_up(p)
            state = 'up' if alive else 'down'
            service['state'] = state
            service = view.format_service(service)
            collection.services.append(service)
            if not service['availability_zone']:
                service['availability_zone'] = CONF.default_availability_zone
        next = collection.get_next(limit=None, url=None, **kwargs)
        if next is not None:
            collection.next = next
        return collection 
Example 31
Source File: utils.py    From httprunner with Apache License 2.0 6 votes vote down vote up
def convert_list_to_dict(origin_list):
    """ convert HAR data list to mapping

    Args:
        origin_list (list)
            [
                {"name": "v", "value": "1"},
                {"name": "w", "value": "2"}
            ]

    Returns:
        dict:
            {"v": "1", "w": "2"}

    """
    return {item["name"]: item.get("value") for item in origin_list} 
Example 32
Source File: config.py    From scout_apm_python with MIT License 5 votes vote down vote up
def convert_to_list(value):
    if isinstance(value, list):
        return value
    if isinstance(value, tuple):
        return list(value)
    if isinstance(value, string_type):
        # Split on commas
        return [item.strip() for item in value.split(",") if item]
    # Unknown type - default to empty?
    return [] 
Example 33
Source File: env_spec.py    From object_detection_with_tensorflow with MIT License 5 votes vote down vote up
def convert_obs_to_list(self, obs):
    if len(self.obs_dims) == 1:
      return [obs]
    else:
      return list(obs) 
Example 34
Source File: ExonArrayEnsemblRules.py    From altanalyze with Apache License 2.0 5 votes vote down vote up
def convertListString(list,delimiter):
    list2 = []; list = unique.unique(list); list.sort()
    for i in list:
        if len(str(i))>0: list2.append(str(i))
    str_values = string.join(list2,delimiter)
    return str_values 
Example 35
Source File: exceptions.py    From easypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_traceback_to_list(tb):
    # convert to list of dictionaries that contain file, line_no and function
    traceback_list = [dict(file=file, line_no=line_no, function=function)
                      for file, line_no, function, _ in traceback.extract_tb(tb)]
    return traceback_list 
Example 36
Source File: minimal_ssz.py    From research with MIT License 5 votes vote down vote up
def convert_to_list(obj):
    if isinstance(obj, (list, Vector)):
        return list(obj)
    elif isinstance(obj, bytes):
        return obj
    elif hasattr(obj.__class__, 'fields'):
        return [getattr(obj, field) for field in list(obj.__class__.fields.keys())]
    elif isinstance(obj, (int, bool)):
        return [obj]
    else:
        raise Exception("Type not recognized") 
Example 37
Source File: waypointer.py    From CAL with MIT License 5 votes vote down vote up
def convert_list_of_nodes_to_pixel(self, route):
        map_points = []
        for point in route:
            map_point = self._converter.convert_to_pixel([int(point[0]), int(point[1])])

            map_points.append(map_point)

        return map_points 
Example 38
Source File: utils.py    From edx-enterprise with GNU Affero General Public License v3.0 5 votes vote down vote up
def convert_comma_separated_string_to_list(comma_separated_string):
    """
    Convert the comma separated string to a valid list.
    """
    return list(set(item.strip() for item in comma_separated_string.split(",") if item.strip())) 
Example 39
Source File: utils_nms.py    From cvToolkit with MIT License 5 votes vote down vote up
def convert_blobs_list_to_blob_list(joint_blobs_list):
    joint_blob_list = []
    for joint_blobs in joint_blobs_list:
        for joint_blob in joint_blobs:
            joint_blob_list.append(joint_blob)
    return joint_blob_list 
Example 40
Source File: string_helper.py    From keyphrase-gan with MIT License 5 votes vote down vote up
def convert_list_to_kphs(keyphrases):
    total = []
    one_list = []
    for i,keyphrase in enumerate(keyphrases):
#        one_keyphrase = []
#        mapper = map(keyphrase,str)
#        mapper = ' '.join(mapper)
#        print(mapper)
        one_keyphrase = []
        for i,word_keyphrase in enumerate(keyphrase):
            #print(word_keyphrase)
            if int(word_keyphrase.item()) == 2:
                if one_keyphrase != []:
                    one_list.append(one_keyphrase) 
                break                
            elif int(word_keyphrase.item()) != 4 and int(word_keyphrase.item()) != 5:
#                print("fdedh")
                one_keyphrase.append(int(word_keyphrase.item()))
            else:
                if one_keyphrase != []:
                    one_list.append(one_keyphrase) 
                one_keyphrase = []
        total.append(one_list)
        one_list = []
    #print(total[0])
    return total 
Example 41
Source File: evaluate.py    From keyphrase-gan with MIT License 5 votes vote down vote up
def convert_to_string_list(kph,idx2word):
    s = []
    for kps in kph:
        s.append(idx2word[kps])
    return s 
Example 42
Source File: utils.py    From traces with MIT License 5 votes vote down vote up
def convert_args_to_list(args):
    """Convert all iterable pairs of inputs into a list of list"""
    list_of_pairs = []
    if len(args) == 0:
        return []

    if any(isinstance(arg, (list, tuple)) for arg in args):
        # Domain([[1, 4]])
        # Domain([(1, 4)])
        # Domain([(1, 4), (5, 8)])
        # Domain([[1, 4], [5, 8]])
        if len(args) == 1 and any(
            isinstance(arg, (list, tuple)) for arg in args[0]
        ):
            for item in args[0]:
                list_of_pairs.append(list(item))
        else:
            # Domain([1, 4])
            # Domain((1, 4))
            # Domain((1, 4), (5, 8))
            # Domain([1, 4], [5, 8])
            for item in args:
                list_of_pairs.append(list(item))
    else:
        # Domain(1, 2)
        if len(args) == 2:
            list_of_pairs.append(list(args))
        else:
            msg = "The argument type is invalid. {}".format(args)
            raise TypeError(msg)

    return list_of_pairs 
Example 43
Source File: tv_grab_IO.py    From tvgrabpyAPI with GNU General Public License v3.0 5 votes vote down vote up
def convert_list(self, val):
        ret_val = []
        val = val.split(';')
        for k in val:
            ret_val.append(k)

        return ret_val 
Example 44
Source File: hrefs.py    From barbican with Apache License 2.0 5 votes vote down vote up
def convert_list_to_href(resources_name, offset, limit):
    """Supports pretty output of paged-list hrefs.

    Convert the offset/limit info to a HATEOAS-style href
    suitable for use in a list navigation paging interface.
    """
    resource = '{0}?limit={1}&offset={2}'.format(resources_name, limit,
                                                 offset)
    return utils.hostname_for_refs(resource=resource) 
Example 45
Source File: train_arrange.py    From MAgent with MIT License 5 votes vote down vote up
def clean_pos_set_convert_to_list(pos_set, pos_list):
    for v in pos_list:
        if v in pos_set:
            pos_set.remove(v)
    return list(pos_set) 
Example 46
Source File: visualize.py    From ludwig with Apache License 2.0 5 votes vote down vote up
def convert_to_list(item):
    """If item is not list class instance or None put inside a list.

    :param item: object to be checked and converted
    :return: original item if it is a list instance or list containing the item.
    """
    return item if item is None or isinstance(item, list) else [item] 
Example 47
Source File: collectsphere.py    From collectsphere with MIT License 5 votes vote down vote up
def convert_folder_tree_to_list(folder_tree):
    result = list()
    for leaf in folder_tree:
        if leaf._wsdlName == "Folder":
            result.extend(convert_folder_tree_to_list(leaf.childEntity))
        else:
            result.append(leaf)
    return result 
Example 48
Source File: fozu.py    From DockerMonitor with Apache License 2.0 5 votes vote down vote up
def convert_user_info_list_to_dict(user_info_list):
    user_info_dict = {}
    for user_info in user_info_list:
        user_info_dict[user_info['username']] = user_info

    return user_info_dict 
Example 49
Source File: utils.py    From LDA_RecEngine with Apache License 2.0 5 votes vote down vote up
def convertListToDict(anylist):
    convertedDict = {}
    for pair in anylist:
        topic = pair[0]
        weight = pair[1]
        convertedDict[topic] = weight
    return convertedDict 
Example 50
Source File: converter.py    From graphene-django with MIT License 5 votes vote down vote up
def convert_postgres_array_to_list(field, registry=None):
    inner_type = convert_django_field(field.base_field)
    if not isinstance(inner_type, (List, NonNull)):
        inner_type = (
            NonNull(type(inner_type))
            if inner_type.kwargs["required"]
            else type(inner_type)
        )
    return List(inner_type, description=field.help_text, required=not field.null) 
Example 51
Source File: converter.py    From graphene-django with MIT License 5 votes vote down vote up
def convert_field_to_list_or_connection(field, registry=None):
    model = field.related_model

    def dynamic_type():
        _type = registry.get_type_for_model(model)
        if not _type:
            return

        description = (
            field.help_text
            if isinstance(field, models.ManyToManyField)
            else field.field.help_text
        )

        # If there is a connection, we should transform the field
        # into a DjangoConnectionField
        if _type._meta.connection:
            # Use a DjangoFilterConnectionField if there are
            # defined filter_fields or a filterset_class in the
            # DjangoObjectType Meta
            if _type._meta.filter_fields or _type._meta.filterset_class:
                from .filter.fields import DjangoFilterConnectionField

                return DjangoFilterConnectionField(
                    _type, required=True, description=description
                )

            return DjangoConnectionField(_type, required=True, description=description)

        return DjangoListField(
            _type,
            required=True,  # A Set is always returned, never None.
            description=description,
        )

    return Dynamic(dynamic_type) 
Example 52
Source File: smgr_client_utils.py    From contrail-server-manager with Apache License 2.0 5 votes vote down vote up
def convert_json_to_list(obj, json_resp):
        return_list = list()
        data_dict = dict(json_resp)
        if len(data_dict.keys()) == 1 and obj in ['server', 'cluster', 'image', 'mac', 'ip']:
            key, value = data_dict.popitem()
            dict_list = eval(str(value))
            for d in dict_list:
                d = dict(d)
                id_key, id_value = d.popitem()
                return_list.append(id_value)
        elif obj == 'tag':
            for key in data_dict:
                return_list.append(data_dict[key])
        return return_list 
Example 53
Source File: material.py    From cats-blender-plugin with MIT License 5 votes vote down vote up
def get_convert_list(self):
        images_to_convert = []
        for image in bpy.data.images:
            # Get texture path and check if the file should be converted
            tex_path = bpy.path.abspath(image.filepath)
            if tex_path.endswith(('.png', '.spa', '.sph')) or not os.path.isfile(tex_path):
                print('IGNORED:', image.name, tex_path)
                continue
            images_to_convert.append(image)
        return images_to_convert 
Example 54
Source File: attributes.py    From tacker with Apache License 2.0 5 votes vote down vote up
def convert_to_list(data):
    if data is None:
        return []
    elif hasattr(data, '__iter__') and not isinstance(data, six.string_types):
        return list(data)
    else:
        return [data] 
Example 55
Source File: attributes.py    From tacker with Apache License 2.0 5 votes vote down vote up
def convert_kvp_str_to_list(data):
    """Convert a value of the form 'key=value' to ['key', 'value'].

    :raises n_exc.InvalidInput: if any of the strings are malformed
                                (e.g. do not contain a key).
    """
    kvp = [x.strip() for x in data.split('=', 1)]
    if len(kvp) == 2 and kvp[0]:
        return kvp
    msg = _("'%s' is not of the form <key>=[value]") % data
    raise n_exc.InvalidInput(error_message=msg) 
Example 56
Source File: vmtoken.py    From neo-boa with MIT License 5 votes vote down vote up
def convert_built_in_list(self, pytoken):
        """

        :param pytoken:
        """
        lenfound = False
        self.convert1(VMOp.NEWARRAY, pytoken) 
Example 57
Source File: helpers.py    From MsfWrapper with MIT License 5 votes vote down vote up
def convert_dict_to_sorted_list(dict):
    """Converts a dictionary object into a sorted-by-key list of tuples"""
    lst = list(dict.items())
    lst.sort()
    return lst 
Example 58
Source File: generic_helper.py    From py_stringsimjoin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_dataframe_to_list(table, join_attr_index,
                              remove_null=True):
    table_list = []
    for row in table.itertuples(index=False):
        if remove_null and pd.isnull(row[join_attr_index]):
            continue
        table_list.append(tuple(row))
    return table_list 
Example 59
Source File: namespace.py    From jx-sqlite with Mozilla Public License 2.0 5 votes vote down vote up
def convert_list(operator, operand):
    if operand==None:
        return None
    elif is_data(operand):
        return operator(operand)
    else:
        return map(operator, operand)