Compile a BEL script to a graph.
777433
def compile(manager, path, allow_naked_names, allow_nested, disallow_unqualified_translocations,
            no_identifier_validation, no_citation_clearing, required_annotations, skip_tqdm, verbose):
    """"""
    if verbose:
        logging.basicConfig(level=logging.DEBUG)
        log.setLevel(logging.DEBUG)
        log.debug('using connection: %s', manager.engine.url)

    click.secho('Compilation', fg='red', bold=True)
    if skip_tqdm:
        click.echo('```')
    graph = from_path(
        path,
        manager=manager,
        use_tqdm=(not (skip_tqdm or verbose)),
        allow_nested=allow_nested,
        allow_naked_names=allow_naked_names,
        disallow_unqualified_translocations=disallow_unqualified_translocations,
        citation_clearing=(not no_citation_clearing),
        required_annotations=required_annotations,
        no_identifier_validation=no_identifier_validation,
        allow_definition_failures=True,
    )
    if skip_tqdm:
        click.echo('```')
    to_pickle(graph, get_corresponding_pickle_path(path))

    click.echo('')
    _print_summary(graph, ticks=skip_tqdm)

    sys.exit(0 if 0 == graph.number_of_warnings() else 1)
468166
function graphvizualize(data, cb) {
  var cp = exec('dot -Tsvg');

  // buffer stdout
  var buf = '';
  cp.stdout.on('data', function (data) {
    buf += data;
  });
  cp.on('error', function () {});
  cp.on('close', function (code) {
    cb(null, code > 0 ? '' : buf);
  });

  // set dot to stdin
  cp.stdin.end(data);
}
570270
def parse_document(graph: BELGraph,
                   enumerated_lines: Iterable[Tuple[int, str]],
                   metadata_parser: MetadataParser,
                   ) -> None:
    """"""
    parse_document_start_time = time.time()

    for line_number, line in enumerated_lines:
        try:
            metadata_parser.parseString(line, line_number=line_number)
        except VersionFormatWarning as exc:
            _log_parse_exception(graph, exc)
            graph.add_warning(exc)
        except Exception as e:
            exc = MalformedMetadataException(line_number, line, 0)
            _log_parse_exception(graph, exc)
            raise exc from e

    for required in REQUIRED_METADATA:
        required_metadatum = metadata_parser.document_metadata.get(required)
        if required_metadatum is not None:
            continue

        required_metadatum_key = INVERSE_DOCUMENT_KEYS[required]
        # This has to be insert since it needs to go on the front!
        exc = MissingMetadataException.make(required_metadatum_key)
        graph.warnings.insert(0, (None, exc, {}))
        _log_parse_exception(graph, exc)

    graph.document.update(metadata_parser.document_metadata)

    log.info('Finished parsing document section in %.02f seconds', time.time() - parse_document_start_time)
297977
def main(graph):
    
    args = parse_args(graph)

    if args.drop:
        drop_all(graph)
    create_all(graph)
1300743
def belu(x):
  """"""
  x_shape = shape_list(x)
  x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1)
  y1 = tf.nn.elu(x1)
  y2 = -tf.nn.elu(-x2)
  return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape)
770774
def draw_graph(G: nx.DiGraph, filename: str):
    
    A = to_agraph(G)
    A.graph_attr["rankdir"] = "LR"
    A.draw(filename, prog="dot")
772945
def pretty_view(graph, oriented=False, construction=False,
                graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
    """"""
    layout = create_layout(graph, graphviz_prog=graphviz_prog)
    matrix_view = defaultdict(lambda: ' ')

    # Add the edge to the view

    # print('GRAPH EDGES:', tuple(graph.edges()))
    # print('LAYOUT:', layout)

    edges = ((layout[source], layout[target])
             for source, target in graph.edges())
    # print('EDGES:', tuple(edges))

    for source, target in edges:
        previous_edge_char = None
        previous_position = source
        while source != target:
            for is_dir, transform, edge_char in DIRECTIONS:
                first_loop = previous_edge_char is None
                if is_dir(source, target):
                    previous_source = source
                    source = transform(source)
                    if not first_loop:  # first loop: no previous char
                        char = CHARACTER[previous_edge_char, edge_char]
                        if not isinstance(char, str):
                            char = char.value
                        matrix_view[previous_source] = char
                        if construction:
                            old = defaultdict(lambda: ' ', matrix_view)
                            yield view.build(matrix_view)
                        assert isinstance(matrix_view[previous_source], str)
                    if source != target:
                        previous_edge_char = edge_char
                    previous_position = previous_source
                    break  # for loop ; don't test the remain directions

        if oriented:
            matrix_view[previous_position] = ORIENTATION[previous_edge_char, edge_char]
        if construction:
            yield view.build(matrix_view)

    # mark the place where nodes labels will be added
    # for node, coords in layout.items():
        # matrix_view[coords] = node[0]
    # Add the node labels to the view
    # matrix_view = view.clean(matrix_view)
    for node, (x, y) in layout.items():
        if len(node) == 1:
            matrix_view[x, y] = node
            continue
        row_min, row_max = (view.previous_unwrittable_on_row(matrix_view, (x, y)),
                            view.next_unwrittable_on_row(matrix_view, (x, y)))
        col_min, col_max = (view.previous_unwrittable_on_col(matrix_view, (x, y)),
                              view.next_unwrittable_on_col(matrix_view, (x, y)))
        # print('NODE ' + node + ':',
              # '→row: [{};{}]'.format(row_min, row_max).ljust(20),
              # '↓col: [{};{}]'.format(col_min, col_max))
        print_coords = [itertools.count(x), itertools.cycle((y,))]
        if row_min is None:  # write left to right, end at (x, y)
            if row_max is None or row_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords[0] = tuple(
                x - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            )
            # print('DEBUG 1:', y, len(node), print_coords[0])
        elif row_max is None:  # write left to right, beginning at (x, y)
            if row_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords[0] = tuple(
                x + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            )
            # print('DEBUG 2:', print_coords[0])
        elif (row_max - row_min) > len(node) + 1:  # write left to right, if enough place
            print_coords[0] = tuple(
                x + offset
                for offset in range(len(node))
            )
            # print('DEBUG 3:', print_coords[0])

        elif col_min is None:  # write up to down, end at (x, y)
            if col_max is None or col_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords = (itertools.cycle((x,)), tuple(
                y - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            ))
            # print('DEBUG 4:', y, len(node), print_coords[1])
        elif col_max is None:  # write up to down, beginning at (x, y)
            if col_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            ))
            # print('DEBUG 5:', print_coords[1])
        elif (col_max - col_min) > len(node) + 1:  # write up to down, if enough place
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset
                for offset in range(len(node))
            ))
            # print('DEBUG 6:', print_coords[1])
        else:  # not enough space
            if (row_max - row_min) > (col_max - col_min):
                # more space on Y axis
                node = node[:row_max - row_min]  # cut the node
                print_coords = (itertools.cycle((x,)), tuple(
                    x + offset
                    for offset in range(len(node))
                ))
                # print('DEBUG 7:', print_coords[1])
            else:
                # more space on X axis
                node = node[:col_max - col_min]  # cut the node
                print_coords[0] = tuple(
                    x + offset
                    for offset in range(len(node))
                )
                # print('DEBUG 8:', print_coords[0])

        for letter, i, j in zip(node, *print_coords):
            matrix_view[i, j] = letter




    if construction:
        yield view.build(matrix_view)
    else:
        yield from view.build(matrix_view)
498799
def get_syntax_errors(graph: BELGraph) -> List[WarningTuple]:
    """"""
    return [
        (path, exc, an)
        for path, exc, an in graph.warnings
        if isinstance(exc, BELSyntaxError)
    ]
1313739
def graph_to_dimacs(g, f):
    
    # write comments
    f.write('c Created by medpy\n')
    f.write('c Oskar Maier, oskar.maier@googlemail.com\n')
    f.write('c\n')
    
    # write problem
    f.write('c problem line\n')
    f.write('p max {} {}\n'.format(g.get_node_count() + 2, len(g.get_edges()))) # +2 as terminal nodes also count in dimacs format # no-nodes / no-edges
    
    # denote source and sink
    f.write('c source descriptor\n')
    f.write('n 1 s\n')
    f.write('c sink descriptor\n')
    f.write('n 2 t\n')
    
    # write terminal arcs (t-weights)
    f.write('c terminal arcs (t-weights)\n')
    for node, weight in list(g.get_tweights().items()):
        # Note: the nodes ids of the graph start from 1, but 1 and 2 are reserved for source and sink respectively, therefore add 2
        if not 0 == weight[0]: # 0 weights are implicit
            f.write('a 1 {} {}\n'.format(node + 2, weight[0]))
        if not 0 == weight[1]: # 0 weights are implicit
            f.write('a {} 2 {}\n'.format(node + 2, weight[1]))
    
    # write inter-node arcs (n-weights)
    f.write('c inter-node arcs (n-weights)\n')
    for edge, weight in list(g.get_nweights().items()):
        if not 0 == weight[0]: # 0 weights are implicit
            f.write('a {} {} {}\n'.format(edge[0] + 2, edge[1] + 2, weight[0]))
        # reversed weights have to follow directly in the next line
        if not 0 == weight[1]: # 0 weights are implicit
            f.write('a {} {} {}\n'.format(edge[1] + 2, edge[0] + 2, weight[1]))
            
    # end comment
    f.write('c end-of-file')
32385
def _text_to_graphiz(self, text):
        """"""
        dot = Source(text, format='svg')
        return dot.pipe().decode('utf-8')
322873
def preprocess_belscript(lines):
    

    set_flag = False
    for line in lines:
        if set_flag is False and re.match("SET", line):
            set_flag = True
            set_line = [line.rstrip()]
        # SET following SET
        elif set_flag and re.match("SET", line):
            yield f"{' '.join(set_line)}\n"
            set_line = [line.rstrip()]
        # Blank line following SET yields single line SET
        elif set_flag and re.match("\s+$", line):
            yield f"{' '.join(set_line)}\n"
            yield line
            set_flag = False

        # Append second, third, ... lines to SET
        elif set_flag:
            set_line.append(line.rstrip())
        else:
            yield line
1152005
def _build_graph_run(self, run_args):
    """"""
    # Could try to use tfe.py_func(fct) but this would require knowing
    # information about the signature of the function.

    # Create a new graph:
    with tf.Graph().as_default() as g:
      # Create placeholder
      input_ = run_args.input
      placeholder = tf.compat.v1.placeholder(
          dtype=input_.dtype, shape=input_.shape)
      output = run_args.fct(placeholder)
    return GraphRun(
        session=raw_nogpu_session(g),
        graph=g,
        placeholder=placeholder,
        output=output,
    )
262514
def dumps(graphs, triples=False, cls=PENMANCodec, **kwargs):
    
    codec = cls(**kwargs)
    strings = [codec.encode(g, triples=triples) for g in graphs]
    return '\n\n'.join(strings)
1267687
function compile(fileNames, options, verbose) {
  const program = ts.createProgram(fileNames, options)
  const emitResult = program.emit()

  /* istanbul ignore next */
  if (verbose) {
    const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics)

    allDiagnostics.forEach((diagnostic) => {
      if (diagnostic.file) {
        const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(
          diagnostic.start
        )
        const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")
        console.log(
          `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`
        )
      } else {
        console.log(`${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`)
      }
    })
  }
}
762775
def add_scripts(self):
        """"""
        common_script = self.node(self.defs, 'script', type='text/javascript')

        def get_js_dict():
            return dict(
                (k, getattr(self.graph.state, k))
                for k in dir(self.graph.config)
                if not k.startswith('_') and hasattr(self.graph.state, k)
                and not hasattr(getattr(self.graph.state, k), '__call__')
            )

        def json_default(o):
            if isinstance(o, (datetime, date)):
                return o.isoformat()
            if hasattr(o, 'to_dict'):
                return o.to_dict()
            return json.JSONEncoder().default(o)

        dct = get_js_dict()
        # Config adds
        dct['legends'] = [
            l.get('title') if isinstance(l, dict) else l
            for l in self.graph._legends + self.graph._secondary_legends
        ]

        common_js = 'window.pygal = window.pygal || {};'
        common_js += 'window.pygal.config = window.pygal.config || {};'
        if self.graph.no_prefix:
            common_js += 'window.pygal.config = '
        else:
            common_js += 'window.pygal.config[%r] = ' % self.graph.uuid

        common_script.text = common_js + json.dumps(dct, default=json_default)

        for js in self.graph.js:
            if js.startswith('file://'):
                script = self.node(self.defs, 'script', type='text/javascript')
                with io.open(js[len('file://'):], encoding='utf-8') as f:
                    script.text = f.read()
            else:
                if js.startswith('//') and self.graph.force_uri_protocol:
                    js = '%s:%s' % (self.graph.force_uri_protocol, js)
                self.node(self.defs, 'script', type='text/javascript', href=js)
391194
def get_graph_by_id(self, network_id: int) -> BELGraph:
        """"""
        network = self.get_network_by_id(network_id)
        log.debug('converting network [id=%d] %s to bel graph', network_id, network)
        return network.as_bel()
111763
def neo(graph: BELGraph, connection: str, password: str):
    """"""
    import py2neo
    neo_graph = py2neo.Graph(connection, password=password)
    to_neo4j(graph, neo_graph)