_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q275200 | CLI.run | test | def run(self, args):
"""
Pass in raw arguments, instantiate Slack API and begin client.
"""
args = self.parser.parse_args(args)
if not args.token:
raise ValueError('Supply the slack token through --token or setting DJANGOBOT_TOKEN')
# Import the channel layer... | python | {
"resource": ""
} |
q275201 | dict_diff | test | def dict_diff(prv, nxt):
"""Return a dict of keys that differ with another config object."""
keys = set(prv.keys() + nxt.keys())
result = {}
for k in keys:
if prv.get(k) != nxt.get(k):
result[k] = (prv.get(k), nxt.get(k))
return result | python | {
"resource": ""
} |
q275202 | colorize | test | def colorize(msg, color):
"""Given a string add necessary codes to format the string."""
if DONT_COLORIZE:
return msg
else:
return "{}{}{}".format(COLORS[color], msg, COLORS["endc"]) | python | {
"resource": ""
} |
q275203 | CallbackModule.v2_playbook_on_task_start | test | def v2_playbook_on_task_start(self, task, **kwargs):
"""Run when a task starts."""
self.last_task_name = task.get_name()
self.printed_last_task = False | python | {
"resource": ""
} |
q275204 | CallbackModule.v2_runner_on_ok | test | def v2_runner_on_ok(self, result, **kwargs):
"""Run when a task finishes correctly."""
failed = "failed" in result._result
unreachable = "unreachable" in result._result
if (
"print_action" in result._task.tags
or failed
or unreachable
or s... | python | {
"resource": ""
} |
q275205 | CallbackModule.v2_playbook_on_stats | test | def v2_playbook_on_stats(self, stats):
"""Display info about playbook statistics."""
print()
self.printed_last_task = False
self._print_task("STATS")
hosts = sorted(stats.processed.keys())
for host in hosts:
s = stats.summarize(host)
if s["failur... | python | {
"resource": ""
} |
q275206 | CallbackModule.v2_runner_on_skipped | test | def v2_runner_on_skipped(self, result, **kwargs):
"""Run when a task is skipped."""
if self._display.verbosity > 1:
self._print_task()
self.last_skipped = False
line_length = 120
spaces = " " * (31 - len(result._host.name) - 4)
line = " * {}... | python | {
"resource": ""
} |
q275207 | prefix_to_addrmask | test | def prefix_to_addrmask(value, sep=" "):
"""
Converts a CIDR formatted prefix into an address netmask representation.
Argument sep specifies the separator between the address and netmask parts.
By default it's a single space.
Examples:
>>> "{{ '192.168.0.1/24|prefix_to_addrmask }}" -> "192.1... | python | {
"resource": ""
} |
q275208 | check_empty | test | def check_empty(default=""):
"""
Decorator that checks if a value passed to a Jinja filter evaluates to false
and returns an empty string. Otherwise calls the original Jinja filter.
Example usage:
@check_empty
def my_jinja_filter(value, arg1):
"""
def real_decorator(func):
@wr... | python | {
"resource": ""
} |
q275209 | Root.add_model | test | def add_model(self, model, force=False):
"""
Add a model.
The model will be asssigned to a class attribute with the YANG name of the model.
Args:
model (PybindBase): Model to add.
force (bool): If not set, verify the model is in SUPPORTED_MODELS
Example... | python | {
"resource": ""
} |
q275210 | Root.get | test | def get(self, filter=False):
"""
Returns a dictionary with the values of the model. Note that the values
of the leafs are YANG classes.
Args:
filter (bool): If set to ``True``, show only values that have been set.
Returns:
dict: A dictionary with the val... | python | {
"resource": ""
} |
q275211 | Root.load_dict | test | def load_dict(self, data, overwrite=False, auto_load_model=True):
"""
Load a dictionary into the model.
Args:
data(dict): Dictionary to load
overwrite(bool): Whether the data present in the model should be overwritten by the
data in the dict or not.
... | python | {
"resource": ""
} |
q275212 | Root.to_dict | test | def to_dict(self, filter=True):
"""
Returns a dictionary with the values of the model. Note that the values
of the leafs are evaluated to python types.
Args:
filter (bool): If set to ``True``, show only values that have been set.
Returns:
dict: A diction... | python | {
"resource": ""
} |
q275213 | Root.parse_config | test | def parse_config(self, device=None, profile=None, native=None, attrs=None):
"""
Parse native configuration and load it into the corresponding models. Only models
that have been added to the root object will be parsed.
If ``native`` is passed to the method that's what we will parse, othe... | python | {
"resource": ""
} |
q275214 | Root.parse_state | test | def parse_state(self, device=None, profile=None, native=None, attrs=None):
"""
Parse native state and load it into the corresponding models. Only models
that have been added to the root object will be parsed.
If ``native`` is passed to the method that's what we will parse, otherwise, we... | python | {
"resource": ""
} |
q275215 | Root.translate_config | test | def translate_config(self, profile, merge=None, replace=None):
"""
Translate the object to native configuration.
In this context, merge and replace means the following:
* **Merge** - Elements that exist in both ``self`` and ``merge`` will use by default the
values in ``merge`... | python | {
"resource": ""
} |
q275216 | load_filters | test | def load_filters():
"""
Loads and returns all filters.
"""
all_filters = {}
for m in JINJA_FILTERS:
if hasattr(m, "filters"):
all_filters.update(m.filters())
return all_filters | python | {
"resource": ""
} |
q275217 | find_yang_file | test | def find_yang_file(profile, filename, path):
"""
Find the necessary file for the given test case.
Args:
device(napalm device connection): for which device
filename(str): file to find
path(str): where to find it relative to where the module is installed
"""
# Find base_dir of... | python | {
"resource": ""
} |
q275218 | model_to_dict | test | def model_to_dict(model, mode="", show_defaults=False):
"""
Given a model, return a representation of the model in a dict.
This is mostly useful to have a quick visual represenation of the model.
Args:
model (PybindBase): Model to transform.
mode (string): Whether to print config, sta... | python | {
"resource": ""
} |
q275219 | diff | test | def diff(f, s):
"""
Given two models, return the difference between them.
Args:
f (Pybindbase): First element.
s (Pybindbase): Second element.
Returns:
dict: A dictionary highlighting the differences.
Examples:
>>> diff = napalm_yang.utils.diff(candidate, runnin... | python | {
"resource": ""
} |
q275220 | Client.http_post | test | def http_post(self, url, data=None):
"""POST to URL and get result as a response object.
:param url: URL to POST.
:type url: str
:param data: Data to send in the form body.
:type data: str
:rtype: requests.Response
"""
if not url.startswith('https://'):
... | python | {
"resource": ""
} |
q275221 | Client.get_authorization_code_uri | test | def get_authorization_code_uri(self, **params):
"""Construct a full URL that can be used to obtain an authorization
code from the provider authorization_uri. Use this URI in a client
frame to cause the provider to generate an authorization code.
:rtype: str
"""
if 'respo... | python | {
"resource": ""
} |
q275222 | Client.get_token | test | def get_token(self, code, **params):
"""Get an access token from the provider token URI.
:param code: Authorization code.
:type code: str
:return: Dict containing access token, refresh token, etc.
:rtype: dict
"""
params['code'] = code
if 'grant_type' not... | python | {
"resource": ""
} |
q275223 | url_query_params | test | def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(urlparse.parse_qsl(urlparse.urlparse(url).query, True)) | python | {
"resource": ""
} |
q275224 | url_dequery | test | def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse.urlparse(url)
return urlparse.urlunparse((url.scheme,
url.netloc,
url.path,
... | python | {
"resource": ""
} |
q275225 | build_url | test | def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_para... | python | {
"resource": ""
} |
q275226 | Provider._handle_exception | test | def _handle_exception(self, exc):
"""Handle an internal exception that was caught and suppressed.
:param exc: Exception to process.
:type exc: Exception
"""
logger = logging.getLogger(__name__)
logger.exception(exc) | python | {
"resource": ""
} |
q275227 | Provider._make_response | test | def _make_response(self, body='', headers=None, status_code=200):
"""Return a response object from the given parameters.
:param body: Buffer/string containing the response body.
:type body: str
:param headers: Dict of headers to include in the requests.
:type headers: dict
... | python | {
"resource": ""
} |
q275228 | Provider._make_redirect_error_response | test | def _make_redirect_error_response(self, redirect_uri, err):
"""Return a HTTP 302 redirect response object containing the error.
:param redirect_uri: Client redirect URI.
:type redirect_uri: str
:param err: OAuth error message.
:type err: str
:rtype: requests.Response
... | python | {
"resource": ""
} |
q275229 | Provider._make_json_response | test | def _make_json_response(self, data, headers=None, status_code=200):
"""Return a response object from the given JSON data.
:param data: Data to JSON-encode.
:type data: mixed
:param headers: Dict of headers to include in the requests.
:type headers: dict
:param status_cod... | python | {
"resource": ""
} |
q275230 | AuthorizationProvider.get_authorization_code | test | def get_authorization_code(self,
response_type,
client_id,
redirect_uri,
**params):
"""Generate authorization code HTTP response.
:param response_type: Desired response type. Must... | python | {
"resource": ""
} |
q275231 | AuthorizationProvider.refresh_token | test | def refresh_token(self,
grant_type,
client_id,
client_secret,
refresh_token,
**params):
"""Generate access token HTTP response from a refresh token.
:param grant_type: Desired grant type. Must ... | python | {
"resource": ""
} |
q275232 | AuthorizationProvider.get_token | test | def get_token(self,
grant_type,
client_id,
client_secret,
redirect_uri,
code,
**params):
"""Generate access token HTTP response.
:param grant_type: Desired grant type. Must be "authorization_code... | python | {
"resource": ""
} |
q275233 | AuthorizationProvider.get_authorization_code_from_uri | test | def get_authorization_code_from_uri(self, uri):
"""Get authorization code response from a URI. This method will
ignore the domain and path of the request, instead
automatically parsing the query string parameters.
:param uri: URI to parse for authorization information.
:type uri... | python | {
"resource": ""
} |
q275234 | AuthorizationProvider.get_token_from_post_data | test | def get_token_from_post_data(self, data):
"""Get a token response from POST data.
:param data: POST data containing authorization information.
:type data: dict
:rtype: requests.Response
"""
try:
# Verify OAuth 2.0 Parameters
for x in ['grant_type'... | python | {
"resource": ""
} |
q275235 | ResourceProvider.get_authorization | test | def get_authorization(self):
"""Get authorization object representing status of authentication."""
auth = self.authorization_class()
header = self.get_authorization_header()
if not header or not header.split:
return auth
header = header.split()
if len(header) ... | python | {
"resource": ""
} |
q275236 | SMBus.open | test | def open(self, bus):
"""Open the smbus interface on the specified bus."""
# Close the device if it's already open.
if self._device is not None:
self.close()
# Try to open the file for the specified bus. Must turn off buffering
# or else Python 3 fails (see: https://b... | python | {
"resource": ""
} |
q275237 | SMBus.read_byte | test | def read_byte(self, addr):
"""Read a single byte from the specified device."""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
return ord(self._device.read(1)) | python | {
"resource": ""
} |
q275238 | SMBus.read_bytes | test | def read_bytes(self, addr, number):
"""Read many bytes from the specified device."""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
return self._device.read(number) | python | {
"resource": ""
} |
q275239 | SMBus.read_byte_data | test | def read_byte_data(self, addr, cmd):
"""Read a single byte from the specified cmd register of the device."""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Build ctypes values to marshall between ioctl and Python.
reg = c_uint8(cmd)
... | python | {
"resource": ""
} |
q275240 | SMBus.write_bytes | test | def write_bytes(self, addr, buf):
"""Write many bytes to the specified device. buf is a bytearray"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
self._device.write(buf) | python | {
"resource": ""
} |
q275241 | SMBus.write_byte_data | test | def write_byte_data(self, addr, cmd, val):
"""Write a byte of data to the specified cmd register of the device.
"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Construct a string of data to send with the command register and byte value.
... | python | {
"resource": ""
} |
q275242 | SMBus.write_i2c_block_data | test | def write_i2c_block_data(self, addr, cmd, vals):
"""Write a buffer of data to the specified cmd register of the device.
"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Construct a string of data to send, including room for the command re... | python | {
"resource": ""
} |
q275243 | File.cdn_url | test | def cdn_url(self):
"""Returns file's CDN url.
Usage example::
>>> file_ = File('a771f854-c2cb-408a-8c36-71af77811f3b')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/
You can set default effects::
>>> file_.default_... | python | {
"resource": ""
} |
q275244 | File.copy | test | def copy(self, effects=None, target=None):
"""Creates a File Copy on Uploadcare or Custom Storage.
File.copy method is deprecated and will be removed in 4.0.0.
Please use `create_local_copy` and `create_remote_copy` instead.
Args:
- effects:
Adds CDN... | python | {
"resource": ""
} |
q275245 | File.create_local_copy | test | def create_local_copy(self, effects=None, store=None):
"""Creates a Local File Copy on Uploadcare Storage.
Args:
- effects:
Adds CDN image effects. If ``self.default_effects`` property
is set effects will be combined with default effects.
- store:... | python | {
"resource": ""
} |
q275246 | File.create_remote_copy | test | def create_remote_copy(self, target, effects=None, make_public=None,
pattern=None):
"""Creates file copy in remote storage.
Args:
- target:
Name of a custom storage connected to the project.
- effects:
Adds CDN image eff... | python | {
"resource": ""
} |
q275247 | File.construct_from | test | def construct_from(cls, file_info):
"""Constructs ``File`` instance from file information.
For example you have result of
``/files/1921953c-5d94-4e47-ba36-c2e1dd165e1a/`` API request::
>>> file_info = {
# ...
'uuid': '1921953c-5d94-4e47-ba36-... | python | {
"resource": ""
} |
q275248 | File.upload | test | def upload(cls, file_obj, store=None):
"""Uploads a file and returns ``File`` instance.
Args:
- file_obj: file object to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None.
- False - do not st... | python | {
"resource": ""
} |
q275249 | File.upload_from_url | test | def upload_from_url(cls, url, store=None, filename=None):
"""Uploads file from given url and returns ``FileFromUrl`` instance.
Args:
- url (str): URL of file to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to N... | python | {
"resource": ""
} |
q275250 | File.upload_from_url_sync | test | def upload_from_url_sync(cls, url, timeout=30, interval=0.3,
until_ready=False, store=None, filename=None):
"""Uploads file from given url and returns ``File`` instance.
Args:
- url (str): URL of file to upload to
- store (Optional[bool]): Should the... | python | {
"resource": ""
} |
q275251 | FileGroup.file_cdn_urls | test | def file_cdn_urls(self):
"""Returns CDN urls of all files from group without API requesting.
Usage example::
>>> file_group = FileGroup('0513dda0-582f-447d-846f-096e5df9e2bb~2')
>>> file_group.file_cdn_urls[0]
'https://ucarecdn.com/0513dda0-582f-447d-846f-096e5df9e2... | python | {
"resource": ""
} |
q275252 | FileGroup.construct_from | test | def construct_from(cls, group_info):
"""Constructs ``FileGroup`` instance from group information."""
group = cls(group_info['id'])
group._info_cache = group_info
return group | python | {
"resource": ""
} |
q275253 | FileGroup.create | test | def create(cls, files):
"""Creates file group and returns ``FileGroup`` instance.
It expects iterable object that contains ``File`` instances, e.g.::
>>> file_1 = File('6c5e9526-b0fe-4739-8975-72e8d5ee6342')
>>> file_2 = File('a771f854-c2cb-408a-8c36-71af77811f3b')
... | python | {
"resource": ""
} |
q275254 | FilesStorage._base_opration | test | def _base_opration(self, method):
""" Base method for storage operations.
"""
uuids = self.uuids()
while True:
chunk = list(islice(uuids, 0, self.chunk_size))
if not chunk:
return
rest_request(method, self.storage_url, chunk) | python | {
"resource": ""
} |
q275255 | FilesStorage.uuids | test | def uuids(self):
""" Extract uuid from each item of specified ``seq``.
"""
for f in self._seq:
if isinstance(f, File):
yield f.uuid
elif isinstance(f, six.string_types):
yield f
else:
raise ValueError(
... | python | {
"resource": ""
} |
q275256 | _list | test | def _list(api_list_class, arg_namespace, **extra):
""" A common function for building methods of the "list showing".
"""
if arg_namespace.starting_point:
ordering_field = (arg_namespace.ordering or '').lstrip('-')
if ordering_field in ('', 'datetime_uploaded', 'datetime_created'):
... | python | {
"resource": ""
} |
q275257 | bar | test | def bar(iter_content, parts, title=''):
""" Iterates over the "iter_content" and draws a progress bar to stdout.
"""
parts = max(float(parts), 1.0)
cells = 10
progress = 0
step = cells / parts
draw = lambda progress: sys.stdout.write(
'\r[{0:10}] {1:.2f}% {2}'.format(
'#... | python | {
"resource": ""
} |
q275258 | uploading_request | test | def uploading_request(verb, path, data=None, files=None, timeout=conf.DEFAULT):
"""Makes Uploading API request and returns response as ``dict``.
It takes settings from ``conf`` module.
Make sure that given ``path`` does not contain leading slash.
Usage example::
>>> file_obj = open('photo.jp... | python | {
"resource": ""
} |
q275259 | Api.home_mode_status | test | def home_mode_status(self, **kwargs):
"""Returns the status of Home Mode"""
api = self._api_info['home_mode']
payload = dict({
'api': api['name'],
'method': 'GetInfo',
'version': api['version'],
'_sid': self._sid
}, **kwargs)
respon... | python | {
"resource": ""
} |
q275260 | Api.camera_list | test | def camera_list(self, **kwargs):
"""Return a list of cameras."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'List',
'version': api['version'],
}, **kwargs)
response = self._get_j... | python | {
"resource": ""
} |
q275261 | Api.camera_info | test | def camera_info(self, camera_ids, **kwargs):
"""Return a list of cameras matching camera_ids."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'GetInfo',
'version': api['version'],
'cam... | python | {
"resource": ""
} |
q275262 | Api.camera_snapshot | test | def camera_snapshot(self, camera_id, **kwargs):
"""Return bytes of camera image."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'GetSnapshot',
'version': api['version'],
'cameraId': c... | python | {
"resource": ""
} |
q275263 | Api.camera_disable | test | def camera_disable(self, camera_id, **kwargs):
"""Disable camera."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'Disable',
'version': 9,
'idList': camera_id,
}, **kwargs)
... | python | {
"resource": ""
} |
q275264 | Api.camera_event_motion_enum | test | def camera_event_motion_enum(self, camera_id, **kwargs):
"""Return motion settings matching camera_id."""
api = self._api_info['camera_event']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'MotionEnum',
'version': api['version']... | python | {
"resource": ""
} |
q275265 | Api.camera_event_md_param_save | test | def camera_event_md_param_save(self, camera_id, **kwargs):
"""Update motion settings matching camera_id with keyword args."""
api = self._api_info['camera_event']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'MDParamSave',
'ver... | python | {
"resource": ""
} |
q275266 | SurveillanceStation.update | test | def update(self):
"""Update cameras and motion settings with latest from API."""
cameras = self._api.camera_list()
self._cameras_by_id = {v.camera_id: v for i, v in enumerate(cameras)}
motion_settings = []
for camera_id in self._cameras_by_id.keys():
motion_setting =... | python | {
"resource": ""
} |
q275267 | is_last_li | test | def is_last_li(li, meta_data, current_numId):
"""
Determine if ``li`` is the last list item for a given list
"""
if not is_li(li, meta_data):
return False
w_namespace = get_namespace(li, 'w')
next_el = li
while True:
# If we run out of element this must be the last list item
... | python | {
"resource": ""
} |
q275268 | get_single_list_nodes_data | test | def get_single_list_nodes_data(li, meta_data):
"""
Find consecutive li tags that have content that have the same list id.
"""
yield li
w_namespace = get_namespace(li, 'w')
current_numId = get_numId(li, w_namespace)
starting_ilvl = get_ilvl(li, w_namespace)
el = li
while True:
... | python | {
"resource": ""
} |
q275269 | get_ilvl | test | def get_ilvl(li, w_namespace):
"""
The ilvl on an li tag tells the li tag at what level of indentation this
tag is at. This is used to determine if the li tag needs to be nested or
not.
"""
ilvls = li.xpath('.//w:ilvl', namespaces=li.nsmap)
if len(ilvls) == 0:
return -1
return in... | python | {
"resource": ""
} |
q275270 | get_v_merge | test | def get_v_merge(tc):
"""
vMerge is what docx uses to denote that a table cell is part of a rowspan.
The first cell to have a vMerge is the start of the rowspan, and the vMerge
will be denoted with 'restart'. If it is anything other than restart then
it is a continuation of another rowspan.
"""
... | python | {
"resource": ""
} |
q275271 | get_grid_span | test | def get_grid_span(tc):
"""
gridSpan is what docx uses to denote that a table cell has a colspan. This
is much more simple than rowspans in that there is a one-to-one mapping
from gridSpan to colspan.
"""
w_namespace = get_namespace(tc, 'w')
grid_spans = tc.xpath('.//w:gridSpan', namespaces=t... | python | {
"resource": ""
} |
q275272 | get_td_at_index | test | def get_td_at_index(tr, index):
"""
When calculating the rowspan for a given cell it is required to find all
table cells 'below' the initial cell with a v_merge. This function will
return the td element at the passed in index, taking into account colspans.
"""
current = 0
for td in tr.xpath(... | python | {
"resource": ""
} |
q275273 | style_is_false | test | def style_is_false(style):
"""
For bold, italics and underline. Simply checking to see if the various tags
are present will not suffice. If the tag is present and set to False then
the style should not be present.
"""
if style is None:
return False
w_namespace = get_namespace(style, ... | python | {
"resource": ""
} |
q275274 | is_bold | test | def is_bold(r):
"""
The function will return True if the r tag passed in is considered bold.
"""
w_namespace = get_namespace(r, 'w')
rpr = r.find('%srPr' % w_namespace)
if rpr is None:
return False
bold = rpr.find('%sb' % w_namespace)
return style_is_false(bold) | python | {
"resource": ""
} |
q275275 | is_italics | test | def is_italics(r):
"""
The function will return True if the r tag passed in is considered
italicized.
"""
w_namespace = get_namespace(r, 'w')
rpr = r.find('%srPr' % w_namespace)
if rpr is None:
return False
italics = rpr.find('%si' % w_namespace)
return style_is_false(italics... | python | {
"resource": ""
} |
q275276 | is_underlined | test | def is_underlined(r):
"""
The function will return True if the r tag passed in is considered
underlined.
"""
w_namespace = get_namespace(r, 'w')
rpr = r.find('%srPr' % w_namespace)
if rpr is None:
return False
underline = rpr.find('%su' % w_namespace)
return style_is_false(un... | python | {
"resource": ""
} |
q275277 | is_title | test | def is_title(p):
"""
Certain p tags are denoted as ``Title`` tags. This function will return
True if the passed in p tag is considered a title.
"""
w_namespace = get_namespace(p, 'w')
styles = p.xpath('.//w:pStyle', namespaces=p.nsmap)
if len(styles) == 0:
return False
style = st... | python | {
"resource": ""
} |
q275278 | get_text_run_content_data | test | def get_text_run_content_data(r):
"""
It turns out that r tags can contain both t tags and drawing tags. Since we
need both, this function will return them in the order in which they are
found.
"""
w_namespace = get_namespace(r, 'w')
valid_elements = (
'%st' % w_namespace,
'%... | python | {
"resource": ""
} |
q275279 | get_relationship_info | test | def get_relationship_info(tree, media, image_sizes):
"""
There is a separate file holds the targets to links as well as the targets
for images. Return a dictionary based on the relationship id and the
target.
"""
if tree is None:
return {}
result = {}
# Loop through each relation... | python | {
"resource": ""
} |
q275280 | _get_document_data | test | def _get_document_data(f, image_handler=None):
'''
``f`` is a ``ZipFile`` that is open
Extract out the document data, numbering data and the relationship data.
'''
if image_handler is None:
def image_handler(image_id, relationship_dict):
return relationship_dict.get(image_id)
... | python | {
"resource": ""
} |
q275281 | get_ordered_list_type | test | def get_ordered_list_type(meta_data, numId, ilvl):
"""
Return the list type. If numId or ilvl not in the numbering dict then
default to returning decimal.
This function only cares about ordered lists, unordered lists get dealt
with elsewhere.
"""
# Early return if numId or ilvl are not val... | python | {
"resource": ""
} |
q275282 | build_list | test | def build_list(li_nodes, meta_data):
"""
Build the list structure and return the root list
"""
# Need to keep track of all incomplete nested lists.
ol_dict = {}
# Need to keep track of the current indentation level.
current_ilvl = -1
# Need to keep track of the current list id.
cur... | python | {
"resource": ""
} |
q275283 | build_tr | test | def build_tr(tr, meta_data, row_spans):
"""
This will return a single tr element, with all tds already populated.
"""
# Create a blank tr element.
tr_el = etree.Element('tr')
w_namespace = get_namespace(tr, 'w')
visited_nodes = []
for el in tr:
if el in visited_nodes:
... | python | {
"resource": ""
} |
q275284 | build_table | test | def build_table(table, meta_data):
"""
This returns a table object with all rows and cells correctly populated.
"""
# Create a blank table element.
table_el = etree.Element('table')
w_namespace = get_namespace(table, 'w')
# Get the rowspan values for cells that have a rowspan.
row_span... | python | {
"resource": ""
} |
q275285 | get_t_tag_content | test | def get_t_tag_content(
t, parent, remove_bold, remove_italics, meta_data):
"""
Generate the string data that for this particular t tag.
"""
if t is None or t.text is None:
return ''
# Need to escape the text so that we do not accidentally put in text
# that is not valid XML.
... | python | {
"resource": ""
} |
q275286 | _strip_tag | test | def _strip_tag(tree, tag):
"""
Remove all tags that have the tag name ``tag``
"""
for el in tree.iter():
if el.tag == tag:
el.getparent().remove(el) | python | {
"resource": ""
} |
q275287 | find | test | def find(dataset, url):
'''Find the location of a dataset on disk, downloading if needed.'''
fn = os.path.join(DATASETS, dataset)
dn = os.path.dirname(fn)
if not os.path.exists(dn):
print('creating dataset directory: %s', dn)
os.makedirs(dn)
if not os.path.exists(fn):
if sys.... | python | {
"resource": ""
} |
q275288 | load_mnist | test | def load_mnist(flatten=True, labels=False):
'''Load the MNIST digits dataset.'''
fn = find('mnist.pkl.gz', 'http://deeplearning.net/data/mnist/mnist.pkl.gz')
h = gzip.open(fn, 'rb')
if sys.version_info < (3, ):
(timg, tlab), (vimg, vlab), (simg, slab) = pickle.load(h)
else:
(timg, tl... | python | {
"resource": ""
} |
q275289 | load_cifar | test | def load_cifar(flatten=True, labels=False):
'''Load the CIFAR10 image dataset.'''
def extract(name):
print('extracting data from {}'.format(name))
h = tar.extractfile(name)
if sys.version_info < (3, ):
d = pickle.load(h)
else:
d = pickle.load(h, encoding='... | python | {
"resource": ""
} |
q275290 | plot_images | test | def plot_images(imgs, loc, title=None, channels=1):
'''Plot an array of images.
We assume that we are given a matrix of data whose shape is (n*n, s*s*c) --
that is, there are n^2 images along the first axis of the array, and each
image is c squares measuring s pixels on a side. Each row of the input wi... | python | {
"resource": ""
} |
q275291 | plot_layers | test | def plot_layers(weights, tied_weights=False, channels=1):
'''Create a plot of weights, visualized as "bottom-level" pixel arrays.'''
if hasattr(weights[0], 'get_value'):
weights = [w.get_value() for w in weights]
k = min(len(weights), 9)
imgs = np.eye(weights[0].shape[0])
for i, weight in en... | python | {
"resource": ""
} |
q275292 | plot_filters | test | def plot_filters(filters):
'''Create a plot of conv filters, visualized as pixel arrays.'''
imgs = filters.get_value()
N, channels, x, y = imgs.shape
n = int(np.sqrt(N))
assert n * n == N, 'filters must contain a square number of rows!'
assert channels == 1 or channels == 3, 'can only plot gray... | python | {
"resource": ""
} |
q275293 | batches | test | def batches(arrays, steps=100, batch_size=64, rng=None):
'''Create a callable that generates samples from a dataset.
Parameters
----------
arrays : list of ndarray (time-steps, data-dimensions)
Arrays of data. Rows in these arrays are assumed to correspond to time
steps, and columns to ... | python | {
"resource": ""
} |
q275294 | Text.encode | test | def encode(self, txt):
'''Encode a text string by replacing characters with alphabet index.
Parameters
----------
txt : str
A string to encode.
Returns
-------
classes : list of int
A sequence of alphabet index values corresponding to the... | python | {
"resource": ""
} |
q275295 | Text.classifier_batches | test | def classifier_batches(self, steps, batch_size, rng=None):
'''Create a callable that returns a batch of training data.
Parameters
----------
steps : int
Number of time steps in each batch.
batch_size : int
Number of training examples per batch.
rn... | python | {
"resource": ""
} |
q275296 | Classifier.predict_sequence | test | def predict_sequence(self, labels, steps, streams=1, rng=None):
'''Draw a sequential sample of class labels from this network.
Parameters
----------
labels : list of int
A list of integer class labels to get the classifier started.
steps : int
The number ... | python | {
"resource": ""
} |
q275297 | Convolution.add_conv_weights | test | def add_conv_weights(self, name, mean=0, std=None, sparsity=0):
'''Add a convolutional weight array to this layer's parameters.
Parameters
----------
name : str
Name of the parameter to add.
mean : float, optional
Mean value for randomly-initialized weigh... | python | {
"resource": ""
} |
q275298 | Autoencoder.encode | test | def encode(self, x, layer=None, sample=False, **kwargs):
'''Encode a dataset using the hidden layer activations of our network.
Parameters
----------
x : ndarray
A dataset to encode. Rows of this dataset capture individual data
points, while columns represent the... | python | {
"resource": ""
} |
q275299 | Autoencoder.decode | test | def decode(self, z, layer=None, **kwargs):
'''Decode an encoded dataset by computing the output layer activation.
Parameters
----------
z : ndarray
A matrix containing encoded data from this autoencoder.
layer : int or str or :class:`Layer <layers.Layer>`, optional
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.