content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_targets(target):
"""
Parse provided targets
:param target: Targets
:return: List of IP addresses
"""
if '-' in target:
ip_range = target.split('-')
try:
t = IPRange(ip_range[0], ip_range[1])
except AddrFormatError:
try:
st... | 5,313,700 |
def lgam(x):
"""Natural log of the gamma fuction: see Cephes docs for details"""
if x < -34:
q = -x
w = lgam(q)
p = floor(q)
if p == q:
raise OverflowError("lgam returned infinity.")
z = q - p
if z > 0.5:
p += 1
z = p - q
... | 5,313,701 |
def matches(G, queue):
"""
If the sequence in 'queue' correspond to a
node in 'G', return the sequence id,
otherwise return False
"""
if not queue:
return False
seq = 0
for a in queue:
try:
seq = G[seq][a]
except KeyError:
return False
... | 5,313,702 |
def get_mu_sigma(prices, returns_model='mean_historical_return', risk_model='ledoit_wolf',
frequency=252, span=500):
"""Get mu (returns) and sigma (asset risk) given a expected returns model and risk model
prices (pd.DataFrame) – adjusted closing prices of the asset,
each row i... | 5,313,703 |
def getPortList(chute):
"""
Get a list of ports to expose in the format expected by create_container.
Uses the port binding dictionary from the chute host_config section.
The keys are expected to be integers or strings in one of the
following formats: "port" or "port/protocol".
Example:
po... | 5,313,704 |
def _apply_kraus_single_qubit(
kraus: Union[Tuple[Any], Sequence[Any]], args: 'ApplyChannelArgs'
) -> np.ndarray:
"""Use slicing to apply single qubit channel. Only for two-level qubits."""
zero_left = linalg.slice_for_qubits_equal_to(args.left_axes, 0)
one_left = linalg.slice_for_qubits_equal_to(args.... | 5,313,705 |
def get_itk_array(path_or_image):
""" Get an image array given a path or itk image.
Parameters
----------
path_or_image : str or itk image
Path pointing to an image file with extension among
*TIFF, JPEG, PNG, BMP, DICOM, GIPL, Bio-Rad, LSM, Nifti (.nii and .nii.gz),
Analyze, SD... | 5,313,706 |
def get_datasets_dbpedia(subset, limit):
"""
Loads dbpedia data from files, split the data into words and generates labels.
Returns split sentences and labels.
"""
datasets = dict()
data = []
target = []
target_int =[]
target_names = []
filename = 'data/dbpedia/'+subset+'.cs... | 5,313,707 |
def track_for_finalization(owner, item, finalizer):
"""Register an object for finalization.
``owner`` is the the object which is responsible for ``item``.
``finalizer`` will be called with ``item`` as its only argument when
``owner`` is destroyed by the garbage collector.
"""
ref = OwnerRef(own... | 5,313,708 |
def cv_read(path):
"""Read an image using opencv.
Args:
path: path to image
Returns:
numpy array containing the RGB image
"""
image = cv2.imread(path)
image = bgr_to_rgb(image)
return image | 5,313,709 |
def check_packages(options):
"""
Checks if all packages that should be installed are installed
First-level: ROS packages that are required for VIKI directly
Second-level: Dependencies of ROS-packages
:return:
"""
print '\033[1;33m# Checking direct VIKI dependencies\033[1;m'
... | 5,313,710 |
def _generate_sqil_samples(
demonstration_iterator: Iterator[types.Transition],
replay_iterator: Iterator[reverb.ReplaySample]
) -> Iterator[reverb.ReplaySample]:
"""Generator which creates the sample iterator for SQIL.
Args:
demonstration_iterator: Iterator of demonstrations.
replay_iterator: Repl... | 5,313,711 |
def get_git_log_raw_output_for_two_commits(commit1, commit2):
"""
Get the git log raw output for a git commit.
:param commit1: the first commit, which occurs earlier than commit2
:param commit2: the second commit, which occurs later than commit1
returns the git command output
"""
if not comm... | 5,313,712 |
def get_info_from_service(service, zconf):
""" Resolve service_info from service. """
service_info = None
try:
service_info = zconf.get_service_info("_googlecast._tcp.local.", service)
if service_info:
_LOGGER.debug(
"get_info_from_service resolved service %s to s... | 5,313,713 |
def evaluate_model(model, X_test, Y_test, category_names):
"""
evaluate the targets' performance on test data in category_names
Input: model: model to be evaluated, X_test: test features, Y_test: test targets,
category_names: print targets.
Output: print accuracy, precision, recall and f1 s... | 5,313,714 |
def recursive_glob(path):
"""Version-agnostic recursive glob.
Implements the Python 3.5+ glob module's recursive glob for Python 2.7+.
Recursive glob emulates the bash shell's globstar feature, which is enabled
with `shopt -s globstar`.
Args:
path: A path that may contain `**` and `*` ("magic").
Retur... | 5,313,715 |
def copy_default_templates(args, next_campaign):
"""Copies the default configuration templates.
Arguments:
- `args`: container with the needed information
- `next_campaign`: destination for the copy operation
"""
default_conf_dir = os.path.join(args.MPS_dir, "templates")
template_files = (... | 5,313,716 |
def _audit_changes(account, auditors, send_report, debug=True):
""" Runs auditors on all items """
try:
for au in auditors:
au.items = au.read_previous_items()
au.audit_objects()
au.save_issues()
if send_report:
report = au.create_report()
... | 5,313,717 |
def test_multiple_declarations(evaluate, memory, input, expected):
"""Test multiple variable declarations."""
instance = evaluate(input, skip_builtins=True)
assert instance.memory == memory(expected) | 5,313,718 |
def _ragged_tile_axis(rt_input, axis, repeats):
"""Tile a dimension of a RaggedTensor to match a ragged shape."""
assert axis > 0 # Outermost dimension may not be ragged.
if not ragged_tensor.is_ragged(rt_input):
rt_input = ragged_conversion_ops.from_tensor(rt_input, ragged_rank=1)
if axis > 1:
retur... | 5,313,719 |
def cc_library(**kwargs):
"""A shim around cc_library that lets us tweak settings for G3 if necessary."""
native.cc_library(**kwargs) | 5,313,720 |
def camelcase_to_snakecase(value: str) -> str:
"""
Convert a string from snake_case to camelCase.
>>> camelcase_to_snakecase('')
''
>>> camelcase_to_snakecase('foo')
'foo'
>>> camelcase_to_snakecase('fooBarBaz')
'foo_bar_baz'
>>> camelcase_to_snakecase('foo_bar_baz')
'foo_bar... | 5,313,721 |
def colorTable():
"""
Returns a table which visualizes all of the named colors.
:return: table which visualizes all of the named colors.
"""
from deephaven.TableTools import emptyTable
return emptyTable(1) \
.updateView("Colors = colorNames()") \
.ungroup() \
... | 5,313,722 |
def not_found(error):
"""Custom error handler for bad requests"""
return jsonify(dict(error = 'Not Found, resource not found')), 404 | 5,313,723 |
def string_distance(str1, str2):
"""
计算两个字符串之间的编辑距离
@author: 仰起脸笑的像满月
@date: 2019/05/15
:param str1:
:param str2:
:return:
"""
m = str1.__len__()
n = str2.__len__()
distance = np.zeros((m + 1, n + 1))
for i in range(0, m + 1):
distance[i, 0] = i
... | 5,313,724 |
def ticks_add(ticks: int, delta: int) -> int:
"""
Offsets ticks value by a given number, which can be either positive or
negative. Given a ticks value, this function allows to calculate ticks
value delta ticks before or after it, following modular-arithmetic
definition of tick values (see ``ticks_ms... | 5,313,725 |
def _batch_loader(iterable, n=1):
"""
데이터를 배치 사이즈만큼 잘라서 보내주는 함수입니다. Py
의 DataLoader와 같은 역할을 합니다
:param iterable: 데이터 list, 혹은 다른 포맷
:param n: 배치 사이즈
:return:
"""
length = len(iterable)
for n_idx in range(0, length, n):
yield iterable[n_idx:min(n_idx + n, length)] | 5,313,726 |
def best_archiver(random, population, archive, args):
"""Archive only the best individual(s).
This function archives the best solutions and removes inferior ones.
If the comparison operators have been overloaded to define Pareto
preference (as in the ``Pareto`` class), then this archiver will form ... | 5,313,727 |
def elections():
"""Download raw election data from the Election Guide API.
Refer to Election Guide API specifications to understand the data structure
and the meaning of specfic fields.
.. note:: This function requires a ``.env`` file in the project root with
the API URL and key. Contact DataKind... | 5,313,728 |
def google_subdomains(name):
"""
This method uses google dorks to get as many subdomains from google as possible
Returns a dictionary with key=str(subdomain), value=GoogleDomainResult object
"""
google_results = {}
results_in_last_iteration = -1
while len(google_results) > results_in_last_... | 5,313,729 |
def contacts_per_person_normal_self_30():
"""
Real Name: b'contacts per person normal self 30'
Original Eqn: b'30'
Units: b'contact/Day'
Limits: (None, None)
Type: constant
b''
"""
return 30 | 5,313,730 |
def _log_signature_report(signature_def_map, excluded_signatures):
"""Log a report of which signatures were produced."""
sig_names_by_method_name = collections.defaultdict(list)
# We'll collect whatever method_names are present, but also we want to make
# sure to output a line for each of the three standard me... | 5,313,731 |
def process_text2phrases(text, clinical_ner_model):
"""
用于从文本中提取Clinical Text Segments
:param text:自由文本
:param clinical_ner_model: Stanza提供的预训练NER模型
:return: List[PhraseItem]
"""
tokenizer = SpanTokenizer()
spliters = getSpliters()
stopwords = getStopWords()
# 将文本处理成正常的小写形式
t... | 5,313,732 |
def get_all(isamAppliance, check_mode=False, force=False):
"""
Receives all services
"""
return isamAppliance.invoke_get("Receiving all Services", module_uri) | 5,313,733 |
def add_interface_config(config: pyramid.config.Configurator, interface_config: Dict[str, Any]) -> None:
"""Add the interface (desktop, mobile, ...) views and routes with only the config."""
add_interface(
config,
interface_config["name"],
interface_config.get("type", INTERFACE_TYPE_NGEO... | 5,313,734 |
def numeric_outlier(feature, keep_rate=0.9545, mode='right', feature_scale=None):
"""feature clip outlier.
Args:
feature: pd.Series, sample feature.
keep_rate: default 0.9545,
method: default 'right', one of ['left', 'right', 'both'], statistical distribution boundary.
feat... | 5,313,735 |
def elk_index(hashDict):
""" Index setup for ELK Stack bulk install """
index_tag_full = {}
index_tag_inner = {}
index_tag_inner['_index'] = "hash-data"
index_tag_inner['_id'] = hashDict['hashvalue']
index_tag_full['index'] = index_tag_inner
return index_tag_full | 5,313,736 |
def extend_instance(obj: object, cls: type) -> None:
"""Apply mixins after object creation"""
base_cls = obj.__class__
base_cls_name = obj.__class__.__name__
obj.__class__ = type(base_cls_name, (cls, base_cls), {}) | 5,313,737 |
def build_2d_gauss_data(mu_1, mu_2, sig_1, sig_2, samples, changes={},
w=50, alpha=0.1, lags=0):
"""Build a bivarite dataset following a Gaussian distribution.
Parameters
----------
mu_1 : float
Mean of x_1.
mu_2 : float
Mean of x_2.
sig_1 : float
... | 5,313,738 |
def parse_between_expression(var_dict, variable, expression_dict):
"""
Takes an integer variable and a string:string expression_dict. The key string is a semicolon-separated expression
denoting the lower and upper bounds of the value it can match, while the value string is a simple arithmetic
expression... | 5,313,739 |
def get_tag(el):
""" :returns: `geographic_msgs/KeyValue`_ message for `<tag>` *el* if any, None otherwise. """
pair = None
key = el.get('k')
if key != None:
pair = KeyValue()
pair.key = key
pair.value = get_required_attribute(el, 'v')
return pair | 5,313,740 |
def json_to_transactions(json_data: Dict[Any, Any]) -> Tuple[Transaction, ...]:
"""
Convert json data to tuple of transaction objects.
Parameters
----------
json_data :
The transactions data where the values are hexadecimals.
Returns
-------
transactions : `Tuple[Transaction, .... | 5,313,741 |
def top_n_images(found_images, limit):
"""Opens up to 'limit' random images from 'found_images'"""
for i in range(0, limit):
res = random.choice(found_images)
# print("FOUND IMAGE: ", res)
found_images.remove(res)
show_img(res.img) | 5,313,742 |
def write_shape_and_dtype_to_ascii(output_fname, shape, dtype):
"""Function creates an ASCII file that serves as metadata about a
memory-mapped ndarray in a way that is readable by the
`read_shape_and_dtype_from_ascii` function.
Parameters
----------
output_fname : string
Name of the ou... | 5,313,743 |
def textureLightingCost(texParam, img, vertexCoord, sh, model, renderObj, w = (1, 1), option = 'tl', constCoef = None):
"""
Energy formulation for fitting texture and spherical harmonic lighting coefficients
"""
if option is 'tl':
texCoef = texParam[:model.numTex]
shCoef = texParam[model... | 5,313,744 |
def find_reaction_by_index(rxn:list,num:int)-> object:
"""
find reactions by chemkin reaction index
:param rxn: (list) rmg reaction list
:param num: (int) chemkin reaction index
:return: rmg reaction
"""
#x1 = []
for react in rxn:
if react.index==num:
#x1.append(react... | 5,313,745 |
def map_contributor(contributor_dict, role_idx=0):
"""Map the DMP's contributor(s) to the record's contributor(s)."""
cid = contributor_dict["contributor_id"]
identifiers = (
{cid["type"]: cid["identifier"]}
if is_identifier_type_allowed(cid["type"], contributor_dict)
else {}
)
... | 5,313,746 |
def timeIntegration(params):
"""
TIMEINTEGRATION : Simulate a network of aLN modules
Return:
rates_exc: N*L array : containing the exc. neuron rates in kHz time series of the N nodes
rates_inh: N*L array : containing the inh. neuron rates in kHz time series of the N nodes
... | 5,313,747 |
def test_mlflow_logger_dirs_creation(tmpdir):
""" Test that the logger creates the folders and files in the right place. """
assert not os.listdir(tmpdir)
logger = MLFlowLogger('test', save_dir=tmpdir)
assert logger.save_dir == tmpdir
assert set(os.listdir(tmpdir)) == {'.trash'}
run_id = logger.... | 5,313,748 |
def string_similarity(s1, s2):
"""
Get a float representation of the difference between 2 strings.
Args:
s1: string
s2: string
Returns: float
"""
return SequenceMatcher(None, s1, s2).ratio() | 5,313,749 |
def pinv(mat: T.FloatTensor) -> T.FloatTensor:
"""
Compute matrix pseudoinverse.
Args:
mat: A square matrix.
Returns:
tensor: The matrix pseudoinverse.
"""
U, s, V = torch.svd(mat)
S = unsqueeze(s.reciprocal(), axis=0)
return multiply(V,S).mm(U.t()) | 5,313,750 |
def get_remappings_full() -> Mapping[str, str]:
"""Get the remappings for xrefs based on the entire xref database."""
return _get_curated_registry()["remappings"]["full"] | 5,313,751 |
def attention(img, att_map):
"""
Inputs:
img -- original image
att_map -- attention map, in this case shape (7,7) or (7,7,1,1) else.
To visualize just imshow new_img
"""
att_map = np.reshape(att_map, [7,7])
att_map = att_map.repeat(32, axis=0).repeat(32, axis=1)
att_map = n... | 5,313,752 |
def _winsorize_wrapper(x, limits):
"""
Wraps scipy winsorize function to drop na's
"""
if hasattr(x, 'dropna'):
if len(x.dropna()) == 0:
return x
x[~np.isnan(x)] = scipy.stats.mstats.winsorize(x[~np.isnan(x)],
l... | 5,313,753 |
def haversine(lon1, lat1, lon2, lat2, unit = 'km'):
"""Calculate the great circle distance between two lat/lons.
Adapted from https://stackoverflow.com/questions/4913349
Parameters
----------
lon1 : :obj:`float` or vector of :obj:`float`
Longitude of 1st point
lat1 : :obj:`float` or ve... | 5,313,754 |
def get_datatype() -> str:
"""Returns a user specified datatype to be used elsewhere.
Returns
-------
desired_datatype: str
User specified datatype from list.
"""
data_func, data_args = get_inquirer("choices")
data_args["choices"] = DATATYPE_NAMES
datatype_call = data_func(**dat... | 5,313,755 |
def stereonet2xyz(lon, lat):
"""
Converts a sequence of longitudes and latitudes from a lower-hemisphere
stereonet into _world_ x,y,z coordinates.
Parameters
----------
lon, lat : array-likes
Sequences of longitudes and latitudes (in radians) from a
lower-hemisphere ste... | 5,313,756 |
def sky_to_cartesian(rdd, degree=True, dtype=None):
"""
Transform distance, RA, Dec into cartesian coordinates.
Parameters
----------
rdd : array of shape (3, N), list of 3 arrays
Right ascension, declination and distance.
degree : default=True
Whether RA, Dec are in degrees (`... | 5,313,757 |
def delete(id):
"""Delete post function"""
data = Post.query.get(id)
db.session.delete(data)
db.session.commit()
flash("Post successfully deleted")
return redirect(url_for(".index2")) | 5,313,758 |
def repeat_n_times(n, fn, *args, **kwargs):
""" Repeat apply fn n times.
Args:
n: n times.
fn: a function or a list of n functions.
*args: additional args. Each arg should either be not a list, or a list
of length n.
**kwargs: additional keyword args. Each arg should... | 5,313,759 |
def get_submissions(request, domain_id=0):
""" Takes a POST containing a tar of all MD5's
and returns a tar of all missing submissions
Heh, this is explicitly against good REST methodology
We leave this inside the django-rest 'Resource' so we can
use their authentication tools
"""
try:... | 5,313,760 |
def generate_unique_str(allow_dashes=True):
"""
Generate unique string using uuid package
Args:
allow_dashes (bool, optional): If true use uuid4() otherwise use hex that will skip dash in names. Defaults to True.
"""
import uuid
if allow_dashes:
unique_str = str(uuid.uuid4())
... | 5,313,761 |
def run_test(test, config, reports_dir='reports'):
"""
Run one test. This creates a Host object, runs the command, and saves the output to a file.
:param test ConfigDict: The ConfigDict object for the test to run
:param config ConfigDict: The top level ConfigDict
:param str reports_dir: The report ... | 5,313,762 |
async def tls(q, where, timeout=None, port=853, source=None, source_port=0,
one_rr_per_rrset=False, ignore_trailing=False, sock=None,
backend=None, ssl_context=None, server_hostname=None):
"""Return the response obtained after sending a query via TLS.
*q*, a ``dns.message.Message``,... | 5,313,763 |
def create_resource():
"""Users resource factory method"""
return wsgi.Resource(Controller()) | 5,313,764 |
def validip(ip, defaultaddr="0.0.0.0", defaultport=8080):
"""
Returns `(ip_address, port)` from string `ip_addr_port`
>>> validip('1.2.3.4')
('1.2.3.4', 8080)
>>> validip('80')
('0.0.0.0', 80)
>>> validip('192.168.0.1:85')
('192.168.0.1', 85)
>>> validip(... | 5,313,765 |
def get_rcs2body(el_deg=37.0, az_deg=0.0, side='left') -> isce3.core.Quaternion:
"""
Get quaternion for conversion from antenna to spacecraft ijk, a forward-
right-down body-fixed system. For details see section 8.1.2 of REE User's
Guide (JPL D-95653).
Parameters
----------
el_deg : float
... | 5,313,766 |
def obtain_parse_wiki_stocks_sp500(url):
"""Download and parse the Wikipedia list of S&P500
constituents using requests and libxml.
Returns a list of tuples for to add to MySQL."""
# Get S&P500 website content
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
data = response.read... | 5,313,767 |
def parseISO(s):
"""Parse ISO8601 (string) date into a floating point seconds since epoch UTC.
The string must be an ISO8601 date of the form
YYYY-MM-DDTHH:MM:SS[.fff...](Z|[+-]dd:dd)
If something doesn't parse, a DateFormatError will be raised.
The return value is floating point seconds si... | 5,313,768 |
def _get_data(url, attempts=5):
""" Downloads data from a given url.
Parameters
----------
url : str
url to fetch data from
attempts : int
number of times to try to download the data in case of failure
Returns
----------
... | 5,313,769 |
def ldns_str2period(*args):
"""LDNS buffer."""
return _ldns.ldns_str2period(*args) | 5,313,770 |
def create_doctor_image_upload_url():
"""Creates url for uploading image for doctor"""
return reverse('doctor:doctor-image-upload') | 5,313,771 |
def reformat_peer_data_csv(csv_file_path, time_step=0.005):
"""Reformat PEER motion records to column-wise, and save to csv.
Typically, PEER data is given in a plane text file, with data
disposed in horizontal consecutive arrays. This function serializes
it in a single column and returns the new data f... | 5,313,772 |
def compute_eval_metrics(labels, predictions, retriever_correct,
reader_correct):
"""Compute eval metrics."""
# []
exact_match = tf.gather(
tf.gather(reader_correct, predictions["block_index"]),
predictions["candidate"])
def _official_exact_match(predicted_answer, reference... | 5,313,773 |
def discretize_model(model):
"""Discretize a `.Model` in-place.
Turns a floating-point `.Model` into a discrete (integer) model
appropriate for Loihi.
Parameters
----------
model : `.Model`
The model to discretize.
"""
v_scale = {}
for block in model.blocks:
v_scal... | 5,313,774 |
def tf_lovasz_grad(gt_sorted):
"""
Code from Maxim Berman's GitHub repo for Lovasz.
Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper
"""
gts = tf.reduce_sum(gt_sorted)
intersection = gts - tf.cumsum(gt_sorted)
union = gts + tf.cumsum(1. - gt_sorted)
... | 5,313,775 |
def phone_setup_4g_for_subscription(log, ad, sub_id):
"""Setup Phone <sub_id> Data to 4G.
Args:
log: log object
ad: android device object
sub_id: subscription id
Returns:
True if success, False if fail.
"""
return phone_setup_data_for_subscription(log, ad, sub_id, G... | 5,313,776 |
def empty(shape, dtype=np.float, order='c', description=None, verbose=None):
"""
Return a new aligned and contiguous array of given shape and type, without
initializing entries.
"""
shape = tointtuple(shape)
dtype = np.dtype(dtype)
if verbose is None:
verbose = config.VERBOSE
r... | 5,313,777 |
def find_occurrences(needle, haystack):
"""find_occurrences."""
for h, s in haystack:
matches = re.findall(needle, s, overlapped=True)
if len(matches):
yield 1
else:
yield 0 | 5,313,778 |
def IDcorner(landmarks):
"""landmarks:检测的人脸5个特征点
"""
corner20 = twopointcor(landmarks[2, :], landmarks[0, :])
corner = np.mean([corner20])
return corner | 5,313,779 |
def train_controller(controller, config):
"""
Adversarial AutoAugment training scheme without image
1. Training TargetNetwork 1 epoch
2. Training Controller 1 step (Diversity)
"""
controller = controller.cuda()
# ori_aug = C.get()["aug"]
dataset = C.get()['test_dataset']
target_path... | 5,313,780 |
def QColorAlpha(*args):
"""Build a QColor with alpha in one call
This function allows to create a `QColor` and set its alpha channel value in a single call.
If one argument is provided and it is a string parsable as hex, it is parsed as `#RRGGBBAA`.
Else, the single argument is passed to QColor and thus alpha is ... | 5,313,781 |
def video_signatures_exist(files, pipeline: PipelineContext):
"""Check if all required signatures do exist."""
return not any(missing_video_signatures(files, pipeline)) | 5,313,782 |
def _run_gn_desc_list_dependencies(build_output_dir: str, target: str,
gn_path: str) -> str:
"""Runs gn desc to list all jars that a target depends on.
This includes direct and indirect dependencies."""
return subprocess_utils.run_command(
[gn_path, 'desc', '--all... | 5,313,783 |
def trainTfidfModel(tsvFile, wordIndex, ngram, dictionary):
""" Train tf-idf model"""
reader = DescriptionReader(tsvFile, wordIndex, ngram)
# construct the dictionary one query at a time
tfidf_model = models.tfidfmodel.TfidfModel( dictionary.doc2bow(d) for d in reader )
return tfidf_model | 5,313,784 |
def IsUnion(sid):
"""
Is a structure a union?
@param sid: structure type ID
@return: 1: yes, this is a union id
0: no
@note: Unions are a special kind of structures
"""
s = idaapi.get_struc(sid)
if not s:
return 0
return s.is_union() | 5,313,785 |
def set_wa_data_directory_temp(path: str):
"""Set wa data directory and yield the result.
For some helper functions, :meth:`~get_wa_data_file` is called implicitly (inside the method itself).
This method will temporarily set the data directory for a short period and return to the
original value.
.... | 5,313,786 |
def test_predict_value_error(random_X_data):
"""Raise ValueError if X doesn't have expected number of variables."""
X = create_random_X(random_X_data)
s = create_s()
lin_acf = counterfactually_fair_models.LinearACFClassifier()
lin_acf.fit(X, create_y(), s)
with pytest.raises(ValueError):
... | 5,313,787 |
def import_atm_mass_info():
"""
Funtion to load dictionary storing atomic mass information by atom type.
dict
dictionary of atomic mass by atom name
"""
massdict = {'H': 1.00797,
'HE': 4.0026,
'LI': 6.941,
'BE': 9.01218,
... | 5,313,788 |
def defaults(group1):
""" Get globals for all model tests. """
values = Defaults()
values.account_attributes = {
'uid': "tux",
'uidNumber': 10,
'givenName': "Tux",
'sn': "Torvalds",
'cn': "Tux Torvalds",
'telephoneNumber': "000",
'mail': "tuz@example.... | 5,313,789 |
def get_move(state: State) -> State:
"""Get next move, check if it's legitimate.
If it's not, record the error or the quit choice.
Otherwise, update the board and determine if
there's a winner or a draw."""
new_move = input(f'Player {state.player}, what is your move? [q to quit]: ')
i... | 5,313,790 |
def _project_im_rois(im_rois, scales):
"""Project image RoIs into the image pyramid built by _get_image_blob.
Arguments:
im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates
scales (list): scale factors as returned by _get_image_blob
Returns:
rois (ndarray): R x 4 ma... | 5,313,791 |
def preprocess_recipe(
adata,
min_expr_level=None,
min_cells=None,
use_hvg=False,
scale=False,
n_top_genes=1500,
pseudo_count=1.0,
):
"""A simple preprocessing recipe for scRNA data
Args:
adata (sc.AnnData): Input annotated data object
min_expr_level (int, optional): ... | 5,313,792 |
async def pympler_tracker_diff(request: web.Request) -> web.StreamResponse:
""" Get Pympler tracker diff: https://pympler.readthedocs.io/en/latest/
Example:
curl -v -X POST 'localhost:9999/pympler/tracker/diff'
curl -v -X POST 'localhost:9999/pympler/tracker/diff?print'
"""
global _tracker
... | 5,313,793 |
def toggle_40g_local(module):
"""
Method to toggle 40g ports to 10g ports.
:param module: The Ansible module to fetch input parameters.
:return: The output messages for assignment.
"""
output = ''
cli = pn_cli(module)
clicopy = cli
cli += ' lldp-show format local-port no-show-headers... | 5,313,794 |
def parse_aa_change(aa_change):
"""Parse an amino acid change to get aa before, position, and aa after
Amino acid changes are a concatenation of amino acid "before"
(or "from", matching reference), followed by codon position, finishing
with the amino acid "after" (or "to", describing the variant).
... | 5,313,795 |
def lazy_index(index):
"""Produces a lazy index
Returns a slice that can be used for indexing an array, if no slice can be
made index is returned as is.
"""
index = asarray(index)
assert index.ndim == 1
if index.dtype.kind == 'b':
index = index.nonzero()[0]
if len(index) == 1:
... | 5,313,796 |
def test_watchdog_success(mocker):
"""Should succeed with valid hosts to monitor."""
process = mocker.patch("subprocess.run")
process.return_value.returncode = 0
probe = WatchdogProbe({"hosts": [("127.0.0.1", "test")]})
probe.run()
assert len(probe.results) == 1
assert len(probe.results["hal... | 5,313,797 |
def _p_rand_generator() -> Generator[int, None, None]:
"""Returns a value from _RNG_TABLE. Use the resultant generator for anything involving map objects and weaponry."""
_p_index = -1
while True:
_p_index += 1
yield _RNG_TABLE[_p_index % 255] | 5,313,798 |
def extreme_contrast(image: Image) -> Image:
"""
T081 Matthew Gray
Returns a copy of the image that has extreme contast, the RGB values for
each pixel are either 255 or 0.
>>> file = load_image(choose_file())
>>> red_image = red_filter(file)
>>> show(red_image)
"""
... | 5,313,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.