Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
385,400 | def build_command_tree(pattern, cmd_params):
from docopt import Either, Optional, OneOrMore, Required, Option, Command, Argument
if type(pattern) in [Either, Optional, OneOrMore]:
for child in pattern.children:
build_command_tree(child, cmd_params)
elif type(pattern) in [Required]:
... | Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object. |
385,401 | def append_columns(self, colnames, values, **kwargs):
n = len(self)
if np.isscalar(values):
values = np.full(n, values)
values = np.atleast_1d(values)
if not isinstance(colnames, str) and len(colnames) > 1:
values = np.atleast_2d(values)
self... | Append new columns to the table.
When appending a single column, ``values`` can be a scalar or an
array of either length 1 or the same length as this array (the one
it's appended to). In case of multiple columns, values must have
the shape ``list(arrays)``, and the dimension of each arr... |
385,402 | def getPeer(self, url):
peers = list(models.Peer.select().where(models.Peer.url == url))
if len(peers) == 0:
raise exceptions.PeerNotFoundException(url)
return peers[0] | Finds a peer by URL and return the first peer record with that URL. |
385,403 | def _parse_table(
self, parent_name=None
):
if self._current != "[":
raise self.parse_error(
InternalParserError, "_parse_table() called on non-bracket character."
)
indent = self.extract()
self.inc()
if self.end():
... | Parses a table element. |
385,404 | def addresses_for_key(gpg, key):
fingerprint = key["fingerprint"]
addresses = []
for key in gpg.list_keys():
if key["fingerprint"] == fingerprint:
addresses.extend([address.split("<")[-1].strip(">")
for address in key["uids"] if address])
re... | Takes a key and extracts the email addresses for it. |
385,405 | def put(self, key, value, minutes):
minutes = self._get_minutes(minutes)
if minutes is not None:
return self._store.put(self.tagged_item_key(key), value, minutes) | Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int or datetime |
385,406 | def execute(self, command):
try:
if self.ssh.get_transport() is not None:
logger.debug(.format(self.target_address,
command))
stdin, stdout, stderr = self.ssh.exec_command(command)
ret... | Executes command on remote hosts
:type command: str
:param command: command to be run on remote host |
385,407 | def load_tf_weights_in_transfo_xl(model, config, tf_path):
try:
import numpy as np
import tensorflow as tf
except ImportError:
print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for instal... | Load tf checkpoints in a pytorch model |
385,408 | def strains(self):
with open(os.path.join(self.path, )) as strains:
next(strains)
for line in strains:
oln, seqid = line.split()
self.straindict[oln] = seqid.rstrip()
self.strainset.add(oln)
logging.debug(oln)
... | Create a dictionary of SEQID: OLNID from the supplied |
385,409 | async def get_messages(self, name):
resp = await self.send_command(OPERATIONS.CMD_QUERY_MESSAGES, {: name},
MESSAGES.QueryMessagesResponse, timeout=5.0)
return [states.ServiceMessage.FromDictionary(x) for x in resp] | Get stored messages for a service.
Args:
name (string): The name of the service to get messages from.
Returns:
list(ServiceMessage): A list of the messages stored for this service |
385,410 | def encode_request(name, expected, updated):
client_message = ClientMessage(payload_size=calculate_size(name, expected, updated))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(name)
client_message.append_long(expected)
client... | Encode request into client_message |
385,411 | def defaulted_config(modules, params=None, yaml=None, filename=None,
config=None, validate=True):
with _temporary_config():
set_default_config(modules, params=params, yaml=yaml,
filename=filename, config=config, validate=validate)
yield get_global... | Context manager version of :func:`set_default_config()`.
Use this with a Python 'with' statement, like
>>> config_yaml = '''
... toplevel:
... param: value
... '''
>>> with yakonfig.defaulted_config([toplevel], yaml=config_yaml) as config:
... assert 'param' in config['toplevel']
... |
385,412 | def from_coeff(self, chebcoeff, domain=None, prune=True, vscale=1.):
coeffs = np.asarray(chebcoeff)
if prune:
N = self._cutoff(coeffs, vscale)
pruned_coeffs = coeffs[:N]
else:
pruned_coeffs = coeffs
values = self.polyval(pruned_coeffs)
... | Initialise from provided coefficients
prune: Whether to prune the negligible coefficients
vscale: the scale to use when pruning |
385,413 | def get_random(min_pt, max_pt):
result = Point(random.random(), random.random())
return result.get_component_product(max_pt - min_pt) + min_pt | Returns a random vector in the given range. |
385,414 | def list_subcommand(vcard_list, parsable):
if not vcard_list:
if not parsable:
print("Found no contacts")
sys.exit(1)
elif parsable:
contact_line_list = []
for vcard in vcard_list:
if config.display_by_name() == "first_name":
name = vc... | Print a user friendly contacts table.
:param vcard_list: the vcards to print
:type vcard_list: list of carddav_object.CarddavObject
:param parsable: machine readable output: columns devided by tabulator (\t)
:type parsable: bool
:returns: None
:rtype: None |
385,415 | def _init(self, run_conf, run_number=None):
self.stop_run.clear()
self.abort_run.clear()
self._run_status = run_status.running
self._write_run_number(run_number)
self._init_run_conf(run_conf) | Initialization before a new run. |
385,416 | def interpolate(self, factor, minKerning, maxKerning, round=True, suppressError=True):
factor = normalizers.normalizeInterpolationFactor(factor)
if not isinstance(minKerning, BaseKerning):
raise TypeError(("Interpolation to an instance of %r can not be "
... | Interpolates all pairs between two :class:`BaseKerning` objects:
**minKerning** and **maxKerning**. The interpolation occurs on a
0 to 1.0 range where **minKerning** is located at 0 and
**maxKerning** is located at 1.0. The kerning data is replaced by
the interpolated kerning.
... |
385,417 | def construct(self, request, service=None, http_args=None, **kwargs):
if in kwargs:
request["client_assertion"] = kwargs[]
if in kwargs:
request[
] = kwargs[]
else:
request["client_assertion_type"] = JWT_BEARER
... | Constructs a client assertion and signs it with a key.
The request is modified as a side effect.
:param request: The request
:param service: A :py:class:`oidcservice.service.Service` instance
:param http_args: HTTP arguments
:param kwargs: Extra arguments
:return: Constr... |
385,418 | def getAccountInfo(self, fields=None):
return self.make_method("getAccountInfo", {
"access_token": self.access_token,
"fields": json.dumps(fields) if fields else None
}) | Use this method to get information about a Telegraph account.
:param fields: List of account fields to return.
Available fields: short_name, author_name, author_url, auth_url, page_count.
:type fields: list
:returns: Account object on success. |
385,419 | def path(self, path):
self._path = self.manager.get_abs_image_path(path)
log.info(.format(name=self._name, id=self._id, path=self._path)) | Path of the IOU executable.
:param path: path to the IOU image executable |
385,420 | def run(self):
try:
proxy = config_ini.engine.open()
self.LOG.info("Stats for %s - up %s, %s" % (
config_ini.engine.engine_id,
fmt.human_duration(proxy.system.time() - config_ini.engine.startup, 0, 2, True).strip(),
proxy
... | Statistics logger job callback. |
385,421 | async def chat_send(self, message: str, team_only: bool):
ch = ChatChannel.Team if team_only else ChatChannel.Broadcast
await self._execute(
action=sc_pb.RequestAction(
actions=[sc_pb.Action(action_chat=sc_pb.ActionChat(channel=ch.value, message=message))]
... | Writes a message to the chat |
385,422 | def _msg(self, label, *msg):
if self.quiet is False:
txt = self._unpack_msg(*msg)
print("[" + label + "] " + txt) | Prints a message with a label |
385,423 | def random_filtered_sources(sources, srcfilter, seed):
random.seed(seed)
while sources:
src = random.choice(sources)
if srcfilter.get_close_sites(src) is not None:
return [src]
sources.remove(src)
return [] | :param sources: a list of sources
:param srcfilte: a SourceFilter instance
:param seed: a random seed
:returns: an empty list or a list with a single filtered source |
385,424 | def _schema(self, path, obj, app):
if path.startswith():
last_token = jp_split(path)[-1]
if app.version == :
obj.update_field(, scope_split(last_token)[-1])
else:
obj.update_field(, last_token) | fulfill 'name' field for objects under
'#/definitions' and with 'properties' |
385,425 | def _get_api_content(self):
if GITHUB_TOKEN is not None:
self.add_params_to_url({
"access_token": GITHUB_TOKEN
})
api_content_response = requests.get(self.api_url)
self.api_content = json.loads(
api_content_response.text
) | Updates class api content by calling Github api and storing result |
385,426 | def category(self, value):
if value is not None:
assert type(value) is unicode, " attribute: type is not !".format(
"category", value)
self.__category = value | Setter for **self.__category** attribute.
:param value: Attribute value.
:type value: unicode |
385,427 | def character_to_vk(self, character):
for vk in self.non_layout_keys:
if self.non_layout_keys[vk] == character.lower():
return (vk, [])
for vk in self.layout_specific_keys:
if self.layout_specific_keys[vk][0] == character:
return (vk, [])
... | Returns a tuple of (scan_code, modifiers) where ``scan_code`` is a numeric scan code
and ``modifiers`` is an array of string modifier names (like 'shift') |
385,428 | def sky_bbox_ll(self):
if self._wcs is not None:
return pixel_to_skycoord(self.xmin.value - 0.5,
self.ymin.value - 0.5,
self._wcs, origin=0)
else:
return None | The sky coordinates of the lower-left vertex of the minimal
bounding box of the source segment, returned as a
`~astropy.coordinates.SkyCoord` object.
The bounding box encloses all of the source segment pixels in
their entirety, thus the vertices are at the pixel *corners*. |
385,429 | def _refresh_channel(self):
self.channel = salt.transport.client.ReqChannel.factory(self.opts)
return self.channel | Reset the channel, in the event of an interruption |
385,430 | def column_types(self):
column_types = {}
for c in self.sqla_columns:
column_types[c.name] = c.type
return column_types | Return a dict mapping column name to type for all columns in table |
385,431 | def delete(method, hmc, uri, uri_parms, logon_required):
try:
adapter = hmc.lookup_by_uri(uri)
except KeyError:
raise InvalidResourceError(method, uri)
cpc = adapter.manager.parent
assert cpc.dpm_enabled
adapter.manager.remove(adapter.oid) | Operation: Delete Hipersocket (requires DPM mode). |
385,432 | def convert_descriptor_and_rows(self, descriptor, rows):
primary_key = None
schema = tableschema.Schema(descriptor)
if len(schema.primary_key) == 1:
primary_key = schema.primary_key[0]
elif len(schema.primary_key) > 1:
message =
rai... | Convert descriptor and rows to Pandas |
385,433 | def _set_neighbor_route_map_name_direction_out(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={: u}), is_leaf=True, yang_name="neighbor-route-map-name-direction-out", rest_name="neighbor-route-m... | Setter method for neighbor_route_map_name_direction_out, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/af_ipv6_vrf/neighbor/af_ipv6_vrf_neighbor_address_holder/af_ipv6_neighbor_addr/neighbor_route_map/neighbor_route_map_direction_out/neighbor_route_map_name_direction_out (comm... |
385,434 | def event(self, event_data, priority="normal", event_method="EVENT"):
logger.debug("event: " + str(event_data))
euuid = uuid.uuid1()
logger.debug("<%s> <euuid:%s> Sending event data to server: "
"%s" % (str(self.cuuid), str(euuid), str(self.server)))
if... | This function will send event packets to the server. This is the
main method you would use to send data from your application to the
server.
Whenever an event is sent to the server, a universally unique event id
(euuid) is created for each event and stored in the "event_uuids"
d... |
385,435 | def filter_kepler_lcdict(lcdict,
filterflags=True,
nanfilter=,
timestoignore=None):
sappdcsap,pdct caught by the quality
flags.
Returns
-------
lcdict
Returns an `lcdict` (this is useable by most astrobase funct... | This filters the Kepler `lcdict`, removing nans and bad
observations.
By default, this function removes points in the Kepler LC that have ANY
quality flags set.
Parameters
----------
lcdict : lcdict
An `lcdict` produced by `consolidate_kepler_fitslc` or
`read_kepler_fitslc`.
... |
385,436 | def get_selections(pattern=None, state=None):
<host><state>pkg1**python-***openssh*
ret = {}
cmd = [, ]
cmd.append(pattern if pattern else )
stdout = __salt__[](cmd,
output_loglevel=,
python_shell=False)
ret = _parse... | View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code... |
385,437 | def hard_equals(a, b):
if type(a) != type(b):
return False
return a == b | Implements the '===' operator. |
385,438 | def set_parameter(self, name, value):
if name == "valuesToForecast":
self._forecastUntil = None
return super(BaseForecastingMethod, self).set_parameter(name, value) | Sets a parameter for the BaseForecastingMethod.
:param string name: Name of the parameter.
:param numeric value: Value of the parameter. |
385,439 | def from_bma_history(cls: Type[TransactionType], currency: str, tx_data: Dict) -> TransactionType:
tx_data = tx_data.copy()
tx_data["currency"] = currency
for data_list in (, , , , ):
tx_data[.format(data_list)] = .join(tx_data[data_list])
if tx_data["version"] >= 3:... | Get the transaction instance from json
:param currency: the currency of the tx
:param tx_data: json data of the transaction
:return: |
385,440 | def authorized_tenants(self):
if self.is_authenticated and self._authorized_tenants is None:
endpoint = self.endpoint
try:
self._authorized_tenants = utils.get_project_list(
user_id=self.id,
auth_url=endpoint,
... | Returns a memoized list of tenants this user may access. |
385,441 | def img(self):
SlipThumbnail.img(self)
if self.rotation:
mat = cv.CreateMat(2, 3, cv.CV_32FC1)
cv.GetRotationMatrix2D((self.width/2,self.height/2),
-self.rotation, 1.0, mat)
self._rotated = cv.CloneImage(self._... | return a cv image for the icon |
385,442 | def point_in_circle(pt, center, radius):
d = np.linalg.norm(np.asarray(pt) - np.asarray(center))
return d <= radius | Returns true if a given point is located inside (or on the border) of a circle.
>>> point_in_circle((0, 0), (0, 0), 1)
True
>>> point_in_circle((1, 0), (0, 0), 1)
True
>>> point_in_circle((1, 1), (0, 0), 1)
False |
385,443 | def GetBaseFiles(self, diff):
files = {}
for line in diff.splitlines(True):
if line.startswith() or line.startswith():
unused, filename = line.split(, 1)
filename = to_slash(filename.strip())
files[filename] = self.GetBaseFile(filename)
return files | Helper that calls GetBase file for each file in the patch.
Returns:
A dictionary that maps from filename to GetBaseFile's tuple. Filenames
are retrieved based on lines that start with "Index:" or
"Property changes on:". |
385,444 | def argdistincts(self, nested=False):
out = self._argdistincts(absolute=False)
if nested:
out = self.JaggedArray.fromcounts(self.numpy.maximum(0, self.counts - 1), self.JaggedArray.fromcounts(self.index[:, :0:-1].flatten(), out._content))
return out | Return all unique combinations (up to permutation) of two elements,
taken without replacement from the indices of the jagged dimension.
Combinations are ordered lexicographically.
nested: Return a doubly-jagged array where the first jagged dimension
matches the shape of this array |
385,445 | def write_defaults(self):
self.defaults.write()
self.reset_defaults(self.defaults.filename) | Create default config file and reload. |
385,446 | def term_symbols(self):
L_symbols =
L, v_e = self.valence
ml = list(range(-L, L + 1))
ms = [1 / 2, -1 / 2]
ml_ms = list(product(ml, ms))
n = (2 * L + 1) * 2
e_config_combs = list(combinations(range(n), v_e)... | All possible Russell-Saunders term symbol of the Element
eg. L = 1, n_e = 2 (s2)
returns
[['1D2'], ['3P0', '3P1', '3P2'], ['1S0']] |
385,447 | def parse_results(fields, data):
master = []
for record in data[]:
row = [None] * len(fields)
for obj, value in record.iteritems():
if not isinstance(value, (dict, list, tuple)):
if obj in fields:
row[fields.index(obj)] = ensure_utf(v... | Traverses ordered dictionary, calls _traverse_results() to recursively read into the dictionary depth of data |
385,448 | def deprecated(message=None):
def deco(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
warnings.warn(
message or .format(func.__name__),
category=PubChemPyDeprecationWarning,
stacklevel=2
)
return fu... | Decorator to mark functions as deprecated. A warning will be emitted when the function is used. |
385,449 | def np2model_tensor(a):
"Tranform numpy array `a` to a tensor of the same type."
dtype = model_type(a.dtype)
res = as_tensor(a)
if not dtype: return res
return res.type(dtype) | Tranform numpy array `a` to a tensor of the same type. |
385,450 | def main():
parser = create_parser()
args = parser.parse_args()
if hasattr(args, ):
args.handler(args)
else:
parser.print_help() | main. |
385,451 | def _system_config_file():
if sys.platform == :
config_path = os.path.sep.join([_windows_system_appdata(),
_APP_DIRNAME,
_CONFIG_FILENAME])
elif sys.platform.startswith():
config_path = os.path.sep.join([os.path... | Returns the path to the settings.cfg file. On Windows the file is
located in the AppData/Local/envipyengine directory. On Unix, the file
will be located in the ~/.envipyengine directory.
:return: String specifying the full path to the settings.cfg file |
385,452 | def circuit_to_tensorflow_runnable(
circuit: circuits.Circuit,
initial_state: Union[int, np.ndarray] = 0,
) -> ComputeFuncAndFeedDict:
if not circuit.are_all_measurements_terminal():
raise ValueError()
t = _TensorCircuit(circuit, initial_state)
return ComputeFuncAndFeed... | Returns a compute function and feed_dict for a `cirq.Circuit`'s output.
`result.compute()` will return a `tensorflow.Tensor` with
`tensorflow.placeholder` objects to be filled in by `result.feed_dict`, at
which point it will evaluate to the output state vector of the circuit.
You can apply further ope... |
385,453 | def midnight(arg=None):
if arg:
_arg = parse(arg)
if isinstance(_arg, datetime.date):
return datetime.datetime.combine(_arg, datetime.datetime.min.time())
elif isinstance(_arg, datetime.datetime):
return datetime.datetime.combine(_arg.date(), datetime.datetime.mi... | convert date to datetime as midnight or get current day's midnight
:param arg: string or date/datetime
:return: datetime at 00:00:00 |
385,454 | def compose(layers, bbox=None, layer_filter=None, color=None, **kwargs):
from PIL import Image
if not hasattr(layers, ):
layers = [layers]
def _default_filter(layer):
return layer.is_visible()
layer_filter = layer_filter or _default_filter
valid_layers = [x for x in layers if... | Compose layers to a single :py:class:`PIL.Image`.
If the layers do not have visible pixels, the function returns `None`.
Example::
image = compose([layer1, layer2])
In order to skip some layers, pass `layer_filter` function which
should take `layer` as an argument and return `True` to keep th... |
385,455 | def trimult(U, x, uplo=, transa=, alpha=1., inplace=False):
if inplace:
b = x
else:
b = x.copy()
dtrmm_wrap(a=U, b=b, uplo=uplo, transa=transa, alpha=alpha)
return b | b = trimult(U,x, uplo='U')
Multiplies U x, where U is upper triangular if uplo='U'
or lower triangular if uplo = 'L'. |
385,456 | def create_item(self, name):
elem = self.controlled_list.create_item(name)
if elem:
return TodoElementUX(parent=self, controlled_element=elem) | create a new todo list item |
385,457 | def batches(dataset):
seq_lengths = dataset.variables[].data
seq_begins = np.concatenate(([0], np.cumsum(seq_lengths)[:-1]))
def sample():
chosen = np.random.choice(
list(range(len(seq_lengths))), BATCH_SIZE, replace=False)
return batch_at(dataset.variables[].data,
... | Returns a callable that chooses sequences from netcdf data. |
385,458 | def _find_types(pkgs):
return sorted({pkg.split(, 1)[0] for pkg in pkgs
if len(pkg.split(, 1)) == 2}) | Form a package names list, find prefixes of packages types. |
385,459 | def get_annotation(self, key, result_format=):
value = self.get(, {}).get(key)
if not value:
return value
if result_format == :
return value[0]
return value | Is a convenience method for accessing annotations on models that have them |
385,460 | def _reconstruct(self, path_to_root):
item_pattern = re.compile()
dot_pattern = re.compile()
path_segments = dot_pattern.split(path_to_root)
schema_endpoint = self.schema
if path_segments[1]:
for i in range(1,len(path_segments)):
... | a helper method for finding the schema endpoint from a path to root
:param path_to_root: string with dot path to root from
:return: list, dict, string, number, or boolean at path to root |
385,461 | def GroupBy(self: dict, f=None):
if f and is_to_destruct(f):
f = destruct_func(f)
return _group_by(self.items(), f) | [
{
'self': [1, 2, 3],
'f': lambda x: x%2,
'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3]
}
] |
385,462 | def _parse_raw_members(
self, leaderboard_name, members, members_only=False, **options):
if members_only:
return [{self.MEMBER_KEY: m} for m in members]
if members:
return self.ranked_in_list_in(leaderboard_name, members, **options)
else:
... | Parse the raw leaders data as returned from a given leader board query. Do associative
lookups with the member to rank, score and potentially sort the results.
@param leaderboard_name [String] Name of the leaderboard.
@param members [List] A list of members as returned from a sorted set range q... |
385,463 | def offset(self):
if callable(self._offset):
return util.WatchingList(self._offset(*(self.widget.pos+self.widget.size)),self._wlredraw_offset)
else:
return util.WatchingList(self._offset,self._wlredraw_offset) | Property to be used for setting and getting the offset of the layer.
Note that setting this property causes an immediate redraw. |
385,464 | def __disambiguate_proper_names_1(self, docs, lexicon):
for doc in docs:
for word in doc[WORDS]:
if len(word[ANALYSIS]) > 1:
highestFreq = 0
properNameAnalyses = []
for analysis... | Teeme esmase yleliigsete analyyside kustutamise: kui sõnal on mitu
erineva sagedusega pärisnimeanalüüsi, siis jätame alles vaid
suurima sagedusega analyysi(d) ... |
385,465 | def scramble(name, **kwargs):
name = Path(name)
mdf = MDF(name)
texts = {}
callback = kwargs.get("callback", None)
if callback:
callback(0, 100)
count = len(mdf.groups)
if mdf.version >= "4.00":
ChannelConversion = ChannelConv... | scramble text blocks and keep original file structure
Parameters
----------
name : str | pathlib.Path
file name
Returns
-------
name : str
scrambled file name |
385,466 | def remove_vectored_io_slice_suffix_from_name(name, slice):
suffix = .format(slice)
if name.endswith(suffix):
return name[:-len(suffix)]
else:
return name | Remove vectored io (stripe) slice suffix from a given name
:param str name: entity name
:param int slice: slice num
:rtype: str
:return: name without suffix |
385,467 | def get(self, param=None, must=[APIKEY]):
param = {} if param is None else param
r = self.verify_param(param, must)
if not r.is_succ():
return r
handle = CommonResultHandler(lambda rsp: {VERSION_V1:rsp.get(USER), VERSION_V2:rsp}[self.version()])
return self.p... | 查账户信息
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
Args:
param: (Optional)
Results:
Result |
385,468 | def plot(self, feature):
if isinstance(feature, gffutils.Feature):
feature = asinterval(feature)
self.make_fig()
axes = []
for ax, method in self.panels():
feature = method(ax, feature)
axes.append(ax)
return axes | Spawns a new figure showing data for `feature`.
:param feature: A `pybedtools.Interval` object
Using the pybedtools.Interval `feature`, creates figure specified in
:meth:`BaseMiniBrowser.make_fig` and plots data on panels according to
`self.panels()`. |
385,469 | def parse(self, buffer, inlineparent = None):
size = 0
v = []
for i in range(0, self.size):
r = self.innerparser.parse(buffer[size:], None)
if r is None:
return None
v.append(r[0])
size += r[1]
return (v, size) | Compatible to Parser.parse() |
385,470 | def get_distances(rupture, mesh, param):
if param == :
dist = rupture.surface.get_min_distance(mesh)
elif param == :
dist = rupture.surface.get_rx_distance(mesh)
elif param == :
dist = rupture.surface.get_ry0_distance(mesh)
elif param == :
dist = rupture.surface.get_... | :param rupture: a rupture
:param mesh: a mesh of points or a site collection
:param param: the kind of distance to compute (default rjb)
:returns: an array of distances from the given mesh |
385,471 | def get_learning_objectives_metadata(self):
metadata = dict(self._mdata[])
metadata.update({: self._my_map[]})
return Metadata(**metadata) | Gets the metadata for learning objectives.
return: (osid.Metadata) - metadata for the learning objectives
*compliance: mandatory -- This method must be implemented.* |
385,472 | def _virtualenv_sys(venv_path):
"obtain version and path info from a virtualenv."
executable = os.path.join(venv_path, env_bin_dir, )
p = subprocess.Popen([executable,
,
],
env={},
stdout=subprocess.PIPE)
stdout, err = p.communicate()
a... | obtain version and path info from a virtualenv. |
385,473 | def cleanup(self):
for future in self.futures:
future.cancel()
self.executor.shutdown(wait=10)
if self.ssh.get_transport() != None:
self.ssh.close() | Release resources used during shell execution |
385,474 | def get_results(self, title_prefix="", title_override="", rnd_dig=2):
if not self.arr_res:
raise ValueError("Call roll_mc before getting results.")
if title_override:
title = title_override
else:
ctitle = PBE._construct_title(... | Constructs a summary of the results as an array, which might be
useful for writing the results of multiple algorithms to a table.
NOTE- This method must be called AFTER "roll_mc".
:param title_prefix: If desired, prefix the title (such as "Alg 1 ")
:param title_override: Override t... |
385,475 | def status(self):
if isinstance(self.attrs[], dict):
return self.attrs[][]
return self.attrs[] | The status of the container. For example, ``running``, or ``exited``. |
385,476 | def main():
DATABASE.load_contents()
continue_flag = False
while not continue_flag:
DATABASE.print_contents()
try:
command = raw_input(">>> ")
for stmnt_unformated in sqlparse.parse(command):
statement = sqlparse.parse(
sqlp... | The main loop for the commandline parser. |
385,477 | def _read_openjp2_common(self):
with ExitStack() as stack:
filename = self.filename
stream = opj2.stream_create_default_file_stream(filename, True)
stack.callback(opj2.stream_destroy, stream)
codec = opj2.create_decompress(self._codec_format)
... | Read a JPEG 2000 image using libopenjp2.
Returns
-------
ndarray or lst
Either the image as an ndarray or a list of ndarrays, each item
corresponding to one band. |
385,478 | def get_fd(file_or_fd, default=None):
fd = file_or_fd
if fd is None:
fd = default
if hasattr(fd, "fileno"):
fd = fd.fileno()
return fd | Helper function for getting a file descriptor. |
385,479 | def deleteNetworkVisualProp(self, networkId, viewId, visualProperty, verbose=None):
response=api(url=self.___url++str(networkId)++str(viewId)++str(visualProperty)+, method="DELETE", verbose=verbose)
return response | Deletes the bypass Visual Property specificed by the `visualProperty`, `viewId`, and `networkId` parameters. When this is done, the Visual Property will be defined by the Visual Style
Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API](http://chianti.uc... |
385,480 | def to_struct(self, value):
if self.str_format:
return value.strftime(self.str_format)
return value.strftime(self.default_format) | Cast `date` object to string. |
385,481 | def make_naive(value, timezone):
value = value.astimezone(timezone)
if hasattr(timezone, ):
value = timezone.normalize(value)
return value.replace(tzinfo=None) | Makes an aware datetime.datetime naive in a given time zone. |
385,482 | def get_metric_values(self, group_name):
if group_name not in self._metric_values:
raise ValueError("Metric values for this group name do not "
"exist: {}".format(group_name))
return self._metric_values[group_name] | Get the faked metric values for a metric group, by its metric group
name.
The result includes all metric object values added earlier for that
metric group name, using
:meth:`~zhmcclient.FakedMetricsContextManager.add_metric_object_values`
i.e. the metric values for all resources... |
385,483 | def _SendTerminationMessage(self, status=None):
if not self.runner_args.request_state.session_id:
return
if status is None:
status = rdf_flows.GrrStatus()
client_resources = self.context.client_resources
user_cpu = client_resources.cpu_usage.user_cpu_time
sys_cpu = client_r... | This notifies the parent flow of our termination. |
385,484 | def get_per_identity_records(self, events: Iterable, data_processor: DataProcessor
) -> Generator[Tuple[str, TimeAndRecord], None, None]:
schema_loader = SchemaLoader()
stream_bts_name = schema_loader.add_schema_spec(self._stream_bts)
stream_transformer_... | Uses the given iteratable events and the data processor convert the event into a list of
Records along with its identity and time.
:param events: iteratable events.
:param data_processor: DataProcessor to process each event in events.
:return: yields Tuple[Identity, TimeAndRecord] for al... |
385,485 | def profile_different_methods(search_file, screen_file, method_list, dir_path, file_name):
profiler = ProfileRecorder(0.05)
profiler.load_images(search_file, screen_file)
profiler.profile_methods(method_list)
profiler.wite_to_json(dir_path, file_name) | 对指定的图片进行性能测试. |
385,486 | def serialize(self, queryset, **options):
self.options = options
self.stream = options.get("stream", StringIO())
self.selected_fields = options.get("fields")
self.use_natural_keys = options.get("use_natural_keys", True)
self.xml = options.get("xml", None)
... | Serialize a queryset.
THE OUTPUT OF THIS SERIALIZER IS NOT MEANT TO BE SERIALIZED BACK
INTO THE DB. |
385,487 | def _compute_distance(self, rup, dists, C):
mref = 3.6
rref = 1.0
rval = np.sqrt(dists.rhypo ** 2 + C[] ** 2)
return (C[] + C[] * (rup.mag - mref)) *\
np.log10(rval / rref) + C[] * (rval - rref) | Compute the distance function, equation (9): |
385,488 | def _are_safety_checks_disabled(self, caller=u"unknown_function"):
if self.rconf.safety_checks:
return False
self.log_warn([u"Safety checks disabled => %s passed", caller])
return True | Return ``True`` if safety checks are disabled.
:param string caller: the name of the caller function
:rtype: bool |
385,489 | def build_package(team, username, package, subpath, yaml_path,
checks_path=None, dry_run=False, env=):
def find(key, value):
if isinstance(value, Iterable) and not isinstance(value, string_types):
for k, v in iteritems(value):
if k == key:
... | Builds a package from a given Yaml file and installs it locally.
Returns the name of the package. |
385,490 | def get_value(self, section, option, default=None):
try:
valuestr = self.get(section, option)
except Exception:
if default is not None:
return default
raise
types = (int, float)
for numtype in types:
try:
... | :param default:
If not None, the given default value will be returned in case
the option did not exist
:return: a properly typed value, either int, float or string
:raise TypeError: in case the value could not be understood
Otherwise the exceptions known to the Confi... |
385,491 | def configure(self, viewport=None, fbo_size=None, fbo_rect=None,
canvas=None):
if canvas is not None:
self.canvas = canvas
canvas = self._canvas
if canvas is None:
raise RuntimeError("No canvas assigned to this Transfo... | Automatically configure the TransformSystem:
* canvas_transform maps from the Canvas logical pixel
coordinate system to the framebuffer coordinate system, taking into
account the logical/physical pixel scale factor, current FBO
position, and y-axis inversion.
* framebuff... |
385,492 | def weather_history_at_id(self, id, start=None, end=None):
assert type(id) is int, " must be an int"
if id < 0:
raise ValueError(" value must be greater than 0")
params = {: id, : self._language}
if start is None and end is None:
pass
elif start i... | Queries the OWM Weather API for weather history for the specified city ID.
A list of *Weather* objects is returned. It is possible to query for
weather history in a closed time period, whose boundaries can be passed
as optional parameters.
:param id: the city ID
:type id: int
... |
385,493 | def _prepare_data_dir(self, data):
logger.debug(__("Preparing data directory for Data with id {}.", data.id))
with transaction.atomic():
temporary_location_string = uuid.uuid4().hex[:10]
data_location = DataLocation.objects.create(... | Prepare destination directory where the data will live.
:param data: The :class:`~resolwe.flow.models.Data` object for
which to prepare the private execution directory.
:return: The prepared data directory path.
:rtype: str |
385,494 | def omitted_parcov(self):
if self.__omitted_parcov is None:
self.log("loading omitted_parcov")
self.__load_omitted_parcov()
self.log("loading omitted_parcov")
return self.__omitted_parcov | get the omitted prior parameter covariance matrix
Returns
-------
omitted_parcov : pyemu.Cov
Note
----
returns a reference
If ErrorVariance.__omitted_parcov is None,
attribute is dynamically loaded |
385,495 | def stylesheet_declarations(string, is_merc=False, scale=1):
display_map = Declaration(Selector(SelectorElement([], [])),
Property(), Value(, False),
(False, (0, 0, 0), (0, 0)))
declarations = [display_map]
tokens = cssTokenizer().t... | Parse a string representing a stylesheet into a list of declarations.
Required boolean is_merc indicates whether the projection should
be interpreted as spherical mercator, so we know what to do with
zoom/scale-denominator in parse_rule(). |
385,496 | def add_infos(self, *keyvals, **kwargs):
kv_pairs = []
for key, val in keyvals:
key = key.strip()
val = str(val).strip()
if in key:
raise ValueError(.format(key))
kv_pairs.append((key, val))
for k, v in kv_pairs:
if k in self._info:
raise ValueError(
... | Adds the given info and returns a dict composed of just this added info. |
385,497 | def write(models, out=None, base=None, propertybase=None, shorteners=None, logger=logging):
assert out is not None
if not isinstance(models, list): models = [models]
shorteners = shorteners or {}
all_propertybase = [propertybase] if propertybase else []
all_propertybase.append(VERSA_BASEIRI)
... | models - input Versa models from which output is generated. Must be a sequence
object, not an iterator |
385,498 | def mandel(x, y, max_iters):
i = 0
c = complex(x,y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
if (z.real*z.real + z.imag*z.imag) >= 4:
return i
return 255 | Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations. |
385,499 | def nvmlUnitGetCount():
r
c_count = c_uint()
fn = _nvmlGetFunctionPointer("nvmlUnitGetCount")
ret = fn(byref(c_count))
_nvmlCheckReturn(ret)
return bytes_to_str(c_count.value) | r"""
/**
* Retrieves the number of units in the system.
*
* For S-class products.
*
* @param unitCount Reference in which to return the number of units
*
* @return
* - \ref NVML_SUCCESS if \a unitCount has been set
* ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.