code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def find_valid_combinations(self, tiles_34, first_index, second_index, hand_not_completed=False):
"""
Find and return all valid set combinations in given suit
:param tiles_34:
:param first_index:
:param second_index:
:param hand_not_completed: in that mode we can return j... | Find and return all valid set combinations in given suit
:param tiles_34:
:param first_index:
:param second_index:
:param hand_not_completed: in that mode we can return just possible shi\pon sets
:return: list of valid combinations |
def get_data_for_model(self, args, kwargs):
"""
In comes args and kwargs expected for the model. Out comes the data from
this invocation that will go to the model.
In other words, this function does the "data negotiation" between the
controller and the model.
"""
... | In comes args and kwargs expected for the model. Out comes the data from
this invocation that will go to the model.
In other words, this function does the "data negotiation" between the
controller and the model. |
def convert_docx_to_text(
filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename: filename to process
blob: binary ``bytes`` object to p... | Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename: filename to process
blob: binary ``bytes`` object to process
config: :class:`TextProcessingConfig` control object
Returns:
text contents
Notes:
- Old ``docx`` (https://pypi.py... |
def _parse_block(self, parser, allow_pluralize):
"""Parse until the next block tag with a given name."""
referenced = []
buf = []
while 1:
if parser.stream.current.type == 'data':
buf.append(parser.stream.current.value.replace('%', '%%'))
next(... | Parse until the next block tag with a given name. |
def _load_paths(self, paths, depth=0):
'''
Goes recursevly through the given list of paths
in order to find and pass all preset files to ```_load_preset()```
'''
if depth > self.MAX_DEPTH:
return
for path in paths:
try:
# avoid em... | Goes recursevly through the given list of paths
in order to find and pass all preset files to ```_load_preset()``` |
def within_ipv4_range(self, field, values):
"""
Add an IP range network filter for relevant address fields.
Range (between) filters allow only one range be provided.
:param str field: name of field to filter on. Taken from 'Show Filter
Expression' within SMC.
... | Add an IP range network filter for relevant address fields.
Range (between) filters allow only one range be provided.
:param str field: name of field to filter on. Taken from 'Show Filter
Expression' within SMC.
:param list values: IP range values. Values would be a list of ... |
def search(self, word, d, allow_spaces=True, return_cost=True):
"""
Finds all dictionary words in d-window from word
"""
if not all((c in self.alphabet
or (c == " " and self.allow_spaces)) for c in word):
return []
# raise ValueError("{0} conta... | Finds all dictionary words in d-window from word |
def make_response(self, content, code=200, headers=None):
"""Wrapper around Flask.make_response which also adds any local headers."""
if headers:
for header in headers:
self.headers[header] = headers[header]
return make_response(content, code, self.headers) | Wrapper around Flask.make_response which also adds any local headers. |
def replace(key,
value,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Replace a key on the memcached server. This only succeeds if the key
already exists. This is the opposite of :mod:`memc... | Replace a key on the memcached server. This only succeeds if the key
already exists. This is the opposite of :mod:`memcached.add
<salt.modules.memcached.add>`
CLI Example:
.. code-block:: bash
salt '*' memcached.replace <key> <value> |
def addModlist(entry: dict, ignore_attr_types: Optional[List[str]] = None) -> Dict[str, List[bytes]]:
"""Build modify list for call of method LDAPObject.add()"""
ignore_attr_types = _list_dict(map(str.lower, (ignore_attr_types or [])))
modlist: Dict[str, List[bytes]] = {}
for attrtype in entry.keys():
... | Build modify list for call of method LDAPObject.add() |
def create_dataset(self, dataset_id, friendly_name=None, description=None,
access=None, location=None, project_id=None):
"""Create a new BigQuery dataset.
Parameters
----------
dataset_id : str
Unique ``str`` identifying the dataset with the project (t... | Create a new BigQuery dataset.
Parameters
----------
dataset_id : str
Unique ``str`` identifying the dataset with the project (the
referenceID of the dataset, not the integer id of the dataset)
friendly_name: str, optional
A human readable nam... |
def show_items(self, cursor, items):
""" Shows the completion widget with 'items' at the position specified
by 'cursor'.
"""
if not items :
return
self.cancel_completion()
strng = text.columnize(items)
self._console_widget._fill_temporary_buffer(cu... | Shows the completion widget with 'items' at the position specified
by 'cursor'. |
def follower_num(self):
"""获取关注此收藏夹的人数.
:return: 关注此收藏夹的人数
:rtype: int
"""
href = re_collection_url_split.match(self.url).group(1)
return int(self.soup.find('a', href=href + 'followers').text) | 获取关注此收藏夹的人数.
:return: 关注此收藏夹的人数
:rtype: int |
def splits(cls, fields, root=".data", train="train.txt",
test="test.txt", validation_frac=0.1, **kwargs):
"""Downloads and loads the CoNLL 2000 Chunking dataset.
NOTE: There is only a train and test dataset so we use
10% of the train set as validation
"""
tr... | Downloads and loads the CoNLL 2000 Chunking dataset.
NOTE: There is only a train and test dataset so we use
10% of the train set as validation |
def createDataFromFile(self, filePath, inputEncoding = None, defaultFps = None):
"""Fetch a given filePath and parse its contents.
May raise the following exceptions:
* RuntimeError - generic exception telling that parsing was unsuccessfull
* IOError - failed to open a file at given fil... | Fetch a given filePath and parse its contents.
May raise the following exceptions:
* RuntimeError - generic exception telling that parsing was unsuccessfull
* IOError - failed to open a file at given filePath
@return SubtitleData filled with non-empty, default datafields. Client should... |
def Flash(self, partition, timeout_ms=0, info_cb=DEFAULT_MESSAGE_CALLBACK):
"""Flashes the last downloaded file to the given partition.
Args:
partition: Partition to overwrite with the new image.
timeout_ms: Optional timeout in milliseconds to wait for it to finish.
info_c... | Flashes the last downloaded file to the given partition.
Args:
partition: Partition to overwrite with the new image.
timeout_ms: Optional timeout in milliseconds to wait for it to finish.
info_cb: See Download. Usually no messages.
Returns:
Response to a downloa... |
def remove(self, i):
'''remove a rally point'''
if i < 1 or i > self.rally_count():
print("Invalid rally point number %u" % i)
self.rally_points.pop(i-1)
self.reindex() | remove a rally point |
def create_dict_subelement(root, subelement, content, **kwargs):
"""Create a XML subelement from a Python dictionary."""
attribs = kwargs.get('attribs', None)
namespace = kwargs.get('namespace', None)
key = subelement
# Add subelement's namespace and attributes.
if namespace and attribs:
... | Create a XML subelement from a Python dictionary. |
def _grab_crl(user_agent, url, timeout):
"""
Fetches a CRL and parses it
:param user_agent:
A unicode string of the user agent to use when fetching the URL
:param url:
A unicode string of the URL to fetch the CRL from
:param timeout:
The number of seconds after which an HT... | Fetches a CRL and parses it
:param user_agent:
A unicode string of the user agent to use when fetching the URL
:param url:
A unicode string of the URL to fetch the CRL from
:param timeout:
The number of seconds after which an HTTP request should timeout
:return:
An as... |
def iter(self):
"""
Iterate over the sequences in self.file_, yielding each as an
instance of the desired read class.
@raise ValueError: If the input file has an odd number of records or
if any sequence has a different length than its predicted
secondary structur... | Iterate over the sequences in self.file_, yielding each as an
instance of the desired read class.
@raise ValueError: If the input file has an odd number of records or
if any sequence has a different length than its predicted
secondary structure. |
def _idle_register_view(self, view):
"""Internal method that calls register_view"""
assert(self.view is None)
self.view = view
if self.handlers == "class":
for name in dir(self):
when, _, what = partition(name, '_')
widget, _, signal = partiti... | Internal method that calls register_view |
def deleted(self, base: pathlib.PurePath = pathlib.PurePath(),
include_children: bool = True,
include_directories: bool = True) -> Iterator[str]:
"""
Find the paths of entities deleted between the left and right entities
in this comparison.
:param base: T... | Find the paths of entities deleted between the left and right entities
in this comparison.
:param base: The base directory to recursively append to entities.
:param include_children: Whether to recursively include children of
deleted directories. These are thems... |
def command_canonize(string, vargs):
"""
Print the canonical representation of the given string.
It will replace non-canonical compound characters
with their canonical synonym.
:param str string: the string to act upon
:param dict vargs: the command line arguments
"""
try:
ipa... | Print the canonical representation of the given string.
It will replace non-canonical compound characters
with their canonical synonym.
:param str string: the string to act upon
:param dict vargs: the command line arguments |
def get_organisation_information(self, query_params=None):
'''
Get information fot this organisation. Returns a dictionary of values.
'''
return self.fetch_json(
uri_path=self.base_uri,
query_params=query_params or {}
) | Get information fot this organisation. Returns a dictionary of values. |
def delay(self, methodname, *args, **kwargs):
"""调用但不要求返回结果,而是通过系统方法getresult来获取.
Parameters:
methodname (str): - 要调用的方法名
args (Any): - 要调用的方法的位置参数
kwargs (Any): - 要调用的方法的关键字参数
"""
ID = str(uuid.uuid4())
self.send_query(ID, methodname, False,... | 调用但不要求返回结果,而是通过系统方法getresult来获取.
Parameters:
methodname (str): - 要调用的方法名
args (Any): - 要调用的方法的位置参数
kwargs (Any): - 要调用的方法的关键字参数 |
def export_as_tfhub_module(model_name,
hparams,
decode_hparams,
problem,
checkpoint_path,
export_dir):
"""Exports the last checkpoint from the directory as tfhub module.
It creates... | Exports the last checkpoint from the directory as tfhub module.
It creates the Module spec and signature (based on T2T problem information),
which is later used to create and export the hub module.
Module will be saved inside the ckpt_dir.
Args:
model_name: name of the model to be exported.
hparams: T... |
def updateResultsForJob(self, forceUpdate=True):
""" Chooses the best model for a given job.
Parameters
-----------------------------------------------------------------------
forceUpdate: (True/False). If True, the update will ignore all the
restrictions on the minimum time to updat... | Chooses the best model for a given job.
Parameters
-----------------------------------------------------------------------
forceUpdate: (True/False). If True, the update will ignore all the
restrictions on the minimum time to update and the minimum
number of records to ... |
def name(self):
"""Instance name."""
return ffi.string(lib.EnvGetInstanceName(self._env, self._ist)).decode() | Instance name. |
def search_patients(self, search_criteria,
include_picture='N', organization_id=None):
"""
invokes TouchWorksMagicConstants.ACTION_SEARCH_PATIENTS action
:return: JSON response
"""
include_picture = include_picture or ''
organization_id = organizat... | invokes TouchWorksMagicConstants.ACTION_SEARCH_PATIENTS action
:return: JSON response |
def prepare(self, node):
""" Format type dependencies information to use if for reordering. """
super(Reorder, self).prepare(node)
candidates = self.type_dependencies.successors(
TypeDependencies.NoDeps)
# We first select function which may have a result without calling any
... | Format type dependencies information to use if for reordering. |
def set_game_score(self, user_id, score, force=False, disable_edit_message=False, chat_id=None, message_id=None, inline_message_id=None):
"""
Use this method to set the score of the specified user in a game.
On success, if the message was sent by the bot, returns the edited Message, otherwise re... | Use this method to set the score of the specified user in a game.
On success, if the message was sent by the bot, returns the edited Message, otherwise returns True.
Returns an error, if the new score is not greater than the user's current score in the chat and force is False.
https://core.tele... |
def make_fileitem_peinfo_type(petype, condition='is', negate=False, preserve_case=False):
"""
Create a node for FileItem/PEInfo/Type
:return: A IndicatorItem represented as an Element node
"""
document = 'FileItem'
search = 'FileItem/PEInfo/Type'
content_type = 'string'
content = pe... | Create a node for FileItem/PEInfo/Type
:return: A IndicatorItem represented as an Element node |
def get_event_teams(self, id, **data):
"""
GET /events/:id/teams/
Returns a list of :format:`teams` for the event.
"""
return self.get("/events/{0}/teams/".format(id), data=data) | GET /events/:id/teams/
Returns a list of :format:`teams` for the event. |
def listFileParents(self, logical_file_name="", block_id=0, block_name=""):
"""
required parameter: logical_file_name or block_name
returns: this_logical_file_name, parent_logical_file_name, parent_file_id
"""
#self.logger.debug("lfn %s, block_name %s, block_id :%s" % (logical_fi... | required parameter: logical_file_name or block_name
returns: this_logical_file_name, parent_logical_file_name, parent_file_id |
def write(filename, f):
"""Write a function `f` defined in terms of spherical coordinates to a file.
"""
import meshio
import meshzoo
points, cells = meshzoo.iso_sphere(5)
# get spherical coordinates from points
polar = numpy.arccos(points[:, 2])
azimuthal = numpy.arctan2(points[:, 1], ... | Write a function `f` defined in terms of spherical coordinates to a file. |
def poll(self):
"""
Initiates the job status polling loop.
"""
task = self.task
# total job count
n_jobs = len(self.submission_data)
# store the number of consecutive polling failures and get the maximum number of polls
n_poll_fails = 0
if task.w... | Initiates the job status polling loop. |
def choices(klass):
"""
Decorator to set `CHOICES` and other attributes
"""
_choices = []
for attr in user_attributes(klass.Meta):
val = getattr(klass.Meta, attr)
setattr(klass, attr, val[0])
_choices.append((val[0], val[1]))
setattr(klass, 'CHOICES', tuple(_choices))
... | Decorator to set `CHOICES` and other attributes |
def Navigate(self, direction: int) -> 'Control':
"""
Call IUIAutomationCustomNavigationPattern::Navigate.
Get the next control in the specified direction within the logical UI tree.
direction: int, a value in class `NavigateDirection`.
Return `Control` subclass or None.
R... | Call IUIAutomationCustomNavigationPattern::Navigate.
Get the next control in the specified direction within the logical UI tree.
direction: int, a value in class `NavigateDirection`.
Return `Control` subclass or None.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomatio... |
def _distance_between_coords(self, lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees).
Haversine formula states that:
d = 2 * r * arcsin(sqrt(sin^2((lat1 - lat2) / 2 +
cos(lat1)cos(lat2)sin^2((l... | Calculate the great circle distance between two points
on the earth (specified in decimal degrees).
Haversine formula states that:
d = 2 * r * arcsin(sqrt(sin^2((lat1 - lat2) / 2 +
cos(lat1)cos(lat2)sin^2((lon1 - lon2) / 2))))
where r is the radius of the sphere. This assumes t... |
def to_json(self):
"""Create a property dict that is used to recreate an edge dictionary for a :class:`BELGraph`.
:return: Property dictionary of an edge that is participant (sub/obj) related.
:rtype: dict
"""
participant = self.side
prop_dict = {
p... | Create a property dict that is used to recreate an edge dictionary for a :class:`BELGraph`.
:return: Property dictionary of an edge that is participant (sub/obj) related.
:rtype: dict |
def EvalAdjustingSchedule(history,
constant=0.1,
steps_to_decrease=20,
improvement_margin=0.001,
decrease_rate=1.5,
history_mode="eval",
metric="metrics/accuracy"):... | Learning rate that decreases when eval metric stalls.
If the chosen metric does not improve by improvement_margin for as many as
steps_to_decrease steps, then the constant gets decreased by decrease rate.
Finally, the MultifactorSchedule gets called with the adjusted constant.
Args:
history: trax.history.... |
def add_node(self, id, radius=8, style=style.DEFAULT, category="", label=None, root=False,
properties={}):
""" Add node from id and return the node object.
"""
if self.has_key(id):
return self[id]
if not isinstance(style, str) ... | Add node from id and return the node object. |
def voip(self):
"""
Access the voip
:returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList
:rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList
"""
if self._voip is None:
self._voip = VoipList(
self.... | Access the voip
:returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList
:rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList |
def list_sets(family='ipv4'):
'''
.. versionadded:: 2014.7.0
List all ipset sets.
CLI Example:
.. code-block:: bash
salt '*' ipset.list_sets
'''
cmd = '{0} list -t'.format(_ipset_cmd())
out = __salt__['cmd.run'](cmd, python_shell=False)
_tmp = out.split('\n')
count... | .. versionadded:: 2014.7.0
List all ipset sets.
CLI Example:
.. code-block:: bash
salt '*' ipset.list_sets |
def _nest_payload(self, keys, payload):
"""
Nest a payload in a dict under the keys contained in `keys`
"""
if len(keys) == 0:
return payload
return {keys[0]: self._nest_payload(keys[1:], payload)} | Nest a payload in a dict under the keys contained in `keys` |
def _deduplicate_indexed_slices(values, indices):
"""Sums `values` associated with any non-unique `indices`.
Args:
values: A `Tensor` with rank >= 1.
indices: A one-dimensional integer `Tensor`, indexing into the first
dimension of `values` (as in an IndexedSlices object).
Returns:
A... | Sums `values` associated with any non-unique `indices`.
Args:
values: A `Tensor` with rank >= 1.
indices: A one-dimensional integer `Tensor`, indexing into the first
dimension of `values` (as in an IndexedSlices object).
Returns:
A tuple of (`summed_values`, `unique_indices`) where `uniq... |
def bulk_create(self, *records):
"""Create and validate multiple records in associated app
Args:
*records (dict): One or more dicts of new record field names and values
Notes:
Requires Swimlane 2.15+
Validates like :meth:`create`, but only sends a single re... | Create and validate multiple records in associated app
Args:
*records (dict): One or more dicts of new record field names and values
Notes:
Requires Swimlane 2.15+
Validates like :meth:`create`, but only sends a single request to create all provided fields, and doe... |
def save(self, filename=None):
""" Saves a constructed Morse-Smale Complex in json file
@ In, filename, a filename for storing the hierarchical
merging of features and the base level partitions of the
data
"""
if filename is None:
filename = "morse... | Saves a constructed Morse-Smale Complex in json file
@ In, filename, a filename for storing the hierarchical
merging of features and the base level partitions of the
data |
def date_elem(ind_days, ind_minutes):
"""Create a function to parse a datetime from the product-specific blocks."""
def inner(seq):
return nexrad_to_datetime(seq[ind_days], seq[ind_minutes] * 60 * 1000)
return inner | Create a function to parse a datetime from the product-specific blocks. |
def _convert_verbal_form( analysis ):
''' Converts ordinary verbal categories of the input analysis.
Performs one-to-one conversions. '''
assert FORM in analysis, '(!) The input analysis does not contain "'+FORM+'" key.'
for form, replacement in _verb_conversion_rules:
# Exact match
... | Converts ordinary verbal categories of the input analysis.
Performs one-to-one conversions. |
def spec(self):
"""
Generate spec for the processor as a Python dictionary.
A spec is a standard way to describe a MountainLab processor in a way
that is easy to process, yet still understandable by humans.
This method generates a Python dictionary that complies with a spec
... | Generate spec for the processor as a Python dictionary.
A spec is a standard way to describe a MountainLab processor in a way
that is easy to process, yet still understandable by humans.
This method generates a Python dictionary that complies with a spec
definition. |
def try_to_create_directory(directory_path):
"""Attempt to create a directory that is globally readable/writable.
Args:
directory_path: The path of the directory to create.
"""
logger = logging.getLogger("ray")
directory_path = os.path.expanduser(directory_path)
if not os.path.exists(di... | Attempt to create a directory that is globally readable/writable.
Args:
directory_path: The path of the directory to create. |
def find_package_dirs(root_path):
""" Find python package directories in directory `root_path`
Parameters
----------
root_path : str
Directory to search for package subdirectories
Returns
-------
package_sdirs : set
Set of strings where each is a subdirectory of `root_path`... | Find python package directories in directory `root_path`
Parameters
----------
root_path : str
Directory to search for package subdirectories
Returns
-------
package_sdirs : set
Set of strings where each is a subdirectory of `root_path`, containing
an ``__init__.py`` fi... |
def asdate(self):
"""Return this datetime_tz as a date object.
Returns:
This datetime_tz as a date object.
"""
return datetime.date(self.year, self.month, self.day) | Return this datetime_tz as a date object.
Returns:
This datetime_tz as a date object. |
def discover(self):
"""
Fetch state for each processes.
Build the self.cluster_tree, self.cluster_tags, self.cluster_running
data structures, needed for sub-commands start, stop, list.
"""
# need self.args['command'] so fail if it's not available
if (not self.arg... | Fetch state for each processes.
Build the self.cluster_tree, self.cluster_tags, self.cluster_running
data structures, needed for sub-commands start, stop, list. |
def peeklist(self, fmt, **kwargs):
"""Interpret next bits according to format string(s) and return list.
fmt -- One or more strings with comma separated tokens describing
how to interpret the next bits in the bitstring.
kwargs -- A dictionary or keyword-value pairs - the keywords... | Interpret next bits according to format string(s) and return list.
fmt -- One or more strings with comma separated tokens describing
how to interpret the next bits in the bitstring.
kwargs -- A dictionary or keyword-value pairs - the keywords used in the
format string w... |
def _phi2deriv(self,R,z,phi=0.,t=0.): #pragma: no cover
"""
NAME:
_phi2deriv
PURPOSE:
evaluate the second azimuthal derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
... | NAME:
_phi2deriv
PURPOSE:
evaluate the second azimuthal derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the second azimuthal derivative
... |
def check_basename_conflicts(self, targets):
"""Apps' basenames are used as bundle directory names. Ensure they are all unique."""
basename_seen = {}
for target in targets:
if target.basename in basename_seen:
raise self.BasenameConflictError('Basename must be unique, found two targets use '
... | Apps' basenames are used as bundle directory names. Ensure they are all unique. |
def ned2geodetic(n: float, e: float, d: float,
lat0: float, lon0: float, h0: float,
ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]:
"""
Converts North, East, Down to target latitude, longitude, altitude
Parameters
----------
n : float or nu... | Converts North, East, Down to target latitude, longitude, altitude
Parameters
----------
n : float or numpy.ndarray of float
North NED coordinate (meters)
e : float or numpy.ndarray of float
East NED coordinate (meters)
d : float or numpy.ndarray of float
Down NED coordinat... |
def model_stats(self):
"""A dict mapping the model's ``default_stats`` to arrays of values.
The returned array has shape ``nwalkers x niterations``.
"""
stats = self.model.default_stats
return blob_data_to_dict(stats, self._sampler.blobs) | A dict mapping the model's ``default_stats`` to arrays of values.
The returned array has shape ``nwalkers x niterations``. |
def get_instance(self, payload):
"""
Build an instance of AuthTypesInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance
:rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesIn... | Build an instance of AuthTypesInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance
:rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance |
def get_object(self, *args, **kwargs):
"""
Should memoize the object to avoid multiple query if get_object is used many times in the view
"""
self.category_instance = get_object_or_404(Category, slug=self.kwargs['category_slug'])
return get_object_or_404(Post, thread__id=self.kwa... | Should memoize the object to avoid multiple query if get_object is used many times in the view |
def prefixed_collapsible_map(m, prefix):
"""
Return a dict of params corresponding to those in m with the added prefix
"""
if m == values.unset:
return {}
def flatten_dict(d, result={}, prv_keys=[]):
for k, v in d.items():
if isinstance(v, dict):
flatten_... | Return a dict of params corresponding to those in m with the added prefix |
def remove_known_hosts(overcloud_ip):
"""For a given IP address remove SSH keys from the known_hosts file"""
known_hosts = os.path.expanduser("~/.ssh/known_hosts")
if os.path.exists(known_hosts):
command = ['ssh-keygen', '-R', overcloud_ip, '-f', known_hosts]
subprocess.check_call(command) | For a given IP address remove SSH keys from the known_hosts file |
def create(self, attributes=values.unset, twilio_address=values.unset,
date_created=values.unset, date_updated=values.unset,
identity=values.unset, user_address=values.unset):
"""
Create a new ParticipantInstance
:param unicode attributes: An optional string metada... | Create a new ParticipantInstance
:param unicode attributes: An optional string metadata field you can use to store any data you wish.
:param unicode twilio_address: The address of the Twilio phone number that the participant is in contact with.
:param datetime date_created: The date that this r... |
def save(self):
"""
Sync local changes in server's attributes to the API.
Note: DOES NOT sync IPAddresses and storage_devices,
use add_ip, add_storage, remove_ip, remove_storage instead.
"""
# dict comprehension that also works with 2.6
# http://stackoverflow.com... | Sync local changes in server's attributes to the API.
Note: DOES NOT sync IPAddresses and storage_devices,
use add_ip, add_storage, remove_ip, remove_storage instead. |
def _clean_inheritance_tokens(self):
"""create a new copy of this :class:`.Context`. with
tokens related to inheritance state removed."""
c = self._copy()
x = c._data
x.pop('self', None)
x.pop('parent', None)
x.pop('next', None)
return c | create a new copy of this :class:`.Context`. with
tokens related to inheritance state removed. |
def serial_udb_extra_f13_encode(self, sue_week_no, sue_lat_origin, sue_lon_origin, sue_alt_origin):
'''
Backwards compatible version of SERIAL_UDB_EXTRA F13: format
sue_week_no : Serial UDB Extra GPS Week Number (int16_t)
sue_lat_origin ... | Backwards compatible version of SERIAL_UDB_EXTRA F13: format
sue_week_no : Serial UDB Extra GPS Week Number (int16_t)
sue_lat_origin : Serial UDB Extra MP Origin Latitude (int32_t)
sue_lon_origin : Serial UDB Extra MP Origin Longitude ... |
def vehicle_type_string(self, hb):
'''return vehicle type string from a heartbeat'''
if hb.type == mavutil.mavlink.MAV_TYPE_FIXED_WING:
return 'Plane'
if hb.type == mavutil.mavlink.MAV_TYPE_GROUND_ROVER:
return 'Rover'
if hb.type == mavutil.mavlink.MAV_TYPE_SURFAC... | return vehicle type string from a heartbeat |
def replace(self, key, value):
"""Replace the value of the first key-value pair with key *key*.
If the key was not found, the pair is inserted.
"""
self._find_lt(key)
node = self._path[0][2]
if node is self._tail or key < node[0]:
node = self._create_node(key... | Replace the value of the first key-value pair with key *key*.
If the key was not found, the pair is inserted. |
def update_instance(self, data):
"""Update a single record by id with the provided data.
Args:
data (dict): The new data to update the record with.
Returns:
self: This is an instance of itself with the updated data.
Raises:
AttributeError: This is r... | Update a single record by id with the provided data.
Args:
data (dict): The new data to update the record with.
Returns:
self: This is an instance of itself with the updated data.
Raises:
AttributeError: This is raised if a key in the ``data`` isn't
... |
def get_proficiencies(self):
"""Gets all ``Proficiencies``.
return: (osid.learning.ProficiencyList) - a list of
``Proficiencies``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This ... | Gets all ``Proficiencies``.
return: (osid.learning.ProficiencyList) - a list of
``Proficiencies``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.* |
def comment(self, message):
"""Add new comment to record comment field"""
message = str(message)
sw_repr = {
'$type': 'Core.Models.Record.Comments, Core',
'createdByUser': self._record._swimlane.user.as_usergroup_selection(),
'createdDate': pendulum.now().to_... | Add new comment to record comment field |
def get_table_names(self, connection, schema=None, **kw):
"""
Return a list of table names for `schema`.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.get_table_names`.
"""
return self._get_table_or_view_names('r', connection, schema, **kw) | Return a list of table names for `schema`.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.get_table_names`. |
def TakeIf(self: dict, f):
"""
[
{
'self': [1, 2, 3],
'f': lambda e: e%2,
'assert': lambda ret: list(ret) == [1, 3]
}
]
"""
if is_to_destruct(f):
f = destruct_func(f)
return (e for e in self.items() if f(e)) | [
{
'self': [1, 2, 3],
'f': lambda e: e%2,
'assert': lambda ret: list(ret) == [1, 3]
}
] |
def structs2records(structs):
"""convert one or more structs and generate dictionaries"""
try:
n = len(structs)
except TypeError:
# no array
yield struct2dict(structs)
# just 1
return
for i in range(n):
struct = structs[i]
yield struct2dict(struct) | convert one or more structs and generate dictionaries |
def set_harakiri_params(self, timeout=None, verbose=None, disable_for_arh=None):
"""Sets workers harakiri parameters.
:param int timeout: Harakiri timeout in seconds.
Every request that will take longer than the seconds specified
in the harakiri timeout will be dropped and the c... | Sets workers harakiri parameters.
:param int timeout: Harakiri timeout in seconds.
Every request that will take longer than the seconds specified
in the harakiri timeout will be dropped and the corresponding
worker is thereafter recycled.
:param bool verbose: Haraki... |
def getChecks(self, **parameters):
"""Pulls all checks from pingdom
Optional Parameters:
* limit -- Limits the number of returned probes to the
specified quantity.
Type: Integer (max 25000)
Default: 25000
* offset -- Offs... | Pulls all checks from pingdom
Optional Parameters:
* limit -- Limits the number of returned probes to the
specified quantity.
Type: Integer (max 25000)
Default: 25000
* offset -- Offset for listing (requires limit.)
... |
def video_mode_supported(self, width, height, bpp):
"""Returns whether the frame buffer implementation is willing to
support a given video mode. In case it is not able to render
the video mode (or for some reason not willing), it should
return @c false. Usually this method is called when... | Returns whether the frame buffer implementation is willing to
support a given video mode. In case it is not able to render
the video mode (or for some reason not willing), it should
return @c false. Usually this method is called when the guest
asks the VMM device whether a given video mo... |
def version_info(self):
""" Tell, what version we're running at and if it's up to date. """
# Retrive and show local version info
package = pkg.get_distribution('git-up')
local_version_str = package.version
local_version = package.parsed_version
print('GitUp ver... | Tell, what version we're running at and if it's up to date. |
def show_current_metadata(self):
"""Show metadata of the current selected layer."""
LOGGER.debug('Showing layer: ' + self.layer.name())
keywords = KeywordIO(self.layer)
content_html = keywords.to_message().to_html()
full_html = html_header() + content_html + html_footer()
... | Show metadata of the current selected layer. |
def close(self):
"""Close subscription.
"""
if self._S is not None:
# after .close() self._event should never be called
self._S.close()
# wait for Cancelled to be delivered
self._evt.wait()
self._S = None | Close subscription. |
def _check_shape(shape):
"""Verify that a shape has the right format."""
if isinstance(shape, tuple):
for dim in shape:
if (isinstance(dim, tuple) and len(dim) == 2 and
isinstance(dim[0], int) and isinstance(dim[1], int)):
if dim[0] < 0:
... | Verify that a shape has the right format. |
def send_request(self, kind, url_components, **kwargs):
"""
Send a request for this resource to the API
Parameters
----------
kind: str, {'get', 'delete', 'put', 'post', 'head'}
"""
return self.api.send_request(kind, self.resource_path, url_components,
... | Send a request for this resource to the API
Parameters
----------
kind: str, {'get', 'delete', 'put', 'post', 'head'} |
def _to_relative_path(cls, parent_repo, path):
""":return: a path guaranteed to be relative to the given parent-repository
:raise ValueError: if path is not contained in the parent repository's working tree"""
path = to_native_path_linux(path)
if path.endswith('/'):
path = p... | :return: a path guaranteed to be relative to the given parent-repository
:raise ValueError: if path is not contained in the parent repository's working tree |
async def on_raw_317(self, message):
""" WHOIS idle time. """
target, nickname, idle_time = message.params[:3]
info = {
'idle': int(idle_time),
}
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | WHOIS idle time. |
def render_target(self):
"""Texture: The current render target, or None if using the default render target."""
render_target = lib.SDL_GetRenderTarget(self._ptr)
if render_target == ffi.NULL:
return None
else:
return Texture._from_ptr(render_target) | Texture: The current render target, or None if using the default render target. |
def make_palette_chunks(palette):
"""
Create the byte sequences for a ``PLTE`` and
if necessary a ``tRNS`` chunk.
Returned as a pair (*p*, *t*).
*t* will be ``None`` if no ``tRNS`` chunk is necessary.
"""
p = bytearray()
t = bytearray()
for x in palette:
p.extend(x[0:3])
... | Create the byte sequences for a ``PLTE`` and
if necessary a ``tRNS`` chunk.
Returned as a pair (*p*, *t*).
*t* will be ``None`` if no ``tRNS`` chunk is necessary. |
def parse_TKIP_hdr(pkt):
"""Extract TSCs, TA and encoded-data from a packet @pkt"""
# Note: FCS bit is not handled
assert pkt.FCfield.protected
# 802.11i - 8.3.2.2
tkip_layer = pkt[Dot11TKIP]
payload = tkip_layer.data
# IV
if not tkip_layer.ext_iv:
# 802.11i p. 46
raise... | Extract TSCs, TA and encoded-data from a packet @pkt |
def place(self, x, y, svg, layer_id):
"""Place the :paramref:`svg` content at ``(x, y)`` position
in the SVG, in a layer with the id :paramref:`layer_id`.
:param float x: the x position of the svg
:param float y: the y position of the svg
:param str svg: the SVG to place at ``(x... | Place the :paramref:`svg` content at ``(x, y)`` position
in the SVG, in a layer with the id :paramref:`layer_id`.
:param float x: the x position of the svg
:param float y: the y position of the svg
:param str svg: the SVG to place at ``(x, y)``
:param str layer_id: the id of the... |
def _evaluate(self,R,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
... | NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
2011-03-27 - Started - Bovy (NYU) |
def remove_post_process(self, name):
"""remove a post-process
Parameters
----------
name : str
name of the post-process to remove.
"""
self._pprocesses = [post_process
for post_process in self._pprocesses
... | remove a post-process
Parameters
----------
name : str
name of the post-process to remove. |
def read_channel_list_file(*source):
"""Read a `~gwpy.detector.ChannelList` from a Channel List File
"""
# read file(s)
config = configparser.ConfigParser(dict_type=OrderedDict)
source = file_list(source)
success_ = config.read(*source)
if len(success_) != len(source):
raise IOError(... | Read a `~gwpy.detector.ChannelList` from a Channel List File |
def changed(self):
"""
Returns list of modified ``FileNode`` objects.
"""
if not self.parents:
return []
return ChangedFileNodesGenerator([n for n in
self._get_paths_for_status('modified')], self) | Returns list of modified ``FileNode`` objects. |
def open(self, url):
"""
Open a document at the specified URL.
The document URL's needs not contain a protocol identifier, and if it
does, that protocol identifier is ignored when looking up the store
content.
Missing documents referenced using the internal 'suds' proto... | Open a document at the specified URL.
The document URL's needs not contain a protocol identifier, and if it
does, that protocol identifier is ignored when looking up the store
content.
Missing documents referenced using the internal 'suds' protocol are
reported by raising an ex... |
def is_end_node(node):
"""Checks if a node is the "end" keyword.
Args:
node: AST node.
Returns:
True if the node is the "end" keyword, otherwise False.
"""
return (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Name) and
node.value.id == 'end') | Checks if a node is the "end" keyword.
Args:
node: AST node.
Returns:
True if the node is the "end" keyword, otherwise False. |
def CreateStorageWriter(cls, storage_format, session, path):
"""Creates a storage writer.
Args:
session (Session): session the storage changes are part of.
path (str): path to the storage file.
storage_format (str): storage format.
Returns:
StorageWriter: a storage writer or None i... | Creates a storage writer.
Args:
session (Session): session the storage changes are part of.
path (str): path to the storage file.
storage_format (str): storage format.
Returns:
StorageWriter: a storage writer or None if the storage file cannot be
opened or the storage format ... |
def set_default_interface(etree):
"""
Sets the default interface that PyAMF will use to deal with XML entities
(both objects and blobs).
"""
global types, ET, modules
t = _get_etree_type(etree)
_types = set(types or [])
_types.update([t])
types = tuple(_types)
modules[t] = et... | Sets the default interface that PyAMF will use to deal with XML entities
(both objects and blobs). |
def slow_reduction_transfer(ii, j, idx, count, x, u, v, c):
'''Perform the reduction transfer step from the Jonker-Volgenant algorithm
The data is input in a ragged array in terms of "i" structured as a
vector of values for each i,j combination where:
ii - the i to be reduced
j - the j-ind... | Perform the reduction transfer step from the Jonker-Volgenant algorithm
The data is input in a ragged array in terms of "i" structured as a
vector of values for each i,j combination where:
ii - the i to be reduced
j - the j-index of every entry
idx - the index of the first entry for each i... |
def json_success_response(data, response):
"""
Formats the response of a successful token request as JSON.
Also adds default headers and status code.
"""
response.body = json.dumps(data)
response.status_code = 200
response.add_header("Content-Type", "application/json")
response.add_hea... | Formats the response of a successful token request as JSON.
Also adds default headers and status code. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.