code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def output_before_run(self, run):
"""
The method output_before_run() prints the name of a file to terminal.
It returns the name of the logfile.
@param run: a Run object
"""
# output in terminal
runSet = run.runSet
try:
OutputHandler.print_lock.... | The method output_before_run() prints the name of a file to terminal.
It returns the name of the logfile.
@param run: a Run object |
def cee_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map")
name = ET.SubElement(cee_map, "name")
name.text = kwargs.pop('name')
callback = kwa... | Auto Generated Code |
def list_zones(profile):
'''
List zones for the given profile
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.list_zones profile1
'''
conn = _get_driver(profile=profile)
return [_simple_zone(zone) for zo... | List zones for the given profile
:param profile: The profile key
:type profile: ``str``
CLI Example:
.. code-block:: bash
salt myminion libcloud_dns.list_zones profile1 |
def get_exception_based_on_api_message(message, image_name=""):
"""Return the exception matching the given API error message."""
msg_bigger_than_source = re.compile('Image was not scaled, is the requested width bigger than the source?')
msg_does_not_exist = re.compile('The source file .* does not exist')
... | Return the exception matching the given API error message. |
def get_gopath(self, target):
"""Returns the $GOPATH for the given target."""
return os.path.join(self.workdir, target.id) | Returns the $GOPATH for the given target. |
def write(self, content=None):
"""
Write report to file.
Parameters
----------
content: str
'summary', 'extended', 'powerflow'
"""
if self.system.files.no_output is True:
return
t, _ = elapsed()
if not content:
... | Write report to file.
Parameters
----------
content: str
'summary', 'extended', 'powerflow' |
def deploy(self):
"""
Open a ZIP archive, validate requirements then deploy the webfont into
project static files
"""
self._info("* Opening archive: {}", self.archive_path)
if not os.path.exists(self.archive_path):
self._error("Given path does not exists: {}",... | Open a ZIP archive, validate requirements then deploy the webfont into
project static files |
def descendants(self, cl=None, noduplicates=True):
""" returns all descendants in the taxonomy """
if not cl:
cl = self
if cl.children():
bag = []
for x in cl.children():
if x.uri != cl.uri: # avoid circular relationships
b... | returns all descendants in the taxonomy |
def add_reader(
self,
fd: IFileLike,
callback: typing.Callable[[IFileLike], typing.Any],
) -> None:
"""Add a file descriptor to the processor and wait for READ.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
return... | Add a file descriptor to the processor and wait for READ.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
returns a valid file descriptor integer.
callback (typing.Callable[[IFileLike], typing.Any]): A function
that consumes the IFileL... |
def send_template_message(self, user_id, template_id, data, url='', topcolor='#FF0000'):
"""
发送模版消息
详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html
:param user_id: 用户 ID, 就是你收到的 WechatMessage 的 source (OpenID)
:param template_id: 模板ID
:param da... | 发送模版消息
详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html
:param user_id: 用户 ID, 就是你收到的 WechatMessage 的 source (OpenID)
:param template_id: 模板ID
:param data: 模板消息数据 (dict形式),示例如下:
{
"first": {
"value": "恭喜你购买成功!",
... |
def do_fileplaceholder(parser, token):
"""
Method that parse the fileplaceholder template tag.
"""
name, params = parse_placeholder(parser, token)
return FilePlaceholderNode(name, **params) | Method that parse the fileplaceholder template tag. |
def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
"""
self.Script = reader.ReadVarBytes()
self.ParameterList = reader.ReadVarBytes()
self.ReturnType = reader.ReadByte() | Deserialize full object.
Args:
reader (neo.IO.BinaryReader): |
def path_param(name, ns):
"""
Build a path parameter definition.
"""
if ns.identifier_type == "uuid":
param_type = "string"
param_format = "uuid"
else:
param_type = "string"
param_format = None
kwargs = {
"name": name,
"in": "path",
"requ... | Build a path parameter definition. |
def _serialize(self, value, *args, **kwargs):
"""Serialize given datetime to timestamp."""
if value is not None:
value = super(MSTimestamp, self)._serialize(value, *args) * 1e3
return value | Serialize given datetime to timestamp. |
def pretty_print_probabilities(self, decimal_digits=2):
"""
Prints outcome probabilities, ignoring all outcomes with approximately zero probabilities
(up to a certain number of decimal digits) and rounding the probabilities to decimal_digits.
:param int decimal_digits: The number of dig... | Prints outcome probabilities, ignoring all outcomes with approximately zero probabilities
(up to a certain number of decimal digits) and rounding the probabilities to decimal_digits.
:param int decimal_digits: The number of digits to truncate to.
:return: A dict with outcomes as keys and probab... |
def _postprocess_request(self, r):
"""
This converts the response to either the response or a parsed :class:`pytgbot.api_types.receivable.Receivable`.
:param r: the request response
:type r: requests.Response
:return: The json response from the server, or, if `self.return_pyth... | This converts the response to either the response or a parsed :class:`pytgbot.api_types.receivable.Receivable`.
:param r: the request response
:type r: requests.Response
:return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type.
:r... |
def emit_event(self, event):
"""Emit the specified event (notify listeners)"""
with self._lock:
listeners = list(self._event_listeners)
for cb in list(self._event_listeners):
# noinspection PyBroadException
try:
cb(event)
except:
... | Emit the specified event (notify listeners) |
def focusout(self, event):
"""Change style on focus out events."""
bc = self.style.lookup("TEntry", "bordercolor", ("!focus",))
dc = self.style.lookup("TEntry", "darkcolor", ("!focus",))
lc = self.style.lookup("TEntry", "lightcolor", ("!focus",))
self.style.configure("%s.spinbox.... | Change style on focus out events. |
def clipping_params(ts, capacity=100, rate_limit=float('inf'), method=None, max_attempts=100):
"""Start, end, and threshold that clips the value of a time series the most, given a limitted "capacity" and "rate"
Assumes that signal can be linearly interpolated between points (trapezoidal integration)
Argum... | Start, end, and threshold that clips the value of a time series the most, given a limitted "capacity" and "rate"
Assumes that signal can be linearly interpolated between points (trapezoidal integration)
Arguments:
ts (TimeSeries): Time series to attempt to clip to as low a max value as possible
ca... |
def check_for_session(self, status=None):
""" check_for_session: see if session is in progress
Args:
status (str): step to check if last session reached (optional)
Returns: boolean indicating if session exists
"""
status = Status.LAST if status is None els... | check_for_session: see if session is in progress
Args:
status (str): step to check if last session reached (optional)
Returns: boolean indicating if session exists |
def _get_conversion_type(self, convert_to=None):
'''a helper function to return the conversion type based on user
preference and input recipe.
Parameters
==========
convert_to: a string either docker or singularity (default None)
'''
acceptable = ['... | a helper function to return the conversion type based on user
preference and input recipe.
Parameters
==========
convert_to: a string either docker or singularity (default None) |
def bamsort_and_index(job, job_vars):
"""
Sorts bam file and produces index file
job_vars: tuple Tuple of dictionaries: input_args and ids
"""
# Unpack variables
input_args, ids = job_vars
work_dir = job.fileStore.getLocalTempDir()
sudo = input_args['sudo']
# I/O
rg_alignmen... | Sorts bam file and produces index file
job_vars: tuple Tuple of dictionaries: input_args and ids |
def _translate_range(self, len_, start, end):
"""
Translate range to valid bounds.
"""
if start < 0:
start += len_
start = max(0, min(start, len_))
if end < 0:
end += len_
end = max(-1, min(end, len_ - 1))
return start, end | Translate range to valid bounds. |
def get_input(self, more=False):
"""Prompt for code input."""
received = None
try:
received = self.prompt.input(more)
except KeyboardInterrupt:
print()
printerr("KeyboardInterrupt")
except EOFError:
print()
self.exit_run... | Prompt for code input. |
def p_to_find(self, ):
'''
To find, pager.
'''
kwd = {
'pager': '',
}
self.render('user/user_find_list.html',
kwd=kwd,
view=MUser.get_by_keyword(""),
cfg=config.CMS_CFG,
userinfo=... | To find, pager. |
def handle_fk_field(self, obj, field):
"""
Called to handle a ForeignKey (we need to treat them slightly
differently from regular fields).
"""
self._start_relational_field(field)
related = getattr(obj, field.name)
if related is not None:
if self.use_na... | Called to handle a ForeignKey (we need to treat them slightly
differently from regular fields). |
def contains(self, *items):
"""Asserts that val contains the given item or items."""
if len(items) == 0:
raise ValueError('one or more args must be given')
elif len(items) == 1:
if items[0] not in self.val:
if self._check_dict_like(self.val, return_as_bool... | Asserts that val contains the given item or items. |
def logger():
"""Access global logger"""
global _LOGGER
if _LOGGER is None:
logging.basicConfig()
_LOGGER = logging.getLogger()
_LOGGER.setLevel('INFO')
return _LOGGER | Access global logger |
def execute(self, statement, *args, **kwargs):
"""
This convenience method will execute the query passed in as is. For
more complex functionality you may want to use the sqlalchemy engine
directly, but this serves as an example implementation.
:param select_query: SQL statement... | This convenience method will execute the query passed in as is. For
more complex functionality you may want to use the sqlalchemy engine
directly, but this serves as an example implementation.
:param select_query: SQL statement to execute that will identify the
resultset of interes... |
def get_timestamp_expression(self, time_grain):
"""Getting the time component of the query"""
label = utils.DTTM_ALIAS
db = self.table.database
pdf = self.python_date_format
is_epoch = pdf in ('epoch_s', 'epoch_ms')
if not self.expression and not time_grain and not is_ep... | Getting the time component of the query |
def _h2ab_s(s):
"""Define the saturated line boundary between Region 4 and 2a-2b, h=f(s)
Parameters
----------
s : float
Specific entropy, [kJ/kgK]
Returns
-------
h : float
Specific enthalpy, [kJ/kg]
Notes
------
Raise :class:`NotImplementedError` if input isn... | Define the saturated line boundary between Region 4 and 2a-2b, h=f(s)
Parameters
----------
s : float
Specific entropy, [kJ/kgK]
Returns
-------
h : float
Specific enthalpy, [kJ/kg]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
*... |
def validate_schema(cls, tx):
"""Validate the validator election vote transaction. Since `VOTE` extends `TRANSFER`
transaction, all the validations for `CREATE` transaction should be inherited
"""
_validate_schema(TX_SCHEMA_COMMON, tx)
_validate_schema(TX_SCHEMA_TRANSFER, tx)
... | Validate the validator election vote transaction. Since `VOTE` extends `TRANSFER`
transaction, all the validations for `CREATE` transaction should be inherited |
def split_data(self, train_images, train_labels):
"""
:param train_images: numpy array (image_dim, image_dim, num_images)
:param train_labels: numpy array (labels)
:return: train_images, train_labels, valid_images, valid_labels
"""
valid_images = train_images[:self.num_va... | :param train_images: numpy array (image_dim, image_dim, num_images)
:param train_labels: numpy array (labels)
:return: train_images, train_labels, valid_images, valid_labels |
def extract_xyz_matrix_from_loop_json(pdb_lines, parsed_loop_json_contents, atoms_of_interest = backbone_atoms, expected_num_residues = None, expected_num_residue_atoms = None, allow_overlaps = False, include_all_columns = False):
'''A utility wrapper to extract_xyz_matrix_from_pdb_residue_range.
Thi... | A utility wrapper to extract_xyz_matrix_from_pdb_residue_range.
This accepts PDB file lines and a loop.json file (a defined Rosetta format) and returns a pandas dataframe of
the X, Y, Z coordinates for the requested atom types for all residues in all loops defined by the loop.json
file.... |
def parse_timedelta(text):
"""Robustly parses a short text description of a time period into a
:class:`datetime.timedelta`. Supports weeks, days, hours, minutes,
and seconds, with or without decimal points:
Args:
text (str): Text to parse.
Returns:
datetime.timedelta
Raises:
... | Robustly parses a short text description of a time period into a
:class:`datetime.timedelta`. Supports weeks, days, hours, minutes,
and seconds, with or without decimal points:
Args:
text (str): Text to parse.
Returns:
datetime.timedelta
Raises:
ValueError: on parse failure.... |
def read_block(self, block):
"""Read an 8-byte data block at address (block * 8).
"""
if block < 0 or block > 255:
raise ValueError("invalid block number")
log.debug("read block {0}".format(block))
cmd = "\x02" + chr(block) + 8 * chr(0) + self.uid
return self.... | Read an 8-byte data block at address (block * 8). |
def to_array(self):
"""
Serializes this MessageEntity to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(MessageEntity, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
arra... | Serializes this MessageEntity to a dictionary.
:return: dictionary representation of this object.
:rtype: dict |
def _init_sub_dsp(self, dsp, fringe, outputs, no_call, initial_dist, index,
full_name):
"""
Initialize the dispatcher as sub-dispatcher and update the fringe.
:param fringe:
Heapq of closest available nodes.
:type fringe: list[(float | int, bool, (str, ... | Initialize the dispatcher as sub-dispatcher and update the fringe.
:param fringe:
Heapq of closest available nodes.
:type fringe: list[(float | int, bool, (str, Dispatcher)]
:param outputs:
Ending data nodes.
:type outputs: list[str], iterable
:param no... |
def _handle_timeout(self) -> None:
"""Called by IOLoop when the requested timeout has passed."""
self._timeout = None
while True:
try:
ret, num_handles = self._multi.socket_action(pycurl.SOCKET_TIMEOUT, 0)
except pycurl.error as e:
ret = e.... | Called by IOLoop when the requested timeout has passed. |
def exists(self, client=None):
"""API call: test for the existence of the taskqueue via a GET request
See
https://cloud.google.com/appengine/docs/python/taskqueue/rest/taskqueues/get
:type client: :class:`taskqueue.client.Client` or ``NoneType``
:param client: the client to us... | API call: test for the existence of the taskqueue via a GET request
See
https://cloud.google.com/appengine/docs/python/taskqueue/rest/taskqueues/get
:type client: :class:`taskqueue.client.Client` or ``NoneType``
:param client: the client to use. If not passed, falls back to the
... |
def host(self):
'''Return the host committee.
'''
_id = None
for participant in self['participants']:
if participant['type'] == 'host':
if set(['participant_type', 'id']) < set(participant):
# This event uses the id keyname "id".
... | Return the host committee. |
def output(self, value):
"""
Sets the client's output (on, off, int)
Sets the general purpose output on some display modules to this value.
Use on to set all outputs to high state, and off to set all to low state.
The meaning of the integer value depends on your specific... | Sets the client's output (on, off, int)
Sets the general purpose output on some display modules to this value.
Use on to set all outputs to high state, and off to set all to low state.
The meaning of the integer value depends on your specific device, usually
it is a bit pattern ... |
def get_clone(rec):
"""
>>> get_clone("Medicago truncatula chromosome 2 clone mth2-48e18")
('2', 'mth2-48e18')
"""
s = rec.description
chr = re.search(chr_pat, s)
clone = re.search(clone_pat, s)
chr = chr.group(1) if chr else ""
clone = clone.group(1) if clone else ""
return chr... | >>> get_clone("Medicago truncatula chromosome 2 clone mth2-48e18")
('2', 'mth2-48e18') |
def clear_relation(cls):
"""
Clear relation properties for reference Model, such as OneToOne, Reference,
ManyToMany
"""
for k, v in cls.properties.items():
if isinstance(v, ReferenceProperty):
if hasattr(v, 'collection_name') and hasattr(v.reference_cl... | Clear relation properties for reference Model, such as OneToOne, Reference,
ManyToMany |
def __getNumberOfFollowers(self, web):
"""Scrap the number of followers from a GitHub profile.
:param web: parsed web.
:type web: BeautifulSoup node.
"""
counters = web.find_all('span', {'class': 'Counter'})
try:
if 'k' not in counters[2].text:
... | Scrap the number of followers from a GitHub profile.
:param web: parsed web.
:type web: BeautifulSoup node. |
def to_dict(self):
"""Render a MessageElement as python dict
:return: Python dict representation
:rtype: dict
"""
obj_dict = super(Cell, self).to_dict()
child_dict = {
'type': self.__class__.__name__,
'header_flag': self.header_flag,
'... | Render a MessageElement as python dict
:return: Python dict representation
:rtype: dict |
def ensure_parent_directory(path, ensure_parent=True):
"""
Ensures the parent directory exists.
:param string path: the path of the file
:param bool ensure_parent: if ``True``, ensure the parent directory of ``path`` exists;
if ``False``, ensure ``path`` exists
:raise... | Ensures the parent directory exists.
:param string path: the path of the file
:param bool ensure_parent: if ``True``, ensure the parent directory of ``path`` exists;
if ``False``, ensure ``path`` exists
:raises: OSError: if the path cannot be created |
def delete(self, **kw):
"""
Delete a policy route from the engine. You can delete using a
single field or multiple fields for a more exact match.
Use a keyword argument to delete a route by any valid attribute.
:param kw: use valid Route keyword values to delete by exact... | Delete a policy route from the engine. You can delete using a
single field or multiple fields for a more exact match.
Use a keyword argument to delete a route by any valid attribute.
:param kw: use valid Route keyword values to delete by exact match |
def create_invoice_from_albaran(pk, list_lines):
MODEL_SOURCE = SalesAlbaran
MODEL_FINAL = SalesInvoice
url_reverse = 'CDNX_invoicing_invoicesaless_list'
# type_doc
msg_error_relation = _("Hay lineas asignadas a facturas")
msg_error_not_found = _('Sales albaran not found'... | context = {}
if list_lines:
new_list_lines = SalesLines.objects.filter(
pk__in=[int(x) for x in list_lines]
).exclude(
invoice__isnull=False
)
if new_list_lines:
new_pk = new_list_lines.first()
if ne... |
def traveling_salesman_qubo(G, lagrange=2, weight='weight'):
"""Return the QUBO with ground states corresponding to a minimum TSP route.
If :math:`|G|` is the number of nodes in the graph, the resulting qubo will have:
* :math:`|G|^2` variables/nodes
* :math:`2 |G|^2 (|G| - 1)` interactions/edges
... | Return the QUBO with ground states corresponding to a minimum TSP route.
If :math:`|G|` is the number of nodes in the graph, the resulting qubo will have:
* :math:`|G|^2` variables/nodes
* :math:`2 |G|^2 (|G| - 1)` interactions/edges
Parameters
----------
G : NetworkX graph
A complete... |
def match(self, props=None, rng=None, offset=None):
"""
Provide any of the args and match or dont.
:param props: Should be a subset of my props.
:param rng: Exactly match my range.
:param offset: I start after this offset.
:returns: True if all the provided predicates ma... | Provide any of the args and match or dont.
:param props: Should be a subset of my props.
:param rng: Exactly match my range.
:param offset: I start after this offset.
:returns: True if all the provided predicates match or are None |
def all_pages(method, request, accessor, cond=None):
"""Helper to process all pages using botocore service methods (exhausts NextToken).
note: `cond` is optional... you can use it to make filtering more explicit
if you like. Alternatively you can do the filtering in the `accessor` which
is perfectly fin... | Helper to process all pages using botocore service methods (exhausts NextToken).
note: `cond` is optional... you can use it to make filtering more explicit
if you like. Alternatively you can do the filtering in the `accessor` which
is perfectly fine, too
Note: lambda uses a slightly different mechanism ... |
def wait_until_title_contains(self, partial_title, timeout=None):
"""
Waits for title to contain <partial_title>
@type partial_title: str
@param partial_title: the partial title to locate
@type timeout: int
@param timeout: the maximum number of seco... | Waits for title to contain <partial_title>
@type partial_title: str
@param partial_title: the partial title to locate
@type timeout: int
@param timeout: the maximum number of seconds the driver will wait before timing out
@rtype: webdriverw... |
def TriToBin(self, x, y, z):
'''
Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the correspo... | Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the corresponding a-b coord
:rtype: a tuple consist ... |
def tags(self, value): # pylint: disable-msg=E0102
"""Set the tags in the configuraton (setter)"""
if not isinstance(value, list):
raise TypeError
self._config['tags'] = value | Set the tags in the configuraton (setter) |
def LaplaceCentreWeight(self):
"""Centre weighting matrix for TV Laplacian."""
sz = [1,] * self.S.ndim
for ax in self.axes:
sz[ax] = self.S.shape[ax]
lcw = 2*len(self.axes)*np.ones(sz, dtype=self.dtype)
for ax in self.axes:
lcw[(slice(None),)*ax + ([0, -1... | Centre weighting matrix for TV Laplacian. |
def rpc_get_namespace_cost( self, namespace_id, **con_info ):
"""
Return the cost of a given namespace, including fees.
Returns {'amount': ..., 'units': ...}
"""
if not check_namespace(namespace_id):
return {'error': 'Invalid namespace', 'http_status': 400}
d... | Return the cost of a given namespace, including fees.
Returns {'amount': ..., 'units': ...} |
def get_attached_cdroms(self, datacenter_id, server_id, depth=1):
"""
Retrieves a list of CDROMs attached to the server.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:... | Retrieves a list of CDROMs attached to the server.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
:param depth: The depth of the response da... |
def r_squared(model, fit_result, data):
"""
Calculates the coefficient of determination, R^2, for the fit.
(Is not defined properly for vector valued functions.)
:param model: Model instance
:param fit_result: FitResults instance
:param data: data with which the fit was performed.
"""
... | Calculates the coefficient of determination, R^2, for the fit.
(Is not defined properly for vector valued functions.)
:param model: Model instance
:param fit_result: FitResults instance
:param data: data with which the fit was performed. |
def get_fn(name):
"""Get the full path to one of the reference files shipped for utils.
In the source distribution, these files are in ``mbuild/utils/reference``,
but on installation, they're moved to somewhere in the user's python
site-packages directory.
Parameters
----------
name : str
... | Get the full path to one of the reference files shipped for utils.
In the source distribution, these files are in ``mbuild/utils/reference``,
but on installation, they're moved to somewhere in the user's python
site-packages directory.
Parameters
----------
name : str
Name of the file ... |
def back_tick(cmd, ret_err=False, as_str=True, raise_err=None):
""" Run command `cmd`, return stdout, or stdout, stderr if `ret_err`
Roughly equivalent to ``check_output`` in Python 2.7
Parameters
----------
cmd : sequence
command to execute
ret_err : bool, optional
If True, re... | Run command `cmd`, return stdout, or stdout, stderr if `ret_err`
Roughly equivalent to ``check_output`` in Python 2.7
Parameters
----------
cmd : sequence
command to execute
ret_err : bool, optional
If True, return stderr in addition to stdout. If False, just return
stdout... |
def quantileclip(arrays, masks=None, dtype=None, out=None,
zeros=None, scales=None, weights=None,
fclip=0.10):
"""Combine arrays using the sigma-clipping, with masks.
Inputs and masks are a list of array objects. All input arrays
have the same shape. If present, the masks ... | Combine arrays using the sigma-clipping, with masks.
Inputs and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
The function returns an array with one more dimension than the
inputs and with size (3, shape). out[0] contains t... |
def get_build_report(self, project, build_id, type=None):
"""GetBuildReport.
[Preview API] Gets a build report.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:param str type:
:rtype: :class:`<BuildReportMetadata> <azure.devops.v5... | GetBuildReport.
[Preview API] Gets a build report.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:param str type:
:rtype: :class:`<BuildReportMetadata> <azure.devops.v5_0.build.models.BuildReportMetadata>` |
def plot_ants_plane(off_screen=False, notebook=None):
"""
Demonstrate how to create a plot class to plot multiple meshes while
adding scalars and text.
Plot two ants and airplane
"""
# load and shrink airplane
airplane = vtki.PolyData(planefile)
airplane.points /= 10
# pts = airpla... | Demonstrate how to create a plot class to plot multiple meshes while
adding scalars and text.
Plot two ants and airplane |
def getSlicesForText(self, body, getFingerprint=None, startIndex=0, maxResults=10):
"""Get a list of slices of the text
Args:
body, str: The text to be evaluated (required)
getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional)
... | Get a list of slices of the text
Args:
body, str: The text to be evaluated (required)
getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional)
startIndex, int: The start-index for pagination (optional)
maxResults, int... |
def consume_gas(self, amount: int, reason: str) -> None:
"""
Consume ``amount`` of gas from the remaining gas.
Raise `eth.exceptions.OutOfGas` if there is not enough gas remaining.
"""
return self._gas_meter.consume_gas(amount, reason) | Consume ``amount`` of gas from the remaining gas.
Raise `eth.exceptions.OutOfGas` if there is not enough gas remaining. |
def get(self, *, kind: Type=None, tag: Hashable=None, **kwargs) -> Iterator:
"""
Get an iterator of GameObjects by kind or tag.
kind: Any type. Pass to get a subset of contained GameObjects with the
given type.
tag: Any Hashable object. Pass to get a subset of contained Ga... | Get an iterator of GameObjects by kind or tag.
kind: Any type. Pass to get a subset of contained GameObjects with the
given type.
tag: Any Hashable object. Pass to get a subset of contained GameObjects
with the given tag.
Pass both kind and tag to get objects that ar... |
def todict(self):
"""Returns a dictionary fully representing the state of this object
"""
return {'index': self.index,
'seed': hb_encode(self.seed),
'n': self.n,
'root': hb_encode(self.root),
'hmac': hb_encode(self.hmac),
... | Returns a dictionary fully representing the state of this object |
def create_nation_fixtures(self):
"""
Create national US and State Map
"""
SHP_SLUG = "cb_{}_us_state_500k".format(self.YEAR)
DOWNLOAD_PATH = os.path.join(self.DOWNLOAD_DIRECTORY, SHP_SLUG)
shape = shapefile.Reader(
os.path.join(DOWNLOAD_PATH, "{}.shp".format... | Create national US and State Map |
def adjustTitleFont(self):
"""
Adjusts the font used for the title based on the current with and \
display name.
"""
left, top, right, bottom = self.contentsMargins()
r = self.roundingRadius()
# include text padding
left += 5 + r / 2
top +... | Adjusts the font used for the title based on the current with and \
display name. |
def get_nlp_base(self):
''' getter '''
if isinstance(self.__nlp_base, NlpBase) is False:
raise TypeError("The type of self.__nlp_base must be NlpBase.")
return self.__nlp_base | getter |
def http_basic(r, username, password):
"""Attaches HTTP Basic Authentication to the given Request object.
Arguments should be considered non-positional.
"""
username = str(username)
password = str(password)
auth_s = b64encode('%s:%s' % (username, password))
r.headers['Authorization'] = ('B... | Attaches HTTP Basic Authentication to the given Request object.
Arguments should be considered non-positional. |
def _process_output(res, parse_json=True):
"""Process output."""
res_payload = res.payload.decode('utf-8')
output = res_payload.strip()
_LOGGER.debug('Status: %s, Received: %s', res.code, output)
if not output:
return None
if not res.code.is_successful():
if 128 <= res.code < ... | Process output. |
def message(request, socket, context, message):
"""
Event handler for a room receiving a message. First validates a
joining user's name and sends them the list of users.
"""
room = get_object_or_404(ChatRoom, id=message["room"])
if message["action"] == "start":
name = strip_tags(message[... | Event handler for a room receiving a message. First validates a
joining user's name and sends them the list of users. |
def reset(self):
"""
Reset the timeout. Starts a new timer.
"""
self.counter += 1
local_counter = self.counter
def timer_timeout():
if self.counter == local_counter and self.running:
self.callback()
self.loop.call_later(self.timeout, ... | Reset the timeout. Starts a new timer. |
def array(self, envelope=()):
"""Returns an NDArray, optionally subset by spatial envelope.
Keyword args:
envelope -- coordinate extent tuple or Envelope
"""
args = ()
if envelope:
args = self.get_offset(envelope)
return self.ds.ReadAsArray(*args) | Returns an NDArray, optionally subset by spatial envelope.
Keyword args:
envelope -- coordinate extent tuple or Envelope |
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Databas... | Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``... |
def mod(self):
"""Modulus of vector."""
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) | Modulus of vector. |
def set_energy_range(self, logemin, logemax):
"""Set the energy range of the analysis.
Parameters
----------
logemin: float
Lower end of energy range in log10(E/MeV).
logemax : float
Upper end of energy range in log10(E/MeV).
"""
if logem... | Set the energy range of the analysis.
Parameters
----------
logemin: float
Lower end of energy range in log10(E/MeV).
logemax : float
Upper end of energy range in log10(E/MeV). |
def extract_packing_plan(self, topology):
"""
Returns the representation of packing plan that will
be returned from Tracker.
"""
packingPlan = {
"id": "",
"container_plans": []
}
if not topology.packing_plan:
return packingPlan
container_plans = topology.packing_p... | Returns the representation of packing plan that will
be returned from Tracker. |
def sliced_wasserstein(PD1, PD2, M=50):
""" Implementation of Sliced Wasserstein distance as described in
Sliced Wasserstein Kernel for Persistence Diagrams by Mathieu Carriere, Marco Cuturi, Steve Oudot (https://arxiv.org/abs/1706.03358)
Parameters
-----------
PD1: np.ar... | Implementation of Sliced Wasserstein distance as described in
Sliced Wasserstein Kernel for Persistence Diagrams by Mathieu Carriere, Marco Cuturi, Steve Oudot (https://arxiv.org/abs/1706.03358)
Parameters
-----------
PD1: np.array size (m,2)
Persistence diagram
... |
def infer_data_type(data_container):
"""
For a given container of data, infer the type of data as one of
continuous, categorical, or ordinal.
For now, it is a one-to-one mapping as such:
- str: categorical
- int: ordinal
- float: continuous
There may be better ways that are not cu... | For a given container of data, infer the type of data as one of
continuous, categorical, or ordinal.
For now, it is a one-to-one mapping as such:
- str: categorical
- int: ordinal
- float: continuous
There may be better ways that are not currently implemented below. For
example, with ... |
def true_num_genes(model, custom_spont_id=None):
"""Return the number of genes in a model ignoring spontaneously labeled genes.
Args:
model (Model):
custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001``
Returns:
int: Numb... | Return the number of genes in a model ignoring spontaneously labeled genes.
Args:
model (Model):
custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001``
Returns:
int: Number of genes excluding spontaneous genes |
def poll(args):
"""Poll data from the sensor."""
backend = _get_backend(args)
poller = MiFloraPoller(args.mac, backend)
print("Getting data from Mi Flora")
print("FW: {}".format(poller.firmware_version()))
print("Name: {}".format(poller.name()))
print("Temperature: {}".format(poller.paramete... | Poll data from the sensor. |
def get_node_id(nuc_or_sat, namespace=None):
"""return the node ID of the given nucleus or satellite"""
node_type = get_node_type(nuc_or_sat)
if node_type == 'leaf':
leaf_id = nuc_or_sat[0].leaves()[0]
if namespace is not None:
return '{0}:{1}'.format(namespace, leaf_id)
... | return the node ID of the given nucleus or satellite |
def valid_path(path):
'''
Check if an entry in the class path exists as either a directory or a file
'''
# check if the suffic of classpath suffix exists as directory
if path.endswith('*'):
Log.debug('Checking classpath entry suffix as directory: %s', path[:-1])
if os.path.isdir(path[:-1]):
retu... | Check if an entry in the class path exists as either a directory or a file |
def build_remap_symbols(self, name_generator, children_only=None):
"""
The children_only flag is inapplicable, but this is included as
the Scope class is defined like so.
Here this simply just place the catch symbol with the next
replacement available.
"""
repla... | The children_only flag is inapplicable, but this is included as
the Scope class is defined like so.
Here this simply just place the catch symbol with the next
replacement available. |
def extract(self, m):
"""
extract info specified in option
"""
self._clear()
self.m = m
# self._preprocess()
if self.option != []:
self._url_filter()
self._email_filter()
if 'tex' in self.option:
self._tex_filte... | extract info specified in option |
def _R2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_R2deriv
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPU... | NAME:
_R2deriv
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the second radial derivative
HISTO... |
def read(self, size=None):
"""Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
re... | Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
... |
def params(self):
""" Read self params from configuration. """
parser = JinjaInterpolationNamespace()
parser.read(self.configuration)
return dict(parser['params'] or {}) | Read self params from configuration. |
def _detect_buffer_encoding(self, f):
"""Guess by checking BOM, and checking `_special_encode_check`, and using memory map."""
encoding = None
with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as m:
encoding = self._analyze_file(m)
return encoding | Guess by checking BOM, and checking `_special_encode_check`, and using memory map. |
def predict_is(self,h=5):
""" Makes dynamic in-sample predictions with the estimated model
Parameters
----------
h : int (default : 5)
How many steps would you like to forecast?
Returns
----------
- pd.DataFrame with predicted values
""" ... | Makes dynamic in-sample predictions with the estimated model
Parameters
----------
h : int (default : 5)
How many steps would you like to forecast?
Returns
----------
- pd.DataFrame with predicted values |
def on_batch_end(self, last_input, last_output, **kwargs):
"Steps through the generators then each of the critics."
self.G_A.zero_grad(); self.G_B.zero_grad()
fake_A, fake_B = last_output[0].detach(), last_output[1].detach()
real_A, real_B = last_input
self._set_trainable(D_A=Tru... | Steps through the generators then each of the critics. |
def index(self, index):
""" :type index: int """
if self._index != index:
self._dirty = True
self._index = index | :type index: int |
def removedirs_p(self):
""" Like :meth:`removedirs`, but does not raise an exception if the
directory is not empty or does not exist. """
with contextlib.suppress(FileExistsError, DirectoryNotEmpty):
with DirectoryNotEmpty.translate():
self.removedirs()
return... | Like :meth:`removedirs`, but does not raise an exception if the
directory is not empty or does not exist. |
def _create_hosting_devices_from_config(self):
"""To be called late during plugin initialization so that any hosting
device specified in the config file is properly inserted in the DB.
"""
hd_dict = config.get_specific_config('cisco_hosting_device')
attr_info = ciscohostingdevice... | To be called late during plugin initialization so that any hosting
device specified in the config file is properly inserted in the DB. |
def switch_to_next_app(self):
"""
switches to the next app
"""
log.debug("switching to next app...")
cmd, url = DEVICE_URLS["switch_to_next_app"]
self.result = self._exec(cmd, url) | switches to the next app |
def ls_mux(sel, lsls_di, ls_do):
""" Multiplexes a list of input signal structures to an output structure.
A structure is represented by a list of signals: [signal_1, signal_2, ..., signal_n]
ls_do[0] = lsls_di[sel][0]
ls_do[1] = lsls_di[sel][1]
...
ls_do[n] ... | Multiplexes a list of input signal structures to an output structure.
A structure is represented by a list of signals: [signal_1, signal_2, ..., signal_n]
ls_do[0] = lsls_di[sel][0]
ls_do[1] = lsls_di[sel][1]
...
ls_do[n] = lsls_di[sel][n]
sel - sele... |
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Render `data` into JSON, returning a bytestring.
"""
if data is None:
return bytes()
renderer_context = renderer_context or {}
indent = self.get_indent(accepted_media_type, renderer_... | Render `data` into JSON, returning a bytestring. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.