code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def iterlines(s):
"""
A generator form of s.split('\n') for reducing memory overhead.
Parameters
----------
s : str
A multi-line string.
Yields
------
line : str
A string.
"""
prevnl = -1
while True:
nextnl = s.find('\n', prevnl + 1)
if next... | A generator form of s.split('\n') for reducing memory overhead.
Parameters
----------
s : str
A multi-line string.
Yields
------
line : str
A string. |
def byte_href_anchors(self, chars=False):
'''
simple, regex-based extractor of anchor tags, so we can
compute BYTE offsets for anchor texts and associate them with
their href.
Generates tuple(href_string, first_byte, byte_length, anchor_text)
'''
input_bu... | simple, regex-based extractor of anchor tags, so we can
compute BYTE offsets for anchor texts and associate them with
their href.
Generates tuple(href_string, first_byte, byte_length, anchor_text) |
def dens_in_meanmatterdens(vo,ro,H=70.,Om=0.3):
"""
NAME:
dens_in_meanmatterdens
PURPOSE:
convert density to units of the mean matter density
INPUT:
vo - velocity unit in km/s
ro - length unit in kpc
H= (default: 70) Hubble constant in km/s/Mpc
Om= (defa... | NAME:
dens_in_meanmatterdens
PURPOSE:
convert density to units of the mean matter density
INPUT:
vo - velocity unit in km/s
ro - length unit in kpc
H= (default: 70) Hubble constant in km/s/Mpc
Om= (default: 0.3) Omega matter
OUTPUT:
conversio... |
def update_file_ext(filename, ext='txt', sep='.'):
r"""Force the file or path str to end with the indicated extension
Note: a dot (".") is assumed to delimit the extension
>>> from __future__ import unicode_literals
>>> update_file_ext('/home/hobs/extremofile', 'bac')
'/home/hobs/extremofile.bac'
... | r"""Force the file or path str to end with the indicated extension
Note: a dot (".") is assumed to delimit the extension
>>> from __future__ import unicode_literals
>>> update_file_ext('/home/hobs/extremofile', 'bac')
'/home/hobs/extremofile.bac'
>>> update_file_ext('/home/hobs/piano.file/', 'musi... |
def set_bind(self):
"""
Sets key bindings -- we need this more than once
"""
IntegerEntry.set_bind(self)
self.bind('<Next>', lambda e: self.set(self.imin))
self.bind('<Prior>', lambda e: self.set(self.imax)) | Sets key bindings -- we need this more than once |
def close_available(self):
"""可平仓数量
Returns:
[type] -- [description]
"""
return {
'volume_long': self.volume_long - self.volume_long_frozen,
'volume_short': self.volume_short - self.volume_short_frozen
} | 可平仓数量
Returns:
[type] -- [description] |
def _create(self, tree):
""" Run a SELECT statement """
tablename = tree.table
indexes = []
global_indexes = []
hash_key = None
range_key = None
attrs = {}
for declaration in tree.attrs:
name, type_ = declaration[:2]
if len(declarat... | Run a SELECT statement |
def orth_gs(order, dist, normed=False, sort="GR", cross_truncation=1., **kws):
"""
Gram-Schmidt process for generating orthogonal polynomials.
Args:
order (int, Poly):
The upper polynomial order. Alternative a custom polynomial basis
can be used.
dist (Dist):
... | Gram-Schmidt process for generating orthogonal polynomials.
Args:
order (int, Poly):
The upper polynomial order. Alternative a custom polynomial basis
can be used.
dist (Dist):
Weighting distribution(s) defining orthogonality.
normed (bool):
I... |
def air_gap(self, volume=None, height=None):
"""
Pull air into the :any:`Pipette` current tip
Notes
-----
If no `location` is passed, the pipette will touch_tip
from it's current position.
Parameters
----------
volume : number
The amo... | Pull air into the :any:`Pipette` current tip
Notes
-----
If no `location` is passed, the pipette will touch_tip
from it's current position.
Parameters
----------
volume : number
The amount in uL to aspirate air into the tube.
(Default wil... |
def _get_question_map(self, question_id):
"""get question map from questions matching question_id
This can make sense of both Section assigned Ids or normal Question/Item Ids
"""
if question_id.get_authority() == ASSESSMENT_AUTHORITY:
key = '_id'
match_value = O... | get question map from questions matching question_id
This can make sense of both Section assigned Ids or normal Question/Item Ids |
def writeProxy(self, obj):
"""
Encodes a proxied object to the stream.
@since: 0.6
"""
proxy = self.context.getProxyForObject(obj)
self.writeObject(proxy, is_proxy=True) | Encodes a proxied object to the stream.
@since: 0.6 |
def match_range(self, field, start=None, stop=None, inclusive=True,
required=True, new_group=False):
"""Add a ``field:[some range]`` term to the query.
Matches will have a ``value`` in the range in the ``field``.
Arguments:
field (str): The field to check for the... | Add a ``field:[some range]`` term to the query.
Matches will have a ``value`` in the range in the ``field``.
Arguments:
field (str): The field to check for the value.
The field must be namespaced according to Elasticsearch rules
using the dot syntax.
... |
def url_request(target_url, output_file):
"""
Use urllib to download the requested file from the target URL. Use the click progress bar to print download
progress
:param target_url: URL from which the file is to be downloaded
:param output_file: Name and path of local copy of fil... | Use urllib to download the requested file from the target URL. Use the click progress bar to print download
progress
:param target_url: URL from which the file is to be downloaded
:param output_file: Name and path of local copy of file |
def bitmask(*args):
"""! @brief Returns a mask with specified bit ranges set.
An integer mask is generated based on the bits and bit ranges specified by the
arguments. Any number of arguments can be provided. Each argument may be either
a 2-tuple of integers, a list of integers, or an individual in... | ! @brief Returns a mask with specified bit ranges set.
An integer mask is generated based on the bits and bit ranges specified by the
arguments. Any number of arguments can be provided. Each argument may be either
a 2-tuple of integers, a list of integers, or an individual integer. The result
is th... |
def add_product_version_to_build_configuration(id=None, name=None, product_version_id=None):
"""
Associate an existing ProductVersion with a BuildConfiguration
"""
data = remove_product_version_from_build_configuration_raw(id, name, product_version_id)
if data:
return utils.format_json_list(... | Associate an existing ProductVersion with a BuildConfiguration |
def make_published(self, request, queryset):
""" Bulk action to mark selected posts as published. If
the date_published field is empty the current time is
saved as date_published.
queryset must not be empty (ensured by DjangoCMS).
"""
cnt1 = queryset.filter(
... | Bulk action to mark selected posts as published. If
the date_published field is empty the current time is
saved as date_published.
queryset must not be empty (ensured by DjangoCMS). |
def css(self, *props, **kwprops):
"""Adds css properties to this element."""
self._stable = False
styles = {}
if props:
if len(props) == 1 and isinstance(props[0], Mapping):
styles = props[0]
else:
raise WrongContentError(self, prop... | Adds css properties to this element. |
def list_all_categories(cls, **kwargs):
"""List Categories
Return a list of Categories
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_categories(async=True)
>>> result = thre... | List Categories
Return a list of Categories
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_categories(async=True)
>>> result = thread.get()
:param async bool
:param ... |
def _scroll(clicks, x=None, y=None):
"""Send the mouse vertical scroll event to Windows by calling the
mouse_event() win32 function.
Args:
clicks (int): The amount of scrolling to do. A positive value is the mouse
wheel moving forward (scrolling up), a negative value is backwards (down).
... | Send the mouse vertical scroll event to Windows by calling the
mouse_event() win32 function.
Args:
clicks (int): The amount of scrolling to do. A positive value is the mouse
wheel moving forward (scrolling up), a negative value is backwards (down).
x (int): The x position of the mouse event.
... |
def active_url(context, urls, css=None):
"""
Highlight menu item based on url tag.
Returns a css class if ``request.path`` is in given ``url``.
:param url:
Django url to be reversed.
:param css:
Css class to be returned for highlighting. Return active if none set.
"""... | Highlight menu item based on url tag.
Returns a css class if ``request.path`` is in given ``url``.
:param url:
Django url to be reversed.
:param css:
Css class to be returned for highlighting. Return active if none set. |
def i4_sobol_generate(dim_num, n, skip=1):
"""
i4_sobol_generate generates a Sobol dataset.
Parameters:
Input, integer dim_num, the spatial dimension.
Input, integer N, the number of points to generate.
Input, integer SKIP, the number of initial points to skip.
Output, real R(M,N),... | i4_sobol_generate generates a Sobol dataset.
Parameters:
Input, integer dim_num, the spatial dimension.
Input, integer N, the number of points to generate.
Input, integer SKIP, the number of initial points to skip.
Output, real R(M,N), the points. |
def subsets_of_fileinfo_from_txt(filename):
"""Returns a dictionary with subsets of FileInfo instances from a TXT file.
Each subset of files must be preceded by a line:
@ <number> <label>
where <number> indicates the number of files in that subset,
and <label> is a label for that subset. Any additi... | Returns a dictionary with subsets of FileInfo instances from a TXT file.
Each subset of files must be preceded by a line:
@ <number> <label>
where <number> indicates the number of files in that subset,
and <label> is a label for that subset. Any additional text
beyond <label> in the same line is ig... |
def build(self, message):
"""buffer all the streaming messages based on the
message id. Reconstruct all fragments together.
:param message:
incoming message
:return: next complete message or None if streaming
is not done
"""
context = None
... | buffer all the streaming messages based on the
message id. Reconstruct all fragments together.
:param message:
incoming message
:return: next complete message or None if streaming
is not done |
def tree_match(cls, field, string):
''' Given a tree index, retrieves the ids atached to the given prefix,
think of if as a mechanism for pattern suscription, where two models
attached to the `a`, `a:b` respectively are found by the `a:b` string,
because both model's subscription key mat... | Given a tree index, retrieves the ids atached to the given prefix,
think of if as a mechanism for pattern suscription, where two models
attached to the `a`, `a:b` respectively are found by the `a:b` string,
because both model's subscription key matches the string. |
def to_json(self):
"""Exports the object to a JSON friendly dict
Returns:
Dict representation of the object
"""
return {
'userId': self.user_id,
'username': self.username,
'roles': self.roles,
'authSystem': self.auth_system
... | Exports the object to a JSON friendly dict
Returns:
Dict representation of the object |
def reserve_items(self, parent_item, *items):
"""Reserve a set of items until a parent item is returned.
Prevent ``check_out_item()`` from returning any of ``items``
until ``parent_item`` is completed or times out. For each
item, if it is not already checked out or reserved by some
... | Reserve a set of items until a parent item is returned.
Prevent ``check_out_item()`` from returning any of ``items``
until ``parent_item`` is completed or times out. For each
item, if it is not already checked out or reserved by some
other parent item, it is associated with ``parent_it... |
def to_json(self):
"""
Prepare data for the initial state of the admin-on-rest
"""
endpoints = []
for endpoint in self.endpoints:
list_fields = endpoint.fields
resource_type = endpoint.Meta.resource_type
table = endpoint.Meta.table
... | Prepare data for the initial state of the admin-on-rest |
def skip(cb, msg, attributes):
"""
Skips applying transforms if data is not geographic.
"""
if not all(a in msg for a in attributes):
return True
plot = get_cb_plot(cb)
return (not getattr(plot, 'geographic', False) or
not hasattr(plot.current_frame, 'crs')) | Skips applying transforms if data is not geographic. |
def logged_exception(self, e):
"""Record the exception, but don't log it; it's already been logged
:param e: Exception to log.
"""
if str(e) not in self._errors:
self._errors.append(str(e))
self.set_error_state()
self.buildstate.state.exception_type = str(... | Record the exception, but don't log it; it's already been logged
:param e: Exception to log. |
def project_update(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /project-xxxx/update API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2Fupdate
"""
return DXHTTPRequest('/%s/update' % object_id, inp... | Invokes the /project-xxxx/update API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2Fupdate |
def guest_create_network_interface(self, userid, os_version,
guest_networks, active=False):
""" Create network interface(s) for the guest inux system. It will
create the nic for the guest, add NICDEF record into the user
direct. It will also constru... | Create network interface(s) for the guest inux system. It will
create the nic for the guest, add NICDEF record into the user
direct. It will also construct network interface configuration
files and punch the files to the guest. These files will take
effect when initializi... |
def extract(self, msg):
"""Yield an ordered dictionary if msg['type'] is in keys_by_type."""
def normal(key):
v = msg.get(key)
if v is None:
return v
normalizer = self.normalizers.get(key, lambda x: x)
return normalizer(v)
def odic... | Yield an ordered dictionary if msg['type'] is in keys_by_type. |
def get_collection(self, lang=None, task=None):
""" Return the collection that represents a specific language or task.
Args:
lang (string): Language code.
task (string): Task name.
"""
if lang: id = "{}{}".format(Downloader.LANG_PREFIX, lang)
elif task: id = "{}{}".format(Downloader.TAS... | Return the collection that represents a specific language or task.
Args:
lang (string): Language code.
task (string): Task name. |
def delete_variable(self, key):
"""Deletes a global variable
:param key: the key of the global variable to be deleted
:raises exceptions.AttributeError: if the global variable does not exist
"""
key = str(key)
if self.is_locked(key):
raise RuntimeError("Glob... | Deletes a global variable
:param key: the key of the global variable to be deleted
:raises exceptions.AttributeError: if the global variable does not exist |
def _cmp_by_router_id(local_asn, path1, path2):
"""Select the route received from the peer with the lowest BGP router ID.
If both paths are eBGP paths, then we do not do any tie breaking, i.e we do
not pick best-path based on this criteria.
RFC: http://tools.ietf.org/html/rfc5004
We pick best path ... | Select the route received from the peer with the lowest BGP router ID.
If both paths are eBGP paths, then we do not do any tie breaking, i.e we do
not pick best-path based on this criteria.
RFC: http://tools.ietf.org/html/rfc5004
We pick best path between two iBGP paths as usual. |
def discord_to_users(self, memberlist):
"""
expects a list of discord.py user objects
returns a list of TrainerDex.py user objects
"""
_memberlist = self.get_discord_user(x.id for x in memberlist)
return list(set(x.owner() for x in _memberlist)) | expects a list of discord.py user objects
returns a list of TrainerDex.py user objects |
def get_iam_policy(self, client=None):
"""Retrieve the IAM policy for the bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.clien... | Retrieve the IAM policy for the bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
... |
def write(filepath, data, **kwargs):
"""
Write a file.
Supported formats:
* CSV
* JSON, JSONL
* pickle
Parameters
----------
filepath : str
Path to the file that should be read. This methods action depends
mainly on the file extension.
data : dict or list
... | Write a file.
Supported formats:
* CSV
* JSON, JSONL
* pickle
Parameters
----------
filepath : str
Path to the file that should be read. This methods action depends
mainly on the file extension.
data : dict or list
Content that should be written
kwargs : di... |
def xmatch_kdtree(kdtree,
extra, extdecl,
xmatchdistdeg,
closestonly=True):
'''This cross-matches between `kdtree` and (`extra`, `extdecl`) arrays.
Returns the indices of the kdtree and the indices of extra, extdecl that
xmatch successfully.
Parame... | This cross-matches between `kdtree` and (`extra`, `extdecl`) arrays.
Returns the indices of the kdtree and the indices of extra, extdecl that
xmatch successfully.
Parameters
----------
kdtree : scipy.spatial.CKDTree
This is a kdtree object generated by the `make_kdtree` function.
ext... |
def redirect_n_times(n):
"""302 Redirects n times.
---
tags:
- Redirects
parameters:
- in: path
name: n
type: int
produces:
- text/html
responses:
302:
description: A redirection.
"""
assert n > 0
absolute = request.args.get("absolute"... | 302 Redirects n times.
---
tags:
- Redirects
parameters:
- in: path
name: n
type: int
produces:
- text/html
responses:
302:
description: A redirection. |
def validate_windows_cred_winexe(host,
username='Administrator',
password=None,
retries=10,
retry_delay=1):
'''
Check if the windows credentials are valid
'''
cmd = "winexe -U '{0}%{1}' //{2} \"hostna... | Check if the windows credentials are valid |
def add_bookmark(self, time):
"""Run this function when user adds a new bookmark.
Parameters
----------
time : tuple of float
start and end of the new bookmark, in s
"""
if self.annot is None: # remove if buttons are disabled
msg = 'No score file... | Run this function when user adds a new bookmark.
Parameters
----------
time : tuple of float
start and end of the new bookmark, in s |
def _set_show_mpls_ldp_path(self, v, load=False):
"""
Setter method for show_mpls_ldp_path, mapped from YANG variable /brocade_mpls_rpc/show_mpls_ldp_path (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_ldp_path is considered as a private
method. Back... | Setter method for show_mpls_ldp_path, mapped from YANG variable /brocade_mpls_rpc/show_mpls_ldp_path (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_ldp_path is considered as a private
method. Backends looking to populate this variable should
do so via ca... |
def make_orthographic_map(central_longitude=0, central_latitude=0, figsize=(8, 8),
add_land=True, land_color='tan', add_ocean=False, ocean_color='lightblue', grid_lines=True,
lat_grid=[-80., -60., -30.,
0., 30., 60., 80.],
... | Function creates and returns an orthographic map projection using cartopy
Example
-------
>>> map_axis = make_orthographic_map(central_longitude=200,central_latitude=30)
Optional Parameters
-----------
central_longitude : central longitude of projection (default is 0)
central_latitude : ce... |
def process_track(self, track, frame_size=400, hop_size=160, sr=None,
start=0, end=float('inf'), utterance=None, corpus=None):
"""
Process the track in **offline** mode, in one go.
Args:
track (Track): The track to process.
frame_size (int): The num... | Process the track in **offline** mode, in one go.
Args:
track (Track): The track to process.
frame_size (int): The number of samples per frame.
hop_size (int): The number of samples between two frames.
sr (int): Use the given sampling rate. If ``None``,
... |
def delete_file(f):
"""Delete the given file
:param f: the file to delete
:type f: :class:`JB_File`
:returns: None
:rtype: None
:raises: :class:`OSError`
"""
fp = f.get_fullpath()
log.info("Deleting file %s", fp)
os.remove(fp) | Delete the given file
:param f: the file to delete
:type f: :class:`JB_File`
:returns: None
:rtype: None
:raises: :class:`OSError` |
def get_names_in_namespace_page(namespace_id, offset, count, proxy=None, hostport=None):
"""
Get a page of names in a namespace
Returns the list of names on success
Returns {'error': ...} on error
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connec... | Get a page of names in a namespace
Returns the list of names on success
Returns {'error': ...} on error |
def _from_binary_stdinfo(cls, binary_stream):
"""See base class."""
'''
TIMESTAMPS(32)
Creation time - 8
File altered time - 8
MFT/Metadata altered time - 8
Accessed time - 8
Flags - 4 (FileInfoFlags)
Maximum number of versions - 4
... | See base class. |
def getJob(self, jobID):
""" returns the results or status of a job """
url = self._url + "/jobs/%s" % (jobID)
return GPJob(url=url,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
proxy_url=self._proxy_url) | returns the results or status of a job |
def find_n75(contig_lengths_dict, genome_length_dict):
"""
Calculate the N75 for each strain. N75 is defined as the largest contig such that at least 3/4 of the total
genome size is contained in contigs equal to or larger than this contig
:param contig_lengths_dict: dictionary of strain name: reverse-so... | Calculate the N75 for each strain. N75 is defined as the largest contig such that at least 3/4 of the total
genome size is contained in contigs equal to or larger than this contig
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:param genome_length_dict: dict... |
def http_error_default(self, url, fp, errcode, errmsg, headers):
"""Default error handling -- don't raise an exception."""
return addinfourl(fp, headers, "http:" + url, errcode) | Default error handling -- don't raise an exception. |
def _query_init(k, oracle, query, method='all'):
"""A helper function for query-matching function initialization."""
if method == 'all':
a = np.subtract(query, [oracle.f_array[t] for t in oracle.latent[oracle.data[k]]])
dvec = (a * a).sum(axis=1) # Could skip the sqrt
_d = dvec.argmin()... | A helper function for query-matching function initialization. |
def remove_api_key_from_groups(self, api_key, body, **kwargs): # noqa: E501
"""Remove API key from groups. # noqa: E501
An endpoint for removing API key from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/{apikey-id}/groups -d '[0162056a9a1586f30242590700... | Remove API key from groups. # noqa: E501
An endpoint for removing API key from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/{apikey-id}/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586f30242590700000000]' -H 'content-type: application/json' -H 'Author... |
def log(**data):
"""RPC method for logging events
Makes entry with new account creating
Return None
"""
# Get data from request body
entry = {
"module": data["params"]["module"],
"event": data["params"]["event"],
"timestamp": data["params"]["timestamp"],
"arguments": data["params"]["arguments"]
}
# Call... | RPC method for logging events
Makes entry with new account creating
Return None |
def layers(self):
'''Construct Keras input layers for the given transformer
Returns
-------
layers : {field: keras.layers.Input}
A dictionary of keras input layers, keyed by the corresponding
field keys.
'''
from keras.layers import Input
... | Construct Keras input layers for the given transformer
Returns
-------
layers : {field: keras.layers.Input}
A dictionary of keras input layers, keyed by the corresponding
field keys. |
def _init_log(level=logging.DEBUG):
"""Initialise the logging object.
Args:
level (int): Logging level.
Returns:
Logger: Python logging object.
"""
log = logging.getLogger(__file__)
log.setLevel(level)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(level)
... | Initialise the logging object.
Args:
level (int): Logging level.
Returns:
Logger: Python logging object. |
def remove_feature_flag_accounts(self, feature, account_id):
"""
Remove feature flag.
Remove feature flag for a given Account, Course, or User. (Note that the flag must
be defined on the Account, Course, or User directly.) The object will then inherit
the feature flags f... | Remove feature flag.
Remove feature flag for a given Account, Course, or User. (Note that the flag must
be defined on the Account, Course, or User directly.) The object will then inherit
the feature flags from a higher account, if any exist. If this flag was 'on' or 'off',
then ... |
def parse(input, identifier: str = None, use_cache=False, clear_cache=True, pattern="*.qface", profile=EProfile.FULL):
"""Input can be either a file or directory or a list of files or directory.
A directory will be parsed recursively. The function returns the resulting system.
Stores the result ... | Input can be either a file or directory or a list of files or directory.
A directory will be parsed recursively. The function returns the resulting system.
Stores the result of the run in the domain cache named after the identifier.
:param path: directory to parse
:param identifier: ide... |
def is_draft_version(self):
""" Return if this version is the draft version of a layer """
pub_ver = getattr(self, 'published_version', None)
latest_ver = getattr(self, 'latest_version', None)
this_ver = getattr(self, 'this_version', None)
return this_ver and latest_ver and (this... | Return if this version is the draft version of a layer |
def display_image(self, reset=1):
"""Utility routine used to display an updated frame from a framebuffer.
"""
try:
fb = self.server.controller.get_frame(self.frame)
except KeyError:
# the selected frame does not exist, create it
fb = self.server.contro... | Utility routine used to display an updated frame from a framebuffer. |
def get_gain(data, attr, class_attr,
method=DEFAULT_DISCRETE_METRIC,
only_sub=0, prefer_fewer_values=False, entropy_func=None):
"""
Calculates the information gain (reduction in entropy) that would
result by splitting the data on the chosen attribute (attr).
Parameters:
prefer_fewe... | Calculates the information gain (reduction in entropy) that would
result by splitting the data on the chosen attribute (attr).
Parameters:
prefer_fewer_values := Weights the gain by the count of the attribute's
unique values. If multiple attributes have the same gain, but one has
s... |
def check_available(self):
"""
Check for availability of a layer and provide run metrics.
"""
success = True
start_time = datetime.datetime.utcnow()
message = ''
LOGGER.debug('Checking layer id %s' % self.id)
signals.post_save.disconnect(layer_post_save, ... | Check for availability of a layer and provide run metrics. |
def _handle_rundebug_from_shell(cmd_line):
"""
Handles all commands that take a filename and 0 or more extra arguments.
Passes the command to backend.
(Debugger plugin may also use this method)
"""
command, args = parse_shell_command(cmd_line)
if len(args) >= 1:
get_workbench().get... | Handles all commands that take a filename and 0 or more extra arguments.
Passes the command to backend.
(Debugger plugin may also use this method) |
def delete(self):
"""
Deletes the current instance. This assumes that we know what we're
doing, and have a primary key in our data already. If this is a new
instance, then we'll let the user know with an Exception
"""
if self._new:
raise Exception("This is a n... | Deletes the current instance. This assumes that we know what we're
doing, and have a primary key in our data already. If this is a new
instance, then we'll let the user know with an Exception |
def load_metascenario(self, scenario_list):
"""Load one or more scenarios from a list.
Each entry in scenario_list should be a dict containing at least a
name key and an optional tile key and args key. If tile is present
and its value is not None, the scenario specified will be loaded ... | Load one or more scenarios from a list.
Each entry in scenario_list should be a dict containing at least a
name key and an optional tile key and args key. If tile is present
and its value is not None, the scenario specified will be loaded into
the given tile only. Otherwise it will be... |
def _set_redist_bgp(self, v, load=False):
"""
Setter method for redist_bgp, mapped from YANG variable /isis_state/router_isis_config/is_address_family_v4/redist_bgp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_redist_bgp is considered as a private
meth... | Setter method for redist_bgp, mapped from YANG variable /isis_state/router_isis_config/is_address_family_v4/redist_bgp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_redist_bgp is considered as a private
method. Backends looking to populate this variable should
... |
def unorm(v1):
"""
Normalize a double precision 3-vector and return its magnitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/unorm_c.html
:param v1: Vector to be normalized.
:type v1: 3-Element Array of floats
:return: Unit vector of v1, Magnitude of v1.
:rtype: tuple
""... | Normalize a double precision 3-vector and return its magnitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/unorm_c.html
:param v1: Vector to be normalized.
:type v1: 3-Element Array of floats
:return: Unit vector of v1, Magnitude of v1.
:rtype: tuple |
def record_move_fields(rec, tag, field_positions_local,
field_position_local=None):
"""
Move some fields to the position specified by 'field_position_local'.
:param rec: a record structure as returned by create_record()
:param tag: the tag of the fields to be moved
:param fie... | Move some fields to the position specified by 'field_position_local'.
:param rec: a record structure as returned by create_record()
:param tag: the tag of the fields to be moved
:param field_positions_local: the positions of the fields to move
:param field_position_local: insert the field before that
... |
def nonparabolicity(self, **kwargs):
'''
Returns the Kane band nonparabolicity parameter for the Gamma-valley.
'''
Eg = self.Eg_Gamma(**kwargs)
meff = self.meff_e_Gamma(**kwargs)
T = kwargs.get('T', 300.)
return k*T/Eg * (1 - meff)**2 | Returns the Kane band nonparabolicity parameter for the Gamma-valley. |
def insert_instance_template(self, body, request_id=None, project_id=None):
"""
Inserts instance template using body specified
Must be called with keyword arguments rather than positional.
:param body: Instance template representation as object according to
https://cloud.goo... | Inserts instance template using body specified
Must be called with keyword arguments rather than positional.
:param body: Instance template representation as object according to
https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates
:type body: dict
:param... |
def skullstrip_template(dset,template,prefix=None,suffix=None,dilate=0):
'''Takes the raw anatomy ``dset``, aligns it to a template brain, and applies a templated skullstrip. Should produce fairly reliable skullstrips as long
as there is a decent amount of normal brain and the overall shape of the brain is norm... | Takes the raw anatomy ``dset``, aligns it to a template brain, and applies a templated skullstrip. Should produce fairly reliable skullstrips as long
as there is a decent amount of normal brain and the overall shape of the brain is normal-ish |
def is_cell_separator(self, cursor=None, block=None):
"""Return True if cursor (or text block) is on a block separator"""
assert cursor is not None or block is not None
if cursor is not None:
cursor0 = QTextCursor(cursor)
cursor0.select(QTextCursor.BlockUnderCursor)
... | Return True if cursor (or text block) is on a block separator |
def exec_workflow(self, model, record_id, signal):
"""Execute the workflow `signal` on
the instance having the ID `record_id` of `model`.
*Python 2:*
:raise: :class:`odoorpc.error.RPCError`
:raise: :class:`odoorpc.error.InternalError` (if not logged)
:raise: `urllib2.UR... | Execute the workflow `signal` on
the instance having the ID `record_id` of `model`.
*Python 2:*
:raise: :class:`odoorpc.error.RPCError`
:raise: :class:`odoorpc.error.InternalError` (if not logged)
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:rais... |
def set_row_min_height(self, y: int, min_height: int):
"""Sets a minimum height for blocks in the row with coordinate y."""
if y < 0:
raise IndexError('y < 0')
self._min_heights[y] = min_height | Sets a minimum height for blocks in the row with coordinate y. |
def loadTopicPageFromFile(self, fname):
"""
load topic page from an existing file
"""
assert os.path.exists(fname)
f = open(fname, "r", encoding="utf-8")
self.topicPage = json.load(f) | load topic page from an existing file |
def to_xy_arrays(self, dtype=np.float32):
"""
Convert this object to an iterable of ``(M,2)`` arrays of points.
This is the inverse of
:func:`imgaug.augmentables.lines.LineStringsOnImage.from_xy_array`.
Parameters
----------
dtype : numpy.dtype, optional
... | Convert this object to an iterable of ``(M,2)`` arrays of points.
This is the inverse of
:func:`imgaug.augmentables.lines.LineStringsOnImage.from_xy_array`.
Parameters
----------
dtype : numpy.dtype, optional
Desired output datatype of the ndarray.
Returns
... |
def create_audit_event(self, code='AUDIT'):
"""Creates a generic auditing Event logging the changes between saves
and the initial data in creates.
Kwargs:
code (str): The code to set the new Event to.
Returns:
Event: A new event with relevant info inserted into ... | Creates a generic auditing Event logging the changes between saves
and the initial data in creates.
Kwargs:
code (str): The code to set the new Event to.
Returns:
Event: A new event with relevant info inserted into it |
def convert_bytes(n):
"""
Convert a size number to 'K', 'M', .etc
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / pre... | Convert a size number to 'K', 'M', .etc |
def dimension_range(lower, upper, hard_range, soft_range, padding=None, log=False):
"""
Computes the range along a dimension by combining the data range
with the Dimension soft_range and range.
"""
lower, upper = range_pad(lower, upper, padding, log)
lower = max_range([(lower, None), (soft_range... | Computes the range along a dimension by combining the data range
with the Dimension soft_range and range. |
def delete_files(self, selections) -> None:
"""Delete the network files corresponding to the given selections
(e.g. a |list| of |str| objects or a |Selections| object)."""
try:
currentpath = self.currentpath
for selection in selections:
name = str(selectio... | Delete the network files corresponding to the given selections
(e.g. a |list| of |str| objects or a |Selections| object). |
def find_proxy_plugin(component, plugin_name):
""" Attempt to find a proxy plugin provided by a specific component
Args:
component (string): The name of the component that provides the plugin
plugin_name (string): The name of the plugin to load
Returns:
TileBuxProxyPlugin: The plug... | Attempt to find a proxy plugin provided by a specific component
Args:
component (string): The name of the component that provides the plugin
plugin_name (string): The name of the plugin to load
Returns:
TileBuxProxyPlugin: The plugin, if found, otherwise raises DataError |
def makemigrations(application, merge=False, dry_run=False, empty=False, extra_applications=None):
"""
Generate migrations
"""
from django.core.management import call_command
apps = [application]
if extra_applications:
if isinstance(extra_applications, text_type):
apps += [e... | Generate migrations |
def get_prev_sibling_tags(mention):
"""Return the HTML tag of the Mention's previous siblings.
Previous siblings are Mentions which are at the same level in the HTML tree
as the given mention, but are declared before the given mention. If a
candidate is passed in, only the previous siblings of its firs... | Return the HTML tag of the Mention's previous siblings.
Previous siblings are Mentions which are at the same level in the HTML tree
as the given mention, but are declared before the given mention. If a
candidate is passed in, only the previous siblings of its first Mention are
considered in the calcula... |
def setup_icons(self, ):
"""Set all icons on buttons
:returns: None
:rtype: None
:raises: None
"""
floppy_icon = get_icon('glyphicons_446_floppy_save.png', asicon=True)
self.release_pb.setIcon(floppy_icon) | Set all icons on buttons
:returns: None
:rtype: None
:raises: None |
def stop(self):
"""Stop Modis and log it out of Discord."""
self.button_toggle_text.set("Start Modis")
self.state = "off"
logger.info("Stopping Discord Modis")
from ._client import client
asyncio.run_coroutine_threadsafe(client.logout(), client.loop)
self.status... | Stop Modis and log it out of Discord. |
def check_settings_for_differences(old, new, as_bool=False, as_tri=False):
"""
Returns a subset of the env dictionary keys that differ,
either being added, deleted or changed between old and new.
"""
assert not as_bool or not as_tri
old = old or {}
new = new or {}
changes = set(k for ... | Returns a subset of the env dictionary keys that differ,
either being added, deleted or changed between old and new. |
def register_iq_response_future(self, from_, id_, fut):
"""
Register a future `fut` for an IQ stanza with type ``result`` or
``error`` from the :class:`~aioxmpp.JID` `from_` with the id
`id_`.
If the type of the IQ stanza is ``result``, the stanza is set as result
to the... | Register a future `fut` for an IQ stanza with type ``result`` or
``error`` from the :class:`~aioxmpp.JID` `from_` with the id
`id_`.
If the type of the IQ stanza is ``result``, the stanza is set as result
to the future. If the type of the IQ stanza is ``error``, the stanzas
erro... |
def share(self, plotters, keys=None, draw=None, auto_update=False):
"""
Share the formatoptions of this plotter with others
This method shares the formatoptions of this :class:`Plotter` instance
with others to make sure that, if the formatoption of this changes,
those of the oth... | Share the formatoptions of this plotter with others
This method shares the formatoptions of this :class:`Plotter` instance
with others to make sure that, if the formatoption of this changes,
those of the others change as well
Parameters
----------
plotters: list of :cla... |
def _internal_declare_key_flags(flag_names,
flag_values=FLAGS, key_flag_values=None):
"""Declares a flag as key for the calling module.
Internal function. User code should call DECLARE_key_flag or
ADOPT_module_key_flags instead.
Args:
flag_names: A list of strings that are... | Declares a flag as key for the calling module.
Internal function. User code should call DECLARE_key_flag or
ADOPT_module_key_flags instead.
Args:
flag_names: A list of strings that are names of already-registered
Flag objects.
flag_values: A FlagValues object that the flags listed in
flag_n... |
def _storage_get_key_names(bucket, pattern):
""" Get names of all storage keys in a specified bucket that match a pattern. """
return [item.metadata.name for item in _storage_get_keys(bucket, pattern)] | Get names of all storage keys in a specified bucket that match a pattern. |
def _create_matrix(self, document, dictionary):
"""
Creates matrix of shape |unique words|×|sentences| where cells
contains number of occurences of words (rows) in senteces (cols).
"""
sentences = document.sentences
words_count = len(dictionary)
sentences_count =... | Creates matrix of shape |unique words|×|sentences| where cells
contains number of occurences of words (rows) in senteces (cols). |
def prepare_params(self):
"""
Prepare the parameters passed to the templatetag
"""
if self.options.resolve_fragment:
self.fragment_name = self.node.fragment_name.resolve(self.context)
else:
self.fragment_name = str(self.node.fragment_name)
# Re... | Prepare the parameters passed to the templatetag |
def request(self, path, data=None, headers=None, method=None):
"""Performs a HTTP request to the Go server
Args:
path (str): The full path on the Go server to request.
This includes any query string attributes.
data (str, dict, bool, optional): If any data is present thi... | Performs a HTTP request to the Go server
Args:
path (str): The full path on the Go server to request.
This includes any query string attributes.
data (str, dict, bool, optional): If any data is present this
request will become a POST request.
headers (dict,... |
def post_event_discounts(self, id, **data):
"""
POST /events/:id/discounts/
Creates a new discount; returns the result as a :format:`discount` as the key ``discount``.
"""
return self.post("/events/{0}/discounts/".format(id), data=data) | POST /events/:id/discounts/
Creates a new discount; returns the result as a :format:`discount` as the key ``discount``. |
def release(self, conn):
"""Release a previously acquired connection.
The connection is put back into the pool."""
self._pool_lock.acquire()
self._pool.put(ConnectionWrapper(self._pool, conn))
self._current_acquired -= 1
self._pool_lock.release() | Release a previously acquired connection.
The connection is put back into the pool. |
def getenv(option, default=undefined, cast=undefined):
"""
Return the value for option or default if defined.
"""
# We can't avoid __contains__ because value may be empty.
if option in os.environ:
value = os.environ[option]
else:
if isinstance(default, Undefined):
ra... | Return the value for option or default if defined. |
def render(self, name, value, attrs=None):
'''Render the widget as HTML inputs for display on a form.
:param name: form field base name
:param value: date value
:param attrs: - unused
:returns: HTML text with three inputs for year/month/day
'''
# expects a value... | Render the widget as HTML inputs for display on a form.
:param name: form field base name
:param value: date value
:param attrs: - unused
:returns: HTML text with three inputs for year/month/day |
def get_stderr(self, tail=None):
"""
Returns current total output written to standard error.
:param tail: Return this number of most-recent lines.
:return: copy of stderr stream
"""
if self.finished():
self.join_threads()
while not self.stderr_q.empty... | Returns current total output written to standard error.
:param tail: Return this number of most-recent lines.
:return: copy of stderr stream |
def vprintf(self, alevel, format, *args):
'''
A verbosity-aware printf.
'''
if self._verbosity and self._verbosity >= alevel:
sys.stdout.write(format % args) | A verbosity-aware printf. |
def fit_transform(self, X, y=None):
"""Fit OneHotEncoder to X, then transform X.
Equivalent to self.fit(X).transform(X), but more convenient and more
efficient. See fit for the parameters, transform for the return value.
Parameters
----------
X : array-like or sparse ma... | Fit OneHotEncoder to X, then transform X.
Equivalent to self.fit(X).transform(X), but more convenient and more
efficient. See fit for the parameters, transform for the return value.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.