repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
wroberts/fsed | fsed/fsed.py | build_trie | python | def build_trie(pattern_filename, pattern_format, encoding, on_word_boundaries):
'''
Constructs a finite state machine for performing string rewriting.
Arguments:
- `pattern_filename`:
- `pattern_format`:
- `encoding`:
- `on_word_boundaries`:
'''
boundaries = on_word_boundaries
i... | Constructs a finite state machine for performing string rewriting.
Arguments:
- `pattern_filename`:
- `pattern_format`:
- `encoding`:
- `on_word_boundaries`: | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L84-L148 | [
"def boundary_transform(seq, force_edges = True):\n '''\n Wraps all word transitions with a boundary token character (\\x00).\n If desired (with ``force_edges`` set to ``True``), this inserts\n the boundary character at the beginning and end of the string.\n\n Arguments:\n - `seq`:\n - `force_e... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
fsed.py
(c) Will Roberts 12 December, 2015
Main module for the ``fsed`` command line utility.
'''
from __future__ import absolute_import, print_function, unicode_literals
from fsed.utils import open_file
import click
import fsed.ahocorasick
import logging
import re
... |
wroberts/fsed | fsed/fsed.py | warn_prefix_values | python | def warn_prefix_values(trie):
'''
Prints warning messages for every node that has both a value and a
longest_prefix.
'''
for current, _parent in trie.dfs():
if current.has_value and current.longest_prefix is not None:
LOGGER.warn(('pattern {} (value {}) is a superstring of patter... | Prints warning messages for every node that has both a value and a
longest_prefix. | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L150-L160 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
fsed.py
(c) Will Roberts 12 December, 2015
Main module for the ``fsed`` command line utility.
'''
from __future__ import absolute_import, print_function, unicode_literals
from fsed.utils import open_file
import click
import fsed.ahocorasick
import logging
import re
... |
wroberts/fsed | fsed/fsed.py | rewrite_str_with_trie | python | def rewrite_str_with_trie(sval, trie, boundaries = False, slow = False):
'''
Rewrites a string using the given trie object.
Arguments:
- `sval`:
- `trie`:
- `boundaries`:
- `slow`:
'''
if boundaries:
sval = fsed.ahocorasick.boundary_transform(sval)
if slow:
sval ... | Rewrites a string using the given trie object.
Arguments:
- `sval`:
- `trie`:
- `boundaries`:
- `slow`: | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L162-L180 | [
"def boundary_transform(seq, force_edges = True):\n '''\n Wraps all word transitions with a boundary token character (\\x00).\n If desired (with ``force_edges`` set to ``True``), this inserts\n the boundary character at the beginning and end of the string.\n\n Arguments:\n - `seq`:\n - `force_e... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
fsed.py
(c) Will Roberts 12 December, 2015
Main module for the ``fsed`` command line utility.
'''
from __future__ import absolute_import, print_function, unicode_literals
from fsed.utils import open_file
import click
import fsed.ahocorasick
import logging
import re
... |
wroberts/fsed | fsed/fsed.py | main | python | def main(pattern_filename, input_filenames, pattern_format,
output_filename,
encoding, words, by_line, slow, verbose, quiet):
'''
Search and replace on INPUT_FILE(s) (or standard input), with
matching on fixed strings.
'''
set_log_level(verbose, quiet)
if slow:
by_line ... | Search and replace on INPUT_FILE(s) (or standard input), with
matching on fixed strings. | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L211-L249 | [
"def open_file(filename, mode='rb'):\n \"\"\"\n Opens a file for access with the given mode. This function\n transparently wraps gzip and xz files as well as normal files.\n You can also open zip files using syntax like:\n\n f = utils.open_file('../semcor-parsed.zip:semcor000.txt')\n \"\"\"\n ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
fsed.py
(c) Will Roberts 12 December, 2015
Main module for the ``fsed`` command line utility.
'''
from __future__ import absolute_import, print_function, unicode_literals
from fsed.utils import open_file
import click
import fsed.ahocorasick
import logging
import re
... |
rosshamish/catan-py | catan/game.py | Game.do | python | def do(self, command: undoredo.Command):
self.undo_manager.do(command)
self.notify_observers() | Does the command using the undo_manager's stack
:param command: Command | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L83-L89 | [
"def notify_observers(self):\n for obs in self.observers.copy():\n obs.notify(self)\n"
] | class Game(object):
"""
class Game represents a single game of catan. It has players, a board, and a log.
A Game has observers. Observers register themselves by adding themselves to
the Game's observers set. When the Game changes, it will notify all its observers,
who can then poll the game state a... |
rosshamish/catan-py | catan/game.py | Game.undo | python | def undo(self):
self.undo_manager.undo()
self.notify_observers()
logging.debug('undo_manager undo stack={}'.format(self.undo_manager._undo_stack)) | Rewind the game to the previous state. | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L91-L97 | [
"def notify_observers(self):\n for obs in self.observers.copy():\n obs.notify(self)\n"
] | class Game(object):
"""
class Game represents a single game of catan. It has players, a board, and a log.
A Game has observers. Observers register themselves by adding themselves to
the Game's observers set. When the Game changes, it will notify all its observers,
who can then poll the game state a... |
rosshamish/catan-py | catan/game.py | Game.redo | python | def redo(self):
self.undo_manager.redo()
self.notify_observers()
logging.debug('undo_manager redo stack={}'.format(self.undo_manager._redo_stack)) | Redo the latest undone command. | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L99-L105 | [
"def notify_observers(self):\n for obs in self.observers.copy():\n obs.notify(self)\n"
] | class Game(object):
"""
class Game represents a single game of catan. It has players, a board, and a log.
A Game has observers. Observers register themselves by adding themselves to
the Game's observers set. When the Game changes, it will notify all its observers,
who can then poll the game state a... |
rosshamish/catan-py | catan/game.py | Game.restore | python | def restore(self, game):
self.observers = game.observers
# self.undo_manager = game.undo_manager
self.options = game.options
self.players = game.players
self.board.restore(game.board)
self.robber = game.robber
self.catanlog = game.catanlog
self.state = ga... | Restore this Game object to match the properties and state of the given Game object
:param game: properties to restore to the current (self) Game | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L114-L138 | [
"def notify_observers(self):\n for obs in self.observers.copy():\n obs.notify(self)\n"
] | class Game(object):
"""
class Game represents a single game of catan. It has players, a board, and a log.
A Game has observers. Observers register themselves by adding themselves to
the Game's observers set. When the Game changes, it will notify all its observers,
who can then poll the game state a... |
rosshamish/catan-py | catan/game.py | Game.start | python | def start(self, players):
from .boardbuilder import Opt
self.reset()
if self.board.opts.get('players') == Opt.debug:
players = Game.get_debug_players()
self.set_players(players)
if self.options.get('pregame') is None or self.options.get('pregame') == 'on':
... | Start the game.
The value of option 'pregame' determines whether the pregame will occur or not.
- Resets the board
- Sets the players
- Sets the game state to the appropriate first turn of the game
- Finds the robber on the board, sets the robber_tile appropriately
- Lo... | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L171-L209 | [
"def reset(self):\n self.players = list()\n self.state = catan.states.GameStateNotInGame(self)\n\n self.last_roll = None\n self.last_player_to_roll = None\n self._cur_player = None\n self._cur_turn = 0\n\n self.notify_observers()\n",
"def set_players(self, players):\n self.players = list(p... | class Game(object):
"""
class Game represents a single game of catan. It has players, a board, and a log.
A Game has observers. Observers register themselves by adding themselves to
the Game's observers set. When the Game changes, it will notify all its observers,
who can then poll the game state a... |
rosshamish/catan-py | catan/board.py | Board.restore | python | def restore(self, board):
self.tiles = board.tiles
self.ports = board.ports
self.state = board.state
self.state.board = self
self.pieces = board.pieces
self.opts = board.opts
self.observers = board.observers
self.notify_observers() | Restore this Board object to match the properties and state of the given Board object
:param board: properties to restore to the current (self) Board | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/board.py#L62-L77 | [
"def notify_observers(self):\n for obs in self.observers:\n obs.notify(self)\n"
] | class Board(object):
"""
class Board represents a catan board. It has tiles, ports, and pieces.
A Board has pieces, which is a dictionary mapping (hexgrid.TYPE, coord) -> Piece.
Use #place_piece, #move_piece, and #remove_piece to manage pieces on the board.
Use #get_pieces to get all the pieces a... |
rosshamish/catan-py | catan/board.py | Board.get_port_at | python | def get_port_at(self, tile_id, direction):
for port in self.ports:
if port.tile_id == tile_id and port.direction == direction:
return port
port = Port(tile_id, direction, PortType.none)
self.ports.append(port)
return port | If no port is found, a new none port is made and added to self.ports.
Returns the port.
:param tile_id:
:param direction:
:return: Port | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/board.py#L170-L185 | null | class Board(object):
"""
class Board represents a catan board. It has tiles, ports, and pieces.
A Board has pieces, which is a dictionary mapping (hexgrid.TYPE, coord) -> Piece.
Use #place_piece, #move_piece, and #remove_piece to manage pieces on the board.
Use #get_pieces to get all the pieces a... |
rosshamish/catan-py | catan/board.py | Board.rotate_ports | python | def rotate_ports(self):
for port in self.ports:
port.tile_id = ((port.tile_id + 1) % len(hexgrid.coastal_tile_ids())) + 1
port.direction = hexgrid.rotate_direction(hexgrid.EDGE, port.direction, ccw=True)
self.notify_observers() | Rotates the ports 90 degrees. Useful when using the default port setup but the spectator is watching
at a "rotated" angle from "true north". | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/board.py#L226-L234 | [
"def notify_observers(self):\n for obs in self.observers:\n obs.notify(self)\n"
] | class Board(object):
"""
class Board represents a catan board. It has tiles, ports, and pieces.
A Board has pieces, which is a dictionary mapping (hexgrid.TYPE, coord) -> Piece.
Use #place_piece, #move_piece, and #remove_piece to manage pieces on the board.
Use #get_pieces to get all the pieces a... |
rosshamish/catan-py | catan/trading.py | CatanTrade.give | python | def give(self, terrain, num=1):
for _ in range(num):
logging.debug('terrain={}'.format(terrain))
self._give.append(terrain) | Add a certain number of resources to the trade from giver->getter
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/trading.py#L26-L35 | null | class CatanTrade(object):
"""
class CatanTrade provides a mutable trade object for catan
The trade relationship is one-to-one, and supports any number of
each of the resources going in both directions.
Usually, the current player is the giver, and the other entity the getter.
Think of it as: t... |
rosshamish/catan-py | catan/trading.py | CatanTrade.get | python | def get(self, terrain, num=1):
for _ in range(num):
logging.debug('terrain={}'.format(terrain))
self._get.append(terrain) | Add a certain number of resources to the trade from getter->giver
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/trading.py#L37-L46 | null | class CatanTrade(object):
"""
class CatanTrade provides a mutable trade object for catan
The trade relationship is one-to-one, and supports any number of
each of the resources going in both directions.
Usually, the current player is the giver, and the other entity the getter.
Think of it as: t... |
rosshamish/catan-py | catan/trading.py | CatanTrade.giving | python | def giving(self):
logging.debug('give={}'.format(self._give))
c = Counter(self._give.copy())
return [(n, t) for t, n in c.items()] | Returns tuples corresponding to the number and type of each
resource in the trade from giver->getter
:return: eg [(2, Terrain.wood), (1, Terrain.brick)] | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/trading.py#L54-L63 | null | class CatanTrade(object):
"""
class CatanTrade provides a mutable trade object for catan
The trade relationship is one-to-one, and supports any number of
each of the resources going in both directions.
Usually, the current player is the giver, and the other entity the getter.
Think of it as: t... |
rosshamish/catan-py | catan/trading.py | CatanTrade.getting | python | def getting(self):
c = Counter(self._get.copy())
return [(n, t) for t, n in c.items()] | Returns tuples corresponding to the number and type of each
resource in the trade from getter->giver
:return: eg [(2, Terrain.wood), (1, Terrain.brick)] | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/trading.py#L65-L73 | null | class CatanTrade(object):
"""
class CatanTrade provides a mutable trade object for catan
The trade relationship is one-to-one, and supports any number of
each of the resources going in both directions.
Usually, the current player is the giver, and the other entity the getter.
Think of it as: t... |
rosshamish/catan-py | catan/boardbuilder.py | get_opts | python | def get_opts(opts):
defaults = {
'board': None,
'terrain': Opt.random,
'numbers': Opt.preset,
'ports': Opt.preset,
'pieces': Opt.preset,
'players': Opt.preset,
}
_opts = defaults.copy()
if opts is None:
opts = dict()
try:
for key, val i... | Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present. | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L40-L72 | null | """
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts... |
rosshamish/catan-py | catan/boardbuilder.py | build | python | def build(opts=None):
board = catan.board.Board()
modify(board, opts)
return board | Build a new board using the given options.
:param opts: dictionary mapping str->Opt
:return: the new board, Board | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L75-L83 | [
"def modify(board, opts=None):\n \"\"\"\n Reset an existing board using the given options.\n :param board: the board to reset\n :param opts: dictionary mapping str->Opt\n :return: None\n \"\"\"\n opts = get_opts(opts)\n if opts['board'] is not None:\n board.tiles = _read_tiles_from_st... | """
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts... |
rosshamish/catan-py | catan/boardbuilder.py | modify | python | def modify(board, opts=None):
opts = get_opts(opts)
if opts['board'] is not None:
board.tiles = _read_tiles_from_string(opts['board'])
else:
board.tiles = _generate_tiles(opts['terrain'], opts['numbers'])
board.ports = _get_ports(opts['ports'])
board.state = catan.states.BoardStateMo... | Reset an existing board using the given options.
:param board: the board to reset
:param opts: dictionary mapping str->Opt
:return: None | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L94-L109 | [
"def get_opts(opts):\n \"\"\"\n Validate options and apply defaults for options not supplied.\n\n :param opts: dictionary mapping str->str.\n :return: dictionary mapping str->Opt. All possible keys are present.\n \"\"\"\n defaults = {\n 'board': None,\n 'terrain': Opt.random,\n ... | """
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts... |
rosshamish/catan-py | catan/boardbuilder.py | _get_tiles | python | def _get_tiles(board=None, terrain=None, numbers=None):
if board is not None:
# we have a board given, ignore the terrain and numbers opts and log warnings
# if they were supplied
tiles = _read_tiles_from_string(board)
else:
# we are being asked to generate a board
tiles ... | Generate a list of tiles using the given terrain and numbers options.
terrain options supported:
- Opt.empty -> all tiles are desert
- Opt.random -> tiles are randomized
- Opt.preset ->
- Opt.debug -> alias for Opt.random
numbers options supported:
- Opt.empty -> no tiles have numbers
... | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L112-L140 | null | """
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts... |
rosshamish/catan-py | catan/boardbuilder.py | _get_ports | python | def _get_ports(port_opts):
if port_opts in [Opt.preset, Opt.debug]:
_preset_ports = [(1, 'NW', catan.board.PortType.any3),
(2, 'W', catan.board.PortType.wood),
(4, 'W', catan.board.PortType.brick),
(5, 'SW', catan.board.PortType.any3... | Generate a list of ports using the given options.
port options supported:
- Opt.empty ->
- Opt.random ->
- Opt.preset -> ports are in default locations
- Opt.debug -> alias for Opt.preset
:param port_opts: Opt
:return: list(Port) | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L231-L258 | null | """
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts... |
rosshamish/catan-py | catan/boardbuilder.py | _get_pieces | python | def _get_pieces(tiles, ports, players_opts, pieces_opts):
if pieces_opts == Opt.empty:
return dict()
elif pieces_opts == Opt.debug:
players = catan.game.Game.get_debug_players()
return {
(hexgrid.NODE, 0x23): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[0]),
... | Generate a dictionary of pieces using the given options.
pieces options supported:
- Opt.empty -> no locations have pieces
- Opt.random ->
- Opt.preset -> robber is placed on the first desert found
- Opt.debug -> a variety of pieces are placed around the board
:param tiles: list of tiles from ... | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/boardbuilder.py#L261-L298 | [
"def get_debug_players(cls):\n return [Player(1, 'yurick', 'green'),\n Player(2, 'josh', 'blue'),\n Player(3, 'zach', 'orange'),\n Player(4, 'ross', 'red')]\n"
] | """
module boardbuilder is responsible for creating starting board layouts.
It can create a variety of boards by supplying various options.
- Options: [terrain, numbers, ports, pieces, players]
- Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug]
The default options are defined in #get_opts.
Use #get_opts... |
rosshamish/catan-py | catan/states.py | GameStateInGame.next_player | python | def next_player(self):
logging.warning('turn={}, players={}'.format(
self.game._cur_turn,
self.game.players
))
return self.game.players[(self.game._cur_turn + 1) % len(self.game.players)] | Returns the player whose turn it will be next.
Uses regular seat-wise clockwise rotation.
Compare to GameStatePreGame's implementation, which uses snake draft.
:return Player | train | https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/states.py#L184-L198 | null | class GameStateInGame(GameState):
"""
All IN-GAME states inherit from this state.
In game is defined as taking turns, rolling dice, placing pieces, etc.
In game starts on 'Start Game', and ends on 'End Game'
this state implements:
is_in_game()
this state provides:
is_in_pregame... |
cnschema/cdata | cdata/wikify.py | wikidata_get | python | def wikidata_get(identifier):
url = 'https://www.wikidata.org/wiki/Special:EntityData/{}.json'.format(identifier)
#logging.info(url)
return json.loads(requests.get(url).content) | https://www.wikidata.org/wiki/Special:EntityData/P248.json | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/wikify.py#L51-L57 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# wikification apis
import os
import sys
import json
import logging
import datetime
import logging
import time
import urllib
import re
import requests
from misc import main_subtask
from core import *
def task_compare(args):
queries = [
"a... |
cnschema/cdata | cdata/wikify.py | wikidata_search | python | def wikidata_search(query, lang="zh", output_lang="en", searchtype="item", max_result=1):
query = any2unicode(query)
params = {
"action":"wbsearchentities",
"search": query,
"format":"json",
"language":lang,
"uselang":output_lang,
"type":searchtype
}
url... | wikification: search wikipedia pages for the given query
https://www.wikidata.org/w/api.php?action=help&modules=wbsearchentities
result format
{
searchinfo: - {
search: "birthday"
},
search: - [
- {
repository: "",
... | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/wikify.py#L59-L115 | [
"def json_dict_copy(json_object, property_list, defaultValue=None):\n \"\"\"\n property_list = [\n { \"name\":\"name\", \"alternateName\": [\"name\",\"title\"]},\n { \"name\":\"birthDate\", \"alternateName\": [\"dob\",\"dateOfBirth\"] },\n { \"name\":\"description\" }\n ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# wikification apis
import os
import sys
import json
import logging
import datetime
import logging
import time
import urllib
import re
import requests
from misc import main_subtask
from core import *
def task_compare(args):
queries = [
"a... |
cnschema/cdata | cdata/wikify.py | wikipedia_search | python | def wikipedia_search(query, lang="en", max_result=1):
query = any2unicode(query)
params = {
"action":"opensearch",
"search": query,
"format":"json",
#"formatversion":2,
#"namespace":0,
"suggest":"true",
"limit": 10
}
urlBase = "https://{}.wikipedia... | https://www.mediawiki.org/wiki/API:Opensearch | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/wikify.py#L137-L171 | [
"def any2utf8(data):\n \"\"\"\n rewrite json object values (unicode) into utf-8 encoded string\n \"\"\"\n if isinstance(data, dict):\n ret = {}\n for k, v in data.items():\n k = any2utf8(k)\n ret[k] = any2utf8(v)\n return ret\n elif isinstance(data, list... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# wikification apis
import os
import sys
import json
import logging
import datetime
import logging
import time
import urllib
import re
import requests
from misc import main_subtask
from core import *
def task_compare(args):
queries = [
"a... |
cnschema/cdata | cdata/misc.py | main_subtask | python | def main_subtask(module_name, method_prefixs=["task_"], optional_params={}):
parser = argparse.ArgumentParser(description="")
parser.add_argument('method_name', help='')
for optional_param_key, optional_param_help in optional_params.items():
parser.add_argument(optional_param_key,
... | http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse
As of 2.7, optparse is deprecated, and will hopefully go away in the future | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/misc.py#L24-L58 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# utility stuff
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import logging
import time
import argparse
import urlparse
import re
import collections
#######################################... |
cnschema/cdata | cdata/web.py | url2domain | python | def url2domain(url):
parsed_uri = urlparse.urlparse(url)
domain = '{uri.netloc}'.format(uri=parsed_uri)
domain = re.sub("^.+@", "", domain)
domain = re.sub(":.+$", "", domain)
return domain | extract domain from url | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/web.py#L20-L27 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# utility stuff
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import logging
import time
import urlparse
import re
|
cnschema/cdata | cdata/core.py | file2abspath | python | def file2abspath(filename, this_file=__file__):
return os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(this_file)), filename)) | generate absolute path for the given file and base dir | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L28-L33 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEX... |
cnschema/cdata | cdata/core.py | file2json | python | def file2json(filename, encoding='utf-8'):
with codecs.open(filename, "r", encoding=encoding) as f:
return json.load(f) | save a line | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L39-L44 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEX... |
cnschema/cdata | cdata/core.py | file2iter | python | def file2iter(filename, encoding='utf-8', comment_prefix="#",
skip_empty_line=True):
ret = list()
visited = set()
with codecs.open(filename, encoding=encoding) as f:
for line in f:
line = line.strip()
# skip empty line
if skip_empty_line and len(line... | json stream parsing or line parsing | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L47-L65 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEX... |
cnschema/cdata | cdata/core.py | json2file | python | def json2file(data, filename, encoding='utf-8'):
with codecs.open(filename, "w", encoding=encoding) as f:
json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True) | write json in canonical json format | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L71-L76 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEX... |
cnschema/cdata | cdata/core.py | lines2file | python | def lines2file(lines, filename, encoding='utf-8'):
with codecs.open(filename, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
f.write("\n") | write json stream, write lines too | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L79-L86 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEX... |
cnschema/cdata | cdata/core.py | items2file | python | def items2file(items, filename, encoding='utf-8', modifier='w'):
with codecs.open(filename, modifier, encoding=encoding) as f:
for item in items:
f.write(u"{}\n".format(json.dumps(
item, ensure_ascii=False, sort_keys=True))) | json array to file, canonical json format | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L89-L96 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEX... |
cnschema/cdata | cdata/core.py | json_get | python | def json_get(json_object, property_path, default=None):
temp = json_object
for field in property_path[:-1]:
if not isinstance(temp, dict):
return None
temp = temp.get(field, {})
if not isinstance(temp, dict):
return None
return temp.get(property_path[-1], default) | get value of property_path from a json object, e.g. person.father.name
* invalid path return None
* valid path (the -1 on path is an object), use default | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L102-L115 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEX... |
cnschema/cdata | cdata/core.py | json_dict_copy | python | def json_dict_copy(json_object, property_list, defaultValue=None):
ret = {}
for prop in property_list:
p_name = prop["name"]
for alias in prop.get("alternateName", []):
if json_object.get(alias) is not None:
ret[p_name] = json_object.get(alias)
break
... | property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
] | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L138-L159 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEX... |
cnschema/cdata | cdata/core.py | any2utf8 | python | def any2utf8(data):
if isinstance(data, dict):
ret = {}
for k, v in data.items():
k = any2utf8(k)
ret[k] = any2utf8(v)
return ret
elif isinstance(data, list):
return [any2utf8(x) for x in data]
elif isinstance(data, unicode):
return data.encode... | rewrite json object values (unicode) into utf-8 encoded string | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L175-L195 | [
"def any2utf8(data):\n \"\"\"\n rewrite json object values (unicode) into utf-8 encoded string\n \"\"\"\n if isinstance(data, dict):\n ret = {}\n for k, v in data.items():\n k = any2utf8(k)\n ret[k] = any2utf8(v)\n return ret\n elif isinstance(data, list... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEX... |
cnschema/cdata | cdata/core.py | any2sha1 | python | def any2sha1(text):
# canonicalize json object or json array
if type(text) in [dict, list]:
text = json.dumps(text, sort_keys=True)
# assert question as utf8
if isinstance(text, unicode):
text = text.encode('utf-8')
return hashlib.sha1(text).hexdigest() | convert a string into sha1hash. For json object/array, first convert
it into canonical json string. | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L221-L234 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEX... |
cnschema/cdata | cdata/core.py | stat_jsonld | python | def stat_jsonld(data, key=None, counter=None):
if counter is None:
counter = collections.Counter()
if isinstance(data, dict):
ret = {}
for k, v in data.items():
stat_jsonld(v, k, counter)
counter[u"p_{}".format(k)] += 0
if key:
counter["triple... | provide statistics for jsonld, right now only count triples
see also https://json-ld.org/playground/
note: attributes @id @context do not contribute any triple | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/core.py#L269-L300 | [
"def stat_jsonld(data, key=None, counter=None):\n \"\"\"\n provide statistics for jsonld, right now only count triples\n see also https://json-ld.org/playground/\n note: attributes @id @context do not contribute any triple\n \"\"\"\n if counter is None:\n counter = collections... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# JSON data manipulation
# base packages
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import time
import argparse
import urlparse
import re
import collections
# global constants
VERSION = 'v20170713'
CONTEX... |
cnschema/cdata | cdata/summary.py | summarize_entity_person | python | def summarize_entity_person(person):
ret = []
value = person.get("name")
if not value:
return False
ret.append(value)
prop = "courtesyName"
value = json_get_first_item(person, prop)
if value == u"不详":
value = ""
if value:
ret.append(u'字{}'.format(value))
val... | assume person entity using cnschma person vocabulary, http://cnschema.org/Person | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/summary.py#L25-L117 | [
"def json_get_list(json_object, p):\n v = json_object.get(p, [])\n if isinstance(v, list):\n return v\n else:\n return [v]\n",
"def json_get_first_item(json_object, p, defaultValue=''):\n # return empty string if the item does not exist\n v = json_object.get(p, [])\n if isinstance(... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:
# summarize a paragraph or an entity into short text description
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import logging
import time
import re
import collections
from misc import main_subtask
from core import *... |
cnschema/cdata | cdata/table.py | json2excel | python | def json2excel(items, keys, filename, page_size=60000):
wb = xlwt.Workbook()
rowindex = 0
sheetindex = 0
for item in items:
if rowindex % page_size == 0:
sheetname = "%02d" % sheetindex
ws = wb.add_sheet(sheetname)
rowindex = 0
sheetindex += 1
... | max_page_size is 65000 because we output old excel .xls format | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/table.py#L22-L53 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# table/excel data manipulation
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import logging
import time
import re
import collections
import xlwt
import xlrd
def excel2json(filename, non_empty_col=-1, fil... |
cnschema/cdata | cdata/table.py | excel2json | python | def excel2json(filename, non_empty_col=-1, file_contents=None):
if file_contents:
workbook = xlrd.open_workbook(file_contents=file_contents)
else:
workbook = xlrd.open_workbook(filename)
start_row = 0
ret = collections.defaultdict(list)
fields = {}
for name in workbook.sheet_na... | http://www.lexicon.net/sjmachin/xlrd.html
non_empty_col is -1 to load all rows, when set to a none-empty value,
this function will skip rows having empty cell on that col. | train | https://github.com/cnschema/cdata/blob/893e2e1e27b61c8551c8b5f5f9bf05ec61490e23/cdata/table.py#L56-L106 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Li Ding
# table/excel data manipulation
import os
import sys
import json
import logging
import codecs
import hashlib
import datetime
import logging
import time
import re
import collections
import xlwt
import xlrd
def json2excel(items, keys, filename, page_size... |
frostming/marko | marko/helpers.py | camel_to_snake_case | python | def camel_to_snake_case(name):
pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])'
return '_'.join(map(str.lower, re.findall(pattern, name))) | Takes a camelCased string and converts to snake_case. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L10-L13 | null | """
Helper functions and data structures
"""
import re
from contextlib import contextmanager
from ._compat import string_types
def is_paired(text, open='(', close=')'):
"""Check if the text only contains:
1. blackslash escaped parentheses, or
2. parentheses paired.
"""
count = 0
escape = Fal... |
frostming/marko | marko/helpers.py | is_paired | python | def is_paired(text, open='(', close=')'):
count = 0
escape = False
for c in text:
if escape:
escape = False
elif c == '\\':
escape = True
elif c == open:
count += 1
elif c == close:
if count == 0:
return False
... | Check if the text only contains:
1. blackslash escaped parentheses, or
2. parentheses paired. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L16-L34 | null | """
Helper functions and data structures
"""
import re
from contextlib import contextmanager
from ._compat import string_types
def camel_to_snake_case(name):
"""Takes a camelCased string and converts to snake_case."""
pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])'
return '_'.join(map(str.lower, re.findall(patt... |
frostming/marko | marko/helpers.py | Source.match_prefix | python | def match_prefix(prefix, line):
m = re.match(prefix, line.expandtabs(4))
if not m:
if re.match(prefix, line.expandtabs(4).replace('\n', ' ' * 99 + '\n')):
return len(line) - 1
return -1
pos = m.end()
if pos == 0:
return 0
for i ... | Check if the line starts with given prefix and
return the position of the end of prefix.
If the prefix is not matched, return -1. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L101-L116 | null | class Source(object):
"""Wrapper class on content to be parsed"""
def __init__(self, text):
self._buffer = _preprocess_text(text)
self.pos = 0
self._anchor = 0
self._states = []
self.match = False
@property
def state(self):
"""Returns the current element... |
frostming/marko | marko/helpers.py | Source.expect_re | python | def expect_re(self, regexp):
prefix_len = self.match_prefix(
self.prefix, self.next_line(require_prefix=False)
)
if prefix_len >= 0:
match = self._expect_re(regexp, self.pos + prefix_len)
self.match = match
return match
else:
re... | Test against the given regular expression and returns the match object.
:param regexp: the expression to be tested.
:returns: the match object. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L118-L132 | [
"def _expect_re(self, regexp, pos):\n if isinstance(regexp, string_types):\n regexp = re.compile(regexp)\n return regexp.match(self._buffer, pos)\n",
"def match_prefix(prefix, line):\n \"\"\"Check if the line starts with given prefix and\n return the position of the end of prefix.\n If the p... | class Source(object):
"""Wrapper class on content to be parsed"""
def __init__(self, text):
self._buffer = _preprocess_text(text)
self.pos = 0
self._anchor = 0
self._states = []
self.match = False
@property
def state(self):
"""Returns the current element... |
frostming/marko | marko/helpers.py | Source.next_line | python | def next_line(self, require_prefix=True):
if require_prefix:
m = self.expect_re(r'(?m)[^\n]*?$\n?')
else:
m = self._expect_re(r'(?m)[^\n]*$\n?', self.pos)
self.match = m
if m:
return m.group() | Return the next line in the source.
:param require_prefix: if False, the whole line will be returned.
otherwise, return the line with prefix stripped or None if the prefix
is not matched. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L134-L147 | [
"def _expect_re(self, regexp, pos):\n if isinstance(regexp, string_types):\n regexp = re.compile(regexp)\n return regexp.match(self._buffer, pos)\n",
"def expect_re(self, regexp):\n \"\"\"Test against the given regular expression and returns the match object.\n\n :param regexp: the expression t... | class Source(object):
"""Wrapper class on content to be parsed"""
def __init__(self, text):
self._buffer = _preprocess_text(text)
self.pos = 0
self._anchor = 0
self._states = []
self.match = False
@property
def state(self):
"""Returns the current element... |
frostming/marko | marko/helpers.py | Source.consume | python | def consume(self):
if self.match:
self.pos = self.match.end()
if self.match.group()[-1] == '\n':
self._update_prefix()
self.match = None | Consume the body of source. ``pos`` will move forward. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L149-L155 | null | class Source(object):
"""Wrapper class on content to be parsed"""
def __init__(self, text):
self._buffer = _preprocess_text(text)
self.pos = 0
self._anchor = 0
self._states = []
self.match = False
@property
def state(self):
"""Returns the current element... |
frostming/marko | marko/__init__.py | Markdown.render | python | def render(self, parsed):
self.renderer.root_node = parsed
with self.renderer as r:
return r.render(parsed) | Call ``self.renderer.render(text)``.
Override this to handle parsed result. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/__init__.py#L48-L55 | null | class Markdown(object):
"""The main class to convert markdown documents.
Attributes:
parser: an instance of :class:`Parser`
renderer: an instance of :class:`Renderer`
:param parser: a subclass or instance of :class:`Parser`
:param renderer: a subclass or instance of :class:`Renderer`
... |
frostming/marko | marko/renderer.py | Renderer.render | python | def render(self, element):
# Store the root node to provide some context to render functions
if not self.root_node:
self.root_node = element
render_func = getattr(
self, self._cls_to_func_name(element.__class__), None)
if not render_func:
render_func =... | Renders the given element to string.
:param element: a element to be rendered.
:returns: the output string or any values. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/renderer.py#L37-L50 | [
"def render_children(self, element):\n if isinstance(element, list):\n return [self.render_children(e) for e in element]\n if isinstance(element, string_types):\n return element\n rv = {k: v for k, v in element.__dict__.items() if not k.startswith('_')}\n if 'children' in rv:\n rv['... | class Renderer(object):
"""The base class of renderers.
A custom renderer should subclass this class and include your own render functions.
A render function should:
* be named as ``render_<element_name>``, where the ``element_name`` is the snake
case form of the element class name, the rendere... |
frostming/marko | marko/renderer.py | Renderer.render_children | python | def render_children(self, element):
rendered = [self.render(child) for child in element.children]
return ''.join(rendered) | Recursively renders child elements. Joins the rendered
strings with no space in between.
If newlines / spaces are needed between elements, add them
in their respective templates, or override this function
in the renderer subclass, so that whitespace won't seem to
appear magicall... | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/renderer.py#L52-L65 | null | class Renderer(object):
"""The base class of renderers.
A custom renderer should subclass this class and include your own render functions.
A render function should:
* be named as ``render_<element_name>``, where the ``element_name`` is the snake
case form of the element class name, the rendere... |
frostming/marko | marko/inline.py | InlineElement.find | python | def find(cls, text):
if isinstance(cls.pattern, string_types):
cls.pattern = re.compile(cls.pattern)
return cls.pattern.finditer(text) | This method should return an iterable containing matches of this element. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline.py#L39-L43 | null | class InlineElement(object):
"""Any inline element should inherit this class"""
#: Use to denote the precedence in parsing.
priority = 5
#: element regex pattern.
pattern = None
#: whether to parse children.
parse_children = False
#: which match group to parse.
parse_group = 1
#... |
frostming/marko | marko/inline_parser.py | parse | python | def parse(text, elements, fallback):
# this is a raw list of elements that may contain overlaps.
tokens = []
for etype in elements:
for match in etype.find(text):
tokens.append(Token(etype, match, text, fallback))
tokens.sort()
tokens = _resolve_overlap(tokens)
return make_el... | Parse given text and produce a list of inline elements.
:param text: the text to be parsed.
:param elements: the element types to be included in parsing
:param fallback: fallback class when no other element type is matched. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L12-L26 | [
"def _resolve_overlap(tokens):\n if not tokens:\n return tokens\n result = []\n prev = tokens[0]\n for cur in tokens[1:]:\n r = prev.relation(cur)\n if r == Token.PRECEDE:\n result.append(prev)\n prev = cur\n elif r == Token.CONTAIN:\n prev.ap... | """
Parse inline elements
"""
from __future__ import unicode_literals
import re
import string
from .helpers import is_paired, normalize_label
from . import patterns
def _resolve_overlap(tokens):
if not tokens:
return tokens
result = []
prev = tokens[0]
for cur in tokens[1:]:
r = prev... |
frostming/marko | marko/inline_parser.py | make_elements | python | def make_elements(tokens, text, start=0, end=None, fallback=None):
result = []
end = end or len(text)
prev_end = start
for token in tokens:
if prev_end < token.start:
result.append(fallback(text[prev_end:token.start]))
result.append(token.as_element())
prev_end = toke... | Make elements from a list of parsed tokens.
It will turn all unmatched holes into fallback elements.
:param tokens: a list of parsed tokens.
:param text: the original tet.
:param start: the offset of where parsing starts. Defaults to the start of text.
:param end: the offset of where parsing ends. ... | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L47-L68 | null | """
Parse inline elements
"""
from __future__ import unicode_literals
import re
import string
from .helpers import is_paired, normalize_label
from . import patterns
def parse(text, elements, fallback):
"""Parse given text and produce a list of inline elements.
:param text: the text to be parsed.
:param ... |
frostming/marko | marko/inline_parser.py | find_links_or_emphs | python | def find_links_or_emphs(text, root_node):
delimiters_re = re.compile(r'(?:!?\[|\*+|_+)')
i = 0
delimiters = []
escape = False
matches = []
code_pattern = re.compile(r'(?<!`)(`+)(?!`)([\s\S]+?)(?<!`)\1(?!`)')
while i < len(text):
if escape:
escape = False
i +=... | Fink links/images or emphasis from text.
:param text: the original text.
:param root_node: a reference to the root node of the AST.
:returns: an iterable of match object. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L125-L163 | [
"def process_emphasis(text, delimiters, stack_bottom, matches):\n star_bottom = underscore_bottom = stack_bottom\n cur = _next_closer(delimiters, stack_bottom)\n while cur is not None:\n d_closer = delimiters[cur]\n bottom = star_bottom if d_closer.content[0] == '*' else underscore_bottom\n ... | """
Parse inline elements
"""
from __future__ import unicode_literals
import re
import string
from .helpers import is_paired, normalize_label
from . import patterns
def parse(text, elements, fallback):
"""Parse given text and produce a list of inline elements.
:param text: the text to be parsed.
:param ... |
frostming/marko | marko/inline_parser.py | _expect_inline_link | python | def _expect_inline_link(text, start):
if start >= len(text) or text[start] != '(':
return None
i = start + 1
m = patterns.whitespace.match(text, i)
if m:
i = m.end()
m = patterns.link_dest_1.match(text, i)
if m:
link_dest = m.start(), m.end(), m.group()
i = m.end(... | (link_dest "link_title") | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L205-L247 | null | """
Parse inline elements
"""
from __future__ import unicode_literals
import re
import string
from .helpers import is_paired, normalize_label
from . import patterns
def parse(text, elements, fallback):
"""Parse given text and produce a list of inline elements.
:param text: the text to be parsed.
:param ... |
frostming/marko | marko/parser.py | Parser.add_element | python | def add_element(self, element, override=False):
if issubclass(element, inline.InlineElement):
dest = self.inline_elements
elif issubclass(element, block.BlockElement):
dest = self.block_elements
else:
raise TypeError(
'The element should be a s... | Add an element to the parser.
:param element: the element class.
:param override: whether to replace the default element based on.
.. note:: If one needs to call it inside ``__init__()``, please call it after
``super().__init__()`` is called. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L37-L63 | null | class Parser(object):
"""
All elements defined in CommonMark's spec are included in the parser
by default. To add your custom elements, you can either:
1. pass the element classes as ``extras`` arguments to the constructor.
2. or subclass to your own parser and call :meth:`Parser.add_element`
... |
frostming/marko | marko/parser.py | Parser.parse | python | def parse(self, source_or_text):
if isinstance(source_or_text, string_types):
block.parser = self
inline.parser = self
return self.block_elements['Document'](source_or_text)
element_list = self._build_block_element_list()
ast = []
while not source_or_t... | Do the actual parsing and returns an AST or parsed element.
:param source_or_text: the text or source object.
Based on the type, it will do following:
- text: returns the parsed Document element.
- source: parse the source and returns the parsed children as a list. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L65-L90 | [
"def _build_block_element_list(self):\n \"\"\"Return a list of block elements, ordered from highest priority to lowest.\n \"\"\"\n return sorted(\n [e for e in self.block_elements.values() if not e.virtual],\n key=lambda e: e.priority,\n reverse=True\n )\n"
] | class Parser(object):
"""
All elements defined in CommonMark's spec are included in the parser
by default. To add your custom elements, you can either:
1. pass the element classes as ``extras`` arguments to the constructor.
2. or subclass to your own parser and call :meth:`Parser.add_element`
... |
frostming/marko | marko/parser.py | Parser.parse_inline | python | def parse_inline(self, text):
element_list = self._build_inline_element_list()
return inline_parser.parse(
text, element_list, fallback=self.inline_elements['RawText']
) | Parses text into inline elements.
RawText is not considered in parsing but created as a wrapper of holes
that don't match any other elements.
:param text: the text to be parsed.
:returns: a list of inline elements. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L92-L103 | [
"def parse(text, elements, fallback):\n \"\"\"Parse given text and produce a list of inline elements.\n\n :param text: the text to be parsed.\n :param elements: the element types to be included in parsing\n :param fallback: fallback class when no other element type is matched.\n \"\"\"\n # this is... | class Parser(object):
"""
All elements defined in CommonMark's spec are included in the parser
by default. To add your custom elements, you can either:
1. pass the element classes as ``extras`` arguments to the constructor.
2. or subclass to your own parser and call :meth:`Parser.add_element`
... |
frostming/marko | marko/parser.py | Parser._build_block_element_list | python | def _build_block_element_list(self):
return sorted(
[e for e in self.block_elements.values() if not e.virtual],
key=lambda e: e.priority,
reverse=True
) | Return a list of block elements, ordered from highest priority to lowest. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L105-L112 | null | class Parser(object):
"""
All elements defined in CommonMark's spec are included in the parser
by default. To add your custom elements, you can either:
1. pass the element classes as ``extras`` arguments to the constructor.
2. or subclass to your own parser and call :meth:`Parser.add_element`
... |
frostming/marko | marko/block.py | BlockElement.parse_inline | python | def parse_inline(self):
if self.inline_children:
self.children = parser.parse_inline(self.children)
elif isinstance(getattr(self, 'children', None), list):
for child in self.children:
if isinstance(child, BlockElement):
child.parse_inline() | Inline parsing is postponed so that all link references
are seen before that. | train | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/block.py#L59-L68 | null | class BlockElement(object):
"""Any block element should inherit this class"""
#: Use to denote the precedence in parsing
priority = 5
#: if True, it won't be included in parsing process but produced by other elements
#: other elements instead.
virtual = False
#: Whether children are parsed a... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/commands.py | await_transform_exists | python | def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
message_payload = {
"transform_paths": [transform_path],
"do_exist": does_exist,
"match_mode": "All",
"timeout": timeout_seconds
}
msg = message.Mess... | Waits for a single transform to exist based on does_exist.
:param cli:
:param transform_path:
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L29-L49 | null | from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or n... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/commands.py | await_any_transforms_exist | python | def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
message_payload = {
"transform_paths": transform_paths,
"do_exist": does_exist,
"match_mode": "Any",
"timeout": timeout_seconds
}
msg = message.... | Waits for a transform to exist based on does_exist.
:param cli:
:param transform_paths: An array of transform paths [...]
:param does_exist: Whether or not to await for exist state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L52-L72 | null | from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or n... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/commands.py | fetch_transform_screen_position | python | def fetch_transform_screen_position(cli, transform_path):
message_payload = {
"transform_path": transform_path
}
msg = message.Message("fetch.unity.transform.screenPosition", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return [
... | Requests screen position of a transform at path. WorldToScreenPoint is used for 3D, otherwise
a screen-scaled center of RectTransform is used.
:param cli:
:param transform_path:
:return: [x,y] | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L98-L118 | null | from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or n... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/commands.py | query_renderer_visible | python | def query_renderer_visible(cli, transform_path):
message_payload = {
"transform_path": transform_path
}
msg = message.Message("query.unity.renderer.visible", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload... | Requests status on whether a renderer at transform_path is visible.
:param cli:
:param transform_path:
:return: bool | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L144-L160 | null | from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or n... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/commands.py | await_renderer_visible | python | def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
message_payload = {
"transform_path": transform_path,
"is_visible": is_visible,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.renderer.visi... | Waits for a transform renderer to become visible based on is_visible.
:param cli:
:param transform_path:
:param is_visible: Whether or not to await for visible state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L163-L182 | null | from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or n... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/commands.py | query_scene_loaded | python | def query_scene_loaded(cli, scene_name):
message_payload = {
"scene_name": scene_name
}
msg = message.Message("query.unity.scene.loaded", message_payload)
cli.send_message(msg)
response = cli.read_message()
verify_response(response)
return bool(response['payload']['result']) | Requests status on whether a scene is loaded or not.
:param cli:
:param scene_name:
:return: bool | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L185-L201 | null | from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or n... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/commands.py | await_scene_loaded | python | def await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
message_payload = {
"scene_name": scene_name,
"is_loaded": is_loaded,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.scene.loaded", message_payload)
... | Waits for a scene to be loaded based on is_loaded.
:param cli:
:param scene_name:
:param is_loaded: Whether or not to await for loaded state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L204-L223 | null | from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or n... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/commands.py | assign_component_value | python | def assign_component_value(cli, transform_path, component_type, name, value):
message_payload = {
"transform_path": transform_path,
"component_type": component_type,
"name": name,
"value": value
}
msg = message.Message("assign.unity.component.value", message_payload)
cli... | Requests status on whether a scene is loaded or not.
:param cli:
:param transform_path: The path of the transform where the component resides
:param component_type: The C# type name of the component GetComponent(type)
:param name: The field or property name.
:param value: The value to assign (String... | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L226-L247 | null | from coeus_test.commands import verify_response
import coeus_test.message as message
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def query_transform_exists(cli, transform_path):
"""
Requests status on whether a transform exists or n... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/assertions.py | assert_transform_exists | python | def assert_transform_exists(cli, transform_path):
result = commands.query_transform_exists(cli, transform_path)
assert result is True
return result | Asserts that the transform exists.
:param cli:
:param transform_path:
:return: | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L9-L18 | [
"def query_transform_exists(cli, transform_path):\n \"\"\"\n Requests status on whether a transform exists or not.\n :param cli:\n :param transform_path:\n :return: bool\n \"\"\"\n\n message_payload = {\n \"transform_path\": transform_path\n }\n msg = message.Message(\"query.unity.... | import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_scene_loaded(cli, scene_name):
"""
Asserts that the scene is loaded.
:param cli:
:param scene_name:
:return:
"""
res... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/assertions.py | assert_scene_loaded | python | def assert_scene_loaded(cli, scene_name):
result = commands.query_scene_loaded(cli, scene_name)
assert result is True
return result | Asserts that the scene is loaded.
:param cli:
:param scene_name:
:return: | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L21-L30 | [
"def query_scene_loaded(cli, scene_name):\n \"\"\"\n Requests status on whether a scene is loaded or not.\n :param cli:\n :param scene_name:\n :return: bool\n \"\"\"\n\n message_payload = {\n \"scene_name\": scene_name\n }\n msg = message.Message(\"query.unity.scene.loaded\", messa... | import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/assertions.py | assert_await_transform_exists | python | def assert_await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
result = commands.await_transform_exists(cli, transform_path, does_exist, timeout_seconds)
assert result is True
return result | Asserts that we successfully awaited for the transform to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_seco... | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L33-L45 | [
"def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):\n \"\"\"\n Waits for a single transform to exist based on does_exist.\n :param cli:\n :param transform_path:\n :param does_exist: Whether or not to await for exist state (Tr... | import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/assertions.py | assert_await_any_transforms_exist | python | def assert_await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
result = commands.await_any_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result | Asserts that we successfully awaited for any transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_se... | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L48-L60 | [
"def await_any_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):\n \"\"\"\n Waits for a transform to exist based on does_exist.\n :param cli:\n :param transform_paths: An array of transform paths [...]\n :param does_exist: Whether or... | import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/assertions.py | assert_await_all_transforms_exist | python | def assert_await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
result = commands.await_all_transforms_exist(cli, transform_paths, does_exist, timeout_seconds)
assert result is True
return result | Asserts that we successfully awaited for all transforms to exist based on does_exist. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_paths:
:param does_exist: (True | False) the state change we are waiting for.
:param timeout_se... | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L63-L75 | [
"def await_all_transforms_exist(cli, transform_paths, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):\n \"\"\"\n Waits for all transforms specified in transform_paths to exist or not based on does_exist.\n :param cli:\n :param transform_paths: An array of transform paths [... | import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/assertions.py | assert_await_renderer_visible | python | def assert_await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
result = commands.await_renderer_visible(cli, transform_path, is_visible, timeout_seconds)
assert result is True
return result | Asserts that we successfully awaited for the renderer to be visible based on is_visible. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param transform_path:
:param is_visible: (True | False) the state change we are waiting for.
:param timeout_... | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L78-L90 | [
"def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):\n \"\"\"\n Waits for a transform renderer to become visible based on is_visible.\n :param cli:\n :param transform_path:\n :param is_visible: Whether or not to await for visi... | import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/assertions.py | assert_await_scene_loaded | python | def assert_await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
result = commands.await_scene_loaded(cli, scene_name, is_loaded, timeout_seconds)
assert result is True
return result | Asserts that we successfully awaited for the scene to be loaded based on is_loaded. If the timeout passes
or the expression is_registered != actual state, then it will fail.
:param cli:
:param scene_name:
:param is_loaded: (True | False) the state change we are waiting for.
:param timeout_seconds: T... | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/assertions.py#L93-L105 | [
"def await_scene_loaded(cli, scene_name, is_loaded=DEFAULT_SCENE_LOADED, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):\n \"\"\"\n Waits for a scene to be loaded based on is_loaded.\n :param cli:\n :param scene_name:\n :param is_loaded: Whether or not to await for loaded state (True | False)\n :param t... | import coeus_unity.commands as commands
DEFAULT_TIMEOUT_SECONDS = 60
DEFAULT_TRANSFORM_EXISTS = True
DEFAULT_RENDERER_VISIBLE = True
DEFAULT_SCENE_LOADED = True
def assert_transform_exists(cli, transform_path):
"""
Asserts that the transform exists.
:param cli:
:param transform_path:
:return:
... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/transform.py | TransformRef.add_child_ref | python | def add_child_ref(self, transform_ref):
if not isinstance(transform_ref, TransformRef):
raise ValueError("transform_ref must be of type TransformRef")
for child in self.children:
if child is transform_ref:
return
transform_ref.parent = self
self.... | Adds the TransformRef if it is not already added.
:param transform_ref:
:return: | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/transform.py#L11-L25 | null | class TransformRef:
id = None
transform_path = None
children = []
parent = None
def __init__(self, transform_path):
self.id = id
self.transform_path = transform_path
def create_child_ref(self, transform_path, child_id=None):
"""
Creates a new child TransformRef... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/transform.py | TransformRef.create_child_ref | python | def create_child_ref(self, transform_path, child_id=None):
transform_ref = TransformRef(transform_path, child_id)
self.add_child_ref(transform_ref)
return transform_ref | Creates a new child TransformRef with transform_path specified.
:param transform_path:
:param child_id:
:return: TransformRef child | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/transform.py#L27-L36 | [
"def add_child_ref(self, transform_ref):\n \"\"\"\n Adds the TransformRef if it is not already added.\n :param transform_ref:\n :return:\n \"\"\"\n if not isinstance(transform_ref, TransformRef):\n raise ValueError(\"transform_ref must be of type TransformRef\")\n\n for child in self.chi... | class TransformRef:
id = None
transform_path = None
children = []
parent = None
def __init__(self, transform_path):
self.id = id
self.transform_path = transform_path
def add_child_ref(self, transform_ref):
"""
Adds the TransformRef if it is not already added.
... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/transform.py | TransformRef.get_rendered_transform_path | python | def get_rendered_transform_path(self):
path = self.transform_path
parent = self.parent
while parent is not None:
path = "{0}/{1}".format(parent.transform_path, path)
parent = parent.parent
return path | Generates a rendered transform path
that is calculated from all parents.
:return: | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/transform.py#L38-L51 | null | class TransformRef:
id = None
transform_path = None
children = []
parent = None
def __init__(self, transform_path):
self.id = id
self.transform_path = transform_path
def add_child_ref(self, transform_ref):
"""
Adds the TransformRef if it is not already added.
... |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/transform.py | TransformRef.get_rendered_transform_path_relative | python | def get_rendered_transform_path_relative(self, relative_transform_ref):
path = self.transform_path
parent = self.parent
while parent is not None and parent is not relative_transform_ref:
path = "{0}/{1}".format(parent.transform_path, path)
parent = parent.parent
... | Generates a rendered transform path relative to
parent.
:param relative_transform_ref:
:return: | train | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/transform.py#L53-L67 | null | class TransformRef:
id = None
transform_path = None
children = []
parent = None
def __init__(self, transform_path):
self.id = id
self.transform_path = transform_path
def add_child_ref(self, transform_ref):
"""
Adds the TransformRef if it is not already added.
... |
clement-alexandre/TotemBionet | totembionet/src/model_picker/model_picker.py | pick_a_model_randomly | python | def pick_a_model_randomly(models: List[Any]) -> Any:
try:
return random.choice(models)
except IndexError as e:
raise ModelPickerException(cause=e) | Naive picking function, return one of the models chosen randomly. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/model_picker/model_picker.py#L16-L21 | null | # coding: utf-8
import random
from typing import Any, List
class ModelPickerException(Exception):
def __init__(self, message=None, cause=None):
self.message = message
self.cause = cause
def __str__(self):
return self.message or str(self.cause)
|
clement-alexandre/TotemBionet | totembionet/src/resource_table/resource_table_with_model.py | ResourceTableWithModel.as_data_frame | python | def as_data_frame(self) -> pandas.DataFrame:
header_gene = {}
header_multiplex = {}
headr_transitions = {}
for gene in self.influence_graph.genes:
header_gene[gene] = repr(gene)
header_multiplex[gene] = f"active multiplex on {gene!r}"
headr_transitions... | Create a panda DataFrame representation of the resource table. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/resource_table/resource_table_with_model.py#L25-L43 | [
"def _repr_multiplexes(self, gene: Gene, state: State) -> str:\n active_multiplexes = self.active_multiplexes_for_gene(gene, state)\n return f'{{{\", \".join(map(repr, active_multiplexes))}}}'\n",
"def _repr_transition(self, gene: Gene, state: State) -> str:\n transition = self.transition_table[gene, sta... | class ResourceTableWithModel(ResourceTable):
def __init__(self, model: DiscreteModel):
super().__init__(model.influence_graph)
self.model = model
self.transition_table: Dict[Tuple[Gene, State], Transition] = self._build_transition_table()
def _build_transition_table(self) -> Dict[Tuple[... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/multiplex.py | Multiplex.is_active | python | def is_active(self, state: 'State') -> bool:
# Remove the genes which does not contribute to the multiplex
sub_state = state.sub_state_by_gene_name(*self.expression.variables)
# If this state is not in the cache
if sub_state not in self._is_active:
params = self._transform_st... | Return True if the multiplex is active in the given state, false otherwise. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/multiplex.py#L21-L30 | [
"def _transform_state_to_dict(self, state: 'State') -> Dict[str, int]:\n return {gene.name: state for gene, state in state.items()\n if gene.name in self.expression.expression}\n"
] | class Multiplex:
def __init__(self, name: str, genes: Tuple[Gene], expression: Expression):
self.name: str = name
self.genes: Tuple[Gene] = genes
self.expression = expression
for gene in genes:
gene.add_multiplex(self)
# a cache table to store the already evaluat... |
clement-alexandre/TotemBionet | totembionet/src/ggea/ggea.py | Graph._build_graph | python | def _build_graph(self) -> nx.DiGraph:
digraph = nx.DiGraph()
for state in self.model.all_states():
self._number_of_states += 1
for next_state in self.model.available_state(state):
self._number_of_transitions += 1
digraph.add_edge(
... | Private method to build the graph from the model. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L22-L33 | [
"def _transform_state_to_string(self, state: State) -> str:\n \"\"\"\n Private method which transform a state to a string.\n\n Examples\n --------\n\n The model contains 2 genes: operon = {0, 1, 2}\n mucuB = {0, 1}\n\n >>> graph._transform_state_to_string({operon: 1,... | class Graph:
"""
The state graph for particular model.
"""
def __init__(self, model: DiscreteModel):
self.model = model
self._number_of_states = 0
self._number_of_transitions = 0
self._graph: nx.DiGraph = self._build_graph()
def _transform_state_to_string(self, stat... |
clement-alexandre/TotemBionet | totembionet/src/ggea/ggea.py | Graph._transform_state_to_string | python | def _transform_state_to_string(self, state: State) -> str:
return ''.join(str(state[gene]) for gene in self.model.genes) | Private method which transform a state to a string.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_state_to_string({operon: 1, mucuB: 0})
"10"
>>> graph._transform_state_to_string... | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L35-L51 | null | class Graph:
"""
The state graph for particular model.
"""
def __init__(self, model: DiscreteModel):
self.model = model
self._number_of_states = 0
self._number_of_transitions = 0
self._graph: nx.DiGraph = self._build_graph()
def _build_graph(self) -> nx.DiGraph:
... |
clement-alexandre/TotemBionet | totembionet/src/ggea/ggea.py | Graph.as_dot | python | def as_dot(self) -> str:
return nx.drawing.nx_pydot.to_pydot(self._graph).to_string() | Return as a string the dot version of the graph. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L65-L67 | null | class Graph:
"""
The state graph for particular model.
"""
def __init__(self, model: DiscreteModel):
self.model = model
self._number_of_states = 0
self._number_of_transitions = 0
self._graph: nx.DiGraph = self._build_graph()
def _build_graph(self) -> nx.DiGraph:
... |
clement-alexandre/TotemBionet | totembionet/src/ggea/ggea.py | Graph.export_to_dot | python | def export_to_dot(self, filename: str = 'output') -> None:
with open(filename + '.dot', 'w') as output:
output.write(self.as_dot()) | Export the graph to the dot file "filename.dot". | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L69-L72 | [
"def as_dot(self) -> str:\n \"\"\" Return as a string the dot version of the graph. \"\"\"\n return nx.drawing.nx_pydot.to_pydot(self._graph).to_string()\n"
] | class Graph:
"""
The state graph for particular model.
"""
def __init__(self, model: DiscreteModel):
self.model = model
self._number_of_states = 0
self._number_of_transitions = 0
self._graph: nx.DiGraph = self._build_graph()
def _build_graph(self) -> nx.DiGraph:
... |
clement-alexandre/TotemBionet | totembionet/src/resource_table/resource_table.py | ResourceTable._build_table | python | def _build_table(self) -> Dict[State, Tuple[Multiplex, ...]]:
result: Dict[State, Tuple[Multiplex, ...]] = {}
for state in self.influence_graph.all_states():
result[state] = tuple(multiplex for multiplex in self.influence_graph.multiplexes
if multiplex.is_a... | Private method which build the table which map a State to the active multiplex. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/resource_table/resource_table.py#L19-L25 | null | class ResourceTable:
"""
Create the resource table from the influence graph.
"""
def __init__(self, influence_graph: InfluenceGraph):
self.influence_graph: InfluenceGraph = influence_graph
self.table: Dict[State, Tuple[Multiplex, ...]] = self._build_table()
def active_multiplexes_f... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/discrete_model.py | DiscreteModel.find_transition | python | def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:
multiplexes = tuple(multiplex for multiplex in multiplexes if gene in multiplex.genes)
for transition in self.transitions:
if transition.gene == gene and set(transition.multiplexes) == set(multiplexes):
... | Find and return a transition in the model for the given gene and multiplexes.
Raise an AttributeError if there is no multiplex in the graph with the given name. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/discrete_model.py#L43-L52 | null | class DiscreteModel:
def __init__(self, influence_graph: InfluenceGraph, transitions: Tuple[Transition, ...] = ()):
self.influence_graph: InfluenceGraph = influence_graph
self.transitions: List[Transition] = list(transitions)
@property
def genes(self) -> Tuple[Gene, ...]:
""" Mappin... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/discrete_model.py | DiscreteModel.available_state | python | def available_state(self, state: State) -> Tuple[State, ...]:
result = []
for gene in self.genes:
result.extend(self.available_state_for_gene(gene, state))
if len(result) > 1 and state in result:
result.remove(state)
return tuple(result) | Return the state reachable from a given state. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/discrete_model.py#L54-L61 | [
"def available_state_for_gene(self, gene: Gene, state: State) -> Tuple[State, ...]:\n \"\"\" Return the state reachable from a given state for a particular gene. \"\"\"\n result: List[State] = []\n active_multiplex: Tuple[Multiplex] = gene.active_multiplex(state)\n transition: Transition = self.find_tra... | class DiscreteModel:
def __init__(self, influence_graph: InfluenceGraph, transitions: Tuple[Transition, ...] = ()):
self.influence_graph: InfluenceGraph = influence_graph
self.transitions: List[Transition] = list(transitions)
@property
def genes(self) -> Tuple[Gene, ...]:
""" Mappin... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/discrete_model.py | DiscreteModel.available_state_for_gene | python | def available_state_for_gene(self, gene: Gene, state: State) -> Tuple[State, ...]:
result: List[State] = []
active_multiplex: Tuple[Multiplex] = gene.active_multiplex(state)
transition: Transition = self.find_transition(gene, active_multiplex)
current_state: int = state[gene]
don... | Return the state reachable from a given state for a particular gene. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/discrete_model.py#L63-L77 | [
"def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:\n \"\"\" \n Find and return a transition in the model for the given gene and multiplexes.\n Raise an AttributeError if there is no multiplex in the graph with the given name.\n \"\"\"\n multiplexes = tuple(multi... | class DiscreteModel:
def __init__(self, influence_graph: InfluenceGraph, transitions: Tuple[Transition, ...] = ()):
self.influence_graph: InfluenceGraph = influence_graph
self.transitions: List[Transition] = list(transitions)
@property
def genes(self) -> Tuple[Gene, ...]:
""" Mappin... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/discrete_model.py | DiscreteModel._state_after_transition | python | def _state_after_transition(self, current_state: int, target_state: int) -> int:
return current_state + (current_state < target_state) - (current_state > target_state) | Return the state reachable after a transition.
Since the state for a gene can only change by 1, if the absolute value of the
difference current_state - target_state is greater than 1, we lower it to 1 or -1.
Examples
--------
>>> model._state_after_transition(0, 2)
... | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/discrete_model.py#L79-L98 | null | class DiscreteModel:
def __init__(self, influence_graph: InfluenceGraph, transitions: Tuple[Transition, ...] = ()):
self.influence_graph: InfluenceGraph = influence_graph
self.transitions: List[Transition] = list(transitions)
@property
def genes(self) -> Tuple[Gene, ...]:
""" Mappin... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/state.py | State.sub_state_by_gene_name | python | def sub_state_by_gene_name(self, *gene_names: str) -> 'State':
return State({gene: state for gene, state in self.items() if gene.name in gene_names}) | Create a sub state with only the gene passed in arguments.
Example
-------
>>> state.sub_state_by_gene_name('operon')
{operon: 2}
>>> state.sub_state_by_gene_name('mucuB')
{mucuB: 0} | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/state.py#L41-L54 | null | class State(collections.UserDict):
"""
Represent a state of the system at a certain time
i.e for each gene, we assign an integer which represent its level.
Examples
--------
>>> state = State()
>>> state[operon] = 2
>>> state[mucuB] = 0
>>> state[operon]
2
>>> for gene, lev... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/influence_graph.py | InfluenceGraph.find_gene_by_name | python | def find_gene_by_name(self, gene_name: str) -> Gene:
for gene in self.genes:
if gene.name == gene_name:
return gene
raise AttributeError(f'gene "{gene_name}" does not exist') | Find and return a gene in the influence graph with the given name.
Raise an AttributeError if there is no gene in the graph with the given name. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/influence_graph.py#L24-L32 | null | class InfluenceGraph:
def __init__(self, genes: Tuple[Gene, ...] = (), multiplexes: Tuple[Multiplex, ...] = ()):
self.genes: List[Gene] = list(genes)
self.multiplexes: List[Multiplex] = list(multiplexes)
def add_gene(self, gene: Gene) -> None:
""" Add a gene to the influence graph. """
... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/influence_graph.py | InfluenceGraph.find_multiplex_by_name | python | def find_multiplex_by_name(self, multiplex_name: str) -> Multiplex:
for multiplex in self.multiplexes:
if multiplex.name == multiplex_name:
return multiplex
raise AttributeError(f'multiplex "{multiplex_name}" does not exist') | Find and return a multiplex in the influence graph with the given name.
Raise an AttributeError if there is no multiplex in the graph with the given name. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/influence_graph.py#L38-L46 | null | class InfluenceGraph:
def __init__(self, genes: Tuple[Gene, ...] = (), multiplexes: Tuple[Multiplex, ...] = ()):
self.genes: List[Gene] = list(genes)
self.multiplexes: List[Multiplex] = list(multiplexes)
def add_gene(self, gene: Gene) -> None:
""" Add a gene to the influence graph. """
... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/influence_graph.py | InfluenceGraph.all_states | python | def all_states(self) -> Tuple[State, ...]:
return tuple(self._transform_list_of_states_to_state(states)
for states in self._cartesian_product_of_every_states_of_each_genes()) | Return all the possible states of this influence graph. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/influence_graph.py#L48-L51 | [
"def _cartesian_product_of_every_states_of_each_genes(self) -> Tuple[Tuple[int, ...]]:\n \"\"\" \n Private method which return the cartesian product of the states\n of the genes in the model. It represents all the possible state for a given model.\n\n Examples\n --------\n\n The model contains 2 g... | class InfluenceGraph:
def __init__(self, genes: Tuple[Gene, ...] = (), multiplexes: Tuple[Multiplex, ...] = ()):
self.genes: List[Gene] = list(genes)
self.multiplexes: List[Multiplex] = list(multiplexes)
def add_gene(self, gene: Gene) -> None:
""" Add a gene to the influence graph. """
... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/influence_graph.py | InfluenceGraph._cartesian_product_of_every_states_of_each_genes | python | def _cartesian_product_of_every_states_of_each_genes(self) -> Tuple[Tuple[int, ...]]:
if not self.genes:
return ()
return tuple(product(*[gene.states for gene in self.genes])) | Private method which return the cartesian product of the states
of the genes in the model. It represents all the possible state for a given model.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
Then this metho... | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/influence_graph.py#L53-L69 | null | class InfluenceGraph:
def __init__(self, genes: Tuple[Gene, ...] = (), multiplexes: Tuple[Multiplex, ...] = ()):
self.genes: List[Gene] = list(genes)
self.multiplexes: List[Multiplex] = list(multiplexes)
def add_gene(self, gene: Gene) -> None:
""" Add a gene to the influence graph. """
... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/influence_graph.py | InfluenceGraph._transform_list_of_states_to_state | python | def _transform_list_of_states_to_state(self, state: List[int]) -> State:
return State({gene: state[i] for i, gene in enumerate(self.genes)}) | Private method which transform a list which contains the state of the gene
in the models to a State object.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_list_of_states_to_dict_of_states(... | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/influence_graph.py#L71-L86 | null | class InfluenceGraph:
def __init__(self, genes: Tuple[Gene, ...] = (), multiplexes: Tuple[Multiplex, ...] = ()):
self.genes: List[Gene] = list(genes)
self.multiplexes: List[Multiplex] = list(multiplexes)
def add_gene(self, gene: Gene) -> None:
""" Add a gene to the influence graph. """
... |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/gene.py | Gene.active_multiplex | python | def active_multiplex(self, state: 'State') -> Tuple['Multiplex']:
return tuple(multiplex for multiplex in self.multiplexes if multiplex.is_active(state)) | Return a tuple of all the active multiplex in the given state. | train | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/gene.py#L16-L20 | null | class Gene:
def __init__(self, name: str, states: Tuple[int, ...]):
self.name: str = name
self.states: Tuple[int, ...] = states
self.multiplexes: List['Multiplex'] = []
def add_multiplex(self, multiplex: 'Multiplex') -> None:
if multiplex not in self.multiplexes:
sel... |
ttroy50/pyephember | pyephember/pyephember.py | EphEmber._requires_refresh_token | python | def _requires_refresh_token(self):
expires_on = datetime.datetime.strptime(
self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ')
refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
return expires_on < refresh | Check if a refresh of the token is needed | train | https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L32-L39 | null | class EphEmber:
"""Interacts with a EphEmber thermostat via API.
Example usage: t = EphEmber('me@somewhere.com', 'mypasswd')
t.getZoneTemperature('myzone') # Get temperature
"""
# pylint: disable=too-many-instance-attributes
def _request_token(self, force=False):
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.