text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def iterators(self, frequency=None):
"""
Returns the iterators (i.e. subject_id, visit_id) that the pipeline
iterates over
Parameters
----------
frequency : str | None
A selected data frequency to use to determine which iterators are
required. If ... | 0.002946 |
def uri(host='localhost', port=5432, dbname='postgres', user='postgres',
password=None):
"""Return a PostgreSQL connection URI for the specified values.
:param str host: Host to connect to
:param int port: Port to connect on
:param str dbname: The database name
:param str user: User to conn... | 0.001536 |
def addLogHandler(func):
"""
Add a custom log handler.
@param func: a function object with prototype (level, object, category,
message) where level is either ERROR, WARN, INFO, DEBUG, or
LOG, and the rest of the arguments are strings or None. Use
getLevelN... | 0.001626 |
def get_version():
"""
parse __init__.py for version number instead of importing the file
see http://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package
"""
version_file = os.path.join(PKG, 'lib/version.py')
ver_str_line = open(version_file, "rt").read()
vers... | 0.003431 |
def op(self):
"""Returns the Instruction object corresponding to the op for the node else None"""
if 'type' not in self.data_dict or self.data_dict['type'] != 'op':
raise QiskitError("The node %s is not an op node" % (str(self)))
return self.data_dict.get('op') | 0.010101 |
def _parseElfHeader(self, data):
"""Returns the elf header"""
ehdr = self.__classes.EHDR.from_buffer(data)
return EhdrData(header=ehdr) | 0.012579 |
def _observe_block(self, change):
""" A change handler for the 'objects' list of the Include.
If the object is initialized objects which are removed will be
unparented and objects which are added will be reparented. Old
objects will be destroyed if the 'destroy_old' flag is True.
... | 0.002853 |
def save_model(self, request, obj, form, change):
"""
If the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``,
send a notification email to the user being saved if their
``active`` status has changed to ``True``.
If the ``ACCOUNTS_VERIFICATION_REQUIRED`` setting is ``True``,
... | 0.001516 |
def get_repository_ids_by_asset(self, asset_id):
"""Gets the list of ``Repository`` ``Ids`` mapped to an ``Asset``.
arg: asset_id (osid.id.Id): ``Id`` of an ``Asset``
return: (osid.id.IdList) - list of repository ``Ids``
raise: NotFound - ``asset_id`` is not found
raise: N... | 0.001885 |
def _user_thread_main(self, target):
"""Main entry point for the thread that will run user's code."""
try:
# Wait for GLib main loop to start running before starting user code.
while True:
if self._gobject_mainloop is not None and self._gobject_mainloop.is_running... | 0.004655 |
def get_ccle_cna():
"""Get CCLE CNA
-2 = homozygous deletion
-1 = hemizygous deletion
0 = neutral / no change
1 = gain
2 = high level amplification
"""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
... | 0.002028 |
def closeStreamToFile(self) :
"""Appends the remaining commited lines and closes the stream. If no stream is active, raises a ValueError"""
if self.streamBuffer is None :
raise ValueError("Commit lines is only for when you are streaming to a file")
for i in xrange(len(self.streamBuffer)) :
self.streamBuffe... | 0.033582 |
def log(context):
"""See history"""
context.obj.find_repo_type()
if context.obj.vc_name == 'git':
format = ("--pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset "
"%s %Cgreen(%cr) %C(bold blue)<%an>%Creset'")
context.obj.call(['git', 'log', '--graph', format,
... | 0.00161 |
def registration_function_for_optionable(self, optionable_class):
"""Returns a function for registering options on the given scope."""
self._assert_not_frozen()
# TODO(benjy): Make this an instance of a class that implements __call__, so we can
# docstring it, and so it's less weird than attatching prop... | 0.007937 |
def iiscgi(application):
"""A specialized version of the reference WSGI-CGI server to adapt to Microsoft IIS quirks.
This is not a production quality interface and will behave badly under load.
"""
try:
from wsgiref.handlers import IISCGIHandler
except ImportError:
print("Python 3.2 or newer is required.")
... | 0.040512 |
def get_means_and_scales(self):
"""
Gets the mean and scales for normal approximating parameters
"""
return self.optim.parameters[::2], np.exp(self.optim.parameters[1::2]) | 0.009852 |
def get(self, request):
"""
method called on GET request on this view
:param django.http.HttpRequest request: The current request object:
:return: The rendering of ``cas_server/serviceValidate.xml`` if no errors is raised,
the rendering or ``cas_server/servic... | 0.002696 |
def _directory (self):
"""The directory for this AitConfig."""
if self._filename is None:
return os.path.join(self._ROOT_DIR, 'config')
else:
return os.path.dirname(self._filename) | 0.013158 |
def setup_subparser(
self, func=None, setup_as=None, insert_at=None, interprete=True,
epilog_sections=None, overwrite=False, append_epilog=True,
return_parser=False, name=None, **kwargs):
"""
Create a subparser with the name of the given function
Parameters a... | 0.000778 |
def perform(self):
"""
Performs all stored actions.
"""
if self._driver.w3c:
self.w3c_actions.perform()
else:
for action in self._actions:
action() | 0.008811 |
def _assign(self, assignment): # type: (Assignment) -> None
"""
Adds an Assignment to _assignments and _positive or _negative.
"""
self._assignments.append(assignment)
self._register(assignment) | 0.008511 |
def _clear_expired_zones(self):
"""
Update zone status for all expired zones.
"""
zones = []
for z in list(self._zones.keys()):
zones += [z]
for z in zones:
if self._zones[z].status != Zone.CLEAR and self._zone_expired(z):
self._u... | 0.005797 |
def find_elements_by_css_selector(self, css_selector):
"""
Finds elements by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:... | 0.004 |
def _common_rational_period(rational_periods: List[fractions.Fraction]
) -> fractions.Fraction:
"""Finds the least common integer multiple of some fractions.
The solution is the smallest positive integer c such that there
exists integers n_k satisfying p_k * n_k = c for all k.
... | 0.001473 |
def _calc_eddy_time(self):
""" estimate the eddy turn-over time in days """
ens = 0.
for j in range(self.nz):
ens = .5*self.Hi[j] * self.spec_var(self.wv2*self.ph[j])
return 2.*pi*np.sqrt( self.H / ens.sum() ) / 86400 | 0.015267 |
def define_from_values(cls, xdtu, ydtu, zdtu, xdtu_0, ydtu_0, zdtu_0):
"""Define class object from from provided values.
Parameters
----------
xdtu : float
XDTU fits keyword value.
ydtu : float
YDTU fits keyword value.
zdtu : float
ZDT... | 0.002538 |
def get_updates(self, offset=None, limit=None, timeout=None, allowed_updates=None):
"""
Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
Notes1. This method will not work if an outgoing webhook is set up.2. In order to avoid getting ... | 0.007081 |
def as_ompenv(cls, obj):
"""Convert an object into a OmpEnv"""
if isinstance(obj, cls): return obj
if obj is None: return cls()
return cls(**obj) | 0.022599 |
def save_prep(cls, instance_or_instances):
"""Preprocess the object before the object is saved. This
automatically gets called when the save method gets called.
"""
instances = make_obj_list(instance_or_instances)
tokens = set(cls.objects.get_available_tokens(
count... | 0.003273 |
def get_lines_from_to(strings: List[str],
firstlinestart: str,
list_of_lastline_starts: Iterable[Optional[str]]) \
-> List[str]:
"""
Takes a list of ``strings``. Returns a list of strings FROM
``firstlinestart`` (inclusive) TO the first of ``list_of_lastli... | 0.000789 |
def get_street_from_xy(self, **kwargs):
"""Obtain a list of streets around the specified point.
Args:
latitude (double): Latitude in decimal degrees.
longitude (double): Longitude in decimal degrees.
radius (int): Radius (in meters) of the search.
lang (s... | 0.002676 |
def flatten_pages(self, pages, level=1):
"""Recursively flattens pages data structure into a one-dimensional data structure"""
flattened = []
for page in pages:
if type(page) is list:
flattened.append(
{
'f... | 0.003543 |
def getoptT(X, W, Y, Z, S, M_E, E, m0, rho):
''' Perform line search
'''
iter_max = 20
norm2WZ = np.linalg.norm(W, ord='fro')**2 + np.linalg.norm(Z, ord='fro')**2
f = np.zeros(iter_max + 1)
f[0] = F_t(X, Y, S, M_E, E, m0, rho)
t = -1e-1
for i in range(iter_max):
f[i + ... | 0.00211 |
def intermediary_to_schema(tables, relationships, output):
""" Transforms and save the intermediary representation to the file chosen. """
dot_file = _intermediary_to_dot(tables, relationships)
graph = AGraph()
graph = graph.from_string(dot_file)
extension = output.split('.')[-1]
graph.draw(path... | 0.005587 |
def nb_persons(self, role = None):
"""
Returns the number of persons contained in the entity.
If ``role`` is provided, only the entity member with the given role are taken into account.
"""
if role:
if role.subroles:
role_condition = np.logica... | 0.010309 |
def _init_client(self, from_archive=False):
"""Init client"""
return JenkinsClient(self.url, self.blacklist_jobs, self.detail_depth,
self.sleep_time,
archive=self.archive, from_archive=from_archive) | 0.007326 |
def save(self, path):
"""
Writes file to a particular location
This won't work for cloud environments like Google's App Engine, use with caution
ensure to catch exceptions so you can provide informed feedback.
prestans does not mask File IO exceptions so your handler can respon... | 0.008772 |
def add_path(self, nodes, t=None):
"""Add a path at time t.
Parameters
----------
nodes : iterable container
A container of nodes.
t : snapshot id (default=None)
See Also
--------
add_path, add_cycle
Examples
--------
... | 0.003839 |
def _parse_multifile(self, desired_type: Type[T], obj: PersistedObject,
parsing_plan_for_children: Dict[str, ParsingPlan], logger: Logger,
options: Dict[str, Dict[str, Any]]) -> T:
"""
First parse all children from the parsing plan, then calls _build_obj... | 0.011429 |
def _parse_int(value, default=None):
"""
Attempt to cast *value* into an integer, returning *default* if it fails.
"""
if value is None:
return default
try:
return int(value)
except ValueError:
print "Couldn't cast value to `int`."
return default | 0.003311 |
def _get_channel_state_statelessly(self, grpc_channel, channel_id):
"""
We get state of the channel (nonce, amount, unspent_amount)
We do it by securely combine information from the server and blockchain
https://github.com/singnet/wiki/blob/master/multiPartyEscrowContract/MultiPartyEscro... | 0.012629 |
def get_exception(self):
"""Retrieve the exception"""
if self.exc_info:
try:
six.reraise(*self.exc_info)
except Exception as e:
return e | 0.009615 |
def _compute_signature(parameters, access_key_secret, method, path):
'''
Generate an API request signature. Detailed document can be found at:
https://docs.qingcloud.com/api/common/signature.html
'''
parameters['signature_method'] = 'HmacSHA256'
string_to_sign = '{0}\n{1}\n'.format(method.uppe... | 0.001333 |
def remove_record(self, common_name):
"""Delete the record associated with this common name"""
bundle = self.get_files(common_name)
num_signees = len(Counter(bundle.record['signees']))
if bundle.is_ca() and num_signees > 0:
raise CertificateAuthorityInUseError(
... | 0.002522 |
def getBirthdate(self, string=True):
"""
Returns the birthdate as string object
Parameters
----------
None
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getBirthdate()=='30 jun 1969'
True
... | 0.005329 |
def icanhaz(parser, token):
"""
Finds the ICanHaz template for the given name and renders it surrounded by
the requisite ICanHaz <script> tags.
"""
bits = token.contents.split()
if len(bits) not in [2, 3]:
raise template.TemplateSyntaxError(
"'icanhaz' tag takes one argument... | 0.002611 |
def get_single_generation(self, table, db='default'):
"""Creates a random generation value for a single table name"""
key = self.keygen.gen_table_key(table, db)
val = self.cache_backend.get(key, None, db)
#if local.get('in_test', None): print force_bytes(val).ljust(32), key
if va... | 0.006303 |
def go_in(self, vertex):
"""
Tell the edge to go into this vertex.
Args:
vertex (Vertex): vertex to go into.
"""
if self.vertex_in:
self.vertex_in.edges_in.remove(self)
self.vertex_in = vertex
vertex.edges_in.add(self) | 0.006689 |
def get_forwarding_address_details(destination_address, api_key, callback_url=None, coin_symbol='btc'):
"""
Give a destination address and return the details of the input address
that will automatically forward to the destination address
Note: a blockcypher api_key is required for this method
"""
... | 0.003911 |
def xdrbody(self, prefix=''):
"""Return xdr code for the body (part between braces) of big 3 types"""
body = ''
prefix += indent
if self.type == 'enum':
body = ''.join(
["%s,\n" % l.xdrout(prefix) for l in self.body[:-1]])
body += "%s\n" % self.bod... | 0.005814 |
def trial_end(self, trial_job_id, success):
"""trial_end
Parameters
----------
trial_job_id: int
trial job id
success: bool
True if succssfully finish the experiment, False otherwise
"""
if trial_job_id in self.running_history:
... | 0.006061 |
def fit(self, Z):
"""Compute the mean and std to be used for later scaling.
Parameters
----------
Z : DictRDD containing (X, y) pairs
X - Training vector.
{array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the m... | 0.001483 |
def hex(self, value, text=None, back=None, style=None, rgb_mode=False):
""" A chained method that sets the fore color to an hex value.
Arguments:
value : Hex value to convert.
text : Text to style if not building up color codes.
back : Back ... | 0.00211 |
def disableTemperature(self):
"""
Specifies the device should NOT write temperature values to the FIFO, is not applied until enableFIFO is called.
:return:
"""
logger.debug("Disabling temperature sensor")
self.fifoSensorMask &= ~self.enableTemperatureMask
self._s... | 0.011799 |
def aot_rpush(self, exit_code):
"""Push message to AOT action channel."""
if self.tcex.default_args.tc_playbook_db_type == 'Redis':
try:
self.db.rpush(self.tcex.default_args.tc_exit_channel, exit_code)
except Exception as e:
self.tcex.exit(1, 'Exce... | 0.010989 |
def add_protein_data(proteins, pgdb, headerfields, genecentric=False,
pool_to_output=False):
"""First creates a map with all master proteins with data,
then outputs protein data dicts for rows of a tsv. If a pool
is given then only output for that pool will be shown in the
protein t... | 0.001493 |
def _best_fit_font_size(self, max_size):
"""
Return the largest whole-number point size less than or equal to
*max_size* that this fitter can fit.
"""
predicate = self._fits_inside_predicate
sizes = _BinarySearchTree.from_ordered_sequence(
range(1, int(max_siz... | 0.005319 |
def _scalar_type_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals for category values.
The shape of the return value is the same as that of *counts*.
"""
expected_counts = expected_freq(counts)
residuals = counts - expected_counts
... | 0.003929 |
def waiter(self, count, *names):
'''
Construct and return a new Waiter for events on this base.
Example:
# wait up to 3 seconds for 10 foo:bar events...
waiter = base.waiter(10,'foo:bar')
# .. fire thread that will cause foo:bar events
events ... | 0.002878 |
def stream_download(url, target_path, verbose=False):
""" Download a large file without loading it into memory. """
response = requests.get(url, stream=True)
handle = open(target_path, "wb")
if verbose:
print("Beginning streaming download of %s" % url)
start = datetime.now()
try:... | 0.001168 |
def run_eidos(endpoint, *args):
"""Run a given enpoint of Eidos through the command line.
Parameters
----------
endpoint : str
The class within the Eidos package to run, for instance
'apps.ExtractFromDirectory' will run
'org.clulab.wm.eidos.apps.ExtractFromDirectory'
*args
... | 0.001339 |
def usage(self):
"""
Get the usage for the remote exectuion options
:return Usage for the remote execution options
"""
# Retrieve the text for just the arguments
usage = self.parser.format_help().split("optional arguments:")[1]
# Remove any blank lines and retur... | 0.004545 |
def day_publications(date):
"""
Returns a QuerySet of Publications that were being read on `date`.
`date` is a date tobject.
"""
readings = Reading.objects \
.filter(start_date__lte=date) \
.filter(
Q(end_date__gte=date)
... | 0.002817 |
def get_default(self, node):
"""
Unless specified otherwise, intr fields are implicitly stickybit
"""
if node.inst.properties.get("intr", False):
# Interrupt is set!
# Default is implicitly stickybit, unless the mutually-exclusive
# sticky property was... | 0.004587 |
def delete_lb_policy(self, lb_name, policy_name):
"""
Deletes a policy from the LoadBalancer. The specified policy must not
be enabled for any listeners.
"""
params = {
'LoadBalancerName' : lb_name,
'PolicyName' : po... | 0.009615 |
def _write_wrapped_codestream(self, ofile, box):
"""Write wrapped codestream."""
# Codestreams require a bit more care.
# Am I a raw codestream?
if len(self.box) == 0:
# Yes, just write the codestream box header plus all
# of myself out to file.
ofile.... | 0.000972 |
def solve(self, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices. It also sets these values in the `sdpRelaxation` object,
along with some status informa... | 0.000922 |
def startLoading(self):
"""
Starts loading this item for the batch.
"""
if super(XBatchItem, self).startLoading():
tree = self.treeWidget()
if not isinstance(tree, XOrbTreeWidget):
self.takeFromTree()
return
... | 0.007444 |
def load_context(ctx_path, ctx_type, scm=None):
"""
:param ctx_path: context file path or '-' (read from stdin)
:param ctx_type: context file type
:param scm: JSON schema file in any formats anyconfig supports, to
validate given context files
"""
if ctx_path == '-':
return loads(... | 0.002304 |
def _GetGsScopes(self):
"""Return all Google Storage scopes available on this VM."""
service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key)
try:
scopes = service_accounts[self.service_account]['scopes']
return list(GS_SCOPES.intersection(set(scopes))) if scopes else None
... | 0.011268 |
def save_with_exif_info(img, *args, **kwargs):
"""Saves an image using PIL, preserving the exif information.
Args:
img (PIL.Image.Image):
*args: The arguments for the `save` method of the Image class.
**kwargs: The keywords for the `save` method of the Image class.
"""
if 'exif... | 0.002208 |
def process_IAC(self, sock, cmd, option):
"""
Read in and parse IAC commands as passed by telnetlib.
SB/SE commands are stored in sbdataq, and passed in w/ a command
of SE.
"""
if cmd == DO:
if option == TM:
# timing mark - send WI... | 0.001969 |
def start_after(self, document_fields):
"""Start query after a cursor with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.start_after` for
more information on this method.
Args:
document_fields (Union[~.firestore_v1beta1.\
docu... | 0.002587 |
def eul2m(angle3, angle2, angle1, axis3, axis2, axis1):
"""
Construct a rotation matrix from a set of Euler angles.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eul2m_c.html
:param angle3: Rotation angle about third rotation axis (radians).
:type angle3: float
:param angle2: Rotatio... | 0.000872 |
async def add(self, setname, ip, timeout):
"""
Adds the given IP address to the specified set.
If timeout is specified, the IP will stay in the set for the given
duration. Else it will stay in the set during the set default timeout.
timeout must be given in seconds.
Th... | 0.006039 |
def dimensionize(maybe_a_list, nd=2):
"""Convert integers to a list of integers to fit the number of dimensions if
the argument is not already a list.
For example:
`dimensionize(3, nd=2)`
will produce the following result:
`(3, 3)`.
`dimensionize([3, 1], nd=2)`
will produce ... | 0.003371 |
def get_csv_import_info(self, path):
"""Launches the csv dialog and returns csv_info
csv_info is a tuple of dialect, has_header, digest_types
Parameters
----------
path: String
\tFile path of csv file
"""
csvfilename = os.path.split(path)[1]
... | 0.001704 |
def _factor(lexer):
"""Return a factor expression."""
tok = _expect_token(lexer, FACTOR_TOKS)
# '~' F
toktype = type(tok)
if toktype is OP_not:
return ('not', _factor(lexer))
# '(' EXPR ')'
elif toktype is LPAREN:
expr = _expr(lexer)
_expect_token(lexer, {RPAREN})
... | 0.000557 |
def _write(self, session, openFile, replaceParamFile):
"""
Link Node Dataset File Write to File Method
"""
# Retrieve TimeStep objects
timeSteps = self.timeSteps
# Write Lines
openFile.write('%s\n' % self.name)
openFile.write('NUM_LINKS %s\n' % self.n... | 0.001655 |
def logscale(x_min, x_max, n):
"""
:param x_min: minumum value
:param x_max: maximum value
:param n: number of steps
:returns: an array of n values from x_min to x_max
"""
if not (isinstance(n, int) and n > 0):
raise ValueError('n must be a positive integer, got %s' % n)
if x_min... | 0.00159 |
def set_group_conditions(self, group_id, conditions, trigger_mode=None):
"""
Set the group conditions.
This replaces any existing conditions on the group and member conditions for all trigger modes.
:param group_id: Group to be updated
:param conditions: New conditions to repla... | 0.005519 |
def close(self):
"""
Send a dead message to the remote, causing :meth:`ChannelError` to be
raised in any waiting thread.
"""
_vv and IOLOG.debug('%r.close()', self)
self.context.send(
Message.dead(
reason=self.explicit_close_msg,
... | 0.005435 |
def check_complicance(self):
"""Check compliance with Media RSS Specification, Version 1.5.1.
see http://www.rssboard.org/media-rss
Raises AttributeError on error.
"""
# check Media RSS requirement: one of the following elements is
# required: media_group | media_content... | 0.000874 |
def get_url(self, resource, params=None):
"""
Generate url for request
"""
# replace placeholders
pattern = r'\{(.+?)\}'
resource = re.sub(pattern, lambda t: str(params.get(t.group(1), '')), resource)
# build url
parts = (self.endpoint, '/api/', r... | 0.007634 |
def open(self, path, encoding=None, use_cached_encoding=True):
"""
Open a file and set its content on the editor widget.
pyqode does not try to guess encoding. It's up to the client code to
handle encodings. You can either use a charset detector to detect
encoding or rely on a s... | 0.000584 |
def _update(self):
"""Initialize the 1D interpolation."""
if self.strains.size and self.strains.size == self.values.size:
x = np.log(self.strains)
y = self.values
if x.size < 4:
self._interpolater = interp1d(
x,
... | 0.003003 |
def launch_help(self, helpname, filename):
"""Generic help launcher
Launches HTMLWindow that shows content of filename
or the Internet page with the filename url
Parameters
----------
filename: String
\thtml file or url
"""
# Set up window
... | 0.001278 |
def configure(self, options, config):
"""Configures the xunit plugin."""
Plugin.configure(self, options, config)
self.config = config
if self.enabled:
self.stats = {'errors': 0,
'failures': 0,
'passes': 0,
... | 0.003643 |
def cluster_sample5():
"Start with wrong number of clusters."
start_centers = [[0.0, 1.0], [0.0, 0.0]]
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE5, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE5, criter... | 0.018519 |
def scatter(points, vertexlabels=None, **kwargs):
'''Scatter plot of barycentric 2-simplex points on a 2D triangle.
:param points: Points on a 2-simplex.
:type points: N x 3 list or ndarray.
:param vertexlabels: Labels for corners of plot in the order
``(a, b, c)`` where ``a == (1,0,0)``, ``b =... | 0.007052 |
def cloneNode(self, deep: bool=False) -> AbstractNode:
"""Return new copy of this node.
If optional argument ``deep`` is specified and is True, new node has
clones of child nodes of this node (if presents).
"""
if deep:
return self._clone_node_deep()
return s... | 0.011869 |
def purge_results(self, client_id, msg):
"""Purge results from memory. This method is more valuable before we move
to a DB based message storage mechanism."""
content = msg['content']
self.log.info("Dropping records with %s", content)
msg_ids = content.get('msg_ids', [])
... | 0.005552 |
def nl_send(sk, msg):
"""Transmit Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L416
Transmits the Netlink message `msg` over the Netlink socket using the `socket.sendmsg()`. This function is based on
`nl_send_iovec()`.
The message is addressed to the peer as specifi... | 0.004993 |
def write_json(dictionary, filename):
"""Write dictionary to JSON"""
with open(filename, 'w') as data_file:
json.dump(dictionary, data_file, indent=4, sort_keys=True)
print('--> Wrote ' + os.path.basename(filename)) | 0.004255 |
def _update_line(self):
""" Update border line to match new shape """
w = self._border_width
m = self.margin
# border is drawn within the boundaries of the widget:
#
# size = (8, 7) margin=2
# internal rect = (3, 3, 2, 1)
# ........
# ........... | 0.002104 |
def rsdl_s(self, Yprev, Y):
"""Compute dual residual vector.
Overriding this method is required if methods :meth:`cnst_A`,
:meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not
overridden.
"""
return self.rho * self.cnst_AT(Yprev - Y) | 0.006897 |
def print_table(table, name=None, fmt=None):
"""
Pretty print a pandas DataFrame.
Uses HTML output if running inside Jupyter Notebook, otherwise
formatted text output.
Parameters
----------
table : pd.Series or pd.DataFrame
Table to pretty-print.
name : str, optional
Ta... | 0.00104 |
def capture(returns, factor_returns, period=DAILY):
"""
Compute capture ratio.
Parameters
----------
returns : pd.Series or np.ndarray
Returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series or np.ndarray... | 0.000963 |
def compile(self, optimizer, loss, metrics=None):
"""
Args:
optimizer (tf.train.Optimizer):
loss, metrics: string or list of strings
"""
if isinstance(loss, six.string_types):
loss = [loss]
if metrics is None:
metrics = []
i... | 0.002628 |
def _get_or_create_user(self, force_populate=False):
"""
Loads the User model object from the database or creates it if it
doesn't exist. Also populates the fields, subject to
AUTH_LDAP_ALWAYS_UPDATE_USER.
"""
save_user = False
username = self.backend.ldap_to_dja... | 0.002549 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.