text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def clear(self):
""" Clear Screen """
widgets.StringWidget(self, ref="_w1_", text=" " * 20, x=1, y=1)
widgets.StringWidget(self, ref="_w2_", text=" " * 20, x=1, y=2)
widgets.StringWidget(self, ref="_w3_", text=" " * 20, x=1, y=3)
widgets.StringWidget(self, ref="_w4_", text=" " * ... | 0.006006 |
def chemical_formula(self):
"""the chemical formula of the molecule"""
counts = {}
for number in self.numbers:
counts[number] = counts.get(number, 0)+1
items = []
for number, count in sorted(counts.items(), reverse=True):
if count == 1:
ite... | 0.004219 |
def follow_user(self, user, delegate):
"""Follow the given user.
Returns the user info back to the given delegate
"""
parser = txml.Users(delegate)
return self.__postPage('/friendships/create/%s.xml' % (user), parser) | 0.007752 |
def set_numeric_score_increment(self, increment):
"""Sets the numeric score increment.
arg: increment (decimal): the numeric score increment
raise: InvalidArgument - ``increment`` is invalid
raise: NoAccess - ``increment`` cannot be modified
*compliance: mandatory -- This m... | 0.00454 |
def get_next_interval_histogram(self,
range_start_time_sec=0.0,
range_end_time_sec=sys.maxsize,
absolute=False):
'''Read the next interval histogram from the log, if interval falls
within an absol... | 0.002907 |
def inverse_transform(self, X, copy=None):
"""
Scale back the data to the original representation.
:param X: Scaled data matrix.
:type X: numpy.ndarray, shape [n_samples, n_features]
:param bool copy: Copy the X data matrix.
:return: X data matrix with the scaling operat... | 0.001609 |
def resource_qualifier(resource):
""" Split a resource in (filename, directory) tuple with taking care of external resources
:param resource: A file path or a URI
:return: (Filename, Directory) for files, (URI, None) for URI
"""
if resource.startswith("//") or resource.startswith("http"):
r... | 0.005076 |
def get_params_parser():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-g', '--debug', dest='debug',
action='store_true',
help=argparse.SUPPRESS)
parser.add_argument("--arthur", action='store_tru... | 0.000793 |
def df_filter_col_sum(df, threshold, take_abs=True):
''' filter columns in matrix at some threshold
and remove rows that have all zero values '''
from copy import deepcopy
from .__init__ import Network
net = Network()
if take_abs is True:
df_copy = deepcopy(df['mat'].abs())
else:
df_copy = deepc... | 0.017329 |
def set_logger(self):
"""
Prepare the logger, using self.logger_name and self.logger_level
"""
self.logger = logging.getLogger(self.logger_name)
self.logger.setLevel(self.logger_level) | 0.008929 |
def eta_hms(seconds, always_show_hours=False, always_show_minutes=False, hours_leading_zero=False):
"""Converts seconds remaining into a human readable timestamp (e.g. hh:mm:ss, h:mm:ss, mm:ss, or ss).
Positional arguments:
seconds -- integer/float indicating seconds remaining.
Keyword arguments:
... | 0.002829 |
def discover_files(base_path, sub_path='', ext='', trim_base_path=False):
"""Discovers all files with certain extension in given paths."""
file_list = []
for root, dirs, files in walk(path.join(base_path, sub_path)):
if trim_base_path:
root = path.relpath(root, base_path)
file_li... | 0.002041 |
def on_message(self, client_conn, msg):
"""Handle message.
Returns
-------
ready : Future
A future that will resolve once we're ready, else None.
Notes
-----
*on_message* should not be called again until *ready* has resolved.
"""
MAX... | 0.002227 |
def remove_dbs(self, double):
"""Remove double item from list
"""
one = []
for dup in double:
if dup not in one:
one.append(dup)
return one | 0.009662 |
def display(self, stats, cs_status=None):
"""Display stats on the screen.
stats: Stats database to display
cs_status:
"None": standalone or server mode
"Connected": Client is connected to a Glances server
"SNMP": Client is connected to a SNMP server
... | 0.001275 |
def _setup_model_loss(self, lr):
"""
Setup loss and optimizer for PyTorch model.
"""
# Setup loss
if not hasattr(self, "loss"):
self.loss = SoftCrossEntropyLoss()
# Setup optimizer
if not hasattr(self, "optimizer"):
self.optimizer = optim.... | 0.005714 |
def _apply_scales(array, scales, dtype):
"""Apply scales to the array.
"""
new_array = np.empty(array.shape, dtype)
for i in array.dtype.names:
try:
new_array[i] = array[i] * scales[i]
except TypeError:
if np.all(scales[i] == 1):
new_array[i] = arr... | 0.002591 |
def does_not_contain(self, element):
"""
Ensures :attr:`subject` does not contain *element*.
"""
self._run(unittest_case.assertNotIn, (element, self._subject))
return ChainInspector(self._subject) | 0.008475 |
def get_profane_words(self):
"""Returns all profane words currently in use."""
profane_words = []
if self._custom_censor_list:
profane_words = [w for w in self._custom_censor_list] # Previous versions of Python don't have list.copy()
else:
profane_words = [w for... | 0.006289 |
def runSearchReferenceSets(self, request):
"""
Runs the specified SearchReferenceSetsRequest.
"""
return self.runSearchRequest(
request, protocol.SearchReferenceSetsRequest,
protocol.SearchReferenceSetsResponse,
self.referenceSetsGenerator) | 0.006494 |
def to_feather(self, fname):
"""
Write out the binary feather-format for DataFrames.
.. versionadded:: 0.20.0
Parameters
----------
fname : str
string file path
"""
from pandas.io.feather_format import to_feather
to_feather(self, fnam... | 0.006211 |
def process_commmon(self):
'''
Some data processing common for all services.
No need to override this.
'''
data = self.data
data_content = data['content'][0]
## Paste the output of a command
# This is deprecated after piping support
if data['comma... | 0.00492 |
def _readMultiple(self, start, end, db):
"""
Returns a list of hashes with serial numbers between start
and end, both inclusive.
"""
self._validatePos(start, end)
# Converting any bytearray to bytes
return [bytes(db.get(str(pos))) for pos in range(start, end + 1... | 0.006211 |
def info_factory(name, libnames, headers, frameworks=None,
section=None, classname=None):
"""Create a system_info class.
Parameters
----------
name : str
name of the library
libnames : seq
list of libraries to look for
headers : seq
... | 0.001136 |
def refresh_console(self, console: tcod.console.Console) -> None:
"""Update an Image created with :any:`tcod.image_from_console`.
The console used with this function should have the same width and
height as the Console given to :any:`tcod.image_from_console`.
The font width and height m... | 0.003221 |
def ProcessHuntClientCrash(flow_obj, client_crash_info):
"""Processes client crash triggerted by a given hunt-induced flow."""
if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id):
hunt.StopHuntIfCrashLimitExceeded(flow_obj.parent_hunt_id)
return
hunt_urn = rdfvalue.RDFURN("hunts").Add(flow_obj.parent_hunt... | 0.009506 |
def call_plugins(self, step):
'''
For each plugins, check if a "step" method exist on it, and call it
Args:
step (str): The method to search and call on each plugin
'''
for plugin in self.plugins:
try:
getattr(plugin, step)()
e... | 0.007286 |
def extend(dict_, *dicts, **kwargs):
"""Extend a dictionary with keys and values from other dictionaries.
:param dict_: Dictionary to extend
Optional keyword arguments allow to control the exact way
in which ``dict_`` will be extended.
:param overwrite:
Whether repeated keys should have ... | 0.000585 |
def cmd_iter(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return a
generator
... | 0.00315 |
def get_parser(cfg_file=cfg_file):
""" Returns a ConfigParser.ConfigParser() object for our cfg_file """
if not os.path.exists(cfg_file):
generate_configfile(cfg_file=cfg_file, defaults=defaults)
config = ConfigParser.ConfigParser()
config.read(cfg_file)
return config | 0.003378 |
def load(cls, cache_file, backend=None):
"""Instantiate AsyncResult from dumped `cache_file`.
This is the inverse of :meth:`dump`.
Parameters
----------
cache_file: str
Name of file from which the run should be read.
backend: clusterjob.backen... | 0.001931 |
def least_upper_bound(*intervals_to_join):
"""
Pseudo least upper bound.
Join the given set of intervals into a big interval. The resulting strided interval is the one which in
all the possible joins of the presented SI, presented the least number of values.
The number of joins ... | 0.005978 |
def pull(self, repository, tag=None, **kwargs):
"""
Pull an image of the given name and return it. Similar to the
``docker pull`` command.
If no tag is specified, all tags from that repository will be
pulled.
If you want to get the raw pull output, use the
:py:me... | 0.000901 |
def export(self, top=True):
"""Exports object to its string representation.
Args:
top (bool): if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are embedded in as fields inlist ... | 0.002448 |
def _registerInterface(self, iName, intf, isPrivate=False):
"""
Register interface object on interface level object
"""
nameAvailabilityCheck(self, iName, intf)
assert intf._parent is None
intf._parent = self
intf._name = iName
intf._ctx = self._ctx
... | 0.003914 |
def _K_computations(self, X, X2=None):
"""Pre-computations for the covariance function (used both when computing the covariance and its gradients). Here self._dK_dvar and self._K_dist2 are updated."""
self._lengthscales=self.mapping.f(X)
self._lengthscales2=np.square(self._lengthscales)
... | 0.007867 |
def get_experiments(base, load=False):
''' get_experiments will return loaded json for all valid experiments from an experiment folder
:param base: full path to the base folder with experiments inside
:param load: if True, returns a list of loaded config.json objects. If False (default) returns the paths to... | 0.008929 |
def is_super_admin(self, req):
"""Returns True if the admin specified in the request represents the
.super_admin.
:param req: The swob.Request to check.
:param returns: True if .super_admin.
"""
return req.headers.get('x-auth-admin-user') == '.super_admin' and \
... | 0.004739 |
def isoformat(self, strict=False):
'''Return date in isoformat (same as __str__ but without qualifier).
WARNING: does not replace '?' in dates unless strict=True.
'''
out = self.year
# what do we do when no year ...
for val in [self.month, self.day]:
if not v... | 0.002674 |
def replicator_eigenmaps(adjacency_matrix, k):
"""
Performs spectral graph embedding on the centrality reweighted adjacency matrix
Inputs: - A in R^(nxn): Adjacency matrix of an undirected network represented as a scipy.sparse.coo_matrix
- k: The number of social dimensions/eigenve... | 0.003793 |
def get_commit_tree(profile, sha):
"""Get the SHA of a commit's tree.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
sha
... | 0.001901 |
def naccess_available():
"""True if naccess is available on the path."""
available = False
try:
subprocess.check_output(['naccess'], stderr=subprocess.DEVNULL)
except subprocess.CalledProcessError:
available = True
except FileNotFoundError:
print("naccess has not been found o... | 0.001912 |
def get_workspace_activities(brain, limit=1):
""" Return the workspace activities sorted by reverse chronological
order
Regarding the time value:
- the datetime value contains the time in international format
(machine readable)
- the title value contains the absolute date and time of the p... | 0.001332 |
def http_get_provider(provider,
request_url, params, token_secret, token_cookie = None):
'''Handle HTTP GET requests on an authentication endpoint.
Authentication flow begins when ``params`` has a ``login`` key with a value
of ``start``. For instance, ``/auth/twitter?login=start``.
... | 0.006785 |
def commit_deposit(self, deposit_id, **params):
"""https://developers.coinbase.com/api/v2#commit-a-deposit"""
return self.api_client.commit_deposit(self.id, deposit_id, **params) | 0.010309 |
def local_dt(dt):
"""Return an aware datetime in system timezone, from a naive or aware
datetime.
Naive datetime are assumed to be in UTC TZ.
"""
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return LOCALTZ.normalize(dt.astimezone(LOCALTZ)) | 0.003676 |
def end_time(self):
""" Return the end time of the current valid segment of data """
return float(self.strain.start_time + (len(self.strain) - self.total_corruption) / self.sample_rate) | 0.014925 |
def _check_psutil(self, instance):
"""
Gather metrics about connections states and interfaces counters
using psutil facilities
"""
custom_tags = instance.get('tags', [])
if self._collect_cx_state:
self._cx_state_psutil(tags=custom_tags)
self._cx_count... | 0.005747 |
def _GetFileByPath(self, key_path_upper):
"""Retrieves a Windows Registry file for a specific path.
Args:
key_path_upper (str): Windows Registry key path, in upper case with
a resolved root key alias.
Returns:
tuple: consists:
str: upper case key path prefix
WinRegis... | 0.005671 |
def check_config(self, config):
"""
Check the config file for required fields and validity.
@param config: The config dict.
@return: True if valid, error string if invalid paramaters where
encountered.
"""
validation = ""
required = ["name", "currency", "I... | 0.003241 |
def evaluation_metrics(predicted, actual, bow=True):
"""
Input:
predicted, actual = lists of the predicted and actual tokens
bow: if true use bag of words assumption
Returns:
precision, recall, F1, Levenshtein distance
"""
if bow:
p = set(predicted)
a = set(ac... | 0.001427 |
def _upgrade(self):
"""
Upgrade the serialized object if necessary.
Raises:
FutureVersionError: file was written by a future version of the
software.
"""
logging.debug("[FeedbackResultsSeries]._upgrade()")
version = Version.fromstring(self.ver... | 0.002172 |
def add_proxy(self, proxy):
"""Add a valid proxy into pool
You must call `add_proxy` method to add a proxy into pool instead of
directly operate the `proxies` variable.
"""
protocol = proxy.protocol
addr = proxy.addr
if addr in self.proxies:
self.prox... | 0.004115 |
def makebunches_alter(data, commdct, theidf):
"""make bunches with data"""
bunchdt = {}
dt, dtls = data.dt, data.dtls
for obj_i, key in enumerate(dtls):
key = key.upper()
objs = dt[key]
list1 = []
for obj in objs:
bobj = makeabunch(commdct, obj, obj_i)
... | 0.002381 |
def get_window():
"""Get IDA's top level window."""
tform = idaapi.get_current_tform()
# Required sometimes when closing IDBs and not IDA.
if not tform:
tform = idaapi.find_tform("Output window")
widget = form_to_widget(tform)
window = widget.window()
return window | 0.0033 |
def POST_query(self, req_hook, req_args):
''' Generic POST query method '''
# HTTP POST queries require keyManagerTokens and sessionTokens
headers = {'Content-Type': 'application/json',
'sessionToken': self.__session__,
'keyManagerToken': self.__keymngr__}
... | 0.001832 |
def chain(self, other_task):
""" Add a chain listener to the execution of this task. Whenever
an item has been processed by the task, the registered listener
task will be queued to be executed with the output of this task.
Can also be written as::
pipeline = task1 > task2
... | 0.004464 |
def simulate(self, nsites, transition_matrix, tree, ncat=1, alpha=1):
"""
Return sequences simulated under the transition matrix's model
"""
sim = SequenceSimulator(transition_matrix, tree, ncat, alpha)
return list(sim.simulate(nsites).items()) | 0.010526 |
def menu_item(self, sub_assistant, path):
"""
The function creates a menu item
and assigns signal like select and button-press-event for
manipulation with menu_item. sub_assistant and path
"""
if not sub_assistant[0].icon_path:
menu_item = self.create_menu_ite... | 0.00402 |
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.c... | 0.000747 |
def unique_field_data_types(self):
"""
Checks if all variants have different data types.
If so, the selected variant can be determined just by the data type of
the value without needing a field name / tag. In some languages, this
lets us make a shortcut
"""
data_... | 0.00314 |
def clean_content(content):
"""\
Removes paragraph numbers, section delimiters, xxxx etc. from the content.
This function can be used to clean-up the cable's content before it
is processed by NLP tools or to create a search engine index.
`content`
The content of the cable.
"""
... | 0.007026 |
def ensure_index(index_like, copy=False):
"""
Ensure that we have an index from some index-like object.
Parameters
----------
index : sequence
An Index or other sequence
copy : bool
Returns
-------
index : Index or MultiIndex
Examples
--------
>>> ensure_index(... | 0.000596 |
def set_daemon_name(self, daemon_name):
"""Set the daemon name of the daemon which this manager is attached to
and propagate this daemon name to our managed modules
:param daemon_name:
:return:
"""
self.daemon_name = daemon_name
for instance in self.instances:
... | 0.00545 |
def ordereddict_push_front(dct, key, value):
"""Set a value at the front of an OrderedDict
The original dict isn't modified, instead a copy is returned
"""
d = OrderedDict()
d[key] = value
d.update(dct)
return d | 0.004167 |
def wait_for_plug_update(self, plug_name, remote_state, timeout_s):
"""Wait for a change in the state of a frontend-aware plug.
Args:
plug_name: Plug name, e.g. 'openhtf.plugs.user_input.UserInput'.
remote_state: The last observed state.
timeout_s: Number of seconds to wait for an update.
... | 0.005698 |
def exception(self, timeout=None):
"""Return the exception raised by the call that the future represents.
Args:
timeout: The number of seconds to wait for the exception if the
future isn't done. If None, then there is no limit on the wait
time.
Retur... | 0.004167 |
def shadowRegisterDeltaCallback(self, srcCallback):
"""
**Description**
Listen on delta topics for this device shadow by subscribing to delta topics. Whenever there
is a difference between the desired and reported state, the registered callback will be called
and the delta pay... | 0.010799 |
def outline(dataset, generate_faces=False):
"""Produces an outline of the full extent for the input dataset.
Parameters
----------
generate_faces : bool, optional
Generate solid faces for the box. This is off by default
"""
alg = vtk.vtkOutlineFilter()
... | 0.004274 |
def custom_classfunc_rule(self, opname, token, customize, next_token):
"""
call ::= expr {expr}^n CALL_FUNCTION_n
call ::= expr {expr}^n CALL_FUNCTION_VAR_n
call ::= expr {expr}^n CALL_FUNCTION_VAR_KW_n
call ::= expr {expr}^n CALL_FUNCTION_KW_n
classdefdeco2 ::= LOAD_BUI... | 0.005685 |
def element_if_exists(self, using, value):
"""Check if an element in the current context.
Support:
Android iOS Web(WebView)
Args:
using(str): The element location strategy.
value(str): The value of the location strategy.
Returns:
Return ... | 0.004644 |
def get_band(cls, b, **kwargs):
"""Defines what a "shortcut" band name refers to. Returns phot_system, band
"""
phot = None
# Default to SDSS for these
if b in ['u','g','r','i','z']:
phot = 'SDSS'
band = 'SDSS_{}'.format(b)
elif b in ['U','B','V... | 0.01343 |
def get_incomings_per_page(self, per_page=1000, page=1, params=None):
"""
Get incomings per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
... | 0.00716 |
def title(self):
"""Extract title from a release."""
if self.event:
if self.release['name']:
return u'{0}: {1}'.format(
self.repository['full_name'], self.release['name']
)
return u'{0} {1}'.format(self.repo_model.name, self.model.t... | 0.006192 |
def register(self, username, password, attr_map=None):
"""
Register the user. Other base attributes from AWS Cognito User Pools
are address, birthdate, email, family_name (last name), gender,
given_name (first name), locale, middle_name, name, nickname,
phone_number, picture, pr... | 0.001271 |
def get_args():
""" get args from command line
"""
parser = argparse.ArgumentParser("FashionMNIST")
parser.add_argument("--batch_size", type=int, default=128, help="batch size")
parser.add_argument("--optimizer", type=str, default="SGD", help="optimizer")
parser.add_argument("--epochs", type=int... | 0.007605 |
def set_level(name, level):
""" Set level for given logger
:param name: Name of logger to set the level for
:param level: The new level, see possible levels from python logging library
"""
if name is None or name == "" or name == "bench":
logging.getLogger("bench").setLevel(level)
logger... | 0.005102 |
def dump_values(self, with_defaults=True, dict_cls=dict, flat=False):
"""
Export values of all items contained in this section to a dictionary.
Items with no values set (and no defaults set if ``with_defaults=True``) will be excluded.
Returns:
dict: A dictionary of key-valu... | 0.004942 |
def move_page(self, direction, n_windows):
"""
Move the page down (positive direction) or up (negative direction).
Paging down:
The post on the bottom of the page becomes the post at the top of
the page and the cursor is moved to the top.
Paging up:
T... | 0.000924 |
def command_canonize(string, vargs):
"""
Print the canonical representation of the given string.
It will replace non-canonical compound characters
with their canonical synonym.
:param str string: the string to act upon
:param dict vargs: the command line arguments
"""
try:
ipa... | 0.003247 |
def check_data_port_connection(self, check_data_port):
"""Checks the connection validity of a data port
The method is called by a child state to check the validity of a data port in case it is connected with data
flows. The data port does not belong to 'self', but to one of self.states.
... | 0.008277 |
def dump_to_response(request, app_label=None, exclude=None,
filename_prefix=None):
"""Utility function that dumps the given app/model to an HttpResponse.
"""
app_label = app_label or []
exclude = exclude
try:
filename = '%s.%s' % (datetime.now().isoformat(),
... | 0.001076 |
def segment_kmeans(self, rgb_weight, num_clusters, hue_weight=0.0):
"""
Segment a color image using KMeans based on spatial and color distances.
Black pixels will automatically be assigned to their own 'background' cluster.
Parameters
----------
rgb_weight : float
... | 0.003016 |
def _fast_kde_2d(x, y, gridsize=(128, 128), circular=False):
"""
2D fft-based Gaussian kernel density estimate (KDE).
The code was adapted from https://github.com/mfouesneau/faststats
Parameters
----------
x : Numpy array or list
y : Numpy array or list
gridsize : tuple
Number ... | 0.000979 |
def link(self, source, target):
'creates a hard link `target -> source` (e.g. ln source target)'
return self.operations('link', target.decode(self.encoding),
source.decode(self.encoding)) | 0.012346 |
def zip_pack(filepath, options):
"""
Creates a zip archive containing the script at *filepath* along with all
imported modules that are local to *filepath* as a self-extracting python
script. A shebang will be appended to the beginning of the resulting
zip archive which will allow it to
If bei... | 0.002774 |
def generate_valid_keys():
""" create a list of valid keys """
valid_keys = []
for minimum, maximum in RANGES:
for i in range(ord(minimum), ord(maximum) + 1):
valid_keys.append(chr(i))
return valid_keys | 0.004202 |
def _print_general_vs_table(self, idset1, idset2):
"""
:param idset1:
:param idset2:
"""
ref1name = ''
set1_hasref = isinstance(idset1, idset_with_reference)
if set1_hasref:
ref1arr = np.array(idset1.reflst)
ref1name = idset1.refname
... | 0.001913 |
def main(**options):
"""Slurp up linter output and send it to a GitHub PR review."""
configure_logging(log_all=options.get('log'))
stdin_stream = click.get_text_stream('stdin')
stdin_text = stdin_stream.read()
click.echo(stdin_text)
ci = find_ci_provider()
config = Config(options, ci=ci)
... | 0.001669 |
def depends(self, *nodes):
""" Adds nodes as relatives to this one, and
updates the relatives with self as children.
:param nodes: GraphNode(s)
"""
for node in nodes:
self.add_relative(node)
node.add_children(self) | 0.007194 |
def present(name,
pattern,
definition,
priority=0,
vhost='/',
runas=None,
apply_to=None):
'''
Ensure the RabbitMQ policy exists.
Reference: http://www.rabbitmq.com/ha.html
name
Policy name
pattern
A regex of qu... | 0.001761 |
def file_hash(path, hash_type="md5", block_size=65536, hex_digest=True):
"""
Hash a given file with md5, or any other and return the hex digest. You
can run `hashlib.algorithms_available` to see which are available on your
system unless you have an archaic python version, you poor soul).
This funct... | 0.000974 |
def cartopy_globe(self):
"""Initialize a `cartopy.crs.Globe` from the metadata."""
if 'earth_radius' in self._attrs:
kwargs = {'ellipse': 'sphere', 'semimajor_axis': self._attrs['earth_radius'],
'semiminor_axis': self._attrs['earth_radius']}
else:
at... | 0.004756 |
def contents_of(f, encoding='utf-8'):
"""Helper to read the contents of the given file or path into a string with the given encoding.
Encoding defaults to 'utf-8', other useful encodings are 'ascii' and 'latin-1'."""
try:
contents = f.read()
except AttributeError:
try:
with ... | 0.003903 |
def get_last_doc(self):
"""Searches through the doc dict to find the document that was
modified or deleted most recently."""
return max(self.doc_dict.values(), key=lambda x: x.ts).meta_dict | 0.00939 |
def _try_to_compute_deterministic_class_id(cls, depth=5):
"""Attempt to produce a deterministic class ID for a given class.
The goal here is for the class ID to be the same when this is run on
different worker processes. Pickling, loading, and pickling again seems to
produce more consistent results tha... | 0.000562 |
def _finaliseRequest(self, request, status, content, mimetype='text/plain'):
"""
Finalises the request.
@param request: The HTTP Request.
@type request: C{http.Request}
@param status: The HTTP status code.
@type status: C{int}
@param content: The content of the r... | 0.002755 |
def filter(self, func):
"""
Filter array along an axis.
Applies a function which should evaluate to boolean,
along a single axis or multiple axes. Array will be
aligned so that the desired set of axes are in the
keys, which may require a transpose/reshape.
Param... | 0.002853 |
def _write_mtlist_ins(ins_filename,df,prefix):
""" write an instruction file for a MODFLOW list file
Parameters
----------
ins_filename : str
name of the instruction file to write
df : pandas.DataFrame
the dataframe of list file entries
prefix : str
the prefix to add to ... | 0.00907 |
def apply_mapping(raw_row, mapping):
'''
Override this to hand craft conversion of row.
'''
row = {target: mapping_func(raw_row[source_key])
for target, (mapping_func, source_key)
in mapping.fget().items()}
return row | 0.003861 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.