python – Graph implementation – representing a subway

I’m new to Python and I have a college work that requires to use the graph, vertex and edge concepts, but I’m having some problems with the implementation.

The works requires to:

a) In Vertex, create a Station subclass, to contain the station id and the position, in decimal degrees, of the location of the object on the earth’s surface.

   class Vertex:
__slots__ = "_element"

def __init__(self, element):
    self._element = element

def elem(self):
    return self._element

def __str__(self):
    return str(self._element)

def __eq__(self, other):
    if isinstance(other, Vertex):
        return self._element == other.elem()
    return False

def __hash__(self):
    '''Referência de memória (usada por causa das keys dos dicionários)'''
    return hash(id(self))


class Station(Vertex):


def __init__(self, id_idstation, latitude, longitude, element):
    super().__init__(element)
    self._idstation = id_idstation
    self._latitude = latitude
    self._longitude = longitude


def __repr__(self):
    return "(({0},{1},{2},{3}".format(self._idstation, self._latitude,self._longitude, self._element)

def get_name(self):
    return self._element

def get_id(self):
    return self._idstation

def get_coordinates(self):
    return (self._latitude, self._longitude)

@property
def idstation(self):
    return self._idstation

b) Create a list of Station objects from the dataset in lisbon.stations.csv.

c) Under Edge, create an Edge_line subclass, to contain the line that the connection is part of.

 class Edge:
__slots__ = "_origem", "_destino", "_peso"

def __init__(self, origem, destino, peso=None):
    self._origem = origem
    self._destino = destino
    self._peso = peso

def origem(self):
    return self._origem

def destino(self):
    return self._destino

def __str__(self):
    return f"Edge: ({self._origem}, {self._destino}"

def __eq__(self, other):
    if isinstance(other, Edge):
        return self._origem == other._origem and self._destino == other._destino and self._peso == other._peso
    return False

def endpoints(self):
    return self._origem, self._destino

def opposite(self, v):
    '''return self._destino if v is self._origem else self._origem'''
    if v is self._origem:  # verifica a instância
        return self._destino
    else:
        return self._origem

def elem(self):
    return self._peso

def __hash__(self):
    return hash((id(self._origem), id(self._destino)))

@property
def origin(self):
    return self._origem

@property
def destination(self):
    return self._destino

class Edge_Line(Edge):


def __init__(self, origem, destino, line):
    super().__init__(origem, destino)
    self._line = line

@property
def get_line(self):
    return self._line

@property
def get_origem(self):
    return self._origem

@property
def get_destino(self):
    return self._destino

def __repr__(self):
    return "(({0},{1},{2}".format(self._origem, self._destino, self._line)

d) Create a list of “Edge_line” objects from the same data set.

e) Create a Graph structure.

f) Create a procedure/method to be able to view the network.

Example:

Import myplotlib.myplot as plt 
fig = plt.figure() 
plt.line(x,y, c=color)  

To view the connections where x and y are lists with the positions on the map of the end stations of an Edge; Run as many times as the number of connections.

Encode the color as shown in the table in lisbon.lines.csv.

Below is my code at the moment. I would appreciate if someone can review the code.

import csv
import matplotlib.pyplot as plt

class GraphList:


def __init__(self, directed=False):  # não dirigido
    self._outgoing = {}  # de onde se parte
    self._incoming = {} if directed else self._outgoing  # quando não tem direção o incoming é o mesmo dicionário que o outgoing

def __repr__(self):
    return "(({0},{1}".format(self._outgoing, self._incoming)

def is_directed(self):
    return self._outgoing is not self._incoming  # se é dirigido

def vertex_count(self):
    return len(self._outgoing)

def vertices(self):
    return self._outgoing.keys()

def edge_count(self):
    # total = sum(len(self._outgoing(key)) for key in self._outgoing)
    total = 0
    for key in self._outgoing:
        value = self._outgoing(key)
        total += len(value)
    return total if self.is_directed() else total // 2

def edges(self):
    result = set()
    for list_edges in self._outgoing.values():
        result.update(list_edges)  # update faz a união
    return result

def get_edge(self, u, v):
    edge = Edge(u, v)  # aresta que eu quero encontrar
    for e in self._outgoing(u):  # procura na lista de saídas
        if e == edge:
            return e
    return None

def degree(self, v, outgoing=None):
    adj = self._outgoing if outgoing else self._incoming
    return len(adj(v))  # comprimento da lista de arestas que estão ligadas ao vértice

def insert_vertex(self, v):
    self._outgoing(v) = ()  # pode fazer-se a importação do módulo 6
    if self.is_directed():
        self._incoming(v) = ()
    return v

def insert_egde(self, u, v, x=None):
    edge = Edge(u, v, x)
    if not self._outgoing.get(u):
        self._outgoing(u) = ()
    elif not self._incoming.get(v):
        self._incoming(v) = ()
    self._outgoing.get(u,()).append(edge)
    self._incoming.get(v,()).append(edge)
    #self._incoming(v).append(edge)

def insert_aresta(self, aresta):
    self._outgoing(aresta.origem).add(aresta)
    self._incoming(aresta.destino).add(aresta)

def remove_edge(self, edge):  # mapa
    del self._outgoing(edge._origem)(edge._destino)
    del self._incoming(edge._destino)(edge._origem)

def remove_edge_v2(self, edge):
    for e in self._outgoing(edge._origem):
        o, d = e.endpoints()
        if o == edge._origem and d == edge._destino:
            self._outgoing(edge._origem).remove(e)
            self._incoming(edge._destino).remove(e)


def create_stations(filename='lisbon.stations.csv'):
    stations = ()
    with open(filename, 'r', newline='') as stations_info:
        station_info = csv.reader(stations_info, delimiter=',')
        # skip first line, which is just attribute names
        next(station_info)
        # empty list to hold stations
 
        # parse all the lines and create stations
        for row in station_info:
            #print(row(3),row(2))
            id = row(0)
            latitude = row(1)
            longitude = row(2)
            nome = row(3)
            # assign each attribute of Station based on line in file
            #(id, latitude, longitude, nome) = tuple(row)
            #create Station instance with those attributes
            newstation = Station(id, latitude, longitude, nome)
            #print(newstation)
            stations.append(newstation)
    return stations
 
def create_connections(filename = 'lisbon.connections.csv'):
    connections = ()
    with open(filename, 'r', newline='') as conections_info:
        conection_info = csv.reader(conections_info, delimiter=',')
        next(conection_info)
        for row in conection_info:
            station_origem = row(0)
            station_destino = row(1)
            linha = row(2)
            connections.append(Edge_Line(station_origem, station_destino, linha))
    return connections
 
 
t_map = GraphList()
 
def station_network():
    for station in create_stations():
        t_map.insert_vertex(station)
    for connection in create_connections():
        t_map.insert_egde(connection.origin, connection.destination)
    return t_map
Also, please find below the CSV files required to use on this work.

lisbon.lines.csv

"line","name","colour" 
1,"Vermelha","r" 
2,"Azul","b" 
3,"Verde","g" 
4,"Amarela","y" 
lisbon.stations.csv

"id","latitude","longitude","name" 
1,38.771746,-9.1306207,"Aeroporto" 
2,38.7758674,-9.1177189,"Encarnação" 
3,38.775383,-9.1048967,"Moscavide" 
4,38.770726,-9.1014767,"Oriente" 
5,38.764569,-9.1064637,"Cabo Ruivo" 
6,38.761624,-9.112163,"Olivais" 
(...)
lisbon.connections.csv

"station1","station2","line" 
1,2,1 
2,3,1 
3,4,1 
4,5,1 
(...)

fa.functional analysis – Is the graph of a Sobolev function path connected?

Let $Omega$ be a bounded, open, simply connected subset of $mathbb R^n$ with Lipschitz boundary.

Question: Does every function in the Sobolev space $W^{1,1} (Omega)$
admit a representative whose graph in $Omega times mathbb R$ is
path connected?

unity – How to create a standard pbr material with shader graph?

I want to create a standard pbr material that is editable with the shader graph, but when I install the package and go the Create -> Shader tab, I only have 2 graph options: Empty Shader Graph, and Sub Graph. Isn’t there a shader graph that starts me off with a basic pbr material with color and reflections? I’m using unity 2020, and the default render pipeline. Do I need to switch to ldrp or hdrp?

Given graph G and vertices v and w can you non-deterministically walk the “least Hamiltonian path” from v to w, if it exists?

My understanding of non-deterministic algorithms is that they’re “as lucky as you want”.

…you can think of the algorithm as being able to make a guess at any point it wants, and a space alien magically guarantees it will always make the right/lucky guess.

For example, if you choose two vertices v and w, if there’s a vw path, then you can non-deterministically walk a vw path, luckily correctly guessing the vertices to walk in a vw path. Given this is true of paths in general, I wonder if the same can be done for Hamiltonian paths. I would think so, but I’m not sure.

Therefore, my first question is: if you can non-deterministically walk a vw path, can you non-deterministically walk a Hamiltonian path from v to w, if a Hamiltonian path exists? If you can non-deterministically walk a Hamiltonian path, I wonder if the same can be done for an additional constraint, what I’m calling a “least Hamiltonian path.” I would think so, but I’m not sure.

Define the least Hamiltonian path from v to w to be the Hamiltonian path such that the second vertex is the smallest it can be, then the third vertex is the smallest it can be, the fourth is the smallest, etc. Assume vertices are integers. For example, if we consider K5 the graph with vertices {1,2,3,4,5} and all possible edges, then the least Hamiltonian path for (v,w) = (2,3) is 21453. If you were at vertex 2, the next least vertex would be 1. Then, the next least vertex would 4. etc.

Therefore, my actual question is: Given graph G and vertices v and w can you non-deterministically walk the least Hamiltonian path from v to w, if it exists?

Motivation: If so, then perhaps there’s a space-efficient algorithm for non-deterministically walking a Hamiltonian path: You can keep a counter for vertices v and w, and go through each pair of vertices such that v<w, checking for the existence of a least Hamiltonian path. To ensure all vertices in G are reached, keep a counter for the number of vertices walked (this should equal N if there are N vertices). Also, ensure that each vertex in the path is unique. The least Hamiltonian path from v to w will be unique, therefore it can be walked multiple times (each time you walk through it, starting at v, you’ll non-deterministically guess the next least vertex in the least Hamiltonian path). You could use two counters to ensure no vertices are repeated – one for the vertex you’re checking to see if it’s unique (loop through the vertices in the least Hamiltonian path), and another counter for a second pass through the least Hamiltonian path. Ensure the second counter encounters the value of the first counter exactly once (use a boolean flag to keep track of this).

Fetching Specific User’s Profile Photo via Graph API in SPFX

How can we fetch a user profile photo through Graph API and display into Web part in SPFX?

Here is my function to call Graph API to fetch Specific user’s Profile Photo filtering through their UserPrincipleName:

private image() {
    this.context.msGraphClientFactory
    .getClient()
    .then((graphclient:MSGraphClient): void=>{
    graphclient
    .api('/users/abhishek.negi@credentinfotech.com/photo/$value')
    .get((error,positionResponse:Blob,rawResponse?:any)=>{
    console.log(positionResponse)
    let binaryData = ();
     binaryData.push(positionResponse);  
    const blobUrl = window.URL.createObjectURL(new Blob(binaryData, {type: "image/jpeg"}));
    document.getElementById('user-img').setAttribute("src", blobUrl );
    })
    })
}

Is their any way to display the API Response Image into a Web part?

In the API Call .api('/users/abhishek.negi@credentinfotech.com/photo/$value') when removing “$value” at the endpoint:

Response at console

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('abhishek.negi%40credentinfotech.com')/photo/$entity",
    "@odata.mediaContentType": "image/jpeg",
    "@odata.mediaEtag": ""5725BAEE"",
    "id": "360X360",
    "height": 360,
    "width": 360
}

Without removing “$value” at the endpoint, I am getting null in the console.

Data Visualisation: Graph for many different options


Your privacy


By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.




co.combinatorics – Fastest algorithm to construct a proper edge $(Delta(G)+1)$-coloring of a simple graph

A proper edge coloring is a coloring of the edges of a graph so that adjacent edges receive distinct colors. Vizing’s theorem states that every simple graph $G$ has a proper edge coloring using at most maximum degree plus one colors. In (1), the authors showed that there is an $O(mn)$-time algorithm to construct a proper edge $(Delta(G)+1)$-coloring of a simple graph whth $m$ edges and $n$ vertices. I wonder whether there is a faster algorithm to construct such an edge coloring.

(1) J. Misra, and D. Gries. A constructive proof of Vizing’s theorem.Inform. Process. Lett.41(3)131–133 (1992)

Prove that any triangle-free planar graph can be colored by 4 colors.

A graph is called "triangle-free" if it does not contain a cycle of length three (a cycle with three edges).
Prove that any triangle-free planar graph can be coloured by 4 colours.

Can someone show me how to prove this problem?

sharepoint online – Using Filter Query in Graph API to fetch the particular users

Current code:

public render(): void {
this.context.msGraphClientFactory
  .getClient()
.then((graphclient:MSGraphClient): void=>{
  graphclient
  .api("https://sharepoint.stackexchange.com/users")
  .filter('Department eq IT')
  .get((error,user:MicrosoftGraph.User,rawResponse?:any)=>{
    console.log(user)
 }

Fetching users detail through Graph API call and filtering users for a particular Department into web part in SPFx.

Using No JavaScript framework to build this web part.

When not using filter, getting all the users details.

How to use filter in the API call?

drawing – Command the draw a graph

Let $G$ be a simple undirected graph. Let the set of vertices be $V=lbrace 1, 2, 3, 4, 5, 6, 7, 8, 9, 10rbrace $, and let the edges set be $E=lbrace (a, b): atext{ divides }btext{ or }btext{ divides }a;text{ and }aneq b~forall a, bin Vrbrace $.

How to draw the graph of this type?