sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def get_orders(self, instrument=None, count=50):
"""
See more:
http://developer.oanda.com/rest-live/orders/#getOrdersForAnAccount
"""
url = "{0}/{1}/accounts/{2}/orders".format(
self.domain,
self.API_VERSION,
self.account_id
)
... | See more:
http://developer.oanda.com/rest-live/orders/#getOrdersForAnAccount | entailment |
def get_order(self, order_id):
"""
See more:
http://developer.oanda.com/rest-live/orders/#getInformationForAnOrder
"""
url = "{0}/{1}/accounts/{2}/orders/{3}".format(
self.domain,
self.API_VERSION,
self.account_id,
order_id
... | See more:
http://developer.oanda.com/rest-live/orders/#getInformationForAnOrder | entailment |
def create_order(self, order):
"""
See more:
http://developer.oanda.com/rest-live/orders/#createNewOrder
"""
url = "{0}/{1}/accounts/{2}/orders".format(
self.domain,
self.API_VERSION,
self.account_id
)
try:
r... | See more:
http://developer.oanda.com/rest-live/orders/#createNewOrder | entailment |
def get_trades(self, max_id=None, count=None, instrument=None, ids=None):
""" Get a list of open trades
Parameters
----------
max_id : int
The server will return trades with id less than or equal
to this, in descending order (for pagination)
... | Get a list of open trades
Parameters
----------
max_id : int
The server will return trades with id less than or equal
to this, in descending order (for pagination)
count : int
Maximum number of open trades to return. Defaul... | entailment |
def update_trade(
self,
trade_id,
stop_loss=None,
take_profit=None,
trailing_stop=None
):
""" Modify an existing trade.
Note: Only the specified parameters will be modified. All
other parameters will remain unchanged. To remove an
... | Modify an existing trade.
Note: Only the specified parameters will be modified. All
other parameters will remain unchanged. To remove an
optional parameter, set its value to 0.
Parameters
----------
trade_id : int
The id of the tr... | entailment |
def request_transaction_history(self):
""" Request full account history.
Submit a request for a full transaction history. A
successfully accepted submission results in a response
containing a URL in the Location header to a file that will
be available once the r... | Request full account history.
Submit a request for a full transaction history. A
successfully accepted submission results in a response
containing a URL in the Location header to a file that will
be available once the request is served. Response for the
URL ... | entailment |
def get_transaction_history(self, max_wait=5.0):
""" Download full account history.
Uses request_transaction_history to get the transaction
history URL, then polls the given URL until it's ready (or
the max_wait time is reached) and provides the decoded
response.... | Download full account history.
Uses request_transaction_history to get the transaction
history URL, then polls the given URL until it's ready (or
the max_wait time is reached) and provides the decoded
response.
Parameters
----------
m... | entailment |
def create_account(self, currency=None):
""" Create a new account.
This call is only available on the sandbox system. Please
create accounts on fxtrade.oanda.com on our production
system.
See more:
http://developer.oanda.com/rest-sandbox/accounts/#-a... | Create a new account.
This call is only available on the sandbox system. Please
create accounts on fxtrade.oanda.com on our production
system.
See more:
http://developer.oanda.com/rest-sandbox/accounts/#-a-name-createtestaccount-a-create-a-test-account | entailment |
def get_accounts(self, username=None):
""" Get a list of accounts owned by the user.
Parameters
----------
username : string
The name of the user. Note: This is only required on the
sandbox, on production systems your access token will
... | Get a list of accounts owned by the user.
Parameters
----------
username : string
The name of the user. Note: This is only required on the
sandbox, on production systems your access token will
identify you.
See more:
... | entailment |
def choose(self):
"""Marks the item as the one the user is in."""
if not self.choosed:
self.choosed = True
self.pos = self.pos + Sep(5, 0) | Marks the item as the one the user is in. | entailment |
def stop_choose(self):
"""Marks the item as the one the user is not in."""
if self.choosed:
self.choosed = False
self.pos = self.pos + Sep(-5, 0) | Marks the item as the one the user is not in. | entailment |
def get_darker_color(self):
"""The color of the clicked version of the MenuElement. Darker than the normal one."""
# we change a bit the color in one direction
if bw_contrasted(self._true_color, 30) == WHITE:
color = mix(self._true_color, WHITE, 0.9)
else:
color =... | The color of the clicked version of the MenuElement. Darker than the normal one. | entailment |
def render(self, screen):
"""Renders the MenuElement"""
self.rect.render(screen)
super(MenuElement, self).render(screen) | Renders the MenuElement | entailment |
def gui():
"""Main function"""
# #######
# setup all objects
# #######
zones = [ALL]
last_zones = []
COLORS.remove(WHITE)
screen = pygame.display.set_mode(SCREEN_SIZE, DOUBLEBUF)
pygame.display.set_caption('Bezier simulator')
pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTT... | Main function | entailment |
def gui():
"""Main function"""
# #######
# setup all objects
# #######
os.environ['SDL_VIDEO_CENTERED'] = '1'
clock = pygame.time.Clock()
screen = pygame.display.set_mode(SCREEN_SIZE, DOUBLEBUF | NOFRAME)
pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTTONDOWN])
game = Morpion()
... | Main function | entailment |
def px_to_pt(self, px):
"""Convert a size in pxel to a size in points."""
if px < 200:
pt = self.PX_TO_PT[px]
else:
pt = int(floor((px - 1.21) / 1.332))
return pt | Convert a size in pxel to a size in points. | entailment |
def set_size(self, pt=None, px=None):
"""
Set the size of the font, in px or pt.
The px method is a bit inacurate, there can be one or two px less, and max 4 for big numbers (like 503)
but the size is never over-estimated. It makes almost the good value.
"""
assert (pt,... | Set the size of the font, in px or pt.
The px method is a bit inacurate, there can be one or two px less, and max 4 for big numbers (like 503)
but the size is never over-estimated. It makes almost the good value. | entailment |
def text(self):
"""Return the string to render."""
if callable(self._text):
return str(self._text())
return str(self._text) | Return the string to render. | entailment |
def color(self, value):
"""Set the color to a new value (tuple). Renders the text if needed."""
if value != self.color:
self._color = value
self._render() | Set the color to a new value (tuple). Renders the text if needed. | entailment |
def bg_color(self, value):
"""Sets the color to a new value (tuple). Renders the text if needed."""
if value != self.bg_color:
self._bg_color = value
self._render() | Sets the color to a new value (tuple). Renders the text if needed. | entailment |
def set_font_size(self, pt=None, px=None):
"""Set the font size to the desired size, in pt or px."""
self.font.set_size(pt, px)
self._render() | Set the font size to the desired size, in pt or px. | entailment |
def _render(self):
"""
Render the text.
Avoid using this fonction too many time as it is slow as it is low to render text and blit it.
"""
self._last_text = self.text
self._surface = self.font.render(self.text, True, self.color, self.bg_color)
rect = self._surf... | Render the text.
Avoid using this fonction too many time as it is slow as it is low to render text and blit it. | entailment |
def render(self, display):
"""Render basicly the text."""
# to handle changing objects / callable
if self.text != self._last_text:
self._render()
display.blit(self._surface, (self.topleft, self.size)) | Render basicly the text. | entailment |
def cursor(self):
"""The position of the cursor in the text."""
if self._cursor < 0:
self.cursor = 0
if self._cursor > len(self):
self.cursor = len(self)
return self._cursor | The position of the cursor in the text. | entailment |
def move_cursor_one_letter(self, letter=RIGHT):
"""Move the cursor of one letter to the right (1) or the the left."""
assert letter in (self.RIGHT, self.LEFT)
if letter == self.RIGHT:
self.cursor += 1
if self.cursor > len(self.text):
self.cursor -= 1
... | Move the cursor of one letter to the right (1) or the the left. | entailment |
def move_cursor_one_word(self, word=LEFT):
"""Move the cursor of one word to the right (1) or the the left (-1)."""
assert word in (self.RIGHT, self.LEFT)
if word == self.RIGHT:
papy = self.text.find(' ', self.cursor) + 1
if not papy:
papy = len(self)
... | Move the cursor of one word to the right (1) or the the left (-1). | entailment |
def delete_one_letter(self, letter=RIGHT):
"""Delete one letter the right or the the left of the cursor."""
assert letter in (self.RIGHT, self.LEFT)
if letter == self.LEFT:
papy = self.cursor
self.text = self.text[:self.cursor - 1] + self.text[self.cursor:]
... | Delete one letter the right or the the left of the cursor. | entailment |
def delete_one_word(self, word=RIGHT):
"""Delete one word the right or the the left of the cursor."""
assert word in (self.RIGHT, self.LEFT)
if word == self.RIGHT:
papy = self.text.find(' ', self.cursor) + 1
if not papy:
papy = len(self.text)
... | Delete one word the right or the the left of the cursor. | entailment |
def add_letter(self, letter):
"""Add a letter at the cursor pos."""
assert isinstance(letter, str)
assert len(letter) == 1
self.text = self.text[:self.cursor] + letter + self.text[self.cursor:]
self.cursor += 1 | Add a letter at the cursor pos. | entailment |
def update(self, event_or_list):
"""Update the text and position of cursor according to the event passed."""
event_or_list = super().update(event_or_list)
for e in event_or_list:
if e.type == KEYDOWN:
if e.key == K_RIGHT:
if e.mod * KMOD_CTRL:
... | Update the text and position of cursor according to the event passed. | entailment |
def _render(self):
"""
Render the text.
Avoid using this fonction too many times as it is slow as it is slow to render text and blit it.
"""
self._last_text = self.text
self._surface = self.font.render(self.text, True, self.color, self.bg_color)
size = self.wid... | Render the text.
Avoid using this fonction too many times as it is slow as it is slow to render text and blit it. | entailment |
def shawn_text(self):
"""The text displayed instead of the real one."""
if len(self._shawn_text) == len(self):
return self._shawn_text
if self.style == self.DOTS:
return chr(0x2022) * len(self)
ranges = [
(902, 1366),
(192, 683),
... | The text displayed instead of the real one. | entailment |
def cursor_pos(self):
"""The cursor position in pixels."""
if len(self) == 0:
return self.left + self.default_text.get_width()
papy = self._surface.get_width()
if papy > self.w:
shift = papy - self.width
else:
shift = 0
return self.le... | The cursor position in pixels. | entailment |
def _render(self):
"""
Render the text.
Avoid using this fonction too many times as it is slow as it is slow to render text and blit it.
"""
self._last_text = self.shawn_text
self._surface = self.font.render(self.shawn_text, True, self.color, self.bg_color)
siz... | Render the text.
Avoid using this fonction too many times as it is slow as it is slow to render text and blit it. | entailment |
def render(self, display):
"""Render basicly the text."""
# to handle changing objects / callable
if self.shawn_text != self._last_text:
self._render()
if self.text:
papy = self._surface.get_width()
if papy <= self.width:
display.blit... | Render basicly the text. | entailment |
def latex_to_img(tex):
"""Return a pygame image from a latex template."""
with tempfile.TemporaryDirectory() as tmpdirname:
with open(tmpdirname + r'\tex.tex', 'w') as f:
f.write(tex)
os.system(r"latex {0}\tex.tex -halt-on-error -interaction=batchmode -disable-in... | Return a pygame image from a latex template. | entailment |
def mix(color1, color2, pos=0.5):
"""
Return the mix of two colors at a state of :pos:
Retruns color1 * pos + color2 * (1 - pos)
"""
opp_pos = 1 - pos
red = color1[0] * pos + color2[0] * opp_pos
green = color1[1] * pos + color2[1] * opp_pos
blue = color1[2] * pos + color2[2] * opp_pos
... | Return the mix of two colors at a state of :pos:
Retruns color1 * pos + color2 * (1 - pos) | entailment |
def name2rgb(name):
"""Convert the name of a color into its RGB value"""
try:
import colour
except ImportError:
raise ImportError('You need colour to be installed: pip install colour')
c = colour.Color(name)
color = int(c.red * 255), int(c.green * 255), int(c.blue * 255)
return ... | Convert the name of a color into its RGB value | entailment |
def parse_page(page):
"""Parse the command man page."""
colors = get_config()['colors']
with io.open(page, encoding='utf-8') as f:
lines = f.readlines()
output_lines = []
for line in lines[1:]:
if is_headline(line):
continue
elif is_description(line):
... | Parse the command man page. | entailment |
def configure_logging(level=logging.DEBUG):
"""Configure the module logging engine."""
if level == logging.DEBUG:
# For debugging purposes, log from everyone!
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
re... | Configure the module logging engine. | entailment |
def path_join(*args):
"""
Wrapper around `os.path.join`.
Makes sure to join paths of the same type (bytes).
"""
args = (paramiko.py3compat.u(arg) for arg in args)
return os.path.join(*args) | Wrapper around `os.path.join`.
Makes sure to join paths of the same type (bytes). | entailment |
def parse_username_password_hostname(remote_url):
"""
Parse a command line string and return username, password, remote hostname and remote path.
:param remote_url: A command line string.
:return: A tuple, containing username, password, remote hostname and remote path.
"""
assert remote_url
... | Parse a command line string and return username, password, remote hostname and remote path.
:param remote_url: A command line string.
:return: A tuple, containing username, password, remote hostname and remote path. | entailment |
def get_ssh_agent_keys(logger):
"""
Ask the SSH agent for a list of keys, and return it.
:return: A reference to the SSH agent and a list of keys.
"""
agent, agent_keys = None, None
try:
agent = paramiko.agent.Agent()
_agent_keys = agent.get_keys()
if not _agent_keys:
... | Ask the SSH agent for a list of keys, and return it.
:return: A reference to the SSH agent and a list of keys. | entailment |
def create_parser():
"""Create the CLI argument parser."""
parser = argparse.ArgumentParser(
description='Sync a local and a remote folder through SFTP.'
)
parser.add_argument(
"path",
type=str,
metavar="local-path",
help="the path of the local folder",
)
... | Create the CLI argument parser. | entailment |
def main(args=None):
"""The main."""
parser = create_parser()
args = vars(parser.parse_args(args))
log_mapping = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'NOTSET': lo... | The main. | entailment |
def _must_be_deleted(local_path, r_st):
"""Return True if the remote correspondent of local_path has to be deleted.
i.e. if it doesn't exists locally or if it has a different type from the remote one."""
# if the file doesn't exists
if not os.path.lexists(local_path):
return... | Return True if the remote correspondent of local_path has to be deleted.
i.e. if it doesn't exists locally or if it has a different type from the remote one. | entailment |
def _match_modes(self, remote_path, l_st):
"""Match mod, utime and uid/gid with locals one."""
self.sftp.chmod(remote_path, S_IMODE(l_st.st_mode))
self.sftp.utime(remote_path, (l_st.st_atime, l_st.st_mtime))
if self.chown:
self.sftp.chown(remote_path, l_st.st_uid, l_st.st_gi... | Match mod, utime and uid/gid with locals one. | entailment |
def file_upload(self, local_path, remote_path, l_st):
"""Upload local_path to remote_path and set permission and mtime."""
self.sftp.put(local_path, remote_path)
self._match_modes(remote_path, l_st) | Upload local_path to remote_path and set permission and mtime. | entailment |
def remote_delete(self, remote_path, r_st):
"""Remove the remote directory node."""
# If it's a directory, then delete content and directory
if S_ISDIR(r_st.st_mode):
for item in self.sftp.listdir_attr(remote_path):
full_path = path_join(remote_path, item.filename)
... | Remove the remote directory node. | entailment |
def check_for_deletion(self, relative_path=None):
"""Traverse the entire remote_path tree.
Find files/directories that need to be deleted,
not being present in the local folder.
"""
if not relative_path:
relative_path = str() # root of shared directory tree
... | Traverse the entire remote_path tree.
Find files/directories that need to be deleted,
not being present in the local folder. | entailment |
def create_update_symlink(self, link_destination, remote_path):
"""Create a new link pointing to link_destination in remote_path position."""
try: # if there's anything, delete it
self.sftp.remove(remote_path)
except IOError: # that's fine, nothing exists there!
pass
... | Create a new link pointing to link_destination in remote_path position. | entailment |
def node_check_for_upload_create(self, relative_path, f):
"""Check if the given directory tree node has to be uploaded/created on the remote folder."""
if not relative_path:
# we're at the root of the shared directory tree
relative_path = str()
# the (absolute) local add... | Check if the given directory tree node has to be uploaded/created on the remote folder. | entailment |
def check_for_upload_create(self, relative_path=None):
"""Traverse the relative_path tree and check for files that need to be uploaded/created.
Relativity here refers to the shared directory tree."""
for f in os.listdir(
path_join(
self.local_path, relative_path) if ... | Traverse the relative_path tree and check for files that need to be uploaded/created.
Relativity here refers to the shared directory tree. | entailment |
def run(self):
"""Run the sync.
Confront the local and the remote directories and perform the needed changes."""
# Check if remote path is present
try:
self.sftp.stat(self.remote_path)
except FileNotFoundError as e:
if self.create_remote_directory:
... | Run the sync.
Confront the local and the remote directories and perform the needed changes. | entailment |
def list_files(start_path):
"""tree unix command replacement."""
s = u'\n'
for root, dirs, files in os.walk(start_path):
level = root.replace(start_path, '').count(os.sep)
indent = ' ' * 4 * level
s += u'{}{}/\n'.format(indent, os.path.basename(root))
sub_indent = ' ' * 4 * (... | tree unix command replacement. | entailment |
def file_tree(start_path):
"""
Create a nested dictionary that represents the folder structure of `start_path`.
Liberally adapted from
http://code.activestate.com/recipes/577879-create-a-nested-dictionary-from-oswalk/
"""
nested_dirs = {}
root_dir = start_path.rstrip(os.sep)
start = roo... | Create a nested dictionary that represents the folder structure of `start_path`.
Liberally adapted from
http://code.activestate.com/recipes/577879-create-a-nested-dictionary-from-oswalk/ | entailment |
def capture_sys_output():
"""Capture standard output and error."""
capture_out, capture_err = StringIO(), StringIO()
current_out, current_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = capture_out, capture_err
yield capture_out, capture_err
finally:
sys.stdout, sy... | Capture standard output and error. | entailment |
def suppress_logging(log_level=logging.CRITICAL):
"""Suppress logging."""
logging.disable(log_level)
yield
logging.disable(logging.NOTSET) | Suppress logging. | entailment |
def override_env_variables():
"""Override user environmental variables with custom one."""
env_vars = ("LOGNAME", "USER", "LNAME", "USERNAME")
old = [os.environ[v] if v in os.environ else None for v in env_vars]
for v in env_vars:
os.environ[v] = "test"
yield
for i, v in enumerate(env_... | Override user environmental variables with custom one. | entailment |
def override_ssh_auth_env():
"""Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent."""
ssh_auth_sock = "SSH_AUTH_SOCK"
old_ssh_auth_sock = os.environ.get(ssh_auth_sock)
del os.environ[ssh_auth_sock]
yield
if old_ssh_auth_sock:
os.environ[ssh_auth_sock] = ol... | Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent. | entailment |
def get_config():
"""Get the configurations from .tldrrc and return it as a dict."""
config_path = path.join(
(os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')),
'.tldrrc')
if not path.exists(config_path):
sys.exit("Can't find config file at: {0}. You may use `tldr init` "
... | Get the configurations from .tldrrc and return it as a dict. | entailment |
def parse_man_page(command, platform):
"""Parse the man page and return the parsed lines."""
page_path = find_page_location(command, platform)
output_lines = parse_page(page_path)
return output_lines | Parse the man page and return the parsed lines. | entailment |
def find_page_location(command, specified_platform):
"""Find the command man page in the pages directory."""
repo_directory = get_config()['repo_directory']
default_platform = get_config()['platform']
command_platform = (
specified_platform if specified_platform else default_platform)
with ... | Find the command man page in the pages directory. | entailment |
def find(command, on):
"""Find the command usage."""
output_lines = parse_man_page(command, on)
click.echo(''.join(output_lines)) | Find the command usage. | entailment |
def update():
"""Update to the latest pages."""
repo_directory = get_config()['repo_directory']
os.chdir(repo_directory)
click.echo("Check for updates...")
local = subprocess.check_output('git rev-parse master'.split()).strip()
remote = subprocess.check_output(
'git ls-remote https://gi... | Update to the latest pages. | entailment |
def init():
"""Init config file."""
default_config_path = path.join(
(os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')),
'.tldrrc')
if path.exists(default_config_path):
click.echo("There is already a config file exists, "
"skip initializing it.")
else:... | Init config file. | entailment |
def locate(command, on):
"""Locate the command's man page."""
location = find_page_location(command, on)
click.echo(location) | Locate the command's man page. | entailment |
def relate(cls, propname, *args, **kwargs):
"""Produce a relationship between this mapped table and another
one.
This makes usage of SQLAlchemy's :func:`sqlalchemy.orm.relationship`
construct.
"""
class_mapper(cls)._configure_property(propname, relation... | Produce a relationship between this mapped table and another
one.
This makes usage of SQLAlchemy's :func:`sqlalchemy.orm.relationship`
construct. | entailment |
def execute(self, stmt, **params):
"""Execute a SQL statement.
The statement may be a string SQL string,
an :func:`sqlalchemy.sql.expression.select` construct, or a
:func:`sqlalchemy.sql.expression.text`
construct.
"""
return self.session.execute(sql.text(stmt... | Execute a SQL statement.
The statement may be a string SQL string,
an :func:`sqlalchemy.sql.expression.select` construct, or a
:func:`sqlalchemy.sql.expression.text`
construct. | entailment |
def map_to(self, attrname, tablename=None, selectable=None,
schema=None, base=None, mapper_args=util.immutabledict()):
"""Configure a mapping to the given attrname.
This is the "master" method that can be used to create any
configuration.
:param attrname: String a... | Configure a mapping to the given attrname.
This is the "master" method that can be used to create any
configuration.
:param attrname: String attribute name which will be
established as an attribute on this :class:.`.SQLSoup`
instance.
:param base: a Python class wh... | entailment |
def map(self, selectable, base=None, **mapper_args):
"""Map a selectable directly.
The class and its mapping are not cached and will
be discarded once dereferenced (as of 0.6.6).
:param selectable: an :func:`.expression.select` construct.
:param base: a Python class which will ... | Map a selectable directly.
The class and its mapping are not cached and will
be discarded once dereferenced (as of 0.6.6).
:param selectable: an :func:`.expression.select` construct.
:param base: a Python class which will be used as the
base for the mapped class. If ``None``,... | entailment |
def with_labels(self, selectable, base=None, **mapper_args):
"""Map a selectable directly, wrapping the
selectable in a subquery with labels.
The class and its mapping are not cached and will
be discarded once dereferenced (as of 0.6.6).
:param selectable: an :func:`.expressio... | Map a selectable directly, wrapping the
selectable in a subquery with labels.
The class and its mapping are not cached and will
be discarded once dereferenced (as of 0.6.6).
:param selectable: an :func:`.expression.select` construct.
:param base: a Python class which will be u... | entailment |
def join(self, left, right, onclause=None, isouter=False,
base=None, **mapper_args):
"""Create an :func:`.expression.join` and map to it.
The class and its mapping are not cached and will
be discarded once dereferenced (as of 0.6.6).
:param left: a mapped class or tabl... | Create an :func:`.expression.join` and map to it.
The class and its mapping are not cached and will
be discarded once dereferenced (as of 0.6.6).
:param left: a mapped class or table object.
:param right: a mapped class or table object.
:param onclause: optional "ON" clause con... | entailment |
def entity(self, attr, schema=None):
"""Return the named entity from this :class:`.SQLSoup`, or
create if not present.
For more generalized mapping, see :meth:`.map_to`.
"""
try:
return self._cache[attr]
except KeyError, ke:
return self.map_to(a... | Return the named entity from this :class:`.SQLSoup`, or
create if not present.
For more generalized mapping, see :meth:`.map_to`. | entailment |
def distance(f1, f2):
"""\
Distance between 2 features. The integer result is always positive or zero.
If the features overlap or touch, it is zero.
>>> from intersecter import Feature, distance
>>> distance(Feature(1, 2), Feature(12, 13))
10
>>> distance(Feature(1, 2), Feature(2, 3))
0
... | \
Distance between 2 features. The integer result is always positive or zero.
If the features overlap or touch, it is zero.
>>> from intersecter import Feature, distance
>>> distance(Feature(1, 2), Feature(12, 13))
10
>>> distance(Feature(1, 2), Feature(2, 3))
0
>>> distance(Feature(1, 1... | entailment |
def find(self, start, end, chrom=None):
"""Return a object of all stored intervals intersecting between (start, end) inclusive."""
intervals = self.intervals[chrom]
ilen = len(intervals)
# NOTE: we only search for starts, since any feature that starts within max_len of
# the quer... | Return a object of all stored intervals intersecting between (start, end) inclusive. | entailment |
def left(self, f, n=1):
"""return the nearest n features strictly to the left of a Feature f.
Overlapping features are not considered as to the left.
f: a Feature object
n: the number of features to return
"""
intervals = self.intervals[f.chrom]
if intervals == [... | return the nearest n features strictly to the left of a Feature f.
Overlapping features are not considered as to the left.
f: a Feature object
n: the number of features to return | entailment |
def right(self, f, n=1):
"""return the nearest n features strictly to the right of a Feature f.
Overlapping features are not considered as to the right.
f: a Feature object
n: the number of features to return
"""
intervals = self.intervals[f.chrom]
ilen = len(int... | return the nearest n features strictly to the right of a Feature f.
Overlapping features are not considered as to the right.
f: a Feature object
n: the number of features to return | entailment |
def upstream(self, f, n=1):
"""find n upstream features where upstream is determined by
the strand of the query Feature f
Overlapping features are not considered.
f: a Feature object
n: the number of features to return
"""
if f.strand == -1:
return se... | find n upstream features where upstream is determined by
the strand of the query Feature f
Overlapping features are not considered.
f: a Feature object
n: the number of features to return | entailment |
def downstream(self, f, n=1):
"""find n downstream features where downstream is determined by
the strand of the query Feature f
Overlapping features are not considered.
f: a Feature object
n: the number of features to return
"""
if f.strand == -1:
ret... | find n downstream features where downstream is determined by
the strand of the query Feature f
Overlapping features are not considered.
f: a Feature object
n: the number of features to return | entailment |
def knearest(self, f_or_start, end=None, chrom=None, k=1):
"""return the n nearest neighbors to the given feature
f: a Feature object
k: the number of features to return
"""
if end is not None:
f = Feature(f_or_start, end, chrom=chrom)
else:
f = ... | return the n nearest neighbors to the given feature
f: a Feature object
k: the number of features to return | entailment |
def find(self, start, end):
"""find all elements between (or overlapping) start and end"""
if self.intervals and not end < self.intervals[0].start:
overlapping = [i for i in self.intervals if i.end >= start
and i.start <= end]
else:... | find all elements between (or overlapping) start and end | entailment |
def sequence(db, chrom, start, end):
"""
return the sequence for a region using the UCSC DAS
server. note the start is 1-based
each feature will have it's own .sequence method which sends
the correct start and end to this function.
>>> sequence('hg18', 'chr2', 2223, 2230)
'caacttag'
"""... | return the sequence for a region using the UCSC DAS
server. note the start is 1-based
each feature will have it's own .sequence method which sends
the correct start and end to this function.
>>> sequence('hg18', 'chr2', 2223, 2230)
'caacttag' | entailment |
def set_table(genome, table, table_name, connection_string, metadata):
"""
alter the table to work between different
dialects
"""
table = Table(table_name, genome._metadata, autoload=True,
autoload_with=genome.bind, extend_existing=True)
#print "\t".join([c.name for c in tab... | alter the table to work between different
dialects | entailment |
def create_url(self, db="", user="genome", host="genome-mysql.cse.ucsc.edu",
password="", dialect="mysqldb"):
"""
internal: create a dburl from a set of parameters or the defaults on
this object
"""
if os.path.exists(db):
db = "sqlite:///" + db
# Is t... | internal: create a dburl from a set of parameters or the defaults on
this object | entailment |
def mirror(self, tables, dest_url):
"""
miror a set of `tables` from `dest_url`
Returns a new Genome object
Parameters
----------
tables : list
an iterable of tables
dest_url: str
a dburl string, e.g. 'sqlite:///local.db'
"""
... | miror a set of `tables` from `dest_url`
Returns a new Genome object
Parameters
----------
tables : list
an iterable of tables
dest_url: str
a dburl string, e.g. 'sqlite:///local.db' | entailment |
def dataframe(self, table):
"""
create a pandas dataframe from a table or query
Parameters
----------
table : table
a table in this database or a query
limit: integer
an integer limit on the query
offset: integer
an offset f... | create a pandas dataframe from a table or query
Parameters
----------
table : table
a table in this database or a query
limit: integer
an integer limit on the query
offset: integer
an offset for the query | entailment |
def load_file(self, fname, table=None, sep="\t", bins=False, indexes=None):
"""
use some of the machinery in pandas to load a file into a table
Parameters
----------
fname : str
filename or filehandle to load
table : str
table to load the file t... | use some of the machinery in pandas to load a file into a table
Parameters
----------
fname : str
filename or filehandle to load
table : str
table to load the file to
sep : str
CSV separator
bins : bool
add a "bin" colu... | entailment |
def david_go(refseq_list, annot=('SP_PIR_KEYWORDS', 'GOTERM_BP_FAT',
'GOTERM_CC_FAT', 'GOTERM_MF_FAT')):
"""
open a web-browser to the DAVID online enrichment tool
Parameters
----------
refseq_list : list
list of refseq names ... | open a web-browser to the DAVID online enrichment tool
Parameters
----------
refseq_list : list
list of refseq names to check for enrichment
annot : list
iterable of DAVID annotations to check for enrichment | entailment |
def bin_query(self, table, chrom, start, end):
"""
perform an efficient spatial query using the bin column if available.
The possible bins are calculated from the `start` and `end` sent to
this function.
Parameters
----------
table : str or table
tabl... | perform an efficient spatial query using the bin column if available.
The possible bins are calculated from the `start` and `end` sent to
this function.
Parameters
----------
table : str or table
table to query
chrom : str
chromosome for the query... | entailment |
def upstream(self, table, chrom_or_feat, start=None, end=None, k=1):
"""
Return k-nearest upstream features
Parameters
----------
table : str or table
table against which to query
chrom_or_feat : str or feat
either a chromosome, e.g. 'chr3' or a... | Return k-nearest upstream features
Parameters
----------
table : str or table
table against which to query
chrom_or_feat : str or feat
either a chromosome, e.g. 'chr3' or a feature with .chrom, .start,
.end attributes
start : int
... | entailment |
def knearest(self, table, chrom_or_feat, start=None, end=None, k=1,
_direction=None):
"""
Return k-nearest features
Parameters
----------
table : str or table
table against which to query
chrom_or_feat : str or feat
either a chromoso... | Return k-nearest features
Parameters
----------
table : str or table
table against which to query
chrom_or_feat : str or feat
either a chromosome, e.g. 'chr3' or a feature with .chrom, .start,
.end attributes
start : int
if `chr... | entailment |
def annotate(self, fname, tables, feature_strand=False, in_memory=False,
header=None, out=sys.stdout, parallel=False):
"""
annotate a file with a number of tables
Parameters
----------
fname : str or file
file name or file-handle
tables : list
... | annotate a file with a number of tables
Parameters
----------
fname : str or file
file name or file-handle
tables : list
list of tables with which to annotate `fname`
feature_strand : bool
if this is True, then the up/downstream designations... | entailment |
def bins(start, end):
"""
Get all the bin numbers for a particular interval defined by
(start, end]
"""
if end - start < 536870912:
offsets = [585, 73, 9, 1]
else:
raise BigException
offsets = [4681, 585, 73, 9, 1]
binFirstShift... | Get all the bin numbers for a particular interval defined by
(start, end] | entailment |
def save_bed(cls, query, filename=sys.stdout):
"""
write a bed12 file of the query.
Parameters
----------
query : query
a table or query to save to file
filename : file
string or filehandle to write output
"""
out = _open(filename... | write a bed12 file of the query.
Parameters
----------
query : query
a table or query to save to file
filename : file
string or filehandle to write output | entailment |
def staticfile_node(parser, token, optimize_if_possible=False):
"""For example:
{% staticfile "/js/foo.js" %}
or
{% staticfile "/js/foo.js" as variable_name %}
Or for multiples:
{% staticfile "/foo.js; /bar.js" %}
or
{% staticfile "/foo.js; /bar.js" as varia... | For example:
{% staticfile "/js/foo.js" %}
or
{% staticfile "/js/foo.js" as variable_name %}
Or for multiples:
{% staticfile "/foo.js; /bar.js" %}
or
{% staticfile "/foo.js; /bar.js" as variable_name %} | entailment |
def _mkdir(newdir):
"""works the way a good mkdir should :)
- already exists, silently complete
- regular file in the way, raise an exception
- parent directory(ies) does not exist, make them as well
"""
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
... | works the way a good mkdir should :)
- already exists, silently complete
- regular file in the way, raise an exception
- parent directory(ies) does not exist, make them as well | entailment |
def _find_filepath_in_roots(filename):
"""Look for filename in all MEDIA_ROOTS, and return the first one found."""
for root in settings.DJANGO_STATIC_MEDIA_ROOTS:
filepath = _filename2filepath(filename, root)
if os.path.isfile(filepath):
return filepath, root
# havent found it in... | Look for filename in all MEDIA_ROOTS, and return the first one found. | entailment |
def default_combine_filenames_generator(filenames, max_length=40):
"""Return a new filename to use as the combined file name for a
bunch of files.
A precondition is that they all have the same file extension
Given that the list of files can have different paths, we aim to use the
most common path.
... | Return a new filename to use as the combined file name for a
bunch of files.
A precondition is that they all have the same file extension
Given that the list of files can have different paths, we aim to use the
most common path.
Example:
/somewhere/else/foo.js
/somewhere/bar.js
/... | entailment |
def render(self, context):
"""inspect the code and look for files that can be turned into combos.
Basically, the developer could type this:
{% slimall %}
<link href="/one.css"/>
<link href="/two.css"/>
{% endslimall %}
And it should be reconsidered like this:
... | inspect the code and look for files that can be turned into combos.
Basically, the developer could type this:
{% slimall %}
<link href="/one.css"/>
<link href="/two.css"/>
{% endslimall %}
And it should be reconsidered like this:
<link href="{% slimfile "/on... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.