content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def compute_accuracy(outputs, targets, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = targets.size(0)
_, preds = outputs.topk(maxk, 1, True, True)
preds = preds.t(... | 6cfcc9e43aaaed09baae567f9cc27818c555fe5f | 9,566 |
import io
def unpack_text_io_wrapper(fp, encoding):
"""
If *fp* is a #io.TextIOWrapper object, this function returns the underlying
binary stream and the encoding of the IO-wrapper object. If *encoding* is not
None and does not match with the encoding specified in the IO-wrapper, a
#RuntimeError is raised.
... | f2c93babab4bff1f08e6fe5c04fbd97dd1ee8a84 | 9,567 |
def dummy_blob(size_arr=(9, 9, 9), pixdim=(1, 1, 1), coordvox=None):
"""
Create an image with a non-null voxels at coordinates specified by coordvox.
:param size_arr:
:param pixdim:
:param coordvox: If None: will create a single voxel in the middle of the FOV.
If tuple: (x,y,z): Create single ... | 2426ca5cddfa3da660bd5e7436f8093b1d7fa109 | 9,568 |
import torch
def poly_edges(P, T):
"""
Returns the ordered edges from the given polygons
Parameters
----------
P : Tensor
a (N, D,) points set tensor
T : LongTensor
a (M, T,) topology tensor
Returns
-------
tuple
a tuple containing the edges of the given p... | c8d838bf1ada319cebc5c08719f66846959ce2c2 | 9,569 |
def make_list(v):
"""
If the object is not a list already, it converts it to one
Examples:
[1, 2, 3] -> [1, 2, 3]
[1] -> [1]
1 -> [1]
"""
if not jsoncfg.node_is_array(v):
if jsoncfg.node_is_scalar(v):
location = jsoncfg.node_location(v)
line = location.lin... | c5288cc726d103667e5f51055bc4e8cd4a90816e | 9,570 |
def score_game(game_core):
"""Запускаем игру 1000 раз, чтобы узнать, как быстро игра угадывает число"""
count_ls = []
np.random.seed(1) # фиксируем RANDOM SEED, чтобы ваш эксперимент был воспроизводим!
random_array = np.random.randint(1, 101, 1000)
for number in random_array:
count_ls.appen... | 74a8c4b44ff2caec31f38f136c3fc2336909759f | 9,571 |
def add_plot(
lon, lat, kind=None, props=None, ax=None, break_on_change=False, transform=identity
):
"""Add a plot with different props for different 'kind' values to an existing map
Parameters
----------
lon : sequence of float
lat : sequence of float
kind : sequence of hashable, optional
... | c5d6b5234fe560e9d954d4ea8d0a7aef0e810f89 | 9,572 |
def can_review_faults(user):
"""
users can review faults if one of the the following applies:
a) No fault review groups exist and they have can_review permissions
b) Fault review groups exist, they are a member of one, and they have
review permissions
"""
can_review = user.h... | c66f022b6f52144d8e9fde6865f0a8a263819813 | 9,573 |
import requests
def create_freshservice_object(obj_type, data):
"""Use the Freshservice v2 API to create an object.
Accepts an object name (string) and a dict of key values.
"""
url = '{}/{}'.format(settings.FRESHSERVICE_ENDPOINT, obj_type)
resp = requests.post(url, auth=FRESHSERVICE_AUTH, json=da... | 597348b744d6193beb12dcf2a3a4958808f09d24 | 9,574 |
def print_begin(*args, sep=' ', end='\n', file=None, ret_value='') -> str:
"""Print the function name and start."""
print(_prefix('begin'), *args, sep=sep, end=end, file=file, flush=True)
return ret_value | 8e9ac418d161a0d2b5b7c0c9de7b81da42ea5017 | 9,575 |
def scale_bounding_box(bounding_box,scale):
"""Scales bounding box coords (in dict from {x1,y1,x2,y2}) by x and y given by sclae in dict form {x,y}"""
scaled_bounding_box = {
"x1" : int(round(bounding_box["x1"]*scale["x"]))
,"y1" : int(round(bounding_box["y1"]*scale["y"]))
,"x2" : int(ro... | 8aa374537ed2ae3ae2324bd8a4819e981f281b71 | 9,576 |
import click
def is_command(obj) -> bool:
"""
Return whether ``obj`` is a click command.
:param obj:
"""
return isinstance(obj, click.Command) | 8159aea42baca70b3218a0b82e2f4dc3f34278aa | 9,577 |
def GetContigs(orthologs):
"""get map of contigs to orthologs.
An ortholog can be part of only one contig, but the same ortholog_id can
be part of several contigs.
"""
contigs = {}
for id, oo in orthologs.items():
for o in oo:
if o.contig not in contigs:
con... | 0c449a31e60f1a149317de815d630c4d8a817ca1 | 9,578 |
def set_backwards_pass(op, backwards):
"""
Returns new operation which behaves like `op` in the forward pass but
like `backwards` in the backwards pass.
"""
return backwards + tf.stop_gradient(op - backwards) | 13287ac73c52ac01808c41c81ba5311bc3f49b91 | 9,580 |
def remove_hydrogens(list_of_lines):
"""
Removes hydrogen from the pdb file.
To add back the hydrogens, run the reduce program on the file.
"""
return (line for line in list_of_lines if line['element']!=" H") | 164ac79171cf6b3632fe7909ace91ffe75192b61 | 9,581 |
def crash_random_instance(org: str, space: str, appname: str, configuration: Configuration, count: int = 1):
"""
Crash one or more random application instances.
:param org: String; Cloud Foundry organization containing the application.
:param space: String; Cloud Foundry space containing the application... | 652ab95038d405b6a193809804aae7f3bc15978f | 9,582 |
def spc_dict_from_spc_info(spc_info: dict, resonance: bool = True) -> dict:
"""
Generate a species dictionary from species info.
Args:
spc_info (dict): Species info contains the label and species geom info.
resonance (bool): Whether generate resonance geom in the species dictionary.
Re... | 0a291f2fd50134b1c1259adc36b5637e30e21118 | 9,583 |
import torch
def label_smooth_loss(log_prob, label, confidence=0.9):
"""
:param log_prob: log probability
:param label: one hot encoded
:param confidence: we replace one (in the one hot) with confidence. 0 <= confidence <= 1.
:return:
"""
N = log_prob.size(0)
C = log_prob.size(1)
s... | f1164d1a41d2c275ae4e406e2a46a0d50a2d240d | 9,584 |
def update(self, using=None, **kwargs):
"""
Updates specified attributes on the current instance.
"""
assert self.pk, "Cannot update an instance that has not yet been created."
using = using or router.db_for_write(self.__class__, instance=self)
for field in self._meta.fields:
if getatt... | b3400f43c0a744de17225ee6c029fc41465b784d | 9,585 |
def differential_privacy_with_risk( dfg_freq, dfg_time, delta, precision, aggregate_type=AggregateType.SUM):
"""
This method adds the differential privacy to the DFG of both time and frequencies.
* It calculates the epsilon using the guessing advantage technique.
* It adds laplace noise to the D... | a85035b8786bb6bf9a5cc0af88433a490faac77f | 9,586 |
from typing import Iterable
from typing import Counter
def get_all_values(string: str) -> Iterable[int]:
"""Return all kinds of candidates, with ordering: Dec, Hex, Oct, Bin."""
if string.startswith('0x'):
return filter(bool, [parse_hex(string[2:])]) # type: ignore[list-item]
if string.startswith... | d9e12290339cbf31dc572c9e3d49ec503949250d | 9,587 |
def svn_auth_get_simple_provider(*args):
"""svn_auth_get_simple_provider(apr_pool_t pool)"""
return _core.svn_auth_get_simple_provider(*args) | e91c2198f5ee214fb1db9e8969711a806caf19c6 | 9,588 |
def preferred_language():
""" It just returns first language from acceptable
"""
return acceptable_languages()[0] | 6e5c2b069f84c5a6601b579616858457598f2cf4 | 9,589 |
def get_frequencies(trial = 1):
"""
get frequency lists
"""
if trial =="run_fast_publish":
lb_targ, ub_targ, obs_hz = 340, 350, 10
elif trial == 1:
lb_targ, ub_targ, obs_hz = 210, 560, int(320 / 2)
elif trial == 2:
lb_targ, ub_targ, obs_hz = 340, 640, 280
elif trial == 3:
lb_... | e6c7f33865ffd76532a19426f0748d4dd22e37f8 | 9,590 |
import re
def parse_field_pubblicazione(field):
"""
Extracts year, place and publisher from the field `pubblicazione` by applying a cascade of regexps.
"""
exp2 = r'^(?P<place>\D+)(?:\s?\W\s?)(?P<publisher>.*?)\D{1}?(?P<year>\d+)?$'
exp1 = r'^(?P<place>.*?)(?::)(?P<publisher>.*?)\D{1}?(?P<year>\d+)?$'
exp3 = r'... | 91aee4dabf62b3ec5bccff2a07d664312226448c | 9,592 |
def test_api_calendar():
"""Return a test calendar object used in API responses."""
return TEST_API_CALENDAR | 1c73e63bf19cef92dbbe328825c2ae4e867c1e84 | 9,593 |
def apply_custom_colormap(image_gray, cmap=plt.get_cmap("seismic")):
"""
Implementation of applyColorMap in OpenCV using colormaps in Matplotlib.
"""
assert image_gray.dtype == np.uint8, "must be np.uint8 image"
if image_gray.ndim == 3:
image_gray = image_gray.squeeze(-1)
# Initialize ... | e2f3c9a8900f47c0e7183f4ebe72f41a7f6d26b9 | 9,594 |
from typing import Callable
def _cond_with_per_branch_args(pred,
true_operand, true_fun: Callable,
false_operand, false_fun: Callable):
"""Conditionally apply ``true_fun`` or ``false_fun``.
Has equivalent semantics to this Python implementation::
... | e942124beafebb69fed80e3175164a34f088cb9e | 9,595 |
import urllib
def msgSet(key, notUsed, queryString, body):
"""no treatment on the body (we send exactly the body like we received it)"""
dict = urllib.parse.parse_qs(body.decode('utf-8'))
#sendSMS.writeRawMsg(body)
user = dict['user'][0]
print(dict)
sendSMS.writeMsgUser(dict['msg'][0], user)
... | b67663f516f54af9a7dbbece67933ee1d04ee7a2 | 9,596 |
import re
def _strip_build_number(api_version):
"""Removes the build number component from a full api version string."""
match = re.match(r"^([A-Z]+-)?([0-9]+)(\.[0-9]+){2}$", api_version)
if match:
return api_version[:match.start(3)]
# if there aren't exactly 3 version number components, just leave it un... | 20d8023281f05dfcb8c9fdd021b77796c72e1001 | 9,597 |
def get_me():
"""サインインしている自分自身の情報を取得"""
jia_user_id = get_user_id_from_session()
return {"jia_user_id": jia_user_id} | c31f6a1a8c794e4a2aa70779f9c8b2559baccd84 | 9,598 |
def dec_file(name, out=None, **kwargs):
"""
This is a helper function to decrypt a file and return its contents.
You can provide an optional output file using `out`
`name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc.
CLI Examples:
.. code-bloc... | 3ff74b9300fa8b441a22daf65d546f329e414447 | 9,599 |
async def conversation_steps(month: int = Query(default=1, ge=2, le=6), current_user: User = Depends(Authentication.get_current_user_and_bot)):
"""
Fetches the number of conversation steps that took place in the chat between the users and the agent
"""
return Utility.trigger_history_server_request(
... | 9845cf39290f056395351953e3d7accbcb14ae06 | 9,600 |
def off(app: str) -> dict:
"""
Switches the app offline, if it isn't already.
:param app: The name of the Heroku app in which you want formation
:return: dictionary containing information about the app
"""
return Herokron(app).off() | 8aa6cef16d8924ce682fa9a7b886cee87d4e02c5 | 9,601 |
def count_weekday(start, stop, wd_target=0):
"""
Returns the number of days between start and stop inclusive which is the
first day of the month and is the specified weekday, with 0 being Monday.
"""
counter = 0
while start != stop + timedelta(days=1):
if start.weekday() == wd_target and... | 27dd8ce6493ac1c24c65c92208767159a6406348 | 9,603 |
import collections
def _get_ngrams(segment, max_order):
"""Extracts all n-grams upto a given maximum order from an input segment.
Args:
segment: text segment from which n-grams will be extracted.
max_order: maximum length in tokens of the n-grams returned by this
methods.
Returns:
... | c4b388d71b2c16e6c324718b8a07db8531c83413 | 9,604 |
def pkg_topics_list(data_dict):
"""
Get a list of topics
"""
pkg = model.Package.get(data_dict['id'])
vocabulary = model.Vocabulary.get('Topics')
topics = []
if vocabulary:
topics = pkg.get_tags(vocab=vocabulary)
return topics | 7594ea421ade2a530d8e08490b542bbd05d1a962 | 9,605 |
def five_five(n):
"""
This checks if n is a power of 2 (or 0).
This is because the only way that n and (n-1) have none of the same bits (the
& check) is when n is a power of 2, or 0.
"""
return ((n & (n-1)) == 0) | 0b1cc310b5d8bd6dab6299b6a999a5dd0720ea80 | 9,607 |
from main import bot
from typing import Optional
import asyncio
async def send_message(user_id: int,
text: str,
buttons: Optional[list[dict[str, str]]] = None,
disable_notification: bool = False) -> bool:
"""
Safe messages sender
:param... | e2cb9879a1eea95d639f6ff3c7b7bf7c5b19ef68 | 9,608 |
def convert_bytes_to_size(some_bytes):
"""
Convert number of bytes to appropriate form for display.
:param some_bytes: A string or integer
:return: A string
"""
some_bytes = int(some_bytes)
suffix_dict = {
'0': 'B',
'1': 'KiB',
'2': 'MiB',
'3': 'GiB',
... | d1579e0fc0850a98145910c056b3fac8be7c66f1 | 9,609 |
def create_bbregister_func_to_anat(fieldmap_distortion=False,
name='bbregister_func_to_anat'):
"""
Registers a functional scan in native space to structural. This is meant to be used
after create_nonlinear_register() has been run and relies on some of it's outputs.
... | 0598cef86fdebe697bfdc1627554c4340303a86b | 9,610 |
def pointShiftFromRange(dataSize, x = all, y = all, z = all, **args):
"""Calculate shift of points given a specific range restriction
Arguments:
dataSize (str): data size of the full image
x,y,z (tuples or all): range specifications
Returns:
tuple: shift of points from orig... | dbe5c2049c5b76bfdbb839faa2a3e6cb942c8249 | 9,611 |
def callparser():
"""Parses a group of expressions."""
def cull_seps(tokens):
return tokens[0] or tokens[1]
return RepeatParser(exprparser() + OptionParser(dlmparser(',')) ^ cull_seps) | af8fbf81044b90d6a1a9ea769a513109237692d4 | 9,612 |
def write_section(section_name, section, keys, writer) -> bool:
"""
Saves the specified section to the specified writer starting at the current
point in the writer. It will not throw an exception. On error (IO exception
or not being able to write the section) it will return false. WARNING: It can
no... | 368f0cac04d392b9ea8946d30538a3fb0265c593 | 9,613 |
def _rotation_270(image):
"""Rotate an image with 270 degrees (clockwise).
Parameters
----------
image : np.ndarray
Image to rotate with shape (y, x, channels).
Returns
-------
image_rotated : np.ndarray
Image rotated with shape (y, x, channels).
"""
image_rotated ... | 3cd291c9283a32d0bc66902bff7861db855f4420 | 9,614 |
def classification_id_for_objs(object_id: str, url: str, token: str):
"""
Get classification id for a given object
Arguments
----------
object_id : str
Object id to get classification id for
url : str
Skyportal url
token : str
Skyportal token
... | b03bb7ff18235cafd1b171e5042d64c65c19cffc | 9,615 |
import math
def ciede2000(Lab_1, Lab_2):
"""Calculates CIEDE2000 color distance between two CIE L*a*b* colors."""
C_25_7 = 6103515625 # 25**7
L1, a1, b1 = Lab_1[0], Lab_1[1], Lab_1[2]
L2, a2, b2 = Lab_2[0], Lab_2[1], Lab_2[2]
C1 = math.sqrt(a1**2 + b1**2)
C2 = math.sqrt(a2**2 + b2**2)
C_a... | f95bc8338fbabe09f2038cea34e7a8fcad87f3bf | 9,616 |
import torch
def ifft2c_new(data: torch.Tensor) -> torch.Tensor:
"""
Apply centered 2-dimensional Inverse Fast Fourier Transform.
Args:
data: Complex valued input data containing at least 3 dimensions:
dimensions -3 & -2 are spatial dimensions and dimension -1 has size
2. A... | 6752dd94c690d8a8d3d0d625a693cd711c12c9c0 | 9,617 |
def _make_options(context, base):
"""Return pyld options for given context and base."""
options = {}
if context is None:
context = default_context()
options['expandContext'] = context
if base is not None:
options['base'] = base
return options | 8fcd514d9b0d11020ea197a29af6e76a53201306 | 9,618 |
def datatable(table_config: DatatableConfig, table_id: str, class_name: str = ''):
"""
Deprecated, use instead
<table id="{table_id}" data-datatable-url="{url}" class="{class_name}"></table>
"""
return {
"rich_columns": table_config.enabled_columns,
"search_box_enabled": table_config... | 777d19f0eaa6f1adbb53cc1fa6042fbec3df4398 | 9,619 |
def npelpt(point, ellipse):
"""npelpt(ConstSpiceDouble [3] point, ConstSpiceDouble [NELLIPSE] ellipse)"""
return _cspyce0.npelpt(point, ellipse) | f81ff9a993f0166ed4899338c66b58e5329382ce | 9,620 |
def register_module():
"""Registers this module in the registry."""
# provide parser to verify
verify.parse_content = content.parse_string_in_scope
# setup routes
courses_routes = [('/faq', utils_faq.FaqHandler),('/allresources', utils_allresources.AllResourcesHandler)]
global custom_module
... | e4fe1ae4d3b05a4c396155ae3b471e941de56f7d | 9,621 |
def degreeList(s):
"""Convert degrees given on command line to a list.
For example, the string '1,2-5,7' is converted to [1,2,3,4,5,7]."""
l = []
for r in s.split(','):
t = r.split('-')
if len(t) == 1:
l.append(int(t[0]))
else:
a = int(t[0])
... | 3b517831ddab47da5cd0e36fa5913d6d59e73715 | 9,622 |
def _get_corrected_msm(msm: pd.DataFrame, elevation: float, ele_target: float):
"""MSMデータフレーム内の気温、気圧、重量絶対湿度を標高補正
Args:
df_msm(pd.DataFrame): MSMデータフレーム
ele(float): 平均標高 [m]
elevation(float): 目標地点の標高 [m]
Returns:
pd.DataFrame: 補正後のMSMデータフレーム
"""
TMP = msm['TMP'].values
P... | 5cbfafa077c02ff5b7b74e47eff30c99e6201ff8 | 9,624 |
def get_answers_by_qname(sim_reads_sam_file):
"""Get a dictionary of Direction Start CIGAR MDtag by ReadID (qname)."""
answers_by_qname = {}
reads_file = open(sim_reads_sam_file)
reads_file.next() #skip header line
for line in reads_file:
id, dir, start, cigar, mdtag = line.strip().split('\t... | eae27387f4ac0e20b16392ca699fad7e6489c6e9 | 9,625 |
def post_times(post: Post) -> html_tag:
"""Display time user created post.
If user has edited their post show the timestamp for that as well.
:param post: Post ORM object.
:return: Rendered paragraph tag with post's timestamp information.
"""
p = tags.p(cls="small")
p.add(f"{_('Posted')}: ... | 8e64d6f49ed5bcf8f9a9ea1f3a5350880bbe7b39 | 9,626 |
def read_articles_stat(path):
"""
读取articles_stat文件,生成可以读取法条正负样本数量的字典列表
:param path: articles_stat文件位置
:return: ret: [{'第一条': (负样本数量, 正样本数量), ...}, {...}, ..., {...}]
"""
df = pd.read_csv(path, header=0, index_col=0)
ret = [{} for i in range(4)]
for index, row in df.iterrows():
r... | be35e11a508e22241188b4719dc6fa0db14f4395 | 9,627 |
def get_bounding_box(font):
""" Returns max and min bbox of given truetype font """
ymin = 0
ymax = 0
if font.sfntVersion == 'OTTO':
ymin = font['head'].yMin
ymax = font['head'].yMax
else:
for g in font['glyf'].glyphs:
char = font['glyf'][g]
if hasattr... | 98161ef3426c2bb9b6dc4079c69f5c1f9d4e93a2 | 9,628 |
def create_user(client, profile, user, resend=False):
""" Creates a new user in the specified user pool """
try:
if resend:
# Resend confirmation email for get back password
response = client.admin_create_user(
UserPoolId=profile["user_pool_id"],
U... | 4c1f83c0ab7fd28dc7b1e2d8f2efa224360dfdb1 | 9,629 |
def generate_move_probabilities(
in_probs: np.ndarray,
move_dirn: float,
nu_par: float,
dir_bool: np.ndarray
):
""" create move probabilities from a 1d array of values"""
out_probs = np.asarray(in_probs.copy())
if np.isnan(out_probs).any():
print('NANs in move probabilities!')
... | 4ea9ef914b905b6ab79933ba90a3604b0391f038 | 9,630 |
def _is_diagonal(x):
"""Helper to identify if `LinearOperator` has only a diagonal component."""
return (isinstance(x, tf.linalg.LinearOperatorIdentity) or
isinstance(x, tf.linalg.LinearOperatorScaledIdentity) or
isinstance(x, tf.linalg.LinearOperatorDiag)) | de3bb0ab2313c5432abab4bf7b0c1e227bc682d7 | 9,631 |
def index():
"""Index Controller"""
return render_template('login.html') | 53499d68c734e6315e3f24927d70cb7cddca346a | 9,632 |
def match_twosided(desc1,desc2):
""" Two-sided symmetric version of match(). """
matches_12 = match(desc1,desc2)
matches_21 = match(desc2,desc1)
ndx_12 = matches_12.nonzero()[0]
# remove matches that are not symmetric
for n in ndx_12:
if matches_21[int(matches_12[n])] != n... | a86d1cfb19afa5404d8c4950dd8b24a130a6a003 | 9,633 |
import re
def parse_header_links(value):
"""Return a list of parsed link headers proxies.
i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
:rtype: list
"""
links = []
replace_chars = ' \'"'
value = value.strip(replace_c... | 58e1a73a524333cbd019387866047d434c7de494 | 9,634 |
def _friends_bootstrap_radius(args):
"""Internal method used to compute the radius (half-side-length) for each
ball (cube) used in :class:`RadFriends` (:class:`SupFriends`) using
bootstrapping."""
# Unzipping.
points, ftype = args
rstate = np.random
# Resampling.
npoints, ndim = points... | 0492f316c53b434faf79445313ec853830f87867 | 9,636 |
def _clip_grad(clip_value, grad):
"""
Clip gradients.
Inputs:
clip_value (float): Specifies how much to clip.
grad (tuple[Tensor]): Gradients.
Outputs:
tuple[Tensor], clipped gradients.
"""
dt = ops.dtype(grad)
new_grad = nn.ClipByNorm()(grad, ops.cast(ops.tuple_to_... | 31cd4693a2bd80af7d3dd4be6a830b2982f8fce8 | 9,638 |
def sample_cast(user, name='David'):
"""Creates a sample Cast"""
return Cast.objects.create(user=user, name=name) | 3e4d03878697dfac931babbeaacaa7687d520189 | 9,639 |
import re
def sort_special_vertex_groups(vgroups,
special_vertex_group_pattern='STYMO:',
global_special_vertex_group_suffix='Character'):
"""
Given a list of special vertex group names, all with the prefix of
special_vertex_group_pattern, selec... | 0cc8f0992553e5da5b37ea9a9886996cb9013582 | 9,640 |
def _GetFullDesktopName(window_station, desktop) -> str:
"""Returns a full name to a desktop.
Args:
window_station: Handle to window station.
desktop: Handle to desktop.
"""
return "\\".join([
win32service.GetUserObjectInformation(handle, win32service.UOI_NAME)
for handle in [window_station... | e9a2aeebdb6f705efab1a0c1997ca66f4079cc07 | 9,641 |
def decrypt(plain_text: str, a: np.ndarray, b: np.ndarray, space: str) -> str:
"""Decrypts the given text with given a, b and space
:param plain_text: Text you want to decrypt
:type plain_text: str
:param a: An integer that corresponds to the A parameter in block cypher
:type a: np.ndarray
:param b: An integer... | 642b47d3459c64c5c7b280401aa96bd8f37cfa59 | 9,642 |
def well2D_to_df1D(xlsx_path, sheet, data_col):
"""
Convert new 2D output format (per well) to 1D dataframe
:param str xlsx_path: path to the xlsx file
:param str sheet: sheet name to load
:param str data_col: new column name of the linearized values
:return dataframe df: linearized dataframe
... | 0d8403b311c50cbc7f723e044f3aa93c50f17e80 | 9,644 |
import hashlib
def obtain_file_hash(path, hash_algo="md5"):
"""Obtains the hash of a file using the specified hash algorithm
"""
hash_algo = hashlib.sha256() if hash_algo=="sha256" else hashlib.md5()
block_size = 65535
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(block_si... | daa996339c638eaab4f3d067dcaaa4b865a6f923 | 9,645 |
def b_q_bar(z_c):
"""Result of integrating from z_c to 1/2 of the
hard collinear part of the quark splitting function"""
b_q_zc = CF * (-3. + 6. * z_c + 4.* np.log(2. - 2.*z_c))/2.
return b_q_zc | c7e68a2b4b17e035081fd07784aeef017fcedabc | 9,646 |
def getsize(store, path=None):
"""Compute size of stored items for a given path."""
path = normalize_storage_path(path)
if hasattr(store, 'getsize'):
# pass through
return store.getsize(path)
elif isinstance(store, dict):
# compute from size of values
prefix = _path_to_pr... | e537a231c49ac1edb6153d4751bd7f1b01979778 | 9,647 |
def split_2DL5AB(GL, cursor, log):
"""
splits the KIR2DL5 GL-string into 2 separate GL strings for 2DL5A and 2DL5B
:param GL: GL-string for KIR2DL5, combining both A and B
:param cursor: cursor to a connection to the nextype archive
:param log: logger instance
"""
log.info("Splitting 2DL5-a... | e4c5eb51927b9e9cd607f95c1e2d1f853f4f2a3e | 9,648 |
def set_system_bios(context, settings, system_id=None, workaround=False):
"""
Finds a system matching the given ID and sets the BIOS settings
Args:
context: The Redfish client object with an open session
settings: The settings to apply to the system
system_id: The system to locate; ... | c28f52db53363399df534efacc506a7e25c99930 | 9,649 |
def geometric_augmentation(images,
flow = None,
mask = None,
crop_height = 640,
crop_width = 640,
probability_flip_left_right = 0.5,
probability_flip_up_down ... | f1a9ce6983edfd47388360b9d777ad5909c046e7 | 9,650 |
def edit_distance_between_seqs(seq1, seq2):
"""Input is two strings. They are globally aligned
and the edit distance is returned. An indel of any length
is counted as one edit"""
aln1, aln2 = _needleman_wunsch(seq1, seq2)
return edit_distance_from_aln_strings(aln1, aln2) | 88e98475c1652311745af69c6f521bba0497e633 | 9,651 |
import torch
def sentence_prediction(sentence):
"""Predict the grammar score of a sentence.
Parameters
----------
sentence : str
The sentence to be predicted.
Returns
-------
float
The predicted grammar probability.
"""
tokenizer = config.TOKENIZER.f... | 14d7c8efa76df4727419c2d99d685707ef46eb25 | 9,652 |
def build_seq(variants, phased_genotype, ref, pre_start, ref_end=None):
"""
Build or extend the haplotype according to provided genotype. We marked the start position iterator of each haplotype and
update with variant alternative base.
"""
seqs = ""
position = pre_start
for variant, phased... | b5f5168603b941fe8a55df5bd3bbf69898db3804 | 9,654 |
def handle_str(x):
"""
handle_str returns a random string of the same length as x.
"""
return random_string(len(x)) | 856341d0e3ff6d41c4c0f14beda5133b7285478c | 9,655 |
def get_process_causality_network_activity_query(endpoint_ids: str, args: dict) -> str:
"""Create the process causality network activity query.
Args:
endpoint_ids (str): The endpoint IDs to use.
args (dict): The arguments to pass to the query.
Returns:
str: The created query.
"... | 97330c89f7599cf4096322088ed7e7bad0699d49 | 9,657 |
async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
try:
client = TickTick()
client.login(data.get("username"), data.get("password"))
except RequestExcepti... | 7f6989ae0a87579f2270aab479247634b7d1f7e8 | 9,658 |
def _shard_batch(xs):
"""Shards a batch for a pmap, based on the number of devices."""
local_device_count = jax.local_device_count()
def _prepare(x):
return x.reshape((local_device_count, -1) + x.shape[1:])
return jax.tree_map(_prepare, xs) | 5c6fb53a97af3543b9e147abfb896719f83a0a28 | 9,659 |
def get_time_limit(component_limit, overall_limit):
"""
Return the minimum time limit imposed by the component and overall limits.
"""
limit = component_limit
if overall_limit is not None:
try:
elapsed_time = util.get_elapsed_time()
except NotImplementedError:
... | 4699ff18459a434a93fb50f8ac8bcc569ceb5e63 | 9,660 |
def keras_decay(step, decay=0.0001):
"""Learning rate decay in Keras-style"""
return 1. / (1. + decay * step) | f26f1f100ecf1622d6da9958d0a6cd95a37b8b2a | 9,661 |
def get_swagger():
""" Request handler for the /swagger path.
GET: returns the My Cars API spec as a swagger json doc.
"""
try:
return _make_response(response=validator.get_swagger_spec())
except Exception as e:
return _make_error(500, e.message) | a7ce1def456264d180dcb15e6039cd32e4df7597 | 9,662 |
def subtract(value, *args, **kwargs):
"""
Return the difference between ``value`` and a :class:`relativedelta`.
:param value: initial date or datetime.
:param args: positional args to pass directly to :class:`relativedelta`.
:param kwargs: keyword args to pass directly to :class:`relativedelta`.
... | 9f3c17b07c4010d9b1bfcff93280f0a59247fc5f | 9,663 |
def plot_coastline(
axes,
bathymetry,
coords='grid',
isobath=0,
xslice=None,
yslice=None,
color='black',
server='local',
zorder=2,
):
"""Plot the coastline contour line from bathymetry on the axes.
The bathymetry data may be specified either as a file path/name,
or as a ... | 1166ea3e942bf5c9212cf07e69326c38f6e77f96 | 9,664 |
def safelog(func):
"""Version of prism.log that has prism as an optional dependency.
This prevents the sql database, which may not be available, from becoming a strict dependency."""
@wraps(func)
def inner(self, update, context):
try:
self.bot.cores["prism"].log_user(update.effective... | fbd1ad03417151705640f0fd20c0caa685896496 | 9,665 |
def draw(args):
"""
Draw a GraphML with the tribe draw method.
"""
G = nx.read_graphml(args.graphml[0])
draw_social_network(G, args.write)
return "" | f5347dceaf6f79ab22218eb8838944d4f3e5a8ea | 9,666 |
import re
def extract_stem_voc(x):
"""extract word from predefined vocbulary with stemming and lemmatization
Args:
x ([string]): [a sentence]
Returns:
[list]: [word after stemming and lemmatization]
"""
stem = PorterStemmer()
# wnl = WordNetLemmatizer()
all_words = se... | 0e882eb8f9b938fc8eb50e69dda2864d2d8a12da | 9,667 |
from typing import Union
from typing import Optional
from typing import List
from typing import Dict
def plot_without_vis_spec(
conditions_df: Union[str, pd.DataFrame],
grouping_list: Optional[List[IdsList]] = None,
group_by: str = 'observable',
measurements_df: Optional[Union[str, pd.... | dba21fae889057e83dd8084b727e7c6312c3cd0f | 9,668 |
import torch
def _get_culled_faces(face_verts: torch.Tensor, frustum: ClipFrustum) -> torch.Tensor:
"""
Helper function used to find all the faces in Meshes which are
fully outside the view frustum. A face is culled if all 3 vertices are outside
the same axis of the view frustum.
Args:
fa... | edb9594b4a9d5fe6c3d7fcf24e9b0e312b94d3cb | 9,669 |
import collections
def _build_pep8_output(result):
"""
Build the PEP8 output based on flake8 results.
Results from both tools conform to the following format:
<filename>:<line number>:<column number>: <issue code> <issue desc>
with some issues providing more details in the description within
... | a4abda2f9d3a2d9b3524c60429b047cbfe0285d9 | 9,670 |
def form_value(request, entity, attribute):
"""
Return value from request params or the given entity.
:param request: Pyramid request.
:param entity: Instance to get attribute from if it isn't found in the request
params.
:param str attribute: Name of attribute to search for in the request ... | 1daea77474dae5a1cb6fdab0b075a5b2f5c40865 | 9,671 |
def process_batch_data(batch_words, batch_tags=None):
"""
Padding batched dataset.
Args:
batch_words: Words in a batch.
batch_tags: Punctuations in a batch.
Returns: Words and punctuations after padding.
"""
b_words, b_words_len = pad_sequences(batch_words)
if batch_tags is N... | 2428b1009cfcaf55df8ef5be275d87f1053643fd | 9,672 |
import torch
import math
def adjust_learning_rate(
optimizer: torch.optim,
base_lr: float,
iteration: int,
warm_iter: int,
max_iter: int,
) -> float:
""" warmup + cosine lr decay """
start_lr = base_lr / 10
if iteration <= warm_iter:
lr = start_lr + (base_lr - start_lr) * itera... | 1304e22abb712cfb6c589a2adf199971c058986f | 9,675 |
def load_data(filename: str):
"""
Load house prices dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (prices) - either as a single
DataFrame or a Tuple[DataFrame, Series]
"""
... | a5d044fa5be8ceefdb3cee7fb212608110f8dae5 | 9,677 |
def face_at_link(shape, actives=None, inactive_link_index=BAD_INDEX_VALUE):
"""Array of faces associated with links.
Returns an array that maps link ids to face ids. For inactive links,
which do not have associated faces, set their ids to
*inactive_link_index*. Use the *actives* keyword to specify an a... | db7e3e87144354fb850b0741a7531d06e73227f6 | 9,678 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.