code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def iter_block_items(self):
block_item_tags = (qn('w:p'), qn('w:tbl'), qn('w:sdt'))
for child in self:
if child.tag in block_item_tags:
yield child | Generate a reference to each of the block-level content elements in
this cell, in the order they appear. |
def lock(self, resource, label='', expire=60, patience=60):
queue = Queue(client=self.client, resource=resource)
with queue.draw(label=label, expire=expire) as number:
queue.wait(number=number, patience=patience)
yield
queue.close() | Lock a resource.
:param resource: String corresponding to resource type
:param label: String label to attach
:param expire: int seconds
:param patience: int seconds |
def _callUpgradeAgent(self, ev_data, failTimeout) -> None:
logger.info("{}'s upgrader calling agent for upgrade".format(self))
self._actionLog.append_started(ev_data)
self._action_start_callback()
self.scheduledAction = None
asyncio.ensure_future(
self._sendUpgradeReq... | Callback which is called when upgrade time come.
Writes upgrade record to upgrade log and asks
node control service to perform upgrade
:param when: upgrade time
:param version: version to upgrade to |
def error_wrapper(error, errorClass):
http_status = 0
if error.check(TwistedWebError):
xml_payload = error.value.response
if error.value.status:
http_status = int(error.value.status)
else:
error.raiseException()
if http_status >= 400:
if not xml_payload:
... | We want to see all error messages from cloud services. Amazon's EC2 says
that their errors are accompanied either by a 400-series or 500-series HTTP
response code. As such, the first thing we want to do is check to see if
the error is in that range. If it is, we then need to see if the error
message is ... |
def check_is_dataarray(comp):
r
@wraps(comp)
def func(data_array, *args, **kwds):
assert isinstance(data_array, xr.DataArray)
return comp(data_array, *args, **kwds)
return func | r"""Decorator to check that a computation has an instance of xarray.DataArray
as first argument. |
def close(self):
handle = self.__handle
if handle is None:
return
weak_transfer_set = self.__transfer_set
transfer_set = self.__set()
while True:
try:
transfer = weak_transfer_set.pop()
except self.__KeyError:
br... | Close this handle. If not called explicitely, will be called by
destructor.
This method cancels any in-flight transfer when it is called. As
cancellation is not immediate, this method needs to let libusb handle
events until transfers are actually cancelled.
In multi-threaded pro... |
def log_mel_spectrogram(data,
audio_sample_rate=8000,
log_offset=0.0,
window_length_secs=0.025,
hop_length_secs=0.010,
**kwargs):
window_length_samples = int(round(audio_sample_rate * window_length_... | Convert waveform to a log magnitude mel-frequency spectrogram.
Args:
data: 1D np.array of waveform data.
audio_sample_rate: The sampling rate of data.
log_offset: Add this to values when taking log to avoid -Infs.
window_length_secs: Duration of each window to analyze.
hop_length_secs: Advance be... |
def _write(self, items):
response = self._batch_write_item(items)
if 'consumed_capacity' in response:
self.consumed_capacity = \
sum(response['consumed_capacity'], self.consumed_capacity)
if response.get('UnprocessedItems'):
unprocessed = response['Unproce... | Perform a batch write and handle the response |
def get_service(self, service_name):
service = self.services.get(service_name)
if not service:
raise KeyError('Service not registered: %s' % service_name)
return service | Given the name of a registered service, return its service definition. |
def keyring_refresh(**kwargs):
ctx = Context(**kwargs)
ctx.execute_action('keyring:refresh', **{
'tvm': ctx.repo.create_secure_service('tvm'),
}) | Refresh the keyring in the cocaine-runtime. |
def embed_seqdiag_sequence(self):
test_name = BuiltIn().replace_variables('${TEST NAME}')
outputdir = BuiltIn().replace_variables('${OUTPUTDIR}')
path = os.path.join(outputdir, test_name + '.seqdiag')
SeqdiagGenerator().compile(path, self._message_sequence) | Create a message sequence diagram png file to output folder and embed the image to log file.
You need to have seqdiag installed to create the sequence diagram. See http://blockdiag.com/en/seqdiag/ |
def get_annotation_entries_by_names(self, url: str, names: Iterable[str]) -> List[NamespaceEntry]:
annotation_filter = and_(Namespace.url == url, NamespaceEntry.name.in_(names))
return self.session.query(NamespaceEntry).join(Namespace).filter(annotation_filter).all() | Get annotation entries by URL and names.
:param url: The url of the annotation source
:param names: The names of the annotation entries from the given url's document |
def restore_model(cls, data):
obj = cls()
for field in data:
setattr(obj, field, data[field][Field.VALUE])
return obj | Returns instance of ``cls`` with attributed loaded
from ``data`` dict. |
def _get_log_model_class(self):
if self.log_model_class is not None:
return self.log_model_class
app_label, model_label = self.log_model.rsplit('.', 1)
self.log_model_class = apps.get_model(app_label, model_label)
return self.log_model_class | Cache for fetching the actual log model object once django is loaded.
Otherwise, import conflict occur: WorkflowEnabled imports <log_model>
which tries to import all models to retrieve the proper model class. |
def pandas(self):
names,prior,posterior = [],[],[]
for iname,name in enumerate(self.posterior_parameter.row_names):
names.append(name)
posterior.append(np.sqrt(float(
self.posterior_parameter[iname, iname]. x)))
iprior = self.parcov.row_names.index(nam... | get a pandas dataframe of prior and posterior for all predictions
Returns:
pandas.DataFrame : pandas.DataFrame
a dataframe with prior and posterior uncertainty estimates
for all forecasts (predictions) |
def get_layer(self, class_: Type[L], became: bool=True) -> L:
try:
return self._index[class_][0]
except KeyError:
if became:
return self._transformed[class_][0]
else:
raise | Return the first layer of a given class. If that layer is not present,
then raise a KeyError.
:param class_: class of the expected layer
:param became: Allow transformed layers in results |
def open(path, mode='r', host=None, user=None, port=DEFAULT_PORT):
if not host:
raise ValueError('you must specify the host to connect to')
if not user:
user = getpass.getuser()
conn = _connect(host, user, port)
sftp_client = conn.get_transport().open_sftp_client()
return sftp_client... | Open a file on a remote machine over SSH.
Expects authentication to be already set up via existing keys on the local machine.
Parameters
----------
path: str
The path to the file to open on the remote machine.
mode: str, optional
The mode to use for opening the file.
host: str,... |
def _condense(self, data):
if data:
data = filter(None,data.values())
if data:
return data[-1]
return None | Condense by returning the last real value of the gauge. |
def create_project(args):
try:
__import__(args.project_name)
except ImportError:
pass
else:
sys.exit("'{}' conflicts with the name of an existing "
"Python module and cannot be used as a project "
"name. Please try another name.".format(args.project_... | Create a new django project using the longclaw template |
def onSave(self, event, alert=False, destroy=True):
if self.drop_down_menu:
self.drop_down_menu.clean_up()
self.grid_builder.save_grid_data()
if not event and not alert:
return
wx.MessageBox('Saved!', 'Info',
style=wx.OK | wx.ICON_INFORMATION... | Save grid data |
def comments(self, update=True):
if not self._comments:
if self.count == 0:
return self._continue_comments(update)
children = [x for x in self.children if 't1_{0}'.format(x)
not in self.submission._comments_by_id]
if not children:
... | Fetch and return the comments for a single MoreComments object. |
def get_process_definition_start(fname, slug):
with open(fname) as file_:
for i, line in enumerate(file_):
if re.search(r'slug:\s*{}'.format(slug), line):
return i + 1
return 1 | Find the first line of process definition.
The first line of process definition is the line with a slug.
:param str fname: Path to filename with processes
:param string slug: process slug
:return: line where the process definiton starts
:rtype: int |
def tag_builder(parser, token, cls, flow_type):
tokens = token.split_contents()
tokens_num = len(tokens)
if tokens_num == 1 or (tokens_num == 3 and tokens[1] == 'for'):
flow_name = None
if tokens_num == 3:
flow_name = tokens[2]
return cls(flow_name)
else:
rais... | Helper function handling flow form tags. |
def get_hash(self, handle):
fpath = self._fpath_from_handle(handle)
return DiskStorageBroker.hasher(fpath) | Return the hash. |
def aborted(self, exc_info):
self.exc_info = exc_info
self.did_end = True
self.write(format_exception(*self.exc_info)) | Called by a logger to log an exception. |
def get_issns_for_journal(nlm_id):
params = {'db': 'nlmcatalog',
'retmode': 'xml',
'id': nlm_id}
tree = send_request(pubmed_fetch, params)
if tree is None:
return None
issn_list = tree.findall('.//ISSN')
issn_linking = tree.findall('.//ISSNLinking')
issns = is... | Get a list of the ISSN numbers for a journal given its NLM ID.
Information on NLM XML DTDs is available at
https://www.nlm.nih.gov/databases/dtd/ |
def scope(self, scope):
if scope is None:
raise ValueError("Invalid value for `scope`, must not be `None`")
allowed_values = ["CLUSTER", "CUSTOMER", "USER"]
if scope not in allowed_values:
raise ValueError(
"Invalid value for `scope` ({0}), must be one of ... | Sets the scope of this Message.
The audience scope that this message should reach # noqa: E501
:param scope: The scope of this Message. # noqa: E501
:type: str |
def match(tgt, opts=None):
if not opts:
opts = __opts__
if not isinstance(tgt, six.string_types):
return False
return fnmatch.fnmatch(opts['id'], tgt) | Returns true if the passed glob matches the id |
def create(cls, path_name=None, name=None, crawlable=True):
project = cls(path_name, name, crawlable)
db.session.add(project)
db.session.commit()
return collect_results(project, force=True) | initialize an instance and save it to db. |
def tot_edges(self):
all_edges = []
for facet in self.facets:
edges = []
pt = self.get_line_in_facet(facet)
lines = []
for i, p in enumerate(pt):
if i == len(pt) / 2:
break
lines.append(tuple(sorted(tuple... | Returns the number of edges in the convex hull.
Useful for identifying catalytically active sites. |
def add_validate(subparsers):
validate_parser = subparsers.add_parser(
'validate', help=add_validate.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
validate_parser.set_defaults(func=validate_parser.print_help)
validate_subparsers = validate_parser.add_subparsers(title='Testers')
... | Validate Spinnaker setup. |
def register_callbacks(self, on_create, on_modify, on_delete):
self.on_create = on_create
self.on_modify = on_modify
self.on_delete = on_delete | Register callbacks for file creation, modification, and deletion |
def update_tenant(
self,
tenant,
update_mask=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
if "update_tenant" not in self._inner_api_calls:
self._inner_api_calls[
... | Updates specified tenant.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.TenantServiceClient()
>>>
>>> # TODO: Initialize `tenant`:
>>> tenant = {}
>>>
>>> response = client.upd... |
def view_context(self):
url = self.get_selected_item().get('context')
if url:
self.selected_page = self.open_submission_page(url) | View the context surrounding the selected comment. |
def compat_get_paginated_response(view, page):
if DRFVLIST[0] == 3 and DRFVLIST[1] >= 1:
from rest_messaging.serializers import ComplexMessageSerializer
serializer = ComplexMessageSerializer(page, many=True)
return view.get_paginated_response(serializer.data)
else:
serializer = v... | get_paginated_response is unknown to DRF 3.0 |
def _build_tag_param_list(params, tags):
keys = sorted(tags.keys())
i = 1
for key in keys:
value = tags[key]
params['Tags.member.{0}.Key'.format(i)] = key
if value is not None:
params['Tags.member.{0}.Value'.format(i)] = value
i += 1 | helper function to build a tag parameter list to send |
def _emp_extra_options(options):
metadata_path = os.path.normpath(os.path.join(options['param_dir'],
options['metadata']))
if not os.path.isfile(metadata_path):
raise IOError, ("Path to metadata file %s is invalid." %
metadata_pat... | Get special options patch, cols, and splits if analysis in emp module |
def create_lockfile(self):
process = subprocess.Popen(
self.pin_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
if process.returncode == 0:
self.fix_lockfile()
else:
logg... | Write recursive dependencies list to outfile
with hard-pinned versions.
Then fix it. |
def put(self, item, *args, **kwargs):
if not self.enabled:
return
timeout = kwargs.pop('timeout', None)
if timeout is None:
timeout = self.default_timeout
cache_key = self.make_key(args, kwargs)
with self._cache_lock:
self._cache[cache_key] = (... | Put an item into the cache, for this combination of args and kwargs.
Args:
*args: any arguments.
**kwargs: any keyword arguments. If ``timeout`` is specified as one
of the keyword arguments, the item will remain available
for retrieval for ``timeout`` s... |
def acquire(self, **kwargs):
return config.download_data(self.temp_filename, self.url,
self.sha256) | Download the file and return its path
Returns
-------
str or None
The path of the file in BatchUp's temporary directory or None if
the download failed. |
def clear(self):
self._logger.debug("Component handlers are cleared")
self._field = None
self._name = None
self._logger = None | Cleans up the handler. The handler can't be used after this method has
been called |
def can_view(self, user):
return user.is_admin or self == user \
or set(self.classes).intersection(user.admin_for) | Return whether or not `user` can view information about the user. |
def ref_context_from_geoloc(geoloc):
text = geoloc.get('text')
geoid = geoloc.get('geoID')
rc = RefContext(name=text, db_refs={'GEOID': geoid})
return rc | Return a RefContext object given a geoloc entry. |
async def on_isupport_casemapping(self, value):
if value in rfc1459.protocol.CASE_MAPPINGS:
self._case_mapping = value
self.channels = rfc1459.parsing.NormalizingDict(self.channels, case_mapping=value)
self.users = rfc1459.parsing.NormalizingDict(self.users, case_mapping=valu... | IRC case mapping for nickname and channel name comparisons. |
async def _execute(self, appt):
user = self.core.auth.user(appt.useriden)
if user is None:
logger.warning('Unknown user %s in stored appointment', appt.useriden)
await self._markfailed(appt)
return
await self.core.boss.execute(self._runJob(user, appt), f'Agend... | Fire off the task to make the storm query |
def competition_leaderboard_view(self, competition):
result = self.process_response(
self.competition_view_leaderboard_with_http_info(competition))
return [LeaderboardEntry(e) for e in result['submissions']] | view a leaderboard based on a competition name
Parameters
==========
competition: the competition name to view leadboard for |
def short_key():
firstlast = list(ascii_letters + digits)
middle = firstlast + list('-_')
return ''.join((
choice(firstlast), choice(middle), choice(middle),
choice(middle), choice(firstlast),
)) | Generate a short key.
>>> key = short_key()
>>> len(key)
5 |
def _refresh_nvr(self):
rpm_info = juicer.utils.rpm_info(self.path)
self.name = rpm_info['name']
self.version = rpm_info['version']
self.release = rpm_info['release'] | Refresh our name-version-release attributes. |
def make_valid_polygon(shape):
assert shape.geom_type == 'Polygon'
shape = make_valid_pyclipper(shape)
assert shape.is_valid
return shape | Make a polygon valid. Polygons can be invalid in many ways, such as
self-intersection, self-touching and degeneracy. This process attempts to
make a polygon valid while retaining as much of its extent or area as
possible.
First, we call pyclipper to robustly union the polygon. Using this on its
own... |
def is_multidex(self):
dexre = re.compile("^classes(\d+)?.dex$")
return len([instance for instance in self.get_files() if dexre.search(instance)]) > 1 | Test if the APK has multiple DEX files
:return: True if multiple dex found, otherwise False |
def set_ctype(self, ctype, orig_ctype=None):
if self.ctype is None:
self.ctype = ctype
self.orig_ctype = orig_ctype | Set the selected content type. Will not override the value of
the content type if that has already been determined.
:param ctype: The content type string to set.
:param orig_ctype: The original content type, as found in the
configuration. |
def printDatawraps() :
l = listDatawraps()
printf("Available datawraps for boostraping\n")
for k, v in l.iteritems() :
printf(k)
printf("~"*len(k) + "|")
for vv in v :
printf(" "*len(k) + "|" + "~~~:> " + vv)
printf('\n') | print all available datawraps for bootstraping |
def include(context, bundle_name, version):
store = Store(context.obj['database'], context.obj['root'])
if version:
version_obj = store.Version.get(version)
if version_obj is None:
click.echo(click.style('version not found', fg='red'))
else:
bundle_obj = store.bundle(bund... | Include a bundle of files into the internal space.
Use bundle name if you simply want to inlcude the latest version. |
def OnTool(self, event):
msgtype = self.ids_msgs[event.GetId()]
post_command_event(self, msgtype) | Toolbar event handler |
def bus_get(celf, type, private, error = None) :
"returns a Connection to one of the predefined D-Bus buses; type is a BUS_xxx value."
error, my_error = _get_error(error)
result = (dbus.dbus_bus_get, dbus.dbus_bus_get_private)[private](type, error._dbobj)
my_error.raise_if_set()
... | returns a Connection to one of the predefined D-Bus buses; type is a BUS_xxx value. |
def set_plot_type(self, plot_type):
ptypes = [pt["type"] for pt in self.plot_types]
self.plot_panel = ptypes.index(plot_type) | Sets plot type |
def verbose(self_,msg,*args,**kw):
self_.__db_print(VERBOSE,msg,*args,**kw) | Print msg merged with args as a verbose message.
See Python's logging module for details of message formatting. |
def inverse_distance_to_grid(xp, yp, variable, grid_x, grid_y, r, gamma=None, kappa=None,
min_neighbors=3, kind='cressman'):
r
points_obs = list(zip(xp, yp))
points_grid = generate_grid_coords(grid_x, grid_y)
img = inverse_distance_to_points(points_obs, variable, points_grid... | r"""Generate an inverse distance interpolation of the given points to a regular grid.
Values are assigned to the given grid using inverse distance weighting based on either
[Cressman1959]_ or [Barnes1964]_. The Barnes implementation used here based on [Koch1983]_.
Parameters
----------
xp: (N, ) n... |
def _get_connection(self):
try:
if self._ncc_connection and self._ncc_connection.connected:
return self._ncc_connection
else:
self._ncc_connection = manager.connect(
host=self._host_ip, port=self._host_ssh_port,
user... | Make SSH connection to the IOS XE device.
The external ncclient library is used for creating this connection.
This method keeps state of any existing connections and reuses them if
already connected. Also interfaces (except management) are typically
disabled by default when it is booted... |
def unset_env():
os.environ.pop('COV_CORE_SOURCE', None)
os.environ.pop('COV_CORE_DATA_FILE', None)
os.environ.pop('COV_CORE_CONFIG', None) | Remove coverage info from env. |
def _GenerateClientInfo(self, client_id, client_fd):
summary_dict = client_fd.ToPrimitiveDict(stringify_leaf_fields=True)
summary = yaml.Dump(summary_dict).encode("utf-8")
client_info_path = os.path.join(self.prefix, client_id, "client_info.yaml")
st = os.stat_result((0o644, 0, 0, 0, 0, 0, len(summary),... | Yields chucks of archive information for given client. |
def create_feature(self, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.create_feature_with_http_info(**kwargs)
else:
(data) = self.create_feature_with_http_info(**kwargs)
return data | Create an enumerated sequence feature
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(respon... |
def get(self, artifact):
coord = self._key(artifact)
if coord in self._artifacts_to_versions:
return self._artifacts_to_versions[coord]
return artifact | Gets the coordinate with the correct version for the given artifact coordinate.
:param M2Coordinate artifact: the coordinate to lookup.
:return: a coordinate which is the same as the input, but with the correct pinned version. If
this artifact set does not pin a version for the input artifact, this just ... |
def show_analysis_dialog(self):
self.analysis_dialog.update_evt_types()
self.analysis_dialog.update_groups()
self.analysis_dialog.update_cycles()
self.analysis_dialog.show() | Create the analysis dialog. |
def add_manager(self, manager):
select_action = 'add_manager'
self._update_scope_project_team(select_action=select_action, user=manager, user_type='manager') | Add a single manager to the scope.
:param manager: single username to be added to the scope list of managers
:type manager: basestring
:raises APIError: when unable to update the scope manager |
async def resetTriggerToken(self, *args, **kwargs):
return await self._makeApiCall(self.funcinfo["resetTriggerToken"], *args, **kwargs) | Reset a trigger token
Reset the token for triggering a given hook. This invalidates token that
may have been issued via getTriggerToken with a new token.
This method gives output: ``v1/trigger-token-response.json#``
This method is ``stable`` |
def first_timestamp(self, sid, epoch=False):
first_block = self.dbcur.execute(SQL_TMPO_FIRST, (sid,)).fetchone()
if first_block is None:
return None
timestamp = first_block[2]
if not epoch:
timestamp = pd.Timestamp.utcfromtimestamp(timestamp)
timestamp... | Get the first available timestamp for a sensor
Parameters
----------
sid : str
SensorID
epoch : bool
default False
If True return as epoch
If False return as pd.Timestamp
Returns
-------
pd.Timestamp | int |
def dispatch_write(self, buf):
self.write_buffer += buf
if len(self.write_buffer) > self.MAX_BUFFER_SIZE:
console_output('Buffer too big ({:d}) for {}\n'.format(
len(self.write_buffer), str(self)).encode())
raise asyncore.ExitNow(1)
return True | Augment the buffer with stuff to write when possible |
def worth(what, level_name):
return (logging.NOTSET
< globals()[what].level
<= getattr(logging, level_name)) | Returns `True` if the watcher `what` would log under `level_name`. |
def reload_localzone():
global _cache_tz
_cache_tz = pytz.timezone(get_localzone_name())
utils.assert_tz_offset(_cache_tz)
return _cache_tz | Reload the cached localzone. You need to call this if the timezone has changed. |
def get_replay(name, query, config, context=None):
endpoint = config.get('replay_endpoints', {}).get(name, None)
if not endpoint:
raise IOError("No appropriate replay endpoint "
"found for {0}".format(name))
if not context:
context = zmq.Context(config['io_threads'])
... | Query the replay endpoint for missed messages.
Args:
name (str): The replay endpoint name.
query (dict): A dictionary used to query the replay endpoint for messages.
Queries are dictionaries with the following any of the following keys:
* 'seq_ids': A ``list`` of ``int``, m... |
def add(self, func: Callable, name: Optional[str]=None,
queue: Optional[str]=None, max_retries: Optional[Number]=None,
periodicity: Optional[timedelta]=None):
if not name:
raise ValueError('Each Spinach task needs a name')
if name in self._tasks:
raise Val... | Register a task function.
:arg func: a callable to be executed
:arg name: name of the task, used later to schedule jobs
:arg queue: queue of the task, the default is used if not provided
:arg max_retries: maximum number of retries, the default is used if
not provided
... |
def escape(self, value):
value = soft_unicode(value)
if self._engine._escape is None:
return value
return self._engine._escape(value) | Escape given value. |
def check_is_notification(self, participant_id, messages):
try:
last_check = NotificationCheck.objects.filter(participant__id=participant_id).latest('id').date_check
except Exception:
for m in messages:
m.is_notification = True
return messages
... | Check if each message requires a notification for the specified participant. |
def request_blocking(self, method, params):
response = self._make_request(method, params)
if "error" in response:
raise ValueError(response["error"])
return response['result'] | Make a synchronous request using the provider |
def _get_error_generator(type, obj, schema_dir=None, version=DEFAULT_VER, default='core'):
if schema_dir is None:
schema_dir = os.path.abspath(os.path.dirname(__file__) + '/schemas-'
+ version + '/')
try:
schema_path = find_schema(schema_dir, type)
sc... | Get a generator for validating against the schema for the given object type.
Args:
type (str): The object type to find the schema for.
obj: The object to be validated.
schema_dir (str): The path in which to search for schemas.
version (str): The version of the STIX specification to ... |
def expr_contains(e, o):
if o == e:
return True
if e.has_args():
for a in e.args():
if expr_contains(a, o):
return True
return False | Returns true if o is in e |
def get_db_filename(impl, working_dir):
db_filename = impl.get_virtual_chain_name() + ".db"
return os.path.join(working_dir, db_filename) | Get the absolute path to the last-block file. |
def process_string_tensor_event(event):
string_arr = tensor_util.make_ndarray(event.tensor_proto)
html = text_array_to_html(string_arr)
return {
'wall_time': event.wall_time,
'step': event.step,
'text': html,
} | Convert a TensorEvent into a JSON-compatible response. |
def load(self, host, exact_host_match=False):
config_string, host_string = ftr_get_config(host, exact_host_match)
if config_string is None:
LOGGER.error(u'Error while loading configuration.',
extra={'siteconfig': host_string})
return
self.append(f... | Load a config for a hostname or url.
This method calls :func:`ftr_get_config` and :meth`append`
internally. Refer to their docs for details on parameters. |
def replace_project(self, project_key, **kwargs):
request = self.__build_project_obj(
lambda: _swagger.ProjectCreateRequest(
title=kwargs.get('title'),
visibility=kwargs.get('visibility')
),
lambda name, url, description, labels:
_s... | Replace an existing Project
*Create a project with a given id or completely rewrite the project,
including any previously added files or linked datasets, if one already
exists with the given id.*
:param project_key: Username and unique identifier of the creator of a
project... |
def get_monitors(self, condition=None, page_size=1000):
req_kwargs = {}
if condition:
req_kwargs['condition'] = condition.compile()
for monitor_data in self._conn.iter_json_pages("/ws/Monitor", **req_kwargs):
yield DeviceCloudMonitor.from_json(self._conn, monitor_data, se... | Return an iterator over all monitors matching the provided condition
Get all inactive monitors and print id::
for mon in dc.monitor.get_monitors(MON_STATUS_ATTR == "DISABLED"):
print(mon.get_id())
Get all the HTTP monitors and print id::
for mon in dc.monitor.... |
def manage_brok(self, brok):
manage = getattr(self, 'manage_' + brok.type + '_brok', None)
if not manage:
return False
brok.prepare()
return manage(brok) | Request the module to manage the given brok.
There are a lot of different possible broks to manage. The list is defined
in the Brok class.
An internal module may redefine this function or, easier, define only the function
for the brok it is interested with. Hence a module interested in ... |
def email_verifier(self, email, raw=False):
params = {'email': email, 'api_key': self.api_key}
endpoint = self.base_endpoint.format('email-verifier')
return self._query_hunter(endpoint, params, raw=raw) | Verify the deliverability of a given email adress.abs
:param email: The email adress to check.
:param raw: Gives back the entire response instead of just the 'data'.
:return: Full payload of the query as a dict. |
def remove_domain_user_role(request, user, role, domain=None):
manager = keystoneclient(request, admin=True).roles
return manager.revoke(role, user=user, domain=domain) | Removes a given single role for a user from a domain. |
def load(klass, filename, inject_env=True):
p = PipfileParser(filename=filename)
pipfile = klass(filename=filename)
pipfile.data = p.parse(inject_env=inject_env)
return pipfile | Load a Pipfile from a given filename. |
def insert_pattern(self, pattern, index):
LOGGER.debug("> Inserting '{0}' at '{1}' index.".format(pattern, index))
self.remove_pattern(pattern)
self.beginInsertRows(self.get_node_index(self.root_node), index, index)
pattern_node = PatternNode(name=pattern)
self.root_node.insert_c... | Inserts given pattern into the Model.
:param pattern: Pattern.
:type pattern: unicode
:param index: Insertion index.
:type index: int
:return: Method success.
:rtype: bool |
def resetStaffCompensationInfo(self, request, queryset):
selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
ct = ContentType.objects.get_for_model(queryset.model)
return HttpResponseRedirect(reverse('resetCompensationRules') + "?ct=%s&ids=%s" % (ct.pk, ",".join(selected))) | This action is added to the list for staff member to permit bulk
reseting to category defaults of compensation information for staff members. |
def _upload_none(self, upload_info, check_result):
return UploadResult(
action=None,
quickkey=check_result['duplicate_quickkey'],
hash_=upload_info.hash_info.file,
filename=upload_info.name,
size=upload_info.size,
created=None,
... | Dummy upload function for when we don't actually upload |
def wait_for_window_focus(self, window, want_focus):
_libxdo.xdo_wait_for_window_focus(self._xdo, window, want_focus) | Wait for a window to have or lose focus.
:param window: The window to wait on
:param want_focus: If 1, wait for focus. If 0, wait for loss of focus. |
def perform_exe_expansion(self):
if self.has_section('executables'):
for option, value in self.items('executables'):
newStr = self.interpolate_exe(value)
if newStr != value:
self.set('executables', option, newStr) | This function will look through the executables section of the
ConfigParser object and replace any values using macros with full paths.
For any values that look like
${which:lalapps_tmpltbank}
will be replaced with the equivalent of which(lalapps_tmpltbank)
Otherwise values w... |
def get_user(
self, identified_with, identifier, req, resp, resource, uri_kwargs
):
stored_value = self.kv_store.get(
self._get_storage_key(identified_with, identifier)
)
if stored_value is not None:
user = self.serialization.loads(stored_value.decode())
... | Get user object for given identifier.
Args:
identified_with (object): authentication middleware used
to identify the user.
identifier: middleware specifix user identifier (string or tuple
in case of all built in authentication middleware classes).
... |
def _delete_msg(self, conn, queue_url, receipt_handle):
resp = conn.delete_message(QueueUrl=queue_url,
ReceiptHandle=receipt_handle)
if resp['ResponseMetadata']['HTTPStatusCode'] != 200:
logger.error('Error: message with receipt handle %s in queue %s '
... | Delete the message specified by ``receipt_handle`` in the queue
specified by ``queue_url``.
:param conn: SQS API connection
:type conn: :py:class:`botocore:SQS.Client`
:param queue_url: queue URL to delete the message from
:type queue_url: str
:param receipt_handle: mess... |
def set_subject(self, value: Union[Literal, Identifier, str], lang: str= None):
return self.metadata.add(key=DC.subject, value=value, lang=lang) | Set the DC Subject literal value
:param value: Value of the subject node
:param lang: Language in which the value is |
def main():
(options, _) = _parse_args()
if options.change_password:
c.keyring_set_password(c["username"])
sys.exit(0)
if options.select:
courses = client.get_courses()
c.selection_dialog(courses)
c.save()
sys.exit(0)
if options.stop:
os.system("ki... | parse command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon |
def get_scenario_data(scenario_id,**kwargs):
user_id = kwargs.get('user_id')
scenario_data = db.DBSession.query(Dataset).filter(Dataset.id==ResourceScenario.dataset_id, ResourceScenario.scenario_id==scenario_id).options(joinedload_all('metadata')).distinct().all()
for sd in scenario_data:
if sd.hidde... | Get all the datasets from the group with the specified name
@returns a list of dictionaries |
def get_ymal_data(data):
try:
format_data = yaml.load(data)
except yaml.YAMLError, e:
msg = "Yaml format error: {}".format(
unicode(str(e), "utf-8")
)
logging.error(msg)
sys.exit(1)
if not check_config(format_data):
sys.exit(1)
return format_da... | Get metadata and validate them
:param data: metadata in yaml format |
def _eval(self):
"Evaluates a individual using recursion and self._pos as pointer"
pos = self._pos
self._pos += 1
node = self._ind[pos]
if isinstance(node, Function):
args = [self._eval() for x in range(node.nargs)]
node.eval(args)
for x in arg... | Evaluates a individual using recursion and self._pos as pointer |
def numbaGaussian2d(psf, sy, sx):
ps0, ps1 = psf.shape
c0,c1 = ps0//2, ps1//2
ssx = 2*sx**2
ssy = 2*sy**2
for i in range(ps0):
for j in range(ps1):
psf[i,j]=exp( -( (i-c0)**2/ssy
+(j-c1)**2/ssx) )
psf/=psf.sum() | 2d Gaussian to be used in numba code |
def get_comments_for_reference_on_date(self, reference_id, from_, to):
comment_list = []
for comment in self.get_comments_for_reference(reference_id):
if overlap(from_, to, comment.start_date, comment.end_date):
comment_list.append(comment)
return objects.CommentList(... | Gets a list of all comments corresponding to a reference ``Id`` and effective during the entire given date range inclusive but not confined to the date range.
arg: reference_id (osid.id.Id): a reference ``Id``
arg: from (osid.calendaring.DateTime): from date
arg: to (osid.calendaring.D... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.