Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
366,100 | def decluster(self, trig_int, timing=, metric=):
all_detections = []
for fam in self.families:
all_detections.extend(fam.detections)
if timing == :
if metric == :
detect_info = [(d.detect_time, d.detect_val / d.no_chans)
... | De-cluster a Party of detections by enforcing a detection separation.
De-clustering occurs between events detected by different (or the same)
templates. If multiple detections occur within trig_int then the
preferred detection will be determined by the metric argument. This
can be eithe... |
366,101 | def check_user_can_comment(recID, client_ip_address, uid=-1):
recID = wash_url_argument(recID, )
client_ip_address = wash_url_argument(client_ip_address, )
uid = wash_url_argument(uid, )
max_action_time = time.time() - \
CFG_WEBCOMMENT_TIMELIMIT_PROCESSING_COMMENTS_IN_SECONDS
max_action... | Check if a user hasn't already commented within the last seconds
time limit: CFG_WEBCOMMENT_TIMELIMIT_PROCESSING_COMMENTS_IN_SECONDS
:param recID: record id
:param client_ip_address: IP => use: str(req.remote_ip)
:param uid: user id, as given by invenio.legacy.webuser.getUid(req) |
366,102 | def getValue(self, row):
if self._cachedValues is None:
return self.calcValue(row)
k = id(row)
if k in self._cachedValues:
return self._cachedValues[k]
ret = self.calcValue(row)
self._cachedValues[k] = ret
cachesize = options.col_cache_... | Memoize calcValue with key id(row) |
366,103 | def _assert_executable_regions_match(workflow_enabled_regions, workflow_spec):
executables = [i.get("executable") for i in workflow_spec.get("stages")]
for exect in executables:
if exect.startswith("applet-") and len(workflow_enabled_regions) > 1:
raise WorkflowBuilderException("Build... | Check if the global workflow regions and the regions of stages (apps) match.
If the workflow contains any applets, the workflow can be currently enabled
in only one region - the region in which the applets are stored. |
366,104 | def exp(self):
vecNorm = self.x**2 + self.y**2 + self.z**2
wPart = np.exp(self.w)
q = Quaternion()
q.w = wPart * np.cos(vecNorm)
q.x = wPart * self.x * np.sin(vecNorm) / vecNorm
q.y = wPart * self.y * np.sin(vecNorm) / ... | Returns the exponent of the quaternion.
(not tested) |
366,105 | def decode(self, X, lengths=None, algorithm=None):
check_is_fitted(self, "startprob_")
self._check()
algorithm = algorithm or self.algorithm
if algorithm not in DECODER_ALGORITHMS:
raise ValueError("Unknown decoder {!r}".format(algorithm))
decoder = {
... | Find most likely state sequence corresponding to ``X``.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Feature matrix of individual samples.
lengths : array-like of integers, shape (n_sequences, ), optional
Lengths of the individual sequence... |
366,106 | def findUnique(self, tableClass, comparison=None, default=_noItem):
results = list(self.query(tableClass, comparison, limit=2))
lr = len(results)
if lr == 0:
if default is _noItem:
raise errors.ItemNotFound(comparison)
else:
retur... | Find an Item in the database which should be unique. If it is found,
return it. If it is not found, return 'default' if it was passed,
otherwise raise L{errors.ItemNotFound}. If more than one item is
found, raise L{errors.DuplicateUniqueItem}.
@param comparison: implementor of L{iaxi... |
366,107 | def filesystem_from_config_dict(config_fs):
if "module" not in config_fs:
print("Key should be defined for the filesystem provider ( configuration option)", file=sys.stderr)
exit(1)
filesystem_providers = get_filesystems_providers()
if config_fs["module"] not in filesystem_providers:
... | Given a dict containing an entry "module" which contains a FSProvider identifier, parse the configuration and returns a fs_provider.
Exits if there is an error. |
366,108 | def parent(self):
path = .join(self.path.split()[:-1])
s = path.strip().split()
if len(s)==2 and s[1]==:
return None
else:
return self.__class__(self, path=path) | return the parent URL, with params, query, and fragment in place |
366,109 | def send(self, msg):
with self._pub_lock:
self.publish.send_string(msg)
return self | Send the given message. |
366,110 | def edit(dataset_uri):
try:
dataset = dtoolcore.ProtoDataSet.from_uri(
uri=dataset_uri,
config_path=CONFIG_PATH
)
except dtoolcore.DtoolCoreTypeError:
dataset = dtoolcore.DataSet.from_uri(
uri=dataset_uri,
config_path=CONFIG_PATH
... | Default editor updating of readme content. |
366,111 | def start(self, *args, **kwargs):
queue = Queue()
stdout_reader, stderr_reader = \
self._create_readers(queue, *args, **kwargs)
self.thread = threading.Thread(target=self._read,
args=(stdout_reader,
... | Start to read the stream(s). |
366,112 | def getEdges(self, edges, inEdges = True, outEdges = True, rawResults = False) :
try :
return edges.getEdges(self, inEdges, outEdges, rawResults)
except AttributeError :
raise AttributeError("%s does not seem to be a valid Edges object" % edges) | returns in, out, or both edges linked to self belonging the collection 'edges'.
If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects |
366,113 | def get_transaction(self, transaction_id):
payload = self._get_data_by_id(
transaction_id, )
txn = Transaction()
txn.ParseFromString(payload)
return txn | Returns a Transaction object from the block store by its id.
Params:
transaction_id (str): The header_signature of the desired txn
Returns:
Transaction: The specified transaction
Raises:
ValueError: The transaction is not in the block store |
366,114 | def get_subpackages_names(dir_):
def is_package(d):
d = os.path.join(dir_, d)
return os.path.isdir(d) and glob.glob(os.path.join(d, ))
ret = list(filter(is_package, os.listdir(dir_)))
ret.sort()
return ret | Figures out the names of the subpackages of a package
Args:
dir_: (str) path to package directory
Source: http://stackoverflow.com/questions/832004/python-finding-all-packages-inside-a-package |
366,115 | def brackets_insanity_check(p_string):
if p_string.count(FORK_TOKEN) != p_string.count(CLOSE_TOKEN):
dict_values = {
FORK_TOKEN: p_string.count(FORK_TOKEN),
CLOSE_TOKEN: p_string.count(CLOSE_TOKEN)
}
max_bracket = max(dict_values, key=dict_valu... | This function performs a check for different number of '(' and ')'
characters, which indicates that some forks are poorly constructed.
Parameters
----------
p_string: str
String with the definition of the pipeline, e.g.::
'processA processB processC(ProcessD | ProcessE)' |
366,116 | def unravel_staff(staff_data):
staff_list = []
for role, staff_members in staff_data[].items():
for member in staff_members:
member[] = role
staff_list.append(member)
return staff_list | Unravels staff role dictionary into flat list of staff
members with ``role`` set as an attribute.
Args:
staff_data(dict): Data return from py:method::get_staff
Returns:
list: Flat list of staff members with ``role`` set to
role type (i.e. course_admin, ... |
366,117 | def url_encode_stream(obj, stream=None, charset=, encode_keys=False,
sort=False, key=None, separator=):
gen = _url_encode_impl(obj, charset, encode_keys, sort, key)
if stream is None:
return gen
for idx, chunk in enumerate(gen):
if idx:
stream.write(sep... | Like :meth:`url_encode` but writes the results to a stream
object. If the stream is `None` a generator over all encoded
pairs is returned.
.. versionadded:: 0.8
:param obj: the object to encode into a query string.
:param stream: a stream to write the encoded object into or `None` if
... |
366,118 | def get_ribo_counts(ribo_fileobj, transcript_name, read_lengths, read_offsets):
read_counts = {}
total_reads = 0
for record in ribo_fileobj.fetch(transcript_name):
query_length = record.query_length
position_ref = record.pos + 1
for index, read_length in enumerate(read_lengths):... | For each mapped read of the given transcript in the BAM file
(pysam AlignmentFile object), return the position (+1) and the
corresponding frame (1, 2 or 3) to which it aligns.
Keyword arguments:
ribo_fileobj -- file object - BAM file opened using pysam AlignmentFile
transcript_name -- Name of trans... |
366,119 | def comp_meta(file_bef, file_aft, mode="pfail"):
if env():
cij.err("cij.nvme.comp_meta: Invalid NVMe ENV.")
return 1
nvme = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)
num_chk = int(nvme["LNVM_TOTAL_CHUNKS"])
meta_bef = cij.bin.Buffer(types=get_descriptor_table(nvme[]), length=nu... | Compare chunk meta, mode=[pfail, power, reboot] |
366,120 | def registerAccountResponse(self, person, vendorSpecific=None):
mmp_dict = {: (, person.toxml())}
return self.POST(, fields=mmp_dict, headers=vendorSpecific) | CNIdentity.registerAccount(session, person) → Subject
https://releases.dataone.org/online/api-
documentation-v2.0.1/apis/CN_APIs.html#CNIdentity.registerAccount.
Args:
person:
vendorSpecific:
Returns: |
366,121 | def return_cursor(self, dataout, sx, sy, frame, wcs, key, strval=):
wcscode = (frame + 1) * 100 + wcs
if (key == ):
curval = "EOF"
else:
if (key in string.printable and key not in string.whitespace):
keystr = key
else:
... | writes the cursor position to dataout.
input:
dataout: the output stream
sx: x coordinate
sy: y coordinate
wcs: nonzero if we want WCS translation
frame: frame buffer index
key: keystroke used as trigge... |
366,122 | def stream_stats(self):
Tp = self.frame_length/float(self.fs)*1000
print( \
% (self.DSP_tic[0]*1000,))
print( % Tp)
Tmp_mean = np.mean(np.diff(np.array(self.DSP_tic))[1:]*1000)
print( % Tmp_mean)
Tprocess_mean = np.mean(np.array(self.DSP_toc... | Display basic statistics of callback execution: ideal period
between callbacks, average measured period between callbacks,
and average time spent in the callback. |
366,123 | def field_pklist_to_json(self, model, pks):
app_label = model._meta.app_label
model_name = model._meta.model_name
return {
: app_label,
: model_name,
: list(pks),
} | Convert a list of primary keys to a JSON dict.
This uses the same format as cached_queryset_to_json |
366,124 | def build_structure(self, component, runnable, structure):
if self.debug: print("\n++++++++ Calling build_structure of %s with runnable %s, parent %s"%(component.id, runnable.id, runnable.parent))
for ch in structure.child_instances:
child_runnable = self.build_run... | Adds structure to a runnable component based on the structure
specifications in the component model.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which structure is to be... |
366,125 | def open_sensor(
self,
input_source: str,
output_dest: Optional[str] = None,
extra_cmd: Optional[str] = None,
) -> Coroutine:
command = ["-vn", "-filter:a", "silencedetect=n={}dB:d=1".format(self._peak)]
return self.start_worker(
cmd=com... | Open FFmpeg process for read autio stream.
Return a coroutine. |
366,126 | def parse_config_file(path: str, final: bool = True) -> None:
return options.parse_config_file(path, final=final) | Parses global options from a config file.
See `OptionParser.parse_config_file`. |
366,127 | def makeSer(segID, N, CA, C, O, geo):
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_OG_length=geo.CB_OG_length
CA_CB_OG_angle=geo.CA_CB_OG_angle
N_CA_CB_OG_diangle=geo.N_CA_CB_OG_diangle
carbon_b= calculateCoordinates... | Creates a Serine residue |
366,128 | def from_settings(cls, settings=None, storage=None):
if storage is None:
storage = cls.DEFAULT_STORAGE
return cls.from_storage(storage(settings=settings)) | Create from settings.
Parameters
----------
settings : `dict`, optional
Settings (default: None).
storage : `type`, optional
Storage class (default: cls.DEFAULT_STORAGE)
Returns
-------
`markovchain.Markov` |
366,129 | def nucleotide_range(self):
s an amino acid variant, otherwise start+2==endp':
return 3 * self.position, 3 * self.position + 2
else:
return self.position, self.position | Returns the nucleotide (start, end) positions inclusive of this variant.
start==end if it's an amino acid variant, otherwise start+2==end |
366,130 | def QA_fetch_future_min(
code,
start, end,
format=,
frequence=,
collections=DATABASE.future_min):
if frequence in [, ]:
frequence =
elif frequence in [, ]:
frequence =
elif frequence in [, ]:
frequence =
elif frequence in [, ]:
... | 获取股票分钟线 |
366,131 | def _default_child_lookup(self, name):
if name in self.indexes or name in self.traversal_indexes:
try:
return self.proxies[name]
except KeyError:
self.proxies[name] = ElementProxy(self, name)
return self.proxies[name]
else:... | Return an instance of :class:`ElementProxy <hl7apy.core.ElementProxy>` containing the children found
having the given name
:type name: ``str``
:param name: the name of the children (e.g. PID)
:return: an instance of :class:`ElementProxy <hl7apy.core.ElementProxy>` containing the result... |
366,132 | def initialize_plugins(self):
for plugin_name in self.options.plugin:
parts = plugin_name.split()
if len(parts) > 1:
module_name = .join(parts[:-1])
class_name = parts[-1]
else:
module_name = parts[0]
... | Attempt to Load and initialize all the plugins.
Any issues loading plugins will be output to stderr. |
366,133 | def add_lnTo(self, x, y):
lnTo = self._add_lnTo()
pt = lnTo._add_pt()
pt.x, pt.y = x, y
return lnTo | Return a newly created `a:lnTo` subtree with end point *(x, y)*.
The new `a:lnTo` element is appended to this `a:path` element. |
366,134 | def robotics_arg_parser():
parser = arg_parser()
parser.add_argument(, help=, type=str, default=)
parser.add_argument(, help=, type=int, default=None)
parser.add_argument(, type=int, default=int(1e6))
return parser | Create an argparse.ArgumentParser for run_mujoco.py. |
366,135 | def _set_clear_mpls_ldp_statistics(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=clear_mpls_ldp_statistics.clear_mpls_ldp_statistics, is_leaf=True, yang_name="clear-mpls-ldp-statistics", rest_name="clear-mpls-ldp-statistics", parent=self, path_helpe... | Setter method for clear_mpls_ldp_statistics, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_ldp_statistics (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_clear_mpls_ldp_statistics is considered as a private
method. Backends looking to populate this variable sh... |
366,136 | def _recv_robust(self, sock, size):
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise | Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability) |
366,137 | def info(self, set_info=None, followlinks=True):
return self.connection.info(self, set_info=set_info, followlinks=followlinks) | info: backend info about self (probably not implemented for
all backends. The result will be backend specific).
@param set_info: If not None, this data will be set on self.
@param followlinks: If True, symlinks will be followed. If
False, the info of the symlink itself will be... |
366,138 | def chassis(self):
self._check_session()
status, data = self._rest.get_request()
return data | Get list of chassis known to test session. |
366,139 | def norm_l1(x, axis=None):
r
nl1 = np.sum(np.abs(x), axis=axis, keepdims=True)
if nl1.size == 1:
nl1 = nl1.ravel()[0]
return nl1 | r"""Compute the :math:`\ell_1` norm
.. math::
\| \mathbf{x} \|_1 = \sum_i | x_i |
where :math:`x_i` is element :math:`i` of vector :math:`\mathbf{x}`.
Parameters
----------
x : array_like
Input array :math:`\mathbf{x}`
axis : `None` or int or tuple of ints, optional (default None)... |
366,140 | def __lock_location(self) -> None:
if not self._is_active:
if self._location in LogdirWriter._locked_locations:
raise RuntimeError(
% self._location)
LogdirWriter._locked_locations.add(self._... | Attempts to lock the location used by this writer. Will raise an error if the location is
already locked by another writer. Will do nothing if the location is already locked by
this writer. |
366,141 | def start_stack(self, stack):
url = .format(self.host, stack)
return self.__post(url) | 启动服务组
启动服务组中的所有停止状态的服务。
Args:
- stack: 服务所属的服务组名称
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回空dict{},失败返回{"error": "<errMsg string>"}
- ResponseInfo 请求的Response信息 |
366,142 | def friendly_type_name(raw_type: typing.Type) -> str:
try:
return _TRANSLATE_TYPE[raw_type]
except KeyError:
LOGGER.error(, raw_type)
return str(raw_type) | Returns a user-friendly type name
:param raw_type: raw type (str, int, ...)
:return: user friendly type as string |
366,143 | def pisaParser(src, context, default_css="", xhtml=False, encoding=None, xml_output=None):
global CSSAttrCache
CSSAttrCache = {}
if xhtml:
document = parser.parse(
src,
)
if xml_output:
if encoding:
xml_output.write(document.toprettyx... | - Parse HTML and get miniDOM
- Extract CSS informations, add default CSS, parse CSS
- Handle the document DOM itself and build reportlab story
- Return Context object |
366,144 | def set_range(self, minimum, maximum):
self._min = minimum
self._max = maximum
self.on_rangeChange(minimum, maximum) | Set a range.
The range is passed unchanged to the rangeChanged member function.
:param minimum: minimum value of the range (None if no percentage is required)
:param maximum: maximum value of the range (None if no percentage is required) |
366,145 | def write_comment(fh, comment):
_require_string(comment, )
fh.write(_escape_comment(comment))
fh.write(b) | Writes a comment to the file in Java properties format.
Newlines in the comment text are automatically turned into a continuation
of the comment by adding a "#" to the beginning of each line.
:param fh: a writable file-like object
:param comment: comment string to write |
366,146 | def forward_backward(self, data_batch):
self.forward(data_batch, is_train=True)
self.backward() | A convenient function that calls both ``forward`` and ``backward``. |
366,147 | def get_build_configuration_set_raw(id=None, name=None):
found_id = common.set_id(pnc_api.build_group_configs, id, name)
response = utils.checked_api_call(pnc_api.build_group_configs, , id=found_id)
if response:
return response.content | Get a specific BuildConfigurationSet by name or ID |
366,148 | def visit_and_update(self, visitor_fn):
new_left = self.left.visit_and_update(visitor_fn)
new_right = self.right.visit_and_update(visitor_fn)
if new_left is not self.left or new_right is not self.right:
return visitor_fn(BinaryComposition(self.operator, new_left, new_right)... | Create an updated version (if needed) of BinaryComposition via the visitor pattern. |
366,149 | def hr(color):
logger = log(color)
return lambda symbol: logger(symbol * terminal_size.usable_width) | Colored horizontal rule printer/logger factory.
The resulting function prints an entire terminal row with the given
symbol repeated. It's a terminal version of the HTML ``<hr/>``. |
366,150 | async def revoke_cred(self, rr_id: str, cr_id) -> int:
LOGGER.debug(, rr_id, cr_id)
if not self.wallet.handle:
LOGGER.debug(, self.name)
raise WalletState(.format(self.name))
if not ok_rev_reg_id(rr_id):
LOGGER.debug(, rr_id)
raise BadI... | Revoke credential that input revocation registry identifier and
credential revocation identifier specify.
Return (epoch seconds) time of revocation.
Raise AbsentTails if no tails file is available for input revocation registry identifier.
Raise WalletState for closed wallet.
Ra... |
366,151 | def concordance_index_censored(event_indicator, event_time, estimate, tied_tol=1e-8):
event_indicator, event_time, estimate = _check_inputs(
event_indicator, event_time, estimate)
w = numpy.ones_like(estimate)
return _estimate_concordance_index(event_indicator, event_time, estimate, w, tied_t... | Concordance index for right-censored data
The concordance index is defined as the proportion of all comparable pairs
in which the predictions and outcomes are concordant.
Samples are comparable if for at least one of them an event occurred.
If the estimated risk is larger for the sample with a higher ... |
366,152 | def run(self):
query = self.query
self.cardinality = query.add_columns(self.columns[0].sqla_expr).count()
self._set_column_filter_expressions()
self._set_global_filter_expression()
self._set_sort_expressions()
self._set_yadcf_data(query)
... | Launch filtering, sorting and paging to output results. |
366,153 | def walk_trie(dicts, w, q, A):
if q in A.F and in dicts:
yield w
for key in dicts.keys():
if key == :
continue
if A.transition_function(q, key) is None:
return
try:
yield from walk_trie(dicts[key], w + key, A.transition_function(q... | Helper function for traversing the word trie. It simultaneously keeps
track of the active Automaton state, producing the intersection of the
given Automaton and the trie (which is equivalent to a DFA). Once an
invalid "terminating" state is reached, the children nodes are immediately
dismissed from the... |
366,154 | def diagonal_neural_gpu(inputs, hparams, name=None):
with tf.variable_scope(name, "diagonal_neural_gpu"):
def step(state_tup, inp):
state, _ = state_tup
x = state
for layer in range(hparams.num_hidden_layers):
x, new_loss = common_layers.diagonal_conv_gru(
x, (hpar... | Improved Neural GPU as in https://arxiv.org/abs/1702.08727. |
366,155 | def alias_proficiency(self, proficiency_id, alias_id):
self._alias_id(primary_id=proficiency_id, equivalent_id=alias_id) | Adds an ``Id`` to a ``Proficiency`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Proficiency`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another proficiency, it is
reassigned to the gi... |
366,156 | def read(self, n=-1):
pos = self.tell()
num_items_to_read = n if n != -1 else self.length - pos
new_pos = min(pos + num_items_to_read, self.length)
if new_pos > self._current_lob_length:
missing_num_items_to_read = new_pos - self._current_lob_length
... | Read up to n items (bytes/chars) from the lob and return them.
If n is -1 then all available data is returned.
Might trigger further loading of data from the database if the number of items requested for
reading is larger than what is currently buffered. |
366,157 | def init_log_config(handler=None):
for applog in lognames.values():
propagate = (applog != LOG_ROOT)
configdict[][applog] = dict(level=, propagate=propagate)
logging.config.dictConfig(configdict)
if handler is None:
handler = ansicolor.ColoredStreamHandler(strm=sys.std... | Set up the application logging (not to be confused with check loggers). |
366,158 | def update_work_as_completed(self, worker_id, work_id, other_values=None,
error=None):
client = self._datastore_client
try:
with client.transaction() as transaction:
work_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id,
K... | Updates work piece in datastore as completed.
Args:
worker_id: ID of the worker which did the work
work_id: ID of the work which was done
other_values: dictionary with additonal values which should be saved
with the work piece
error: if not None then error occurred during computatio... |
366,159 | def add(self, name, value):
clone = self._clone()
clone._qsl = [p for p in self._qsl
if not(p[0] == name and p[1] == value)]
clone._qsl.append((name, value,))
return clone | Append a value to multiple value parameter. |
366,160 | def save(self):
LOGGER.debug("Cluster.save")
post_payload = {}
consolidated_containers_id = []
if self.id is not None:
post_payload[] = self.id
if self.name is not None:
post_payload[] = self.name
if self.containers_id is not None:
... | save or update this cluster in Ariane Server
:return: |
366,161 | def path(self, which=None):
if which in (, ):
return .format(
super(PuppetClass, self).path(which=),
which
)
return super(PuppetClass, self).path(which) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
smart_class_parameters
/api/puppetclasses/:puppetclass_id/smart_class_parameters
Otherwise, call ``super``. |
366,162 | def _make_version(major, minor, micro, releaselevel, serial):
assert releaselevel in [, , , ]
version = "%d.%d" % (major, minor)
if micro:
version += ".%d" % (micro,)
if releaselevel != :
short = {: , : , : }[releaselevel]
version += "%s%d" % (short, serial)
return versi... | Create a readable version string from version_info tuple components. |
366,163 | def handleDetailDblClick( self, item ):
if ( isinstance(item, XOrbRecordItem) ):
self.emitRecordDoubleClicked(item.record()) | Handles when a detail item is double clicked on.
:param item | <QTreeWidgetItem> |
366,164 | def is_hermitian(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
return (matrix.shape[0] == matrix.shape[1] and
np.allclose(matrix, np.conj(matrix.T), rtol=rtol, atol=atol)) | Determines if a matrix is approximately Hermitian.
A matrix is Hermitian if it's square and equal to its adjoint.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
... |
366,165 | def update_refs(self, ref_updates, repository_id, project=None, project_id=None):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
if repository_id is not None:
route_values[] = self._serialize.url(, repository_id, )
... | UpdateRefs.
Creating, updating, or deleting refs(branches).
:param [GitRefUpdate] ref_updates: List of ref updates to attempt to perform
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param str project_id: ID or name of... |
366,166 | def start(self):
while True:
task = self.taskmaster.next_task()
if task is None:
break
try:
task.prepare()
if task.needs_execute():
task.execute()
except:
if se... | Start the job. This will begin pulling tasks from the taskmaster
and executing them, and return when there are no more tasks. If a task
fails to execute (i.e. execute() raises an exception), then the job will
stop. |
366,167 | def _prt_line_detail(self, prt, line, lnum=""):
data = zip(self.flds, line.split())
txt = ["{:2}) {:13} {}".format(i, hdr, val) for i, (hdr, val) in enumerate(data)]
prt.write("{LNUM}\n{TXT}\n".format(LNUM=lnum, TXT=.join(txt))) | Print each field and its value. |
366,168 | def consume_keys_asynchronous_processes(self):
print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n")
jobs = multiprocessing.cpu_count()*4 if (multiprocessing.cpu_count()*4 < self.input_queue.qsize()) \
else self.input_queue.qsize()
... | Work through the keys to look up asynchronously using multiple processes |
366,169 | def SetAlpha(self, alpha):
s transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return:
'
self._AlphaChannel = alpha * 255
if self._AlphaChannel is not None:
self.MasterFrame.SetTransparent(self._AlphaChannel) | Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return: |
366,170 | def is_valid_address(self, *args, **kwargs):
client = HTTPClient(self.withdraw_server_address + self.withdraw_endpoint)
return client.request(, kwargs) | check address
Accepts:
- address [hex string] (withdrawal address in hex form)
- coinid [string] (blockchain id (example: BTCTEST, LTCTEST))
Returns dictionary with following fields:
- bool [Bool] |
366,171 | def inter(a, b):
assert isinstance(a, stypes.SpiceCell)
assert isinstance(b, stypes.SpiceCell)
assert a.dtype == b.dtype
if a.dtype is 0:
c = stypes.SPICECHAR_CELL(max(a.size, b.size), max(a.length, b.length))
elif a.dtype is 1:
c = stypes.SPICEDOUBLE_CELL(max(a.size, ... | Intersect two sets of any data type to form a third set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inter_c.html
:param a: First input set.
:type a: spiceypy.utils.support_types.SpiceCell
:param b: Second input set.
:type b: spiceypy.utils.support_types.SpiceCell
:return: Intersec... |
366,172 | def output(self, out_file):
self.out_file = out_file
out_file.write()
out_file.write()
self._output_summary()
for entry in sorted(self.entries, key=_entry_sort_key):
self._output_entry(entry) | Write the converted entries to out_file |
366,173 | def get_runs(project_name):
conn, c = open_data_base_connection()
try:
c.execute(.format(project_name + "_run_table"))
run_names = np.array(c.fetchall()).squeeze(axis=1)
run_names = convert_list_to_dict(run_names)
return run_names
except sqlite3.OperationalError:
... | Returns a dict of runs present in project.
:return: dict -> {<int_keys>: <project_name>} |
366,174 | def _set_suppress_arp(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=suppress_arp.suppress_arp, is_container=, presence=False, yang_name="suppress-arp", rest_name="suppress-arp", parent=self, path_helper=self._path_helper, extmethods=self._extmethods... | Setter method for suppress_arp, mapped from YANG variable /bridge_domain/suppress_arp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_suppress_arp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._... |
366,175 | def _dos2unix_cygwin(self, file_path):
dos2unix_cmd = \
[os.path.join(self._cygwin_bin_location, "dos2unix.exe"),
self._get_cygwin_path(file_path)]
process = Popen(dos2unix_cmd,
stdout=PIPE, stderr=PIPE, shell=False)
process.communicate() | Use cygwin to convert file to unix format |
366,176 | def _push_to_list(lst, func_name, char, line, offset,
first_arg_pos, first_item, in_list_literal,
lead_spaces, options=None):
opts = parse_options(options)
keywords = add_keywords(opts)
pos_hash = {: char,
: line,
: offset,
... | _push_to_list(lst : [str], func_name : str, char : str, line : int, offset : int,
first_arg_pos :int , first_item : int, in_list_literal : bool,
lead_spaces : int, options : str)
Called when an opening bracket is encountered. A hash containing the
necessary data ... |
366,177 | def save(criteria, report, report_path, adv_x_val):
print_stats(criteria[], criteria[], )
print("Saving to " + report_path)
serial.save(report_path, report)
assert report_path.endswith(".joblib")
adv_x_path = report_path[:-len(".joblib")] + "_adv.npy"
np.save(adv_x_path, adv_x_val) | Saves the report and adversarial examples.
:param criteria: dict, of the form returned by AttackGoal.get_criteria
:param report: dict containing a confidence report
:param report_path: string, filepath
:param adv_x_val: numpy array containing dataset of adversarial examples |
366,178 | def instructions(self):
if self._instructions is None:
self._instructions = parser.parse_rule(self.name, self.text)
return self._instructions | Retrieve the instructions for the rule. |
366,179 | def checkAndCreate(self, key, payload,
hostgroupConf,
hostgroupParent,
puppetClassesId):
if key not in self:
self[key] = payload
oid = self[key][]
if not oid:
return False
if ... | Function checkAndCreate
check And Create procedure for an hostgroup
- check the hostgroup is not existing
- create the hostgroup
- Add puppet classes from puppetClassesId
- Add params from hostgroupConf
@param key: The hostgroup name or ID
@param payload: The des... |
366,180 | def text(self,txt):
if not txt:
return
try:
txt = txt.decode()
except:
try:
txt = txt.decode()
except:
pass
self.extra_chars = 0
def encode_char(char):
c... | Print Utf8 encoded alpha-numeric text |
366,181 | def batch_iterable(l, n):
i = iter(l)
piece = list(islice(i, n))
while piece:
yield piece
piece = list(islice(i, n)) | Chunks iterable into n sized batches
Solution from: http://stackoverflow.com/questions/1915170/split-a-generator-iterable-every-n-items-in-python-splitevery |
366,182 | def get_available_name(self, name):
dir_name, file_name = os.path.split(name)
file_root, file_ext = os.path.splitext(file_name)
count = itertools.count(1)
while self.exists(name):
name = os.path.join(dir_name, "%s_%s%s" % (file... | Returns a filename that's free on the target storage system, and
available for new content to be written to. |
366,183 | def create_user_pool(PoolName=None, Policies=None, LambdaConfig=None, AutoVerifiedAttributes=None, AliasAttributes=None, SmsVerificationMessage=None, EmailVerificationMessage=None, EmailVerificationSubject=None, SmsAuthenticationMessage=None, MfaConfiguration=None, DeviceConfiguration=None, EmailConfiguration=None, Sms... | Creates a new Amazon Cognito user pool and sets the password policy for the pool.
See also: AWS API Documentation
:example: response = client.create_user_pool(
PoolName='string',
Policies={
'PasswordPolicy': {
'MinimumLength': 123,
'RequireUp... |
366,184 | def read_mol2(self, path, columns=None):
mol2_code, mol2_lines = next(split_multimol2(path))
self._load_mol2(mol2_lines, mol2_code, columns)
self.mol2_path = path
return self | Reads Mol2 files (unzipped or gzipped) from local drive
Note that if your mol2 file contains more than one molecule,
only the first molecule is loaded into the DataFrame
Attributes
----------
path : str
Path to the Mol2 file in .mol2 format or gzipped format (.mol2.... |
366,185 | def resetVector(x1, x2):
size = len(x1)
for i in range(size):
x2[i] = x1[i] | Copies the contents of vector x1 into vector x2.
@param x1 (array) binary vector to be copied
@param x2 (array) binary vector where x1 is copied |
366,186 | def prepare_rows(table):
num_columns = max(len(row) for row in table)
for row in table:
while len(row) < num_columns:
row.append()
for i in range(num_columns):
row[i] = str(row[i]) if row[i] is not None else
return table | Prepare the rows so they're all strings, and all the same length.
:param table: A 2D grid of anything.
:type table: [[``object``]]
:return: A table of strings, where every row is the same length.
:rtype: [[``str``]] |
366,187 | def valuegetter(*fieldspecs, **kwargs):
combine_subfields = kwargs.get(, False)
pattern = r
def values(record):
for s in fieldspecs:
match = re.match(pattern, s)
if not match:
continue
gd = match.groupdict()
for field in record.ge... | Modelled after `operator.itemgetter`. Takes a variable
number of specs and returns a function, which applied to
any `pymarc.Record` returns the matching values.
Specs are in the form `field` or `field.subfield`, e.g.
`020` or `020.9`.
Example:
>>> from marcx import Record, valuegetter
>>>... |
366,188 | def get_org(self, organization_name=):
self.organization_name = organization_name
if(organization_name == ):
self.organization_name = raw_input()
print
self.org_retrieved = self.logged_in_gh.organization(organization_name) | Retrieves an organization via given org name. If given
empty string, prompts user for an org name. |
366,189 | def stream(command, stdin=None, env=os.environ, timeout=None):
if not isinstance(command, list):
command = shlex.split(command)
cmd = which(command[0])
if cmd is None:
path = env.get("PATH", "")
raise Exception("Command [%s] not in PATH [%s]" % (command[0], path))
command[... | Yields a generator of a command's output. For line oriented commands only.
Args:
command (str or list): a command without pipes. If it's not a list,
``shlex.split`` is applied.
stdin (file like object): stream to use as the command's standard input.
env (dict): The environment i... |
366,190 | def _from_dict(cls, _dict):
args = {}
if in _dict or in _dict:
args[] = _dict.get() or _dict.get(
)
else:
raise ValueError(
final\
)
if in _dict:
args[] = [
SpeechRecognitionAltern... | Initialize a SpeechRecognitionResult object from a json dictionary. |
366,191 | def refkeys(self,fields):
"returns {ModelClass:list_of_pkey_tuples}. see syncschema.RefKey. Donnot all in',self.REFKEYS.keys())
for f in fields:
rk=self.REFKEYS[f]
for model in rk.refmodels: dd[model].extend(rk.pkeys(self,f))
return dd | returns {ModelClass:list_of_pkey_tuples}. see syncschema.RefKey. Don't use this yet. |
366,192 | def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0):
if self.closed or self.eof_received or self.eof_sent or not self.active:
raise SSHException()
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string... | Resize the pseudo-terminal. This can be used to change the width and
height of the terminal emulation created in a previous `get_pty` call.
:param int width: new width (in characters) of the terminal screen
:param int height: new height (in characters) of the terminal screen
:param int... |
366,193 | def to_result(self):
text = [self.text]
if self.note:
text.append(self.note)
return {
: self.line_num,
: self.column,
: .join(text),
: self.types.get(self.message_type, )
} | Convert to the Linter.run return value |
366,194 | def get_item_list_by_name(self, item_list_name, category=):
resp = self.api_request()
for item_list in resp[category]:
if item_list[] == item_list_name:
return self.get_item_list(item_list[])
raise ValueError( + item_list_name) | Retrieve an item list from the server as an ItemList object
:type item_list_name: String
:param item_list_name: name of the item list to retrieve
:type category: String
:param category: the category of lists to fetch. At the time of
writing, supported values are "own" and "s... |
366,195 | def trim_docstring(docstring):
if not docstring:
return
indent = max_indent
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
trimmed = [lines[0].strip()]
if indent < max_indent:
for line in lines[1:]:
trimmed.ap... | Removes indentation from triple-quoted strings.
This is the function specified in PEP 257 to handle docstrings:
https://www.python.org/dev/peps/pep-0257/.
Args:
docstring: str, a python docstring.
Returns:
str, docstring with indentation removed. |
366,196 | def _getFirstOnBit(self, input):
if input == SENTINEL_VALUE_FOR_MISSING_DATA:
return [None]
else:
if input < self.minval:
if input >= self.maxval:
raise Exception( %
(str(input), str(self.minval), str(self.maxval)))
else:
if i... | Return the bit offset of the first bit to be set in the encoder output.
For periodic encoders, this can be a negative number when the encoded output
wraps around. |
366,197 | def missing_datetimes(self, finite_datetimes):
return [d for d in finite_datetimes if not self._instantiate_task_cls(self.datetime_to_parameter(d)).complete()] | Override in subclasses to do bulk checks.
Returns a sorted list.
This is a conservative base implementation that brutally checks completeness, instance by instance.
Inadvisable as it may be slow. |
366,198 | def make_ranges(self, file_url):
size = file_url.size
bytes_per_chunk = self.determine_bytes_per_chunk(size)
start = 0
ranges = []
while size > 0:
amount = bytes_per_chunk
if amount > size:
amount = size
ranges.append((... | Divides file_url size into an array of ranges to be downloaded by workers.
:param: file_url: ProjectFileUrl: file url to download
:return: [(int,int)]: array of (start, end) tuples |
366,199 | def standardDeviation2d(img, ksize=5, blurred=None):
if ksize not in (list, tuple):
ksize = (ksize,ksize)
if blurred is None:
blurred = gaussian_filter(img, ksize)
else:
assert blurred.shape == img.shape
std = np.empty_like(img)
_calc(img, ksize[0]... | calculate the spatial resolved standard deviation
for a given 2d array
ksize -> kernel size
blurred(optional) -> with same ksize gaussian filtered image
setting this parameter reduces processing time |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.