text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def guest_capture(self, userid, image_name, capture_type='rootonly',
compress_level=6):
""" Capture the guest to generate a image
:param userid: (str) the user id of the vm
:param image_name: (str) the unique image name after capture
:param capture_type: (str) the ... | 0.002988 |
def log(self, priority, msg):
"""
Just a wrapper, for convenience.
NB1: priority may be set to one of:
- CRITICAL [50]
- ERROR [40]
- WARNING [30]
- INFO [20]
- DEBUG [10]
- NOTSET [0]
Anything else defa... | 0.003527 |
def _read_node_data(subnw, current_node, node_type, matcher, formatcode):
"""
Reads a leaf node from a subpart of the original newicktree
"""
if node_type == "leaf" or node_type == "single":
if node_type == "leaf":
node = current_node.add_child()
else:
node = cu... | 0.004222 |
def history(self, *, limit=100, before=None, after=None, around=None, oldest_first=None):
"""Return an :class:`.AsyncIterator` that enables receiving the destination's message history.
You must have :attr:`~.Permissions.read_message_history` permissions to use this.
Examples
---------
... | 0.004545 |
def _tr_system(line_info):
"Translate lines escaped with: !"
cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
return '%sget_ipython().system(%r)' % (line_info.pre, cmd) | 0.010471 |
def c2f(r, i, ctype_name):
"""
Convert strings to complex number instance with specified numpy type.
"""
ftype = c2f_dict[ctype_name]
return np.typeDict[ctype_name](ftype(r) + 1j * ftype(i)) | 0.004739 |
def register_viewer(self, vclass):
"""Register a channel viewer with the reference viewer.
`vclass` is the class of the viewer.
"""
self.viewer_db[vclass.vname] = Bunch.Bunch(vname=vclass.vname,
vclass=vclass,
... | 0.005479 |
def _build_casefold_map(self):
"""
Function for parsing the case folding data from the Unicode Character
Database (UCD) and generating a lookup table. For more info on the UCD,
see the following website: https://www.unicode.org/ucd/
"""
self._casefold_map = defaultdict(d... | 0.006135 |
def update(self, friendly_name=values.unset, chat_service_sid=values.unset,
channel_type=values.unset, contact_identity=values.unset,
enabled=values.unset, integration_type=values.unset,
integration_flow_sid=values.unset, integration_url=values.unset,
integrat... | 0.005957 |
def stop_workflow(config, *, names=None):
""" Stop one or more workflows.
Args:
config (Config): Reference to the configuration object from which the
settings for the workflow are retrieved.
names (list): List of workflow names, workflow ids or workflow job ids for the
w... | 0.003226 |
def sleep(self, seconds=0.05, dt=0.01):
"""
A "smooth" version of time.sleep(): waits for the time to pass but
processes events every dt as well.
Note this requires that the object is either a window or embedded
somewhere within a window.
"""
t0 = _t.tim... | 0.011538 |
def connect_put_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs):
"""
connect PUT requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_n... | 0.006375 |
def tail(conn, stack_name, log_func=_tail_print, sleep_time=5,
include_initial=True):
"""Show and then tail the event log"""
# First dump the full list of events in chronological order and keep
# track of the events we've seen already
seen = set()
initial_events = get_events(conn, stack_nam... | 0.001414 |
def parse(trigger_word_file):
"""Parse the file for source and sink definitions.
Returns:
A definitions tuple with sources and sinks.
"""
with open(trigger_word_file) as fd:
triggers_dict = json.load(fd)
sources = [Source(s) for s in triggers_dict['sources']]
sinks = [
Si... | 0.002212 |
def find_sidechain_atoms_within_radius_of_residue_objects(self, source_residues, search_radius, find_ATOM_atoms = True, find_HETATM_atoms = False, restrict_to_CA = False):
'''for residue in source_residues:
for all heavy atoms in residue
find all heavy atoms within radius which are w... | 0.010033 |
def get_blast2(pdb_id, chain_id='A', output_form='HTML'):
'''Alternative way to look up BLAST for a given PDB ID. This function is a wrapper
for get_raw_blast and parse_blast
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
chain_id : string
... | 0.00269 |
def global_request_interceptor(self):
# type: () -> Callable
"""Decorator that can be used to add global request
interceptors easily to the builder.
The returned wrapper function can be applied as a decorator on
any function that processes the input. The function should
... | 0.002222 |
def prompt_yn(stmt):
'''Prints the statement stmt to the terminal and wait for a Y or N answer.
Returns True for 'Y', False for 'N'.'''
print(stmt)
answer = ''
while answer not in ['Y', 'N']:
sys.stdout.write("$ ")
answer = sys.stdin.readline().upper().strip()
return answer ==... | 0.003086 |
def _maybe_stop_timeout():
"""If there is a pending timeout, remove it from the IOLoop and set the
``_timeout`` global to None.
"""
global _timeout
if _timeout is not None:
LOGGER.debug('Removing the pending timeout (%r)', _timeout)
ioloop.IOLoop.current().remove_timeout(_timeout)
... | 0.002915 |
def point2pos(self, point):
"""Converts a point or offset in a file to a (row, col) position."""
row = self._vim.eval('byte2line({})'.format(point))
col = self._vim.eval('{} - line2byte({})'.format(point, row))
return (int(row), int(col)) | 0.007407 |
def classify(self, classifier_name, examples, max_labels=None,
goodness_of_fit=False):
"""Usar un clasificador SVM para etiquetar textos nuevos.
Args:
classifier_name (str): Nombre del clasidicador a usar.
examples (list or str): Se espera un ejemplo o una lista... | 0.002125 |
def set_primary_ip(self, name, vrid, value=None, disable=False,
default=False, run=True):
"""Set the primary_ip property of the vrrp
Args:
name (string): The interface to configure.
vrid (integer): The vrid number for the vrrp to be managed.
va... | 0.001661 |
def summary_extra(self):
"""
Build the extra data for the summary logger.
"""
out = {
'errno': 0,
'agent': request.headers.get('User-Agent', ''),
'lang': request.headers.get('Accept-Language', ''),
'method': request.method,
'pat... | 0.002045 |
def dis(msg, msg_nocr, section, errmsg, x=None, start_line=-1, end_line=None,
relative_pos = False, highlight='light', start_offset=0, end_offset=None,
include_header=False):
"""Disassemble classes, methods, functions, or code.
With no argument, disassemble the last traceback.
"""
last... | 0.005105 |
def close_page(self, state_identifier, delete=True):
"""Closes the desired page
The page belonging to the state with the specified state_identifier is closed. If the deletion flag is set to
False, the controller of the page is stored for later usage.
:param state_identifier: Identifier... | 0.004699 |
def join(self, *groupnames):
"""Return an index group that contains atoms from all *groupnames*.
The method will silently ignore any groups that are not in the
index.
**Example**
Always make a solvent group from water and ions, even if not
all ions are present in all ... | 0.004211 |
def ramp_limits(network):
""" Add ramping constraints to thermal power plants.
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
Returns
-------
"""
carrier = ['coal', 'biomass', 'gas', 'oil', 'waste', 'lignite',
'urani... | 0.012865 |
def infer_declared_from_conditions(conds, namespace=None):
''' like infer_declared except that it is passed a set of first party
caveat conditions as a list of string rather than a set of macaroons.
'''
conflicts = []
# If we can't resolve that standard namespace, then we'll look for
# just bare... | 0.000865 |
def structs2pandas(structs):
"""convert ctypes structure or structure array to pandas data frame"""
try:
import pandas
records = list(structs2records(structs))
df = pandas.DataFrame.from_records(records)
# TODO: do this for string columns, for now just for id
# How can we... | 0.00339 |
def sync_db():
"""
Runs the django syncdb command
"""
with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',env.project_package_name,'sitesettings'])):
venv = '/'.join([deployment_root(),'env',env.project_fullname,'bin','activate'])
sites = _get_django_sites()
... | 0.025505 |
def cio_open(cinfo, src=None):
"""Wrapper for openjpeg library function opj_cio_open."""
argtypes = [ctypes.POINTER(CommonStructType), ctypes.c_char_p,
ctypes.c_int]
OPENJPEG.opj_cio_open.argtypes = argtypes
OPENJPEG.opj_cio_open.restype = ctypes.POINTER(CioType)
if src is None:
... | 0.001684 |
def restrict_to_level(self, level):
"""Restricts the generated PostScript file to :obj:`level`.
See :meth:`get_levels` for a list of available level values
that can be used here.
This method should only be called
before any drawing operations have been performed on the given su... | 0.00335 |
def normalize_response(response, request=None):
"""
Given a response, normalize it to the internal Response class. This also
involves normalizing the associated request object.
"""
if isinstance(response, Response):
return response
if request is not None and not isinstance(request, Requ... | 0.001669 |
def _read_para_echo_request_signed(self, code, cbit, clen, *, desc, length, version):
"""Read HIP ECHO_REQUEST_SIGNED parameter.
Structure of HIP ECHO_REQUEST_SIGNED parameter [RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3... | 0.002734 |
def Start(self):
"""Starts the worker thread."""
self._shutdown = False
self._main_thread = threading.Thread(target=self._MainThreadProc)
self._main_thread.name = 'Cloud Debugger main worker thread'
self._main_thread.daemon = True
self._main_thread.start() | 0.003559 |
def full_line_width(self):
"""Find actual length of bar_str
e.g., Progress [ | ] 10/10
"""
bar_str_len = sum([
self._indent,
((len(self.title) + 1) if self._title_pos in ["left", "right"]
else 0), # Title if present
len(self.start... | 0.003559 |
def extract_residue_accessibility(in_rsa, path=True, get_total=False):
"""Parses rsa file for solvent accessibility for each residue.
Parameters
----------
in_rsa : str
Path to naccess rsa file
path : bool
Indicates if in_rsa is a path or a string
get_total : bool
Indica... | 0.000783 |
def metadata(dataset, node, entityids, extended=False, api_key=None):
"""
Request metadata for a given scene in a USGS dataset.
:param dataset:
:param node:
:param entityids:
:param extended:
Send a second request to the metadata url to get extended metadata on the scene.
:param api... | 0.004545 |
def parse_secondary_types(self, request):
"""
Return secondary event types that occurrences must belong to, or `None`
if there is no constraint on secondary type.
"""
if request.GET.getlist('secondary_types'):
return EventType.objects.filter(
slug__in=... | 0.005277 |
def GET_AUTH(self):
""" GET request """
return self.template_helper.get_renderer().queue(*self.submission_manager.get_job_queue_snapshot(), datetime.fromtimestamp) | 0.01676 |
def embedding(self, dimensions, method, **kwargs):
"""
Embeds the distance matrix in a coordinate space. Implemented methods are:
cmds: Classical MultiDimensional Scaling
kpca: Kernel Principal Components Analysis
mmds: Metric MultiDimensional Scaling
nmmd... | 0.005482 |
def get_shifted_center_blocks(x, indices):
"""Get right shifted blocks for masked local attention 2d.
Args:
x: A tensor with shape [batch, heads, height, width, depth]
indices: The indices to gather blocks
Returns:
x_shifted: a tensor of extracted blocks, each block right shifted along
length.... | 0.009957 |
def get_distribute_compositions_metadata(self):
"""Gets the metadata for the distribute compositions rights flag.
return: (osid.Metadata) - metadata for the distribution rights
fields
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented ... | 0.006838 |
def find_icelines(self):
"""Finds iceline according to the surface temperature.
This method is called by the private function
:func:`~climlab.surface.albedo.Iceline._compute`
and updates following attributes according to the freezing temperature
``self.param['Tf']`` and the surf... | 0.006036 |
def _manual_recv(self, method, body, headers={}):
"""Used in the tests"""
headers.setdefault('sent_at', time.time())
return self.recv(self._make_context(), {'method': method, 'body': body, 'headers': headers}) | 0.012876 |
def setup_environment_from_config_file():
"""
Imports the environmental configuration settings from the
config file, if present, and sets the environment
variables to test it.
"""
from os.path import exists
config_file = get_config_file()
if not exists(config_file):
return
... | 0.003043 |
def _run_up(self, path, migration_file, batch, pretend=False):
"""
Run "up" a migration instance.
:type migration_file: str
:type batch: int
:type pretend: bool
"""
migration = self._resolve(path, migration_file)
if pretend:
return self._pr... | 0.002882 |
def _explore(self, explore_iterable):
"""Explores the parameter according to the iterable.
Raises ParameterLockedException if the parameter is locked.
Raises TypeError if the parameter does not support the data,
the types of the data in the iterable are not the same as the type of the d... | 0.005239 |
def set_inbound_cipher(
self, block_engine, block_size, mac_engine, mac_size, mac_key
):
"""
Switch inbound data cipher.
"""
self.__block_engine_in = block_engine
self.__block_size_in = block_size
self.__mac_engine_in = mac_engine
self.__mac_size_in = ... | 0.003974 |
def make_reply(msgname, types, arguments, major):
"""Helper method for constructing a reply message from a list or tuple.
Parameters
----------
msgname : str
Name of the reply message.
types : list of kattypes
The types of the reply message parameters (in order).
arguments : lis... | 0.001238 |
def get_object(self, resource, object_type, content_ids, object_ids='*', location=0):
"""
Get a list of Objects from a resource
:param resource: The resource to get objects from
:param object_type: The type of object to fetch
:param content_ids: The unique id of the item to get o... | 0.003089 |
def status(self):
'''returns information about module'''
transfered = self.download - self.prev_download
now = time.time()
interval = now - self.last_status_time
self.last_status_time = now
return("DFLogger: %(state)s Rate(%(interval)ds):%(rate).3fkB/s Block:%(block_cnt)d... | 0.006812 |
def append_field(self, path, name, value):
"""
Appends the field to the container at the specified path.
:param path: str or Path instance
:param name:
:type name: str
:param value:
:type value: str
"""
path = make_path(path)
container = s... | 0.002829 |
def stdin_channel(self):
"""Get the REP socket channel object to handle stdin (raw_input)."""
if self._stdin_channel is None:
self._stdin_channel = self.stdin_channel_class(self.context,
self.session,
... | 0.012469 |
def read_length_encoded_integer(self):
"""Read a 'Length Coded Binary' number from the data buffer.
Length coded numbers can be anywhere from 1 to 9 bytes depending
on the value of the first byte.
"""
c = self.read_uint8()
if c == NULL_COLUMN:
return None
... | 0.003273 |
def revoke_api_key():
"""Form submission handler for revoking API keys."""
build = g.build
form = forms.RevokeApiKeyForm()
if form.validate_on_submit():
api_key = models.ApiKey.query.get(form.id.data)
if api_key.build_id != build.id:
logging.debug('User does not have access t... | 0.001404 |
def __read_line(self, f):
"""
Get logic line according the syntax not the physical line
It'll return the line text and if there is identifier existed
return line, bool
"""
g = tokenize.generate_tokens(f.readline)
buf = []
time =... | 0.004283 |
def visitShapeDefinition(self, ctx: ShExDocParser.ShapeDefinitionContext):
""" shapeDefinition: qualifier* '{' oneOfShape? '}' annotation* semanticActions """
if ctx.qualifier():
for q in ctx.qualifier():
self.visit(q)
if ctx.oneOfShape():
oneof_parser = S... | 0.003229 |
def create(self, typ, data, return_response=False):
"""
Create new type
Valid arguments:
skip : number of records to skip
limit : number of records to limit request to
"""
res = self._request(typ, method='POST', data=data)
if res.status_code != 201... | 0.00339 |
def remove_names(self, dtype):
"""
Remove unneeded name columns ('specimen'/'sample'/etc)
from the specified table.
Parameters
----------
dtype : str
Returns
---------
pandas DataFrame without the unneeded columns
Example
-------... | 0.005425 |
def _check_triple(self, triple):
"""compare triple to ontology, return error or None"""
subj, pred, obj = triple
if self._should_ignore_predicate(pred):
log.info("Ignoring triple with predicate '{}'"
.format(self._field_name_from_uri(pred)))
return
... | 0.000929 |
def join(delimiter, iterable, **kwargs):
"""Returns a string which is a concatenation of strings in ``iterable``,
separated by given ``delimiter``.
:param delimiter: Delimiter to put between strings
:param iterable: Iterable to join
Optional keyword arguments control the exact joining strategy:
... | 0.000905 |
def Find(cls, setting_matcher, port_path=None, serial=None, timeout_ms=None):
"""Gets the first device that matches according to the keyword args."""
if port_path:
device_matcher = cls.PortPathMatcher(port_path)
usb_info = port_path
elif serial:
device_matcher... | 0.00339 |
def apply_inverse(self, y):
"""
Apply the inverse of the covariance matrix to a vector or matrix
Solve ``K.x = y`` for ``x`` where ``K`` is the covariance matrix of
the GP with the white noise and ``yerr`` components included on the
diagonal.
Args:
y (array[... | 0.002829 |
def _get_bucket(self):
'''get a bucket based on a bucket name. If it doesn't exist, create it.
'''
# Case 1: The bucket already exists
try:
self._bucket = self._bucket_service.get_bucket(self._bucket_name)
# Case 2: The bucket needs to be created
except goog... | 0.008078 |
def set_in_bounds(self,obj,val):
"""
Set to the given value, but cropped to be within the legal bounds.
All objects are accepted, and no exceptions will be raised. See
crop_to_bounds for details on how cropping is done.
"""
if not callable(val):
bounded_val =... | 0.013605 |
def get(self, sid):
"""
Constructs a EnvironmentContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.environment.EnvironmentContext
:rtype: twilio.rest.serverless.v1.service.environment.EnvironmentContext
"""
return EnvironmentContext(self._ve... | 0.013158 |
def get_arg_info(self, state, is_fp=None, sizes=None):
"""
This is just a simple wrapper that collects the information from various locations
is_fp and sizes are passed to self.arg_locs and self.get_args
:param angr.SimState state: The state to evaluate and extract the values from
... | 0.008424 |
def get_identities(self, item):
""" Return the identities from an item """
item = item['data']
for identity in self.issue_roles:
if item[identity]:
user = self.get_sh_identity(item[identity])
if user:
yield user | 0.006667 |
def _is_node_return_ended(self, node):
"""Check if the node ends with an explicit return statement.
Args:
node (astroid.NodeNG): node to be checked.
Returns:
bool: True if the node ends with an explicit statement, False otherwise.
"""
# Recursion base ... | 0.001857 |
def is_python(self, path):
"""Test whether argument path is a Python script."""
head, tail = os.path.splitext(path)
return tail.lower() in (".py", ".pyw") | 0.011236 |
def iterstd(cmd, std="out", **kwargs):
"""Iterates through the lines of a stderr/stdout stream for the given shell
command."""
def _readline():
while True:
line = getattr(proc, "std"+std).readline()
if line != b"":
yield line.rstrip().decode("UTF-8", "replace"... | 0.005533 |
def attach(self, canvas):
"""Attach this interact to a canvas."""
self.canvas = canvas
@canvas.connect
def on_visual_added(e):
self.update_program(e.visual.program) | 0.009569 |
def _get_fault_rates(self, source, mmin, mmax=np.inf):
"""
Adds the rates for a simple or complex fault source
:param source:
Fault source as instance of :class:
openquake.hazardlib.source.simple_fault.SimpleFaultSource or
openquake.hazardlib.source.complex_f... | 0.001919 |
def validate(self, settings):
"""Raise ValidationError if invalid"""
if self.envs is None:
self.envs = [settings.current_env]
if self.when is not None:
try:
# inherit env if not defined
if self.when.envs is None:
self.... | 0.002165 |
def get_view_name(self):
"""
Return the view name, as used in OPTIONS responses and in the
browsable API.
"""
func = self.settings.VIEW_NAME_FUNCTION
return func(self.__class__, getattr(self, 'suffix', None)) | 0.007813 |
def init_chain(self):
"""Autodetect the devices attached to the Controller, and initialize a JTAGDevice for each.
This is a required call before device specific Primitives can
be used.
"""
if not self._hasinit:
self._hasinit = True
self._devices = []
... | 0.006071 |
def read_stream(self, left_chunk, right_chunk, volume, bit16=32767.0):
'''
具象メソッド
wavファイルに保存するモノラルビートを読み込む
Args:
left_chunk: 左音源に対応するチャンク
right_chunk: 右音源に対応するチャンク
volume: 音量
bit16: 整数化の条件
Return... | 0.002849 |
def open_state_machine(path=None, recent_opened_notification=False):
""" Open a state machine from respective file system path
:param str path: file system path to the state machine
:param bool recent_opened_notification: flags that indicates that this call also should update recently open
:rtype rafc... | 0.004673 |
def download(directory, filename):
"""Download (and unzip) a file from the MNIST dataset if not already done."""
filepath = os.path.join(directory, filename)
if tf.gfile.Exists(filepath):
return filepath
if not tf.gfile.Exists(directory):
tf.gfile.MakeDirs(directory)
url = 'http://yann.lecun.com/exdb/... | 0.018895 |
def use_value(self, value):
"""Converts value to field type or use original"""
if self.check_value(value):
return value
return self.convert_value(value) | 0.010638 |
async def strings(self, request: Optional['Request']=None) \
-> List[Tuple[Text, ...]]:
"""
For the given request, find the list of strings of that intent. If the
intent does not exist, it will raise a KeyError.
"""
if request:
locale = await request.get_... | 0.009662 |
def _default(self, obj):
""" return a serialized version of obj or raise a TypeError
:param obj:
:return: Serialized version of obj
"""
return obj.__dict__ if isinstance(obj, JsonObj) else json.JSONDecoder().decode(obj) | 0.011538 |
def flat_to_nested(data, instance=None, attname=None,
separator=None, loads=None):
'''Convert a flat representation of a dictionary to
a nested representation. Fields in the flat representation are separated
by the *splitter* parameters.
:parameter data: a flat dictionary of key value pairs.
:pa... | 0.000571 |
def abstracts(self, key, value):
"""Populate the ``abstracts`` key."""
result = []
source = force_single_element(value.get('9'))
for a_value in force_list(value.get('a')):
result.append({
'source': source,
'value': a_value,
})
return result | 0.0033 |
def flush_cache(self):
'''
Use a cache to save state changes to avoid opening a session for every change.
The cache will be flushed at the end of the simulation, and when history is accessed.
'''
logger.debug('Flushing cache {}'.format(self.db_path))
with self.db:
... | 0.009452 |
def set_content(self, content):
"""
Sets document with given content while providing undo capability.
:param content: Content to set.
:type content: list
:return: Method success.
:rtype: bool
"""
cursor = self.textCursor()
cursor.movePosition(QTe... | 0.00335 |
def _argcheck(*args, **kwargs):
"""
Check that arguments are consistent with spark array construction.
Conditions are:
(1) a positional argument is a SparkContext
(2) keyword arg 'context' is a SparkContext
(3) an argument is a BoltArraySpark, or
(4) an argument ... | 0.003315 |
def get_Object_or_None(klass, *args, **kwargs):
"""
Uses get() to return an object, or None if the object does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Note: Like with get(), an MultipleObjectsReturn... | 0.001497 |
def list_unmanaged_cpcs(self, name=None):
"""
List the unmanaged CPCs of this HMC.
For details, see :meth:`~zhmcclient.UnmanagedCpc.list`.
Authorization requirements:
* None
Parameters:
name (:term:`string`):
Regular expression pattern for the C... | 0.001914 |
def temp_to_spmatrix(self, ty):
"""
Convert Jacobian tuples to matrices
:param ty: name of the matrices to convert in ``('jac0','jac')``
:return: None
"""
assert ty in ('jac0', 'jac')
jac0s = ['Fx0', 'Fy0', 'Gx0', 'Gy0']
jacs = ['Fx', 'Fy', 'Gx', 'Gy']
... | 0.002625 |
def requiredUnless(col_name, arg, dm, df, *args):
"""
Arg is a string in the format "str1, str2, ..."
Each string will be a column name.
Col_name is required in df unless each column from arg is present.
"""
# if column name is present, no need to check if it is required
if col_name in df.co... | 0.002584 |
def parametric_line(x, y):
"""
Parameters
----------
x : 1D numpy array
y : 1D numpy array
"""
if len(x) != len(y):
raise ValueError("Arrays must be the same length")
X = np.ones((len(x), len(x)))*np.nan
Y = X.copy()
for i in range(len(x)):
X[i, :(i+1)] = x[:(i+... | 0.002688 |
def metafilename(self):
"""Returns the filename for the metadata file (not full path). Only used for local files."""
metafilename = os.path.dirname(self.filename)
if metafilename: metafilename += '/'
metafilename += '.' + os.path.basename(self.filename) + '.METADATA'
return metaf... | 0.012232 |
def xpointerNewRangeNodes(self, end):
"""Create a new xmlXPathObjectPtr of type range using 2 nodes """
if end is None: end__o = None
else: end__o = end._o
ret = libxml2mod.xmlXPtrNewRangeNodes(self._o, end__o)
if ret is None:raise treeError('xmlXPtrNewRangeNodes() failed')
... | 0.017192 |
def get_max_bond_distance(self, el1_sym, el2_sym):
"""
Use Jmol algorithm to determine bond length from atomic parameters
Args:
el1_sym: (str) symbol of atom 1
el2_sym: (str) symbol of atom 2
Returns: (float) max bond length
"""
return sqrt(
... | 0.007576 |
def get_object(self, request, year, month, day, slug):
"""
Retrieve the discussions by entry's slug.
"""
return get_object_or_404(Entry, slug=slug,
publication_date__year=year,
publication_date__month=month,
... | 0.005479 |
def K(self, parm):
""" Returns the Gram Matrix
Parameters
----------
parm : np.ndarray
Parameters for the Gram Matrix
Returns
----------
- Gram Matrix (np.ndarray)
"""
return ARD_K_matrix(self.X, parm) + np.identity(self.X.shape[0])*(... | 0.009146 |
def setSubTotal( self, amount ):
"""
Sets the total value for the sub progress bar.
:param amount | <int>
"""
self._subProgressBar.setValue(0)
self._subProgressBar.setMaximum(amount)
if amount:
self.setShowSubProgress(True) | 0.016393 |
def get_signatures_with_results(vcs):
"""Returns the list of signatures for which test results are saved.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
List[str]
"""
results_dir = os.path.join(vcs.private_dir(), 'results')
if not os.path.exists(results_dir):
return []
re... | 0.004608 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.