code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def format_citations(zid, url='https://zenodo.org/', hits=10, tag_prefix='v'):
"""Query and format a citations page from Zenodo entries
Parameters
----------
zid : `int`, `str`
the Zenodo ID of the target record
url : `str`, optional
the base URL of the Zenodo host, defaults to ``h... | Query and format a citations page from Zenodo entries
Parameters
----------
zid : `int`, `str`
the Zenodo ID of the target record
url : `str`, optional
the base URL of the Zenodo host, defaults to ``https://zenodo.org``
hist : `int`, optional
the maximum number of hits to ... |
def convert_dotted(params):
""" Convert dotted keys in :params: dictset to a nested dictset.
E.g. {'settings.foo': 'bar'} -> {'settings': {'foo': 'bar'}}
"""
if not isinstance(params, dictset):
params = dictset(params)
dotted_items = {k: v for k, v in params.items()... | Convert dotted keys in :params: dictset to a nested dictset.
E.g. {'settings.foo': 'bar'} -> {'settings': {'foo': 'bar'}} |
def reconstruct_from_shape(self, shape, optimize=False):
"""
Shape is a tuple that may contain integers, shape symbols (tf, keras, theano) and UnknownSize (keras, mxnet)
known axes can be integers or symbols, but not Nones
"""
axes_lengths = list(self.elementary_axes_lengths)
... | Shape is a tuple that may contain integers, shape symbols (tf, keras, theano) and UnknownSize (keras, mxnet)
known axes can be integers or symbols, but not Nones |
def execute(self, *args, **kwargs):
"""Analogous to :any:`sqlite3.Cursor.execute`
:returns: self
"""
with self:
self._cursor.execute(*args, **kwargs) | Analogous to :any:`sqlite3.Cursor.execute`
:returns: self |
def _general_error_handler(http_error):
''' Simple error handler for azure.'''
message = str(http_error)
if http_error.respbody is not None:
message += '\n' + http_error.respbody.decode('utf-8-sig')
raise AzureHttpError(message, http_error.status) | Simple error handler for azure. |
def selected_exercise(func):
"""
Passes the selected exercise as the first argument to func.
"""
@wraps(func)
def inner(*args, **kwargs):
exercise = Exercise.get_selected()
return func(exercise, *args, **kwargs)
return inner | Passes the selected exercise as the first argument to func. |
def fill_blind_pores(im):
r"""
Fills all pores that are not connected to the edges of the image.
Parameters
----------
im : ND-array
The image of the porous material
Returns
-------
image : ND-array
A version of ``im`` but with all the disconnected pores removed.
S... | r"""
Fills all pores that are not connected to the edges of the image.
Parameters
----------
im : ND-array
The image of the porous material
Returns
-------
image : ND-array
A version of ``im`` but with all the disconnected pores removed.
See Also
--------
find_... |
def optimize(self, objective_fct, iterations=None, min_iterations=1,
args=(), verb_disp=None, logger=None, call_back=None):
"""find minimizer of `objective_fct`.
CAVEAT: the return value for `optimize` has changed to ``self``.
Arguments
---------
`objectiv... | find minimizer of `objective_fct`.
CAVEAT: the return value for `optimize` has changed to ``self``.
Arguments
---------
`objective_fct`
function be to minimized
`iterations`
number of (maximal) iterations, while ``not self.stop()``
... |
def exprvar(name, index=None):
r"""Return a unique Expression variable.
A Boolean *variable* is an abstract numerical quantity that may assume any
value in the set :math:`B = \{0, 1\}`.
The ``exprvar`` function returns a unique Boolean variable instance
represented by a logic expression.
Variab... | r"""Return a unique Expression variable.
A Boolean *variable* is an abstract numerical quantity that may assume any
value in the set :math:`B = \{0, 1\}`.
The ``exprvar`` function returns a unique Boolean variable instance
represented by a logic expression.
Variable instances may be used to symboli... |
def position_fingerprint(
word, n_bits=16, most_common=MOST_COMMON_LETTERS_CG, bits_per_letter=3
):
"""Return the position fingerprint.
This is a wrapper for :py:meth:`Position.fingerprint`.
Parameters
----------
word : str
The word to fingerprint
n_bits : int
Number of bit... | Return the position fingerprint.
This is a wrapper for :py:meth:`Position.fingerprint`.
Parameters
----------
word : str
The word to fingerprint
n_bits : int
Number of bits in the fingerprint returned
most_common : list
The most common tokens in the target language, ord... |
def getByteStatistic(self, wanInterfaceId=1, timeout=1):
"""Execute GetTotalBytesSent&GetTotalBytesReceived actions to get WAN statistics.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: a tuple of two ... | Execute GetTotalBytesSent&GetTotalBytesReceived actions to get WAN statistics.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: a tuple of two values, total bytes sent and total bytes received
:rtype: li... |
def run_scratch(self, path_to_scratch, num_cores=1, outname=None, outdir=None, force_rerun=False):
"""Run SCRATCH on the sequence_file that was loaded into the class.
Args:
path_to_scratch: Path to the SCRATCH executable, run_SCRATCH-1D_predictors.sh
outname: Prefix to name the ... | Run SCRATCH on the sequence_file that was loaded into the class.
Args:
path_to_scratch: Path to the SCRATCH executable, run_SCRATCH-1D_predictors.sh
outname: Prefix to name the output files
outdir: Directory to store the output files
force_rerun: Flag to force re... |
def from_df(cls, df):
"""Creates an OrbitPopulation from a DataFrame.
:param df:
:class:`pandas.DataFrame` object. Must contain the following
columns: ``['M1','M2','P','ecc','mean_anomaly','obsx','obsy','obsz']``,
i.e., as what is accessed via :attr:`OrbitPopulation... | Creates an OrbitPopulation from a DataFrame.
:param df:
:class:`pandas.DataFrame` object. Must contain the following
columns: ``['M1','M2','P','ecc','mean_anomaly','obsx','obsy','obsz']``,
i.e., as what is accessed via :attr:`OrbitPopulation.dataframe`.
:return:
... |
def _htmlify_text(self, s):
"""Make text HTML-friendly."""
colored = self._handle_ansi_color_codes(html.escape(s))
return linkify(self._buildroot, colored, self._linkify_memo).replace('\n', '</br>') | Make text HTML-friendly. |
def flush(self):
"""
Remove all items from the cache.
"""
if os.path.isdir(self._directory):
for root, dirs, files in os.walk(self._directory, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name ... | Remove all items from the cache. |
def sru(x,
num_layers=2,
activation=None,
initial_state=None,
name=None,
reuse=None):
"""SRU cell as in https://arxiv.org/abs/1709.02755.
As defined in the paper:
(1) x'_t = W x_t
(2) f_t = sigmoid(Wf x_t + bf)
(3) r_t = sigmoid(Wr x_t + br)
(4) c_t = f_t * c_{t-1} +... | SRU cell as in https://arxiv.org/abs/1709.02755.
As defined in the paper:
(1) x'_t = W x_t
(2) f_t = sigmoid(Wf x_t + bf)
(3) r_t = sigmoid(Wr x_t + br)
(4) c_t = f_t * c_{t-1} + (1 - f_t) * x'_t
(5) h_t = r_t * activation(c_t) + (1 - r_t) * x_t
This version uses functional ops to be faster on GPUs with... |
def as_dict(self, cache=None, fetch=True):
"""Return torrent properties as a dictionary.
Set the cache flag to False to disable the cache. On the other hand,
set the fetch flag to False to avoid fetching data if it's not cached.
"""
if not self._fetched and fetch:
i... | Return torrent properties as a dictionary.
Set the cache flag to False to disable the cache. On the other hand,
set the fetch flag to False to avoid fetching data if it's not cached. |
def get_site_model(oqparam):
"""
Convert the NRML file into an array of site parameters.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
an array with fields lon, lat, vs30, ...
"""
req_site_params = get_gsim_lt(oqparam).req_site_params
... | Convert the NRML file into an array of site parameters.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
an array with fields lon, lat, vs30, ... |
def rpc(self, request, args):
"""RPC
:param request:
:args ???:
"""
if request.method != 'POST':
return self.error(405, request)
payload = request.get_data(as_text=True) or '{}'
request_method = request.args.get('method')
if not request_metho... | RPC
:param request:
:args ???: |
def validate_fields_only_with_permissions(self, val, caller_permissions):
"""
To pass field validation, no required field should be missing.
This method assumes that the contents of each field have already been
validated on assignment, so it's merely a presence check.
Should only... | To pass field validation, no required field should be missing.
This method assumes that the contents of each field have already been
validated on assignment, so it's merely a presence check.
Should only be called for callers with extra permissions. |
def from_pyfile(self, filename: str, silent: bool=False) -> None:
"""Load the configuration from a Python cfg or py file.
See Python's ConfigParser docs for details on the cfg format.
It is a common practice to load the defaults from the source
using the :meth:`from_object` and then ove... | Load the configuration from a Python cfg or py file.
See Python's ConfigParser docs for details on the cfg format.
It is a common practice to load the defaults from the source
using the :meth:`from_object` and then override with a cfg or
py file, for example
.. code-block:: pyt... |
def enroll(self, uuid, organization, from_date=MIN_PERIOD_DATE, to_date=MAX_PERIOD_DATE,
merge=False):
"""Enroll a unique identity in an organization.
This method adds a new relationship between the unique identity,
identified by <uuid>, and <organization>. Both entities must exi... | Enroll a unique identity in an organization.
This method adds a new relationship between the unique identity,
identified by <uuid>, and <organization>. Both entities must exist
on the registry before creating the new enrollment.
The period of the enrollment can be given with the parame... |
def _copy_listed(self: T, names) -> T:
"""Create a new Dataset with the listed variables from this dataset and
the all relevant coordinates. Skips all validation.
"""
variables = OrderedDict() # type: OrderedDict[Any, Variable]
coord_names = set()
indexes = OrderedDict()... | Create a new Dataset with the listed variables from this dataset and
the all relevant coordinates. Skips all validation. |
def get_group_policy(self, group_name, policy_name):
"""
Retrieves the specified policy document for the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type policy_name: string
:param policy_name: The p... | Retrieves the specified policy document for the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type policy_name: string
:param policy_name: The policy document to get. |
def lharmonicmean (inlist):
"""
Calculates the harmonic mean of the values in the passed list.
That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list.
Usage: lharmonicmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + 1.0/item
return len(inlist) / sum | Calculates the harmonic mean of the values in the passed list.
That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list.
Usage: lharmonicmean(inlist) |
def printf(format, *args):
"""Format args with the first argument as format string, and write.
Return the last arg, or format itself if there are no args."""
sys.stdout.write(str(format) % args)
return if_(args, lambda: args[-1], lambda: format) | Format args with the first argument as format string, and write.
Return the last arg, or format itself if there are no args. |
def get_setter(cls, prop_name, # @NoSelf
user_setter=None, setter_takes_name=False,
user_getter=None, getter_takes_name=False):
"""Similar to get_getter, but for setting property
values. If user_getter is specified, that it may be used to
get the old value... | Similar to get_getter, but for setting property
values. If user_getter is specified, that it may be used to
get the old value of the property before setting it (this
is the case in some derived classes' implementation). if
getter_takes_name is True and user_getter is not None, than
... |
def load(fin, dtype=np.float32, max_vocab=None):
"""
Load word embedding file.
Args:
fin (File): File object to read. File should be open for reading ascii.
dtype (numpy.dtype): Element data type to use for the array.
max_vocab (int): Number of vocabulary to read.
Returns:
... | Load word embedding file.
Args:
fin (File): File object to read. File should be open for reading ascii.
dtype (numpy.dtype): Element data type to use for the array.
max_vocab (int): Number of vocabulary to read.
Returns:
numpy.ndarray: Word embedding representation vectors
... |
def make_article_info_correspondences(self, article_info_div):
"""
Articles generally provide a first contact, typically an email address
for one of the authors. This will supply that content.
"""
corresps = self.article.root.xpath('./front/article-meta/author-notes/corresp')
... | Articles generally provide a first contact, typically an email address
for one of the authors. This will supply that content. |
def _expand_subsystems(self, scope_infos):
"""Add all subsystems tied to a scope, right after that scope."""
# Get non-global subsystem dependencies of the specified subsystem client.
def subsys_deps(subsystem_client_cls):
for dep in subsystem_client_cls.subsystem_dependencies_iter():
if dep.... | Add all subsystems tied to a scope, right after that scope. |
def build_instance_name(inst, obj=None):
"""Return an instance name from an instance, and set instance.path """
if obj is None:
for _ in inst.properties.values():
inst.path.keybindings.__setitem__(_.name, _.value)
return inst.path
if not isinstance(obj, list):
return buil... | Return an instance name from an instance, and set instance.path |
def close_socket(sock):
'''Shutdown and close the socket.'''
if sock:
try:
sock.shutdown(socket.SHUT_RDWR)
except Exception:
pass
try:
sock.close()
except Exception:
pass | Shutdown and close the socket. |
def _merge_wf_outputs(new, cur, parallel):
"""Merge outputs for a sub-workflow, replacing variables changed in later steps.
ignore_ids are those used internally in a sub-workflow but not exposed to subsequent steps
"""
new_ids = set([])
out = []
for v in new:
outv = {}
outv["sou... | Merge outputs for a sub-workflow, replacing variables changed in later steps.
ignore_ids are those used internally in a sub-workflow but not exposed to subsequent steps |
def run(self, input_func=_stdin_):
"""Run the sections."""
# reset question count
self.qcount = 1
for section_name in self.survey:
self.run_section(section_name, input_func) | Run the sections. |
def getDigitalID(self,num):
"""
Reads the COMTRADE ID of a given channel number.
The number to be given is the same of the COMTRADE header.
"""
listidx = self.Dn.index(num) # Get the position of the channel number.
return self.Dch_id[listidx] | Reads the COMTRADE ID of a given channel number.
The number to be given is the same of the COMTRADE header. |
def get_knowledge_category_id(self):
"""Gets the grade ``Id`` associated with the knowledge dimension.
return: (osid.id.Id) - the grade ``Id``
raise: IllegalState - ``has_knowledge_category()`` is ``false``
*compliance: mandatory -- This method must be implemented.*
"""
... | Gets the grade ``Id`` associated with the knowledge dimension.
return: (osid.id.Id) - the grade ``Id``
raise: IllegalState - ``has_knowledge_category()`` is ``false``
*compliance: mandatory -- This method must be implemented.* |
def _display_big_warning(self, content):
""" Displays a BIG warning """
print("")
print(BOLD + WARNING + "--- WARNING ---" + ENDC)
print(WARNING + content + ENDC)
print("") | Displays a BIG warning |
def data_contains_key_builder(key: str) -> NodePredicate: # noqa: D202
"""Build a filter that passes only on nodes that have the given key in their data dictionary.
:param key: A key for the node's data dictionary
"""
def data_contains_key(_: BELGraph, node: BaseEntity) -> bool:
"""Pass only ... | Build a filter that passes only on nodes that have the given key in their data dictionary.
:param key: A key for the node's data dictionary |
def get_languages_from_item(ct_item, item):
"""
Get the languages configured for the current item
:param ct_item:
:param item:
:return:
"""
try:
item_lan = TransItemLanguage.objects.filter(content_type__pk=ct_item.id, object_id=item.id).get()
... | Get the languages configured for the current item
:param ct_item:
:param item:
:return: |
def setup_signals(self, ):
"""Connect the signals with the slots to make the ui functional
:returns: None
:rtype: None
:raises: None
"""
prjlvl = self.prjbrws.get_level(0)
prjlvl.new_root.connect(self.update_browsers)
for rb in self._releasetype_button_ma... | Connect the signals with the slots to make the ui functional
:returns: None
:rtype: None
:raises: None |
def to_xml(self, xml_declaration=True):
"""
Return the contents of this verb as an XML string
:param bool xml_declaration: Include the XML declaration. Defaults to True
"""
xml = ET.tostring(self.xml()).decode('utf-8')
return '<?xml version="1.0" encoding="UTF-8"?>{}'.fo... | Return the contents of this verb as an XML string
:param bool xml_declaration: Include the XML declaration. Defaults to True |
def masters_by_queue(self, region, queue):
"""
Get the master league for a given queue.
:param string region: the region to execute this request on
:param string queue: the queue to get the master players for
:returns: LeagueListDTO
"""
url, query = LeagueA... | Get the master league for a given queue.
:param string region: the region to execute this request on
:param string queue: the queue to get the master players for
:returns: LeagueListDTO |
def check_email_status(mx_resolver, recipient_address, sender_address, smtp_timeout=10, helo_hostname=None):
"""
Checks if an email might be valid by getting the status from the SMTP server.
:param mx_resolver: MXResolver
:param recipient_address: string
:param sender_address: string
:param smt... | Checks if an email might be valid by getting the status from the SMTP server.
:param mx_resolver: MXResolver
:param recipient_address: string
:param sender_address: string
:param smtp_timeout: integer
:param helo_hostname: string
:return: dict |
def get(self, key: Any, default: Any = None) -> Any:
"""
获取 cookie 中的 value
"""
if key in self:
return self[key].value
return default | 获取 cookie 中的 value |
def _iter_candidate_groups(self, init_match, edges0, edges1):
"""Divide the edges into groups"""
# collect all end vertices0 and end vertices1 that belong to the same
# group.
sources = {}
for start_vertex0, end_vertex0 in edges0:
l = sources.setdefault(start_vertex0,... | Divide the edges into groups |
def AddBlob(self, blob_id, length):
"""Add another blob to this image using its hash.
Once a blob is added that is smaller than the chunksize we finalize the
file, since handling adding more blobs makes the code much more complex.
Args:
blob_id: rdf_objects.BlobID object.
length: int lengt... | Add another blob to this image using its hash.
Once a blob is added that is smaller than the chunksize we finalize the
file, since handling adding more blobs makes the code much more complex.
Args:
blob_id: rdf_objects.BlobID object.
length: int length of blob
Raises:
IOError: if bl... |
def disconnect(self, chassis_list):
"""Remove connection with one or more chassis.
Arguments:
chassis_list -- List of chassis (IP addresses or DNS names)
"""
self._check_session()
if not isinstance(chassis_list, (list, tuple, set, dict, frozenset)):
chassis_... | Remove connection with one or more chassis.
Arguments:
chassis_list -- List of chassis (IP addresses or DNS names) |
def cli(ctx, dname, site):
"""
Enable the <site> under the specified <domain>
"""
assert isinstance(ctx, Context)
dname = domain_parse(dname).hostname
domain = Session.query(Domain).filter(Domain.name == dname).first()
if not domain:
click.secho('No such domain: {dn}'.format(dn=dnam... | Enable the <site> under the specified <domain> |
def unzoom(self, event=None, set_bounds=True):
""" zoom out 1 level, or to full data range """
lims = None
if len(self.conf.zoom_lims) > 1:
lims = self.conf.zoom_lims.pop()
ax = self.axes
if lims is None: # auto scale
self.conf.zoom_lims = [None]
... | zoom out 1 level, or to full data range |
def item(self, current_item):
"""
Return the current item.
@param current_item: Current item
@type param: django.models
@return: Value and label of the current item
@rtype : dict
"""
return {
'value': text(getattr(current_item, self.get_fiel... | Return the current item.
@param current_item: Current item
@type param: django.models
@return: Value and label of the current item
@rtype : dict |
def all(self):
""" Returns list with all indexed partitions. """
partitions = []
for partition in self.index.searcher().documents():
partitions.append(
PartitionSearchResult(dataset_vid=partition['dataset_vid'], vid=partition['vid'], score=1))
return partition... | Returns list with all indexed partitions. |
def auth_required(*auth_methods):
"""
Decorator that protects enpoints through multiple mechanisms
Example::
@app.route('/dashboard')
@auth_required('token', 'session')
def dashboard():
return 'Dashboard'
:param auth_methods: Specified mechanisms.
"""
login_... | Decorator that protects enpoints through multiple mechanisms
Example::
@app.route('/dashboard')
@auth_required('token', 'session')
def dashboard():
return 'Dashboard'
:param auth_methods: Specified mechanisms. |
def gen_passwd(self):
'''
reseting password
'''
post_data = self.get_post_data()
userinfo = MUser.get_by_name(post_data['u'])
sub_timestamp = int(post_data['t'])
cur_timestamp = tools.timestamp()
if cur_timestamp - sub_timestamp < 600 and cur_timestamp >... | reseting password |
def add_source(self, name, src_dict, free=None, init_source=True,
save_source_maps=True, use_pylike=True,
use_single_psf=False, **kwargs):
"""Add a source to the ROI model. This function may be called
either before or after `~fermipy.gtanalysis.GTAnalysis.setup`.
... | Add a source to the ROI model. This function may be called
either before or after `~fermipy.gtanalysis.GTAnalysis.setup`.
Parameters
----------
name : str
Source name.
src_dict : dict or `~fermipy.roi_model.Source` object
Dictionary or source object def... |
def from_datetime(self, dt):
"""
generates a UUID for a given datetime
:param dt: datetime
:type dt: datetime
:return:
"""
global _last_timestamp
epoch = datetime(1970, 1, 1, tzinfo=dt.tzinfo)
offset = epoch.tzinfo.utcoffset(epoch).total_seconds(... | generates a UUID for a given datetime
:param dt: datetime
:type dt: datetime
:return: |
def cancel(self):
'''
Cancel a running workflow.
Args:
None
Returns:
None
'''
if not self.id:
raise WorkflowError('Workflow is not running. Cannot cancel.')
if self.batch_values:
self.workflow.batch_workflow_canc... | Cancel a running workflow.
Args:
None
Returns:
None |
def diagnose_embedding(emb, source, target):
"""A detailed diagnostic for minor embeddings.
This diagnostic produces a generator, which lists all issues with `emb`. The errors
are yielded in the form
ExceptionClass, arg1, arg2,...
where the arguments following the class are used to construct ... | A detailed diagnostic for minor embeddings.
This diagnostic produces a generator, which lists all issues with `emb`. The errors
are yielded in the form
ExceptionClass, arg1, arg2,...
where the arguments following the class are used to construct the exception object.
User-friendly variants of ... |
def _index_range(self, version, symbol, from_version=None, **kwargs):
"""
Tuple describing range to read from the ndarray - closed:open
"""
from_index = None
if from_version:
from_index = from_version['up_to']
return from_index, None | Tuple describing range to read from the ndarray - closed:open |
def run_evaluate(self) -> None:
"""
Overrides the base evaluation to set the value to the evaluation result of the value
expression in the schema
"""
result = None
self.eval_error = False
if self._needs_evaluation:
result = self._schema.value.evaluate(... | Overrides the base evaluation to set the value to the evaluation result of the value
expression in the schema |
def parse(value, pattern='{head}{padding}{tail} [{ranges}]'):
'''Parse *value* into a :py:class:`~clique.collection.Collection`.
Use *pattern* to extract information from *value*. It may make use of the
following keys:
* *head* - Common leading part of the collection.
* *tail* - Common tra... | Parse *value* into a :py:class:`~clique.collection.Collection`.
Use *pattern* to extract information from *value*. It may make use of the
following keys:
* *head* - Common leading part of the collection.
* *tail* - Common trailing part of the collection.
* *padding* - Padding value in ... |
def get_title(self, obj):
"""Set search entry title for object"""
search_title = self.get_model_config_value(obj, 'search_title')
if not search_title:
return super().get_title(obj)
return search_title.format(**obj.__dict__) | Set search entry title for object |
def tcp_receive(self):
"""Receive data from TCP port."""
data = self.conn.recv(self.BUFFER_SIZE)
if type(data) != str:
# Python 3 specific
data = data.decode("utf-8")
return str(data) | Receive data from TCP port. |
def compile_tilebus(files, env, outdir=None, header_only=False):
"""Given a path to a *.cdb file, process it and generate c tables and/or headers containing the information."""
if outdir is None:
dirs = env["ARCH"].build_dirs()
outdir = dirs['build']
cmdmap_c_path = os.path.join(outdir, 'c... | Given a path to a *.cdb file, process it and generate c tables and/or headers containing the information. |
def _delete(self, pos, idx):
"""
Delete the item at the given (pos, idx).
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the leaf
... | Delete the item at the given (pos, idx).
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the leaf
node to the root. For an example traversal see s... |
def image_import(infile, force):
"""Import image anchore data from a JSON file."""
ecode = 0
try:
with open(infile, 'r') as FH:
savelist = json.loads(FH.read())
except Exception as err:
anchore_print_err("could not load input file: " + str(err))
ecode = 1
if... | Import image anchore data from a JSON file. |
def convert_branch(self, old_node, new_node, ids_to_skip, comment_dict=None):
"""
Recursively walk a indicator logic tree, starting from a Indicator node.
Converts OpenIOC 1.1 Indicator/IndicatorItems to Openioc 1.0 and preserves order.
:param old_node: An Indicator node, which we walk... | Recursively walk a indicator logic tree, starting from a Indicator node.
Converts OpenIOC 1.1 Indicator/IndicatorItems to Openioc 1.0 and preserves order.
:param old_node: An Indicator node, which we walk down to convert
:param new_node: An Indicator node, which we add new IndicatorItem and In... |
def _from_dict(cls, _dict):
"""Initialize a DialogSuggestionValue object from a json dictionary."""
args = {}
if 'input' in _dict:
args['input'] = MessageInput._from_dict(_dict.get('input'))
if 'intents' in _dict:
args['intents'] = [
RuntimeIntent.... | Initialize a DialogSuggestionValue object from a json dictionary. |
def main(): # pragma: nocover
"""Return exit code of zero iff directory is not changed.
"""
p = argparse.ArgumentParser()
p.add_argument(
'directory',
help="Directory to check"
)
p.add_argument(
'--verbose', '-v', action='store_true',
help="increase verbosity"
... | Return exit code of zero iff directory is not changed. |
def fix_flags(self, flags):
"""Fixes standard TensorBoard CLI flags to parser."""
FlagsError = base_plugin.FlagsError
if flags.version_tb:
pass
elif flags.inspect:
if flags.logdir and flags.event_file:
raise FlagsError(
'Must specify either --logdir or --event_file, but n... | Fixes standard TensorBoard CLI flags to parser. |
def get_members_of_group(self, gname):
"""Get all members of a group which name is given in parameter
:param gname: name of the group
:type gname: str
:return: list of the services in the group
:rtype: list[alignak.objects.service.Service]
"""
hostgroup = self.fi... | Get all members of a group which name is given in parameter
:param gname: name of the group
:type gname: str
:return: list of the services in the group
:rtype: list[alignak.objects.service.Service] |
def dirWavFeatureExtractionNoAveraging(dirName, mt_win, mt_step, st_win, st_step):
"""
This function extracts the mid-term features of the WAVE
files of a particular folder without averaging each file.
ARGUMENTS:
- dirName: the path of the WAVE directory
- mt_win, mt_step: m... | This function extracts the mid-term features of the WAVE
files of a particular folder without averaging each file.
ARGUMENTS:
- dirName: the path of the WAVE directory
- mt_win, mt_step: mid-term window and step (in seconds)
- st_win, st_step: short-term window and step (... |
def partition(predicate, iterable):
"""Use a predicate to partition true and false entries.
Reference
---------
Python itertools documentation.
"""
t1, t2 = tee(iterable)
return filterfalse(predicate, t1), filter(predicate, t2) | Use a predicate to partition true and false entries.
Reference
---------
Python itertools documentation. |
def write_version(name=None, path=None):
"""Write the version info to ../version.json, for setup.py.
Args:
name (Optional[str]): this is for the ``write_version(name=__name__)``
below. That's one way to both follow the
``if __name__ == '__main__':`` convention but also allow for full
... | Write the version info to ../version.json, for setup.py.
Args:
name (Optional[str]): this is for the ``write_version(name=__name__)``
below. That's one way to both follow the
``if __name__ == '__main__':`` convention but also allow for full
coverage without ignoring parts of the file... |
def check_voltage(grid, mode):
""" Checks for voltage stability issues at all nodes for MV or LV grid
Parameters
----------
grid : GridDing0
Grid identifier.
mode : str
Kind of grid ('MV' or 'LV').
Returns
-------
:any:`list` of :any:`GridDing0`
List of critical... | Checks for voltage stability issues at all nodes for MV or LV grid
Parameters
----------
grid : GridDing0
Grid identifier.
mode : str
Kind of grid ('MV' or 'LV').
Returns
-------
:any:`list` of :any:`GridDing0`
List of critical nodes, sorted descending by voltage di... |
def handler(self):
"""Run the required analyses"""
printtime('Creating and populating objects', self.start)
self.populate()
printtime('Populating {} sequence profiles'.format(self.analysistype), self.start)
self.profiler()
# Annotate sequences with prokka
self.ann... | Run the required analyses |
def create(context, job_id, name, type, url, data):
"""create(context, job_id, name, type, url, data)
Create an analytic.
>>> dcictl analytic-create [OPTIONS]
:param string job-id: The job on which to attach the analytic
:param string name: Name of the analytic [required]
:param string type: ... | create(context, job_id, name, type, url, data)
Create an analytic.
>>> dcictl analytic-create [OPTIONS]
:param string job-id: The job on which to attach the analytic
:param string name: Name of the analytic [required]
:param string type: Type of the analytic [required]
:param string url: Url ... |
def _append(lst, indices, value):
"""Adds `value` to `lst` list indexed by `indices`. Will create sub lists as required.
"""
for i, idx in enumerate(indices):
# We need to loop because sometimes indices can increment by more than 1 due to missing tokens.
# Example: Sentence with no words aft... | Adds `value` to `lst` list indexed by `indices`. Will create sub lists as required. |
def _imm_merge_class(cls, parent):
'''
_imm_merge_class(imm_class, parent) updates the given immutable class imm_class to have the
appropriate attributes of its given parent class. The parents should be passed through this
function in method-resolution order.
'''
# If this is not an immutable pa... | _imm_merge_class(imm_class, parent) updates the given immutable class imm_class to have the
appropriate attributes of its given parent class. The parents should be passed through this
function in method-resolution order. |
def AuthenticateSessionId(self, username, password):
"""
Authenticate using a username and password.
The SenseApi object will store the obtained session_id internally until a call to LogoutSessionId is performed.
@param username (string) - CommonSense usern... | Authenticate using a username and password.
The SenseApi object will store the obtained session_id internally until a call to LogoutSessionId is performed.
@param username (string) - CommonSense username
@param password (string) - MD5Hash of CommonSense password
... |
def create_precursor_quant_lookup(quantdb, mzmlfn_feats, quanttype,
rttol, mztol, mztoltype):
"""Fills quant sqlite with precursor quant from:
features - generator of xml features from openms
"""
featparsermap = {'kronik': kronik_featparser,
'op... | Fills quant sqlite with precursor quant from:
features - generator of xml features from openms |
def decode(self, input, final=False):
"""Decode one chunk of the input.
:param input: A byte string.
:param final:
Indicate that no more input is available.
Must be :obj:`True` if this is the last call.
:returns: An Unicode string.
"""
decoder = ... | Decode one chunk of the input.
:param input: A byte string.
:param final:
Indicate that no more input is available.
Must be :obj:`True` if this is the last call.
:returns: An Unicode string. |
def get_customer_transitions(self, issue_id_or_key):
"""
Returns a list of transitions that customers can perform on the request
:param issue_id_or_key: str
:return:
"""
url = 'rest/servicedeskapi/request/{}/transition'.format(issue_id_or_key)
return self.get(ur... | Returns a list of transitions that customers can perform on the request
:param issue_id_or_key: str
:return: |
def processFlat(self):
"""Main process.
Returns
-------
est_idxs : np.array(N)
Estimated indeces the segment boundaries in frames.
est_labels : np.array(N-1)
Estimated labels for the segments.
"""
# Preprocess to obtain features
F =... | Main process.
Returns
-------
est_idxs : np.array(N)
Estimated indeces the segment boundaries in frames.
est_labels : np.array(N-1)
Estimated labels for the segments. |
def flatten_probas(probas, labels, ignore=None):
"""
Flattens predictions in the batch
"""
B, C, H, W = probas.size()
probas = probas.permute(0, 2, 3, 1).contiguous().view(-1, C) # B * H * W, C = P, C
labels = labels.view(-1)
if ignore is None:
return probas, labels
valid = (lab... | Flattens predictions in the batch |
def init_app(state):
"""
Prepare the Flask application for Flask-Split.
:param state: :class:`BlueprintSetupState` instance
"""
app = state.app
app.config.setdefault('SPLIT_ALLOW_MULTIPLE_EXPERIMENTS', False)
app.config.setdefault('SPLIT_DB_FAILOVER', False)
app.config.setdefault('SPLI... | Prepare the Flask application for Flask-Split.
:param state: :class:`BlueprintSetupState` instance |
def hex_color(value):
'''Accepts a hexadecimal color `value` in the format ``0xrrggbb`` and
returns an (r, g, b) tuple where 0.0 <= r, g, b <= 1.0.
'''
r = ((value >> (8 * 2)) & 255) / 255.0
g = ((value >> (8 * 1)) & 255) / 255.0
b = ((value >> (8 * 0)) & 255) / 255.0
return (r, g, b) | Accepts a hexadecimal color `value` in the format ``0xrrggbb`` and
returns an (r, g, b) tuple where 0.0 <= r, g, b <= 1.0. |
def validate_request_method_to_operation(request_method, path_definition):
"""
Given a request method, validate that the request method is valid for the
api path.
If so, return the operation definition related to this request method.
"""
try:
operation_definition = path_definition[reque... | Given a request method, validate that the request method is valid for the
api path.
If so, return the operation definition related to this request method. |
def _append_data(self, value, _file):
"""Call this function to write data contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
# binascii.b2a_base64(value) -> plistlib.Data
# binascii.a2b_base64(Data) -> val... | Call this function to write data contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file |
def run(self, job_list):
"""
Runs a job set which consists of the jobs in an iterable job list.
"""
if self._closed:
raise RuntimeError("master is closed")
return self._manager.add_job_set(job_list) | Runs a job set which consists of the jobs in an iterable job list. |
def NewFd(self, fd, URL, encoding, options):
"""Setup an xmltextReader to parse an XML from a file
descriptor. NOTE that the file descriptor will not be
closed when the reader is closed or reset. The parsing
flags @options are a combination of xmlParserOption. This
reuse... | Setup an xmltextReader to parse an XML from a file
descriptor. NOTE that the file descriptor will not be
closed when the reader is closed or reset. The parsing
flags @options are a combination of xmlParserOption. This
reuses the existing @reader xmlTextReader. |
def create_generate(kind, project, resource, offset):
"""A factory for creating `Generate` objects
`kind` can be 'variable', 'function', 'class', 'module' or
'package'.
"""
generate = eval('Generate' + kind.title())
return generate(project, resource, offset) | A factory for creating `Generate` objects
`kind` can be 'variable', 'function', 'class', 'module' or
'package'. |
def create(blocks, mode='basic', inplanes=16, divisor=4, num_classes=1000):
""" Vel factory function """
block_dict = {
'basic': BasicBlock,
'bottleneck': Bottleneck
}
def instantiate(**_):
return ResNetV2(block_dict[mode], blocks, inplanes=inplanes, divisor=divisor, num_classes... | Vel factory function |
def _pybossa_req(method, domain, id=None, payload=None, params={},
headers={'content-type': 'application/json'},
files=None):
"""
Send a JSON request.
Returns True if everything went well, otherwise it returns the status
code of the response.
"""
url = _opts['e... | Send a JSON request.
Returns True if everything went well, otherwise it returns the status
code of the response. |
def _handle_request(self, scheme, netloc, path, headers, body=None, method="GET"):
"""
Run the actual request
"""
backend_url = "{}://{}{}".format(scheme, netloc, path)
try:
response = self.http_request.request(backend_url, method=method, body=body, headers=dict(heade... | Run the actual request |
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`BumpSequence`.
"""
bump_sequence_op = Xdr.types.BumpSequenceOp(self.bump_to)
self.body.type = Xdr.const.BUMP_SEQUENCE
self.body.bumpSequenceOp = bump_sequence_op
return super... | Creates an XDR Operation object that represents this
:class:`BumpSequence`. |
def newChild(self, ns, name, content):
"""Creation of a new child element, added at the end of
@parent children list. @ns and @content parameters are
optional (None). If @ns is None, the newly created element
inherits the namespace of @parent. If @content is non None,
a c... | Creation of a new child element, added at the end of
@parent children list. @ns and @content parameters are
optional (None). If @ns is None, the newly created element
inherits the namespace of @parent. If @content is non None,
a child list containing the TEXTs and ENTITY_REFs nod... |
def update_warning(self):
"""Update the warning label, buttons state and sequence text."""
new_qsequence = self.new_qsequence
new_sequence = self.new_sequence
self.text_new_sequence.setText(
new_qsequence.toString(QKeySequence.NativeText))
conflicts = self.che... | Update the warning label, buttons state and sequence text. |
def _install(archive_filename, install_args=()):
"""Install Setuptools."""
with archive_context(archive_filename):
# installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.'... | Install Setuptools. |
def document_endpoint(endpoint):
"""Extract the full documentation dictionary from the endpoint."""
descr = clean_description(py_doc_trim(endpoint.__doc__))
docs = {
'name': endpoint._route_name,
'http_method': endpoint._http_method,
'uri': endpoint._uri,
'description': descr... | Extract the full documentation dictionary from the endpoint. |
def afx_adafactor():
"""Adafactor with recommended learning rate schedule."""
hparams = afx_adam()
hparams.optimizer = "Adafactor"
hparams.learning_rate_schedule = "rsqrt_decay"
hparams.learning_rate_warmup_steps = 10000
return hparams | Adafactor with recommended learning rate schedule. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.