text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def reload_localzone():
"""Reload the cached localzone. You need to call this if the timezone has changed."""
global _cache_tz
_cache_tz = pytz.timezone(get_localzone_name())
utils.assert_tz_offset(_cache_tz)
return _cache_tz | 0.008163 |
def generate_gaussian_profile(seeing_fwhm):
"""Generate a normalized Gaussian profile from its FWHM"""
FWHM_G = 2 * math.sqrt(2 * math.log(2))
sigma = seeing_fwhm / FWHM_G
amplitude = 1.0 / (2 * math.pi * sigma * sigma)
seeing_model = Gaussian2D(amplitude=amplitude,
x_m... | 0.002058 |
def as_dict(self):
"""
Json-serializable dict representation of DefectEntry
"""
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"defect": self.defect.as_dict(),
"uncorrected_energy": self.uncorrected_energy,
... | 0.004396 |
def valid_hash_value(hashname):
"""Return true if given value is a valid, recommended hash name according
to the STIX 2 specification.
"""
custom_hash_prefix_re = re.compile(r"^x_")
if hashname in enums.HASH_ALGO_OV or custom_hash_prefix_re.match(hashname):
return True
else:
retu... | 0.003049 |
def checkIpDetails(query=None):
'''
Method that checks if the given hash is stored in the md5crack.com website. An example of the json received:
{
"as": "AS8560 1\u00261 Internet AG",
"city": "",
"country": "Germany",
"countryCode": "DE",
... | 0.007544 |
def update_position(self, newpos):
'''update trail'''
tnow = time.time()
if tnow >= self.last_time + self.timestep:
self.points.append(newpos.latlon)
self.last_time = tnow
while len(self.points) > self.count:
self.points.pop(0) | 0.006601 |
def transform_op_tree(
root: OP_TREE,
op_transformation: Callable[[Operation], OP_TREE]=lambda e: e,
iter_transformation: Callable[[Iterable[OP_TREE]], OP_TREE]=lambda e: e,
preserve_moments: bool = False
) -> OP_TREE:
"""Maps transformation functions onto the nodes of an OP_TREE.
... | 0.004255 |
def qr(self,text):
""" Print QR Code for the provided string """
qr_code = qrcode.QRCode(version=4, box_size=4, border=1)
qr_code.add_data(text)
qr_code.make(fit=True)
qr_img = qr_code.make_image()
im = qr_img._img.convert("RGB")
# Convert the RGB image in printab... | 0.008333 |
def generate_ini(self):
""" Generate a sample ini
"""
example = []
example.append("[settings]")
for key in sorted(list(self.spec.keys())):
if self.spec[key]['type'] in [list, dict]:
value = json.dumps(self.spec[key].get('example', ''))
else... | 0.004049 |
def post(self, endpoint, return_response=False, **kwargs):
"""Send HTTP POST to the endpoint.
:arg str endpoint: The endpoint to send to.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error.
"""
args... | 0.003413 |
def get_comparable_values(self):
"""Return a tupple of values representing the unicity of the object
"""
return (not self.generic, str(self.name), str(self.description)) | 0.010363 |
def probabilities(self, choosers, alternatives, filter_tables=True):
"""
Returns the probabilities for a set of choosers to choose
from among a set of alternatives.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, ... | 0.000562 |
def translate(self, addr):
"""
Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which
will point to the private IP address within the same datacenter.
"""
# get family of this address so we translate to the same
family = sock... | 0.006494 |
def bottleneck_block(inputs,
filters,
is_training,
projection_shortcut,
strides,
final_block,
data_format="channels_first",
use_td=False,
targeting_rate... | 0.004421 |
def flags(self, index):
""""Determines interaction allowed with table cells.
See :qtdoc:`QAbstractItemModel<QAbstractItemModel.flags>`,
and :qtdoc:`subclassing<qabstractitemmodel.subclassing>`
"""
if index.isValid():
if self.model.editableRow(index.row()) and index.... | 0.004511 |
def toints(self):
"""\
Returns an iterable of integers interpreting the content of `seq`
as sequence of binary numbers of length 8.
"""
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x')... | 0.006 |
def inputindex(input):
"""Handler for showing keyboard or mouse page with day and total links."""
stats = {}
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
tables = ("moves", "clicks", "scrolls") if "mouse" == input else ("keys", "combos")
for table in tables:
... | 0.00381 |
def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property de... | 0.004082 |
def signal_handler(self, signum, frame):
"""
Handle print_exit via signals.
"""
self.print_exit()
print("\n(Terminated with signal %d)\n" % (signum))
sys.exit(0) | 0.009569 |
def obs(self):
"""
return the number of observations for your SASdata object
"""
code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;"
if self.sas.nosub:
print(code)... | 0.005277 |
def http_post_request(url, params, add_to_headers=None, _async=False):
"""
from 火币demo, post方法
:param url:
:param params:
:param add_to_headers:
:return:
"""
headers = {
"Accept": "application/json",
'Content-Type': 'application/json'
}
if add_to_headers:
... | 0.002973 |
def _copy_net(block_out, net, temp_wv_net, mem_map):
"""This function makes a copy of all nets passed to it for synth uses
"""
new_args = tuple(temp_wv_net[a_arg] for a_arg in net.args)
new_dests = tuple(temp_wv_net[a_dest] for a_dest in net.dests)
if net.op in "m@": # special stuff for copying mem... | 0.003597 |
def generate_slug(text, tail_number=0):
from wagtail.core.models import Page
"""
Returns a new unique slug. Object must provide a SlugField called slug.
URL friendly slugs are generated using django.template.defaultfilters'
slugify. Numbers are added to the end of slugs for uniqueness.
based on... | 0.000782 |
def build(surname, name, birthday, sex, municipality):
"""``build(surname, name, birthday, sex, municipality) -> string``
Computes the fiscal code for the given person data.
eg: build('Rocca', 'Emanuele', datetime.datetime(1983, 11, 18), 'M', 'D969')
-> RCCMNL83S18D969H
"""
# RCCMNL
... | 0.006658 |
def constraint_present(name, constraint_id, constraint_type, constraint_options=None, cibname=None):
'''
Ensure that a constraint is created
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not u... | 0.002574 |
def perform_check(self,
env: env_tools.PreparedEnv,
verbose: bool) -> Tuple[bool, str]:
"""Evaluates the status check and returns a pass/fail with message.
Args:
env: Describes a prepared python 3 environment in which to run.
verbose: ... | 0.010593 |
def _write_summary(self, session, frame):
'''Writes the frame to disk as a tensor summary.'''
summary = session.run(self.summary_op, feed_dict={
self.frame_placeholder: frame
})
path = '{}/{}'.format(self.PLUGIN_LOGDIR, SUMMARY_FILENAME)
write_file(summary, path) | 0.003436 |
def matches(self, path):
"""Tests if the given path matches the pattern.
Note that the unicode translation of the patch is matched, so
replacement characters might have been added.
"""
path = self._prepare_path(path)
return self.full_regex.search(path) is not None | 0.00639 |
def collect_env_info():
"""
Returns:
str - a table contains important information about the environment
"""
data = []
data.append(("sys.platform", sys.platform))
data.append(("Python", sys.version.replace("\n", "")))
data.append(("Tensorpack", __git_version__))
data.append(("Nump... | 0.000801 |
def queue_ramp_dicts(ramp_dict_list, server_ip_and_port):
"""Simple utility function to queue up a list of dictionaries."""
client = server.ClientForServer(server.BECServer, server_ip_and_port)
for dct in ramp_dict_list:
client.queue_ramp(dct)
client.start({}) | 0.003521 |
def CreateSessionCompletion(self):
"""Creates a session completion.
Returns:
SessionCompletion: session completion attribute container.
"""
self.completion_time = int(time.time() * 1000000)
session_completion = SessionCompletion()
session_completion.aborted = self.aborted
session_com... | 0.001524 |
def energy_density(self, strain, convert_GPa_to_eV=True):
"""
Calculates the elastic energy density due to a strain
"""
return sum([c.energy_density(strain, convert_GPa_to_eV)
for c in self]) | 0.00823 |
def _extend_blocks(extend_node, blocks, context):
"""
Extends the dictionary `blocks` with *new* blocks in the parent node (recursive)
:param extend_node: The ``{% extends .. %}`` node object.
:type extend_node: ExtendsNode
:param blocks: dict of all block names found in the template.
:type blo... | 0.00304 |
def satisfiable(self, **kwargs):
"""
Whether the state's constraints are satisfiable
"""
if o.ABSTRACT_SOLVER in self.options or o.SYMBOLIC not in self.options:
extra_constraints = kwargs.pop('extra_constraints', ())
for e in extra_constraints:
if ... | 0.004149 |
def kill_eaters(self):
"""
Returns a list of tuples containing the proper localized kill eater type strings and their values
according to set/type/value "order"
"""
eaters = {}
ranktypes = self._kill_types
for attr in self:
aname = attr.name.strip()
... | 0.001738 |
def later(timeout, f, *args, **kwargs):
'''
Sets a timer that will call the *f* function past *timeout* seconds.
See example in :ref:`sample_inter`
:return: :class:`Timer`
'''
t = Timer(timeout, f, args, kwargs)
t.start()
return t | 0.003788 |
def cell_to_text(self):
"""Return the text representation for the cell"""
if self.cell_type != 'code':
self.metadata['cell_type'] = self.cell_type
active = is_active('py', self.metadata)
if self.language != self.default_language and 'active' not in self.metadata:
... | 0.003872 |
def parse_input(s):
"""Parse the given input and intelligently transform it into an absolute,
non-naive, timezone-aware datetime object for the UTC timezone.
The input can be specified as a millisecond-precision UTC timestamp (or
delta against Epoch), with or without a terminating 'L'. Alternatively, t... | 0.000708 |
def remote_media_url(self, with_ssl=False):
"""
Returns the base remote media URL. In this case, we can safely make
some assumptions on the URL string based on bucket names, and having
public ACL on.
args:
with_ssl: (bool) If True, return an HTTPS url.
... | 0.006745 |
def disable_buttons(self):
"""
Function disables buttons
"""
self.main_btn.set_sensitive(False)
self.back_btn.hide()
self.info_label.set_label('<span color="#FFA500">In progress...</span>')
self.disable_close_window()
if self.link is not None:
... | 0.008929 |
def get_uuid_list(dbconn):
"""
Get a list of tables that exist in dbconn
:param dbconn: master database connection
:return: List of uuids in the database
"""
cur = dbconn.cursor()
tables = get_table_list(dbconn)
uuids = set()
for table in tables:
cur.execute("SELECT (UUID) FR... | 0.002128 |
def S(self):
"""Cross-spectral density.
.. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f)
"""
if self.c is None:
raise RuntimeError('Cross-spectral density requires noise '
'covariance matrix c.')
H = self.H()
# ... | 0.011342 |
def system_monitor_cid_card_alert_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
cid_card = ET.SubElement(system_monitor, "cid-card")
... | 0.005474 |
def action_notify(self, action):
"""
Notify all subscribers of an action status change.
action -- the action whose status changed
"""
message = json.dumps({
'messageType': 'actionStatus',
'data': action.as_action_description(),
})
for sub... | 0.003992 |
def nba_season(x):
"""Takes in 4-digit year for first half of season and returns API appropriate formatted code
Input Values: YYYY
Used in: _Draft.Anthro(), _Draft.Agility(), _Draft.NonStationaryShooting(),
_Draft.SpotUpShooting(), _Draft.Combine()
"""
if len(str(x)) == 4:
try:
... | 0.009646 |
def detect_link_tag_time(self, tag):
"""
Detect link, name and time for specified tag.
:param dict tag: Tag data.
:rtype: str, str, datetime
:return: Link, name and time of the tag.
"""
# if tag is nil - set current time
newer_tag_time = self.get_time_of... | 0.003846 |
def list_policies(self, scaling_group):
"""
Returns a list of all policies defined for the specified scaling group.
"""
uri = "/%s/%s/policies" % (self.uri_base, utils.get_id(scaling_group))
resp, resp_body = self.api.method_get(uri)
return [AutoScalePolicy(self, data, sc... | 0.005115 |
def summarize_edge_filter(graph: BELGraph, edge_predicates: EdgePredicates) -> None:
"""Print a summary of the number of edges passing a given set of filters."""
passed = count_passed_edge_filter(graph, edge_predicates)
print('{}/{} edges passed {}'.format(
passed, graph.number_of_edges(),
(... | 0.005871 |
def add_homogeneous_model(self, magnitude, phase=0):
"""Add a homogeneous resistivity model to the tomodir. This is useful
for synthetic measurements.
Parameters
----------
magnitude : float
magnitude [Ohm m] value of the homogeneous model
phase : float, opti... | 0.00165 |
def exec(self, **kwargs):
"""
Execute solr query
Result object is a dict with the following keys:
- raw
- associations : list
- compact_associations : list
- facet_counts
- facet_pivot
"""
params = self.solr_params()
loggin... | 0.004306 |
def slices(self):
"""Returns a generator yielding tuple of slice objects.
Order is not guaranteed.
"""
if self.chunks is None:
yield tuple(slice(None, s) for s in self.shape)
else:
ceilings = tuple(-(-s // c) for s, c in zip(self.shape, self.chunks))
... | 0.006088 |
def visitLexerAltList(self, ctx: jsgParser.LexerAltListContext):
""" lexerAltList: lexerAlt (LBAR lexerAlt)* """
altlist = ctx.lexerAlt()
self.visit(altlist[0])
for alt in altlist[1:]:
self._rulePattern += '|'
self.visit(alt) | 0.007117 |
def evaluate(self, data, env):
"""
Evaluate the predicates and values
"""
bool_idx = self.predicate_expr.evaluate(data, env)
true_value = self.true_value_expr.evaluate(data, env)
false_value = self.false_value_expr.evaluate(data, env)
true_idx = np.where(bool_idx)... | 0.003442 |
def synthese(self, month=None):
"""
month format: YYYYMM
"""
if month is None and self.legislature == '2012-2017':
raise AssertionError('Global Synthesis on legislature does not work, see https://github.com/regardscitoyens/nosdeputes.fr/issues/69')
if month is None:
... | 0.005618 |
def _open_ftp(self):
# type: () -> FTP
"""Open an ftp object for the file."""
ftp = self.fs._open_ftp()
ftp.voidcmd(str("TYPE I"))
return ftp | 0.016575 |
def Write(self, output_writer):
"""Writes the table to the output writer.
Args:
output_writer (OutputWriter): output writer.
"""
if self._title:
output_writer.Write('### {0:s}\n\n'.format(self._title))
if not self._columns:
self._columns = ['' for _ in range(0, self._number_of_co... | 0.008487 |
def reverse_list_valued_dict(dict_obj):
"""Reverse a list-valued dict, so each element in a list maps to its key.
Parameters
----------
dict_obj : dict
A dict where each key maps to a list of unique values. Values are
assumed to be unique across the entire dict, on not just per-list.
... | 0.001295 |
def unindex(self, data, field):
'''Remove index of a given set of data'''
indices = extractIndices(self.index_fields[field])
for doc in data:
if doc:
for _, index, preprocess in indices:
index.unindex(preprocess(doc))
for index_type, inde... | 0.00369 |
def gmres_mgs(A, b, x0=None, tol=1e-5, restrt=None, maxiter=None, xtype=None,
M=None, callback=None, residuals=None, reorth=False):
"""Generalized Minimum Residual Method (GMRES) based on MGS.
GMRES iteratively refines the initial solution guess to the system
Ax = b
Modified Gram-Schmidt ... | 0.00026 |
def get_log(self, log_id, timeout=None):
""" API call to get a specific log entry """
return self._api_request(
self.GET_LOG_ENDPOINT % log_id,
self.HTTP_GET,
timeout=timeout
) | 0.008475 |
def _get_game_number(cls, gid_path):
"""
Game Number
:param gid_path: game logs directory path
:return: game number(int)
"""
game_number = str(gid_path[len(gid_path)-2:len(gid_path)-1])
if game_number.isdigit():
return int(game_number)
else:
... | 0.00578 |
def get_or_create_media(self, api_media):
"""
Find or create a Media object given API data.
:param api_media: the API data for the Media
:return: a tuple of an Media instance and a boolean indicating whether the Media was created or not
"""
return Media.objects.get_or_cr... | 0.007905 |
def from_uniform(
cls, z, origin=(0, 0), step=(1, 1), formatter=numpy_formatter):
"""Construct a contour generator from a uniform grid.
NOTE
----
The default `origin` and `step` values is equivalent to calling
:meth:`matplotlib.axes.Axes.contour` with only the `z` ar... | 0.000993 |
def check_strict(self, name, original, loc, tokens):
"""Check that syntax meets --strict requirements."""
internal_assert(len(tokens) == 1, "invalid " + name + " tokens", tokens)
if self.strict:
raise self.make_err(CoconutStyleError, "found " + name, original, loc)
else:
... | 0.011628 |
def get_modules(paths, toplevel=True):
"""Take files from the command line even if they don't end with .py."""
modules = []
for path in paths:
path = os.path.abspath(path)
if toplevel and path.endswith('.pyc'):
sys.exit('.pyc files are not supported: {0}'.format(path))
if... | 0.00133 |
def leaders_in(self, leaderboard_name, current_page, **options):
'''
Retrieve a page of leaders from the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param current_page [int] Page to retrieve from the named leaderboard.
@param options [Hash] Opti... | 0.0027 |
def load_content(self, account_id, urls):
"""Prefetches one or more URLs to the CDN edge nodes.
:param int account_id: the CDN account ID into which content should be
preloaded.
:param urls: a string or a list of strings representing the CDN URLs
... | 0.002356 |
def remove_all(self, *tagnames):
"""
Remove all child elements whose tagname (e.g. 'a:p') appears in
*tagnames*.
"""
for tagname in tagnames:
matching = self.findall(qn(tagname))
for child in matching:
self.remove(child) | 0.006667 |
def upload_s3(file_path, bucket_name, file_key, force=False, acl='private'):
"""Upload a local file to S3.
"""
file_path = path(file_path)
bucket = open_s3(bucket_name)
if file_path.isdir():
# Upload the contents of the dir path.
paths = file_path.listdir()
paths_keys = list... | 0.002976 |
def _change_state(interface, new_state):
'''
Enable or disable an interface
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param interface: interface label
:param new_state: up or down
:return: True if the service was enabled, otherwise an e... | 0.006552 |
def oauth2_auth_url(redirect_uri=None, client_id=None, base_url=OH_BASE_URL):
"""
Returns an OAuth2 authorization URL for a project, given Client ID. This
function constructs an authorization URL for a user to follow.
The user will be redirected to Authorize Open Humans data for our external
applica... | 0.000657 |
def pick_config_ids(device_type, os, navigator):
"""
Select one random pair (device_type, os_id, navigator_id) from
all possible combinations matching the given os and
navigator filters.
:param os: allowed os(es)
:type os: string or list/tuple or None
:param navigator: allowed browser engin... | 0.001103 |
def agent_from_entity(self, relation, entity_id):
"""Create a (potentially grounded) INDRA Agent object from a given
Medscan entity describing the subject or object.
Uses helper functions to convert a Medscan URN to an INDRA db_refs
grounding dictionary.
If the entity has prope... | 0.000276 |
def from_json_to_list(cls, data: str,
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T]:
"""From json string to list of instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PE... | 0.008036 |
def _done_callback(self, wrapped):
"""Internal "done callback" to set the result of the object.
The result of the object if forced by the wrapped future. So this
internal callback must be called when the wrapped future is ready.
Args:
wrapped (Future): the wrapped Future ob... | 0.004167 |
def vocab_to_json(vocab: Vocab, path: str):
"""
Saves vocabulary in human-readable json.
:param vocab: Vocabulary mapping.
:param path: Output file path.
"""
with open(path, "w", encoding=C.VOCAB_ENCODING) as out:
json.dump(vocab, out, indent=4, ensure_ascii=False)
logger.info('... | 0.002841 |
def rename_document(self, old_path, new_path):
"""
Renames an already opened document (this will not rename the file,
just update the file path and tab title).
Use that function to update a file that has been renamed externally.
:param old_path: old path (path of the widget to ... | 0.00213 |
def check_credentials(self, username, password):
"""
Override credential checking to use configured credentials.
"""
return password is not None and self.credentials.get(username, None) == password | 0.013043 |
def get_alert_history(self, id, **kwargs): # noqa: E501
"""Get the version history of a specific alert # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_ale... | 0.002083 |
def delayed_redraw(self):
"""Handle delayed redrawing of the canvas."""
# This is the optimized redraw method
with self._defer_lock:
# pick up the lowest necessary level of redrawing
whence = self._defer_whence
self._defer_whence = self._defer_whence_reset
... | 0.003984 |
def _pad_nochord(target, axis=-1):
'''Pad a chord annotation with no-chord flags.
Parameters
----------
target : np.ndarray
the input data
axis : int
the axis along which to pad
Returns
-------
target_pad
`target` expanded by 1 along the specified `axis`.
... | 0.001848 |
def _split_on_reappear(cls, df, p, id_offset):
"""Assign a new identity to an objects that appears after disappearing previously.
Works on `df` in-place.
:param df: data frame
:param p: presence
:param id_offset: offset added to new ids
:return:
"""
next_... | 0.002863 |
def process(self, item_session: ItemSession, request, response, file_writer_session):
'''Process PhantomJS.
Coroutine.
'''
if response.status_code != 200:
return
if not HTMLReader.is_supported(request=request, response=response):
return
_logger.... | 0.002634 |
def oauth_signup(self, provider, attrs, defaults, redirect_url=None):
"""Start the signup process after having logged in via oauth
"""
session["oauth_user_defaults"] = defaults
session["oauth_user_attrs"] = dict(provider=provider, **attrs)
if not redirect_url:
redirec... | 0.004695 |
def plot(self, entity):
"""
Basic plot of a single binary sensor data.
Parameters
----------
entity : string
The entity to plot
"""
df = self._binary_df[[entity]]
resampled = df.resample("s").ffill() # Sample at seconds and ffill
resa... | 0.003444 |
def decompose_position(self, offset):
"""
Returns a ``line, column`` tuple for a character offset into the source,
orraises :exc:`IndexError` if ``lineno`` is out of range.
"""
line_begins = self._extract_line_begins()
lineno = bisect.bisect_right(line_begins, offset) - 1... | 0.006098 |
def call_sockeye_train(model: str,
bpe_dir: str,
model_dir: str,
log_fname: str,
num_gpus: int,
test_mode: bool = False):
"""
Call sockeye.train with specified arguments on prepared inputs. Will r... | 0.00349 |
def _load_dataset_info():
"""This loads dataset info from three package files:
vega_datasets/datasets.json
vega_datasets/dataset_info.json
vega_datasets/local_datasets.json
It returns a dictionary with dataset information.
"""
def load_json(path):
raw = pkgutil.get_data('vega_datas... | 0.001443 |
def do_gen(argdict):
'''Generate the whole site.'''
site = make_site_obj(argdict)
try:
st = time.time()
site.generate()
et = time.time()
print "Generated Site in %f seconds."% (et-st)
except ValueError as e: # pragma: no cover
print "Cannot generate. You are not w... | 0.010417 |
def unsquish(incs, f):
"""
This function applies uses a flattening factor (f) to unflatten inclination
data (incs) and returns 'unsquished' values.
Parameters
----------
incs : list of inclination values or a single value
f : unflattening factor (between 0.0 and 1.0)
Returns
------... | 0.001477 |
def queryModelIDs(self):
"""Queuries DB for model IDs of all currently instantiated models
associated with this HyperSearch job.
See also: _iterModels()
Parameters:
----------------------------------------------------------------------
retval: A sequence of Nupic modelIDs
"""
j... | 0.002049 |
def _command_sender(self):
""" Command sender. """
sequence = -1
while True:
cmd = self._queue.get()
ipaddr = cmd["target"]
payloadtype = cmd["payloadtype"]
if "sequence" not in cmd:
# get next sequence number if we haven't got o... | 0.001067 |
def addLabel(self, start, end, labelName):
"""
Add the label labelName to each record with record ROWID in range from
start to end, noninclusive of end.
This will recalculate all points from end to the last record stored in the
internal cache of this classifier.
"""
if len(self.saved_states... | 0.010137 |
def read(cls, fname):
""" read(fname, fmt)
This classmethod is the entry point for reading OBJ files.
Parameters
----------
fname : str
The name of the file to read.
fmt : str
Can be "obj" or "gz" to specify the file format.
"""
#... | 0.002232 |
def fa(arr, t, dist='norm', mode='high'):
"""Return the value corresponding to the given return period.
Parameters
----------
arr : xarray.DataArray
Maximized/minimized input data with a `time` dimension.
t : int or sequence
Return period. The period depends on the resolution of the inp... | 0.003692 |
def _create_doc_summary(self, obj, fullname, refrole):
"""Create a paragraph containing the object's one-sentence docstring
summary with a link to further documentation.
The paragrah should be inserted into the ``desc`` node's
``desc_content``.
"""
summary_text = extract... | 0.00274 |
def main():
"""
main method
"""
# initialize parser
usage = "usage: %prog [-u USER] [-p PASSWORD] [-t TITLE] [-s selection] url"
parser = OptionParser(usage, version="%prog "+instapaperlib.__version__)
parser.add_option("-u", "--user", action="store", dest="user",
m... | 0.001122 |
def main():
""" Run the simulation """
parser = argparse.ArgumentParser(prog='opentrons_simulate',
description=__doc__)
parser.add_argument(
'protocol', metavar='PROTOCOL_FILE',
type=argparse.FileType('r'),
help='The protocol file to simulate (spe... | 0.000865 |
def _module_name_from_previous_frame(num_frames_back):
"""
Returns the module name associated with a frame `num_frames_back` in the
call stack. This function adds 1 to account for itself, so `num_frames_back`
should be given relative to the caller.
"""
frm = inspect.stack()[num_frames_back + 1]
... | 0.005479 |
def outline(self, level=logging.INFO, message=""):
"""Print an outline of the actions the plan is going to take.
The outline will represent the rough ordering of the steps that will be
taken.
Args:
level (int, optional): a valid log level that should be used to log
... | 0.00227 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.