text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _setup_db(cls):
"""
Setup the DB connection if DB_URL is set
"""
uri = cls._app.config.get("DB_URL")
if uri:
db.connect__(uri, cls._app) | 0.015544 |
def naive(gold_schemes):
"""find naive baseline (most common scheme of a given length)?"""
scheme_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'schemes.json')
with open(scheme_path, 'r') as f:
dist = json.loads(f.read())
best_schemes = {}
for i in dist.keys():
... | 0.005102 |
def key_from_password(password):
"""This method just hashes self.password."""
if isinstance(password, unicode):
password = password.encode('utf-8')
if not isinstance(password, bytes):
raise TypeError("password must be byte string, not %s" % type(password))
sha = SHA256.new()
sha... | 0.00831 |
def rx_filter(header, data):
"""Check if the message in rx_data matches to the information in header.
The following checks are done:
- Header checksum
- Payload checksum
- NetFn matching
- LUN matching
- Command Id matching
header: the header to compare with
data: the rec... | 0.000792 |
def export_pipeline(url, pipeline_id, auth, verify_ssl):
"""Export the config and rules for a pipeline.
Args:
url (str): the host url in the form 'http://host:port/'.
pipeline_id (str): the ID of of the exported pipeline.
auth (tuple): a tuple of username, and password.
... | 0.002774 |
def bids_to_pwl(self, bids):
""" Updates the piece-wise linear total cost function using the given
bid blocks.
Based on off2case.m from MATPOWER by Ray Zimmerman, developed at PSERC
Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info.
"""
assert self.is_... | 0.001207 |
def filter(self, table, group_types, filter_string):
"""Naive case-insensitive search."""
query = filter_string.lower()
return [group_type for group_type in group_types
if query in group_type.name.lower()] | 0.008163 |
def future(self, request, timeout=None, metadata=None, credentials=None):
"""Asynchronously invokes the underlying RPC.
Args:
request: The request value for the RPC.
timeout: An optional duration of time in seconds to allow for the RPC.
metadata: Optional :term:`metadata` to be transmitte... | 0.003261 |
def delete(self):
"""
Remove entries from the table. Often combined with `where`, as it acts
on all records in the table unless restricted.
"""
cmd = "delete from {table} {where_clause}".format(
table=self.table_name,
where_clause=self.where_clause
... | 0.005277 |
def stopObserver(self):
""" Stops this region's observer loop.
If this is running in a subprocess, the subprocess will end automatically.
"""
self._observer.isStopped = True
self._observer.isRunning = False | 0.012146 |
def load_config(self, **kwargs):
"""Load the configuration for the user or seed it with defaults.
:return: Boolean if successful
"""
virgin_config = False
if not os.path.exists(CONFIG_PATH):
virgin_config = True
os.makedirs(CONFIG_PATH)
if not os.... | 0.003049 |
def _allocate(self, dut_configuration): # pylint: disable=too-many-branches
"""
Internal allocation function. Allocates a single resource based on dut_configuration.
:param dut_configuration: ResourceRequirements object which describes a required resource
:return: True
:raises:... | 0.004202 |
def set(self, target, value):
"""Set the value of this attribute for the passed object.
"""
if not self._set:
return
if self.path is None:
# There is no path defined on this resource.
# We can do no magic to set the value.
self.set = lamb... | 0.001675 |
def dead(cls, reason=None, **kwargs):
"""
Syntax helper to construct a dead message.
"""
kwargs['data'], _ = UTF8_CODEC.encode(reason or u'')
return cls(reply_to=IS_DEAD, **kwargs) | 0.009091 |
def run(options, exit_codeword=None):
"""Actually execute the program.
Calling this method can be done from tests to simulate executing the
application from command line.
Parameters:
options -- `optionparser` from config file.
exit_codeword -- an optional exit_message that will shut down... | 0.000372 |
def prefix_size(size, base=1024):
'''Return size in B (bytes), kB, MB, GB or TB.'''
if ARGS.prefix == 'None':
for i, prefix in enumerate(['', 'ki', 'Mi', 'Gi', 'Ti']):
if size < pow(base, i + 1):
return '{0} {1}B'.format(round(float(size) / pow(base, i), 1),
... | 0.001585 |
def list_to_str(lst):
"""
Turn a list into a comma- and/or and-separated string.
Parameters
----------
lst : :obj:`list`
A list of strings to join into a single string.
Returns
-------
str_ : :obj:`str`
A string with commas and/or ands separating th elements from ``lst`... | 0.001626 |
def _filter_in(self, term_list, field_name, field_type, is_not):
"""
Returns a query that matches exactly ANY term in term_list.
Notice that:
A in {B,C} <=> (A = B or A = C)
~(A in {B,C}) <=> ~(A = B or A = C)
Because OP_AND_NOT(C, D) <=> (C and ~D), then D=(A in {B,C}... | 0.005175 |
def get_black(self):
"""Return blacklist packages from /etc/slpkg/blacklist
configuration file."""
blacklist = []
for read in self.black_conf.splitlines():
read = read.lstrip()
if not read.startswith("#"):
blacklist.append(read.replace("\n", ""))
... | 0.005831 |
def process_request_thread(self, mainthread):
"""obtain request from queue instead of directly from server socket"""
life_time = time.time()
nb_requests = 0
while not mainthread.killed():
if self.max_life_time > 0:
if (time.time() - life_time) >= self.max_l... | 0.006141 |
def find(self, query):
'''Passes the query to the upstream, if it exists'''
if self.upstream:
return self.upstream.find(query)
else:
return False | 0.010363 |
def samples(self):
"""Yield samples as dictionaries, keyed by dimensions."""
names = self.series.dimensions
for n, offset in enumerate(self.series.offsets):
dt = datetime.timedelta(microseconds=offset * 1000)
d = {"ts": self.ts + dt}
for name in names:
... | 0.005155 |
def clear(self, apply_to='all'):
"""
Clear range values, format, fill, border, etc.
:param str apply_to: Optional. Determines the type of clear action.
The possible values are: all, formats, contents.
"""
url = self.build_url(self._endpoints.get('clear_range'))
r... | 0.007595 |
def charges_net_effect(self):
"""
The total effect of the net_affecting charges (note affect vs effect here).
Currently this is single currency only (AMAAS-110).
Cast to Decimal in case the result is zero (no net_affecting charges).
:return:
"""
return Decimal(... | 0.009195 |
def security_rule_absent(name, security_group, resource_group, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a security rule does not exist in the network security group.
:param name:
Name of the security rule.
:param security_group:
The network security group conta... | 0.002646 |
def close_threads(self, parent):
"""Close threads associated to parent_id"""
logger.debug("Call ThreadManager's 'close_threads'")
if parent is None:
# Closing all threads
self.pending_threads = []
threadlist = []
for threads in list(self.sta... | 0.002116 |
def zpipe(ctx):
"""build inproc pipe for talking to threads
mimic pipe used in czmq zthread_fork.
Returns a pair of PAIRs connected via inproc
"""
a = ctx.socket(zmq.PAIR)
a.linger = 0
b = ctx.socket(zmq.PAIR)
b.linger = 0
socket_set_hwm(a, 1)
socket_set_hwm(b, 1)
iface = "... | 0.002375 |
def get_field_mappings(self, field):
"""Converts ES field mappings to .kibana field mappings"""
retdict = {}
retdict['indexed'] = False
retdict['analyzed'] = False
for (key, val) in iteritems(field):
if key in self.mappings:
if (key == 'type' and
... | 0.002094 |
def _refresh(self):
"""Refresh the API token using the currently bound credentials.
This is simply a convenience method to be invoked automatically if authentication fails
during normal client use.
"""
# Request and set a new API token.
new_token = self.authenticate(self... | 0.006289 |
def get_observed_mmax_sigma(self, default=None):
"""
:returns: the sigma for the maximum observed magnitude
"""
if not isinstance(self.data['sigmaMagnitude'], np.ndarray):
obsmaxsig = default
else:
obsmaxsig = self.data['sigmaMagnitude'][
n... | 0.005291 |
def _CountClientStatisticByLabel(self, statistic, day_buckets, cursor):
"""Returns client-activity metrics for a given statistic.
Args:
statistic: The name of the statistic, which should also be a column in the
'clients' table.
day_buckets: A set of n-day-active buckets.
cursor: MySQL... | 0.005876 |
def post(self, result_id, project_id):
"""POST /api/v1/results/<int:id>/commands."""
result = db.session.query(Result).filter_by(id=result_id).first()
if result is None:
return jsonify({
'result': None,
'message': 'No interface defined for URL.'
... | 0.000873 |
def call_on_commit(self, callback):
"""Call a callback upon successful commit of a transaction.
If not in a transaction, the callback is called immediately.
In a transaction, multiple callbacks may be registered and will be
called once the transaction commits, in the order in which they
were regis... | 0.003333 |
def register_model(self, model_id, properties, parameters, outputs, connector):
"""Create an experiment object for the subject and image group. Objects
are referenced by their identifier. The reference to a functional data
object is optional.
Raises ValueError if no valid experiment nam... | 0.002586 |
def get_minions():
'''
Return a list of minions
'''
query = '''SELECT DISTINCT minion_id
FROM {keyspace}.minions;'''.format(keyspace=_get_keyspace())
ret = []
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
data = __salt__['cassandra_cql.cql_query'](... | 0.001353 |
def cleanup(self):
"""Cleanup all the expired keys"""
keys = self.client.smembers(self.keys_container)
for key in keys:
entry = self.client.get(key)
if entry:
entry = pickle.loads(entry)
if self._is_expired(entry, self.timeout):
... | 0.005698 |
def update_column(self, header, column):
"""Update a column named `header` in the table.
If length of column is smaller than number of rows, lets say
`k`, only the first `k` values in the column is updated.
Parameters
----------
header : str
Header of the co... | 0.002378 |
def keys_to_string(data):
"""
Function to convert all the unicode keys in string keys
"""
if isinstance(data, dict):
for key in list(data.keys()):
if isinstance(key, six.string_types):
value = data[key]
val = keys_to_string(value)
del d... | 0.002494 |
def parse_directive_definition(lexer: Lexer) -> DirectiveDefinitionNode:
"""InputObjectTypeExtension"""
start = lexer.token
description = parse_description(lexer)
expect_keyword(lexer, "directive")
expect_token(lexer, TokenKind.AT)
name = parse_name(lexer)
args = parse_argument_defs(lexer)
... | 0.001733 |
def close_all_pages(self):
"""Closes all tabs of the states editor"""
states_to_be_closed = []
for state_identifier in self.tabs:
states_to_be_closed.append(state_identifier)
for state_identifier in states_to_be_closed:
self.close_page(state_identifier, delete=Fal... | 0.006192 |
def self_build(self, field_pos_list=None):
# type: (Any) -> str
"""self_build is overridden because type and len are determined at
build time, based on the "data" field internal type
"""
if self.getfieldval('type') is None:
self.type = 1 if isinstance(self.getfieldval... | 0.006912 |
def fetch(self, country_code=values.unset, type=values.unset,
add_ons=values.unset, add_ons_data=values.unset):
"""
Fetch a PhoneNumberInstance
:param unicode country_code: The ISO country code of the phone number
:param unicode type: The type of information to return
... | 0.006244 |
def _get_edges(self):
"""Get the edges for the current surface.
If they haven't been computed yet, first compute and store them.
This is provided as a means for internal calls to get the edges
without copying (since :attr:`.edges` copies before giving to
a user to keep the stor... | 0.003247 |
def _closing_bracket_index(self, text, bpair=('(', ')')):
"""Return the index of the closing bracket that matches the opening bracket at the start of the text."""
level = 1
for i, char in enumerate(text[1:]):
if char == bpair[0]:
level += 1
elif char == bp... | 0.007317 |
def export_to_crtomo_seit_manager(self, grid):
"""Return a ready-initialized seit-manager object from the CRTomo
tools. This function only works if the crtomo_tools are installed.
"""
import crtomo
g = self.data.groupby('frequency')
seit_data = {}
for name, item i... | 0.003306 |
def get_dependencies_from_cache(ireq):
"""Retrieves dependencies for the given install requirement from the dependency cache.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequ... | 0.001554 |
def drop_matching_records(self, check):
"""Remove a record from the DB."""
matches = self._match(check)
for m in matches:
del self._records[m['msg_id']] | 0.010638 |
def verbosity(self, *args):
'''
get/set the verbosity level.
The verbosity level filters messages that are output
to the console. Only messages tagged with a verbosity
less-than-or-equal-to the class verbosity are output.
This does not affect output to non-console devic... | 0.006601 |
def select_one_album(albums):
"""Display the albums returned by search api.
:params albums: API['result']['albums']
:return: a Album object.
"""
if len(albums) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Album Name', 'Artist Name']... | 0.002353 |
def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=None):
"""Create a leaf Fake directory + create any non-existent parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directories) with.... | 0.001951 |
def check_messages(msgs, cmd, value=None):
"""Check if specific message is present.
Parameters
----------
cmd : string
Command to check for in bytestring from microscope CAM interface. If
``value`` is falsey, value of received command does not matter.
value : string
Check if... | 0.001563 |
def api_user(request, userPk, key=None, hproPk=None):
"""Return information about an user"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
if settings.PIAPI_STANDALONE:
if not settings.PIAPI_REALUSERS:
user = generate_user(pk=userPk)
if us... | 0.001571 |
def _build_ref_data_names(self, project, build_system):
'''
We want all reference data names for every task that runs on a specific project.
For example:
* Buildbot - "Windows 8 64-bit mozilla-inbound debug test web-platform-tests-1"
* TaskCluster = "test-linux64/opt-moc... | 0.002591 |
def bitterness(self, ibu_method, early_og, batch_size):
"Calculate bitterness based on chosen method"
if ibu_method == "tinseth":
bitterness = 1.65 * math.pow(0.000125, early_og - 1.0) * ((1 - math.pow(math.e, -0.04 * self.time)) / 4.15) * ((self.alpha / 100.0 * self.amount * 1000000) / bat... | 0.006468 |
def polarization_vector(phi, theta, alpha, beta, p,
numeric=False, abstract=False):
"""This function returns a unitary vector describing the polarization
of plane waves.:
INPUT:
- ``phi`` - The spherical coordinates azimuthal angle of the wave vector\
k.
- ``theta`` - Th... | 0.000355 |
def amplitude(self, caldb, calv, atten=0):
"""Calculates the voltage amplitude for this stimulus, using
internal intensity value and the given reference intensity & voltage
:param caldb: calibration intensity in dbSPL
:type caldb: float
:param calv: calibration voltage that was ... | 0.006237 |
def service_delete(auth=None, **kwargs):
'''
Delete a service
CLI Example:
.. code-block:: bash
salt '*' keystoneng.service_delete name=glance
salt '*' keystoneng.service_delete name=39cc1327cdf744ab815331554430e8ec
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwar... | 0.005348 |
def argument_types(self):
"""Retrieve a container for the non-variadic arguments for this type.
The returned object is iterable and indexable. Each item in the
container is a Type instance.
"""
class ArgumentsIterator(collections.Sequence):
def __init__(self, parent)... | 0.002874 |
def isalive(self):
'''This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
... | 0.003605 |
def get_package_status(owner, repo, identifier):
"""Get the status for a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_status_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratel... | 0.001592 |
def render(self):
""" Returns the rendered release notes from all parsers as a string """
release_notes = []
for parser in self.parsers:
parser_content = parser.render()
if parser_content is not None:
release_notes.append(parser_content)
return u"\... | 0.005747 |
def get_svnpath():
'''
This subroutine gives back the path of the whole svn tree
installation, which is necessary for the script to run.
'''
svnpathtmp = __file__
splitsvnpath = svnpathtmp.split('/')
if len(splitsvnpath) == 1:
svnpath = os.path.abspath('.') + '/../../'
else:
... | 0.002242 |
def removeSessionWithKey(self, key):
"""
Remove a persistent session, if it exists.
@type key: L{bytes}
@param key: The persistent session identifier.
"""
self.store.query(
PersistentSession,
PersistentSession.sessionKey == key).deleteFromStore() | 0.00627 |
def configure_stack():
"""Set up the OpenDNP3 configuration."""
stack_config = asiodnp3.OutstationStackConfig(opendnp3.DatabaseSizes.AllTypes(10))
stack_config.outstation.eventBufferConfig = opendnp3.EventBufferConfig().AllTypes(10)
stack_config.outstation.params.allowUnsolicited = True
... | 0.007952 |
def render_html(html_str):
"""
makes a temporary html rendering
"""
import utool as ut
from os.path import abspath
import webbrowser
try:
html_str = html_str.decode('utf8')
except Exception:
pass
html_dpath = ut.ensure_app_resource_dir('utool', 'temp_html')
fpat... | 0.002203 |
def _shutdown_proc(p, timeout):
"""Wait for a proc to shut down, then terminate or kill it after `timeout`."""
freq = 10 # how often to check per second
for _ in range(1 + timeout * freq):
ret = p.poll()
if ret is not None:
logging.info("Shutdown gracefully.")
return ret
time.sleep(1 / fr... | 0.025381 |
def custom_getter_router(custom_getter_map, name_fn):
"""Creates a custom getter than matches requests to dict of custom getters.
Custom getters are callables which implement the
[custom getter API]
(https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/get_variable).
The returned custom getter dispat... | 0.004521 |
def getConf(self, conftype):
'''
conftype must be a Zooborg constant
'''
zooconf={}
if conftype not in [ZooConst.CLIENT, ZooConst.WORKER, ZooConst.BROKER]:
raise Exception('Zooborg.getConf: invalid type')
self.initconn()
if conftype in [ZooConst.CLIEN... | 0.009067 |
def refreshButton(self):
"""
Refreshes the button for this toolbar.
"""
collapsed = self.isCollapsed()
btn = self._collapseButton
if not btn:
return
btn.setMaximumSize(MAX_SIZE, MAX_SIZE)
# set up a vertical... | 0.007143 |
def queuedb_find(path, queue_id, name, offset=None, limit=None):
"""
Find a record by name and queue ID.
Return the rows on success (empty list if not found)
Raise on error
"""
return queuedb_findall(path, queue_id, name=name, offset=offset, limit=limit) | 0.007194 |
def AddConnectedPeer(self, peer):
"""
Add a new connect peer to the known peers list.
Args:
peer (NeoNode): instance.
"""
# if present
self.RemoveFromQueue(peer.address)
self.AddKnownAddress(peer.address)
if len(self.Peers) > settings.CONNECT... | 0.003831 |
def _generate(cls, strategy, params):
"""generate the object.
Args:
params (dict): attributes to use for generating the object
strategy: the strategy to use
"""
if cls._meta.abstract:
raise errors.FactoryError(
"Cannot generate instanc... | 0.003401 |
def eval_conditions(conditions=None, data={}):
'''
Evaluates conditions and returns Boolean value.
Args:
conditions (tuple) for the format of the tuple, see below
data (dict) the keys of which can be used in conditions
Returns:
(boolea)
Raises:
ValueError if an inval... | 0.003279 |
def run_changed_file_cmd(cmd, fp, pretty):
""" running commands on changes.
pretty the parsed file
"""
with open(fp) as f:
raw = f.read()
# go sure regarding quotes:
for ph in (dir_mon_filepath_ph, dir_mon_content_raw,
dir_mon_content_pretty):
if ph in cmd and... | 0.002522 |
def find(cls, channel, start, end, frametype=None, pad=None,
scaled=None, dtype=None, nproc=1, verbose=False, **readargs):
"""Find and read data from frames for a channel
Parameters
----------
channel : `str`, `~gwpy.detector.Channel`
the name of the channel to ... | 0.001391 |
def run_from_argv(self, argv):
"""
Runs command for given arguments.
:param argv: arguments
"""
parser = self.get_parser(argv[0], argv[1])
options, args = parser.parse_args(argv[2:])
self.execute(*args, **options.__dict__) | 0.007168 |
def _set_src_port_any(self, v, load=False):
"""
Setter method for src_port_any, mapped from YANG variable /overlay/access_list/type/vxlan/extended/ext_seq/src_port_any (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_src_port_any is considered as a private
met... | 0.005552 |
def parse_venue(data):
"""
Parse a ``MeetupVenue`` from the given response data.
Returns
-------
A `pythonkc_meetups.types.`MeetupVenue``.
"""
return MeetupVenue(
id=data.get('id', None),
name=data.get('name', None),
address_1=data.get('address_1', None),
ad... | 0.001582 |
def get_ids_g_goids(self, goids):
"""Get database IDs (DB_IDs), given a set of GO IDs."""
return set(nt.DB_ID for nt in self.associations if nt.GO_ID in goids) | 0.011429 |
def IsLink(self):
"""Determines if the file entry is a link.
Returns:
bool: True if the file entry is a link.
"""
if self._stat_object is None:
self._stat_object = self._GetStat()
if self._stat_object is not None:
self.entry_type = self._stat_object.type
return self.entry_type... | 0.008427 |
def update_model(self, name, **kw):
"""
Update a model in the registry (create if needed)
:param name: name for the model
:param datapackage_url: origin URL for the datapackage which is the
source for this model
:param datapackage: datapackage object from which this m... | 0.000884 |
def load_balancer_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific load balancer.
:param name: The name of the load balancer to query.
:param resource_group: The resource group name assigned to the
load balancer.
CLI Example:
.. co... | 0.001188 |
def setState(self, state):
"""See comments in base class."""
self._position = state['_position']
self._velocity = state['velocity']
self._bestPosition = state['bestPosition']
self._bestResult = state['bestResult'] | 0.004292 |
def add(self, key, value):
"""Add an entry to a list preference
Add `value` to the list of entries for the `key` preference.
"""
if not key in self.prefs:
self.prefs[key] = []
self.prefs[key].append(value) | 0.011583 |
def setup_fake_forward_run(pst,new_pst_name,org_cwd='.',bak_suffix="._bak",new_cwd='.'):
"""setup a fake forward run for a pst. The fake
forward run simply copies existing backup versions of
model output files to the outfiles pest(pp) is looking
for. This is really a development option for debugging
... | 0.008287 |
def access_add(name, event, cid, uid, **kwargs):
"""
Creates a new record with specified cid/uid in the event authorization.
Requests with token that contains such cid/uid will have access to the specified event of a
service.
"""
ctx = Context(**kwargs)
ctx.execute_action('access:add', **{
... | 0.004175 |
def add_string(self, s):
"""
Add a string to the stream.
:param str s: string to add
"""
s = asbytes(s)
self.add_size(len(s))
self.packet.write(s)
return self | 0.012987 |
def gaussian(data, mean, covariance):
"""!
@brief Calculates gaussian for dataset using specified mean (mathematical expectation) and variance or covariance in case
multi-dimensional data.
@param[in] data (list): Data that is used for gaussian calculation.
@param[in] mean (float|n... | 0.013115 |
def read_memory(self, space, offset, width, extended=False):
"""Reads in an 8-bit, 16-bit, 32-bit, or 64-bit value from the specified memory space and offset.
:param space: Specifies the address space. (Constants.*SPACE*)
:param offset: Offset (in bytes) of the address or register from which to... | 0.007764 |
def retract(self, e, a, v):
""" redact the value of an attribute
"""
ta = datetime.datetime.now()
ret = u"[:db/retract %i :%s %s]" % (e, a, dump_edn_val(v))
rs = self.tx(ret)
tb = datetime.datetime.now() - ta
print cl('<<< retracted %s,%s,%s in %sms' % (e,a,v, tb.microseconds/1000.0), 'cyan'... | 0.01194 |
def logout(self):
"""
Log out, revoking the access tokens
and forgetting the login details if they were given.
"""
self.revoke_refresh_token()
self.revoke_access_token()
self._username, self._password = None, None | 0.00738 |
def take_until_including(condition):
"""
>>> [1, 4, 6, 4, 1] > take_until_including(X > 5) | list
[1, 4, 6]
"""
def take_until_including_(interable):
for i in interable:
if not condition(i):
yield i
else:
yield i
break
... | 0.002849 |
def chunks_str(str, n, separator="\n", fill_blanks_last=True):
"""returns lines with max n characters
:Example:
>>> print (chunks_str('123456X', 3))
123
456
X
"""
return separator.join(chunks(str, n)) | 0.004016 |
def _create_job_info(self, job_dir):
"""Create information for given job.
Meta file will be loaded if exists, and the job information will
be saved in db backend.
Args:
job_dir (str): Directory path of the job.
"""
meta = self._build_job_meta(job_dir)
... | 0.004556 |
def _nelec(self):
""" Particles per unit lorentz factor
"""
pd = self.particle_distribution(self._gam * mec2)
return pd.to(1 / mec2_unit).value | 0.011429 |
def quic_graph_lasso_cv(X, metric):
"""Run QuicGraphicalLassoCV on data with metric of choice.
Compare results with GridSearchCV + quic_graph_lasso. The number of
lambdas tested should be much lower with similar final lam_ selected.
"""
print("QuicGraphicalLassoCV with:")
print(" metric: {}"... | 0.001305 |
def compute_histogram(values, edges, use_orig_distr=False):
"""Computes histogram (density) for a given vector of values."""
if use_orig_distr:
return values
# ignoring invalid values: Inf and Nan
values = check_array(values).compressed()
hist, bin_edges = np.histogram(values, bins=edges,... | 0.002475 |
def opt_rankings(n_items, data, alpha=1e-6, method="Newton-CG",
initial_params=None, max_iter=None, tol=1e-5):
"""Compute the ML estimate of model parameters using ``scipy.optimize``.
This function computes the maximum-likelihood estimate of model parameters
given ranking data (see :ref:`data-ranki... | 0.001385 |
def plot_observer(population, num_generations, num_evaluations, args):
"""Plot the output of the evolutionary computation as a graph.
This function plots the performance of the EC as a line graph
using matplotlib and numpy. The graph consists of a blue line
representing the best fitness, a gr... | 0.005889 |
def parse_definite_clause(s):
"Return the antecedents and the consequent of a definite clause."
assert is_definite_clause(s)
if is_symbol(s.op):
return [], s
else:
antecedent, consequent = s.args
return conjuncts(antecedent), consequent | 0.003623 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.