Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
345,600 | def epcrparse(self):
from Bio.Blast.Applications import NcbiblastnCommandline
while True:
sample, record, line = self.epcrparsequeue.get()
gene, chromosome, strand, start, end, m_match, gaps, act_len_exp_len = line.split()
... | Run BLAST, and record results to the object |
345,601 | def _make_it_3d(img):
shape = get_shape(img)
if len(shape) == 3:
return img
elif (len(shape) == 4 and shape[3] == 1):
try:
data = get_data(img)
affine = img.get_affine()
img = nib.Nifti1Image(data[:, :, :, 0], affine)
except Exc... | Enforce that img is a 3D img-like object, if it is not, raise a TypeError.
i.e., remove dimensions of size 1.
Parameters
----------
img: img-like object
Returns
-------
3D img-like object |
345,602 | def _wrap_function_return(val):
if type(val) is _UnityGraphProxy:
return _SGraph(_proxy = val)
elif type(val) is _UnitySFrameProxy:
return _SFrame(_proxy = val)
elif type(val) is _UnitySArrayProxy:
return _SArray(_proxy = val)
elif type(val) is _UnityModel:
... | Recursively walks each thing in val, opening lists and dictionaries,
converting all occurrences of UnityGraphProxy to an SGraph,
UnitySFrameProxy to SFrame, and UnitySArrayProxy to SArray. |
345,603 | def explain(self):
return ([self._sqlAndArgs(, self._queryTarget)[0]] +
self._runQuery(, self._queryTarget)) | A debugging API, exposing SQLite's I{EXPLAIN} statement.
While this is not a private method, you also probably don't have any
use for it unless you understand U{SQLite
opcodes<http://www.sqlite.org/opcode.html>} very well.
Once you do, it can be handy to call this interactively to get ... |
345,604 | def _get_b(self):
orig = self.origin
dest = self.destination
(ox, oy) = orig.pos
(dx, dy) = dest.pos
denominator = dx - ox
x_numerator = (dy - oy) * ox
y_numerator = denominator * oy
return ((y_numerator - x_numerator), denominator) | Return my Y-intercept.
I probably don't really hit the left edge of the window, but
this is where I would, if I were long enough. |
345,605 | def read_byte_data(self, i2c_addr, register, force=None):
self._set_address(i2c_addr, force=force)
msg = i2c_smbus_ioctl_data.create(
read_write=I2C_SMBUS_READ, command=register, size=I2C_SMBUS_BYTE_DATA
)
ioctl(self.fd, I2C_SMBUS, msg)
return msg.data.conten... | Read a single byte from a designated register.
:param i2c_addr: i2c address
:type i2c_addr: int
:param register: Register to read
:type register: int
:param force:
:type force: Boolean
:return: Read byte value
:rtype: int |
345,606 | def get_ips(self, instance_id):
self._restore_from_storage(instance_id)
if self._start_failed:
raise Exception(
% instance_id)
ret = list()
v_m = self._qualified_name_to_vm(instance_id)
if not v_m:
raise Exception("Ca... | Retrieves the private and public ip addresses for a given instance.
Note: Azure normally provides access to vms from a shared load
balancer IP and
mapping of ssh ports on the vms. So by default, the Azure provider
returns strings
of the form 'ip:port'. However, 'stock' elasticlus... |
345,607 | def _order(self, value, is_reverse=None):
def _dict_parser(dict_doc):
result = list()
for key in dict_doc:
data = self._order(dict_doc[key])
res = (data[0], key, data[1])
result.append(res)
return tuple(re... | Parsing data to a sortable form
By giving each data type an ID(int), and assemble with the value
into a sortable tuple. |
345,608 | def get_provider(cls, scm_name: str, conf) -> SourceControl:
for entry_point in pkg_resources.iter_entry_points(,
scm_name):
entry_point.load()
logger.debug(
, entry_point)
logger.debug(,... | Load and return named SCM provider instance.
:param conf: A yabt.config.Config object used to initialize the SCM
provider instance.
:raises KeyError: If no SCM provider with name `scm_name` registered. |
345,609 | def edit_matching_entry(program, arguments):
entry = program.select_entry(*arguments)
entry.context.execute("pass", "edit", entry.name) | Edit the matching entry. |
345,610 | def sign_message(privkey_path, message, passphrase=None):
key = get_rsa_key(privkey_path, passphrase)
log.debug()
if HAS_M2:
md = EVP.MessageDigest()
md.update(salt.utils.stringutils.to_bytes(message))
digest = md.final()
return key.sign(digest)
else:
signer ... | Use Crypto.Signature.PKCS1_v1_5 to sign a message. Returns the signature. |
345,611 | def _changes(cur, dns_proto, dns_servers, ip_proto, ip_addrs, gateway):
changes = {}
cur_dns_proto = (
if in cur
else
)
if cur_dns_proto == :
if isinstance(cur[], list):
cur_dns_servers = cur[]
else:
cur_dns_servers = [cur[]]
if set... | Compares the current interface against the desired configuration and
returns a dictionary describing the changes that need to be made. |
345,612 | def ximshow_rectified(self, slitlet2d_rect):
title = "Slitlet
ax = ximshow(slitlet2d_rect, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
show=False)
xx = np.arange(0, self.bb_nc2_orig - self.bb_nc1_orig + 1,
... | Display rectified image with spectrails and frontiers.
Parameters
----------
slitlet2d_rect : numpy array
Array containing the rectified slitlet image |
345,613 | def makeBdc(self, buses=None, branches=None):
buses = self.connected_buses if buses is None else buses
branches = self.online_branches if branches is None else branches
nb = len(buses)
nl = len(branches)
online = array([br.online for br in branches])
... | The bus real power injections are related to bus voltage angles
by::
P = Bbus * Va + Pbusinj
The real power flows at the from end the lines are related to the bus
voltage angles by::
Pf = Bf * Va + Pfinj
| Pf | | Bff Bft | | Vaf | | Pfinj... |
345,614 | def package(self, login, package_name):
url = % (self.domain, login, package_name)
res = self.session.get(url)
self._check_response(res)
return res.json() | Get information about a specific package
:param login: the login of the package owner
:param package_name: the name of the package |
345,615 | def _reatach(self):
for item, p, idx in self._detached:
if self.treeview.exists(item) and self.treeview.exists(p):
self.treeview.move(item, p, idx)
self._detached = [] | Reinsert the hidden items. |
345,616 | def reverse_cipher(message):
translated =
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
return translated | 反转加密法
:param message: 待加密字符串
:return: 被加密字符串 |
345,617 | def crypto_aead_chacha20poly1305_encrypt(message, aad, nonce, key):
ensure(isinstance(message, bytes), ,
raising=exc.TypeError)
mlen = len(message)
ensure(mlen <= crypto_aead_chacha20poly1305_MESSAGEBYTES_MAX,
.format(
crypto_aead_chacha20poly1305_MESSAGEBYTES_MAX... | Encrypt the given ``message`` using the "legacy" construction
described in draft-agl-tls-chacha20poly1305.
:param message:
:type message: bytes
:param aad:
:type aad: bytes
:param nonce:
:type nonce: bytes
:param key:
:type key: bytes
:return: authenticated ciphertext
:rtype... |
345,618 | def _resolve_dotted_name(dotted_name):
if not isinstance(dotted_name, str):
return dotted_name
if not in dotted_name:
return dotted_name
args = None
params = None
match = P_PARAMS.match(dotted_name)
if match:
dotted_name = match.group()
params = match.grou... | Returns objects from strings
Deals e.g. with 'torch.nn.Softmax(dim=-1)'.
Modified from palladium:
https://github.com/ottogroup/palladium/blob/8a066a9a7690557d9b1b6ed54b7d1a1502ba59e3/palladium/util.py
with added support for instantiated objects. |
345,619 | def read_mac(self):
mac0 = self.read_reg(self.ESP_OTP_MAC0)
mac1 = self.read_reg(self.ESP_OTP_MAC1)
mac3 = self.read_reg(self.ESP_OTP_MAC3)
if (mac3 != 0):
oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff)
elif ((mac1 >> 16) & 0xff) == 0:
... | Read MAC from OTP ROM |
345,620 | def add_blacklisted_filepaths(self, filepaths, remove_from_stored=True):
self.file_manager.add_blacklisted_filepaths(filepaths,
remove_from_stored) | Add `filepaths` to blacklisted filepaths.
If `remove_from_stored` is `True`, any `filepaths` in
internal state will be automatically removed. |
345,621 | def start(self, num_processes: Optional[int] = 1, max_restarts: int = None) -> None:
assert not self._started
self._started = True
if num_processes != 1:
process.fork_processes(num_processes, max_restarts)
sockets = self._pending_sockets
self._pending_sockets... | Starts this server in the `.IOLoop`.
By default, we run the server in this process and do not fork any
additional child process.
If num_processes is ``None`` or <= 0, we detect the number of cores
available on this machine and fork that number of child
processes. If num_process... |
345,622 | def do_extra_polishing(self):
for f in self.EXTRA_POLISH_FUNCTIONS:
if not hasattr(f, ):
if hasattr(f, ) and self.URL in f.polish_urls:
f()
if not hasattr(f, ):
if hasattr(f, ) and self.CURRENT_COMMIT_INDEX in f.polish_commit_... | Goes over each EXTRA_POLISH_FUNCTION to see if it applies to this page, if so, calls it |
345,623 | def sleep(self, seconds=0.05, dt=0.01):
t0 = _t.time()
while _t.time()-t0 < seconds:
_t.sleep(dt)
self.process_events() | 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. |
345,624 | def disconnect(self):
if self._driver:
self._driver.disconnect()
self.axis_homed = {
: False, : False, : False, : False, : False} | Disconnects from the robot. |
345,625 | def extract_coverage(self, container: Container) -> FileLineSet:
uid = container.uid
r = self.__api.post(.format(uid))
if r.status_code == 200:
return FileLineSet.from_dict(r.json())
self.__api.handle_erroneous_response(r) | Extracts a report of the lines that have been executed since the last
time that a coverage report was extracted. |
345,626 | def latex_visit_inheritance_diagram(
self: NodeVisitor, node: inheritance_diagram
) -> None:
inheritance_graph = node["graph"]
graphviz_graph = inheritance_graph.build_graph()
graphviz_graph.attributes["size"] = 6.0
dot_code = format(graphviz_graph, "graphviz")
render_dot_latex(self, node, ... | Builds LaTeX output from an :py:class:`~uqbar.sphinx.inheritance.inheritance_diagram` node. |
345,627 | def subarray_match(shape, ref, sshape, sref=None):
ref1 = asarray(ref, dtype=)
if sref is not None:
ref2 = asarray(sref, dtype=)
else:
ref2 = zeros_like(ref1)
offset = ref1 - ref2
urc1 = minimum(offset + asarray(sshape) - 1, asarray(shape) - 1)
blc1 = maximum(offset, ... | Compute the slice representation of intersection of two arrays.
Given the shapes of two arrays and a reference point ref, compute the
intersection of the two arrays.
It returns a tuple of slices, that can be passed to the two \
images as indexes
:param shape: the shape of the reference array
:... |
345,628 | def main():
docraptor = DocRaptor()
print("Create PDF")
resp = docraptor.create(
{
"document_content": "<h1>python-docraptor</h1><p>Async Test</p>",
"test": True,
"async": True,
}
)
print("Status ID: {status_id}".format(status_id=resp["status... | Generate a PDF using the async method. |
345,629 | def avail_sizes(call=None):
if call == :
raise SaltCloudException(
)
response = _query(, )
ret = {}
for item in response[]:
name = item[]
ret[name] = item
return ret | Return available Linode sizes.
CLI Example:
.. code-block:: bash
salt-cloud --list-sizes my-linode-config
salt-cloud -f avail_sizes my-linode-config |
345,630 | def stdout_redirector():
old_stdout = sys.stdout
sys.stdout = Stream()
try:
yield sys.stdout
finally:
sys.stdout.close()
sys.stdout = old_stdout | Simplify redirect of stdout.
Taken from here: https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/ |
345,631 | def verify_month(self, now):
return self.month == "*" or str(now.month) in self.month.split(" ") | Verify the month |
345,632 | def deserialize_compact(jwt):
parts = jwt.split()
if len(parts) == 3:
token_type = JWS
elif len(parts) == 5:
token_type = JWE
else:
raise Error()
return token_type(*parts) | Deserialization of a compact representation of a :class:`~jwt.JWE`
:param jwt: The serialized JWT to deserialize.
:rtype: :class:`~jose.JWT`.
:raises: :class:`~jose.Error` if the JWT is malformed |
345,633 | def random_dag(nodes, edges):
G = nx.DiGraph()
for i in range(nodes):
G.add_node(i)
while edges > 0:
a = randint(0,nodes-1)
b=a
while b==a:
b = randint(0,nodes-1)
G.add_edge(a,b)
if nx.is_directed_acyclic_graph(G):
edges -= 1
... | Generate a random Directed Acyclic Graph (DAG) with a given number of nodes and edges. |
345,634 | def fetch_exemplars(keyword, outfile, n=50):
list_urls = fetch_lists(keyword, n)
print( % (len(list_urls), keyword))
counts = Counter()
for list_url in list_urls:
counts.update(fetch_list_members(list_url))
outf = io.open(outfile, )
for handle in sorted(counts):
outf.wr... | Fetch top lists matching this keyword, then return Twitter screen
names along with the number of different lists on which each appers.. |
345,635 | def messages(count, size):
import string
letters = islice(cycle(chain(string.lowercase, string.uppercase)), size)
return islice(cycle(.join(l) for l in permutations(letters, size)), count) | Generator for count messages of the provided size |
345,636 | def from_key_bytes(cls, algorithm, key_bytes):
key = serialization.load_der_private_key(data=key_bytes, password=None, backend=default_backend())
return cls(algorithm, key) | Builds a `Signer` from an algorithm suite and a raw signing key.
:param algorithm: Algorithm on which to base signer
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes key_bytes: Raw signing key
:rtype: aws_encryption_sdk.internal.crypto.Signer |
345,637 | def delete_order_line_item_by_id(cls, order_line_item_id, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._delete_order_line_item_by_id_with_http_info(order_line_item_id, **kwargs)
else:
(data) = cls._delete_order_line_item_by_id_with_http_info(order_line_... | Delete OrderLineItem
Delete an instance of OrderLineItem by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_order_line_item_by_id(order_line_item_id, async=True)
>>> result = th... |
345,638 | def covar_rescaling_factor_efficient(C):
n = C.shape[0]
P = sp.eye(n) - sp.ones((n,n))/float(n)
CP = C - C.mean(0)[:, sp.newaxis]
trPCP = sp.sum(P * CP)
r = (n-1) / trPCP
return r | Returns the rescaling factor for the Gower normalizion on covariance matrix C
the rescaled covariance matrix has sample variance of 1 |
345,639 | def read(self):
try:
buf = os.read(self._fd, 2)
except OSError as e:
raise GPIOError(e.errno, "Reading GPIO: " + e.strerror)
try:
os.lseek(self._fd, 0, os.SEEK_SET)
except OSError as e:
raise GPIOError(e.errno, "... | Read the state of the GPIO.
Returns:
bool: ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs. |
345,640 | def blt(f: List[SYM], x: List[SYM]) -> Dict[str, Any]:
J = ca.jacobian(f, x)
nblock, rowperm, colperm, rowblock, colblock, coarserow, coarsecol = J.sparsity().btf()
return {
: J,
: nblock,
: rowperm,
: colperm,
: rowblock,
: colblock,
: coarserow,... | Sort equations by dependence |
345,641 | def maximum_address(self):
maximum_address = self._segments.maximum_address
if maximum_address is not None:
maximum_address //= self.word_size_bytes
return maximum_address | The maximum address of the data, or ``None`` if the file is empty. |
345,642 | def rsync_git(local_path, remote_path, exclude=None, extra_opts=None,
version_file=):
with settings(hide(, ), warn_only=True):
print(green( + run( + .format(
remote_path, version_file)).strip()))
print(green( +
write_version(join(local_path, version_file))))
... | Rsync deploy a git repo. Write and compare version.txt |
345,643 | def _str_datetime_now(self, x=None):
if (x == ):
return(datetime_to_str())
try:
junk = x + 0.0
return datetime_to_str(x)
except TypeError:
return x | Return datetime string for use with time attributes.
Handling depends on input:
'now' - returns datetime for now
number - assume datetime values, generate string
other - no change, return same value |
345,644 | def absl_to_cpp(level):
if not isinstance(level, int):
raise TypeError(.format(type(level)))
if level >= 0:
return 0
else:
return -level | Converts an absl log level to a cpp log level.
Args:
level: int, an absl.logging level.
Raises:
TypeError: Raised when level is not an integer.
Returns:
The corresponding integer level for use in Abseil C++. |
345,645 | def delete(self, cascade=False, delete_shares=False):
if self.id:
self.connection.post(, video_id=self.id,
cascade=cascade, delete_shares=delete_shares)
self.id = None | Deletes the video. |
345,646 | def set_default_viewport(self):
if self.aspect_ratio:
expected_width = int(self.buffer_height * self.aspect_ratio)
expected_height = int(expected_width / self.aspect_ratio)
if expected_width > self.buffer_width:
expected_width = self.buffer_wi... | Calculates the viewport based on the configured aspect ratio.
Will add black borders and center the viewport if the window
do not match the configured viewport.
If aspect ratio is None the viewport will be scaled
to the entire window size regardless of size. |
345,647 | def get_worksheets(self):
url = self.build_url(self._endpoints.get())
response = self.session.get(url)
if not response:
return []
data = response.json()
return [self.worksheet_constructor(parent=self, **{self._cloud_data_key: ws})
for ws i... | Returns a collection of this workbook worksheets |
345,648 | def segment_content_handler():
from ligo.lw.lsctables import (SegmentTable, SegmentDefTable,
SegmentSumTable)
from ligo.lw.ligolw import PartialLIGOLWContentHandler
def _filter(name, attrs):
return reduce(
operator.or_,
[table_.CheckPr... | Build a `~xml.sax.handlers.ContentHandler` to read segment XML tables |
345,649 | def result_fullpath(self, package_index):
ret = os.path.join(self.path, self.result_relpath(package_index))
return ret | Returns the full path of the result
This method returns the full path to the result. This method
simply constructs the path based on the convention and doesn't
check if the result actually exists.
Parameters
----------
package_index :
a package index
... |
345,650 | def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT):
return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format) | Convert unix timestamp to human readable date/time string |
345,651 | def com_google_fonts_check_linegaps(ttFont):
if ttFont["hhea"].lineGap != 0:
yield WARN, Message("hhea", "hhea lineGap is not equal to 0.")
elif ttFont["OS/2"].sTypoLineGap != 0:
yield WARN, Message("OS/2", "OS/2 sTypoLineGap is not equal to 0.")
else:
yield PASS, "OS/2 sTypoLineGap and hhea lineGa... | Checking Vertical Metric Linegaps. |
345,652 | def multi_iter(iterable, count=2):
if not isinstance(
iterable,
(
list, tuple, set,
FutureChainResults,
collections.Sequence, collections.Set, collections.Mapping, collections.MappingView
)):
iterable =... | Return `count` independent, thread-safe iterators for `iterable` |
345,653 | def from_dict(cls, fields, mapping):
iterable = [None] * len(fields)
for key, value in mapping.items():
try:
index = fields.index(key)
except KeyError:
raise ItsdbError( + key)
iterable[index] = value
return cls(fields,... | Create a Record from a dictionary of field mappings.
The *fields* object is used to determine the column indices
of fields in the mapping.
Args:
fields: the Relation schema for the table of this record
mapping: a dictionary or other mapping from field names to
... |
345,654 | def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=False):
ends_with_sep = self.ends_with_path_separator(dir_name)
dir_name = self.absnormpath(dir_name)
if (ends_with_sep and self.is_macos and
self.exists(dir_name, check_link=True) and
not self.exists(d... | Create a leaf Fake directory and create any non-existent
parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directories) with. This argument defaults to 0o777.
The umask i... |
345,655 | def _get_machines_cache_from_dns(self, host, port):
if self.protocol == :
ret = []
for af, _, _, _, sa in self._dns_resolver.resolve(host, port):
host, port = sa[:2]
if af == socket.AF_INET6:
host = .format(host)
... | One host might be resolved into multiple ip addresses. We will make list out of it |
345,656 | def generate_proteins(pepfn, proteins, pepheader, scorecol, minlog,
higherbetter=True, protcol=False):
protein_peptides = {}
if minlog:
higherbetter = False
if not protcol:
protcol = peptabledata.HEADER_MASTERPROTEINS
for psm in reader.generate_tsv_psms(pepfn, ... | Best peptide for each protein in a table |
345,657 | def register_signals(self):
from .receivers import OAIServerUpdater
self.update_function = OAIServerUpdater()
records_signals.before_record_insert.connect(self.update_function,
weak=False)
records_signals.before_recor... | Register signals. |
345,658 | def list_runtime_class(self, **kwargs):
kwargs[] = True
if kwargs.get():
return self.list_runtime_class_with_http_info(**kwargs)
else:
(data) = self.list_runtime_class_with_http_info(**kwargs)
return data | list or watch objects of kind RuntimeClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_runtime_class(async_req=True)
>>> result = thread.get()
:param async_req bool
:param... |
345,659 | def _run_argparser(self, argv):
if self._parser is None:
raise ValueError()
args = self._parser.parse_args(argv)
self.update_args(args.__dict__)
return args | Initialize a link with a set of arguments using an `argparser.ArgumentParser` |
345,660 | def most_recent(self):
if not self.instance:
raise TypeError(
"Can't use most_recent() without a {} instance.".format(
self.model._meta.object_name
)
)
tmp = []
excluded_fields = getattr(self.model, "_history_ex... | Returns the most recent copy of the instance available in the history. |
345,661 | def post_process(self, indices):
array = javabridge.call(self.jobject, "postProcess", "([I)[I", indices)
if array is None:
return None
else:
return javabridge.get_env().get_int_array_elements(array) | Post-processes the evaluator with the selected attribute indices.
:param indices: the attribute indices list to use
:type indices: ndarray
:return: the processed indices
:rtype: ndarray |
345,662 | def read_associations(assoc_fn, anno_type=, **kws):
obj = get_objanno(assoc_fn, anno_type, **kws)
return obj.get_id2gos(**kws) | Return associatinos in id2gos format |
345,663 | def rpc_get_all_names_cumulative( self, offset, count, **con_info ):
if not check_offset(offset):
return {: , : 400}
if not check_count(count, 100):
return {: , : 400}
db = get_db_state(self.working_dir)
all_names = db.get_all_names( offset=offset, coun... | Get all names that have ever existed, paginated
Return {'status': true, 'names': [...]} on success
Return {'error': ...} on error |
345,664 | def word2id(self, xs):
if isinstance(xs, list):
return [self._word2id.get(x, self.UNK) for x in xs]
return self._word2id.get(xs, self.UNK) | Map word(s) to its id(s)
Parameters
----------
xs : str or list
word or a list of words
Returns
-------
int or list
id or a list of ids |
345,665 | def _determine_dialect(self, lines):
permuts = [(quotechar, escapechar)
for quotechar in CSV_QUOTECHARS
for escapechar in CSV_ESCAPECHARS]
for delim in CSV_DELIMITERS:
counts = [line.count(delim) for line in lines]
if min(counts) == 0:
continue
for quotechar, escapechar in permuts:
do... | Expects a non-empty [] of strings; these would normally be the first
few lines of a csv file. Returns the most likely Dialect named tuple or
None if the data seems to form a single column.
Ensures that using the returned dialect, all the lines given will have
the same number of columns.
Helper for the get_d... |
345,666 | def remove_absolute_resample__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
return __run_measure(measures.remove_resample, X, y, model_generator, method_name, 0, num_fcounts, sklearn.metrics.roc_auc_score) | Remove Absolute (resample)
xlabel = "Max fraction of features removed"
ylabel = "1 - ROC AUC"
transform = "one_minus"
sort_order = 15 |
345,667 | def _objective(self, x):
try:
self.optimizer_array = x
obj = self.objective_function()
self._fail_count = 0
except (LinAlgError, ZeroDivisionError, ValueError):
if self._fail_count >= self._allowed_failures:
raise
self.... | The objective function passed to the optimizer. It combines
the likelihood and the priors.
Failures are handled robustly. The algorithm will try several times to
return the objective, and will raise the original exception if
the objective cannot be computed.
:param x: the param... |
345,668 | def parse_mntr(self, buf):
buf.seek(0)
first = buf.readline()
if first == :
return (None, )
metrics = []
mode =
for line in buf:
try:
key, value = line.split()
if key == "zk_server_state":
... | Parse `mntr` command's content.
`buf` is a readable file-like object
Returns: a tuple (metrics, mode)
if mode == 'inactive', metrics will be None |
345,669 | def V(x, requires_grad=False, volatile=False):
return map_over(x, lambda o: V_(o, requires_grad, volatile)) | creates a single or a list of pytorch tensors, depending on input x. |
345,670 | def parse(self, stride=None):
if stride is None:
stride = self.stride
self.corrupted_lineno = []
irow = 0
with utilities.openany(self.real_filename) as xvg:
rows = []
ncol = None
for lineno,line in enumerate(xvg):
... | Read and cache the file as a numpy array.
Store every *stride* line of data; if ``None`` then the class default is used.
The array is returned with column-first indexing, i.e. for a data file with
columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... . |
345,671 | def get_parent(self):
parent_iter = self.model.iter_parent(self.iter)
if parent_iter:
return TreeModelRow(self.model, parent_iter) | Returns the parent :obj:`Gtk.TreeModelRow` or htis row or None |
345,672 | def serialize_dict_keys(d, prefix=""):
keys = []
for k, v in d.iteritems():
fqk = % (prefix, k)
keys.append(fqk)
if isinstance(v, dict):
keys.extend(serialize_dict_keys(v, prefix="%s." % fqk))
return keys | returns all the keys in a dictionary.
>>> serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } })
['a', 'a.b', 'a.b.c', 'a.b.b'] |
345,673 | def get_account_delta(self, address, token_type, block_id, vtxindex):
cur = self.db.cursor()
return namedb_get_account_delta(cur, address, token_type, block_id, vtxindex) | Get two consecutive account states---the one at (block_id, vtxindex), and the one prior. |
345,674 | def get_tree_type(tree):
tree_type = tree.label()
assert tree_type in SUBTREE_TYPES, "tree_type: {}".format(tree_type)
return tree_type | returns the type of the (sub)tree: Root, Nucleus or Satellite
Parameters
----------
tree : nltk.tree.ParentedTree
a tree representing a rhetorical structure (or a part of it) |
345,675 | def makeairplantloop(data, commdct):
anode = "epnode"
endnode = "EndNode"
plantloops = loops.plantloopfields(data, commdct)
splitters = loops.splitterfields(data, commdct)
mixers = loops.mixerfields(data, commdct)
... | make the edges for the airloop and the plantloop |
345,676 | def equivalent_potential_temperature(pressure, temperature, dewpoint):
r
t = temperature.to().magnitude
td = dewpoint.to().magnitude
p = pressure.to().magnitude
e = saturation_vapor_pressure(dewpoint).to().magnitude
r = saturation_mixing_ratio(pressure, dewpoint).magnitude
t_l = 56 + 1. / (... | r"""Calculate equivalent potential temperature.
This calculation must be given an air parcel's pressure, temperature, and dewpoint.
The implementation uses the formula outlined in [Bolton1980]_:
First, the LCL temperature is calculated:
.. math:: T_{L}=\frac{1}{\frac{1}{T_{D}-56}+\frac{ln(T_{K}/T_{D}... |
345,677 | def make_fixture(model_class, **kwargs):
all_fields = get_fields(model_class)
fields_for_random_generation = map(
lambda x: getattr(model_class, x), all_fields
)
overrides = {}
for kwarg, value in kwargs.items():
if kwarg in all_fields:
kwarg_field = getattr(model... | Take the model_klass and generate a fixure for it
Args:
model_class (MongoEngine Document): model for which a fixture
is needed
kwargs (dict): any overrides instead of random values
Returns:
dict for now, other fixture types are not implemented yet |
345,678 | def _api_call(self, path, data={}, http_method=requests.get):
log.info(, path=path)
response = http_method(.join([self.api_url, path]),
params={: self.api_key},
data=data)
log.debug(.format(
response.headers[]))
... | Process an http call against the hipchat api |
345,679 | def get_worker_class(worker_class=None):
RQ = getattr(settings, , {})
if worker_class is None:
worker_class = Worker
if in RQ:
worker_class = RQ.get()
if isinstance(worker_class, six.string_types):
worker_class = import_attribute(worker_class)
return worker_cl... | Return worker class from RQ settings, otherwise return Worker.
If `worker_class` is not None, it is used as an override (can be
python import path as string). |
345,680 | def find_repos(self, depth=10):
repos = []
for root, subdirs, files in walk_dn(self.root, depth=depth):
if in root:
continue
if in subdirs:
repos.append(root)
return repos | Get all git repositories within this environment |
345,681 | def get_parameters(self):
parameters = []
for node in sorted(self.model.nodes()):
cpd = self.estimate_cpd(node)
parameters.append(cpd)
return parameters | Method to estimate the model parameters (CPDs) using Maximum Likelihood Estimation.
Returns
-------
parameters: list
List of TabularCPDs, one for each variable of the model
Examples
--------
>>> import numpy as np
>>> import pandas as pd
>>> ... |
345,682 | def _detect_devices(self) -> None:
devices_num = len(self.devices_list)
if devices_num == 0:
raise DeviceConnectionException(
)
elif not self.device_sn and devices_num > 1:
raise DeviceConnectionException(
f"Multiple devices detect... | Detect whether devices connected. |
345,683 | def get_mask(cls, azim):
if cls.mask is None:
raise ValueError("No mask defined for the station {}".format(cls.name))
azim %= 2 * np.pi
if azim in cls.mask[0, :]:
return cls.mask[1, np.where(azim == cls.mask[0, :])[0][0]]
for next_i, mask_azim in enum... | Linear interpolation between two points of the mask |
345,684 | def get_user_groups(self, dn, group_search_dn=None, _connection=None):
connection = _connection
if not connection:
connection = self._make_connection(
bind_user=self.config.get(),
bind_password=self.config.get()
)
connection.b... | Gets a list of groups a user at dn is a member of
Args:
dn (str): The dn of the user to find memberships for.
_connection (ldap3.Connection): A connection object to use when
searching. If not given, a temporary connection will be
created, and destroyed af... |
345,685 | def transform_lines(self, line_index_iterator, transform_callback):
lines = self.text.split()
for index in line_index_iterator:
try:
lines[index] = transform_callback(lines[index])
except IndexError:
pass
return... | Transforms the text on a range of lines.
When the iterator yield an index not in the range of lines that the
document contains, it skips them silently.
To uppercase some lines::
new_text = transform_lines(range(5,10), lambda text: text.upper())
:param line_index_iterator: ... |
345,686 | def fold(*vals):
vals = [v for v in vals if v is not None]
if not vals:
return None
return min(vals), max(vals) | Initialize a new (min,max) tuple interval from values.
Args:
*vals ([int,...]): A list of values (or Nones)
Returns:
((int,int)): A (min,max) interval tuple or None |
345,687 | def model_stoch_vol(data, samples=2000, progressbar=True):
from pymc3.distributions.timeseries import GaussianRandomWalk
with pm.Model() as model:
nu = pm.Exponential(, 1. / 10, testval=5.)
sigma = pm.Exponential(, 1. / .02, testval=.1)
s = GaussianRandomWalk(, sigma**-2, shape=le... | Run stochastic volatility model.
This model estimates the volatility of a returns series over time.
Returns are assumed to be T-distributed. lambda (width of
T-distributed) is assumed to follow a random-walk.
Parameters
----------
data : pandas.Series
Return series to model.
sample... |
345,688 | def _read(self):
line =
finished = False
while not finished:
char = self._socket.recv(1)
if char == :
return
elif char == :
continue
elif char == :
finished = True
continue
... | Read a single response line from the server. |
345,689 | def range_params(self, ran, kw):
if kw == "length":
if ran[0][0] != "m" and (len(ran) == 1 or ran[0] == ran[1]):
elem = SchemaNode("param").set_attr("name","length")
elem.text = ran[0]
return [elem]
min_ = SchemaNode("param").set_a... | Return list of <param>s corresponding to range `ran`.
`kw` is the statement keyword determining the type of the
range, i.e. 'range' or 'length'. `ran` is the internal
representation of a range as constructed by the `get_ranges`
method. |
345,690 | def _validate_optional_key(key, missing, value, validated, optional):
try:
validated[key] = optional[key](value)
except NotValid as ex:
return [ % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return [] | Validate an optional key. |
345,691 | def _validate_noneof(self, definitions, field, value):
valids, _errors = \
self.__validate_logical(, definitions, field, value)
if valids > 0:
self._error(field, errors.NONEOF, _errors,
valids, len(definitions)) | {'type': 'list', 'logical': 'noneof'} |
345,692 | def read_piezo_tensor(self):
header_pattern = r"PIEZOELECTRIC TENSOR for field in x, y, " \
r"z\s+\(C/m\^2\)\s+([X-Z][X-Z]\s+)+\-+"
row_pattern = r"[x-z]\s+" + r"\s+".join([r"(\-*[\.\d]+)"] * 6)
footer_pattern = r"BORN EFFECTIVE"
pt_table = self.read_ta... | Parse the piezo tensor data |
345,693 | def merge(self, x=None, y=None, ildj=None, kwargs=None, mapping=None):
if mapping is None:
mapping = _Mapping(x=x, y=y, ildj=ildj, kwargs=kwargs)
elif any(arg is not None for arg in [x, y, ildj, kwargs]):
raise ValueError("Cannot simultaneously specify mapping and individual "
... | Returns new _Mapping with args merged with self.
Args:
x: `Tensor` or None. Input to forward; output of inverse.
y: `Tensor` or None. Input to inverse; output of forward.
ildj: `Tensor`. This is the (un-reduce_sum'ed) inverse log det jacobian.
kwargs: Python dictionary. Extra args supplied ... |
345,694 | def _get_variable_name_or_register(var, variables, names, params, prefix):
if var not in variables.values():
vname = prefix
if var.data in params:
vname = params[var.data]
elif var in names:
vname = names[var]
vname = _get_unique_variable_name(vname, vari... | Args:
var (~nnabla.Variable)
variables (OrderedDict)
names (dict): Force name table, Variable -> str
params (dict): NdArray -> str
prefix(str) |
345,695 | def init_config(self, app):
for k in dir(config):
if k.startswith():
app.config.setdefault(k, getattr(config, k))
host_setting = app.config[]
if not host_setting or host_setting == :
app.logger.warning(.format(
host_setting)) | Initialize configuration. |
345,696 | def add_email(self,
email_path,
source,
reference,
method=,
upload_type=,
campaign=,
confidence=,
description=,
bucket_list=[],
password=):
... | Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining th... |
345,697 | def get_traffic_items(self):
traffic = self.get_child_static()
return {o.obj_name(): o for o in traffic.get_objects_or_children_by_type()} | :return: dictionary {name: object} of all traffic items. |
345,698 | def to_dict(self, properties=None):
if not properties:
properties = [p for p in dir(Assay) if isinstance(getattr(Assay, p), property)]
return {p: getattr(self, p) for p in properties} | Return a dictionary containing Assay data.
If the properties parameter is not specified, everything is included.
:param properties: (optional) A list of the desired properties. |
345,699 | def dlogpdf_dlink(self, inv_link_f, y, Y_metadata=None):
e = y - inv_link_f
grad = ((self.v + 1) * e) / (self.v * self.sigma2 + (e**2))
return grad | Gradient of the log likelihood function at y, given link(f) w.r.t link(f)
.. math::
\\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{d\\lambda(f)} = \\frac{(v+1)(y_{i}-\lambda(f_{i}))}{(y_{i}-\lambda(f_{i}))^{2} + \\sigma^{2}v}
:param inv_link_f: latent variables (f)
:type inv_link_f: Nx1 ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.