code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def alias_config_alias_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
alias_config = ET.SubElement(config, "alias-config", xmlns="urn:brocade.com:mgmt:brocade-aaa")
alias = ET.SubElement(alias_config, "alias")
name = ET.SubElement(alias, "n... | Auto Generated Code |
def save_to_mat_file(self, parameter_space,
result_parsing_function,
filename, runs):
"""
Return the results relative to the desired parameter space in the form
of a .mat file.
Args:
parameter_space (dict): dictionary contain... | Return the results relative to the desired parameter space in the form
of a .mat file.
Args:
parameter_space (dict): dictionary containing
parameter/list-of-values pairs.
result_parsing_function (function): user-defined function, taking a
result d... |
def group_membership_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/group_memberships#create-membership"
api_path = "/api/v2/group_memberships.json"
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/group_memberships#create-membership |
def render_unregistered(error=None):
"""
Render template file for the unregistered user.
Args:
error (str, default None): Optional error message.
Returns:
str: Template filled with data.
"""
return template(
read_index_template(),
registered=False,
error... | Render template file for the unregistered user.
Args:
error (str, default None): Optional error message.
Returns:
str: Template filled with data. |
def generate_df(js_dict, naming, value="value"):
"""Decode JSON-stat dict into pandas.DataFrame object. Helper method \
that should be called inside from_json_stat().
Args:
js_dict(OrderedDict): OrderedDict with data in JSON-stat format, \
previously deserialized into a... | Decode JSON-stat dict into pandas.DataFrame object. Helper method \
that should be called inside from_json_stat().
Args:
js_dict(OrderedDict): OrderedDict with data in JSON-stat format, \
previously deserialized into a python object by \
json.loa... |
def _handle_github(self):
"""Handle exception and submit it as GitHub issue."""
value = click.prompt(
_BUG + click.style(
'1. Open an issue by typing "open";\n',
fg='green',
) + click.style(
'2. Print human-readable information by t... | Handle exception and submit it as GitHub issue. |
def strip_to_chains(self, chains, break_at_endmdl = True):
'''Throw away all ATOM/HETATM/ANISOU/TER lines for chains that are not in the chains list.'''
if chains:
chains = set(chains)
# Remove any structure lines not associated with the chains
self.lines = [l for l ... | Throw away all ATOM/HETATM/ANISOU/TER lines for chains that are not in the chains list. |
def update_module_item(self, id, course_id, module_id, module_item_completion_requirement_min_score=None, module_item_completion_requirement_type=None, module_item_external_url=None, module_item_indent=None, module_item_module_id=None, module_item_new_tab=None, module_item_position=None, module_item_published=None, mod... | Update a module item.
Update and return an existing module item |
def _set_boutons_interface(self, buttons):
"""Display buttons given by the list of tuples (id,function,description,is_active)"""
for id_action, f, d, is_active in buttons:
icon = self.get_icon(id_action)
action = self.addAction(QIcon(icon), d)
action.setEnabled(is_act... | Display buttons given by the list of tuples (id,function,description,is_active) |
def get_vlan_brief_output_vlan_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubEl... | Auto Generated Code |
def GenerateNetworkedConfigFile(load_hook, normal_class_load_hook, normal_class_dump_hook, **kwargs) -> NetworkedConfigObject:
"""
Generates a NetworkedConfigObject using the specified hooks.
"""
def NetworkedConfigObjectGenerator(url, safe_load: bool=True):
cfg = NetworkedConfigObject(url=url, ... | Generates a NetworkedConfigObject using the specified hooks. |
def get_motor_offsets(SERVO_OUTPUT_RAW, ofs, motor_ofs):
'''calculate magnetic field strength from raw magnetometer'''
import mavutil
self = mavutil.mavfile_global
m = SERVO_OUTPUT_RAW
motor_pwm = m.servo1_raw + m.servo2_raw + m.servo3_raw + m.servo4_raw
motor_pwm *= 0.25
rc3_min = self.par... | calculate magnetic field strength from raw magnetometer |
def _apply_rate(self, max_rate, aggressive=False):
"""
Try to adjust the rate (characters/second)
of the fragments of the list,
so that it does not exceed the given ``max_rate``.
This is done by testing whether some slack
can be borrowed from the fragment before
... | Try to adjust the rate (characters/second)
of the fragments of the list,
so that it does not exceed the given ``max_rate``.
This is done by testing whether some slack
can be borrowed from the fragment before
the faster current one.
If ``aggressive`` is ``True``,
... |
def grow(files: hug.types.multiple, in_ext: hug.types.text="short", out_ext: hug.types.text="html",
out_dir: hug.types.text="", recursive: hug.types.smart_boolean=False):
"""Grow up your markup"""
if files == ['-']:
print(text(sys.stdin.read()))
return
print(INTRO)
if recursive... | Grow up your markup |
def for_kind(kind_map, type_, fallback_key):
"""
Create an Options object from any mapping.
"""
if type_ not in kind_map:
if fallback_key not in kind_map:
raise ConfigException('"%s" is not in the config and has no fallback' % type_)
config = kind... | Create an Options object from any mapping. |
def display_col_dp(dp_list, attr_name):
"""
show a value assocciated with an attribute for each
DataProperty instance in the dp_list
"""
print()
print("---------- {:s} ----------".format(attr_name))
print([getattr(dp, attr_name) for dp in dp_list]) | show a value assocciated with an attribute for each
DataProperty instance in the dp_list |
async def send_rpc(self, msg, _context):
"""Send an RPC to a service on behalf of a client."""
service = msg.get('name')
rpc_id = msg.get('rpc_id')
payload = msg.get('payload')
timeout = msg.get('timeout')
response_id = await self.service_manager.send_rpc_command(servic... | Send an RPC to a service on behalf of a client. |
def get_beam(self, ra, dec):
"""
Get the psf as a :class:`AegeanTools.fits_image.Beam` object.
Parameters
----------
ra, dec : float
The sky position (degrees).
Returns
-------
beam : :class:`AegeanTools.fits_image.Beam`
The psf a... | Get the psf as a :class:`AegeanTools.fits_image.Beam` object.
Parameters
----------
ra, dec : float
The sky position (degrees).
Returns
-------
beam : :class:`AegeanTools.fits_image.Beam`
The psf at the given location. |
def create_run(cmd, project, exp, grp):
"""
Create a new 'run' in the database.
This creates a new transaction in the database and creates a new
run in this transaction. Afterwards we return both the transaction as
well as the run itself. The user is responsible for committing it when
the time ... | Create a new 'run' in the database.
This creates a new transaction in the database and creates a new
run in this transaction. Afterwards we return both the transaction as
well as the run itself. The user is responsible for committing it when
the time comes.
Args:
cmd: The command that has ... |
def update(self):
"""Update the command result attributed."""
# Only continue if monitor list is not empty
if len(self.__folder_list) == 0:
return self.__folder_list
# Iter upon the folder list
for i in range(len(self.get())):
# Update folder size
... | Update the command result attributed. |
def clean_series(series, *args, **kwargs):
"""Ensure all datetimes are valid Timestamp objects and dtype is np.datetime64[ns]
>>> from datetime import timedelta
>>> clean_series(pd.Series([datetime.datetime(1, 1, 1), 9, '1942', datetime.datetime(1970, 10, 23)]))
0 1677-09-22 00:12:44+00:00
1 ... | Ensure all datetimes are valid Timestamp objects and dtype is np.datetime64[ns]
>>> from datetime import timedelta
>>> clean_series(pd.Series([datetime.datetime(1, 1, 1), 9, '1942', datetime.datetime(1970, 10, 23)]))
0 1677-09-22 00:12:44+00:00
1 9
2 ... |
def threenum(h5file, var, post_col='mult'):
""" Calculates the three number summary for a variable.
The three number summary is the minimum, maximum and the mean
of the data. Traditionally one would summerise data with the
five number summary: max, min, 1st, 2nd (median), 3rd quartile.
But quantile... | Calculates the three number summary for a variable.
The three number summary is the minimum, maximum and the mean
of the data. Traditionally one would summerise data with the
five number summary: max, min, 1st, 2nd (median), 3rd quartile.
But quantiles are hard to calculate without sorting the data
... |
def build(cls, builder, *args, build_loop=None, **kwargs):
""" Build a hardware control API and initialize the adapter in one call
:param builder: the builder method to use (e.g.
:py:meth:`hardware_control.API.build_hardware_simulator`)
:param args: Args to forward to th... | Build a hardware control API and initialize the adapter in one call
:param builder: the builder method to use (e.g.
:py:meth:`hardware_control.API.build_hardware_simulator`)
:param args: Args to forward to the builder method
:param kwargs: Kwargs to forward to the builde... |
def rename(name, new_name):
'''
.. versionadded:: 2017.7.0
Renames a container. Returns ``True`` if successful, and raises an error if
the API returns one. If unsuccessful and the API returns no error (should
not happen), then ``False`` will be returned.
name
Name or ID of existing con... | .. versionadded:: 2017.7.0
Renames a container. Returns ``True`` if successful, and raises an error if
the API returns one. If unsuccessful and the API returns no error (should
not happen), then ``False`` will be returned.
name
Name or ID of existing container
new_name
New name to... |
def read_namespaced_replication_controller_status(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replication_controller_status # noqa: E501
read status of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | read_namespaced_replication_controller_status # noqa: E501
read status of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_replica... |
def key(self, direction, mechanism, purviews=False, _prefix=None):
"""Cache key. This is the call signature of |Subsystem.find_mice()|."""
return "subsys:{}:{}:{}:{}:{}".format(
self.subsystem_hash, _prefix, direction, mechanism, purviews) | Cache key. This is the call signature of |Subsystem.find_mice()|. |
def encode(self):
"""
Return binary string representation of object.
:rtype: str
"""
buf = bytearray()
for typ in sorted(self.format.keys()):
encoded = None
if typ != 0xFFFF: # end of block
(name, marshall) = self.format[ty... | Return binary string representation of object.
:rtype: str |
def blocking_start(self, waiting_func=None):
"""this function is just a wrapper around the start and
wait_for_completion methods. It starts the queuing thread and then
waits for it to complete. If run by the main thread, it will detect
the KeyboardInterrupt exception (which is what SIG... | this function is just a wrapper around the start and
wait_for_completion methods. It starts the queuing thread and then
waits for it to complete. If run by the main thread, it will detect
the KeyboardInterrupt exception (which is what SIGTERM and SIGHUP
have been translated to) and wil... |
def GetRunlevelsLSB(states):
"""Accepts a string and returns a list of strings of numeric LSB runlevels."""
if not states:
return set()
valid = set(["0", "1", "2", "3", "4", "5", "6"])
_LogInvalidRunLevels(states, valid)
return valid.intersection(set(states.split())) | Accepts a string and returns a list of strings of numeric LSB runlevels. |
def merge_from(self, other):
"""Merge information from another NumberFormat object into this one."""
if other.pattern is not None:
self.pattern = other.pattern
if other.format is not None:
self.format = other.format
self.leading_digits_pattern.extend(other.leading... | Merge information from another NumberFormat object into this one. |
def _init_security(self):
"""
Initialize a secure connection to the server.
"""
if not self._starttls():
raise SecurityError("Could not start TLS connection")
# _ssh_handshake() will throw an exception upon failure
self._ssl_handshake()
if not self._au... | Initialize a secure connection to the server. |
def get(self):
'''
An endpoint to determine salt-api capabilities
.. http:get:: /
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
c... | An endpoint to determine salt-api capabilities
.. http:get:: /
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i localhost:8000
.. c... |
def paint(self, painter, option, index):
"""
Reimplements the :meth:`QStyledItemDelegate.paint` method.
"""
if option.state & QStyle.State_MouseOver:
styleSheet = self.__style.hover
elif option.state & QStyle.State_Selected:
styleSheet = self.__style.high... | Reimplements the :meth:`QStyledItemDelegate.paint` method. |
def get_unique_sample_files(file_samples):
"""Filter file_sample data frame to only keep one file per sample.
Params
------
file_samples : `pandas.DataFrame`
A data frame containing a mapping between file IDs and sample barcodes.
This type of data frame is returned by :meth:`get_fil... | Filter file_sample data frame to only keep one file per sample.
Params
------
file_samples : `pandas.DataFrame`
A data frame containing a mapping between file IDs and sample barcodes.
This type of data frame is returned by :meth:`get_file_samples`.
Returns
-------
`... |
def write(self, s):
"""Write the unicode string ``s`` to the pseudoterminal.
Returns the number of bytes written.
"""
b = s.encode(self.encoding)
return super(PtyProcessUnicode, self).write(b) | Write the unicode string ``s`` to the pseudoterminal.
Returns the number of bytes written. |
def sphere_constrained_cubic(dr, a, alpha):
"""
Sphere generated by a cubic interpolant constrained to be (1,0) on
(r0-sqrt(3)/2, r0+sqrt(3)/2), the size of the cube in the (111) direction.
"""
sqrt3 = np.sqrt(3)
b_coeff = a*0.5/sqrt3*(1 - 0.6*sqrt3*alpha)/(0.15 + a*a)
rscl = np.clip(dr, -0... | Sphere generated by a cubic interpolant constrained to be (1,0) on
(r0-sqrt(3)/2, r0+sqrt(3)/2), the size of the cube in the (111) direction. |
def clone(self, folder, git_repository):
"""Ensures theme destination folder and clone git specified repo in it.
:param git_repository: git url of the theme folder
:param folder: path of the git managed theme folder
"""
os.makedirs(folder)
git.Git().clone(git_repository,... | Ensures theme destination folder and clone git specified repo in it.
:param git_repository: git url of the theme folder
:param folder: path of the git managed theme folder |
def proximal_convex_conj_kl_cross_entropy(space, lam=1, g=None):
r"""Proximal factory of the convex conj of cross entropy KL divergence.
Function returning the proximal factory of the convex conjugate of the
functional F, where F is the cross entropy Kullback-Leibler (KL)
divergence given by::
... | r"""Proximal factory of the convex conj of cross entropy KL divergence.
Function returning the proximal factory of the convex conjugate of the
functional F, where F is the cross entropy Kullback-Leibler (KL)
divergence given by::
F(x) = sum_i (x_i ln(pos(x_i)) - x_i ln(g_i) + g_i - x_i) + ind_P(x)... |
def put_content(self, content):
"""
Makes a ``PUT`` request with the content in the body.
:raise: An :exc:`requests.RequestException` if it is not 2xx.
"""
r = requests.request(self.method if self.method else 'PUT', self.url, data=content, **self.storage_args)
if self.r... | Makes a ``PUT`` request with the content in the body.
:raise: An :exc:`requests.RequestException` if it is not 2xx. |
def broker_metadata(self, broker_id):
"""Get BrokerMetadata
Arguments:
broker_id (int): node_id for a broker to check
Returns:
BrokerMetadata or None if not found
"""
return self._brokers.get(broker_id) or self._bootstrap_brokers.get(broker_id) | Get BrokerMetadata
Arguments:
broker_id (int): node_id for a broker to check
Returns:
BrokerMetadata or None if not found |
def show_qt(qt_class, modal=False, onshow_event=None, force_style=False):
"""
Shows and raise a pyqt window ensuring it's not duplicated
(if it's duplicated then raise the old one).
qt_class argument should be a class/subclass of QMainWindow, QDialog or any
top-level widget.
onshow_event provide... | Shows and raise a pyqt window ensuring it's not duplicated
(if it's duplicated then raise the old one).
qt_class argument should be a class/subclass of QMainWindow, QDialog or any
top-level widget.
onshow_event provides a way to pass a function to execute before the window
is showed on screen, it sh... |
def get_cond_latents_at_level(cond_latents, level, hparams):
"""Returns a single or list of conditional latents at level 'level'."""
if cond_latents:
if hparams.latent_dist_encoder in ["conv_net", "conv3d_net"]:
return [cond_latent[level] for cond_latent in cond_latents]
elif hparams.latent_dist_encod... | Returns a single or list of conditional latents at level 'level'. |
def timeit(unit='s'):
"""
测试函数耗时
:param unit: 时间单位,有 's','m','h' 可选(seconds,minutes,hours)
"""
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
start = time.time()
_result = func(*args, **kwargs)
_format(unit, time.time() - start, func.... | 测试函数耗时
:param unit: 时间单位,有 's','m','h' 可选(seconds,minutes,hours) |
def clear(self):
"""
Remove all entries from the cache and delete all data.
:return:
"""
for f in [x['content'] for x in self.metadata.values()]:
os.remove(f)
self.metadata = {}
self._flush() | Remove all entries from the cache and delete all data.
:return: |
def bind_column(model, name, column, force=False, recursive=False, copy=False) -> Column:
"""Bind a column to the model with the given name.
This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily
attach a new column to an existing model:
.. code-block:: pyt... | Bind a column to the model with the given name.
This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily
attach a new column to an existing model:
.. code-block:: python
import bloop.models
class User(BaseModel):
id = Column(String, ... |
def DeserializeExclusiveData(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
Raises:
Exception: If the transaction type is incorrect or if there are no claims.
"""
self.Type = TransactionType.ClaimTransaction
... | Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
Raises:
Exception: If the transaction type is incorrect or if there are no claims. |
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed ... | Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
... |
def inst(self, *instructions):
"""
Mutates the Program object by appending new instructions.
This function accepts a number of different valid forms, e.g.
>>> p = Program()
>>> p.inst(H(0)) # A single instruction
>>> p.inst(H(0), H(1)) # Multiple instruction... | Mutates the Program object by appending new instructions.
This function accepts a number of different valid forms, e.g.
>>> p = Program()
>>> p.inst(H(0)) # A single instruction
>>> p.inst(H(0), H(1)) # Multiple instructions
>>> p.inst([H(0), H(1)]) # A list of ... |
def reload(self):
"""
Automatically reloads the config file.
This is just an alias for self.load()."""
if not self.fd.closed: self.fd.close()
self.fd = open(self.fd.name, 'r')
self.load() | Automatically reloads the config file.
This is just an alias for self.load(). |
def cressman_point(sq_dist, values, radius):
r"""Generate a Cressman interpolation value for a point.
The calculated value is based on the given distances and search radius.
Parameters
----------
sq_dist: (N, ) ndarray
Squared distance between observations and grid point
values: (N, ) ... | r"""Generate a Cressman interpolation value for a point.
The calculated value is based on the given distances and search radius.
Parameters
----------
sq_dist: (N, ) ndarray
Squared distance between observations and grid point
values: (N, ) ndarray
Observation values in same order ... |
def set_dependent_orders(
self,
accountID,
tradeSpecifier,
**kwargs
):
"""
Create, replace and cancel a Trade's dependent Orders (Take Profit,
Stop Loss and Trailing Stop Loss) through the Trade itself
Args:
accountID:
Acco... | Create, replace and cancel a Trade's dependent Orders (Take Profit,
Stop Loss and Trailing Stop Loss) through the Trade itself
Args:
accountID:
Account Identifier
tradeSpecifier:
Specifier for the Trade
takeProfit:
The ... |
def _remove_unicode_encoding(xml_file):
'''
attempts to remove the "encoding='unicode'" from an xml file
as lxml does not support that on a windows node currently
see issue #38100
'''
with salt.utils.files.fopen(xml_file, 'rb') as f:
xml_content = f.read()
modified_xml = re.sub(r' en... | attempts to remove the "encoding='unicode'" from an xml file
as lxml does not support that on a windows node currently
see issue #38100 |
def _kl_half_normal_half_normal(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`.
Args:
a: Instance of a `HalfNormal` distribution object.
b: Instance of a `HalfNormal` distribution object.
name: (optional) Name to use for created operations.
default i... | Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`.
Args:
a: Instance of a `HalfNormal` distribution object.
b: Instance of a `HalfNormal` distribution object.
name: (optional) Name to use for created operations.
default is "kl_half_normal_half_normal".
Returns:
Batchwi... |
def _evaluate_rhs(cls, funcs, nodes, problem):
"""
Compute the value of the right-hand side of the system of ODEs.
Parameters
----------
basis_funcs : list(function)
nodes : numpy.ndarray
problem : TwoPointBVPLike
Returns
-------
evaluate... | Compute the value of the right-hand side of the system of ODEs.
Parameters
----------
basis_funcs : list(function)
nodes : numpy.ndarray
problem : TwoPointBVPLike
Returns
-------
evaluated_rhs : list(float) |
def transfer(self, user):
"""Transfers app to given username's account."""
r = self._h._http_resource(
method='PUT',
resource=('apps', self.name),
data={'app[transfer_owner]': user}
)
return r.ok | Transfers app to given username's account. |
def sensorupdate(self, data):
"""
Given a dict of sensors and values, updates those sensors with the
values in Scratch.
"""
if not isinstance(data, dict):
raise TypeError('Expected a dict')
msg = 'sensor-update '
for key in data.keys():
ms... | Given a dict of sensors and values, updates those sensors with the
values in Scratch. |
def SkipAhead(self, file_object, number_of_characters):
"""Skips ahead a number of characters.
Args:
file_object (dfvfs.FileIO): file-like object.
number_of_characters (int): number of characters.
"""
lines_size = len(self.lines)
while number_of_characters >= lines_size:
number_of... | Skips ahead a number of characters.
Args:
file_object (dfvfs.FileIO): file-like object.
number_of_characters (int): number of characters. |
def seek_in_frame(self, pos, *args, **kwargs):
"""
Seeks relative to the total offset of the current contextual frames.
"""
super().seek(self._total_offset + pos, *args, **kwargs) | Seeks relative to the total offset of the current contextual frames. |
def get_thumbnail(original, size, **options):
"""
Creates or gets an already created thumbnail for the given image with the given size and
options.
:param original: File-path, url or base64-encoded string of the image that you want an
thumbnail.
:param size: String with the wan... | Creates or gets an already created thumbnail for the given image with the given size and
options.
:param original: File-path, url or base64-encoded string of the image that you want an
thumbnail.
:param size: String with the wanted thumbnail size. On the form: ``200x200``, ``200`` or
... |
def new(self):
# type: () -> None
'''
A method to create a new UDF Implementation Use Volume Descriptor Implementation Use field.
Parameters:
None:
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalErr... | A method to create a new UDF Implementation Use Volume Descriptor Implementation Use field.
Parameters:
None:
Returns:
Nothing. |
def plotlyviz(
scomplex,
colorscale=None,
title="Kepler Mapper",
graph_layout="kk",
color_function=None,
color_function_name=None,
dashboard=False,
graph_data=False,
factor_size=3,
edge_linewidth=1.5,
node_linecolor="rgb(200,200,200)",
width=600,
height=5... | Visualizations and dashboards for kmapper graphs using Plotly. This method is suitable for use in Jupyter notebooks.
The generated FigureWidget can be updated (by performing a restyle or relayout). For example, let us add a title
to the colorbar (the name of the color function, if any),
... |
def redefined_by_decorator(node):
"""return True if the object is a method redefined via decorator.
For example:
@property
def x(self): return self._x
@x.setter
def x(self, value): self._x = value
"""
if node.decorators:
for decorator in node.decorators.nodes:
... | return True if the object is a method redefined via decorator.
For example:
@property
def x(self): return self._x
@x.setter
def x(self, value): self._x = value |
def nextLunarEclipse(date):
""" Returns the Datetime of the maximum phase of the
next global lunar eclipse.
"""
eclipse = swe.lunarEclipseGlobal(date.jd, backward=False)
return Datetime.fromJD(eclipse['maximum'], date.utcoffset) | Returns the Datetime of the maximum phase of the
next global lunar eclipse. |
def recurse_taxonomy_map(tax_id_map, tax_id, parent=False):
"""
Takes the output dict from make_taxonomy_map and an input tax_id
and recurses either up or down through the tree to get /all/ children
(or parents) of the given tax_id.
"""
if parent:
# TODO: allow filtering on tax_id and i... | Takes the output dict from make_taxonomy_map and an input tax_id
and recurses either up or down through the tree to get /all/ children
(or parents) of the given tax_id. |
def escape_latex(text):
r"""Escape characters of given text.
This function takes the given text and escapes characters
that have a special meaning in LaTeX: # $ % ^ & _ { } ~ \
"""
text = unicode(text.decode('utf-8'))
CHARS = {
'&': r'\&',
'%': r'\%',
'$': r'\$',
... | r"""Escape characters of given text.
This function takes the given text and escapes characters
that have a special meaning in LaTeX: # $ % ^ & _ { } ~ \ |
def import_sequence_flow_to_graph(diagram_graph, sequence_flows, process_id, flow_element):
"""
Adds a new edge to graph and a record to sequence_flows dictionary.
Input parameter is object of class xml.dom.Element.
Edges are identified by pair of sourceRef and targetRef attributes of BP... | Adds a new edge to graph and a record to sequence_flows dictionary.
Input parameter is object of class xml.dom.Element.
Edges are identified by pair of sourceRef and targetRef attributes of BPMNFlow element. We also
provide a dictionary, that maps sequenceFlow ID attribute with its sourceRef and... |
def collage(img_spec,
num_rows=2,
num_cols=6,
rescale_method='global',
cmap='gray',
annot=None,
padding=5,
bkground_thresh=None,
output_path=None,
figsize=None,
**kwargs):
"Produces a collage of v... | Produces a collage of various slices from different orientations in the given 3D image |
def register(self, item):
"""
Registers a new orb object to this schema. This could be a column, index, or collector -- including
a virtual object defined through the orb.virtual decorator.
:param item: <variant>
:return:
"""
if callable(item) and hasattr(item,... | Registers a new orb object to this schema. This could be a column, index, or collector -- including
a virtual object defined through the orb.virtual decorator.
:param item: <variant>
:return: |
def selected(self, sel):
"""Called when this item has been selected (sel=True) OR deselected (sel=False)"""
ParameterItem.selected(self, sel)
if self.widget is None:
return
if sel and self.param.writable():
self.showEditor()
elif self.hideWidget:
... | Called when this item has been selected (sel=True) OR deselected (sel=False) |
def sizeof_fmt(num, suffix='B'):
"""
Adapted from https://stackoverflow.com/a/1094933
Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection
"""
precision = {'': 0, 'Ki': 0, 'Mi': 0, 'Gi': 3, 'Ti': 6, 'Pi': 9, 'Ei': 12, 'Zi': 15}
for unit in ['', 'Ki', ... | Adapted from https://stackoverflow.com/a/1094933
Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection |
def update_nginx_from_config(nginx_config):
"""Write the given config to disk as a Dusty sub-config
in the Nginx includes directory. Then, either start nginx
or tell it to reload its config to pick up what we've
just written."""
logging.info('Updating nginx with new Dusty config')
temp_dir = tem... | Write the given config to disk as a Dusty sub-config
in the Nginx includes directory. Then, either start nginx
or tell it to reload its config to pick up what we've
just written. |
def compute_edge_widths(self):
"""Compute the edge widths."""
if type(self.edge_width) is str:
edges = self.graph.edges
self.edge_widths = [edges[n][self.edge_width] for n in self.edges]
else:
self.edge_widths = self.edge_width | Compute the edge widths. |
def convertShape(shapeString):
""" Convert xml shape string into float tuples.
This method converts the 2d or 3d shape string from SUMO's xml file
into a list containing 3d float-tuples. Non existant z coordinates default
to zero. If shapeString is empty, an empty list will be returned.
"""
cs... | Convert xml shape string into float tuples.
This method converts the 2d or 3d shape string from SUMO's xml file
into a list containing 3d float-tuples. Non existant z coordinates default
to zero. If shapeString is empty, an empty list will be returned. |
def _get_hourly_data(self, day_date, p_p_id):
"""Get Hourly Data."""
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_state": "normal",
"p_p_mode": "view",
"p_p_resource_id": "resourceObtenirDonneesConsommationHoraires",
... | Get Hourly Data. |
def _is_chunk_markdown(source):
"""Return whether a chunk contains Markdown contents."""
lines = source.splitlines()
if all(line.startswith('# ') for line in lines):
# The chunk is a Markdown *unless* it is commented Python code.
source = '\n'.join(line[2:] for line in lines
... | Return whether a chunk contains Markdown contents. |
def cmd_notice(self, connection, sender, target, payload):
"""
Sends a message
"""
msg_target, topic, content = self.parse_payload(payload)
def callback(sender, payload):
logging.info("NOTICE ACK from %s: %s", sender, payload)
self.__herald.notice(msg_target... | Sends a message |
def create_tasks(self, wfk_file, scr_input):
"""
Create the SCR tasks and register them in self.
Args:
wfk_file: Path to the ABINIT WFK file to use for the computation of the screening.
scr_input: Input for the screening calculation.
"""
assert len(self) ... | Create the SCR tasks and register them in self.
Args:
wfk_file: Path to the ABINIT WFK file to use for the computation of the screening.
scr_input: Input for the screening calculation. |
def frame_iv(algorithm, sequence_number):
"""Builds the deterministic IV for a body frame.
:param algorithm: Algorithm for which to build IV
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param int sequence_number: Frame sequence number
:returns: Generated IV
:rtype: bytes
:rais... | Builds the deterministic IV for a body frame.
:param algorithm: Algorithm for which to build IV
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param int sequence_number: Frame sequence number
:returns: Generated IV
:rtype: bytes
:raises ActionNotAllowedError: if sequence number of o... |
def _request_one_trial_job(self):
"""get one trial job, i.e., one hyperparameter configuration.
If this function is called, Command will be sent by BOHB:
a. If there is a parameter need to run, will return "NewTrialJob" with a dict:
{
'parameter_id': id of new hyperparamete... | get one trial job, i.e., one hyperparameter configuration.
If this function is called, Command will be sent by BOHB:
a. If there is a parameter need to run, will return "NewTrialJob" with a dict:
{
'parameter_id': id of new hyperparameter
'parameter_source': 'algorithm'... |
def atstart(callback, *args, **kwargs):
'''Schedule a callback to run before the main hook.
Callbacks are run in the order they were added.
This is useful for modules and classes to perform initialization
and inject behavior. In particular:
- Run common code before all of your hooks, such as ... | Schedule a callback to run before the main hook.
Callbacks are run in the order they were added.
This is useful for modules and classes to perform initialization
and inject behavior. In particular:
- Run common code before all of your hooks, such as logging
the hook name or interesting ... |
def delete_evpn_local(route_type, route_dist, **kwargs):
"""Deletes/withdraws EVPN route from VRF identified by *route_dist*.
"""
try:
tm = CORE_MANAGER.get_core_service().table_manager
tm.update_vrf_table(route_dist,
route_family=VRF_RF_L2_EVPN,
... | Deletes/withdraws EVPN route from VRF identified by *route_dist*. |
def fastqWrite(fileHandleOrFile, name, seq, qualValues, mode="w"):
"""Writes out fastq file. If qualValues is None or '*' then prints a '*' instead.
"""
fileHandle = _getFileHandle(fileHandleOrFile, mode)
assert seq.__class__ == "".__class__
for i in seq:
if not ((i >= 'A' and i <= 'Z') or (... | Writes out fastq file. If qualValues is None or '*' then prints a '*' instead. |
def filter_duplicate(self, url):
"""
url去重
"""
if self.filterDuplicate:
if url in self.historys:
raise Exception('duplicate excepiton: %s is duplicate' % url)
else:
self.historys.add(url)
else:
pass | url去重 |
def delete_Variable(self,name):
'''
pops a variable from class and delete it from parameter list
:parameter name: name of the parameter to delete
'''
self.message(1,'Deleting variable {0}'.format(name))
self.par_list=self.par_list[self.par_list != name]
... | pops a variable from class and delete it from parameter list
:parameter name: name of the parameter to delete |
def tempfilename(**kwargs):
"""
Reserve a temporary file for future use.
This is useful if you want to get a temporary file name, write to it in the
future and ensure that if an exception is thrown the temporary file is removed.
"""
kwargs.update(delete=False)
try:
f = NamedTemporar... | Reserve a temporary file for future use.
This is useful if you want to get a temporary file name, write to it in the
future and ensure that if an exception is thrown the temporary file is removed. |
def delete_network(context, id):
"""Delete a network.
: param context: neutron api request context
: param id: UUID representing the network to delete.
"""
LOG.info("delete_network %s for tenant %s" % (id, context.tenant_id))
with context.session.begin():
net = db_api.network_find(conte... | Delete a network.
: param context: neutron api request context
: param id: UUID representing the network to delete. |
def draw(self):
"""
N.draw()
Sets all N's stochastics to random values drawn from
the normal approximation to the posterior.
"""
devs = normal(size=self._sig.shape[1])
p = inner(self._sig, devs) + self._mu
self._set_stochastics(p) | N.draw()
Sets all N's stochastics to random values drawn from
the normal approximation to the posterior. |
def get_my_feed(self, limit=150, offset=20, sort="updated", nid=None):
"""Get my feed
:type limit: int
:param limit: Number of posts from feed to get, starting from ``offset``
:type offset: int
:param offset: Offset starting from bottom of feed
:type sort: str
:p... | Get my feed
:type limit: int
:param limit: Number of posts from feed to get, starting from ``offset``
:type offset: int
:param offset: Offset starting from bottom of feed
:type sort: str
:param sort: How to sort feed that will be retrieved; only current
known... |
def load_mayaplugins():
"""Loads the maya plugins (not jukebox plugins) of the pipeline
:returns: None
:rtype: None
:raises: None
"""
mpp = os.environ.get('MAYA_PLUG_IN_PATH')
if mpp is not None:
';'.join([mpp, MAYA_PLUGIN_PATH])
else:
mpp = MAYA_PLUGIN_PATH
# to si... | Loads the maya plugins (not jukebox plugins) of the pipeline
:returns: None
:rtype: None
:raises: None |
def insert_inexistence(self, table, kwargs, condition):
""".. :py:method::
Usage::
>>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}, {'id': '12de3wrv'})
insert into hospital (id, province) select '12de3wrv', 'shanghai' where not exists (select 1 from hospital w... | .. :py:method::
Usage::
>>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}, {'id': '12de3wrv'})
insert into hospital (id, province) select '12de3wrv', 'shanghai' where not exists (select 1 from hospital where id='12de3wrv' limit 1); |
def search(self, search_phrase, limit=None):
"""Search for datasets, and expand to database records"""
from ambry.identity import ObjectNumber
from ambry.orm.exc import NotFoundError
from ambry.library.search_backends.base import SearchTermParser
results = []
stp = Sear... | Search for datasets, and expand to database records |
def dump_registers_peek(registers, data, separator = ' ', width = 16):
"""
Dump data pointed to by the given registers, if any.
@type registers: dict( str S{->} int )
@param registers: Dictionary mapping register names to their values.
This value is returned by L{Thread.get... | Dump data pointed to by the given registers, if any.
@type registers: dict( str S{->} int )
@param registers: Dictionary mapping register names to their values.
This value is returned by L{Thread.get_context}.
@type data: dict( str S{->} str )
@param data: Dictionary mapp... |
def _clean_tx(response_dict):
''' Pythonize a blockcypher API response '''
confirmed_txrefs = []
for confirmed_txref in response_dict.get('txrefs', []):
confirmed_txref['confirmed'] = parser.parse(confirmed_txref['confirmed'])
confirmed_txrefs.append(confirmed_txref)
response_dict['txref... | Pythonize a blockcypher API response |
def setup(self, database):
"""Setup connection to database."""
self.db = database
self.hgnc_collection = database.hgnc_gene
self.user_collection = database.user
self.whitelist_collection = database.whitelist
self.institute_collection = database.institute
self.even... | Setup connection to database. |
def pack(o, stream, **kwargs):
'''
.. versionadded:: 2018.3.4
Wraps msgpack.pack and ensures that the passed object is unwrapped if it is
a proxy.
By default, this function uses the msgpack module and falls back to
msgpack_pure, if the msgpack is not available. You can pass an alternate
ms... | .. versionadded:: 2018.3.4
Wraps msgpack.pack and ensures that the passed object is unwrapped if it is
a proxy.
By default, this function uses the msgpack module and falls back to
msgpack_pure, if the msgpack is not available. You can pass an alternate
msgpack module using the _msgpack_module argu... |
def delete_instance(self, instance_id):
'''
method for removing an instance from AWS EC2
:param instance_id: string of instance id on AWS
:return: string reporting state of instance
'''
title = '%s.delete_instance' % self.__class__.__name__
# validate inputs
... | method for removing an instance from AWS EC2
:param instance_id: string of instance id on AWS
:return: string reporting state of instance |
def train(self, recall=0.95, index_predicates=True): # pragma: no cover
"""
Keyword arguments:
maximum_comparisons -- The maximum number of comparisons a
blocking rule is allowed to make.
Defaults to 1000000
recall -- The ... | Keyword arguments:
maximum_comparisons -- The maximum number of comparisons a
blocking rule is allowed to make.
Defaults to 1000000
recall -- The proportion of true dupe pairs in our training
data that that we the learned... |
def get_supported_filepaths(filepaths, supported_extensions, max_depth=float('inf')):
"""Get filepaths with supported extensions from given filepaths.
Parameters:
filepaths (list or str): Filepath(s) to check.
supported_extensions (tuple or str): Supported file extensions or a single file extension.
max_dept... | Get filepaths with supported extensions from given filepaths.
Parameters:
filepaths (list or str): Filepath(s) to check.
supported_extensions (tuple or str): Supported file extensions or a single file extension.
max_depth (int): The depth in the directory tree to walk.
A depth of '0' limits the walk to the... |
def PC_PI_calc(P, TOP, POP):
"""
Calculate percent chance agreement for Scott's Pi.
:param P: condition positive
:type P : dict
:param TOP: test outcome positive
:type TOP : dict
:param POP: population
:type POP:dict
:return: percent chance agreement as float
"""
try:
... | Calculate percent chance agreement for Scott's Pi.
:param P: condition positive
:type P : dict
:param TOP: test outcome positive
:type TOP : dict
:param POP: population
:type POP:dict
:return: percent chance agreement as float |
def pylint_amnesty(pylint_output):
"""
Add ``# pylint: disable`` clauses to add exceptions to all existing pylint errors in a codebase.
"""
errors = defaultdict(lambda: defaultdict(set))
for pylint_error in parse_pylint_output(pylint_output):
errors[pylint_error.filename][pylint_error.linenu... | Add ``# pylint: disable`` clauses to add exceptions to all existing pylint errors in a codebase. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.