code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _set_properties(self, data):
"""
set the properties of the app model by the given data dict
"""
for property in data.keys():
if property in vars(self):
setattr(self, property, data[property]) | set the properties of the app model by the given data dict |
def eeg_microstates_clustering(data, n_microstates=4, clustering_method="kmeans", n_jobs=1, n_init=25, occurence_rejection_treshold=0.05, max_refitting=5, verbose=True):
"""
Fit the clustering algorithm.
"""
# Create training set
training_set = data.copy()
if verbose is True:
print("- I... | Fit the clustering algorithm. |
def check_for_blob(self, container_name, blob_name, **kwargs):
"""
Check if a blob exists on Azure Blob Storage.
:param container_name: Name of the container.
:type container_name: str
:param blob_name: Name of the blob.
:type blob_name: str
:param kwargs: Option... | Check if a blob exists on Azure Blob Storage.
:param container_name: Name of the container.
:type container_name: str
:param blob_name: Name of the blob.
:type blob_name: str
:param kwargs: Optional keyword arguments that
`BlockBlobService.exists()` takes.
:t... |
def prepare(_next, self):
"""Hook after prepare and set expiration widget to
``self.form``.
"""
_next(self)
cfg = ugm_general(self.model)
if cfg.attrs['users_account_expiration'] != 'True':
return
mode = 'edit'
if not self.request.has_permissio... | Hook after prepare and set expiration widget to
``self.form``. |
def install(self):
"""
Run the actual installation
"""
self._start_install()
mr_link = self._get_mr_link()
# Set up the progress bar
pbar = ProgressBar(100, 'Running installation...')
pbar.start()
mr_j, mr_r = self._ajax(mr_link)
# Loop u... | Run the actual installation |
def to_new(self, data, perplexity=None, return_distances=False):
"""Compute the affinities of new samples to the initial samples.
This is necessary for embedding new data points into an existing
embedding.
Please see the :ref:`parameter-guide` for more information.
Parameters
... | Compute the affinities of new samples to the initial samples.
This is necessary for embedding new data points into an existing
embedding.
Please see the :ref:`parameter-guide` for more information.
Parameters
----------
data: np.ndarray
The data points to b... |
def _flushContour(self):
"""
This normalizes the contour so that:
- there are no line segments. in their place will be
curve segments with the off curves positioned on top
of the previous on curve and the new curve on curve.
- the contour starts with an on curve
... | This normalizes the contour so that:
- there are no line segments. in their place will be
curve segments with the off curves positioned on top
of the previous on curve and the new curve on curve.
- the contour starts with an on curve |
def advance_permutation(a, increasing=True, forward=True):
"""
Advance a list of unique, ordered elements in-place, lexicographically
increasing or backward, by rightmost or leftmost digit.
Returns False if the permutation wrapped around - i.e. went from
lexicographically greatest to least, and Tru... | Advance a list of unique, ordered elements in-place, lexicographically
increasing or backward, by rightmost or leftmost digit.
Returns False if the permutation wrapped around - i.e. went from
lexicographically greatest to least, and True in all other cases.
If the length of the list is N, then this fu... |
def get_next_occurrence(self) -> date:
""" Returns the next occurrence date for transaction """
result = get_next_occurrence(self.transaction)
assert isinstance(result, date)
return result | Returns the next occurrence date for transaction |
def glr_path_static():
"""Returns path to packaged static files"""
return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static')) | Returns path to packaged static files |
def assert_no_title(self, title, **kwargs):
"""
Asserts that the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
Tru... | Asserts that the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the asserti... |
def deprecated(use_instead=None):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used."""
def wrapped(func):
@wraps(func)
def new_func(*args, **kwargs):
message = "Call to deprecated fu... | This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used. |
def _expand_config_values(section, key):
"""
Walker function for ConfigObj.walk
Applies expand_environment_and_home to all configuration values that
are strings (or strings that are elements of tuples/lists)
:param section: as passed by ConfigObj.walk
:param key: as pas... | Walker function for ConfigObj.walk
Applies expand_environment_and_home to all configuration values that
are strings (or strings that are elements of tuples/lists)
:param section: as passed by ConfigObj.walk
:param key: as passed by ConfigObj.walk |
def create_input_for_numbered_sequences(headerDir, sourceDir, containers, maxElements):
"""Creates additional source- and header-files for the numbered sequence MPL-containers."""
# Create additional container-list without "map".
containersWithoutMap = containers[:]
try:
containersWithoutMap.rem... | Creates additional source- and header-files for the numbered sequence MPL-containers. |
def streamer(main_method):
"""Open a stream for the first file in arguments, or stdin"""
def main(arguments):
streams = [StringIO(get_clipboard_data())] if (arguments and '-c' in arguments) else []
streams = streams or ([file(_, 'r') for _ in arguments if os.path.isfile(argument)] if arguments e... | Open a stream for the first file in arguments, or stdin |
def submission_to_json(self, task, data, debug, reloading=False, replace=False, tags={}):
""" Converts a submission to json (keeps only needed fields) """
if "ssh_host" in data:
return json.dumps({'status': "waiting", 'text': "<b>SSH server active</b>",
'ssh_h... | Converts a submission to json (keeps only needed fields) |
def corr_heatmap(
x,
mask_half=True,
cmap="RdYlGn_r",
vmin=-1,
vmax=1,
linewidths=0.5,
square=True,
figsize=(10, 10),
**kwargs
):
"""Wrapper around seaborn.heatmap for visualizing correlation matrix.
Parameters
----------
x : DataFrame
Underly... | Wrapper around seaborn.heatmap for visualizing correlation matrix.
Parameters
----------
x : DataFrame
Underlying data (not a correlation matrix)
mask_half : bool, default True
If True, mask (whiteout) the upper right triangle of the matrix
All other parameters passed to sea... |
def add_block(self, name):
""" Adds a new block to the AST.
`name`
Block name.
* Raises a ``ValueError`` exception if `name` is invalid or
an existing block name matches value provided for `name`.
"""
if not self.RE_NAME.match(name):
... | Adds a new block to the AST.
`name`
Block name.
* Raises a ``ValueError`` exception if `name` is invalid or
an existing block name matches value provided for `name`. |
def url_to_path(url):
# type: (str) -> str
"""
Convert a file: URL to a path.
"""
assert url.startswith('file:'), (
"You can only turn file: urls into filenames (not %r)" % url)
_, netloc, path, _, _ = urllib_parse.urlsplit(url)
# if we have a UNC path, prepend UNC share notation
... | Convert a file: URL to a path. |
def returner(ret):
'''
Take in the return and shove it into the couchdb database.
'''
options = _get_options(ret)
# Check to see if the database exists.
_response = _request("GET",
options['url'] + "_all_dbs",
user=options['user'],
... | Take in the return and shove it into the couchdb database. |
def render(template_path, output_file=None, **kwargs):
"""
Render jinja2 template file use absolute path.
**Usage**
A simple template as follow:
.. code-block:: jinja
This is a test template
{{ title }}
Then write render code by single line.
.. code-block:: python
... | Render jinja2 template file use absolute path.
**Usage**
A simple template as follow:
.. code-block:: jinja
This is a test template
{{ title }}
Then write render code by single line.
.. code-block:: python
render('template.tpl', name='toolkit')
:param template_pa... |
def clean_response(response):
""" Cleans string quoting in response. """
response = re.sub("^['\"]", "", response)
response = re.sub("['\"]$", "", response)
return response | Cleans string quoting in response. |
def add_subtract_misfeatured_tile(
st, tile, rad='calc', max_iter=3, invert='guess', max_allowed_remove=20,
minmass=None, use_tp=False, **kwargs):
"""
Automatically adds and subtracts missing & extra particles in a region
of poor fit.
Parameters
----------
st: :class:`peri.state... | Automatically adds and subtracts missing & extra particles in a region
of poor fit.
Parameters
----------
st: :class:`peri.states.State`
The state to add and subtract particles to.
tile : :class:`peri.util.Tile`
The poorly-fit region to examine.
rad : Float or 'calc', optional
... |
def require_setting(self, name, feature="this feature"):
"""Raises an exception if the given app setting is not defined."""
if name not in self.settings:
raise Exception("You must define the '%s' setting in your "
"application to use %s" % (name, feature)) | Raises an exception if the given app setting is not defined. |
def list_column_families(self):
"""List the column families owned by this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_list_column_families]
:end-before: [END bigtable_list_column_families]
:rtype: dict
:return... | List the column families owned by this table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_list_column_families]
:end-before: [END bigtable_list_column_families]
:rtype: dict
:returns: Dictionary of column families attached t... |
def tzinfo_from_match(match_object):
"""Create a timezone information object from a regular expression match.
The regular expression match is expected to be from RE_DATE, RE_TIME or
RE_DATETIME.
@param match_object: The regular expression match.
@type value: B{re}.I{MatchObject}
@return: A tim... | Create a timezone information object from a regular expression match.
The regular expression match is expected to be from RE_DATE, RE_TIME or
RE_DATETIME.
@param match_object: The regular expression match.
@type value: B{re}.I{MatchObject}
@return: A timezone information object.
@rtype: B{date... |
def _create_rule(path, rule):
# type: (List[Type[Rule]], Type[Rule]) -> Type[ReducedUnitRule]
"""
Create ReducedUnitRule based on sequence of unit rules and end, generating rule.
:param path: Sequence of unit rules.
:param rule: Rule that is attached after sequence of unit rules.
:return: Reduce... | Create ReducedUnitRule based on sequence of unit rules and end, generating rule.
:param path: Sequence of unit rules.
:param rule: Rule that is attached after sequence of unit rules.
:return: ReducedUnitRule class. |
def service_class_uuid_list(self):
"""Listq of Service Class UUIDs. Set and retrieved as a list
of complete 128-bit UUIDs. Decoded from and encoded as EIR
types 0x02/0x03 (16-bit partial/complete UUIDs), 0x04/0x05
(32-bit partial/complete UUIDs), 0x06/0x07 (128-bit
partial/comple... | Listq of Service Class UUIDs. Set and retrieved as a list
of complete 128-bit UUIDs. Decoded from and encoded as EIR
types 0x02/0x03 (16-bit partial/complete UUIDs), 0x04/0x05
(32-bit partial/complete UUIDs), 0x06/0x07 (128-bit
partial/complete UUIDs). |
def fitNormalization(self, specVals, xlims):
"""Fit the normalization given a set of spectral values that
define a spectral shape
This version is faster, and solves for the root of the derivatvie
Parameters
----------
specVals : an array of (nebin values that define a ... | Fit the normalization given a set of spectral values that
define a spectral shape
This version is faster, and solves for the root of the derivatvie
Parameters
----------
specVals : an array of (nebin values that define a spectral shape
xlims : fit limits
... |
def _RemoveRegistryKeys(self, metadata_value_pairs):
"""Filter out registry keys to operate on files."""
filtered_pairs = []
for metadata, stat_entry in metadata_value_pairs:
# Ignore registry keys.
if stat_entry.pathspec.pathtype != rdf_paths.PathSpec.PathType.REGISTRY:
filtered_pairs.a... | Filter out registry keys to operate on files. |
def _analysis_data(self, analysis):
""" Returns a dict that represents the analysis
"""
decimalmark = analysis.aq_parent.aq_parent.getDecimalMark()
keyword = analysis.getKeyword()
andict = {
'obj': analysis,
'id': analysis.id,
'title': analysis... | Returns a dict that represents the analysis |
def authors_json(soup):
"""authors list in article json format"""
authors_json_data = []
contributors_data = contributors(soup, "full")
author_contributions_data = author_contributions(soup, None)
author_competing_interests_data = competing_interests(soup, None)
author_correspondence_data = full... | authors list in article json format |
def en_passant_moves(self, position):
"""
Finds possible en passant moves.
:rtype: list
"""
# if pawn is not on a valid en passant get_location then return None
if self.on_en_passant_valid_location():
for move in itertools.chain(self.add_one_en_passant_move(... | Finds possible en passant moves.
:rtype: list |
def _escape_solr_query(query, field="title"):
"""
Escapes special characters in Solr queries.
Note that this omits * - this is intentionally permitted in user queries.
The list of special characters is located at http://lucene.apache.org/core/4_0_0/queryparser/org/apache/lucene/querypars... | Escapes special characters in Solr queries.
Note that this omits * - this is intentionally permitted in user queries.
The list of special characters is located at http://lucene.apache.org/core/4_0_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#Escaping_Special_Characters |
def create_item(self, name):
"""create a new named todo list
:rtype: TodoListUX
"""
item = self.app.create_item(name)
return TodoListUX(ux=self, controlled_list=item) | create a new named todo list
:rtype: TodoListUX |
def write_multiple_registers(self, regs_addr, regs_value):
"""Modbus function WRITE_MULTIPLE_REGISTERS (0x10)
:param regs_addr: registers address (0 to 65535)
:type regs_addr: int
:param regs_value: registers values to write
:type regs_value: list
:returns: True if write... | Modbus function WRITE_MULTIPLE_REGISTERS (0x10)
:param regs_addr: registers address (0 to 65535)
:type regs_addr: int
:param regs_value: registers values to write
:type regs_value: list
:returns: True if write ok or None if fail
:rtype: bool or None |
def populate_fabfile():
"""
Automatically includes all submodules and role selectors
in the top-level fabfile using spooky-scary black magic.
This allows us to avoid manually declaring imports for every module, e.g.
import burlap.pip
import burlap.vm
import burlap...
which... | Automatically includes all submodules and role selectors
in the top-level fabfile using spooky-scary black magic.
This allows us to avoid manually declaring imports for every module, e.g.
import burlap.pip
import burlap.vm
import burlap...
which has the added benefit of allowing u... |
def update(self, product_id, product_data):
"""修改商品"""
product_data['product_id'] = product_id
return self._post(
'merchant/update',
data=product_data
) | 修改商品 |
def checksum_ip(ipvx, length, payload):
"""
calculate checksum of IP pseudo header
IPv4 pseudo header
UDP RFC768
TCP RFC793 3.1
0 7 8 15 16 23 24 31
+--------+--------+--------+--------+
| source address |
+--------+--------+--------+--------+
... | calculate checksum of IP pseudo header
IPv4 pseudo header
UDP RFC768
TCP RFC793 3.1
0 7 8 15 16 23 24 31
+--------+--------+--------+--------+
| source address |
+--------+--------+--------+--------+
| destination address |
+--------... |
def _deconstruct_binary(self, data):
"""Extract binary components in the packet."""
attachments = []
data = self._deconstruct_binary_internal(data, attachments)
return data, attachments | Extract binary components in the packet. |
def run_asset_discovery(
self,
parent,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Runs asset discovery. The discovery is tracked with a long-running
operation.
This API... | Runs asset discovery. The discovery is tracked with a long-running
operation.
This API can only be called with limited frequency for an organization.
If it is called too frequently the caller will receive a
TOO\_MANY\_REQUESTS error.
Example:
>>> from google.cloud i... |
def get_setting(self, twig=None, **kwargs):
"""
Filter in the 'setting' context
:parameter str twig: the twig used for filtering
:parameter **kwargs: any other tags to do the filter (except tag or
context)
:return: :class:`phoebe.parameters.parameters.ParameterSet`
... | Filter in the 'setting' context
:parameter str twig: the twig used for filtering
:parameter **kwargs: any other tags to do the filter (except tag or
context)
:return: :class:`phoebe.parameters.parameters.ParameterSet` |
def update_discount_promotion_by_id(cls, discount_promotion_id, discount_promotion, **kwargs):
"""Update DiscountPromotion
Update attributes of DiscountPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
... | Update DiscountPromotion
Update attributes of DiscountPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_discount_promotion_by_id(discount_promotion_id, discount_promotion, async=True)
... |
def analyze_script(self, index=None):
"""Analyze current script with todos"""
if self.is_analysis_done:
return
if index is None:
index = self.get_stack_index()
if self.data:
finfo = self.data[index]
if self.todolist_enabled:
... | Analyze current script with todos |
def get(self, count=None, since_id=None, silent=False):
"""
Get all photos from the user or members of the list
:param count: Number of tweets to try and retrieve. If None, return
all photos since `since_id`
:param since_id: An integer specifying the oldest tweet id
"... | Get all photos from the user or members of the list
:param count: Number of tweets to try and retrieve. If None, return
all photos since `since_id`
:param since_id: An integer specifying the oldest tweet id |
def exists(self, fileDirSpec, **kwargs):
"""
Simple returns a boolean if the <fileDirSpec>
exists in the current dir (or dir spec'd by **kwargs)
"""
str_path = self.cwd()
for k,v in kwargs.items():
if k == 'path': str_path ... | Simple returns a boolean if the <fileDirSpec>
exists in the current dir (or dir spec'd by **kwargs) |
def replace_uuid_w_names(self, resp):
""" Replace the uuid's with names.
Parameters
----------
resp : ???
???
Returns
-------
???
???
"""
col_mapper = self.get_point_name(resp.context)["?point"].to_dict()
... | Replace the uuid's with names.
Parameters
----------
resp : ???
???
Returns
-------
???
??? |
def display_ioc(self, width=120, sep=' ', params=False):
"""
Get a string representation of an IOC.
:param width: Width to print the description too.
:param sep: Separator used for displaying the contents of the criteria nodes.
:param params: Boolean, set to True in order to di... | Get a string representation of an IOC.
:param width: Width to print the description too.
:param sep: Separator used for displaying the contents of the criteria nodes.
:param params: Boolean, set to True in order to display node parameters.
:return: |
def parse_arguments(argv):
"""Parse command line arguments.
Args:
argv: list of command line arguments, includeing programe name.
Returns:
An argparse Namespace object.
"""
parser = argparse.ArgumentParser(
description='Runs Preprocessing on structured CSV data.')
parser.add_argument('--inpu... | Parse command line arguments.
Args:
argv: list of command line arguments, includeing programe name.
Returns:
An argparse Namespace object. |
def parse_modes(modes, targets=None, noargs=''):
"""Parse channel modes:
.. code-block:: python
>>> parse_modes('+c-n', noargs='cn')
[('+', 'c', None), ('-', 'n', None)]
>>> parse_modes('+c-v', ['gawel'], noargs='c')
[('+', 'c', None), ('-', 'v', 'gawel')]
"""
if not ta... | Parse channel modes:
.. code-block:: python
>>> parse_modes('+c-n', noargs='cn')
[('+', 'c', None), ('-', 'n', None)]
>>> parse_modes('+c-v', ['gawel'], noargs='c')
[('+', 'c', None), ('-', 'v', 'gawel')] |
def _FormatValue(self, value, level=0):
"""Pretty-prints an object for a logger.
This function is very similar to the standard pprint. The main difference
is that it enforces limits to make sure we never produce an extremely long
string or take too much time.
Args:
value: Python object to pr... | Pretty-prints an object for a logger.
This function is very similar to the standard pprint. The main difference
is that it enforces limits to make sure we never produce an extremely long
string or take too much time.
Args:
value: Python object to print.
level: current recursion level.
... |
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(Value=self.value,
Status=self.status.value,
ProtocolDeviationRepeatKey=self.repeat_key
)
if self.code:
params['Code'] = self.code
... | Build XML by appending to builder |
def _array_clip_val(val):
"""Helper to turn val into array and clip between 0 and 1"""
val = np.array(val)
if val.max() > 1 or val.min() < 0:
logger.warning('value will be clipped between 0 and 1')
val[...] = np.clip(val, 0, 1)
return val | Helper to turn val into array and clip between 0 and 1 |
def render_templates_generator(*files, **template_map):
"""Render jinja templates according to template_map.
Yields (path, result)
"""
for path in files:
if not os.path.isfile(path):
raise ValueError("Template file %s not found"
% os.path.relpath(path))
... | Render jinja templates according to template_map.
Yields (path, result) |
def sort_players(self, sort_key=None, sort_func=None, reverse=False):
"""
Return all home and away by player info sorted by either the provided key or function. Must provide
at least one of the two parameters. Can sort either ascending or descending.
:param sort_key: (def None) ... | Return all home and away by player info sorted by either the provided key or function. Must provide
at least one of the two parameters. Can sort either ascending or descending.
:param sort_key: (def None) dict key to sort on
:param sort_func: (def None) sorting function
:param r... |
def _run_bunny(args):
"""Run CWL with rabix bunny.
"""
main_file, json_file, project_name = _get_main_and_json(args.directory)
work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "bunny_work"))
flags = ["-b", work_dir]
log_file = os.path.join(work_dir, "%s-bunny.log" % project_name)
if o... | Run CWL with rabix bunny. |
def save(self, temp_file, filename, obj):
"""Saves the specified file to either S3 or the local filesystem, depending on the currently enabled storage type."""
if not (self.storage_type and self.bucket_name):
ret = self._save_local(temp_file, filename, obj)
else:
if self... | Saves the specified file to either S3 or the local filesystem, depending on the currently enabled storage type. |
def wait_instances_running(ec2, instances):
"""
Wait until no instance in the given iterable is 'pending'. Yield every instance that
entered the running state as soon as it does.
:param boto.ec2.connection.EC2Connection ec2: the EC2 connection to use for making requests
:param Iterator[Instance] in... | Wait until no instance in the given iterable is 'pending'. Yield every instance that
entered the running state as soon as it does.
:param boto.ec2.connection.EC2Connection ec2: the EC2 connection to use for making requests
:param Iterator[Instance] instances: the instances to wait on
:rtype: Iterator[I... |
def _GetConnectionArgs(host=None,
port=None,
user=None,
password=None,
database=None,
client_key_path=None,
client_cert_path=None,
ca_cert_path=None):
"""Bui... | Builds connection arguments for MySQLdb.Connect function. |
def _update_limits_from_api(self):
"""
Query DynamoDB's DescribeLimits API action, and update limits
with the quotas returned. Updates ``self.limits``.
"""
self.connect()
logger.info("Querying DynamoDB DescribeLimits for limits")
# no need to paginate
lims... | Query DynamoDB's DescribeLimits API action, and update limits
with the quotas returned. Updates ``self.limits``. |
def show_group(self, group_id):
"""
Get information about a group
:type group_id: int
:param group_id: Group ID Number
:rtype: dict
:return: a dictionary containing group information
"""
res = self.post('loadGroups', {'groupId': group_id})
if isi... | Get information about a group
:type group_id: int
:param group_id: Group ID Number
:rtype: dict
:return: a dictionary containing group information |
def get_app(self):
'''Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle`
'''
if self.config is None:
... | Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle` |
def close(self, session):
"""Closes the specified session, event, or find list.
Corresponds to viClose function of the VISA library.
:param session: Unique logical identifier to a session, event, or find list.
:return: return value of the library call.
:rtype: :class:`pyvisa.co... | Closes the specified session, event, or find list.
Corresponds to viClose function of the VISA library.
:param session: Unique logical identifier to a session, event, or find list.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode` |
def get_row_headers(rows, row_headers_count_value=0, column_headers_count=1):
"""
Return row headers.
Assume that by default it has one column header.
Assume that there is only one father row header.
"""
# TODO: REFACTOR ALGORITHM NEEDED
partial_headers = []
if row_headers_count_value:
... | Return row headers.
Assume that by default it has one column header.
Assume that there is only one father row header. |
def status(directory: str) -> Tuple[RepositoryLocation, Branch, Commit]:
"""
Gets the status of the subrepo that has been cloned into the given directory.
:param directory: the directory containing the subrepo
:return: a tuple consisting of the URL the subrepo is tracking, the branch that has been check... | Gets the status of the subrepo that has been cloned into the given directory.
:param directory: the directory containing the subrepo
:return: a tuple consisting of the URL the subrepo is tracking, the branch that has been checked out and the commit
reference |
def copy(self):
"""
Make a hard copy of `self`.
:return: A new LiveDefinition instance.
:rtype: angr.analyses.ddg.LiveDefinitions
"""
ld = LiveDefinitions()
ld._memory_map = self._memory_map.copy()
ld._register_map = self._register_map.copy()
ld.... | Make a hard copy of `self`.
:return: A new LiveDefinition instance.
:rtype: angr.analyses.ddg.LiveDefinitions |
def map(self, features=None, query=None, styles=None,
bbox=[-180,-90,180,90], zoom=10, center=None,
image=None, image_bounds=None, cmap='viridis',
api_key=os.environ.get('MAPBOX_API_KEY', None), **kwargs):
"""
Renders a mapbox gl map from a vector... | Renders a mapbox gl map from a vector service query or a list of geojson features
Args:
features (list): a list of geojson features
query (str): a VectorServices query
styles (list): a list of VectorStyles to apply to the features
bbox (list): a bounding box... |
def get_files_for_document(document):
"""
Returns the available files for all languages.
In case the file is already present in another language, it does not re-add
it again.
"""
files = []
for doc_trans in document.translations.all():
if doc_trans.filer_file is not None and \
... | Returns the available files for all languages.
In case the file is already present in another language, it does not re-add
it again. |
def update_node_ids(self, sub_job_num=None):
"""
Associate Jobs with respective cluster ids.
"""
# Build condor_q and condor_history commands
dag_id = '%s.%s' % (self.cluster_id, sub_job_num) if sub_job_num else str(self.cluster_id)
job_delimiter = '+++'
attr_deli... | Associate Jobs with respective cluster ids. |
def load_panel_app(adapter, panel_id=None, institute='cust000'):
"""Load PanelApp panels into scout database
If no panel_id load all PanelApp panels
Args:
adapter(scout.adapter.MongoAdapter)
panel_id(str): The panel app panel id
"""
base_url = 'https://panelapp.genomicseng... | Load PanelApp panels into scout database
If no panel_id load all PanelApp panels
Args:
adapter(scout.adapter.MongoAdapter)
panel_id(str): The panel app panel id |
def read_bucket(self, bucket_name):
'''
a method to retrieve properties of a bucket in s3
:param bucket_name: string with name of bucket
:return: dictionary with details of bucket
'''
title = '%s.read_bucket' % self.__class__.__name__
# validate inputs... | a method to retrieve properties of a bucket in s3
:param bucket_name: string with name of bucket
:return: dictionary with details of bucket |
def cli(host, verbose):
"""
Floyd CLI interacts with FloydHub server and executes your commands.
Detailed help is available at https://docs.floydhub.com/commands/.
"""
import raven
raven.Client(
dsn='https://d8669005bd2b4b1ba6387ec57e1ce660:1d25ce33fcdb4864b9fd4f0c97689a98@sentry.io/2269... | Floyd CLI interacts with FloydHub server and executes your commands.
Detailed help is available at https://docs.floydhub.com/commands/. |
def load_clients(stream, configuration_class=ClientConfiguration):
"""
Loads client configurations from a YAML document stream.
:param stream: YAML stream.
:type stream: file
:param configuration_class: Class of the configuration object to create.
:type configuration_class: class
:return: A... | Loads client configurations from a YAML document stream.
:param stream: YAML stream.
:type stream: file
:param configuration_class: Class of the configuration object to create.
:type configuration_class: class
:return: A dictionary of client configuration objects.
:rtype: dict[unicode | str, do... |
def encodeSentence(self, *words):
"""
Encode given sentence in API format.
:param words: Words to endoce.
:returns: Encoded sentence.
"""
encoded = map(self.encodeWord, words)
encoded = b''.join(encoded)
# append EOS (end of sentence) byte
encoded... | Encode given sentence in API format.
:param words: Words to endoce.
:returns: Encoded sentence. |
def qmax_boiling(rhol=None, rhog=None, sigma=None, Hvap=None, D=None, P=None,
Pc=None, Method=None, AvailableMethods=False):
r'''This function handles the calculation of nucleate boiling critical
heat flux and chooses the best method for performing the calculation.
Preferred methods a... | r'''This function handles the calculation of nucleate boiling critical
heat flux and chooses the best method for performing the calculation.
Preferred methods are 'Serth-HEDH' when a tube diameter is specified,
and 'Zuber' otherwise.
Parameters
----------
rhol : float, optional
Den... |
def git_reset_all_repos(cat, hard=True, origin=False, clean=True):
"""Perform a 'git reset' in each data repository.
"""
log = cat.log
log.debug("gitter.git_reset_all_repos()")
all_repos = cat.PATHS.get_all_repo_folders()
for repo in all_repos:
log.warning("Repo in: '{}'".format(repo))
... | Perform a 'git reset' in each data repository. |
def beforeRender(self, ctx):
"""
Before rendering, retrieve the hostname from the request being
responded to and generate an URL which will serve as the root for
all JavaScript modules to be loaded.
"""
request = IRequest(ctx)
root = self.webSite.rootURL(request)
... | Before rendering, retrieve the hostname from the request being
responded to and generate an URL which will serve as the root for
all JavaScript modules to be loaded. |
def balanced_repartition(data, partitions):
""" balanced_repartition(data, partitions)
Reparations an RDD making sure data is evenly distributed across partitions
for Spark version < 2.1 (see: https://issues.apache.org/jira/browse/SPARK-17817)
or < 2.3 when #partitions is power of 2 (see: https://is... | balanced_repartition(data, partitions)
Reparations an RDD making sure data is evenly distributed across partitions
for Spark version < 2.1 (see: https://issues.apache.org/jira/browse/SPARK-17817)
or < 2.3 when #partitions is power of 2 (see: https://issues.apache.org/jira/browse/SPARK-21782)
:para... |
def _get_fd(fileobj):
"""
Get a descriptor out of a file object.
:param fileobj:
An integer (existing descriptor) or any object having the `fileno()`
method.
:raises ValueError:
if the descriptor cannot be obtained or if the descriptor is invalid
:returns:
file descr... | Get a descriptor out of a file object.
:param fileobj:
An integer (existing descriptor) or any object having the `fileno()`
method.
:raises ValueError:
if the descriptor cannot be obtained or if the descriptor is invalid
:returns:
file descriptor number |
def replace(self, to_replace, value, inplace=False, filter=None,
regex=False, convert=True):
"""replace the to_replace value with value, possible to create new
blocks here this is just a call to putmask. regex is not used here.
It is used in ObjectBlocks. It is here for API comp... | replace the to_replace value with value, possible to create new
blocks here this is just a call to putmask. regex is not used here.
It is used in ObjectBlocks. It is here for API compatibility. |
def should_close(self):
"""
Check whether the HTTP connection of this request should be closed
after the request is finished.
We check for the `Connection` HTTP header and for the HTTP Version
(only `HTTP/1.1` supports keep-alive.
"""
if self.headers.get('connect... | Check whether the HTTP connection of this request should be closed
after the request is finished.
We check for the `Connection` HTTP header and for the HTTP Version
(only `HTTP/1.1` supports keep-alive. |
def set_full_width(self, flag=True, clear=True):
"""
Enables FullWidthSelection (the selection does not stops at after the
character instead it goes up to the right side of the widget).
:param flag: True to use full width selection.
:type flag: bool
:param clear: True t... | Enables FullWidthSelection (the selection does not stops at after the
character instead it goes up to the right side of the widget).
:param flag: True to use full width selection.
:type flag: bool
:param clear: True to clear any previous selection. Default is True.
:type clear:... |
def main(argv=None):
"""Main entry point for the cdstar CLI."""
args = docopt(__doc__, version=pycdstar.__version__, argv=argv, options_first=True)
subargs = [args['<command>']] + args['<args>']
if args['<command>'] in ['help', None]:
cmd = None
if len(subargs) > 1:
cmd = CO... | Main entry point for the cdstar CLI. |
def get_info(self, url=None, thing_id=None, *args, **kwargs):
"""Look up existing items by thing_id (fullname) or url.
:param url: A url to lookup.
:param thing_id: A single thing_id, or a list of thing_ids. A thing_id
can be any one of Comment (``t1_``), Link (``t3_``), or Subreddi... | Look up existing items by thing_id (fullname) or url.
:param url: A url to lookup.
:param thing_id: A single thing_id, or a list of thing_ids. A thing_id
can be any one of Comment (``t1_``), Link (``t3_``), or Subreddit
(``t5_``) to lookup by fullname.
:returns: When a s... |
def __find_file(name, path, deep=False, partial=False):
"""
Searches for a file and returns its path upon finding it.
Searches for a file with the given `name` in the list of directory
mentioned in `path`. It also supports `deep` search (recursive) and
`partial` search (searching for files having f... | Searches for a file and returns its path upon finding it.
Searches for a file with the given `name` in the list of directory
mentioned in `path`. It also supports `deep` search (recursive) and
`partial` search (searching for files having filename matching
partially with the query) through the respectiv... |
def set_flask_metadata(app, version, repository, description,
api_version="1.0", name=None, auth=None,
route=None):
"""
Sets metadata on the application to be returned via metadata routes.
Parameters
----------
app : :class:`flask.Flask` instance
... | Sets metadata on the application to be returned via metadata routes.
Parameters
----------
app : :class:`flask.Flask` instance
Flask application for the microservice you're adding metadata to.
version: `str`
Version of your microservice.
repository: `str`
URL of the reposi... |
def user_search(auth=None, **kwargs):
'''
List users
CLI Example:
.. code-block:: bash
salt '*' keystoneng.user_list
salt '*' keystoneng.user_list domain_id=b62e76fbeeff4e8fb77073f591cf211e
'''
cloud = get_openstack_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return c... | List users
CLI Example:
.. code-block:: bash
salt '*' keystoneng.user_list
salt '*' keystoneng.user_list domain_id=b62e76fbeeff4e8fb77073f591cf211e |
def descriptions(self):
"""The description of each keyword in the rcParams dictionary"""
return {key: val[2] for key, val in six.iteritems(self.defaultParams)
if len(val) >= 3} | The description of each keyword in the rcParams dictionary |
def copy_template(template_name, copy_to, **options):
"""Copy the specified template directory to the copy_to location"""
import django_extensions
style = color_style()
ERROR = getattr(style, 'ERROR', lambda x: x)
SUCCESS = getattr(style, 'SUCCESS', lambda x: x)
template_dir = os.path.join(dja... | Copy the specified template directory to the copy_to location |
def watsonsV(Dir1, Dir2):
"""
calculates Watson's V statistic for two sets of directions
"""
counter, NumSims = 0, 500
#
# first calculate the fisher means and cartesian coordinates of each set of Directions
#
pars_1 = fisher_mean(Dir1)
pars_2 = fisher_mean(Dir2)
#
# get V statistic for these
#
... | calculates Watson's V statistic for two sets of directions |
def remove_insignificant_text_nodes(dom):
"""
For html elements that should not have text nodes inside them, remove all
whitespace. For elements that may have text, collapse multiple spaces to a
single space.
"""
nodes_to_remove = []
for node in walk_dom(dom):
if is_text(node):
... | For html elements that should not have text nodes inside them, remove all
whitespace. For elements that may have text, collapse multiple spaces to a
single space. |
def draw_figure(self, s, update_high_plots=True):
"""
Convenience function that sets current specimen to s and calculates
data for that specimen then redraws all plots.
Parameters
----------
s : specimen to set current specimen too
update_high_plots : bool which ... | Convenience function that sets current specimen to s and calculates
data for that specimen then redraws all plots.
Parameters
----------
s : specimen to set current specimen too
update_high_plots : bool which decides if high level mean plot
updates (default: False) |
def create_csi_node(self, body, **kwargs):
"""
create a CSINode
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_csi_node(body, async_req=True)
>>> result = thread.get()
... | create a CSINode
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_csi_node(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param V1beta1CSINode body: (... |
def bake(self):
"""
Bake a `rubocop` command so it's ready to execute and returns None.
:return: None
"""
self._rubocop_command = sh.rubocop.bake(
self.options,
self._tests,
_env=self.env,
_out=LOG.out,
_err=LOG.error) | Bake a `rubocop` command so it's ready to execute and returns None.
:return: None |
def eeg_add_events(raw, events_channel, conditions=None, treshold="auto", cut="higher", time_index=None, number="all", after=0, before=None, min_duration=1):
"""
Find events on a channel, convert them into an MNE compatible format, and add them to the raw data.
Parameters
----------
raw : mne.io.Ra... | Find events on a channel, convert them into an MNE compatible format, and add them to the raw data.
Parameters
----------
raw : mne.io.Raw
Raw EEG data.
events_channel : str or array
Name of the trigger channel if in the raw, or array of equal length if externally supplied.
conditio... |
def _range(self, link_map, radius):
"""
Return range of linked pages to substiture placeholder in pattern
"""
leftmost_page = max(self.first_page, (self.page - radius))
rightmost_page = min(self.last_page, (self.page + radius))
nav_items = []
# Create a link to ... | Return range of linked pages to substiture placeholder in pattern |
def list_wildcard(self, wildcard_path):
"""Yields full object URIs matching the given wildcard.
Currently only the '*' wildcard after the last path delimiter is supported.
(If we need "full" wildcard functionality we should bring in gsutil dependency with its
https://github.com/GoogleC... | Yields full object URIs matching the given wildcard.
Currently only the '*' wildcard after the last path delimiter is supported.
(If we need "full" wildcard functionality we should bring in gsutil dependency with its
https://github.com/GoogleCloudPlatform/gsutil/blob/master/gslib/wildcard_iter... |
def process_message(message, notification):
"""
Function to process a JSON message delivered from Amazon
"""
# Confirm that there are 'notificationType' and 'mail' fields in our
# message
if not set(VITAL_MESSAGE_FIELDS) <= set(message):
# At this point we're sure that it's Amazon sendin... | Function to process a JSON message delivered from Amazon |
def submit_job(pbs_script, pbs_config, pbs_vars=None):
"""Submit a userscript the scheduler."""
# Initialisation
if pbs_vars is None:
pbs_vars = {}
pbs_flags = []
pbs_queue = pbs_config.get('queue', 'normal')
pbs_flags.append('-q {queue}'.format(queue=pbs_queue))
pbs_project = pb... | Submit a userscript the scheduler. |
def remove_isolated_nodes_op(graph):
"""Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph
"""
rv = graph.copy()
nodes = list(nx.isolates(rv))
rv.remove_nodes_from(nodes)
return rv | Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.