positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def setViewMode( self, state = True ):
"""
Starts the view mode for moving around the scene.
"""
if self._viewMode == state:
return
self._viewMode = state
if state:
self._mainView.setDragMode( self._mainView.ScrollHandDrag )
el... | Starts the view mode for moving around the scene. |
def manifest_download(self):
'''download manifest files'''
if self.downloaders_lock.acquire(False):
if len(self.downloaders):
# there already exist downloader threads
self.downloaders_lock.release()
return
for url in ['http://firmw... | download manifest files |
def json2elem(json_data, factory=ET.Element):
"""Convert a JSON string into an Element.
Whatever Element implementation we could import will be used by
default; if you want to use something else, pass the Element class
as the factory parameter.
"""
return internal_to_elem(json.loads(json_data... | Convert a JSON string into an Element.
Whatever Element implementation we could import will be used by
default; if you want to use something else, pass the Element class
as the factory parameter. |
def passthrough_repl(self, inputstring, **kwargs):
"""Add back passthroughs."""
out = []
index = None
for c in append_it(inputstring, None):
try:
if index is not None:
if c is not None and c in nums:
index += c
... | Add back passthroughs. |
def case_study_social_link_linkedin(value):
"""
Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError
"""
parsed = parse.urlparse(value.lower())
if not parsed.netloc.endswith('link... | Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError |
def from_id(cls, id):
"""Load a `cls` entity and instantiate the Context it stores."""
from furious.context import Context
# TODO: Handle exceptions and retries here.
entity = cls.get_by_id(id)
if not entity:
raise FuriousContextNotFoundError(
"Contex... | Load a `cls` entity and instantiate the Context it stores. |
def getimage(app):
"""Get image file."""
# append source directory to TEMPLATE_PATH so template is found
srcdir = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_PATH.append(srcdir)
staticbase = '_static'
buildpath = os.path.join(app.outdir, staticbase)
try:
os.makedirs(buildpath... | Get image file. |
def get_val(source, extract=None, transform=None):
"""Extract a value from a source, transform and return it."""
if extract is None:
raw_value = source
else:
raw_value = extract(source)
if transform is None:
return raw_value
else:
return transform(raw_value) | Extract a value from a source, transform and return it. |
def count(self, *columns):
"""
Retrieve the "count" result of the query
:param columns: The columns to get
:type columns: tuple
:return: The count
:rtype: int
"""
if not columns and self.distinct_:
columns = self.columns
if not colum... | Retrieve the "count" result of the query
:param columns: The columns to get
:type columns: tuple
:return: The count
:rtype: int |
def get_networkid(vm_):
'''
Return the networkid to use, only valid for Advanced Zone
'''
networkid = config.get_cloud_config_value('networkid', vm_, __opts__)
if networkid is not None:
return networkid
else:
return False | Return the networkid to use, only valid for Advanced Zone |
def pl2nvc(plane):
"""
Return a unit normal vector and constant that define a specified plane.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pl2nvc_c.html
:param plane: A SPICE plane.
:type plane: supporttypes.Plane
:return:
A normal vector and constant defining
... | Return a unit normal vector and constant that define a specified plane.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pl2nvc_c.html
:param plane: A SPICE plane.
:type plane: supporttypes.Plane
:return:
A normal vector and constant defining
the geometric plane represen... |
def p_generate_if(self, p):
'generate_if : IF LPAREN cond RPAREN gif_true_item ELSE gif_false_item'
p[0] = IfStatement(p[3], p[5], p[7], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | generate_if : IF LPAREN cond RPAREN gif_true_item ELSE gif_false_item |
def get_instance(self, payload):
"""
Build an instance of EnvironmentInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.environment.EnvironmentInstance
:rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance... | Build an instance of EnvironmentInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.environment.EnvironmentInstance
:rtype: twilio.rest.serverless.v1.service.environment.EnvironmentInstance |
def site_is_of_motif_type(struct, n, approach="min_dist", delta=0.1, \
cutoff=10.0, thresh=None):
"""
Returns the motif type of the site with index n in structure struct;
currently featuring "tetrahedral", "octahedral", "bcc", and "cp"
(close-packed: fcc and hcp) as well as "sq... | Returns the motif type of the site with index n in structure struct;
currently featuring "tetrahedral", "octahedral", "bcc", and "cp"
(close-packed: fcc and hcp) as well as "square pyramidal" and
"trigonal bipyramidal". If the site is not recognized,
"unrecognized" is returned. If a site should be ass... |
def invert(self, src=None):
"""Calculate the inverted matrix. Return 0 if successful and replace
current one. Else return 1 and do nothing.
"""
if src is None:
dst = TOOLS._invert_matrix(self)
else:
dst = TOOLS._invert_matrix(src)
if dst[0] == 1:
... | Calculate the inverted matrix. Return 0 if successful and replace
current one. Else return 1 and do nothing. |
def merge_tasks(core_collections, sandbox_collections, id_prefix, new_tasks, batch_size=100, wipe=False):
"""Merge core and sandbox collections into a temporary collection in the sandbox.
:param core_collections: Core collection info
:type core_collections: Collections
:param sandbox_collections: Sandb... | Merge core and sandbox collections into a temporary collection in the sandbox.
:param core_collections: Core collection info
:type core_collections: Collections
:param sandbox_collections: Sandbox collection info
:type sandbox_collections: Collections |
def rm_files(path, extension):
"""
Remove all files in the given directory with the given extension
:param str path: Directory
:param str extension: File type to remove
:return none:
"""
files = list_files(extension, path)
for file in files:
if file.endswith(extension):
... | Remove all files in the given directory with the given extension
:param str path: Directory
:param str extension: File type to remove
:return none: |
def get_vm_by_name(content, name, regex=False):
'''
Get a VM by its name
'''
return get_object_by_name(content, vim.VirtualMachine, name, regex) | Get a VM by its name |
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
port=None, fatal=True,
username="testuser1", password="changeme"):
"""Establish and return a pika amqp connection to the rabbitmq service
running on a rmq juju unit.
:param sentry_un... | Establish and return a pika amqp connection to the rabbitmq service
running on a rmq juju unit.
:param sentry_unit: sentry unit pointer
:param ssl: boolean, default to False
:param port: amqp port, use defaults if None
:param fatal: boolean, default to True (raises on connect er... |
def __remove_duplicates(self, _other):
"""Remove from other items already in list."""
if not isinstance(_other, type(self)) \
and not isinstance(_other, type(list)) \
and not isinstance(_other, type([])):
other = [_other]
else:
other = list(_other)
... | Remove from other items already in list. |
def generate_item_instances(cls, items, mediawiki_api_url='https://www.wikidata.org/w/api.php', login=None,
user_agent=config['USER_AGENT_DEFAULT']):
"""
A method which allows for retrieval of a list of Wikidata items or properties. The method generates a list of
... | A method which allows for retrieval of a list of Wikidata items or properties. The method generates a list of
tuples where the first value in the tuple is the QID or property ID, whereas the second is the new instance of
WDItemEngine containing all the data of the item. This is most useful for mass retr... |
def content_sha1(context):
"""
Used by the FileContent model to automatically compute the sha1
hash of content before storing it to the database.
"""
try:
content = context.current_parameters['content']
except AttributeError:
content = context
return hashlib.sha1(encodeutils.... | Used by the FileContent model to automatically compute the sha1
hash of content before storing it to the database. |
def install_service(instance, dbhost, dbname, port):
"""Install systemd service configuration"""
_check_root()
log("Installing systemd service")
launcher = os.path.realpath(__file__).replace('manage', 'launcher')
executable = sys.executable + " " + launcher
executable += " --instance " + inst... | Install systemd service configuration |
def addBrokerList(self, aBrokerInfoList):
"""Add a broker to the broker cluster available list.
Connects to the added broker if needed."""
self.clusterAvailable.update(set(aBrokerInfoList))
# If we need another connection to a fellow broker
# TODO: only connect to a given number... | Add a broker to the broker cluster available list.
Connects to the added broker if needed. |
def create_session(self):
""" Request a new session id """
url = self.build_url(self._endpoints.get('create_session'))
response = self.con.post(url, data={'persistChanges': self.persist})
if not response:
raise RuntimeError('Could not create session as requested by the user.... | Request a new session id |
def RGB_to_XYZ(cobj, target_illuminant=None, *args, **kwargs):
"""
RGB to XYZ conversion. Expects 0-255 RGB values.
Based off of: http://www.brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html
"""
# Will contain linearized RGB channels (removed the gamma func).
linear_channels = {}
if isinst... | RGB to XYZ conversion. Expects 0-255 RGB values.
Based off of: http://www.brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html |
def guessoffset(args):
"""
%prog guessoffset fastqfile
Guess the quality offset of the fastqfile, whether 33 or 64.
See encoding schemes: <http://en.wikipedia.org/wiki/FASTQ_format>
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS...............................
..........................XXXXXXXXX... | %prog guessoffset fastqfile
Guess the quality offset of the fastqfile, whether 33 or 64.
See encoding schemes: <http://en.wikipedia.org/wiki/FASTQ_format>
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS...............................
..........................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX... |
def message_about_scripts_not_on_PATH(scripts):
# type: (Sequence[str]) -> Optional[str]
"""Determine if any scripts are not on PATH and format a warning.
Returns a warning message if one or more scripts are not on PATH,
otherwise None.
"""
if not scripts:
return None
# Group scrip... | Determine if any scripts are not on PATH and format a warning.
Returns a warning message if one or more scripts are not on PATH,
otherwise None. |
def get_notification(self, id):
"""
Return a Notification object.
:param id: The id of the notification object to return.
"""
url = self._base_url + "/3/notification/{0}".format(id)
resp = self._send_request(url)
return Notification(resp, self) | Return a Notification object.
:param id: The id of the notification object to return. |
def has_header_line(self, key, id_):
"""Return whether there is a header line with the given ID of the
type given by ``key``
:param key: The VCF header key/line type.
:param id_: The ID value to compare fore
:return: ``True`` if there is a header line starting with ``##${key}=`... | Return whether there is a header line with the given ID of the
type given by ``key``
:param key: The VCF header key/line type.
:param id_: The ID value to compare fore
:return: ``True`` if there is a header line starting with ``##${key}=``
in the VCF file having the mapping... |
def move_pos(line=1, column=1, file=sys.stdout):
""" Move the cursor to a new position. Values are 1-based, and default
to 1.
Esc[<line>;<column>H
or
Esc[<line>;<column>f
"""
move.pos(line=line, col=column).write(file=file) | Move the cursor to a new position. Values are 1-based, and default
to 1.
Esc[<line>;<column>H
or
Esc[<line>;<column>f |
def dbRestore(self, db_value, context=None):
"""
Extracts the db_value provided back from the database.
:param db_value: <variant>
:param context: <orb.Context>
:return: <variant>
"""
if isinstance(db_value, (str, unicode)) and db_value.startswith('{'):
... | Extracts the db_value provided back from the database.
:param db_value: <variant>
:param context: <orb.Context>
:return: <variant> |
def verify_edge_segments(edge_infos):
"""Verify that the edge segments in an intersection are valid.
.. note::
This is a helper used only by :func:`generic_intersect`.
Args:
edge_infos (Optional[list]): List of "edge info" lists. Each list
represents a curved polygon and contai... | Verify that the edge segments in an intersection are valid.
.. note::
This is a helper used only by :func:`generic_intersect`.
Args:
edge_infos (Optional[list]): List of "edge info" lists. Each list
represents a curved polygon and contains 3-tuples of edge index,
start ... |
def _EntryToEvent(entry, handlers, transformers):
"""Converts an APIAuditEntry to a legacy AuditEvent."""
event = rdf_events.AuditEvent(
timestamp=entry.timestamp,
user=entry.username,
action=handlers[entry.router_method_name])
for fn in transformers:
fn(entry, event)
return event | Converts an APIAuditEntry to a legacy AuditEvent. |
def remove_from_sonos_playlist(self, sonos_playlist, track, update_id=0):
"""Remove a track from a Sonos Playlist.
This is a convenience method for :py:meth:`reorder_sonos_playlist`.
Example::
device.remove_from_sonos_playlist(sonos_playlist, track=0)
Args:
son... | Remove a track from a Sonos Playlist.
This is a convenience method for :py:meth:`reorder_sonos_playlist`.
Example::
device.remove_from_sonos_playlist(sonos_playlist, track=0)
Args:
sonos_playlist
(:py:class:`~.soco.data_structures.DidlPlaylistContainer`... |
def lookup_fg_color(self, fg_color):
"""
Return the color for use in the
`windll.kernel32.SetConsoleTextAttribute` API call.
:param fg_color: Foreground as text. E.g. 'ffffff' or 'red'
"""
# Foreground.
if fg_color in FG_ANSI_COLORS:
return FG_ANSI_CO... | Return the color for use in the
`windll.kernel32.SetConsoleTextAttribute` API call.
:param fg_color: Foreground as text. E.g. 'ffffff' or 'red' |
def get_filename(request, geometry):
""" Returns filename
Returns the filename's location on disk where data is or is going to be stored.
The files are stored in the folder specified by the user when initialising OGC-type
of request. The name of the file has the following structure:
... | Returns filename
Returns the filename's location on disk where data is or is going to be stored.
The files are stored in the folder specified by the user when initialising OGC-type
of request. The name of the file has the following structure:
{service_type}_{layer}_{geometry}_{crs}_{st... |
def load_progress(self, resume_step):
""" load_progress: loads progress from restoration file
Args: resume_step (str): step at which to resume session
Returns: manager with progress from step
"""
resume_step = Status[resume_step]
progress_path = self.get_restore_p... | load_progress: loads progress from restoration file
Args: resume_step (str): step at which to resume session
Returns: manager with progress from step |
def _get_solr_type(self, field):
"""Returns the Solr type of the specified field name.
Assumes the convention of dynamic fields using an underscore + type character
code for the field name.
"""
field_type = 'string'
try:
field_type = FIELD_TYPE_CONVERSION_MA... | Returns the Solr type of the specified field name.
Assumes the convention of dynamic fields using an underscore + type character
code for the field name. |
def search(self, song_title, limit=1):
"""
根据歌曲名搜索歌曲
: params : song_title: 歌曲名
limit: 搜索数量
"""
url = "http://music.163.com/api/search/pc"
headers = {'Cookie': 'appver=1.5.2',
'Referer': 'http://music.163.com'}
payload = {'s'... | 根据歌曲名搜索歌曲
: params : song_title: 歌曲名
limit: 搜索数量 |
def eq(self, value):
"""Construct an equal to (``=``) filter.
:param value: Filter value
:return: :class:`filters.Field <filters.Field>` object
:rtype: filters.Field
"""
self.op = '='
self.negate_op = '!='
self.value = self._value(value)
return se... | Construct an equal to (``=``) filter.
:param value: Filter value
:return: :class:`filters.Field <filters.Field>` object
:rtype: filters.Field |
def set_vm_status(self, device='FLOPPY',
boot_option='BOOT_ONCE', write_protect='YES'):
"""Sets the Virtual Media drive status
It sets the boot option for virtual media device.
Note: boot option can be set only for CD device.
:param device: virual media device
... | Sets the Virtual Media drive status
It sets the boot option for virtual media device.
Note: boot option can be set only for CD device.
:param device: virual media device
:param boot_option: boot option to set on the virtual media device
:param write_protect: set the write prote... |
def get_color_scheme(name):
"""Get syntax color scheme"""
color_scheme = {}
for key in sh.COLOR_SCHEME_KEYS:
color_scheme[key] = CONF.get("appearance", "%s/%s" % (name, key))
return color_scheme | Get syntax color scheme |
def get_composite_keywords(ckw_db, fulltext, skw_spans):
"""Return a list of composite keywords bound with number of occurrences.
:param ckw_db: list of KewordToken objects
(they are supposed to be composite ones)
:param fulltext: string to search in
:param skw_spans: dictionary of a... | Return a list of composite keywords bound with number of occurrences.
:param ckw_db: list of KewordToken objects
(they are supposed to be composite ones)
:param fulltext: string to search in
:param skw_spans: dictionary of already identified single keywords
:return : dictionary of m... |
def visit_update(self, update_stmt, **kw):
"""
used to compile <sql.expression.Update> expressions
Parts are taken from the SQLCompiler base class.
"""
if not update_stmt.parameters and \
not hasattr(update_stmt, '_crate_specific'):
return super(Crate... | used to compile <sql.expression.Update> expressions
Parts are taken from the SQLCompiler base class. |
async def confirmbalance(self, *args, **kwargs):
""" Confirm balance after trading
Accepts:
- message (signed dictionary):
- "txid" - str
- "coinid" - str
- "amount" - int
Returns:
- "address" - str
- "coinid" - str
- "amount" - int
- "... | Confirm balance after trading
Accepts:
- message (signed dictionary):
- "txid" - str
- "coinid" - str
- "amount" - int
Returns:
- "address" - str
- "coinid" - str
- "amount" - int
- "uid" - int
- "unconfirmed" - int (0 by defaul... |
def occurrence_view(
request,
event_pk,
pk,
template='swingtime/occurrence_detail.html',
form_class=forms.SingleOccurrenceForm
):
'''
View a specific occurrence and optionally handle any updates.
Context parameters:
``occurrence``
the occurrence object keyed by ``pk``
... | View a specific occurrence and optionally handle any updates.
Context parameters:
``occurrence``
the occurrence object keyed by ``pk``
``form``
a form object for updating the occurrence |
def _set_protected_vlans(self, v, load=False):
"""
Setter method for protected_vlans, mapped from YANG variable /interface/ethernet/openflow/protected_vlans (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_protected_vlans is considered as a private
method.... | Setter method for protected_vlans, mapped from YANG variable /interface/ethernet/openflow/protected_vlans (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_protected_vlans is considered as a private
method. Backends looking to populate this variable should
do s... |
def generate_timing_stats(file_list, var_list):
"""
Parse all of the timing files, and generate some statistics
about the run.
Args:
file_list: A list of timing files to parse
var_list: A list of variables to look for in the timing file
Returns:
A dict containing values tha... | Parse all of the timing files, and generate some statistics
about the run.
Args:
file_list: A list of timing files to parse
var_list: A list of variables to look for in the timing file
Returns:
A dict containing values that have the form:
[mean, min, max, mean, standard... |
def commit_output(cls, shard_ctx, iterator):
"""Saves output references when a shard finishes.
Inside end_shard(), an output writer can optionally use this method
to persist some references to the outputs from this shard
(e.g a list of filenames)
Args:
shard_ctx: map_job_context.ShardContext... | Saves output references when a shard finishes.
Inside end_shard(), an output writer can optionally use this method
to persist some references to the outputs from this shard
(e.g a list of filenames)
Args:
shard_ctx: map_job_context.ShardContext for this shard.
iterator: an iterator that yi... |
def get_job(self, job_resource_name: str) -> Dict:
"""Returns metadata about a previously created job.
See get_job_result if you want the results of the job and not just
metadata about the job.
Params:
job_resource_name: A string of the form
`projects/projec... | Returns metadata about a previously created job.
See get_job_result if you want the results of the job and not just
metadata about the job.
Params:
job_resource_name: A string of the form
`projects/project_id/programs/program_id/jobs/job_id`.
Returns:
... |
def _grouped(input_type, output_type, base_class, output_type_method):
"""Define a user-defined function that is applied per group.
Parameters
----------
input_type : List[ibis.expr.datatypes.DataType]
A list of the types found in :mod:`~ibis.expr.datatypes`. The
... | Define a user-defined function that is applied per group.
Parameters
----------
input_type : List[ibis.expr.datatypes.DataType]
A list of the types found in :mod:`~ibis.expr.datatypes`. The
length of this list must match the number of arguments to the
functio... |
def set_thread(self, thread = None):
"""
Manually set the thread process. Use with care!
@type thread: L{Thread}
@param thread: (Optional) Thread object. Use C{None} to autodetect.
"""
if thread is None:
self.__thread = None
else:
self.__... | Manually set the thread process. Use with care!
@type thread: L{Thread}
@param thread: (Optional) Thread object. Use C{None} to autodetect. |
def _decode_surrogatepass(data, codec):
"""Like data.decode(codec, 'surrogatepass') but makes utf-16-le/be work
on Python < 3.4 + Windows
https://bugs.python.org/issue27971
Raises UnicodeDecodeError, LookupError
"""
try:
return data.decode(codec, _surrogatepass)
except UnicodeDeco... | Like data.decode(codec, 'surrogatepass') but makes utf-16-le/be work
on Python < 3.4 + Windows
https://bugs.python.org/issue27971
Raises UnicodeDecodeError, LookupError |
def do_loglevel(self, args, arguments):
"""
::
Usage:
loglevel
loglevel critical
loglevel error
loglevel warning
loglevel info
loglevel debug
Shows current log level or changes it.
... | ::
Usage:
loglevel
loglevel critical
loglevel error
loglevel warning
loglevel info
loglevel debug
Shows current log level or changes it.
loglevel - shows current log level
critical ... |
def image_vacuum(name):
'''
Delete images not in use or installed via image_present
.. warning::
Only image_present states that are included via the
top file will be detected.
'''
name = name.lower()
ret = {'name': name,
'changes': {},
'result': None,
... | Delete images not in use or installed via image_present
.. warning::
Only image_present states that are included via the
top file will be detected. |
def list(self):
"""List available reports from the server by returning a dictionary
with reports classified by data model:
.. doctest::
:options: +SKIP
>>> odoo.report.list()['account.invoice']
[{'name': u'Duplicates',
'report_name': u'account.... | List available reports from the server by returning a dictionary
with reports classified by data model:
.. doctest::
:options: +SKIP
>>> odoo.report.list()['account.invoice']
[{'name': u'Duplicates',
'report_name': u'account.account_invoice_report_dupl... |
def electron_shells_are_subset(subset, superset, compare_meta=False, rel_tol=0.0):
'''
Determine if a list of electron shells is a subset of another
If 'subset' is a subset of the 'superset', True is returned.
The shells are compared approximately (exponents/coefficients are
within a tolerance)
... | Determine if a list of electron shells is a subset of another
If 'subset' is a subset of the 'superset', True is returned.
The shells are compared approximately (exponents/coefficients are
within a tolerance)
If compare_meta is True, the metadata is also compared for exact equality. |
def _patch_tcpserver():
"""
Patch shutdown_request to open blocking interaction after the end of the
request
"""
shutdown_request = TCPServer.shutdown_request
def shutdown_request_patched(*args, **kwargs):
thread = current_thread()
shutdown_request(*args, **kwargs)
if th... | Patch shutdown_request to open blocking interaction after the end of the
request |
def expression(sceneid, tile_x, tile_y, tile_z, expr=None, **kwargs):
"""
Apply expression on data.
Attributes
----------
sceneid : str
Landsat id, Sentinel id, CBERS ids or file url.
tile_x : int
Mercator tile X index.
tile_y : int
Mercator tile Y index.
tile_z... | Apply expression on data.
Attributes
----------
sceneid : str
Landsat id, Sentinel id, CBERS ids or file url.
tile_x : int
Mercator tile X index.
tile_y : int
Mercator tile Y index.
tile_z : int
Mercator tile ZOOM level.
expr : str, required
Expressi... |
def get_float(self, key: str) -> Optional[float]:
"""
Returns an optional configuration value, as a float, by its key, or None if it doesn't exist.
If the configuration value isn't a legal float, this function will throw an error.
:param str key: The requested configuration key.
... | Returns an optional configuration value, as a float, by its key, or None if it doesn't exist.
If the configuration value isn't a legal float, this function will throw an error.
:param str key: The requested configuration key.
:return: The configuration key's value, or None if one does not exist... |
def ls(quiet, verbose, uri):
"""List datasets / items in a dataset.
If the URI is a dataset the items in the dataset will be listed.
It is not possible to list the items in a proto dataset.
If the URI is a location containing datasets the datasets will be listed.
Proto datasets are highlighted in ... | List datasets / items in a dataset.
If the URI is a dataset the items in the dataset will be listed.
It is not possible to list the items in a proto dataset.
If the URI is a location containing datasets the datasets will be listed.
Proto datasets are highlighted in red. |
def copy_resources(src_container, src_resources, storage_dir, dst_directories=None, apply_chown=None, apply_chmod=None):
"""
Copies files and directories from a Docker container. Multiple resources can be copied and additional options are
available than in :func:`copy_resource`. Unlike in :func:`copy_resour... | Copies files and directories from a Docker container. Multiple resources can be copied and additional options are
available than in :func:`copy_resource`. Unlike in :func:`copy_resource`, Resources are copied as they are and not
compressed to a tarball, and they are left on the remote machine.
:param src_c... |
def keys(self):
"Returns a list of ConfigMap keys."
return (list(self._pb.IntMap.keys()) + list(self._pb.StringMap.keys()) +
list(self._pb.FloatMap.keys()) + list(self._pb.BoolMap.keys())) | Returns a list of ConfigMap keys. |
def tapered_gutenberg_richter_cdf(moment, moment_threshold, beta,
corner_moment):
'''
Tapered Gutenberg Richter Cumulative Density Function
:param float or numpy.ndarray moment:
Moment for calculation of rate
:param float or numpy.ndarray moment_threshold:
... | Tapered Gutenberg Richter Cumulative Density Function
:param float or numpy.ndarray moment:
Moment for calculation of rate
:param float or numpy.ndarray moment_threshold:
Threshold Moment of the distribution (moment rate essentially!)
:param float beta:
Beta value (b * ln(10.)) of... |
def add_commit_branches(self, git_repo, enrich_backend):
"""Add the information about branches to the documents representing commits in
the enriched index. Branches are obtained using the command `git ls-remote`,
then for each branch, the list of commits is retrieved via the command `git rev-lis... | Add the information about branches to the documents representing commits in
the enriched index. Branches are obtained using the command `git ls-remote`,
then for each branch, the list of commits is retrieved via the command `git rev-list branch-name` and
used to update the corresponding items in... |
def store(self, response):
"""Store response in cache, skipping if code is forbidden.
:param requests.Response response: HTTP response
"""
if response.status_code not in CACHE_CODES:
return
now = datetime.datetime.now()
self.data[response.url] = {
... | Store response in cache, skipping if code is forbidden.
:param requests.Response response: HTTP response |
def pip_ins_req(
ctx,
python,
req_path,
venv_path=None,
inputs=None,
outputs=None,
touch=None,
check_import=False,
check_import_module=None,
pip_setup_file=None,
pip_setup_touch=None,
virtualenv_setup_touch=None,
always=False,
):
"""
Create task that uses give... | Create task that uses given virtual environment's `pip` to sets up \
packages listed in given requirements file.
:param ctx: BuildContext object.
:param python: Python program path used to set up `pip` and `virtualenv`.
:param req_path: Requirements file relative path relative to top directory.
... |
def exchange_code_and_store_config(auth_client, auth_code):
"""
Finishes auth flow after code is gotten from command line or local server.
Exchanges code for tokens and gets user info from auth.
Stores tokens and user info in config.
"""
# do a token exchange with the given code
tkn = auth_c... | Finishes auth flow after code is gotten from command line or local server.
Exchanges code for tokens and gets user info from auth.
Stores tokens and user info in config. |
def locus_read_generator(
samfile,
chromosome,
base1_position_before_variant,
base1_position_after_variant,
use_duplicate_reads=USE_DUPLICATE_READS,
use_secondary_alignments=USE_SECONDARY_ALIGNMENTS,
min_mapping_quality=MIN_READ_MAPPING_QUALITY):
"""
Gener... | Generator that yields a sequence of ReadAtLocus records for reads which
contain the positions before and after a variant. The actual work to figure
out if what's between those positions matches a variant happens later in
the `variant_reads` module.
Parameters
----------
samfile : pysam.Alignmen... |
def cg_prolongation_smoothing(A, T, B, BtBinv, Sparsity_Pattern, maxiter, tol,
weighting='local', Cpt_params=None):
"""Use CG to smooth T by solving A T = 0, subject to nullspace and sparsity constraints.
Parameters
----------
A : csr_matrix, bsr_matrix
SPD sparse ... | Use CG to smooth T by solving A T = 0, subject to nullspace and sparsity constraints.
Parameters
----------
A : csr_matrix, bsr_matrix
SPD sparse NxN matrix
T : bsr_matrix
Tentative prolongator, a NxM sparse matrix (M < N).
This is initial guess for the equation A T = 0.
... |
def lat_from_pole(ref_loc_lon, ref_loc_lat, pole_plon, pole_plat):
"""
Calculate paleolatitude for a reference location based on a paleomagnetic pole
Required Parameters
----------
ref_loc_lon: longitude of reference location in degrees
ref_loc_lat: latitude of reference location
pole_plon:... | Calculate paleolatitude for a reference location based on a paleomagnetic pole
Required Parameters
----------
ref_loc_lon: longitude of reference location in degrees
ref_loc_lat: latitude of reference location
pole_plon: paleopole longitude in degrees
pole_plat: paleopole latitude in degrees |
def _getdata_by_idx(data, idx):
"""Shuffle the data."""
shuffle_data = []
for k, v in data:
if (isinstance(v, h5py.Dataset) if h5py else False):
shuffle_data.append((k, v))
elif isinstance(v, CSRNDArray):
shuffle_data.append((k, sparse_array(v.asscipy()[idx], v.conte... | Shuffle the data. |
def set_up_logging(log_file, console_log_level):
"""Configure logging settings and return a logger object."""
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler(str(log_file))
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(console_log_le... | Configure logging settings and return a logger object. |
def validate_character_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Validates that character is from the same outline as the story node.
'''
if action == 'pre_add':
if reverse:
for spk in pk_set:
story_node = StoryElementNode.obje... | Validates that character is from the same outline as the story node. |
def thresh(data, threshold, threshold_type='hard'):
r"""Threshold data
This method perfoms hard or soft thresholding on the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
threshold : float or np.ndarray
Threshold level(s)
threshold_type :... | r"""Threshold data
This method perfoms hard or soft thresholding on the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
threshold : float or np.ndarray
Threshold level(s)
threshold_type : str {'hard', 'soft'}
Type of noise to be added ... |
def wrmap(func, iterable, *args):
'Same as map(func, iterable, *args), but ignoring exceptions.'
for it in iterable:
try:
yield func(it, *args)
except Exception as e:
pass | Same as map(func, iterable, *args), but ignoring exceptions. |
def bot_has_permissions(**perms):
"""Similar to :func:`.has_permissions` except checks if the bot itself has
the permissions listed.
This check raises a special exception, :exc:`.BotMissingPermissions`
that is inherited from :exc:`.CheckFailure`.
"""
def predicate(ctx):
guild = ctx.guil... | Similar to :func:`.has_permissions` except checks if the bot itself has
the permissions listed.
This check raises a special exception, :exc:`.BotMissingPermissions`
that is inherited from :exc:`.CheckFailure`. |
def ignore_path(path, ignore_list=None, whitelist=None):
"""
Returns a boolean indicating if a path should be ignored given an
ignore_list and a whitelist of glob patterns.
"""
if ignore_list is None:
return True
should_ignore = matches_glob_list(path, ignore_list)
if whitelist is N... | Returns a boolean indicating if a path should be ignored given an
ignore_list and a whitelist of glob patterns. |
def _reverse_convert(x, factor1, factor2):
"""
Converts mixing ratio x in c1 - c2 tie line to that in
comp1 - comp2 tie line.
Args:
x (float): Mixing ratio x in c1 - c2 tie line, a float between
0 and 1.
factor1 (float): Compositional ratio betwee... | Converts mixing ratio x in c1 - c2 tie line to that in
comp1 - comp2 tie line.
Args:
x (float): Mixing ratio x in c1 - c2 tie line, a float between
0 and 1.
factor1 (float): Compositional ratio between composition c1 and
processed composition comp... |
def add_cookie_header(self, request):
"""Add correct Cookie: header to request (urllib.request.Request object).
The Cookie2 header is also added unless policy.hide_cookie2 is true.
"""
_debug("add_cookie_header")
self._cookies_lock.acquire()
try:
self._poli... | Add correct Cookie: header to request (urllib.request.Request object).
The Cookie2 header is also added unless policy.hide_cookie2 is true. |
def write(self, address, data, x, y, p=0):
"""Write a bytestring to an address in memory.
It is strongly encouraged to only read and write to blocks of memory
allocated using :py:meth:`.sdram_alloc`. Additionally,
:py:meth:`.sdram_alloc_as_filelike` can be used to safely wrap
re... | Write a bytestring to an address in memory.
It is strongly encouraged to only read and write to blocks of memory
allocated using :py:meth:`.sdram_alloc`. Additionally,
:py:meth:`.sdram_alloc_as_filelike` can be used to safely wrap
read/write access to memory with a file-like interface a... |
def render_title(text, markup=True, no_smartquotes=False):
""" Convert a Markdown title to HTML """
# HACK: If the title starts with something that looks like a list, save it
# for later
pfx, text = re.match(r'([0-9. ]*)(.*)', text).group(1, 2)
text = pfx + misaka.Markdown(TitleRenderer(),
... | Convert a Markdown title to HTML |
def local_async(self, *args, **kwargs):
'''
Run :ref:`execution modules <all-salt.modules>` asynchronously
Wraps :py:meth:`salt.client.LocalClient.run_job`.
:return: job ID
'''
local = salt.client.get_local_client(mopts=self.opts)
ret = local.run_job(*args, **kw... | Run :ref:`execution modules <all-salt.modules>` asynchronously
Wraps :py:meth:`salt.client.LocalClient.run_job`.
:return: job ID |
def replaceMaskedValue(self, replacementValue):
""" Replaces values where the mask is True with the replacement value.
"""
if self.mask is False:
pass
elif self.mask is True:
self.data[:] = replacementValue
else:
self.data[self.mask] = replacem... | Replaces values where the mask is True with the replacement value. |
def b58decode(val, charset=DEFAULT_CHARSET):
"""Decode base58check encoded input to original raw bytes.
:param bytes val: The value to base58cheeck decode.
:param bytes charset: (optional) The character set to use for decoding.
:return: the decoded bytes.
:rtype: bytes
Usage::
>>> impor... | Decode base58check encoded input to original raw bytes.
:param bytes val: The value to base58cheeck decode.
:param bytes charset: (optional) The character set to use for decoding.
:return: the decoded bytes.
:rtype: bytes
Usage::
>>> import base58check
>>> base58check.b58decode('\x00v... |
def describe_group(record, region):
"""Attempts to describe group ids."""
account_id = record['account']
group_name = cloudwatch.filter_request_parameters('groupName', record)
vpc_id = cloudwatch.filter_request_parameters('vpcId', record)
group_id = cloudwatch.filter_request_parameters('groupId', r... | Attempts to describe group ids. |
def kill_process(process_name):
""" method is called to kill a running process """
try:
sys.stdout.write('killing: {0} {{ \n'.format(process_name))
pid = get_process_pid(process_name)
if pid is not None and psutil.pid_exists(int(pid)):
p = psutil.Process(pid)
p.ki... | method is called to kill a running process |
def get_protein_seq_for_transcript(self, transcript_id):
""" obtain the sequence for a transcript from ensembl
"""
headers = {"content-type": "text/plain"}
self.attempt = 0
ext = "/sequence/id/{}?type=protein".format(transcript_id)
return self.e... | obtain the sequence for a transcript from ensembl |
def ensure_valid_environment_config(module_name, config):
"""Exit if config is invalid."""
if not config.get('namespace'):
LOGGER.fatal("staticsite: module %s's environment configuration is "
"missing a namespace definition!",
module_name)
sys.exit(1) | Exit if config is invalid. |
def parse(args=None):
"""Defines how to parse CLI arguments for the DomainTools API"""
parser = argparse.ArgumentParser(description='The DomainTools CLI API Client')
parser.add_argument('-u', '--username', dest='user', default='', help='API Username')
parser.add_argument('-k', '--key', dest='key', defau... | Defines how to parse CLI arguments for the DomainTools API |
def retry(self):
"""
Retry a failed or aborted command.
@return: A new ApiCommand object with the updated information.
"""
path = self._path() + '/retry'
resp = self._get_resource_root().post(path)
return ApiCommand.from_json_dict(resp, self._get_resource_root()) | Retry a failed or aborted command.
@return: A new ApiCommand object with the updated information. |
def clean_service_url(url):
"""
Return only the scheme, hostname (with optional port) and path
components of the parameter URL.
"""
parts = urlparse(url)
return urlunparse((parts.scheme, parts.netloc, parts.path, '', '', '')) | Return only the scheme, hostname (with optional port) and path
components of the parameter URL. |
def box_cox(table):
"""
box-cox transform table
"""
from scipy.stats import boxcox as bc
t = []
for i in table:
if min(i) == 0:
scale = min([j for j in i if j != 0]) * 10e-10
else:
scale = 0
t.append(np.ndarray.tolist(bc(np.array([j + scale for j i... | box-cox transform table |
def F(Document, __raw__=None, **filters):
"""Generate a MongoDB filter document through parameter interpolation.
Arguments passed by name have their name interpreted as an optional prefix (currently only `not`), a double-
underscore
Because this utility is likely going to be used frequently it has been given a ... | Generate a MongoDB filter document through parameter interpolation.
Arguments passed by name have their name interpreted as an optional prefix (currently only `not`), a double-
underscore
Because this utility is likely going to be used frequently it has been given a single-character name. |
def make_passwordmanager(schemes=None):
"""
schemes contains a list of replace this list with the hash(es) you wish
to support.
this example sets pbkdf2_sha256 as the default,
with support for legacy bcrypt hashes.
:param schemes:
:return: CryptContext()
"""
from passlib.context imp... | schemes contains a list of replace this list with the hash(es) you wish
to support.
this example sets pbkdf2_sha256 as the default,
with support for legacy bcrypt hashes.
:param schemes:
:return: CryptContext() |
def load_command_line_args(clargs=None):
"""Load and parse command-line arguments.
Arguments
---------
args : str or None
'Faked' commandline arguments passed to `argparse`.
Returns
-------
args : `argparse.Namespace` object
Namespace in which settings are stored - default ... | Load and parse command-line arguments.
Arguments
---------
args : str or None
'Faked' commandline arguments passed to `argparse`.
Returns
-------
args : `argparse.Namespace` object
Namespace in which settings are stored - default values modified by the
given command-lin... |
def calculatePathIntegrationError(self, time, dt=None, trajectory=None,
envelope=False, inputNoise=None):
"""
Calculate the error of our path integration, relative to an ideal module.
To do this, we track the movement of an individual bump
Note that the network must ... | Calculate the error of our path integration, relative to an ideal module.
To do this, we track the movement of an individual bump
Note that the network must be trained before this is done.
:param time: How long to simulate for in seconds. We recommend using a
small value, e.g. ~10s.
:param... |
def _parse_args(args: List[str]) -> _UpdateArgumentsRunConfig:
"""
Parses the given CLI arguments to get a run configuration.
:param args: CLI arguments
:return: run configuration derived from the given CLI arguments
"""
parser = argparse.ArgumentParser(
prog="gitlab-update-variables", d... | Parses the given CLI arguments to get a run configuration.
:param args: CLI arguments
:return: run configuration derived from the given CLI arguments |
def calc_loss(self, embedding):
"""Helper function to calculate rieman loss given new embedding"""
Hnew = self.compute_dual_rmetric(Ynew=embedding)
return self.rieman_loss(Hnew=Hnew) | Helper function to calculate rieman loss given new embedding |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.