content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def filter_example(config, example, mode="train"):
"""
Whether filter a given example according to configure.
:param config: config contains parameters for filtering example
:param example: an example instance
:param mode: "train" or "test", they differs in filter restrictions
:return: boolean
... | 5,343,700 |
def _dict_flatten(data):
"""Return flattened dict of input dict <data>.
After https://codereview.stackexchange.com/revisions/21035/3
Parameters
----------
data : dict
Input dict to flatten
Returns
-------
fdata : dict
Flattened dict.
"""
def expand(key, valu... | 5,343,701 |
def main1():
"""
采用生成器
"""
n=int(input("How many queens?\n"))
for index,result in enumerate(findnextpos(n,())):
print(repr(index)+":")
resultprint(result)
print("\n") | 5,343,702 |
def merkleroot(elements):
"""
Args:
elements (List[str]): List of hashes that make the merkletree.
Returns:
str: The root element of the merkle tree.
"""
return Merkletree(elements).merkleroot | 5,343,703 |
def category_start(update, context):
"""Separate function for category selection to filter the options with inline keyboard."""
update.message.reply_text(
"Choose a Group",
reply_markup=create_category_inline(trx_categories.keys(), "group_sel"),
)
return CATEGORY_REPLY_CHOOSE_TRX_OPTS | 5,343,704 |
def query_handler(query, data):
"""Handle UPDATE and INSERT queries in the admin panel."""
try:
db_conn = get_db_connection()
with db_conn.cursor() as cur:
cur.execute(query, data)
flash('Operation successfully completed', 'success')
except psycopg2.Error as e:
d... | 5,343,705 |
def betatest():
"""Main Function Definition"""
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('--host',\
required=True,\
help="site hostname")
parser.add_argument('--outputfile',\
'-o',\
... | 5,343,706 |
def create_player(mode, race, char_name):
""" Create the player's character """
# Evil
if mode == 2:
if race == 1:
player = character.Goblin(char_name, 1, app)
elif race == 2:
player = character.Orc(char_name, 1, app)
elif race == 3:
player = chara... | 5,343,707 |
def _get_item(i, j, block):
"""
Returns a single item from the block. Coords must be in block space.
"""
return block[i, j] | 5,343,708 |
def calculate_potentials_python(volume, mass, volume_material_mass, mass_material_mass):
""" Easy to read python function which calculates potentials using two Python loops
Still uses NumPy for the rote math.
"""
potentials = np.zeros(len(volume), dtype=np.float32)
for volume_i, volume_coord in enu... | 5,343,709 |
def snapshot(locks, source, destination):
"""Convert a possibly COW layered disk file into a snapshot."""
util_process.execute(
locks,
('qemu-img convert --force-share -o cluster_size=%s -O qcow2 -c %s %s'
% (constants.QCOW2_CLUSTER_SIZE, source, destination)),
iopriority=util_... | 5,343,710 |
def who_is_in_lab(bot, msg):
"""Report on who is currently in the lab."""
staff = {session.user for session in staff_in_lab()}
total = users_in_lab_count()
if total != 1:
are_number_people = 'are {} people'.format(total)
else:
are_number_people = 'is 1 person'
if staff:
... | 5,343,711 |
def test_bad_pct():
""" Dies on bad percent """
bad = random.randint(1, 10)
rv, out = getstatusoutput(f'{RUN} -p {bad} {N1K}')
assert rv != 0
assert re.match('usage:', out, re.I)
assert re.search(f'--percent "{float(bad)}" must be between 0 and 1', out) | 5,343,712 |
def rect2sphericalcoord3D(
v: list[Number, Number, Number]
) -> list[float, float, float]:
"""Does a 3D coordinate transform
from rectangular to spherical
coordinate system
p = The length of the hypotenuse
or the magnitude of the
vector
... | 5,343,713 |
def GetAssignmentByKeyName(key_name):
"""Gets the assignment with the specified key name."""
return Assignment.get_by_key_name(key_name) | 5,343,714 |
def fit_integer_type(n, is_signed=True):
"""Determine the minimal space needed to store integers of maximal value n
"""
if is_signed:
m = 1
types = [np.int8, np.int16, np.int32, np.int64]
else:
m = 0
types = [np.uint8, np.uint16, np.uint32, np.uint64]
if n < 2 ** (8... | 5,343,715 |
def admin_userforms_order_by_field(user_id):
""" Set User's forms order_by preference
"""
if not g.is_admin:
return jsonify("Forbidden"), 403
data = request.get_json(silent=True)
if not 'order_by_field_name' in data:
return jsonify("Not Acceptable"), 406
field_names = [ field['na... | 5,343,716 |
def check_all_rows(A):
"""
Check if all rows in 2-dimensional matrix don't have more than one queen
"""
for row_inx in range(len(A)):
# compute sum of row row_inx
if sum(A[row_inx]) > 1:
return False
return True | 5,343,717 |
def import_silda_command_line():
"""
Do the SILDa to kapture import using the command line parameters provided by the user.
"""
parser = argparse.ArgumentParser(description='imports SILDa dataset to kapture format.')
###################################################################################... | 5,343,718 |
def field_name_validator(field_name):
"""
Validates a field name for a document.
Note that this validator allows periods in the name. Dot notation
is permitted because it will be used to nest the field within the
document. E.g., a field name 'user.screen_name' will be saved as
the field 'screen... | 5,343,719 |
def extract_largest_connected_region(vtk_im, label_id):
"""
Extrac the largest connected region of a vtk image
Args:
vtk_im: vtk image
label_id: id of the label
Return:
new_im: processed vtk image
"""
fltr = vtk.vtkImageConnectivityFilter()
fltr.SetScalarRange(label... | 5,343,720 |
def _run_cli_cmd(cmd_list):
"""Run a shell command and return the error code.
:param cmd_list: A list of strings that make up the command to execute.
"""
try:
return subprocess.call(cmd_list)
except Exception as e:
print(str(e))
sys.exit(1) | 5,343,721 |
def findStandards(elm, min=0.1, max=1.0, sim=False):
"""findStandards(elm, min=0.1, max=1.0, simulate=False):
Search the standard database for suitable materials for use as a standard for the specified element."""
elm = element(elm)
sdb = App.getStandardsDatabase()
stds = sdb.findStandards(elm, min ... | 5,343,722 |
def group_set_array_data_ptr(d):
"""
call view%set_external_data_ptr
hide c_loc call and add target attribute
"""
# XXX - should this check the type/shape of value against the view?
# typename - part of function name
# nd - number of dimensions
# f_type - fortran type
# shape... | 5,343,723 |
def releaseTagName(version: Version) -> str:
"""
Compute the name of the release tag for the given version.
"""
return cast(str, version.public()) | 5,343,724 |
def get_calibrated_values(timeout=10):
"""Return an instance of CalibratedValues containing the 6 spectral bands."""
t_start = time.time()
while _as7262.CONTROL.get_data_ready() == 0 and (time.time() - t_start) <= timeout:
pass
with _as7262.CALIBRATED_DATA as DATA:
return CalibratedValue... | 5,343,725 |
def customizable_admin(cls):
"""
Returns a customizable admin class
"""
class CustomSearchableAdmin(BaseAdmin):
form = customizable_form(cls)
def __init__(self, *args, **kwargs):
super(CustomSearchableAdmin, self).__init__(*args, **kwargs)
# add the custom field... | 5,343,726 |
def restoreIm(transformeddata, pca, origshape, datamean, datastd):
"""Given a PCA object and transformeddata that consists of projections onto
the PCs, return images by using the PCA's inverse transform and reshaping to
the provided origshape."""
if transformeddata.shape[0] < transformeddata.shape[1]:
... | 5,343,727 |
def ga_multi(gene_info, ga_info):
"""Main loop which sets DEAP objects and calls a multi objective EA algorithm.
Parameters
-------
gene_info, GeneInfo class
See respective class documentation.
ga_info, GAInfo class
See respective class documentation.
Returns
-------
po... | 5,343,728 |
def sample(population, k=None):
"""Behaves like random.sample, but if k is omitted, it default to
randint(1, len(population)), so that a non-empty sample is returned."""
population = list(population)
if k is None:
k = randint(1, len(population))
return random_sample(population, k) | 5,343,729 |
def test_all_unique_violation_codes(all_violations):
"""Ensures that all violations have unique violation codes."""
codes = []
for violation in all_violations:
codes.append(int(violation.code))
assert len(set(codes)) == len(all_violations) | 5,343,730 |
def dense_to_one_hot(array, class_num, dtype_, axis=-1):
"""
this function offer a method to change the numpy array to one hot like base on axis
as we know array dims_size in axis should be 1
keep_shape
:param array: a numpy array, data type should be int
:param class_num: one hot class number
... | 5,343,731 |
def add_momentum_ta(df, high, low, close, volume, fillna=False):
"""Add trend technical analysis features to dataframe.
Args:
df (pandas.core.frame.DataFrame): Dataframe base.
high (str): Name of 'high' column.
low (str): Name of 'low' column.
close (str): Name of 'close' column... | 5,343,732 |
def get_experiment_type(filename):
"""
Get the experiment type from the filename.
The filename is assumed to be in the form of:
'<reliability>_<durability>_<history kind>_<topic>_<timestamp>'
:param filename: The filename to get the type.
:return: A string where the timesptamp is taken out fro... | 5,343,733 |
def async_check_significant_change(
hass: HomeAssistant,
old_state: str,
old_attrs: dict,
new_state: str,
new_attrs: dict,
**kwargs: Any,
) -> bool | None:
"""Test if state significantly changed."""
if old_state != new_state:
return True
if old_attrs.get(ATTR_EFFECT) != new_... | 5,343,734 |
def array2string(a, max_line_width=None, precision=None,
suppress_small=None, separator=' ', prefix="",
style=np._NoValue, formatter=None, threshold=None,
edgeitems=None, sign=None):
"""
Return a string representation of an array.
Parameters
----------... | 5,343,735 |
def registered_types():
""" list of registered types """
return list(Registry.types.get_all().keys()) | 5,343,736 |
def is_retain_bg_files(config: Dict[str, ConfigVO] = None) -> bool:
"""
在拉取新的壁纸前,是否保留旧的壁纸
"""
key = const.Key.Task.RETAIN_BGS.value
vo = config.get(key) if config else dao.get_config(key)
return vo and vo.value | 5,343,737 |
def getAwareTime(tt):
"""
Generates timezone aware timestamp from timezone unaware timestamp
PARAMETERS
------------
:param tt: datatime
timezome unaware timestamp
RETURNS
------------
:return: datatime
timezone aware timestamp
"""
... | 5,343,738 |
def test_get_teams_id(flask_cli, init_api_teams):
"""Tests the API endpoint ``GET /v1/teams/{id}``."""
team_id = init_api_teams[2]['id']
resp = flask_cli.get(f'/v1/teams/{team_id}')
data = json.loads(resp.data)
assert data == init_api_teams[2] | 5,343,739 |
def xdfs(request, tmpdir, vol_name, dos_format):
"""return (xdf_file, xdf_size_spec, vol_name) for various disks"""
size = request.param
if size == "880K":
file_name = tmpdir / "disk.adf"
size = ""
else:
file_name = tmpdir / "disk-" + size + ".hdf"
size = "size=" + size
... | 5,343,740 |
def nfvi_get_networks(paging, callback):
"""
Get a list of networks
"""
cmd_id = _network_plugin.invoke_plugin('get_networks', paging,
callback=callback)
return cmd_id | 5,343,741 |
def get_fasta(uniprot_id):
"""Get the protein sequence for a UniProt ID as a string.
Args:
uniprot_id: Valid UniProt ID
Returns:
str: String of the protein (amino acid) sequence
"""
# Silencing the "Will be moved to Biokit" message
with ssbio.utils.suppress_stdout():
r... | 5,343,742 |
def split_path(path, minsegs=1, maxsegs=None, rest_with_last=False):
"""
Validate and split the given HTTP request path.
**Examples**::
['a'] = split_path('/a')
['a', None] = split_path('/a', 1, 2)
['a', 'c'] = split_path('/a/c', 1, 2)
['a', 'c', 'o/r'] = split_path('/a/c/o... | 5,343,743 |
def get_purchases_formset(n_forms=0):
"""
Helper method that returns a Django formset for a dynamic amount of Purchases. Initially `n_forms` empty
forms are shown.
"""
return modelformset_factory(Purchase, fields=('amount', 'fruit'), extra=n_forms) | 5,343,744 |
async def git_pull():
"""
Pulls any changes down from github and returns the result of the command.
_> changed: str
"""
cmd = Popen(["git", "pull"], stdout=PIPE)
out, _ = cmd.communicate()
out = out.decode()
return out | 5,343,745 |
def inverse_word_map(word_map):
""" Create an inverse word mapping.
:param word_map: word mapping
"""
return {v: k for k, v in word_map.items()} | 5,343,746 |
def get_coalition_wins_sql_string_for_state(coalition_id,state_id):
"""
:type party_id: integer
"""
str = """ select
lr.candidate_id,
c.fullname as winning_candidate,
lr.constituency_id,
cons.name as constituency,
lr.party_id,
lr.max_votes,
(lr.max_vot... | 5,343,747 |
def computeAPLSF(data):
"""
Compute the LSF kernel for each chip
"""
index = 2047
## define lsf range and pixel centers
xlsf = numpy.linspace(-7.,7.,43)
xcenter = numpy.arange(0,4096)
## compute LSF profiles for each chip as a function of pixel
raw_out2_a = raw(xlsf,xcenter,data.lsfcoeff[0])
raw_out2... | 5,343,748 |
def test_random_density_not_real():
"""Generate random non-real density matrix."""
mat = random_density_matrix(2)
np.testing.assert_equal(is_density(mat), True) | 5,343,749 |
def login():
"""Log in a registered user by adding the user id to the session."""
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
error = None
user = User.query.filter_by(name=username).first()
if user is None:
... | 5,343,750 |
def test_metabolite_annotation_overview(model, db):
"""
Expect all metabolites to have annotations from common databases.
Specific database cross-references are paramount to mapping information.
To provide references to as many databases as possible helps to make the
metabolic model more accessible... | 5,343,751 |
async def create_pr_review(
gh: GitHubAPI, *, pull_request: Mapping[str, Any], comments: list[dict[str, Any]]
) -> None:
"""Submit a comment review for the given pull request.
`comments` is a list of ``parser.record.ReviewComment`` as dictionary which
represents the pull request review comment.
"""... | 5,343,752 |
def _timedeltaformat(value, include_ms=False):
"""Formats a timedelta in a sane way.
Ignores sub-second precision by default.
"""
if not value:
return NON_BREAKING_HYPHEN + NON_BREAKING_HYPHEN
total_seconds = value.total_seconds()
suffix = ''
if include_ms:
ms = int(round(total_seconds-int(total_... | 5,343,753 |
def get_viame_src(url):
"""
Get image src from via.me API.
"""
END_POINT = 'http://via.me/api/v1/posts/'
tmp = url.split('/')
viame_id = tmp[-1][1:]
address = END_POINT + viame_id
result = httpget(address)['response']['post']
return result['thumb_300_url'] | 5,343,754 |
def Geom_BSplineCurve_MaxDegree(*args):
"""
* Returns the value of the maximum degree of the normalized B-spline basis functions in this package.
:rtype: int
"""
return _Geom.Geom_BSplineCurve_MaxDegree(*args) | 5,343,755 |
def iou_score(pred_cls, true_cls, nclass, drop=(), mask=None):
"""
compute the intersection-over-union score
both inputs should be categorical (as opposed to one-hot)
"""
assert pred_cls.shape == true_cls.shape, 'Shape of predictions should match GT'
if mask is not None:
assert mask.dim(... | 5,343,756 |
def check_args(source_path, args):
"""Checks lengths of supplied args match or raise an error.
Lists can have only one element where they are automatically extended.
Args:
source_path(list(str)): List of source_paths supplied to turbiniactl.
args(list(list)): List of args (i.e. name, source, partitio... | 5,343,757 |
def futures_dce_position_rank(date: str = "20160104") -> pd.DataFrame:
"""
大连商品交易日每日持仓排名-具体合约
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/rcjccpm/index.html
:param date: 指定交易日; e.g., "20200511"
:type date: str
:return: 指定日期的持仓排名数据
:rtype: pandas.DataFrame
"""
date = cons.con... | 5,343,758 |
def make_earray(file_name, arrays, atom, sizes):
"""
make_earray(file_name, arrays, atom, sizes)
General purpose algorithm to create an empty earray
Parameters
----------
file_name: str
Name of file
arrays: str, list
List of references for arrays in data table
atom: type
Type of data in earray
size... | 5,343,759 |
def gen_rsa():
"""
Generate an RSA Key Pair for digital signature
this is designed to be called once per user
TODO maybe this belongs in server-specific code since server will
need to know public and private keys
"""
pkey = PKey()
pkey.generate_key(TYPE_RSA, RSA_BITS)
pkey.check()
... | 5,343,760 |
def get_token_type_str(token):
"""根据传入的token对象的类型返回该token的类型的字符串表达
参数
----
token : Token
返回
----
str : str
"""
token_type = token.type
if token_type == TOKEN_TYPE_IF:
return '(keyword)if'
elif token_type == TOKEN_TYPE_ELIF:
return '(keyword)elif'
elif tok... | 5,343,761 |
def _(
sklearn_model: ensemble.GradientBoostingRegressor,
path: os.PathLike,
) -> tf.keras.Model:
"""Converts a gradient boosting regression model into a TFDF model."""
if isinstance(sklearn_model.init_, dummy.DummyRegressor):
# If the initial estimator is a DummyRegressor, then it predicts a constant
... | 5,343,762 |
def task_checkqueue(storage):
"""
Task that watches a queue for messages and acts on them when received.
"""
# Get the queue object from the storage dictionary
thequeue = storage.get("queue")
try:
# Use a timeout so it blocks for at-most 0.5 seconds while waiting for a message. Smaller v... | 5,343,763 |
def to_sparse(x):
""" converts dense tensor x to sparse format """
x_typename = torch.typename(x).split('.')[-1]
sparse_tensortype = getattr(torch.sparse, x_typename)
indices = torch.nonzero(x)
if len(indices.shape) == 0: # if all elements are zeros
return sparse_tensortype(*x.shape)
i... | 5,343,764 |
def get_top_article_categories():
"""
获取顶级文章分类列表
自定义模版标签
"""
return Category.objects.filter(level=1) | 5,343,765 |
def filter_variants_top_k(log, k, parameters=None):
"""
Keeps the top-k variants of the log
Parameters
-------------
log
Event log
k
Number of variants that should be kept
parameters
Parameters
Returns
-------------
filtered_log
Filtered log
... | 5,343,766 |
def create_classifier(GrokClassifier=None, XMLClassifier=None, JsonClassifier=None, CsvClassifier=None):
"""
Creates a classifier in the user\'s account. This can be a GrokClassifier , an XMLClassifier , a JsonClassifier , or a CsvClassifier , depending on which field of the request is present.
See also: AW... | 5,343,767 |
def get_weighted_average(embedding, x, w):
"""
Compute the weighted average vectors
:param embedding: embedding[i,:] is the vector for word i
:param x: x[i, :] are the indices of the words in sentence i
:param w: w[i, :] are the weights for the words in sentence i
:return: emb[i, :] are the weig... | 5,343,768 |
async def startup_jobs_client(app: Application):
"""
An application `on_startup` callback that initializes a Virtool
:class:`virtool.job_manager.Manager` object and puts it in app state.
:param app: the app object
:type app: :class:`aiohttp.aiohttp.web.Application`
"""
app["jobs"] = JobsCl... | 5,343,769 |
def _build_gdef(ufo):
"""Build a table GDEF statement for ligature carets."""
from glyphsLib import glyphdata # Expensive import
bases, ligatures, marks, carets = set(), set(), set(), {}
category_key = GLYPHLIB_PREFIX + 'category'
subCategory_key = GLYPHLIB_PREFIX + 'subCategory'
for glyph in ... | 5,343,770 |
def winningRate2(r, s, X, Y):
"""
revised version, now we want to investigate how value of X and Y will affect.
r: int = remaining round of game
s: int = current score
X: int = points winning for X-head
Y: int = points wining for Y-head
(assuming X and Y are both fair, and we always assume Y... | 5,343,771 |
def handler(event, context):
"""Deletes all user content based on username provided in body,
only accessible from authenticated users with the custom:group=admin"""
logger.info(f"Received event: {json.dumps(event)}")
try:
if event["requestContext"]["authorizer"]["claims"]["custom:group"] != "ad... | 5,343,772 |
def DayOfWeek(year,month,day):
"""DayOfWeek returns the day of week 1-7, 1 being Monday for the given year, month
and day"""
num=year*365
num=num+year//4+1
num=num-(year//100+1)
num=num+year//400+1
if month<3 and LeapYear(year):
num=num-1
return (num+MONTH_OFFSETS[month-1]+day+4)%7+1 | 5,343,773 |
def get_stand_exe() -> str:
"""Get the path to standexe
Returns:
Path to standexe
Raises:
ValueError: If STAND_EXE is not found in environment variables.
"""
if os.environ['STAND_EXE']:
return os.environ['STAND_EXE']
else:
raise ValueError('STAND_EXE environment... | 5,343,774 |
def chef_execute_cli_commands(configuration):
"""
API to generate sonic cli commands with the provided configuration
:param configuration:
:return:
"""
if not configuration:
return False
commands = ""
action_run = "action:run"
for module in configuration:
if module ... | 5,343,775 |
def _normalize(vector):
"""Returns a normalized version of a numpy vector."""
return vector/np.sqrt(np.dot(vector, vector)); | 5,343,776 |
def load_ext(ext_name, name, func=None, endpoint=None):
"""
Load an external module.
Example: ``load_ext("distkv_ext","owfs","model")`` loads …/distkv_ext/owfs/model.py
and returns its global dict. When "ep" is given it returns the entry
point.
Any additional keywords are added to the module d... | 5,343,777 |
def get_chol_factor(lower_tri_vals):
"""
Args:
lower_tri_vals: numpy array, shaped as the number of lower triangular
elements, number of observations.
The values ordered according to np.tril_indices(p)
where p is the dimension of t... | 5,343,778 |
def debug(msg):
"""Send a debug message to the OTR debug buffer."""
debug_option = weechat.config_get(config_prefix('general.debug'))
global otr_debug_buffer
if weechat.config_boolean(debug_option):
if not otr_debug_buffer:
otr_debug_buffer = weechat.buffer_new("OTR Debug", "", "",
... | 5,343,779 |
def get_angles_gram_mask(gram, mask):
"""
Input: (gram) square numpy array, (mask) square numpy array where
1 = select, 0 = do not select
Output: (angles) numpy array or angles in mask in degrees
"""
angles = gram * mask
angles = angles[angles != 0]
angles = np.degrees(np.arccos(angles... | 5,343,780 |
def _expectation(p, kern1, feat1, kern2, feat2, nghp=None):
"""
Compute the expectation:
expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n)
- Ka_{.,.}, Kb_{.,.} :: Linear kernels
Ka and Kb as well as Z1 and Z2 can differ from each other, but this is supported
only if the Gaussian p is Diago... | 5,343,781 |
def rotX(angle):
"""
-----------------------------------------------------------------------
Purpose: Calculate the matrix that represents a 3d rotation
around the X axis.
Input: Rotation angle in degrees
Returns: A 3x3 matrix representing the rotation about angle around
X axis.
... | 5,343,782 |
def extract_url(url):
"""
extract the real url from yahoo rss feed item
"""
_url = None
if '*' in url: # old style yahoo redirect link
_url = "http" + url.split("*http")[-1]
elif url.startswith("http://finance.yahoo.com/r/"): # new style yahoo... | 5,343,783 |
def LF_positive_MeshTerm(report):
"""
Looking for positive mesh terms
"""
for idx in range(1,len(categories)):
reg_pos = re.compile(categories[idx],re.IGNORECASE)
reg_neg = re.compile('(No|without|resolution)\\s([a-zA-Z0-9\-,_]*\\s){0,10}'+categories[idx],re.IGNORECASE)
for s in ... | 5,343,784 |
def adopt(
objs: K8sObjects,
owner: Optional[bodies.Body] = None,
*,
nested: Optional[Iterable[dicts.FieldSpec]] = None,
) -> None:
"""
The children should be in the same namespace, named after their parent, and owned by it.
"""
real_owner = _guess_owner(owner)
append... | 5,343,785 |
def user_ratio_shuffle_split_with_targets(X,
train_ratio=0.8,
n_valid_users=1000,
n_test_users=1000,
minimum_interaction=3,
... | 5,343,786 |
def slice_core(core_tensor, inputs):
"""
Get matrix slices by indexing or contracting inputs, depending on input dtype
"""
assert isinstance(core_tensor, torch.Tensor)
assert isinstance(inputs, torch.Tensor)
if is_int_type(inputs):
return core_tensor[:, inputs, :]
else:
retur... | 5,343,787 |
def start_with_strategy(args, strategy, ants):
"""Reads command-line arguments and starts a game with those options."""
import argparse
parser = argparse.ArgumentParser(description="Play Ants vs. SomeBees")
parser.add_argument('-d', type=str, metavar='DIFFICULTY',
help='sets diff... | 5,343,788 |
def is_trivially_equal(lhs, rhs):
"""
True if lhs and rhs are trivially equal.
Use this for comparison of Sage expressions. Otherwise you
may start the whole proof machinery which may not exist at
the time of testing.
"""
assert (lhs - rhs).is_trivial_zero() | 5,343,789 |
async def test_discovery_by_firstbeat(
socket_push: wizlight, caplog: pytest.LogCaptureFixture
) -> None:
"""Test discovery from first beat."""
bulb_type = await socket_push.get_bulbtype()
assert bulb_type == BulbType(
features=Features(
color=False,
color_tmp=False,
... | 5,343,790 |
def assert_object_equals_dict(attributemap, obj, d):
"""Assert that the attributes of obj equal the dict values
:param attributemap: a dict to map attributes to dict keys
:type attributemap: :class:`dict`
:param obj: the object with attributes
:param d: the dictionary
:type d: :class:`dict`
... | 5,343,791 |
def replace_text(name, old, new, recurse=False, ext=''):
"""Replaces `name` with binary string params `old` and `new`"""
from clay.files.core import _rt_helper
if recurse:
sure = eval(input('Replace all "{1}" in "{0}" with "{2}" (True/False)? '.format(name, old, new)))
if sure:
... | 5,343,792 |
def diff_tools(preferred_tool='auto'):
# type: (str) -> Iterator[Tuple[str, str, List[str]]]
"""Yields a number of installed and working diff tools that we can use for this program.
We compare a "Hello, World!" program against itself with two different modifications and
check if a diff tool returns the... | 5,343,793 |
def dep_fetch_devices(app: Flask, dep: DEP, dep_account_id: int):
"""Perform fetch or sync of devices.
TODO: If default DEP Profile is nominated, it is queued for assignment here. But may want to check `profile_status`
to see whether only devices with the `removed` status are considered unassigned.
... | 5,343,794 |
def geo2xy(ff_lat_pto, ff_lng_pto, ff_lat_ref=cdf.M_REF_LAT, ff_lng_ref=cdf.M_REF_LNG):
"""
transforma coordenadas geográficas em coordenadas cartesianas
:param ff_lat_pto: latitude em graus
:param ff_lng_pto: longitude em graus
:param ff_lat_ref: latitude do ponto de referência
:param ff_lng_r... | 5,343,795 |
def size(e):
"""
:rtype: Column
"""
return col(Size(parse(e))) | 5,343,796 |
def b64pad(b64data):
"""Pad base64 string with '=' to achieve a length that is a multiple of 4
"""
return b64data + '=' * (4 - (len(b64data) % 4)) | 5,343,797 |
def get_peak_electric_demand(points_on_line):
"""
Initialize Power Demand
:param points_on_line: information about every node in study case
:type points_on_line: GeoDataFrame
:returns:
- **dict_peak_el**: Value is the ELECTRIC peak demand depending on thermally connected or disconnected.
... | 5,343,798 |
def replace_obfuscatables(module, tokens, obfunc, replace, name_generator, table=None):
"""
Iterates over *tokens*, which must be an equivalent output to what
tokenize.generate_tokens() produces, replacing the given identifier name
(*replace*) by calling *obfunc* on each token with the following paramet... | 5,343,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.