content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def superior():
"""a fixture for lake superior"""
superior = LakeFactory(lake_name="Lake Superior", abbrev="SU")
return superior | db21ff1ffbaf6be91dd8f0907083ee87bc4541de | 30,100 |
def hsv_mask(img, hue_mask, sat_mask, val_mask):
"""
Returns a binary image based on the mask thresholds
:param img: The image to mask
:param hue_mask: Tuple of (hue_min, hue_max)
:param sat_mask: Tuple of (sat_min, sat_max)
:param val_mask: Tuple of (val_min, val_max)
:return: Binary image ... | 194cb97b42850244b601653551d359b2c42caacd | 30,101 |
def convert_parameter_dict_to_presamples(parameters):
"""Convert a dictionary of named parameters to the form needed for ``parameter_presamples``.
``parameters`` should be a dictionary with names (as strings) as keys and Numpy arrays as values. All Numpy arrays should have the same shape.
Returns (numpy s... | f136c9c795ab4c7023e774866c061b19488cc81f | 30,102 |
def convert_to_rle(annotation, width, height):
"""Convert complex polygons to COCO RLE format.
Arguments:
annotation: a dictionary for an individual annotation in Darwin's format
Returns: an annotation in encrypted RLE format and a bounding box
@author Dinis Gokaydin <d.gokaydin@nationaldrones.... | a9562e95817585798164a91ef793841143329dd7 | 30,103 |
import socket
def getfqdn(name=None):
"""return (a) local IPv4 or v6 FQDN (Fully Qualified Domain Name)
if name is not given, returns local hostname
may raise socket.gaierror"""
return _getfqdn(socket.AF_UNSPEC, name) | cbebf1e3deda3a095996034b559af8f2ae4692c3 | 30,104 |
def create_answer_dict(elem, restrict_elem=None, checkbox=False):
"""
Construct dict with choices to fulfil form's div attribute
:param elem: ElemntTree element
:param restrict_elem: name of element which is not included in choice text
:param checkbox: boolean flag to work return data for checkbox ... | c87d5d22b3f779f4645263ae18febaa95984d614 | 30,105 |
def fasta(file_allname: str):
"""
需要传入file_allname的路径
:param file_allname:
:return: 返回fasta格式的序列list
"""
try:
# file_allname = input("输入你要分析出的文件,包括后缀名\n")
f = open(file_allname).read()
fasts = f.split(">")
fast_seq = []
index = 0
for fast in fasts:... | bbd03531a7d311c322fdbd66e401788fb6526120 | 30,106 |
def ask_version(version):
""" interact with user to determine what to do"""
upgrades = get_upgrades()
latest = get_latest(version, upgrades)
answer = False
if latest > version:
msg = "a new version (%s) is available. You have %s. Upgrade?" % (latest, version)
answer = True if raw_inp... | 1e6c7c87eeb4e222efd2b952e9d23b7c95275f85 | 30,107 |
def format_size(size):
"""
:param float size:
:rtype: str
"""
size = float(size)
unit = 'TB'
for current_unit in ['bytes', 'KB', 'MB', 'GB']:
if size < 1024:
unit = current_unit
break
size /= 1024
return '{0:.2f}'.format(size).rstrip('0').rstrip('... | 95470360fcc34df5a51a7cf354138413b41940aa | 30,108 |
def make_full_block_header_list(block_header):
"""Order all block header fields into a list."""
return make_short_block_header_list(block_header) + [
block_header.timestamp,
block_header.extraData,
] | 59bcfdd3cefd3a1b7a8dcaf063964eb27dbafd67 | 30,109 |
from typing import Union
import os
def path_constructor(
loader: Union[Loader, FullLoader, UnsafeLoader], node: Node
) -> PathLike:
"""
Extract the matched value, expand env variable, and replace the match.
:param loader: not used
:param node: YAML node
:return: path
:raises SyntaxError: ... | bd528fe8b5decdba57781fef47a5774fc8eceafb | 30,110 |
def rc_seq(seq=""):
"""Returns the reverse compliment sequence."""
rc_nt_ls = []
rc_dict = {
"a": "t",
"c": "g",
"t": "a",
"g": "c",
"n": "n",
"A": "T",
"C": "G",
"T": "A",
"G": "C",
"N": "N"
}
rc_nt_ls = [rc_dict[seq[i]... | 827877a76d4ffbe61e40e4f00641afa4277f3ff5 | 30,111 |
def descriptions(path, values):
"""Transform descriptions."""
if not values:
return
root = E.descriptions()
for value in values:
elem = E.description(
value['description'], descriptionType=value['descriptionType']
)
set_non_empty_attr(elem, '{xml}lang', value... | 34d570f0c2a97616833af5432ed5607413e2af9a | 30,112 |
from typing import Mapping
from typing import Union
from typing import Sequence
from typing import Optional
from typing import Any
def build_default_region_dataset(
metrics: Mapping[FieldName, Union[Sequence[float], TimeseriesLiteral]],
*,
region=DEFAULT_REGION,
start_date="2020-04-01",
static: Op... | 4c50876817b80ae412a193ba078b7948b7603322 | 30,113 |
import requests
import unicodedata
import time
def process(entries):
"""
Look for Science Direct (SCOPUS) database to update the bibliography entries.
This update evaluates only '@ARTICLE' entry types.
:param entries: list of bibtex entries
:return:
"""
log.info("Seeking for Science Direct... | 8db324dcea38d65a09132fb35a7114891534c7ca | 30,114 |
def load_espnet_model(model_path):
"""Load an end-to-end model from ESPnet.
:param model_path: Path to the model.
:type model_path: str
:return: The model itself, mapping from subword to index,
and training arguments used.
:rtype: (torch.nn.Module, dict, dict)
"""
model, train_... | d9f001a64465547cf27c6d600939e57e9b8f1a19 | 30,115 |
from typing import Iterator
from typing import Union
from typing import Match
def full_match(nfa: NFA, text: Iterator[str]) -> Union[Match, None]:
"""
:param nfa: a NFA
:param text: a text to match against
:return: match or ``None``
"""
text_it = _peek(text, sof='', eof='')
curr_states_s... | 9cbb30633f648405e193f61f46b5e2dd80fffde0 | 30,116 |
def smiles_tokenizer(line, atoms=None):
"""
Tokenizes SMILES string atom-wise using regular expressions. While this
method is fast, it may lead to some mistakes: Sn may be considered as Tin
or as Sulfur with Nitrogen in aromatic cycle. Because of this, you should
specify a set of two-letter atoms ex... | c31916558fdbeda345a0667b43364f8bff504840 | 30,117 |
from typing import Set
def merge_parameter_sets(first: Set[ParameterDefinition], second: Set[ParameterDefinition]) -> Set[ParameterDefinition]:
"""
Given two sets of parameter definitions, coming from different dependencies for example, merge them into a single set
"""
result: Set[ParameterDefinition]... | 4b60ae17eb6e8b1ccd5149517c9d0ae809c33411 | 30,118 |
import time
import sys
def pca(data, submeans=0, keep=-1, flip=1, sparse=0):
"""Auto-selecting PCA, with data in columns.
The 'data' matrix should be ndims X npts.
If npts > ndims, then does a PCA directly.
If ndims > npts, then does PCA on transpose, and does appropriate normalization.
Returns (e... | 8af0fe69351cf5a580936555ba5e289155d648c1 | 30,119 |
import struct
def build_udp_header(src_port, dst_port, length):
"""Builds a valid UDP header and returns it
Parameters:
- src_port: A uint16 which will be used as source port for the UDP
header
- dst_port: A uint16 which will be used as destination port for the
... | d110c19ff38f88bc892ecb52c8203e356a930bab | 30,120 |
def plot_confus_mat(y_true, y_pred, classes_on=None,
normalize='true',
linewidths=0.02, linecolor='grey',
figsize: tuple = (4, 3),
ax=None, fp=None,
**kwargs):
""" by default, normalized by row (true classes)
"""... | 59ef04547b4829d7c3c1049c93fab69faaa3b23d | 30,121 |
from typing import Any
import os
def set_config_option(section: str, option: str, value: Any, write_to_disk: bool = False) -> bool:
"""
Function which updates configuration option value.
By default if "write_to_disk" is False, value will only be updated in memory and not on disk.
This means it won't... | 32cb66f2fbaa983f38e010f99c485fa35237f96e | 30,122 |
async def home():
"""
Home endpoint to redirect to docs.
"""
return RedirectResponse("/docs") | 1ebece9db1a86f54ec101037279087065aaa2f0a | 30,123 |
def robust_hist(x, ax=None, **kwargs):
"""
Wrapper function to `plt.hist` dropping values that are not finite
Returns:
Axes
"""
mask = np.isfinite(x)
ax = ax or plt.gca()
ax.hist(x[mask], **kwargs)
return ax | 32165e3e5cb796fe941bc0f177606dbc502c61ef | 30,124 |
import os
import re
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = open(os.path.join(package, "__init__.py")).read()
return re.search(
r"^__version__ = ['\"]([^'\"]+)['\"]",
init_py,
re.MULTILINE,
).group(1) | d62d9cc95955c1979a6ef7f612789028aaa3bffc | 30,125 |
def base36encode(number, alphabet='0123456789abcdefghijklmnopqrstuvxxyz'):
"""Convert positive integer to a base36 string."""
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
# Special case for zero
if number == 0:
return alphabet[0]
base36 = ''
... | d670a047d210f1d452d2acde76dc47208be2f4bf | 30,126 |
def pipe(*args, **kwargs):
"""A source that builds a url.
Args:
item (dict): The entry to process
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. Must contain the key 'base'. May
contain the keys 'params' or 'path'... | a9fca4149bca2ee50ffe5efcbb67c3066523cdf8 | 30,127 |
import six
def get_rotation(rotation):
"""
Return the text angle as float. The returned
angle is between 0 and 360 deg.
*rotation* may be 'horizontal', 'vertical', or a numeric value in degrees.
"""
try:
angle = float(rotation)
except (ValueError, TypeError):
isString = is... | 7ed0fd31f9a90ddb5743faa8e45e46f0d5cc08bd | 30,128 |
def checkWrite(request):
"""Check write"""
try:
_path = request.query_params.get("path")
_file = open(_path + "test.txt", "w")
_file.write("engine write test")
_file.close()
return HttpResponse(_path + "test.txt")
except ValueError as e:
return genericApiExce... | c3d196126c67cc9b8ba5482a4ebb7df778cd1d5e | 30,129 |
def most_seen_creators(event_kind=None, num=10):
"""
Returns a QuerySet of the Creators that are associated with the most Events.
"""
return Creator.objects.by_events(kind=event_kind)[:num] | 60d4865b56ea2d2ede8cad5123fbaa3f49e72bcd | 30,130 |
from .extract.utils import _get_dataset_dir
from datetime import datetime
import os
def use_memmap(logger, n_files=1):
"""Memory-map array to a file, and perform cleanup after.
.. versionadded:: 0.0.8
Parameters
----------
logger : :obj:`logging.Logger`
A Logger with which to log informa... | 0e55a521386af49b95e6be49d32235422461b80d | 30,131 |
import argparse
def _create_parser():
"""
@rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser()
parser.add_argument("tasks", help="perform specified task and all its dependencies",
metavar="task", nargs = '*')
parser.add_argument('-l', '--list-tasks', h... | af9f5087546ea5a16d8f55d9b6231419d623c1e8 | 30,132 |
def read_lexicon():
"""
Returns the dict of {'word': string, 'score': int} represented by lexicon.txt
"""
return read_dict('resources/lexicon.txt') | 69cdf729aabfd42d4e02690cabcd91b1162598aa | 30,133 |
from tpDcc.libs.python import path
import os
def get_usd_qt_path():
"""
Returns path where USD Qt files are located
:return: str
"""
platform_dir = get_platform_path()
if not platform_dir or not os.path.isdir(platform_dir):
LOGGER.warning('No USD platform directory found: "{}"'.forma... | de5d01401807f6558f0c98a4524b98e8d985776f | 30,134 |
import tqdm
def show_erps(Ds, align_window, labels=None, show_sem=True, co_data=None,
**kwargs):
"""
Use plot ERPs on electrode_grid
Parameters
----------
Ds: list
list of D tensors (electrodes x time x trials)
align_window: tuple
time before and after stim in se... | 988a89af259387796e3735ce9526304591c09131 | 30,135 |
def insert_with_key_enumeration(agent, agent_data: list, results: dict):
"""
Checks if agent with the same name has stored data already in the given dict and enumerates in that case
:param agent: agent that produced data
:param agent_data: simulated data
:param results: dict to store data into
:... | d2d653dcff20836c4eaf8cf55b31b1a1209a4ddd | 30,136 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='First Bank of Change',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('value', metavar='int', type=int, help='Sum')
args = parser.parse_args()... | 117ae5596c95154ac0dc10fd9b1793d89d471da8 | 30,137 |
def parse_condition_code(value, is_day: bool) -> str:
"""Convert WeatherAPI condition code to standard weather condition."""
if value is None:
return None
try:
condition_code = int(value)
if condition_code == 1000:
return ATTR_CONDITION_SUNNY if is_day else ATTR_CONDITI... | cd650a27b907f6d0ced7c05bd8aec5a316bf3b42 | 30,138 |
def min__to__s():
"""Convert minute to second"""
return '6.0E+1{kind}*{var}' | 2730af2cc79a6c4af6d1b18f79326623c0fd0289 | 30,139 |
import html
def home():
"""Home tab."""
icon = html.I(className="fas fa-home fa-lg", title="Home")
return html.Li(html.Span(icon), id="view-info", className="active") | f1771b014b3d0332965b4bb0d74038dfddda8c21 | 30,140 |
def score_per_term(base_t, mis_t, special_t, metric):
"""Computes three distinct similarity scores for each list of terms.
Parameters
----------
base_t, mismatch_t special_t: list of str
Lists of toponym terms identified as base, mismatch or frequent (special) respectively.
metric: str
... | 55e5b9b0d9feaa359ab0907b399eb37514dcfacd | 30,141 |
import bisect
def _eliminationOrder_OLD(gm, orderMethod=None, nExtra=-1, cutoff=inf, priority=None, target=None):
"""Find an elimination order for a graphical model
Args:
gm (GraphModel): A graphical model object
method (str): Heuristic method; one of {'minfill','wtminfill','minwidth','wtminwidth','random... | dfe770db099dc65bcba1afb8c2706005dd7bb81d | 30,142 |
import sys
def inject_module(module, *args, **kwargs):
"""
Imports a function from a python module :module: and executes it with *args, **kwargs arguments. Dotted referencing
can be used to specify the function from the module.
For example, the following code will execute func1 and func2 from module ... | 68c9044501a8418f6200aba4fa2ee076dce15d59 | 30,143 |
import torch
def get_pretrain_data_loader(mode, pretrain_data_setting):
"""Get pre-training loader.
Args:
mode (str): either "train" or "valid".
pretrain_data_setting (dict, optional): pretrain dataset setting.
Returns:
loader (torch.dataloader): a PyTorch dataloader with all input
d... | dc894eb5fb41cf49910568d01a749ebc93aded6d | 30,144 |
def do_simple_math(number1, number2, operator):
"""
Does simple math between two numbers and an operator
:param number1: The first number
:param number2: The second number
:param operator: The operator (string)
:return: Float
"""
ans = 0
if operator is "*":
ans = number1 * nu... | eb745f9c3f3c1e18de30cbe6c564d68c29e39ff4 | 30,145 |
def test_global_settings_data():
"""Ensure that GlobalSettingsData objects are properly initialized
per-thread"""
def check_initialized(index):
if index == 0:
sleep(0.1)
with pytest.raises(AttributeError):
_global_settings_data.testing_index # pylint: disable=W0104
... | bd1229bb9150b25c88be621d5af0f8da9cf7327d | 30,146 |
def set_client(client):
"""
Set the global HTTP client for sdk.
Returns previous client.
"""
global _global_client
previous = _global_client
_global_client = client
return previous | 9f29f5491cee42581fb2b0a22edd36a2297754b4 | 30,147 |
def readNetAddress(b, hasStamp):
"""
Reads an encoded NetAddress from b depending on the protocol version and
whether or not the timestamp is included per hasStamp. Some messages like
version do not include the timestamp.
Args:
b (ByteArray): The encoded NetAddress.
hasStamp (bool)... | 7d523c0465039008e0015c075e8282a1aacea000 | 30,148 |
def get_all_clouds(session, return_type=None, **kwargs):
"""
Retrieves details for all available storage clouds.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object.
:type return_type: str
:param return_type: If this is set to the string 'json', this... | 61029884408733398d8e2c3bb52c18ef4e9f83fc | 30,149 |
def _get_account_balances_by_regid(user_regid):
"""
returns uw_sws.models.Finance object for a given regid
"""
if user_regid is None:
return None
return get_account_balances_by_regid(user_regid) | 6c81ca23411a415d3551d856a44c44f6377ec1b9 | 30,150 |
def scrape_meaning(word):
"""
Method to scrape the meaning of a word from google search
"""
# TODO: Add validation checks on the word passed
raw_html_response = fetch_content_from_web(word)
response = parse_html_content(raw_html_response)
return response | fa9bc34d4052e5d5b0362dfa00ac99d61e3e894a | 30,151 |
import os
def libname(name):
"""gets 'name' and returns something like libname.cpython-37m-darwin.so"""
filename = build_ext_cmd.get_ext_filename(name)
fn, ext = os.path.splitext(filename)
return build_ext_cmd.shlib_compiler.library_filename(fn, libtype) | 853aa244d06be4661a7d4a87c7e669286bb38e65 | 30,152 |
def make_embed(msg_type='', title=None, icon=None, content=None,
msg_colour=None, guild=None, title_url=None,
thumbnail='', image='', fields=None, footer=None,
footer_icon=None, inline=False):
"""Returns a formatted discord embed object.
Define either a type or a co... | 5cdeb5862ffc525160361f760b5530e15d3258c1 | 30,153 |
import torch
def dynamic_stitch(indices, data):
"""
Args
indices: A list of at least 1 Tensor objects with type int32.
data: A list with the same length as indices of Tensor objects with
the same type.
Returns
A Tensor. Has the same type as data.
"""
dim_0 = in... | 6988b400ca1110187643eba932f00103f5f393b6 | 30,154 |
def snake(string):
"""snake_case"""
return "_".join(string.split()) | 6bf99dede918937ad59ec9be14ffade8fadb5794 | 30,155 |
def parse_standard_metadata():
"""
Gather the standard metadata information from Jenkins and the DBMS.
Returns
-------
The metadata obtained from Jenkins and the DBMS.
Warnings
--------
Underlying implementation is hacky right now.
"""
return {**_parse_jenkins_env_vars(), **_pa... | 535bc56eabbdc2d178b448951127adf37af217eb | 30,156 |
import jinja2
import json
def load_resource(api_server):
"""Load a default resource file.
:type api_server: str
:rtype: dict
"""
logger.debug('load_resource({0})...'.format(api_server))
rsrcs = {}
rsrc_files = [
"resources/misc.json.j2",
"resources/api_clients.json.j2",
... | 54ceee11114eae56c4a1e663a23c18ac3ef86cda | 30,157 |
def match_all_args(ctx, node, func, args):
"""Call match_args multiple times to find all type errors.
Args:
ctx: The abstract context.
node: The current CFG node.
func: An abstract function
args: An Args object to match against func
Returns:
A tuple of (new_args, errors)
where new_args... | 88bd473876dd3a286c02330023555dab211336df | 30,158 |
import torch
def samples_from_cpprb(npsamples, device=None):
"""
Convert samples generated by cpprb.ReplayBuffer.sample() into
State, Action, rewards, State.
Return Samples object.
Args:
npsamples (dict of nparrays):
Samples generated by cpprb.ReplayBuffer.sample()
devi... | 6775f0eee7544f35e04e6e6fd3096516411dc0e8 | 30,159 |
def generateKeys():
"""
generates and returns a dictionary containing the original columns names from the
LIDAR file as values and the currently used column names as corresponding keys
ws_1 : Speed Value.1
dir_1 : Direction Value.1
h_1 : Node RT01 Lidar Height
"""
keys = {"ws_0" :... | 9d0d55c3fdc32ddda46da4a9e876d4ce1ecde25d | 30,160 |
def process_line(line):
"""Return the syntax error points of line."""
stack = []
for c in line:
if c in '([{<':
stack.append(c)
elif c != closings[stack.pop()]:
return points[c]
return 0 | 4ab64c74d89f950cc6c87b7a91addeb29717d74a | 30,161 |
def get_uniprot_homologs(rev=False):
"""As above, but exclusively uniprot => mouse uniprot"""
homologs = {}
with open('data/corum_mouse_homologs.txt') as infile:
data = [line.strip().split('\t') for line in infile]
for line in data:
original = line[1].split('|')[1]
uniprot = line... | 969085375265b90b5501b4b86eaaed3e1c48795f | 30,162 |
import typing
def flatten(
value: list,
levels: typing.Optional[int] = None
) -> list:
"""Flatten a list.
.. code-block:: yaml
- vars:
new_list: "{{ [1, 2, [3, [4, 5, [6]], 7]] | flatten }}"
# -> [1, 2, 3, 4, 5, 6, 7]
To flatten only the top level, use the ``leve... | 569ccb15f140a517792bc6b5ea962537db0b31f8 | 30,163 |
def GetStage(messages):
"""Returns corresponding GoogleCloudFunctionsV2(alpha|beta)Stage."""
if messages is apis.GetMessagesModule(_API_NAME, _V2_ALPHA):
return messages.GoogleCloudFunctionsV2alphaStage
elif messages is apis.GetMessagesModule(_API_NAME, _V2_BETA):
return messages.GoogleCloudFunctionsV2bet... | 3bdb130cf78694b223bd555f6db20e1c687b5552 | 30,164 |
def get_general_case_info(adapter, institute_id=None, slice_query=None):
"""Return general information about cases
Args:
adapter(adapter.MongoAdapter)
institute_id(str)
slice_query(str): Query to filter cases to obtain statistics for.
Returns:
general(dict)
"""
g... | a5afc2244db59f7a3dd0da55dd4759a57af641a4 | 30,165 |
def _normalize_ids(arg, atoms={int, long, str, unicode, NewId}):
""" Normalizes the ids argument for ``browse`` (v7 and v8) to a tuple.
Various implementations were tested on the corpus of all browse() calls
performed during a full crawler run (after having installed all website_*
modules) and this one... | 1a7b930896a046357474000b8ebc598f70fbba76 | 30,166 |
def is_intersection(g, n):
"""
Determine if a node is an intersection
graph: 1 -->-- 2 -->-- 3
>>> is_intersection(g, 2)
False
graph:
1 -- 2 -- 3
|
4
>>> is_intersection(g, 2)
True
Parameters
----------
g : networkx DiGraph
n : node id
R... | 415e5154095cd78112ef029b6c4d62c36da0b3b8 | 30,167 |
def AxisRotation(p, ang, inplace=False, deg=True, axis='z'):
""" Rotates points p angle ang (in deg) about an axis """
axis = axis.lower()
# Copy original array to if not inplace
if not inplace:
p = p.copy()
# Convert angle to radians
if deg:
ang *= np.pi / 180
if axis == ... | 1df385b98edb69134849cb052380fb99261f96b2 | 30,168 |
from pathlib import Path
from typing import List
def get_dir_list(path: Path)->List[str]:
"""
Return directory list
"""
dir_list = []
paths = Path(path).glob("**/*")
for p in paths:
if p.is_dir():
dir_list.append(str(p))
return dir_list | a0fe0659ad0175364048be6ef96026584fa6f3ef | 30,169 |
import typing
def tokenize(data: typing.Union[str, typing.Sequence[str]]) -> list[str]:
"""break up string into tokens, tokens can be separated by commas or spaces
creates separate tokens for:
- "(" or "[" at beginning
- ")" or "]" at end
"""
# break into tokens
if isinstance(data, str):... | 832343067c8777aa386c0c87c2c4e8202a7cb88f | 30,170 |
def de_comma(string):
"""Remove any trailing commas
>>> de_comma(',fred,,') == ',fred'
True
"""
return string.rstrip(',') | 453d615c1fbbef5139d05d6e4510731c969d6a86 | 30,171 |
def MakeData(ea, flags, size, tid):
"""
Create a data item at the specified address
@param ea: linear address
@param flags: FF_BYTE..FF_PACKREAL
@param size: size of item in bytes
@param tid: for FF_STRU the structure id
@return: 1-ok, 0-failure
"""
return idaapi.do_data_ex(ea, fla... | ab890848784407bf0ee2864469a5c8874346c5ec | 30,172 |
def get_node_network_receive(cluster_id, ip, start, end, bk_biz_id=None):
"""获取网络数据
start, end单位为毫秒,和数据平台保持一致
数据单位KB/s
"""
step = (end - start) // 60
prom_query = f"""
max(rate(node_network_receive_bytes_total{{cluster_id="{cluster_id}",job="node-exporter", instance=~"{ ip }:9100"}}[5m])... | 9ba68d19c6ca959fd92020f50498d4aa14dfeb58 | 30,173 |
def verify_vrrpv3_summary(dut,**kwargs):
"""
Author: Raghukumar Rampur
email : raghukumar.thimmareddy@broadcom.com
:param dut:
:param interface:
:type string or list
:param vrid:
:type string or list
:param vip:
:type virtual-ip in string or list
:param state:
:type vrrp ... | b5d9ae54fc316cadfd8c4d067439b19ecac4c371 | 30,174 |
def attributes_restore(node):
"""Restore previously unlocked attributes to their default state.
Args:
node (str): Node to restore attributes
Returns:
bool: False if attribute doesn't exists else True
"""
attr_name = "attributes_state"
base_attr = "{}.{}".format(node, attr_nam... | 8c598518d7df1bcc88cbbb3c48d34fecd41b0487 | 30,175 |
import pickle
def get_actual_data(base, n_run, log_path, subfolders):
"""
:param base: the sub folder name right before the _DATE_InstanceNumber
:param n_run: the INSTANCE number in the subfolder name
:param log_path: path to the main log folder containing all the runs of an experiment (e.g. ../data/C... | b9f76b14b90e3c187e19bcd0b8bbbfe865518fe7 | 30,176 |
def secs_to_str(secs):
"""Given number of seconds returns, e.g., `02h 29m 39s`"""
units = (('s', 60), ('m', 60), ('h', 24), ('d', 7))
out = []
rem = secs
for (unit, cycle) in units:
out.append((rem % cycle, unit))
rem = int(rem / cycle)
if not rem:
break
if re... | 0918fd72fbaaa0adf8fe75bcb1ef39b4e9aba75b | 30,177 |
def shuffle(xsets, ysets, seed=None):
"""Shuffle two datasets harmonically
Args:
x, y: datasets, both of them should have same length
Return:
(shuffled_x, shuffled_y): tuple including shuffled x and y
"""
if len(xsets) != len(ysets):
raise ValueError
np.random.seed(seed=s... | 0d07fa7b1d556a5af0bb4f3d174326c756d3d6a7 | 30,178 |
import math
def get_CL_parameters(file_pointer, class_10_100_1000):
""" Function to predict cluster count and mean size by means of clustering
Args:
file_pointer: string with a file path
Returns
tuple with(
clusters: predicted number of clusters
log_me... | 498bf2e3b6a1e70808b159e2b630d9cdb8cebc40 | 30,179 |
def _nanclean(cube, rejectratio=0.25, boxsz=1):
"""
Detects NaN values in cube and removes them by replacing them with an
interpolation of the nearest neighbors in the data cube. The positions in
the cube are retained in nancube for later remasking.
"""
logger.info('Cleaning NaN values in the c... | 154bf994161a932505101ccbe921792e2d3c9f3b | 30,180 |
import json
def parseData(filePath):
"""
Tries to import JSON JobShop PRO file to program
:return machineList itinerariesList
"""
machinesList = []
itinerariesList = []
with open(filePath, 'r', encoding="utf8") as inputfile: # read file from path
importedData = json.loads(inputf... | b02471737e320eb35c4c9626c11737952455f18e | 30,181 |
def curve_fit_log(xdata, ydata, sigma):
"""Fit data to a power law with weights according to a log scale"""
# Weights according to a log scale
# Apply fscalex
xdata_log = np.log10(xdata)
# Apply fscaley
ydata_log = np.log10(ydata)
sigma_log = np.log10(sigma)
# Fit linear
popt_lo... | f00484c2e520e8060d7cb29ea503170c2e6ff07d | 30,182 |
def get_computed_response_text_value(response):
"""
extract the text message from the Dialogflow response, fallback: None
"""
try:
if len(response.query_result.fulfillment_text):
return response.query_result.fulfillment_text
elif len(response.query_result.fulfillment_mes... | fa7410ac4b0ef2c0dea59b0e9d001a7893a56479 | 30,183 |
def tmpdir_factory(request):
"""Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session.
"""
return request.config._tmpdirhandler | cb506efaef55275d30755fc010d130f61b331215 | 30,184 |
import os
def get_sims(word, language, lemmatized=False, threshold=0.70):
"""Get similar Word2Vec terms from vocabulary or trained model.
TODO: Add option to install corpus if not available.
"""
# Normalize incoming word string
jv_replacer = JVReplacer()
if language == 'latin':
# Note... | cdf0d04f448180bae7a8a3fdb6716603b0221ae4 | 30,185 |
def collect_ips():
"""Fill IP addresses into people list. Return if all addresses collected or not."""
out, rc, _ = run_cmd('sudo nmap -sn ' + net, log_error=False)
if rc:
print "Error: nmap is required. Run following command:"
print "sudo apt-get -y install nmap"
sys.exit(4)
#... | 52d1369d4af469a62af465b000489ad43f71d2e3 | 30,186 |
def roles(*role_list):
"""
Decorator defining a list of role names, used to look up host lists.
A role is simply defined as a key in `env` whose value is a list of one or
more host connection strings. For example, the following will ensure that,
barring an override on the command line, ``my_func`` ... | 2e30be0cb8876085c0c071b61a0a62061904816e | 30,187 |
from typing import List
from typing import Optional
from typing import Any
def pool_tr(
sents: List[str],
# services: List[str] = None,
max_workers: Optional[int] = -1,
from_lang: str = "auto",
to_lang: str = "zh",
timeout: float = 100,
) -> List[Any]:
# fmt: on
... | 1faf8970420dd8f3d6d58dd401f10ee2b9d74b9f | 30,188 |
def stairmaster_mets(setting):
"""
For use in submaximal tests on the StairMaster 4000 PT step ergometer.
Howley, Edward T., Dennis L. Colacino, and Thomas C. Swensen. "Factors Affecting the Oxygen Cost of Stepping on an Electronic Stepping Ergometer." Medicine & Science in Sports & Exercise 24.9 (1992): n... | 1d6cc9fc846773cfe82dfacb8a34fb6f46d69903 | 30,189 |
from typing import Optional
from typing import List
from pathlib import Path
from typing import Protocol
def get_uri_for_directory(directory: str,
excludes: Optional[List[str]] = None) -> str:
"""Get a content-addressable URI from a directory's contents.
This function will generate ... | acb7586d9adf210563ba73c3aed46c8ac695be26 | 30,190 |
def clean_cancer_dataset(df_training):
"""
Checks and cleans the dataset of any potential impossible values, e.g. bi-rads columns, the 1st only allows
values in the range of 1-5, ordinal
Age, 2nd column, cannot be negative, integer
Shape, 3rd column, only allows values between 1 and 4, nominal
M... | a30f377b48bb665f42f3efa58b15d289f7e7f9b3 | 30,191 |
from datetime import datetime
def str_to_date(date, form=None):
"""
Return Date with datetime format
:param form:
:param date: str date
:return: datetime date
"""
if form is None:
form = get_form(date)
return datetime.datetime.strptime(date, form) | acda6e393b468ffaf8eceb689c859440a53e486e | 30,192 |
def get_model_results(corpus, texts, ldamodel=None):
"""function extract model result such as topics, percentage distribution and return it as pandas dataframe
in: corpus : encoded features
in: text : main text
in: ldamodel: the trained model
out: dataframe
"""
topics_df = pd.DataFrame()
... | 31aa99db41193d2e25bd723720b68eb30606517f | 30,193 |
def rest_notify():
"""Github rest endpoint."""
sdkid = request.args.get("sdkid")
sdkbase = request.args.get("sdkbase", "master")
sdk_tag = request.args.get("repotag", sdkid.split("/")[-1].lower())
if not sdkid:
return {'message': 'sdkid is a required query parameter'}
rest_bot = RestAP... | 4f7c15186fbb2d0a4a3dd7199045178b62da362f | 30,194 |
def lib_pt_loc(sys_chars_vals, tolerance = 1e-12):
"""Computes Non-Dimensionalized Libration Points Location for P1-P2 system
Parameters
----------
sys_chars_vals: object
Object of Class sys_char
tolerance: float
convergence tolerance for Newton-Raphson Method
... | 2ee92c8f6e91353a675236a7f63eed4d7f807846 | 30,195 |
def max_pool_forward_naive(x, pool_param):
"""
A naive implementation of the forward pass for a max pooling
layer.
Inputs:
- x: Input data, of shape (N, C, H, W)
- pool_param: dictionary with the following keys:
- 'pool_height': The height of each pooling region
- 'pool_width': The ... | 61abc1cfaf6e559f8063690764de8530d555797c | 30,196 |
def _find_connection_file(connection_file):
"""Return the absolute path for a connection file
- If nothing specified, return current Kernel's connection file
- Otherwise, call jupyter_client.find_connection_file
"""
if connection_file is None:
# get connection file from current kernel
... | 2e4adfd67e0d2b35545cab1e82def271175b9de3 | 30,197 |
from typing import List
def _symbols_of_input(label: str) -> List[str]:
"""Extracts FST symbols that compose complex input label of the rewrite rule.
FST symbols of a complex input label is;
- Epsilon symbol if the complex input label is an epsilon symbol
(e.g. ['<eps>'] for label '<eps>').
- Digit... | 8298a242701aa586ba50ffa6059a8e33e4cf01f3 | 30,198 |
def preset_select_func(area, preset):
"""Create preset selection packet."""
return DynetPacket.select_area_preset_packet(area, preset, 0) | 9ae5e162cb32c3f3b0ab1d07e1d5cd2961e1e91e | 30,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.