code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def __return_json(url):
"""
Returns JSON data which is returned by querying the API service
Called by
- meaning()
- synonym()
:param url: the complete formatted url which is then queried using requests
:returns: json content being fed by the API
"""
... | Returns JSON data which is returned by querying the API service
Called by
- meaning()
- synonym()
:param url: the complete formatted url which is then queried using requests
:returns: json content being fed by the API |
def _get_warped_array(
input_file=None,
indexes=None,
dst_bounds=None,
dst_shape=None,
dst_crs=None,
resampling=None,
src_nodata=None,
dst_nodata=None
):
"""Extract a numpy array from a raster file."""
try:
return _rasterio_read(
input_file=input_file,
... | Extract a numpy array from a raster file. |
def from_xmldict(cls, xml_dict):
"""Create an `Author` from a datacite3 metadata converted by
`xmltodict`.
Parameters
----------
xml_dict : :class:`collections.OrderedDict`
A `dict`-like object mapping XML content for a single record (i.e.,
the contents o... | Create an `Author` from a datacite3 metadata converted by
`xmltodict`.
Parameters
----------
xml_dict : :class:`collections.OrderedDict`
A `dict`-like object mapping XML content for a single record (i.e.,
the contents of the ``record`` tag in OAI-PMH XML). This d... |
def estimate_size_in_bytes(cls, key, value, headers):
""" Get the upper bound estimate on the size of record
"""
return (
cls.HEADER_STRUCT.size + cls.MAX_RECORD_OVERHEAD +
cls.size_of(key, value, headers)
) | Get the upper bound estimate on the size of record |
def load(self, context):
"""Returns the plugin, if possible.
Args:
context: The TBContext flags.
Returns:
A BeholderPlugin instance or None if it couldn't be loaded.
"""
try:
# pylint: disable=g-import-not-at-top,unused-import
import tensorflow
except ImportError:
... | Returns the plugin, if possible.
Args:
context: The TBContext flags.
Returns:
A BeholderPlugin instance or None if it couldn't be loaded. |
def _http_get_json(self, url):
"""
Make an HTTP GET request to the specified URL, check that it returned a
JSON response, and returned the data parsed from that response.
Parameters
----------
url
The URL to GET.
Returns
-------
Dicti... | Make an HTTP GET request to the specified URL, check that it returned a
JSON response, and returned the data parsed from that response.
Parameters
----------
url
The URL to GET.
Returns
-------
Dictionary of data parsed from a JSON HTTP response.
... |
def list_(runas=None):
'''
List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list
'''
rubies = []
output = _rvm(['... | List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list |
def hello(self):
"""
Test pulp server connections defined in ~/.config/juicer/config.
"""
for env in self.args.environment:
juicer.utils.Log.log_info("Trying to open a connection to %s, %s ...",
env, self.connectors[env].base_url)
... | Test pulp server connections defined in ~/.config/juicer/config. |
def delete_mutating_webhook_configuration(self, name, **kwargs):
"""
delete a MutatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_mutating_webhook_configurat... | delete a MutatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_mutating_webhook_configuration(name, async_req=True)
>>> result = thread.get()
:param async_req... |
def add_instruction (self, instr):
"""
Adds the argument instruction in the list of instructions of this basic block.
Also updates the variable lists (used_variables, defined_variables)
"""
assert(isinstance(instr, Instruction))
self.instruction_list.append(instr)
... | Adds the argument instruction in the list of instructions of this basic block.
Also updates the variable lists (used_variables, defined_variables) |
def varvalu(self, varn=None):
'''
$foo
$foo.bar
$foo.bar()
$foo[0]
$foo.bar(10)
'''
self.ignore(whitespace)
if varn is None:
varn = self.varname()
varv = s_ast.VarValue(kids=[varn])
# handle derefs and calls...
... | $foo
$foo.bar
$foo.bar()
$foo[0]
$foo.bar(10) |
def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resour... | invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request |
def remove(self,
package,
shutit_pexpect_child=None,
options=None,
echo=None,
timeout=shutit_global.shutit_global_object.default_timeout,
note=None):
"""Distro-independent remove function.
Takes a package name and runs relevant remove function.... | Distro-independent remove function.
Takes a package name and runs relevant remove function.
@param package: Package to remove, which is run through package_map.
@param shutit_pexpect_child: See send()
@param options: Dict of options to pass to the remove command,
mapped by install_type.... |
def get_json_files(files, recursive=False):
"""Return a list of files to validate from `files`. If a member of `files`
is a directory, its children with a ``.json`` extension will be added to
the return value.
Args:
files: A list of file paths and/or directory paths.
recursive: If ``tru... | Return a list of files to validate from `files`. If a member of `files`
is a directory, its children with a ``.json`` extension will be added to
the return value.
Args:
files: A list of file paths and/or directory paths.
recursive: If ``true``, this will descend into any subdirectories
... |
def persist(filename):
"""
Append the digital elevation map projected (using lat lon) as variables of
the netcdf file.
Keyword arguments:
filename -- the name of a netcdf file.
"""
dem_projected = obtain_to(filename)
with nc.loader(filename) as root:
data = nc.getvar(root, 'data... | Append the digital elevation map projected (using lat lon) as variables of
the netcdf file.
Keyword arguments:
filename -- the name of a netcdf file. |
def _recover_public_key(G, order, r, s, i, e):
"""Recover a public key from a signature.
See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public
Key Recovery Operation".
http://www.secg.org/sec1-v2.pdf
"""
c = G.curve()
# 1.1 Let x = r + jn
x = r + (i // 2) * order
# 1.3 po... | Recover a public key from a signature.
See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public
Key Recovery Operation".
http://www.secg.org/sec1-v2.pdf |
def update_endpoint(self, endpoint_name, endpoint_config_name):
""" Update an Amazon SageMaker ``Endpoint`` according to the endpoint configuration specified in the request
Raise an error if endpoint with endpoint_name does not exist.
Args:
endpoint_name (str): Name of the Amazon S... | Update an Amazon SageMaker ``Endpoint`` according to the endpoint configuration specified in the request
Raise an error if endpoint with endpoint_name does not exist.
Args:
endpoint_name (str): Name of the Amazon SageMaker ``Endpoint`` to update.
endpoint_config_name (str): Nam... |
def program_global_reg(self):
"""
Send the global register to the chip.
Loads the values of self['GLOBAL_REG'] onto the chip.
Includes enabling the clock, and loading the Control (CTR)
and DAC shadow registers.
"""
self._clear_strobes()
gr_size = len(s... | Send the global register to the chip.
Loads the values of self['GLOBAL_REG'] onto the chip.
Includes enabling the clock, and loading the Control (CTR)
and DAC shadow registers. |
def find_connected_atoms(struct, tolerance=0.45, ldict=JmolNN().el_radius):
"""
Finds bonded atoms and returns a adjacency matrix of bonded atoms.
Author: "Gowoon Cheon"
Email: "gcheon@stanford.edu"
Args:
struct (Structure): Input structure
tolerance: length in angstroms used in fi... | Finds bonded atoms and returns a adjacency matrix of bonded atoms.
Author: "Gowoon Cheon"
Email: "gcheon@stanford.edu"
Args:
struct (Structure): Input structure
tolerance: length in angstroms used in finding bonded atoms. Two atoms
are considered bonded if (radius of atom 1) + ... |
def move(self, dst, **kwargs):
"""Move file to a new destination and update ``uri``."""
_fs, filename = opener.parse(self.uri)
_fs_dst, filename_dst = opener.parse(dst)
movefile(_fs, filename, _fs_dst, filename_dst, **kwargs)
self.uri = dst | Move file to a new destination and update ``uri``. |
def system_monitor_sfp_alert_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
sfp = ET.SubElement(system_monitor, "sfp")
alert = ET... | Auto Generated Code |
def get_layout(self, object):
"""Get complete layout for given object"""
layout = self.create_layout(object)
if isinstance(layout, Component):
layout = Layout(layout)
if isinstance(layout, list):
layout = Layout(*layout)
for update_layout in self.layout_... | Get complete layout for given object |
def cancel():
"""Returns a threading.Event() that will get set when SIGTERM, or
SIGINT are triggered. This can be used to cancel execution of threads.
"""
cancel = threading.Event()
def cancel_execution(signum, frame):
signame = SIGNAL_NAMES.get(signum, signum)
logger.info("Signal %... | Returns a threading.Event() that will get set when SIGTERM, or
SIGINT are triggered. This can be used to cancel execution of threads. |
def redact_image(
self,
parent,
inspect_config=None,
image_redaction_configs=None,
include_findings=None,
byte_item=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
... | Redacts potentially sensitive info from an image.
This method has limits on input size, processing time, and output size.
See https://cloud.google.com/dlp/docs/redacting-sensitive-data-images to
learn more.
When no InfoTypes or CustomInfoTypes are specified in this request, the
... |
def search(filter, # pylint: disable=C0103
dn=None, # pylint: disable=C0103
scope=None,
attrs=None,
**kwargs):
'''
Run an arbitrary LDAP query and return the results.
CLI Example:
.. code-block:: bash
salt 'ldaphost' ldap.search "filter=cn=... | Run an arbitrary LDAP query and return the results.
CLI Example:
.. code-block:: bash
salt 'ldaphost' ldap.search "filter=cn=myhost"
Return data:
.. code-block:: python
{'myhost': {'count': 1,
'results': [['cn=myhost,ou=hosts,o=acme,c=gb',
... |
def validate_v_rgb(value):
"""Validate a V_RGB value."""
if len(value) != 6:
raise vol.Invalid(
'{} is not six characters long'.format(value))
return validate_hex(value) | Validate a V_RGB value. |
def create_locks(context, network_ids, addresses):
"""Creates locks for each IP address that is null-routed.
The function creates the IP address if it is not present in the database.
"""
for address in addresses:
address_model = None
try:
address_model = _find_or_create_ad... | Creates locks for each IP address that is null-routed.
The function creates the IP address if it is not present in the database. |
def _index_verify(index_file, **extra_kwargs):
"""Populate the template and compare to documentation index file.
Used for both ``docs/index.rst`` and ``docs/index.rst.release.template``.
Args:
index_file (str): Filename to compare against.
extra_kwargs (Dict[str, str]): Over-ride for templ... | Populate the template and compare to documentation index file.
Used for both ``docs/index.rst`` and ``docs/index.rst.release.template``.
Args:
index_file (str): Filename to compare against.
extra_kwargs (Dict[str, str]): Over-ride for template arguments.
One **special** keyword is ... |
def unmark_featured(self, request, queryset):
"""
Un-Mark selected featured posts.
"""
queryset.update(featured=False)
self.message_user(
request, _('Selected entries are no longer marked as featured.')) | Un-Mark selected featured posts. |
def get_complex_and_node_state(self, hosts, services):
"""Get state , handle AND aggregation ::
* Get the worst state. 2 or max of sons (3 <=> UNKNOWN < CRITICAL <=> 2)
* Revert if it's a not node
:param hosts: host objects
:param services: service objects
:return... | Get state , handle AND aggregation ::
* Get the worst state. 2 or max of sons (3 <=> UNKNOWN < CRITICAL <=> 2)
* Revert if it's a not node
:param hosts: host objects
:param services: service objects
:return: 0, 1 or 2
:rtype: int |
def getFaxResultRN(self, CorpNum, RequestNum, UserID=None):
""" ํฉ์ค ์ ์ก๊ฒฐ๊ณผ ์กฐํ
args
CorpNum : ํ๋นํ์ ์ฌ์
์๋ฒํธ
RequestNum : ์ ์ก์์ฒญ์ ํ ๋นํ ์ ์ก์์ฒญ๋ฒํธ
UserID : ํ๋นํ์ ์์ด๋
return
ํฉ์ค์ ์ก์ ๋ณด as list
raise
PopbillException
... | ํฉ์ค ์ ์ก๊ฒฐ๊ณผ ์กฐํ
args
CorpNum : ํ๋นํ์ ์ฌ์
์๋ฒํธ
RequestNum : ์ ์ก์์ฒญ์ ํ ๋นํ ์ ์ก์์ฒญ๋ฒํธ
UserID : ํ๋นํ์ ์์ด๋
return
ํฉ์ค์ ์ก์ ๋ณด as list
raise
PopbillException |
def addSplits(self, login, tableName, splits):
"""
Parameters:
- login
- tableName
- splits
"""
self.send_addSplits(login, tableName, splits)
self.recv_addSplits() | Parameters:
- login
- tableName
- splits |
def _get_types_from_sample(result_vars, sparql_results_json):
"""Return types if homogenous within sample
Compare up to 10 rows of results to determine homogeneity.
DESCRIBE and CONSTRUCT queries, for example,
:param result_vars:
:param sparql_results_json:
"""
total_bindings = len(sparql... | Return types if homogenous within sample
Compare up to 10 rows of results to determine homogeneity.
DESCRIBE and CONSTRUCT queries, for example,
:param result_vars:
:param sparql_results_json: |
def to_key(literal_or_identifier):
''' returns string representation of this object'''
if literal_or_identifier['type'] == 'Identifier':
return literal_or_identifier['name']
elif literal_or_identifier['type'] == 'Literal':
k = literal_or_identifier['value']
if isinstance(k, float):
... | returns string representation of this object |
def fetch_and_parse(method, uri, params_prefix=None, **params):
"""Fetch the given uri and return the root Element of the response."""
doc = ElementTree.parse(fetch(method, uri, params_prefix, **params))
return _parse(doc.getroot()) | Fetch the given uri and return the root Element of the response. |
def _report_disk_stats(self):
"""Report metrics about the volume space usage"""
stats = {
'docker.data.used': None,
'docker.data.total': None,
'docker.data.free': None,
'docker.metadata.used': None,
'docker.metadata.total': None,
'd... | Report metrics about the volume space usage |
def calculate_path(self, remote_relative_path, input_type):
""" Only for used by Pulsar client, should override for managers to
enforce security and make the directory if needed.
"""
directory, allow_nested_files = self._directory_for_file_type(input_type)
return self.path_helper... | Only for used by Pulsar client, should override for managers to
enforce security and make the directory if needed. |
def _draw_text(self, pos, text, font, **kw):
"""
Remember a single drawable tuple to paint later.
"""
self.drawables.append((pos, text, font, kw)) | Remember a single drawable tuple to paint later. |
def check_index(self, key, *, index):
"""Fails the transaction if Key does not have a modify index equal to
Index
Parameters:
key (str): Key to check
index (ObjectIndex): Index ID
"""
self.append({
"Verb": "check-index",
"Key": key... | Fails the transaction if Key does not have a modify index equal to
Index
Parameters:
key (str): Key to check
index (ObjectIndex): Index ID |
def _raise_unrecoverable_error_client(self, exception):
"""
Raises an exceptions.ClientError with a message telling that the error probably comes from the client
configuration.
:param exception: Exception that caused the ClientError
:type exception: Exception
:raise excep... | Raises an exceptions.ClientError with a message telling that the error probably comes from the client
configuration.
:param exception: Exception that caused the ClientError
:type exception: Exception
:raise exceptions.ClientError |
def get_arp_output_arp_entry_ip_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_arp = ET.Element("get_arp")
config = get_arp
output = ET.SubElement(get_arp, "output")
arp_entry = ET.SubElement(output, "arp-entry")
ip_a... | Auto Generated Code |
def _spelling_pipeline(self, sources, options, personal_dict):
"""Check spelling pipeline."""
for source in self._pipeline_step(sources, options, personal_dict):
# Don't waste time on empty strings
if source._has_error():
yield Results([], source.context, source.... | Check spelling pipeline. |
def generate_sky_catalog(image, refwcs, **kwargs):
"""Build source catalog from input image using photutils.
This script borrows heavily from build_source_catalog.
The catalog returned by this function includes sources found in all chips
of the input image with the positions translated to the coordina... | Build source catalog from input image using photutils.
This script borrows heavily from build_source_catalog.
The catalog returned by this function includes sources found in all chips
of the input image with the positions translated to the coordinate frame
defined by the reference WCS `refwcs`. The s... |
def string2json(self, string):
"""Convert json into its string representation.
Used for writing outputs to markdown."""
kwargs = {
'cls': BytesEncoder, # use the IPython bytes encoder
'indent': 1,
'sort_keys': True,
'separators': (',', ': '),
... | Convert json into its string representation.
Used for writing outputs to markdown. |
def RIBSystemRouteLimitExceeded_originator_switch_info_switchIpV6Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
RIBSystemRouteLimitExceeded = ET.SubElement(config, "RIBSystemRouteLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")... | Auto Generated Code |
def _load_cell(args, cell_body):
"""Implements the BigQuery load magic used to load data from GCS to a table.
The supported syntax is:
%bq load <optional args>
Args:
args: the arguments following '%bq load'.
cell_body: optional contents of the cell interpreted as YAML or JSON.
Returns:
A ... | Implements the BigQuery load magic used to load data from GCS to a table.
The supported syntax is:
%bq load <optional args>
Args:
args: the arguments following '%bq load'.
cell_body: optional contents of the cell interpreted as YAML or JSON.
Returns:
A message about whether the load succeed... |
def _parseAttrs(self, attrsStr):
"""
Parse the attributes and values
"""
attributes = dict()
for attrStr in self.SPLIT_ATTR_COL_RE.split(attrsStr):
name, vals = self._parseAttrVal(attrStr)
if name in attributes:
raise GFF3Exception(
... | Parse the attributes and values |
def currentView(cls, parent=None):
"""
Returns the current view for the given class within a viewWidget. If
no view widget is supplied, then a blank view is returned.
:param viewWidget | <projexui.widgets.xviewwidget.XViewWidget> || None
:return <XView... | Returns the current view for the given class within a viewWidget. If
no view widget is supplied, then a blank view is returned.
:param viewWidget | <projexui.widgets.xviewwidget.XViewWidget> || None
:return <XView> || None |
def retrieve_activity_profile(self, activity, profile_id):
"""Retrieve activity profile with the specified parameters
:param activity: Activity object of the desired activity profile
:type activity: :class:`tincan.activity.Activity`
:param profile_id: UUID of the desired profile
... | Retrieve activity profile with the specified parameters
:param activity: Activity object of the desired activity profile
:type activity: :class:`tincan.activity.Activity`
:param profile_id: UUID of the desired profile
:type profile_id: str | unicode
:return: LRS Response object ... |
def parse_setup(raw_frames, destination_frame=None, header=0, separator=None, column_names=None,
column_types=None, na_strings=None, skipped_columns=None, custom_non_data_line_markers=None):
"""
Retrieve H2O's best guess as to what the structure of the data file is.
During parse setup, the ... | Retrieve H2O's best guess as to what the structure of the data file is.
During parse setup, the H2O cluster will make several guesses about the attributes of
the data. This method allows a user to perform corrective measures by updating the
returning dictionary from this method. This dictionary is then fed... |
def getTrackedDeviceIndexForControllerRole(self, unDeviceType):
"""Returns the device index associated with a specific role, for example the left hand or the right hand. This function is deprecated in favor of the new IVRInput system."""
fn = self.function_table.getTrackedDeviceIndexForControllerRole
... | Returns the device index associated with a specific role, for example the left hand or the right hand. This function is deprecated in favor of the new IVRInput system. |
def start(self):
"""
Start all the processes
"""
Global.LOGGER.info("starting the flow manager")
self._start_actions()
self._start_message_fetcher()
Global.LOGGER.debug("flow manager started") | Start all the processes |
def header_canonical(self, header_name):
"""Translate HTTP headers to Django header names."""
# Translate as stated in the docs:
# https://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.META
header_name = header_name.lower()
if header_name == 'content... | Translate HTTP headers to Django header names. |
def escape(s, quote=False):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences. If
the optional flag `quote` is `True`, the quotation mark character is
also translated.
There is a special handling for `None` which escapes to an empty string.
:param s: the string to escape.
... | Replace special characters "&", "<" and ">" to HTML-safe sequences. If
the optional flag `quote` is `True`, the quotation mark character is
also translated.
There is a special handling for `None` which escapes to an empty string.
:param s: the string to escape.
:param quote: set to true to also e... |
def read_function(data, window, ij, g_args):
"""Takes an array, and sets any value above the mean to the max, the rest to 0"""
output = (data[0] > numpy.mean(data[0])).astype(data[0].dtype) * data[0].max()
return output | Takes an array, and sets any value above the mean to the max, the rest to 0 |
def download_album_by_id(self, album_id, album_name):
"""Download a album by its name.
:params album_id: album id.
:params album_name: album name.
"""
try:
# use old api
songs = self.crawler.get_album_songs(album_id)
except RequestException as ex... | Download a album by its name.
:params album_id: album id.
:params album_name: album name. |
def granularity_to_time(s):
"""convert a named granularity into seconds.
get value in seconds for named granularities: M1, M5 ... H1 etc.
>>> print(granularity_to_time("M5"))
300
"""
mfact = {
'S': 1,
'M': 60,
'H': 3600,
'D': 86400,
'W': 604800,
}
... | convert a named granularity into seconds.
get value in seconds for named granularities: M1, M5 ... H1 etc.
>>> print(granularity_to_time("M5"))
300 |
def add_inverse_query(self, key_val={}):
"""
Add an es_dsl inverse query object to the es_dsl Search object
:param key_val: a key-value pair(dict) containing the query to be added to the search object
:returns: self, which allows the method to be chainable with the other methods
... | Add an es_dsl inverse query object to the es_dsl Search object
:param key_val: a key-value pair(dict) containing the query to be added to the search object
:returns: self, which allows the method to be chainable with the other methods |
def route_election(self, election):
"""
Legislative or executive office?
"""
if (
election.election_type.slug == ElectionType.GENERAL
or ElectionType.GENERAL_RUNOFF
):
self.bootstrap_general_election(election)
elif election.race.special... | Legislative or executive office? |
def get_network_attributegroup_items(network_id, **kwargs):
"""
Get all the group items in a network
"""
user_id=kwargs.get('user_id')
net_i = _get_network(network_id)
net_i.check_read_permission(user_id)
group_items_i = db.DBSession.query(AttrGroupItem).filter(
... | Get all the group items in a network |
def list_names():
""" List all known color names. """
names = get_all_names()
# This is 375 right now. Probably won't ever change, but I'm not sure.
nameslen = len(names)
print('\nListing {} names:\n'.format(nameslen))
# Using 3 columns of names, still alphabetically sorted from the top down.
... | List all known color names. |
def _set_ospf(self, v, load=False):
"""
Setter method for ospf, mapped from YANG variable /rbridge_id/router/ospf (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ospf is considered as a private
method. Backends looking to populate this variable should
do s... | Setter method for ospf, mapped from YANG variable /rbridge_id/router/ospf (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ospf is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_ospf() directly. |
def system_find_users(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /system/findUsers API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method%3A-%2Fsystem%2FfindUsers
"""
return DXHTTPRequest('/system/findUsers', input_params, always_ret... | Invokes the /system/findUsers API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method%3A-%2Fsystem%2FfindUsers |
def from_dict(cls, d, ignore=()):
"""Create an instance from a serialized version of cls
Args:
d(dict): Endpoints of cls to set
ignore(tuple): Keys to ignore
Returns:
Instance of this class
"""
filtered = {}
for k, v in d.items():
... | Create an instance from a serialized version of cls
Args:
d(dict): Endpoints of cls to set
ignore(tuple): Keys to ignore
Returns:
Instance of this class |
def try_checkpoint_metadata(self, trial):
"""Checkpoints metadata.
Args:
trial (Trial): Trial to checkpoint.
"""
if trial._checkpoint.storage == Checkpoint.MEMORY:
logger.debug("Not saving data for trial w/ memory checkpoint.")
return
try:
... | Checkpoints metadata.
Args:
trial (Trial): Trial to checkpoint. |
def parse_url(self) -> RequestUrl:
"""
่ทๅurl่งฃๆๅฏน่ฑก
"""
if self._URL is None:
current_url = b"%s://%s%s" % (
encode_str(self.schema),
encode_str(self.host),
self._current_url
)
self._URL = RequestUrl(current... | ่ทๅurl่งฃๆๅฏน่ฑก |
def _internal_network_removed(self, ri, port, ex_gw_port):
"""Remove an internal router port
Check to see if this is the last port to be removed for
a given network scoped by a VRF (note: there can be
different mappings between VRFs and networks -- 1-to-1,
1-to-n, n-to-1, n-to-n... | Remove an internal router port
Check to see if this is the last port to be removed for
a given network scoped by a VRF (note: there can be
different mappings between VRFs and networks -- 1-to-1,
1-to-n, n-to-1, n-to-n -- depending on the configuration
and workflow used). If it i... |
def pvwatts_ac(pdc, pdc0, eta_inv_nom=0.96, eta_inv_ref=0.9637):
r"""
Implements NREL's PVWatts inverter model [1]_.
.. math::
\eta = \frac{\eta_{nom}}{\eta_{ref}} (-0.0162\zeta - \frac{0.0059}{\zeta} + 0.9858)
.. math::
P_{ac} = \min(\eta P_{dc}, P_{ac0})
where :math:`\zeta=P_{... | r"""
Implements NREL's PVWatts inverter model [1]_.
.. math::
\eta = \frac{\eta_{nom}}{\eta_{ref}} (-0.0162\zeta - \frac{0.0059}{\zeta} + 0.9858)
.. math::
P_{ac} = \min(\eta P_{dc}, P_{ac0})
where :math:`\zeta=P_{dc}/P_{dc0}` and :math:`P_{dc0}=P_{ac0}/\eta_{nom}`.
Parameters
... |
def find_elb_dns_zone_id(name='', env='dev', region='us-east-1'):
"""Get an application's AWS elb dns zone id.
Args:
name (str): ELB name
env (str): Environment/account of ELB
region (str): AWS Region
Returns:
str: elb DNS zone ID
"""
LOG.info('Find %s ELB DNS Zone... | Get an application's AWS elb dns zone id.
Args:
name (str): ELB name
env (str): Environment/account of ELB
region (str): AWS Region
Returns:
str: elb DNS zone ID |
def zeroize():
'''
Resets the device to default factory settings
CLI Example:
.. code-block:: bash
salt 'device_name' junos.zeroize
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cli('request system zeroize')
ret['message'] = 'Com... | Resets the device to default factory settings
CLI Example:
.. code-block:: bash
salt 'device_name' junos.zeroize |
def get_private_name(self, f):
""" get private protected name of an attribute
:param str f: name of the private attribute to be accessed.
"""
f = self.__swagger_rename__[f] if f in self.__swagger_rename__.keys() else f
return '_' + self.__class__.__name__ + '__' + f | get private protected name of an attribute
:param str f: name of the private attribute to be accessed. |
def _str(obj):
"""Show nicely the generic object received."""
values = []
for name in obj._attribs:
val = getattr(obj, name)
if isinstance(val, str):
val = repr(val)
val = str(val) if len(str(val)) < 10 else "(...)"
values.append((name, val))
values = ", ".joi... | Show nicely the generic object received. |
def get_earth_radii(self):
"""Get earth radii from prologue
Returns:
Equatorial radius, polar radius [m]
"""
earth_model = self.prologue['GeometricProcessing']['EarthModel']
a = earth_model['EquatorialRadius'] * 1000
b = (earth_model['NorthPolarRadius'] +
... | Get earth radii from prologue
Returns:
Equatorial radius, polar radius [m] |
def has(self, url, xpath=None):
"""Check if a URL (and xpath) exists in the cache
If DB has not been initialized yet, returns ``False`` for any URL.
Args:
url (str): If given, clear specific item only. Otherwise remove the DB file.
xpath (str): xpath to search (may be `... | Check if a URL (and xpath) exists in the cache
If DB has not been initialized yet, returns ``False`` for any URL.
Args:
url (str): If given, clear specific item only. Otherwise remove the DB file.
xpath (str): xpath to search (may be ``None``)
Returns:
bool... |
def _values_of_same_type(self, val1, val2):
"""Checks if two values agree in type.
The sparse parameter is less restrictive than the parameter. If both values
are sparse matrices they are considered to be of same type
regardless of their size and values they contain.
"""
... | Checks if two values agree in type.
The sparse parameter is less restrictive than the parameter. If both values
are sparse matrices they are considered to be of same type
regardless of their size and values they contain. |
def db_open(cls, impl, working_dir):
"""
Open a connection to our chainstate db
"""
path = config.get_snapshots_filename(impl, working_dir)
return cls.db_connect(path) | Open a connection to our chainstate db |
def tf_loss_per_instance(self, states, internals, actions, terminal, reward,
next_states, next_internals, update, reference=None):
"""
Creates the TensorFlow operations for calculating the loss per batch instance.
Args:
states: Dict of state tensors.
... | Creates the TensorFlow operations for calculating the loss per batch instance.
Args:
states: Dict of state tensors.
internals: Dict of prior internal state tensors.
actions: Dict of action tensors.
terminal: Terminal boolean tensor.
reward: Reward ten... |
def track(self, tracking_number):
"Track a UPS package by number. Returns just a delivery date."
resp = self.send_request(tracking_number)
return self.parse_response(resp) | Track a UPS package by number. Returns just a delivery date. |
def add_quasi_dipole_coordinates(inst, glat_label='glat', glong_label='glong',
alt_label='alt'):
"""
Uses Apexpy package to add quasi-dipole coordinates to instrument object.
The Quasi-Dipole coordinate system includes both the tilt and offset of the
geomag... | Uses Apexpy package to add quasi-dipole coordinates to instrument object.
The Quasi-Dipole coordinate system includes both the tilt and offset of the
geomagnetic field to calculate the latitude, longitude, and local time
of the spacecraft with respect to the geomagnetic field.
This system is ... |
def string_to_sign(self):
"""
The AWS SigV4 string being signed.
"""
return (AWS4_HMAC_SHA256 + "\n" +
self.request_timestamp + "\n" +
self.credential_scope + "\n" +
sha256(self.canonical_request.encode("utf-8")).hexdigest()) | The AWS SigV4 string being signed. |
def null(alphabet):
'''
An FSM accepting nothing (not even the empty string). This is
demonstrates that this is possible, and is also extremely useful
in some situations
'''
return fsm(
alphabet = alphabet,
states = {0},
initial = 0,
finals = set(),
map = {
0: dict([(symbol, 0) for symbo... | An FSM accepting nothing (not even the empty string). This is
demonstrates that this is possible, and is also extremely useful
in some situations |
def _get_number_of_slices(self, slice_type):
"""
Get the number of slices in a certain direction
"""
if slice_type == SliceType.AXIAL:
return self.dimensions[self.axial_orientation.normal_component]
elif slice_type == SliceType.SAGITTAL:
return self.dimens... | Get the number of slices in a certain direction |
def create_pth():
"""
Create the default PTH file
:return:
"""
if prefix == '/usr':
print("Not creating PTH in real prefix: %s" % prefix)
return False
with open(vext_pth, 'w') as f:
f.write(DEFAULT_PTH_CONTENT)
return True | Create the default PTH file
:return: |
def delist(values):
"""Reduce lists of zero or one elements to individual values."""
assert isinstance(values, list)
if not values:
return None
elif len(values) == 1:
return values[0]
return values | Reduce lists of zero or one elements to individual values. |
def bootstrap_vi(version=None, venvargs=None):
'''
Bootstrap virtualenv into current directory
:param str version: Virtualenv version like 13.1.0 or None for latest version
:param list venvargs: argv list for virtualenv.py or None for default
'''
if not version:
version = get_latest_vir... | Bootstrap virtualenv into current directory
:param str version: Virtualenv version like 13.1.0 or None for latest version
:param list venvargs: argv list for virtualenv.py or None for default |
def rgb_color_picker(obj, min_luminance=None, max_luminance=None):
"""Modified version of colour.RGB_color_picker"""
color_value = int.from_bytes(
hashlib.md5(str(obj).encode('utf-8')).digest(),
'little',
) % 0xffffff
color = Color(f'#{color_value:06x}')
if min_luminance and color.ge... | Modified version of colour.RGB_color_picker |
def pending_items(self) -> Iterable[Tuple[bytes, bytes]]:
"""
A tuple of (key, value) pairs for every key that has been updated.
Like :meth:`pending_keys()`, this does not return any deleted keys.
"""
for key, value in self._changes.items():
if value is not DELETED:
... | A tuple of (key, value) pairs for every key that has been updated.
Like :meth:`pending_keys()`, this does not return any deleted keys. |
def cmp_ast(node1, node2):
'''
Compare if two nodes are equal.
'''
if type(node1) != type(node2):
return False
if isinstance(node1, (list, tuple)):
if len(node1) != len(node2):
return False
for left, right in zip(node1, node2):
if not cmp_ast(left, ... | Compare if two nodes are equal. |
def createResourceMapFromStream(in_stream, base_url=d1_common.const.URL_DATAONE_ROOT):
"""Create a simple OAI-ORE Resource Map with one Science Metadata document and any
number of Science Data objects, using a stream of PIDs.
Args:
in_stream:
The first non-blank line is the PID of the resourc... | Create a simple OAI-ORE Resource Map with one Science Metadata document and any
number of Science Data objects, using a stream of PIDs.
Args:
in_stream:
The first non-blank line is the PID of the resource map itself. Second line is
the science metadata PID and remaining lines are science ... |
def tab(tab_name, element_list=None, section_list=None):
"""
Returns a dictionary representing a new tab to display elements.
This can be thought of as a simple container for displaying multiple
types of information.
Args:
tab_name: The title to display
element_list: The list of ele... | Returns a dictionary representing a new tab to display elements.
This can be thought of as a simple container for displaying multiple
types of information.
Args:
tab_name: The title to display
element_list: The list of elements to display. If a single element is
given ... |
def output_datacenter(gandi, datacenter, output_keys, justify=14):
""" Helper to output datacenter information."""
output_generic(gandi, datacenter, output_keys, justify)
if 'dc_name' in output_keys:
output_line(gandi, 'datacenter', datacenter['name'], justify)
if 'status' in output_keys:
... | Helper to output datacenter information. |
def delete_wallet(self, wallet_name):
"""Delete a wallet.
@param the name of the wallet.
@return a success string from the plans server.
@raise ServerError via make_request.
"""
return make_request(
'{}wallet/{}'.format(self.url, wallet_name),
met... | Delete a wallet.
@param the name of the wallet.
@return a success string from the plans server.
@raise ServerError via make_request. |
def get_element_by_name(self, el_name, el_idx=0):
"""
Args:
el_name : str
Name of element to get.
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same name.
Returns:
element : The selected element.
... | Args:
el_name : str
Name of element to get.
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same name.
Returns:
element : The selected element. |
def p_string_literal(self, p):
"""string_literal : STRING"""
p[0] = self.asttypes.String(p[1])
p[0].setpos(p) | string_literal : STRING |
def format_csv(self, delim=',', qu='"'):
"""
Prepares the data in CSV format
"""
res = qu + self.name + qu + delim
if self.data:
for d in self.data:
res += qu + str(d) + qu + delim
return res + '\n' | Prepares the data in CSV format |
def set_config(self, config):
"""Set (replace) the configuration for the session.
Args:
config: Configuration object
"""
with self._conn:
self._conn.execute("DELETE FROM config")
self._conn.execute('INSERT INTO config VALUES(?)',
... | Set (replace) the configuration for the session.
Args:
config: Configuration object |
def joint_sfs(dac1, dac2, n1=None, n2=None):
"""Compute the joint site frequency spectrum between two populations.
Parameters
----------
dac1 : array_like, int, shape (n_variants,)
Derived allele counts for the first population.
dac2 : array_like, int, shape (n_variants,)
Derived al... | Compute the joint site frequency spectrum between two populations.
Parameters
----------
dac1 : array_like, int, shape (n_variants,)
Derived allele counts for the first population.
dac2 : array_like, int, shape (n_variants,)
Derived allele counts for the second population.
n1, n2 : ... |
def store_disorder(self, sc=None, force_rerun=False):
"""Wrapper for _store_disorder"""
log.info('Loading sequences to reference GEM-PRO...')
from random import shuffle
g_ids = [g.id for g in self.reference_gempro.functional_genes]
shuffle(g_ids)
def _store_disorder_sc(g... | Wrapper for _store_disorder |
def MultimodeCombine(pupils):
"""
Return the instantaneous coherent fluxes and photometric fluxes for a
multiway multimode combiner (no spatial filtering)
"""
fluxes=[np.vdot(pupils[i],pupils[i]).real for i in range(len(pupils))]
coherentFluxes=[np.vdot(pupils[i],pupils[j])
f... | Return the instantaneous coherent fluxes and photometric fluxes for a
multiway multimode combiner (no spatial filtering) |
def parse_val(cfg,section,option):
"""extract a single value from .cfg"""
vals = parse_vals(cfg,section,option)
if len(vals)==0:
return ''
else:
assert len(vals)==1, (section, option, vals, type(vals))
return vals[0] | extract a single value from .cfg |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.