Map MXNet's Tile operator attributes to onnx's Tile
    operator and return the created node.
506799
def convert_tile(node, **kwargs):
    
    name, input_nodes, attrs = get_inputs(node, kwargs)

    reps_list = convert_string_to_list(attrs["reps"])

    initializer = kwargs["initializer"]
    reps_shape_np = np.array(reps_list, dtype='int64')
    data_type = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[reps_shape_np.dtype]
    dims = np.shape(reps_shape_np)

    output_shape_name = "reps_attr_tensor" + str(kwargs["idx"])
    tensor_node = onnx.helper.make_tensor_value_info(output_shape_name, data_type, dims)

    initializer.append(
        onnx.helper.make_tensor(
            name=output_shape_name,
            data_type=data_type,
            dims=dims,
            vals=reps_list,
            raw=False,
        )
    )

    input_nodes.append(output_shape_name)
    tile_node = onnx.helper.make_node(
        "Tile",
        input_nodes,
        [name],
        name=name
    )

    return [tensor_node, tile_node]
342024
void build(int nodeOffset, GraphMeshData graphData, List<int[]> connections) {
		for (int n = 0; n < connections.size(); n++) {
			int[] nodeConnections = connections.get(n);
			MeshData tile = graphData.getTile(n);
			Poly node = graphData.getNode(n);
			for (int connection : nodeConnections) {
				MeshData neighbourTile = graphData.getTile(connection - nodeOffset);
				if (neighbourTile != tile) {
					buildExternalLink(tile, node, neighbourTile);
				} else {
					Poly neighbour = graphData.getNode(connection - nodeOffset);
					buildInternalLink(tile, node, neighbourTile, neighbour);
				}
			}
		}
	}
620755
@SuppressWarnings("rawtypes")
    private Map.Entry getMapEntry(Node node) {
        Object value = null;
        String keyName = node.getLocalName();
        XmlMapEntry xmlMapEntry = this.mapSpecification.get(keyName);
        switch (node.getNodeType()) {
            case Node.ATTRIBUTE_NODE:
                value = node.getNodeValue();
                break;
            case Node.ELEMENT_NODE: {
                if (xmlMapEntry == null) {
                    value = new NodeArray(node.getChildNodes());
                } else {
                    XmlMapFacet valueFacet = xmlMapEntry.getValue();
                    switch (valueFacet.getType()) {
                        case ELEMENT:
                            value = keyName;
                            break;
                        case CONTENT: {
                            NodeList nodeList = node.getChildNodes();
                            if (nodeList.getLength() > 0) {
                                value = new NodeArray(nodeList);
                            }
                        }
                            break;
                        case ATTRIBUTE: {
                            NamedNodeMap attributes = node.getAttributes();
                            Node attribute = attributes.getNamedItem(valueFacet.getName());
                            if (attribute != null) {
                                value = attribute.getNodeValue();
                            }
                        }
                            break;
                        default:
                            throw new IllegalStateException();
                    }
                    XmlMapFacet keyFacet = xmlMapEntry.getKey();
                    switch (keyFacet.getType()) {
                        case ELEMENT:
                            break;
                        case CONTENT: {
                            NodeList nodeList = node.getChildNodes();
                            if (nodeList.getLength() > 0) {
                                keyName = getStringValue((Node) nodeList.item(0));
                            } else {
                                keyName = null;
                            }
                        }
                            break;
                        case ATTRIBUTE: {
                            NamedNodeMap attributes = node.getAttributes();
                            Node attribute = attributes.getNamedItem(keyFacet.getName());
                            if (attribute != null) {
                                keyName = attribute.getNodeValue();
                            } else {
                                keyName = null;
                            }
                            break;
                        }
                        default:
                            throw new IllegalStateException();
                    }
                }
            }
        }
        if (keyName == null) {
            return null;
        } else {
            final Object _key = keyName;
            final Object _value = value;
            return new Map.Entry() {

                @Override
                public Object getKey() {
                    return _key;
                }

                @Override
                public Object getValue() {
                    return _value;
                }

                @Override
                public Object setValue(Object object) {
                    return null;
                }

            };
        }
    }
1366272
def unsqueeze(attrs, inputs, cls):
    """"""
    # MXNet can only add one axis at a time.
    mxnet_op = inputs[0]
    for axis in attrs["axes"]:
        mxnet_op = symbol.expand_dims(mxnet_op, axis=axis)

    return mxnet_op, attrs, inputs
532402
def convert_softmax(node, **kwargs):
    
    name, input_nodes, attrs = get_inputs(node, kwargs)

    axis = int(attrs.get("axis", -1))

    softmax_node = onnx.helper.make_node(
        "Softmax",
        input_nodes,
        [name],
        axis=axis,
        name=name
    )

    return [softmax_node]
716277
def _gen_net_xml(name,
                 bridge,
                 forward,
                 vport,
                 tag=None):
    '''
    
    '''
    context = {
        'name': name,
        'bridge': bridge,
        'forward': forward,
        'vport': vport,
        'tag': tag,
    }
    fn_ = 'libvirt_network.jinja'
    try:
        template = JINJA.get_template(fn_)
    except jinja2.exceptions.TemplateNotFound:
        log.error('Could not load template %s', fn_)
        return ''
    return template.render(**context)
443379
def get_tile_properties(self, x, y, layer):
        
        try:
            assert (x >= 0 and y >= 0 and layer >= 0)
        except AssertionError:
            raise ValueError

        try:
            gid = self.layers[int(layer)].data[int(y)][int(x)]
        except (IndexError, ValueError):
            msg = "Coords: ({0},{1}) in layer {2} is invalid."
            logger.debug(msg.format(x, y, layer))
            raise Exception

        else:
            try:
                return self.tile_properties[gid]
            except (IndexError, ValueError):
                msg = "Coords: ({0},{1}) in layer {2} has invalid GID: {3}"
                logger.debug(msg.format(x, y, layer, gid))
                raise Exception
            except KeyError:
                return None
1069974
def nodes_map(self):
        
        dct = dict()
        for node in self.nodes.values():
            cls = next(base for base in getmro(node.__class__) if "__tablename__" in base.__dict__)
            key = getattr(cls, "__alias__", underscore(cls.__name__))
            dct.setdefault(key, []).append(node)
        return dct
249844
def convert_transpose(node, **kwargs):
    
    name, input_nodes, attrs = get_inputs(node, kwargs)

    axes = attrs.get("axes", ())
    if axes:
        axes = tuple(map(int, re.findall(r'\d+', axes)))

        transpose_node = onnx.helper.make_node(
            "Transpose",
            input_nodes,
            [name],
            perm=axes,
            name=name
        )
    else:
        transpose_node = onnx.helper.make_node(
            "Transpose",
            input_nodes,
            [name],
            name=name
        )

    return [transpose_node]
1372357
def convert_reshape(node, **kwargs):
    
    name, input_nodes, attrs = get_inputs(node, kwargs)

    output_shape_list = convert_string_to_list(attrs["shape"])

    initializer = kwargs["initializer"]
    output_shape_np = np.array(output_shape_list, dtype='int64')
    data_type = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[output_shape_np.dtype]
    dims = np.shape(output_shape_np)

    output_shape_name = "reshape_attr_tensor" + str(kwargs["idx"])
    tensor_node = onnx.helper.make_tensor_value_info(output_shape_name, data_type, dims)

    initializer.append(
        onnx.helper.make_tensor(
            name=output_shape_name,
            data_type=data_type,
            dims=dims,
            vals=output_shape_list,
            raw=False,
        )
    )

    input_nodes.append(output_shape_name)

    not_supported_shape = [-2, -3, -4]

    for val in output_shape_list:
        if val in not_supported_shape:
            raise AttributeError("Reshape: Shape value not supported in ONNX", val)

    reshape_node = onnx.helper.make_node(
        "Reshape",
        input_nodes,
        [name],
        name=name
    )

    return [tensor_node, reshape_node]
759983
def get_tile_properties_by_layer(self, layer):
        
        try:
            assert (int(layer) >= 0)
            layer = int(layer)
        except (TypeError, AssertionError):
            msg = "Layer must be a positive integer.  Got {0} instead."
            logger.debug(msg.format(type(layer)))
            raise ValueError

        p = product(range(self.width), range(self.height))
        layergids = set(self.layers[layer].data[y][x] for x, y in p)

        for gid in layergids:
            try:
                yield gid, self.tile_properties[gid]
            except KeyError:
                continue
138044
def get_nodekey(self, token, types=types, coll_abc=collections.abc):
        '''
        '''
        # Check the mro.
        for mro_type in type(token).__mro__:
            yield mro_type.__name__

        # Check for callability.
        if callable(token):
            yield 'callable'

        # Check for the collections.abc types.
        abc_types = (
            'Hashable',
            'Iterable',
            'Iterator',
            'Sized',
            'Container',
            'Callable',
            'Set',
            'MutableSet',
            'Mapping',
            'MutableMapping',
            'MappingView',
            'KeysView',
            'ItemsView',
            'ValuesView',
            'Sequence',
            'MutableSequence',
            'ByteString')
        for type_name in abc_types:
            type_ = getattr(coll_abc, type_name, None)
            if type_ is None:
                continue
            if isinstance(token, type_):
                yield type_name

        # Check for the standard interpreter types in the types module.
        interp_types = (
            'BuiltinFunctionType',
            'BuiltinMethodType',
            'CodeType',
            'DynamicClassAttribute',
            'FrameType',
            'FunctionType',
            'GeneratorType',
            'GetSetDescriptorType',
            'LambdaType',
            'MappingProxyType',
            'MemberDescriptorType',
            'MethodType',
            'ModuleType',
            'SimpleNamespace',
            'TracebackType')
        for type_name in interp_types:
            type_ = getattr(types, type_name, None)
            if type_ is None:
                continue
            if isinstance(token, type_):
                yield type_name
382455
private static @Nonnull Map<String, String> attributesToMap(NamedNodeMap nnm) {
        return IntStream.range(0, nnm.getLength())
                    .mapToObj(nnm::item)
                    .collect(toMap(Node::getNodeName, Node::getNodeValue));
    }
677850
protected void batchNN(AbstractRStarTreeNode<?, ?> node, Map<DBID, KNNHeap> knnLists) {
    if(node.isLeaf()) {
      for(int i = 0; i < node.getNumEntries(); i++) {
        SpatialEntry p = node.getEntry(i);
        for(Entry<DBID, KNNHeap> ent : knnLists.entrySet()) {
          final DBID q = ent.getKey();
          final KNNHeap knns_q = ent.getValue();
          double knn_q_maxDist = knns_q.getKNNDistance();

          DBID pid = ((LeafEntry) p).getDBID();
          // FIXME: objects are NOT accessible by DBID in a plain R-tree
          // context!
          double dist_pq = distanceFunction.distance(relation.get(pid), relation.get(q));
          tree.statistics.countDistanceCalculation();
          if(dist_pq <= knn_q_maxDist) {
            knns_q.insert(dist_pq, pid);
          }
        }
      }
    }
    else {
      ModifiableDBIDs ids = DBIDUtil.newArray(knnLists.size());
      for(DBID id : knnLists.keySet()) {
        ids.add(id);
      }
      List<DoubleDistanceEntry> entries = getSortedEntries(node, ids);
      for(DoubleDistanceEntry distEntry : entries) {
        double minDist = distEntry.distance;
        for(Entry<DBID, KNNHeap> ent : knnLists.entrySet()) {
          final KNNHeap knns_q = ent.getValue();
          double knn_q_maxDist = knns_q.getKNNDistance();

          if(minDist <= knn_q_maxDist) {
            SpatialEntry entry = distEntry.entry;
            AbstractRStarTreeNode<?, ?> child = tree.getNode(((DirectoryEntry) entry).getPageID());
            batchNN(child, knnLists);
            break;
          }
        }
      }
    }
  }
401498
def cx_to_networkx(cx):
    """"""
    graph = networkx.MultiDiGraph()
    for node_entry in get_aspect(cx, 'nodes'):
        id = node_entry['@id']
        attrs = get_attributes(get_aspect(cx, 'nodeAttributes'), id)
        attrs['n'] = node_entry['n']
        graph.add_node(id, **attrs)
    for edge_entry in get_aspect(cx, 'edges'):
        id = edge_entry['@id']
        attrs = get_attributes(get_aspect(cx, 'edgeAttributes'), id)
        attrs['i'] = edge_entry['i']
        graph.add_edge(edge_entry['s'], edge_entry['t'], key=id, **attrs)
    return graph
1037251
def _get_vector_tile(self, x_tile, y_tile, z_tile):
        """"""
        cache_file = "mapscache/{}.{}.{}.json".format(z_tile, x_tile, y_tile)
        if cache_file not in self._tiles:
            if os.path.isfile(cache_file):
                with open(cache_file, 'rb') as f:
                    tile = json.loads(f.read().decode('utf-8'))
            else:
                url = _VECTOR_URL.format(z_tile, x_tile, y_tile, _KEY)
                data = requests.get(url).content
                try:
                    tile = mapbox_vector_tile.decode(data)
                    with open(cache_file, mode='w') as f:
                        json.dump(literal_eval(repr(tile)), f)
                except DecodeError:
                    tile = None
            if tile:
                self._tiles[cache_file] = [x_tile, y_tile, z_tile, tile, False]
                if len(self._tiles) > _CACHE_SIZE:
                    self._tiles.popitem(False)
                self._screen.force_update()
575500
function getOperator() {
  const type = NodeType.OperatorType;
  const token = tokens[pos];
  const line = token.ln;
  const column = token.col;
  const content = token.value;

  pos++;

  return newNode(type, content, line, column);
}