code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _validate_contains(self, expected_values, field, value):
""" {'empty': False } """
if not isinstance(value, Iterable):
return
if not isinstance(expected_values, Iterable) or isinstance(
expected_values, _str_type
):
expected_values = set((expected... | {'empty': False } |
def add_to_group(server_context, user_ids, group_id, container_path=None):
"""
Add user to group
:param server_context: A LabKey server context. See utils.create_server_context.
:param user_ids: users to add
:param group_id: to add to
:param container_path:
:return:
"""
return __make... | Add user to group
:param server_context: A LabKey server context. See utils.create_server_context.
:param user_ids: users to add
:param group_id: to add to
:param container_path:
:return: |
def unsubscribe_from_data(
self,
subscriber: Callable[[bytes], bool],
) -> None:
"""
Not thread-safe.
"""
self._data_subscribers.remove(subscriber) | Not thread-safe. |
def import_string(import_name, silent=False):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml... | Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If `silent` is True th... |
def create_new_file(help_string=NO_HELP, default=NO_DEFAULT, suffixes=None):
# type: (str, Union[str, NO_DEFAULT_TYPE], Union[List[str], None]) -> str
"""
Create a new file parameter
:param help_string:
:param default:
:param suffixes:
:return:
"""
... | Create a new file parameter
:param help_string:
:param default:
:param suffixes:
:return: |
def setup_auditlog_catalog(portal):
"""Setup auditlog catalog
"""
logger.info("*** Setup Audit Log Catalog ***")
catalog_id = auditlog_catalog.CATALOG_AUDITLOG
catalog = api.get_tool(catalog_id)
for name, meta_type in auditlog_catalog._indexes.iteritems():
indexes = catalog.indexes()
... | Setup auditlog catalog |
def query_saved_guest_screen_info(self, screen_id):
"""Returns the guest dimensions from the saved state.
in screen_id of type int
Saved guest screen to query info from.
out origin_x of type int
The X position of the guest monitor top left corner.
out origin_y ... | Returns the guest dimensions from the saved state.
in screen_id of type int
Saved guest screen to query info from.
out origin_x of type int
The X position of the guest monitor top left corner.
out origin_y of type int
The Y position of the guest monitor top... |
def validate_wavelengths(wavelengths):
"""Check wavelengths for ``synphot`` compatibility.
Wavelengths must satisfy these conditions:
* valid unit type, if given
* no zeroes
* monotonic ascending or descending
* no duplicate values
Parameters
----------
wavelengths... | Check wavelengths for ``synphot`` compatibility.
Wavelengths must satisfy these conditions:
* valid unit type, if given
* no zeroes
* monotonic ascending or descending
* no duplicate values
Parameters
----------
wavelengths : array-like or `~astropy.units.quantity.Quan... |
def friends(self, delegate, params={}, extra_args=None):
"""Get updates from friends.
Calls the delgate once for each status object received."""
return self.__get('/statuses/friends_timeline.xml', delegate, params,
txml.Statuses, extra_args=extra_args) | Get updates from friends.
Calls the delgate once for each status object received. |
def offset_data(data_section, offset, readable = False, wraparound = False):
"""
Offset the whole data section.
see offset_byte_in_data for more information
Returns: the entire data section + offset on each byte
"""
for pos in range(0, len(data_section)/2):
data_section = off... | Offset the whole data section.
see offset_byte_in_data for more information
Returns: the entire data section + offset on each byte |
def map(self, func):
"""
A lazy way to apply the given function to each element in the stream.
Useful for type casting, like:
>>> from audiolazy import count
>>> count().take(5)
[0, 1, 2, 3, 4]
>>> my_stream = count().map(float)
>>> my_stream.take(5) # A float counter
[0.0, 1.0, 2.0... | A lazy way to apply the given function to each element in the stream.
Useful for type casting, like:
>>> from audiolazy import count
>>> count().take(5)
[0, 1, 2, 3, 4]
>>> my_stream = count().map(float)
>>> my_stream.take(5) # A float counter
[0.0, 1.0, 2.0, 3.0, 4.0] |
def class_variables(self):
"""
Returns all documented class variables in the class, sorted
alphabetically as a list of `pydoc.Variable`.
"""
p = lambda o: isinstance(o, Variable) and self.module._docfilter(o)
return filter(p, self.doc.values()) | Returns all documented class variables in the class, sorted
alphabetically as a list of `pydoc.Variable`. |
def GetSources(self, event):
"""Determines the the short and long source for an event object.
Args:
event (EventObject): event.
Returns:
tuple(str, str): short and long source string.
Raises:
WrongFormatter: if the event object cannot be formatted by the formatter.
"""
if se... | Determines the the short and long source for an event object.
Args:
event (EventObject): event.
Returns:
tuple(str, str): short and long source string.
Raises:
WrongFormatter: if the event object cannot be formatted by the formatter. |
def usearch(query, db, type, out, threads = '6', evalue = '100', alignment = 'local', max_hits = 100, cluster = False):
"""
run usearch
"""
if 'usearch64' in os.environ:
usearch_loc = os.environ['usearch64']
else:
usearch_loc = 'usearch'
if os.path.exists(out) is False:
d... | run usearch |
def _reregister_types(self):
"""Registers existing types for a new connection"""
for _type in self._register_types:
psycopg2.extensions.register_type(psycopg2.extensions.new_type(*_type)) | Registers existing types for a new connection |
def unfreeze_extensions(self):
"""Remove a previously frozen list of extensions."""
output_path = os.path.join(_registry_folder(), 'frozen_extensions.json')
if not os.path.isfile(output_path):
raise ExternalError("There is no frozen extension list")
os.remove(output_path)
... | Remove a previously frozen list of extensions. |
async def run_asgi(self):
"""
Wrapper around the ASGI callable, handling exceptions and unexpected
termination states.
"""
try:
result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
except BaseException as exc:
self.closed_event.se... | Wrapper around the ASGI callable, handling exceptions and unexpected
termination states. |
def read_config(args):
""" Read configuration options from ~/.shakedown (if exists)
:param args: a dict of arguments
:type args: dict
:return: a dict of arguments
:rtype: dict
"""
configfile = os.path.expanduser('~/.shakedown')
if os.path.isfile(configfile):
w... | Read configuration options from ~/.shakedown (if exists)
:param args: a dict of arguments
:type args: dict
:return: a dict of arguments
:rtype: dict |
def _register_client(self, client, region_name):
"""Uses functools.partial to wrap all methods on a client with the self._wrap_client method
:param botocore.client.BaseClient client: the client to proxy
:param str region_name: AWS Region ID (ex: us-east-1)
"""
for item in client... | Uses functools.partial to wrap all methods on a client with the self._wrap_client method
:param botocore.client.BaseClient client: the client to proxy
:param str region_name: AWS Region ID (ex: us-east-1) |
def _create_dmnd_database(self, unaligned_sequences_path, daa_output):
'''
Build a diamond database using diamond makedb
Parameters
----------
unaligned_sequences_path: str
path to a FASTA file containing unaligned sequences
daa_output: str
Name o... | Build a diamond database using diamond makedb
Parameters
----------
unaligned_sequences_path: str
path to a FASTA file containing unaligned sequences
daa_output: str
Name of output database. |
def _ClientPathToString(client_path, prefix=""):
"""Returns a path-like String of client_path with optional prefix."""
return os.path.join(prefix, client_path.client_id, client_path.vfs_path) | Returns a path-like String of client_path with optional prefix. |
def get_composition_smart_repository_session(self, repository_id, proxy):
"""Gets a composition smart repository session for the given
repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.Comp... | Gets a composition smart repository session for the given
repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionSmartRepositorySession) - a
CompositionSmartRepositorySession
... |
def op_token(self, display_name, opt):
"""Return a properly annotated token for our use. This
token will be revoked at the end of the session. The token
will have some decent amounts of metadata tho."""
args = {
'lease': opt.lease,
'display_name': display_name,
... | Return a properly annotated token for our use. This
token will be revoked at the end of the session. The token
will have some decent amounts of metadata tho. |
def escape_dictionary(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'):
"""Escape dictionary values with keys as column names and values column values
@type dictionary: dict
@param dictionary: Key-values
"""
for k, v in dictionary.iteritems():
if isinstance(v, dateti... | Escape dictionary values with keys as column names and values column values
@type dictionary: dict
@param dictionary: Key-values |
def genargs() -> ArgumentParser:
"""
Create a command line parser
:return: parser
"""
parser = ArgumentParser()
parser.add_argument("infile", help="Input ShExC specification")
parser.add_argument("-nj", "--nojson", help="Do not produce json output", action="store_true")
parser.add_argume... | Create a command line parser
:return: parser |
def spam(self, msg, *args, **kw):
"""Log a message with level :data:`SPAM`. The arguments are interpreted as for :func:`logging.debug()`."""
if self.isEnabledFor(SPAM):
self._log(SPAM, msg, args, **kw) | Log a message with level :data:`SPAM`. The arguments are interpreted as for :func:`logging.debug()`. |
def request_start(self):
""" Indicate readiness to receive stream.
This is a blocking call.
"""
self._queue.put(command_packet(CMD_START_STREAM))
_LOGGER.info('Requesting stream')
self._source.run() | Indicate readiness to receive stream.
This is a blocking call. |
def text(self, x, y, txt=''):
"Output a string"
txt = self.normalize_text(txt)
if (self.unifontsubset):
txt2 = self._escape(UTF8ToUTF16BE(txt, False))
for uni in UTF8StringToArray(txt):
self.current_font['subset'].append(uni)
else:
txt2... | Output a string |
def parse_params(self, core_params):
"""
Goes through a set of parameters, extracting information about each.
:param core_params: The collection of parameters
:type core_params: A collection of ``<botocore.parameters.Parameter>``
subclasses
:returns: A list of dicti... | Goes through a set of parameters, extracting information about each.
:param core_params: The collection of parameters
:type core_params: A collection of ``<botocore.parameters.Parameter>``
subclasses
:returns: A list of dictionaries |
def serialize_to_file(
root_processor, # type: RootProcessor
value, # type: Any
xml_file_path, # type: Text
encoding='utf-8', # type: Text
indent=None # type: Optional[Text]
):
# type: (...) -> None
"""
Serialize the value to an XML file using the root processor.... | Serialize the value to an XML file using the root processor.
:param root_processor: Root processor of the XML document.
:param value: Value to serialize.
:param xml_file_path: Path to the XML file to which the serialized value will be written.
:param encoding: Encoding of the file.
:param indent: I... |
def step_a_new_working_directory(context):
"""
Creates a new, empty working directory
"""
command_util.ensure_context_attribute_exists(context, "workdir", None)
command_util.ensure_workdir_exists(context)
shutil.rmtree(context.workdir, ignore_errors=True) | Creates a new, empty working directory |
def add_var_arg(self, arg):
"""
Add a variable (or macro) argument to the condor job. The argument is
added to the submit file and a different value of the argument can be set
for each node in the DAG.
@param arg: name of option to add.
"""
self.__args.append(arg)
self.__job.add_var_arg(... | Add a variable (or macro) argument to the condor job. The argument is
added to the submit file and a different value of the argument can be set
for each node in the DAG.
@param arg: name of option to add. |
def Storage_clearDataForOrigin(self, origin, storageTypes):
"""
Function path: Storage.clearDataForOrigin
Domain: Storage
Method name: clearDataForOrigin
Parameters:
Required arguments:
'origin' (type: string) -> Security origin.
'storageTypes' (type: string) -> Comma separated origin name... | Function path: Storage.clearDataForOrigin
Domain: Storage
Method name: clearDataForOrigin
Parameters:
Required arguments:
'origin' (type: string) -> Security origin.
'storageTypes' (type: string) -> Comma separated origin names.
No return value.
Description: Clears storage for origin. |
def are_forms_valid(self, forms):
"""
Check if all forms defined in `form_classes` are valid.
"""
for form in six.itervalues(forms):
if not form.is_valid():
return False
return True | Check if all forms defined in `form_classes` are valid. |
def render_css_classes(self):
"""
Return a string containing the css classes for the module.
>>> mod = DashboardModule(enabled=False, draggable=True,
... collapsible=True, deletable=True)
>>> mod.render_css_classes()
'dashboard-module disabled dragg... | Return a string containing the css classes for the module.
>>> mod = DashboardModule(enabled=False, draggable=True,
... collapsible=True, deletable=True)
>>> mod.render_css_classes()
'dashboard-module disabled draggable collapsible deletable'
>>> mod.css_cl... |
def clearness_index_zenith_independent(clearness_index, airmass,
max_clearness_index=2.0):
"""
Calculate the zenith angle independent clearness index.
Parameters
----------
clearness_index : numeric
Ratio of global to extraterrestrial irradiance on a h... | Calculate the zenith angle independent clearness index.
Parameters
----------
clearness_index : numeric
Ratio of global to extraterrestrial irradiance on a horizontal
plane
airmass : numeric
Airmass
max_clearness_index : numeric, default 2.0
Maximum value of the cl... |
def remove(self, recursive=True, ignore_error=True):
"""
Remove the directory.
"""
try:
if recursive or self._cleanup == 'recursive':
shutil.rmtree(self.path)
else:
os.rmdir(self.path)
except Exception as e:
if n... | Remove the directory. |
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, ac... | Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24' |
def get_points_within_r(center_points, target_points, r):
r"""Get all target_points within a specified radius of a center point.
All data must be in same coordinate system, or you will get undetermined results.
Parameters
----------
center_points: (X, Y) ndarray
location from which to grab... | r"""Get all target_points within a specified radius of a center point.
All data must be in same coordinate system, or you will get undetermined results.
Parameters
----------
center_points: (X, Y) ndarray
location from which to grab surrounding points within r
target_points: (X, Y) ndarray... |
def request(self, *args, **kwargs) -> XMLResponse:
"""Makes an HTTP Request, with mocked User–Agent headers.
Returns a class:`HTTPResponse <HTTPResponse>`.
"""
# Convert Request object into HTTPRequest object.
r = super(XMLSession, self).request(*args, **kwargs)
return X... | Makes an HTTP Request, with mocked User–Agent headers.
Returns a class:`HTTPResponse <HTTPResponse>`. |
def _print_topics(self, header: str, cmds: List[str], verbose: bool) -> None:
"""Customized version of print_topics that can switch between verbose or traditional output"""
import io
if cmds:
if not verbose:
self.print_topics(header, cmds, 15, 80)
else:
... | Customized version of print_topics that can switch between verbose or traditional output |
def getList(self, aspList):
""" Returns a sorted list with all
primary directions.
"""
# Significators
objects = self._elements(self.SIG_OBJECTS, self.N, [0])
houses = self._elements(self.SIG_HOUSES, self.N, [0])
angles = self._elements(self.SIG_ANGLES, ... | Returns a sorted list with all
primary directions. |
def createPenStyleCti(nodeName, defaultData=0, includeNone=False):
""" Creates a ChoiceCti with Qt PenStyles.
If includeEmtpy is True, the first option will be None.
"""
displayValues=PEN_STYLE_DISPLAY_VALUES
configValues=PEN_STYLE_CONFIG_VALUES
if includeNone:
displayValues = [''] +... | Creates a ChoiceCti with Qt PenStyles.
If includeEmtpy is True, the first option will be None. |
def identity(obj):
"""
returns a string representing "<pk>,<version>" of the passed object
"""
if hasattr(obj, '_concurrencymeta'):
return mark_safe("{0},{1}".format(unlocalize(obj.pk),
get_revision_of_object(obj)))
else:
return mark_safe(unl... | returns a string representing "<pk>,<version>" of the passed object |
def getEyeToHeadTransform(self, eEye):
"""
Returns the transform from eye space to the head space. Eye space is the per-eye flavor of head
space that provides stereo disparity. Instead of Model * View * Projection the sequence is Model * View * Eye^-1 * Projection.
Normally View and Eye... | Returns the transform from eye space to the head space. Eye space is the per-eye flavor of head
space that provides stereo disparity. Instead of Model * View * Projection the sequence is Model * View * Eye^-1 * Projection.
Normally View and Eye^-1 will be multiplied together and treated as View in your... |
def placebo_session(function):
"""
Decorator to help do testing with placebo.
Simply wrap the function you want to test and make sure to add
a "session" argument so the decorator can pass the placebo session.
Accepts the following environment variables to configure placebo:
PLACEBO_MODE: set to ... | Decorator to help do testing with placebo.
Simply wrap the function you want to test and make sure to add
a "session" argument so the decorator can pass the placebo session.
Accepts the following environment variables to configure placebo:
PLACEBO_MODE: set to "record" to record AWS calls and save them
... |
def get_instance(self, payload):
"""
Build an instance of CredentialListInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance
:rtype: twilio.rest.api.v2010.account.sip.credential_list.Crede... | Build an instance of CredentialListInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance
:rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListInstance |
def _bss_decomp_mtifilt(reference_sources, estimated_source, j, C, Cj):
"""Decomposition of an estimated source image into four components
representing respectively the true source image, spatial (or filtering)
distortion, interference and artifacts, derived from the true source
images using multichanne... | Decomposition of an estimated source image into four components
representing respectively the true source image, spatial (or filtering)
distortion, interference and artifacts, derived from the true source
images using multichannel time-invariant filters. |
def tabulate_state_blocks(x, states, pos=None):
"""Construct a dataframe where each row provides information about continuous state blocks.
Parameters
----------
x : array_like, int
1-dimensional array of state values.
states : set
Set of states of interest. Any state value not in t... | Construct a dataframe where each row provides information about continuous state blocks.
Parameters
----------
x : array_like, int
1-dimensional array of state values.
states : set
Set of states of interest. Any state value not in this set will be ignored.
pos : array_like, int, opt... |
def rename(old_name, new_name):
'''Rename the given virtual folder. This operation is irreversible!
You cannot change the vfolders that are shared by other users,
and the new name must be unique among all your accessible vfolders
including the shared ones.
OLD_NAME: The current name of a virtual fo... | Rename the given virtual folder. This operation is irreversible!
You cannot change the vfolders that are shared by other users,
and the new name must be unique among all your accessible vfolders
including the shared ones.
OLD_NAME: The current name of a virtual folder.
NEW_NAME: The new name of a v... |
def select_ipam_strategy(self, network_id, network_strategy, **kwargs):
"""Return relevant IPAM strategy name.
:param network_id: neutron network id.
:param network_strategy: default strategy for the network.
NOTE(morgabra) This feels like a hack but I can't think of a better
i... | Return relevant IPAM strategy name.
:param network_id: neutron network id.
:param network_strategy: default strategy for the network.
NOTE(morgabra) This feels like a hack but I can't think of a better
idea. The root problem is we can now attach ports to networks with
a differe... |
def inet_pton(address_family, ip_string):
""" A platform independent version of inet_pton """
global __inet_pton
if __inet_pton is None:
if hasattr(socket, 'inet_pton'):
__inet_pton = socket.inet_pton
else:
from ospd import win_socket
__inet_pton = win_soc... | A platform independent version of inet_pton |
def prepare_framework_container_def(model, instance_type, s3_operations):
"""Prepare the framework model container information. Specify related S3 operations for Airflow to perform.
(Upload `source_dir`)
Args:
model (sagemaker.model.FrameworkModel): The framework model
instance_type (str): ... | Prepare the framework model container information. Specify related S3 operations for Airflow to perform.
(Upload `source_dir`)
Args:
model (sagemaker.model.FrameworkModel): The framework model
instance_type (str): The EC2 instance type to deploy this Model to. For example, 'ml.p2.xlarge'.
... |
def post_info(self, name, message):
"""Asynchronously post a user facing info message about a service.
Args:
name (string): The name of the service
message (string): The user facing info message that will be stored
for the service and can be queried later.
... | Asynchronously post a user facing info message about a service.
Args:
name (string): The name of the service
message (string): The user facing info message that will be stored
for the service and can be queried later. |
def new_driver(browser_name, *args, **kwargs):
"""Instantiates a new WebDriver instance, determining class by environment variables
"""
if browser_name == FIREFOX:
return webdriver.Firefox(*args, **kwargs)
# elif options['local'] and options['browser_name'] == CHROME:
... | Instantiates a new WebDriver instance, determining class by environment variables |
def get_message_content(self):
"""
Given the Slap XML, extract out the payload.
"""
body = self.doc.find(
".//{http://salmon-protocol.org/ns/magic-env}data").text
body = urlsafe_b64decode(body.encode("ascii"))
logger.debug("diaspora.protocol.get_message_cont... | Given the Slap XML, extract out the payload. |
def add_node(self, node):
"""Add a node to cluster.
:param node: should be formated like this
`{"addr": "", "role": "slave", "master": "master_node_id"}
"""
new = ClusterNode.from_uri(node["addr"])
cluster_member = self.nodes[0]
check_new_nodes([new], [cluster_me... | Add a node to cluster.
:param node: should be formated like this
`{"addr": "", "role": "slave", "master": "master_node_id"} |
def _cache_is_expired():
"""Indica si la caché está caducada"""
now = timezone.now()
timediff = TransCache.SINGLETON_CREATION_DATETIME - now
return (timediff.total_seconds() > TransCache.SINGLETON_EXPIRATION_MAX_SECONDS) | Indica si la caché está caducada |
def set_features(self, filter_type):
"""Calls splitter to split percolator output into target/decoy
elements.
Writes two new xml files with features. Currently only psms and
peptides. Proteins not here, since one cannot do protein inference
before having merged and remapped multi... | Calls splitter to split percolator output into target/decoy
elements.
Writes two new xml files with features. Currently only psms and
peptides. Proteins not here, since one cannot do protein inference
before having merged and remapped multifraction data anyway. |
def _unescape_str(value):
"""
Unescape a TS3 compatible string into a normal string
@param value: Value
@type value: string/int
"""
if isinstance(value, int):
return "%d" % value
value = value.replace(r"\\", "\\")
for i, j in ts3_escape.items(... | Unescape a TS3 compatible string into a normal string
@param value: Value
@type value: string/int |
def agent_version(self):
"""Get the version of the Juju machine agent.
May return None if the agent is not yet available.
"""
version = self.safe_data['agent-status']['version']
if version:
return client.Number.from_json(version)
else:
return None | Get the version of the Juju machine agent.
May return None if the agent is not yet available. |
def status(self, build_record_id, **kwargs):
"""
Latest push result of BuildRecord.
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.
>>> d... | Latest push result of BuildRecord.
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(response)
... |
def build_defaults(self):
"""Build a dictionary of default values from the `Scheme`.
Returns:
dict: The default configurations as set by the `Scheme`.
Raises:
errors.InvalidSchemeError: The `Scheme` does not contain
valid options.
"""
def... | Build a dictionary of default values from the `Scheme`.
Returns:
dict: The default configurations as set by the `Scheme`.
Raises:
errors.InvalidSchemeError: The `Scheme` does not contain
valid options. |
def guess_payload_class(self, payload):
"""
Handles NTPv4 extensions and MAC part (when authentication is used.)
"""
plen = len(payload)
if plen > _NTP_AUTH_MD5_TAIL_SIZE:
return NTPExtensions
elif plen == _NTP_AUTH_MD5_TAIL_SIZE:
return NTPAuthen... | Handles NTPv4 extensions and MAC part (when authentication is used.) |
async def close(self):
'''Close the listening socket. This does not close any ServerSession
objects created to handle incoming connections.
'''
if self.server:
self.server.close()
await self.server.wait_closed()
self.server = None | Close the listening socket. This does not close any ServerSession
objects created to handle incoming connections. |
def start(self, poll_period=None):
""" Start the NeedNameQeueu
Parameters:
----------
TODO: Move task receiving to a thread
"""
logger.info("Incoming ports bound")
if poll_period is None:
poll_period = self.poll_period
start = time.time()
... | Start the NeedNameQeueu
Parameters:
----------
TODO: Move task receiving to a thread |
def sensitivity(imgs, bg=None):
'''
Extract pixel sensitivity from a set of homogeneously illuminated images
This method is detailed in Section 5 of:
---
K.Bedrich, M.Bokalic et al.:
ELECTROLUMINESCENCE IMAGING OF PV DEVICES:
ADVANCED FLAT FIELD CALIBRATION,2017
---
'''
... | Extract pixel sensitivity from a set of homogeneously illuminated images
This method is detailed in Section 5 of:
---
K.Bedrich, M.Bokalic et al.:
ELECTROLUMINESCENCE IMAGING OF PV DEVICES:
ADVANCED FLAT FIELD CALIBRATION,2017
--- |
def block(self, mcs):
"""
Block a (previously computed) MCS. The MCS should be given as an
iterable of integers. Note that this method is not automatically
invoked from :func:`enumerate` because a user may want to block
some of the MCSes conditionally depending on... | Block a (previously computed) MCS. The MCS should be given as an
iterable of integers. Note that this method is not automatically
invoked from :func:`enumerate` because a user may want to block
some of the MCSes conditionally depending on the needs. For
example, one may w... |
def get_composition_repository_assignment_session(self, proxy):
"""Gets the session for assigning composition to repository
mappings.
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionRepositoryAssignmentSession)
- a CompositionRepositoryAssig... | Gets the session for assigning composition to repository
mappings.
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.CompositionRepositoryAssignmentSession)
- a CompositionRepositoryAssignmentSession
raise: OperationFailed - unable to complete request
... |
def listen(self, topic, timeout=1, limit=1):
""" Listen to a topic and return a list of message payloads received
within the specified time. Requires an async Subscribe to have been called previously.
`topic` topic to listen to
`timeout` duration to listen
`limit` the max ... | Listen to a topic and return a list of message payloads received
within the specified time. Requires an async Subscribe to have been called previously.
`topic` topic to listen to
`timeout` duration to listen
`limit` the max number of payloads that will be returned. Specify 0
... |
def profile(func):
"""
Decorator to profile functions with cProfile
Args:
func: python function
Returns:
profile report
References:
https://osf.io/upav8/
"""
def inner(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
res = func(*args, ... | Decorator to profile functions with cProfile
Args:
func: python function
Returns:
profile report
References:
https://osf.io/upav8/ |
def _at_dump_context(self, calculator, rule, scope, block):
"""
Implements @dump_context
"""
sys.stderr.write("%s\n" % repr(rule.namespace._variables)) | Implements @dump_context |
def is_child_of_objective_bank(self, id_, objective_bank_id):
"""Tests if an objective bank is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
return: (boolean) - ``true`` if the ``id``... | Tests if an objective bank is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
return: (boolean) - ``true`` if the ``id`` is a child of
``objective_bank_id,`` ``false`` otherwis... |
def _prfx_getattr_(obj, item):
"""Replacement of __getattr__"""
if item.startswith('f_') or item.startswith('v_'):
return getattr(obj, item[2:])
raise AttributeError('`%s` object has no attribute `%s`' % (obj.__class__.__name__, item)) | Replacement of __getattr__ |
def rename(idf, objkey, objname, newname):
"""rename all the refrences to this objname"""
refnames = getrefnames(idf, objkey)
for refname in refnames:
objlists = getallobjlists(idf, refname)
# [('OBJKEY', refname, fieldindexlist), ...]
for refname in refnames:
# TODO : there ... | rename all the refrences to this objname |
def _buildTime(self, source, quantity, modifier, units):
"""
Take C{quantity}, C{modifier} and C{unit} strings and convert them into values.
After converting, calcuate the time and return the adjusted sourceTime.
@type source: time
@param source: time to use as the ba... | Take C{quantity}, C{modifier} and C{unit} strings and convert them into values.
After converting, calcuate the time and return the adjusted sourceTime.
@type source: time
@param source: time to use as the base (or source)
@type quantity: string
@param quantity: quant... |
def activate():
"""Enter into an environment with support for tab-completion
This command drops you into a subshell, similar to the one
generated via `be in ...`, except no topic is present and
instead it enables tab-completion for supported shells.
See documentation for further information.
h... | Enter into an environment with support for tab-completion
This command drops you into a subshell, similar to the one
generated via `be in ...`, except no topic is present and
instead it enables tab-completion for supported shells.
See documentation for further information.
https://github.com/motto... |
def interface(iface):
'''
Return the details of `iface` or an error if it does not exist
'''
iface_info, error = _get_iface_info(iface)
if error is False:
return iface_info.get(iface, {}).get('inet', '')
else:
return error | Return the details of `iface` or an error if it does not exist |
def parseArguments(argv=None): # pragma: no cover
"""
I parse arguments in sys.argv and return the args object. The parser
itself is available as args.parser.
Adds the following members to args:
parser = the parser object
store_opt = the StoreOpt object
"""
store_opt = Stor... | I parse arguments in sys.argv and return the args object. The parser
itself is available as args.parser.
Adds the following members to args:
parser = the parser object
store_opt = the StoreOpt object |
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to... | Returns the model properties as a dict |
def process_transport_command(self, header, message):
"""Parse a command coming in through the transport command subscription"""
if not isinstance(message, dict):
return
relevant = False
if "host" in message: # Filter by host
if message["host"] != self.__hostid:... | Parse a command coming in through the transport command subscription |
def on_tool_finish(self, tool):
"""
Called when an individual tool completes execution.
:param tool: the name of the tool that completed
:type tool: str
"""
with self._lock:
if tool in self.current_tools:
self.current_tools.remove(tool)
... | Called when an individual tool completes execution.
:param tool: the name of the tool that completed
:type tool: str |
def _load_mapping(self, mapping):
"""Load data for a single step."""
mapping["oid_as_pk"] = bool(mapping.get("fields", {}).get("Id"))
job_id, local_ids_for_batch = self._create_job(mapping)
result = self._wait_for_job(job_id)
# We store inserted ids even if some batches failed
... | Load data for a single step. |
def append(self, name, data, start):
"""
Update timeout for all throttles
:param name: name of throttle to append to ("read" or "write")
:type name: :py:class:`str`
:param data: bytes of data for count
:type data: :py:class:`bytes`
:param start: start of read/w... | Update timeout for all throttles
:param name: name of throttle to append to ("read" or "write")
:type name: :py:class:`str`
:param data: bytes of data for count
:type data: :py:class:`bytes`
:param start: start of read/write time from
:py:meth:`asyncio.BaseEventLoo... |
def find_tf_idf(file_names=['./../test/testdata'],prev_file_path=None, dump_path=None):
'''Function to create a TF-IDF list of dictionaries for a corpus of docs.
If you opt for dumping the data, you can provide a file_path with .tfidfpkl extension(standard made for better understanding)
and also re-generate... | Function to create a TF-IDF list of dictionaries for a corpus of docs.
If you opt for dumping the data, you can provide a file_path with .tfidfpkl extension(standard made for better understanding)
and also re-generate a new tfidf list which overrides over an old one by mentioning its path.
@Args:
--
... |
def add_dependency(self, name, obj):
"""Add a code dependency so it gets inserted into globals"""
if name in self._deps:
if self._deps[name] is obj:
return
raise ValueError(
"There exists a different dep with the same name : %r" % name)
se... | Add a code dependency so it gets inserted into globals |
def get_auth_token_login_url(
self,
auth_token_ticket,
authenticator,
private_key,
service_url,
username,
):
'''
Build an auth token login URL.
See https://github.com/rbCAS/CASino/wiki/Auth-Token-Login for details.
'''
auth_tok... | Build an auth token login URL.
See https://github.com/rbCAS/CASino/wiki/Auth-Token-Login for details. |
def search(self, value, createIndex=None):
''' Full-text support, make sure that text index already exist on collection. Raise IndexNotFound if text index not exist.
**Examples**: ``query.search('pecel lele', createIndex=['FullName', 'Username'])``
'''
if createIndex:
... | Full-text support, make sure that text index already exist on collection. Raise IndexNotFound if text index not exist.
**Examples**: ``query.search('pecel lele', createIndex=['FullName', 'Username'])`` |
def get_graphs_by_ids(self, network_ids: Iterable[int]) -> List[BELGraph]:
"""Get a list of networks with the given identifiers and converts to BEL graphs."""
rv = [
self.get_graph_by_id(network_id)
for network_id in network_ids
]
log.debug('returning graphs for n... | Get a list of networks with the given identifiers and converts to BEL graphs. |
def _retry_deliveries(self):
"""
Handle [MQTT-4.4.0-1] by resending PUBLISH and PUBREL messages for pending out messages
:return:
"""
self.logger.debug("Begin messages delivery retries")
tasks = []
for message in itertools.chain(self.session.inflight_in.values(), ... | Handle [MQTT-4.4.0-1] by resending PUBLISH and PUBREL messages for pending out messages
:return: |
def choose(msg, items, attr): # pragma: no cover
""" Command line helper to display a list of choices, asking the
user to choose one of the options.
"""
# Return the first item if there is only one choice
if len(items) == 1:
return items[0]
# Print all choices to the command line
... | Command line helper to display a list of choices, asking the
user to choose one of the options. |
def sub_channel(self):
"""Get the SUB socket channel object."""
if self._sub_channel is None:
self._sub_channel = self.sub_channel_class(self.context,
self.session,
(self.ip, self.io... | Get the SUB socket channel object. |
def per(arga, argb, prec=10):
r"""
Calculate percentage difference between numbers.
If only two numbers are given, the percentage difference between them is
computed. If two sequences of numbers are given (either two lists of
numbers or Numpy vectors), the element-wise percentage difference is
... | r"""
Calculate percentage difference between numbers.
If only two numbers are given, the percentage difference between them is
computed. If two sequences of numbers are given (either two lists of
numbers or Numpy vectors), the element-wise percentage difference is
computed. If any of the numbers in... |
def generalized_lsp_value_withtau(times, mags, errs, omega):
'''Generalized LSP value for a single omega.
This uses tau to provide an arbitrary time-reference point.
The relations used are::
P(w) = (1/YY) * (YC*YC/CC + YS*YS/SS)
where: YC, YS, CC, and SS are all calculated at T
... | Generalized LSP value for a single omega.
This uses tau to provide an arbitrary time-reference point.
The relations used are::
P(w) = (1/YY) * (YC*YC/CC + YS*YS/SS)
where: YC, YS, CC, and SS are all calculated at T
and where: tan 2omegaT = 2*CS/(CC - SS)
and where:
... |
def load_configuration(conf_path):
"""Load and validate test configuration.
:param conf_path: path to YAML configuration file.
:return: configuration as dict.
"""
with open(conf_path) as f:
conf_dict = yaml.load(f)
validate_config(conf_dict)
return conf_dict | Load and validate test configuration.
:param conf_path: path to YAML configuration file.
:return: configuration as dict. |
def show_firmware_version_output_show_firmware_version_node_info_firmware_version_info_application_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
out... | Auto Generated Code |
def get(self, requirement):
"""Find packages matching ``requirement``.
:param requirement: Requirement to match against repository packages.
:type requirement: `str` or :class:`.Requirement`
:returns: :func:`list` of matching :class:`.Package` objects.
"""
if isinstance... | Find packages matching ``requirement``.
:param requirement: Requirement to match against repository packages.
:type requirement: `str` or :class:`.Requirement`
:returns: :func:`list` of matching :class:`.Package` objects. |
def format_op_row(ipFile, totLines, totWords, uniqueWords):
"""
Format the output row with stats
"""
txt = os.path.basename(ipFile).ljust(36) + ' '
txt += str(totLines).rjust(7) + ' '
txt += str(totWords).rjust(7) + ' '
txt += str(len(uniqueWords)).rjust(7) + ' '
return txt | Format the output row with stats |
def create(cls, cli, management_address,
local_username=None, local_password=None,
remote_username=None, remote_password=None,
connection_type=None):
"""
Configures a remote system for remote replication.
:param cls: this class.
:param cli: t... | Configures a remote system for remote replication.
:param cls: this class.
:param cli: the rest client.
:param management_address: the management IP address of the remote
system.
:param local_username: administrative username of local system.
:param local_password: a... |
def _initialize_likelihood_prior(self, positions, log_likelihoods, log_priors):
"""Initialize the likelihood and the prior using the given positions.
This is a general method for computing the log likelihoods and log priors for given positions.
Subclasses can use this to instantiate secondary ... | Initialize the likelihood and the prior using the given positions.
This is a general method for computing the log likelihoods and log priors for given positions.
Subclasses can use this to instantiate secondary chains as well. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.