_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2500
|
RepoResultManager.add_git
|
train
|
def add_git(meta, git_info):
"""Enrich the result meta information with commit data."""
meta["hexsha"] = git_info.hexsha
meta["author"] = git_info.author
|
python
|
{
"resource": ""
}
|
q2501
|
RepoResultManager.load
|
train
|
def load(self, commit=None):
"""Load a result from the storage directory."""
git_info = self.record_git_info(commit)
LOGGER.debug("Loading the result for commit '%s'.", git_info.hexsha)
filename = self.get_filename(git_info)
|
python
|
{
"resource": ""
}
|
q2502
|
MemoteExtension.normalize
|
train
|
def normalize(filename):
"""Return an absolute path of the given file name."""
# Default value means we do not resolve a model file.
if filename == "default":
return filename
filename =
|
python
|
{
"resource": ""
}
|
q2503
|
GrowthExperiment.evaluate
|
train
|
def evaluate(self, model, threshold=0.1):
"""Evaluate in silico growth rates."""
with model:
if self.medium is not None:
self.medium.apply(model)
if self.objective is not None:
model.objective = self.objective
model.add_cons_vars(self.constraints)
threshold *= model.slim_optimize()
growth = list()
for row in self.data.itertuples(index=False):
with model:
exchange = model.reactions.get_by_id(row.exchange)
|
python
|
{
"resource": ""
}
|
q2504
|
BJSON.process_bind_param
|
train
|
def process_bind_param(self, value, dialect):
"""Convert the value to a JSON encoded string before storing it."""
try:
with BytesIO() as stream:
with GzipFile(fileobj=stream, mode="wb") as file_handle:
file_handle.write(
jsonify(value, pretty=False).encode("utf-8")
)
|
python
|
{
"resource": ""
}
|
q2505
|
BJSON.process_result_value
|
train
|
def process_result_value(self, value, dialect):
"""Convert a JSON encoded string to a dictionary structure."""
if value is not None:
with BytesIO(value) as stream:
with GzipFile(fileobj=stream, mode="rb") as
|
python
|
{
"resource": ""
}
|
q2506
|
ZXCVBNValidator.validate
|
train
|
def validate(self, password, user=None):
"""Validate method, run zxcvbn and check score."""
user_inputs = []
if user is not None:
for attribute in self.user_attributes:
if hasattr(user, attribute):
user_inputs.append(getattr(user, attribute))
results = zxcvbn(password, user_inputs=user_inputs)
|
python
|
{
"resource": ""
}
|
q2507
|
_get_html_contents
|
train
|
def _get_html_contents(html):
"""Process a HTML block and detects whether it is a code block,
a math block, or a regular HTML block."""
parser = MyHTMLParser()
parser.feed(html)
if parser.is_code:
|
python
|
{
"resource": ""
}
|
q2508
|
_is_path
|
train
|
def _is_path(s):
"""Return whether an object is a path."""
if isinstance(s, string_types):
|
python
|
{
"resource": ""
}
|
q2509
|
FormatManager.format_manager
|
train
|
def format_manager(cls):
"""Return the instance singleton, creating if necessary
"""
if cls._instance is None:
# Discover the formats
|
python
|
{
"resource": ""
}
|
q2510
|
FormatManager.register_entrypoints
|
train
|
def register_entrypoints(self):
"""Look through the `setup_tools` `entry_points` and load all of
the formats.
"""
for spec in iter_entry_points(self.entry_point_group):
format_properties = {"name": spec.name}
try:
format_properties.update(spec.load())
except (DistributionNotFound, ImportError) as err:
self.log.info(
|
python
|
{
"resource": ""
}
|
q2511
|
FormatManager.format_from_extension
|
train
|
def format_from_extension(self, extension):
"""Find a format from its extension."""
formats = [name
for name, format in self._formats.items()
if format.get('file_extension', None) == extension]
if len(formats) == 0:
return None
|
python
|
{
"resource": ""
}
|
q2512
|
FormatManager.load
|
train
|
def load(self, file, name=None):
"""Load a file. The format name can be specified explicitly or
inferred from the file extension."""
if name is None:
name = self.format_from_extension(op.splitext(file)[1])
file_format = self.file_type(name)
if file_format == 'text':
return _read_text(file)
elif file_format == 'json':
return _read_json(file)
else:
|
python
|
{
"resource": ""
}
|
q2513
|
FormatManager.save
|
train
|
def save(self, file, contents, name=None, overwrite=False):
"""Save contents into a file. The format name can be specified
explicitly or inferred from the file extension."""
if name is None:
name = self.format_from_extension(op.splitext(file)[1])
file_format = self.file_type(name)
if file_format == 'text':
_write_text(file, contents)
elif file_format == 'json':
_write_json(file, contents)
else:
write_function = self._formats[name].get('save', None)
if write_function
|
python
|
{
"resource": ""
}
|
q2514
|
FormatManager.create_reader
|
train
|
def create_reader(self, name, *args, **kwargs):
"""Create a new reader instance for a given format."""
|
python
|
{
"resource": ""
}
|
q2515
|
FormatManager.create_writer
|
train
|
def create_writer(self, name, *args, **kwargs):
"""Create a new writer instance for a given format."""
|
python
|
{
"resource": ""
}
|
q2516
|
FormatManager.convert
|
train
|
def convert(self,
contents_or_path,
from_=None,
to=None,
reader=None,
writer=None,
from_kwargs=None,
to_kwargs=None,
):
"""Convert contents between supported formats.
Parameters
----------
contents : str
The contents to convert from.
from_ : str or None
The name of the source format. If None, this is the
ipymd_cells format.
to : str or None
The name of the target format. If None, this is the
ipymd_cells format.
reader : a Reader instance or None
writer : a Writer instance or None
from_kwargs : dict
Optional keyword arguments to pass to the reader instance.
to_kwargs : dict
Optional keyword arguments to pass to the writer instance.
"""
# Load the file if 'contents_or_path' is a path.
if _is_path(contents_or_path):
contents = self.load(contents_or_path, from_)
else:
contents = contents_or_path
if from_kwargs is None:
from_kwargs = {}
if to_kwargs is None:
to_kwargs = {}
if reader is None:
reader = (self.create_reader(from_, **from_kwargs)
if from_ is not None else None)
if writer is None:
writer = (self.create_writer(to, **to_kwargs)
if to is not None else None)
if reader is not None:
# Convert from the source format to ipymd cells.
cells = [cell for cell in reader.read(contents)]
else:
# If no reader is specified, 'contents' is assumed to already be
# a list of ipymd cells.
cells = contents
notebook_metadata = [cell for cell in cells
|
python
|
{
"resource": ""
}
|
q2517
|
FormatManager.clean_meta
|
train
|
def clean_meta(self, meta):
"""Removes unwanted metadata
Parameters
----------
meta : dict
Notebook metadata.
"""
if not self.verbose_metadata:
default_kernel_name = (self.default_kernel_name
|
python
|
{
"resource": ""
}
|
q2518
|
FormatManager.clean_cell_meta
|
train
|
def clean_cell_meta(self, meta):
"""Remove cell metadata that matches the default cell metadata."""
for k, v in DEFAULT_CELL_METADATA.items():
|
python
|
{
"resource": ""
}
|
q2519
|
_starts_with_regex
|
train
|
def _starts_with_regex(line, regex):
"""Return whether a line starts with a regex or not."""
if not regex.startswith('^'):
regex
|
python
|
{
"resource": ""
}
|
q2520
|
create_prompt
|
train
|
def create_prompt(prompt):
"""Create a prompt manager.
Parameters
----------
prompt : str or class driving from BasePromptManager
The prompt name ('python' or 'ipython') or a custom PromptManager
class.
"""
if prompt is None:
prompt = 'python'
|
python
|
{
"resource": ""
}
|
q2521
|
BasePromptManager.split_input_output
|
train
|
def split_input_output(self, text):
"""Split code into input lines and output lines, according to the
input and output prompt templates."""
lines = _to_lines(text)
i = 0
for line in lines:
|
python
|
{
"resource": ""
}
|
q2522
|
_split_python
|
train
|
def _split_python(python):
"""Split Python source into chunks.
Chunks are separated by at least two return lines. The break must not
be followed by a space. Also, long Python strings spanning several lines
are not splitted.
|
python
|
{
"resource": ""
}
|
q2523
|
_is_chunk_markdown
|
train
|
def _is_chunk_markdown(source):
"""Return whether a chunk contains Markdown contents."""
lines = source.splitlines()
if all(line.startswith('# ') for line in lines):
# The chunk is a Markdown *unless* it is commented Python code.
|
python
|
{
"resource": ""
}
|
q2524
|
_filter_markdown
|
train
|
def _filter_markdown(source, filters):
"""Only keep some Markdown headers from a Markdown string."""
lines = source.splitlines()
# Filters is a list of 'hN' strings where 1 <= N <= 6.
headers =
|
python
|
{
"resource": ""
}
|
q2525
|
BlockLexer.parse_lheading
|
train
|
def parse_lheading(self, m):
"""Parse setext heading."""
level = 1 if m.group(2) == '=' else 2
|
python
|
{
"resource": ""
}
|
q2526
|
MarkdownWriter.ensure_newline
|
train
|
def ensure_newline(self, n):
"""Make sure there are 'n' line breaks at the end."""
assert n >= 0
text = self._output.getvalue().rstrip('\n')
if not text:
return
self._output = StringIO()
|
python
|
{
"resource": ""
}
|
q2527
|
BaseMarkdownReader._meta_from_regex
|
train
|
def _meta_from_regex(self, m):
"""Extract and parse YAML metadata from a meta match
Notebook metadata must appear at the beginning of the file and follows
the Jekyll front-matter convention of dashed delimiters:
---
some: yaml
---
Cell metadata follows the YAML spec of dashes and periods
---
some: yaml
...
Both must be followed by at least one blank line (\n\n).
"""
body = m.group('body')
is_notebook = m.group('sep_close') == '---'
|
python
|
{
"resource": ""
}
|
q2528
|
MarkdownReader._code_cell
|
train
|
def _code_cell(self, source):
"""Split the source into input and output."""
input, output = self._prompt.to_cell(source)
|
python
|
{
"resource": ""
}
|
q2529
|
_preprocess
|
train
|
def _preprocess(text, tab=4):
"""Normalize a text."""
text = re.sub(r'\r\n|\r', '\n', text)
text = text.replace('\t', ' ' * tab)
text = text.replace('\u00a0', ' ')
text = text.replace('\u2424', '\n')
|
python
|
{
"resource": ""
}
|
q2530
|
_diff
|
train
|
def _diff(text_0, text_1):
"""Return a diff between two strings."""
|
python
|
{
"resource": ""
}
|
q2531
|
_write_json
|
train
|
def _write_json(file, contents):
"""Write a dict to a JSON file."""
|
python
|
{
"resource": ""
}
|
q2532
|
_numbered_style
|
train
|
def _numbered_style():
"""Create a numbered list style."""
style = ListStyle(name='_numbered_list')
lls = ListLevelStyleNumber(level=1)
lls.setAttribute('displaylevels', 1)
lls.setAttribute('numsuffix', '. ')
lls.setAttribute('numformat', '1')
llp = ListLevelProperties()
llp.setAttribute('listlevelpositionandspacemode', 'label-alignment')
llla = ListLevelLabelAlignment(labelfollowedby='listtab')
llla.setAttribute('listtabstopposition', '1.27cm')
|
python
|
{
"resource": ""
}
|
q2533
|
_create_style
|
train
|
def _create_style(name, family=None, **kwargs):
"""Helper function for creating a new style."""
if family == 'paragraph' and 'marginbottom' not in kwargs:
kwargs['marginbottom'] = '.5cm'
style = Style(name=name, family=family)
# Extract paragraph properties.
kwargs_par = {}
keys = sorted(kwargs.keys())
for k in keys:
|
python
|
{
"resource": ""
}
|
q2534
|
default_styles
|
train
|
def default_styles():
"""Generate default ODF styles."""
styles = {}
def _add_style(name, **kwargs):
styles[name] = _create_style(name, **kwargs)
_add_style('heading-1',
family='paragraph',
fontsize='24pt',
fontweight='bold',
)
_add_style('heading-2',
family='paragraph',
fontsize='22pt',
fontweight='bold',
)
_add_style('heading-3',
family='paragraph',
fontsize='20pt',
fontweight='bold',
)
_add_style('heading-4',
family='paragraph',
fontsize='18pt',
fontweight='bold',
)
_add_style('heading-5',
family='paragraph',
fontsize='16pt',
fontweight='bold',
)
_add_style('heading-6',
family='paragraph',
fontsize='14pt',
fontweight='bold',
)
_add_style('normal-paragraph',
family='paragraph',
fontsize='12pt',
marginbottom='0.25cm',
)
_add_style('code',
family='paragraph',
fontsize='10pt',
fontweight='bold',
fontfamily='Courier New',
color='#555555',
)
_add_style('quote',
family='paragraph',
fontsize='12pt',
fontstyle='italic',
)
_add_style('list-paragraph',
family='paragraph',
fontsize='12pt',
marginbottom='.1cm',
)
_add_style('sublist-paragraph',
family='paragraph',
|
python
|
{
"resource": ""
}
|
q2535
|
load_styles
|
train
|
def load_styles(path_or_doc):
"""Return a dictionary of all styles contained in an ODF document."""
if isinstance(path_or_doc, string_types):
doc = load(path_or_doc)
else:
# Recover the OpenDocumentText instance.
if isinstance(path_or_doc, ODFDocument):
doc = path_or_doc._doc
|
python
|
{
"resource": ""
}
|
q2536
|
_item_type
|
train
|
def _item_type(item):
"""Indicate to the ODF reader the type of the block or text."""
tag = item['tag']
style = item.get('style', None)
if tag == 'p':
if style is None or 'paragraph' in style:
return 'paragraph'
else:
return style
elif tag == 'span':
if style in (None, 'normal-text'):
return 'text'
elif style == 'url':
return 'link'
else:
return style
elif tag == 'h':
|
python
|
{
"resource": ""
}
|
q2537
|
ODFDocument.add_styles
|
train
|
def add_styles(self, **styles):
"""Add ODF styles to the current document."""
|
python
|
{
"resource": ""
}
|
q2538
|
ODFDocument._add_element
|
train
|
def _add_element(self, cls, **kwargs):
"""Add an element."""
# Convert stylename strings to actual style elements.
|
python
|
{
"resource": ""
}
|
q2539
|
ODFDocument._style_name
|
train
|
def _style_name(self, el):
"""Return the style name of an element."""
if el.attributes is None:
return None
style_field = ('urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'style-name')
name =
|
python
|
{
"resource": ""
}
|
q2540
|
ODFDocument.start_container
|
train
|
def start_container(self, cls, **kwargs):
"""Append a new container."""
# Convert stylename strings to actual style elements.
kwargs = self._replace_stylename(kwargs)
|
python
|
{
"resource": ""
}
|
q2541
|
ODFDocument.end_container
|
train
|
def end_container(self, cancel=None):
"""Finishes and registers the currently-active container, unless
'cancel' is True."""
if not self._containers:
return
container = self._containers.pop()
if len(self._containers) >= 1:
|
python
|
{
"resource": ""
}
|
q2542
|
ODFDocument.container
|
train
|
def container(self, cls, **kwargs):
"""Container context manager."""
self.start_container(cls,
|
python
|
{
"resource": ""
}
|
q2543
|
ODFDocument.start_paragraph
|
train
|
def start_paragraph(self, stylename=None):
"""Start a new paragraph."""
# Use the next paragraph style if
|
python
|
{
"resource": ""
}
|
q2544
|
ODFDocument.require_paragraph
|
train
|
def require_paragraph(self):
"""Create a new paragraph unless the currently-active container
is already a paragraph."""
if self._containers and _is_paragraph(self._containers[-1]):
|
python
|
{
"resource": ""
}
|
q2545
|
ODFDocument._code_line
|
train
|
def _code_line(self, line):
"""Add a code line."""
assert self._containers
container = self._containers[-1]
# Handle extra spaces.
text = line
while text:
if text.startswith(' '):
r = re.match(r'(^ +)', text)
n = len(r.group(1))
container.addElement(S(c=n))
text = text[n:]
elif ' ' in text:
|
python
|
{
"resource": ""
}
|
q2546
|
ODFDocument.code
|
train
|
def code(self, text, lang=None):
"""Add a code block."""
# WARNING: lang is discarded currently.
with self.paragraph(stylename='code'):
lines = text.splitlines()
for line in lines[:-1]:
|
python
|
{
"resource": ""
}
|
q2547
|
ODFDocument.start_numbered_list
|
train
|
def start_numbered_list(self):
"""Start a numbered list."""
self._ordered = True
self.start_container(List, stylename='_numbered_list')
self.set_next_paragraph_style('numbered-list-paragraph'
|
python
|
{
"resource": ""
}
|
q2548
|
ODFDocument.start_list
|
train
|
def start_list(self):
"""Start a list."""
self._ordered = False
self.start_container(List)
self.set_next_paragraph_style('list-paragraph'
|
python
|
{
"resource": ""
}
|
q2549
|
ODFDocument.text
|
train
|
def text(self, text, stylename=None):
"""Add text within the current container."""
assert self._containers
container = self._containers[-1]
if stylename is not None:
stylename = self._get_style_name(stylename)
|
python
|
{
"resource": ""
}
|
q2550
|
_cell_output
|
train
|
def _cell_output(cell):
"""Return the output of an ipynb cell."""
outputs = cell.get('outputs', [])
# Add stdout.
stdout = ('\n'.join(_ensure_string(output.get('text', ''))
for output in outputs)).rstrip()
# Add text output.
text_outputs = []
for output in outputs:
out = output.get('data', {}).get('text/plain', [])
|
python
|
{
"resource": ""
}
|
q2551
|
FireTV._dump
|
train
|
def _dump(self, service, grep=None):
"""Perform a service dump.
:param service: Service to dump.
:param grep: Grep for this string.
:returns: Dump, optionally grepped.
"""
if grep:
|
python
|
{
"resource": ""
}
|
q2552
|
FireTV._dump_has
|
train
|
def _dump_has(self, service, grep, search):
"""Check if a dump has particular content.
:param service: Service to dump.
:param grep: Grep for this string.
:param search: Check for this substring.
:returns: Found or not.
"""
|
python
|
{
"resource": ""
}
|
q2553
|
FireTV._ps
|
train
|
def _ps(self, search=''):
"""Perform a ps command with optional filtering.
:param search: Check for this substring.
:returns: List of matching fields
"""
if not self.available:
return
result = []
ps = self.adb_streaming_shell('ps')
try:
for bad_line in ps:
# The splitting of the StreamingShell doesn't always work
# this is to ensure that we get only one line
|
python
|
{
"resource": ""
}
|
q2554
|
FireTV.connect
|
train
|
def connect(self, always_log_errors=True):
"""Connect to an Amazon Fire TV device.
Will attempt to establish ADB connection to the given host.
Failure sets state to UNKNOWN and disables sending actions.
:returns: True if successful, False otherwise
"""
self._adb_lock.acquire(**LOCK_KWARGS)
try:
if not self.adb_server_ip:
# python-adb
try:
if self.adbkey:
signer = Signer(self.adbkey)
# Connect to the device
self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, rsa_keys=[signer], default_timeout_ms=9000)
else:
self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, default_timeout_ms=9000)
# ADB connection successfully established
self._available = True
except socket_error as serr:
if self._available or always_log_errors:
if serr.strerror is None:
|
python
|
{
"resource": ""
}
|
q2555
|
FireTV.update
|
train
|
def update(self, get_running_apps=True):
"""Get the state of the device, the current app, and the running apps.
:param get_running_apps: whether or not to get the ``running_apps`` property
:return state: the state of the device
:return current_app: the current app
:return running_apps: the running apps
"""
# The `screen_on`, `awake`, `wake_lock_size`, `current_app`, and `running_apps` properties.
screen_on, awake, wake_lock_size, _current_app, running_apps = self.get_properties(get_running_apps=get_running_apps, lazy=True)
# Check if device is off.
if not screen_on:
state = STATE_OFF
current_app = None
running_apps = None
# Check if screen saver is on.
elif not awake:
state = STATE_IDLE
current_app = None
running_apps = None
else:
|
python
|
{
"resource": ""
}
|
q2556
|
FireTV.app_state
|
train
|
def app_state(self, app):
"""Informs if application is running."""
if not self.available or not self.screen_on:
return STATE_OFF
|
python
|
{
"resource": ""
}
|
q2557
|
FireTV.state
|
train
|
def state(self):
"""Compute and return the device state.
:returns: Device state.
"""
# Check if device is disconnected.
if not self.available:
return STATE_UNKNOWN
# Check if device is off.
if not self.screen_on:
return STATE_OFF
# Check if screen saver is on.
if not self.awake:
return STATE_IDLE
# Check if the launcher is active.
|
python
|
{
"resource": ""
}
|
q2558
|
FireTV.available
|
train
|
def available(self):
"""Check whether the ADB connection is intact."""
if not self.adb_server_ip:
# python-adb
return bool(self._adb)
# pure-python-adb
try:
# make sure the server is available
adb_devices = self._adb_client.devices()
# make sure the device is available
try:
# case 1: the device is currently available
if any([self.host in dev.get_serial_no() for dev in adb_devices]):
if not self._available:
self._available = True
return True
# case 2: the device is not currently available
if self._available:
logging.error('ADB server is not connected to the device.')
|
python
|
{
"resource": ""
}
|
q2559
|
FireTV.running_apps
|
train
|
def running_apps(self):
"""Return a list of running user applications."""
ps = self.adb_shell(RUNNING_APPS_CMD)
if ps:
|
python
|
{
"resource": ""
}
|
q2560
|
FireTV.current_app
|
train
|
def current_app(self):
"""Return the current app."""
current_focus = self.adb_shell(CURRENT_APP_CMD)
if current_focus is None:
return None
current_focus = current_focus.replace("\r", "")
matches = WINDOW_REGEX.search(current_focus)
# case 1: current app was successfully found
if matches:
|
python
|
{
"resource": ""
}
|
q2561
|
FireTV.wake_lock_size
|
train
|
def wake_lock_size(self):
"""Get the size of the current wake lock."""
output = self.adb_shell(WAKE_LOCK_SIZE_CMD)
if not output:
|
python
|
{
"resource": ""
}
|
q2562
|
FireTV.get_properties
|
train
|
def get_properties(self, get_running_apps=True, lazy=False):
"""Get the ``screen_on``, ``awake``, ``wake_lock_size``, ``current_app``, and ``running_apps`` properties."""
if get_running_apps:
output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
WAKE_LOCK_SIZE_CMD + " && " +
CURRENT_APP_CMD + " && " +
RUNNING_APPS_CMD)
else:
output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
WAKE_LOCK_SIZE_CMD + " && " +
CURRENT_APP_CMD)
# ADB command was unsuccessful
if output is None:
return None, None, None, None, None
# `screen_on` property
if not output:
return False, False, -1, None, None
screen_on = output[0] == '1'
# `awake` property
if len(output) < 2:
return screen_on, False, -1, None, None
awake = output[1] == '1'
|
python
|
{
"resource": ""
}
|
q2563
|
is_valid_device_id
|
train
|
def is_valid_device_id(device_id):
""" Check if device identifier is valid.
A valid device identifier contains only ascii word characters or dashes.
:param device_id: Device identifier
:returns: Valid or not.
"""
valid = valid_device_id.match(device_id)
if not valid:
logging.error("A
|
python
|
{
"resource": ""
}
|
q2564
|
add
|
train
|
def add(device_id, host, adbkey='', adb_server_ip='', adb_server_port=5037):
""" Add a device.
Creates FireTV instance associated with device identifier.
:param device_id: Device identifier.
:param host: Host in <address>:<port> format.
:param adbkey: The path to the "adbkey" file
:param adb_server_ip: the IP address for the ADB server
:param adb_server_port: the port for the ADB server
:returns:
|
python
|
{
"resource": ""
}
|
q2565
|
add_device
|
train
|
def add_device():
""" Add a device via HTTP POST.
POST JSON in the following format ::
{
"device_id": "<your_device_id>",
"host": "<address>:<port>",
"adbkey": "<path to the adbkey file>"
}
"""
req = request.get_json()
success = False
|
python
|
{
"resource": ""
}
|
q2566
|
list_devices
|
train
|
def list_devices():
""" List devices via HTTP GET. """
output = {}
for device_id, device in devices.items():
output[device_id] = {
|
python
|
{
"resource": ""
}
|
q2567
|
device_state
|
train
|
def device_state(device_id):
""" Get device state via HTTP GET. """
if device_id not in devices:
|
python
|
{
"resource": ""
}
|
q2568
|
current_app
|
train
|
def current_app(device_id):
""" Get currently running app. """
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
|
python
|
{
"resource": ""
}
|
q2569
|
running_apps
|
train
|
def running_apps(device_id):
""" Get running apps via HTTP GET. """
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
|
python
|
{
"resource": ""
}
|
q2570
|
get_app_state
|
train
|
def get_app_state(device_id, app_id):
""" Get the state of the requested app """
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id
|
python
|
{
"resource": ""
}
|
q2571
|
device_action
|
train
|
def device_action(device_id, action_id):
""" Initiate device action via HTTP GET. """
success = False
if device_id in devices:
input_cmd = getattr(devices[device_id], action_id, None)
|
python
|
{
"resource": ""
}
|
q2572
|
app_start
|
train
|
def app_start(device_id, app_id):
""" Starts an app with corresponding package name"""
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
|
python
|
{
"resource": ""
}
|
q2573
|
app_stop
|
train
|
def app_stop(device_id, app_id):
""" stops an app with corresponding package name"""
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
|
python
|
{
"resource": ""
}
|
q2574
|
device_connect
|
train
|
def device_connect(device_id):
""" Force a connection attempt via HTTP GET. """
success = False
if device_id in devices:
|
python
|
{
"resource": ""
}
|
q2575
|
_parse_config
|
train
|
def _parse_config(config_file_path):
""" Parse Config File from yaml file. """
config_file = open(config_file_path, 'r')
|
python
|
{
"resource": ""
}
|
q2576
|
_add_devices_from_config
|
train
|
def _add_devices_from_config(args):
""" Add devices from config. """
config = _parse_config(args.config)
for device in config['devices']:
if args.default:
if device == "default":
raise ValueError('devicename "default" in config is not allowed if default param is set')
if config['devices'][device]['host'] == args.default:
|
python
|
{
"resource": ""
}
|
q2577
|
main
|
train
|
def main():
""" Set up the server. """
parser = argparse.ArgumentParser(description='AFTV Server')
parser.add_argument('-p', '--port', type=int, help='listen port', default=5556)
parser.add_argument('-d', '--default', help='default Amazon Fire TV host', nargs='?')
parser.add_argument('-c', '--config', type=str, help='Path to config file')
|
python
|
{
"resource": ""
}
|
q2578
|
ProfanityFilter._load_words
|
train
|
def _load_words(self):
"""Loads the list of profane words from file."""
with open(self._words_file, 'r') as f:
|
python
|
{
"resource": ""
}
|
q2579
|
ProfanityFilter.get_profane_words
|
train
|
def get_profane_words(self):
"""Returns all profane words currently in use."""
profane_words = []
if self._custom_censor_list:
profane_words = [w for w in self._custom_censor_list] # Previous versions of Python don't have list.copy()
else:
profane_words = [w for w in self._censor_list]
profane_words.extend(self._extra_censor_list)
profane_words.extend([inflection.pluralize(word) for word in profane_words])
profane_words =
|
python
|
{
"resource": ""
}
|
q2580
|
ProfanityFilter.censor
|
train
|
def censor(self, input_text):
"""Returns input_text with any profane words censored."""
bad_words = self.get_profane_words()
res = input_text
for word in bad_words:
# Apply word boundaries to the bad word
regex_string = r'{0}' if self._no_word_boundaries else r'\b{0}\b'
|
python
|
{
"resource": ""
}
|
q2581
|
SMB2NetworkInterfaceInfo.unpack_multiple
|
train
|
def unpack_multiple(data):
"""
Get's a list of SMB2NetworkInterfaceInfo messages from the byte value
passed in. This is the raw buffer value that is set on the
SMB2IOCTLResponse message.
:param data: bytes of the messages
:return: List of SMB2NetworkInterfaceInfo messages
|
python
|
{
"resource": ""
}
|
q2582
|
CreateContextName.get_response_structure
|
train
|
def get_response_structure(name):
"""
Returns the response structure for a know list of create context
responses.
:param name: The constant value above
:return: The response structure or None if unknown
"""
return {
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST:
SMB2CreateDurableHandleResponse(),
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT:
SMB2CreateDurableHandleReconnect(),
CreateContextName.SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST:
SMB2CreateQueryMaximalAccessResponse(),
CreateContextName.SMB2_CREATE_REQUEST_LEASE:
SMB2CreateResponseLease(),
CreateContextName.SMB2_CREATE_QUERY_ON_DISK_ID:
|
python
|
{
"resource": ""
}
|
q2583
|
SMB2CreateContextRequest.get_context_data
|
train
|
def get_context_data(self):
"""
Get the buffer_data value of a context response and try to convert it
to the relevant structure based on the buffer_name used. If it is an
unknown structure then the raw bytes are returned.
:return: relevant Structure of buffer_data or bytes if unknown name
"""
buffer_name = self['buffer_name'].get_value()
structure
|
python
|
{
"resource": ""
}
|
q2584
|
SMB2CreateEABuffer.pack_multiple
|
train
|
def pack_multiple(messages):
"""
Converts a list of SMB2CreateEABuffer structures and packs them as a
bytes object used when setting to the SMB2CreateContextRequest
buffer_data field. This should be used as it would calculate the
correct next_entry_offset field value for each buffer entry.
:param messages: List of SMB2CreateEABuffer structures
:return: bytes object that is set on the SMB2CreateContextRequest
buffer_data field.
"""
data = b""
msg_count = len(messages)
for i, msg in enumerate(messages):
|
python
|
{
"resource": ""
}
|
q2585
|
TreeConnect.connect
|
train
|
def connect(self, require_secure_negotiate=True):
"""
Connect to the share.
:param require_secure_negotiate: For Dialects 3.0 and 3.0.2, will
verify the negotiation parameters with the server to prevent
SMB downgrade attacks
"""
log.info("Session: %s - Creating connection to share %s"
% (self.session.username, self.share_name))
utf_share_name = self.share_name.encode('utf-16-le')
connect = SMB2TreeConnectRequest()
connect['buffer'] = utf_share_name
log.info("Session: %s - Sending Tree Connect message"
% self.session.username)
log.debug(str(connect))
request = self.session.connection.send(connect,
sid=self.session.session_id)
log.info("Session: %s - Receiving Tree Connect response"
% self.session.username)
response = self.session.connection.receive(request)
tree_response = SMB2TreeConnectResponse()
tree_response.unpack(response['data'].get_value())
log.debug(str(tree_response))
# https://msdn.microsoft.com/en-us/library/cc246687.aspx
self.tree_connect_id = response['tree_id'].get_value()
log.info("Session: %s - Created tree connection with ID %d"
% (self.session.username, self.tree_connect_id))
self._connected = True
self.session.tree_connect_table[self.tree_connect_id] = self
capabilities = tree_response['capabilities']
self.is_dfs_share = capabilities.has_flag(
|
python
|
{
"resource": ""
}
|
q2586
|
TreeConnect.disconnect
|
train
|
def disconnect(self):
"""
Disconnects the tree connection.
"""
if not self._connected:
return
log.info("Session: %s, Tree: %s - Disconnecting from Tree Connect"
% (self.session.username, self.share_name))
req = SMB2TreeDisconnect()
log.info("Session: %s, Tree: %s - Sending Tree Disconnect message"
% (self.session.username, self.share_name))
log.debug(str(req))
request = self.session.connection.send(req,
sid=self.session.session_id,
tid=self.tree_connect_id)
log.info("Session: %s, Tree: %s - Receiving Tree Disconnect response"
|
python
|
{
"resource": ""
}
|
q2587
|
Connection.disconnect
|
train
|
def disconnect(self, close=True):
"""
Closes the connection as well as logs off any of the
Disconnects the TCP connection and shuts down the socket listener
running in a thread.
:param close: Will close all
|
python
|
{
"resource": ""
}
|
q2588
|
Connection.send
|
train
|
def send(self, message, sid=None, tid=None, credit_request=None):
"""
Will send a message to the server that is passed in. The final
unencrypted header is returned to the function that called this.
:param message: An SMB message structure to send
:param sid: A session_id that the message is sent for
:param tid: A tree_id object that the message is sent for
:param credit_request: Specifies extra credits to be requested with the
SMB header
:return: Request of the message that was sent
"""
header = self._generate_packet_header(message, sid, tid,
credit_request)
# get the actual Session and TreeConnect object instead of the IDs
session = self.session_table.get(sid, None) if sid else None
tree = None
if tid and session:
if tid not in session.tree_connect_table.keys():
error_msg = "Cannot find Tree with the ID %d in the session " \
|
python
|
{
"resource": ""
}
|
q2589
|
Connection.send_compound
|
train
|
def send_compound(self, messages, sid, tid, related=False):
"""
Sends multiple messages within 1 TCP request, will fail if the size
of the total length exceeds the maximum of the transport max.
:param messages: A list of messages to send to the server
:param sid: The session_id that the request is sent for
:param tid: A tree_id object that the message is sent for
:return: List<Request> for each request that was sent, each entry in
the list is in the same order of the message list that was passed
in
"""
send_data = b""
session = self.session_table[sid]
tree = session.tree_connect_table[tid]
requests = []
total_requests = len(messages)
for i, message in enumerate(messages):
if i == total_requests - 1:
next_command = 0
|
python
|
{
"resource": ""
}
|
q2590
|
Connection.receive
|
train
|
def receive(self, request, wait=True, timeout=None):
"""
Polls the message buffer of the TCP connection and waits until a valid
message is received based on the message_id passed in.
:param request: The Request object to wait get the response for
:param wait: Wait for the final response in the case of a
STATUS_PENDING response, the pending response is returned in the
case of wait=False
:param timeout: Set a timeout used while waiting for a response from
the server
:return: SMB2HeaderResponse of the received message
"""
start_time = time.time()
# check if we have received a response
while True:
self._flush_message_buffer()
status = request.response['status'].get_value() if \
request.response else None
if status is not None and (wait and
status != NtStatus.STATUS_PENDING):
break
current_time = time.time() - start_time
if timeout
|
python
|
{
"resource": ""
}
|
q2591
|
Connection.echo
|
train
|
def echo(self, sid=0, timeout=60, credit_request=1):
"""
Sends an SMB2 Echo request to the server. This can be used to request
more credits from the server with the credit_request param.
On a Samba server, the sid can be 0 but for a Windows SMB Server, the
sid of an authenticated session must be passed into this function or
else the socket will close.
:param sid: When talking to a Windows host this must be populated with
a valid session_id from a negotiated session
:param timeout: The timeout in seconds to wait for the Echo Response
:param credit_request: The number of credits to request
:return: the credits that were granted by the server
"""
log.info("Sending Echo request with a timeout of %d and credit "
|
python
|
{
"resource": ""
}
|
q2592
|
Connection._flush_message_buffer
|
train
|
def _flush_message_buffer(self):
"""
Loops through the transport message_buffer until there are no messages
left in the queue. Each response is assigned to the Request object
based on the message_id which are then available in
self.outstanding_requests
"""
while True:
message_bytes = self.transport.receive()
# there were no messages receives, so break from the loop
if message_bytes is None:
break
# check if the message is encrypted and decrypt if necessary
if message_bytes[:4] == b"\xfdSMB":
message = SMB2TransformHeader()
message.unpack(message_bytes)
message_bytes = self._decrypt(message)
# now retrieve message(s) from response
is_last = False
session_id = None
while not is_last:
next_command = struct.unpack("<L", message_bytes[20:24])[0]
header_length = \
next_command if next_command != 0 else len(message_bytes)
header_bytes = message_bytes[:header_length]
message = SMB2HeaderResponse()
message.unpack(header_bytes)
flags = message['flags']
if not flags.has_flag(Smb2Flags.SMB2_FLAGS_RELATED_OPERATIONS):
|
python
|
{
"resource": ""
}
|
q2593
|
Connection._calculate_credit_charge
|
train
|
def _calculate_credit_charge(self, message):
"""
Calculates the credit charge for a request based on the command. If
connection.supports_multi_credit is not True then the credit charge
isn't valid so it returns 0.
The credit charge is the number of credits that are required for
sending/receiving data over 64 kilobytes, in the existing messages only
the Read, Write, Query Directory or IOCTL commands will end in this
scenario and each require their own calculation to get the proper
value. The generic formula for calculating the credit charge is
https://msdn.microsoft.com/en-us/library/dn529312.aspx
(max(SendPayloadSize, Expected ResponsePayloadSize) - 1) / 65536 + 1
:param message: The message being sent
:return: The credit charge to set on the header
"""
credit_size = 65536
if not self.supports_multi_credit:
credit_charge = 0
elif message.COMMAND == Commands.SMB2_READ:
max_size = message['length'].get_value() + \
message['read_channel_info_length'].get_value() - 1
credit_charge = math.ceil(max_size / credit_size)
elif message.COMMAND == Commands.SMB2_WRITE:
max_size = message['length'].get_value() + \
|
python
|
{
"resource": ""
}
|
q2594
|
Session.disconnect
|
train
|
def disconnect(self, close=True):
"""
Logs off the session
:param close: Will close all tree connects in a session
"""
if not self._connected:
# already disconnected so let's return
return
if close:
for open in list(self.open_table.values()):
open.close(False)
for tree in list(self.tree_connect_table.values()):
tree.disconnect()
log.info("Session: %s - Logging off of SMB Session" % self.username)
logoff = SMB2Logoff()
log.info("Session: %s - Sending Logoff message" % self.username)
log.debug(str(logoff))
|
python
|
{
"resource": ""
}
|
q2595
|
Field.pack
|
train
|
def pack(self):
"""
Packs the field value into a byte string so it can be sent to the
server.
:param structure: The message structure class object
:return: A byte string of the packed field's value
"""
value = self._get_calculated_value(self.value)
packed_value = self._pack_value(value)
size = self._get_calculated_size(self.size, packed_value)
if len(packed_value) != size:
|
python
|
{
"resource": ""
}
|
q2596
|
Field.set_value
|
train
|
def set_value(self, value):
"""
Parses, and sets the value attribute for the field.
:param value: The value to be parsed and set, the allowed input types
|
python
|
{
"resource": ""
}
|
q2597
|
Field.unpack
|
train
|
def unpack(self, data):
"""
Takes in a byte string and set's the field value based on field
definition.
:param structure: The message structure class object
:param data: The byte string of the data to unpack
:return: The remaining data for subsequent fields
|
python
|
{
"resource": ""
}
|
q2598
|
Field._get_calculated_value
|
train
|
def _get_calculated_value(self, value):
"""
Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value
"""
if isinstance(value, types.LambdaType):
expanded_value
|
python
|
{
"resource": ""
}
|
q2599
|
Field._get_struct_format
|
train
|
def _get_struct_format(self, size):
"""
Get's the format specified for use in struct. This is only designed
for 1, 2, 4, or 8 byte values and will throw an exception if it is
anything else.
:param size: The size as an int
:return: The struct format specifier for the size specified
"""
if isinstance(size, types.LambdaType):
size = size(self.structure)
struct_format = {
1: 'B',
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.