content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def get_analysis_status_command(
client: Client,
ids: str, # argsToList called inside
) -> List[CommandResults]:
"""Check the status of a sandbox analysis.
:param client: the client object with an access token
:param ids: ids of a submitted malware samples.
:re... | 79bff4beecd9f7f802e3af0e430ec7b86823b354 | 76,093 |
import re
def generate_drac_arpa(cfg, cidr):
"""
Retrieves server list from mothership to create drac arpa records
"""
net = mothership.network_mapper.get_network(cidr)
num = 0
while re.search('\.0+$', net):
net = re.sub('\.0+$', '', net)
num += 1
alist = ''
for n in cf... | 861ff83822f2c6fa9ca08a07e3bf316dc5314b1d | 76,094 |
import typing
from typing import Sequence
def walk_expression(
expression: Expression,
visit: typing.Callable[
[Expression], typing.Union[bool, typing.Optional[Expression]]
],
replacements: typing.Optional[typing.Dict[str, typing.List[Expression]]] = None,
) -> typing.Union[bool, typing.Option... | 27cf1a2d0b2a4d5bc951aed081443b7925962d9d | 76,095 |
import time
def mdd(self, method='laplace', chain=None, lprobs=None, tune=None, verbose=False, **args):
"""Approximate the marginal data density.
Parameters
----------
method : str
The method used for the approximation. Can be either of 'laplace', 'mhm' (modified harmonic mean) or 'hess' (LaP... | b57d2018098526c128dcdeb841b0aa048d515667 | 76,096 |
def send_appsrc_data(appsrc_id, tensor, stream_name, stream_manager):
"""
Construct the input of the stream,
send inputs data to a specified stream based on streamName.
Returns:
bool: send data success or not
"""
tensor = np.expand_dims(tensor, 0)
tensor_package_list = MxpiDataType.... | 5951524bf7552b312e2061d2aad5e60f84142bf3 | 76,097 |
def decode_subs(s, mapping):
"""
>>> decode_subs('hi there', [])
'hi there'
>>> decode_subs('g0SUB;there', [('hi ', 'g0SUB;')])
'hi there'
>>> decode_subs('g0SUB; theg1SUB;', [('hi', 'g0SUB;'), ('re', 'g1SUB;')])
'hi there'
"""
for tup in mapping:
s = s.replace(tup[1], tup[... | e0be61cae24956557c3d40348a0445cd237a2a0c | 76,098 |
def append(name, family="ipv4", **kwargs):
"""
.. versionadded:: 0.17.0
Append a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Network family, ipv4 or ipv6.
All other argu... | 83dbd1c376bcf20844b72b21890607e21bbae77e | 76,099 |
def findDate(num_projects):
"""
Given the number of projects, this will return the predicted date
it will be reached
"""
num_day = int((inverseDate(num_projects)))
unmodified_date = str((date(2002, 11, 5) + timedelta(days = num_day)))
mdict = {"01":"Jan", "02":"Feb", "03":"Mar", "04":"Apr", ... | e1a0bd787481827c5d335d4e5e1bbe0f9206e0af | 76,100 |
def shared_area(polygon1, polygon2, normalized=False):
""" Get area shared by 2 polygons
:param polygon1:
:param polygon2:
:param normalized:
:return:
"""
if not polygon1.intersects(polygon2):
return 0
else:
new_poly = polygon1.intersection(polygon2)
if normalize... | 63cb169cd2a7f408b9298342b6830674fb5a43ea | 76,102 |
def process_target(path):
"""
Get coordinate of target
Args:
path: path to image
Returns:
coordinates
"""
img_target, target_gray = imread(path)
# dilate image
target_segment = filter_color_hsv(img_target, [0, 10, 245], [30, 255, 255])
kernel = np.ones((10,10), np... | f83b2fa43cd81c5080dd2e45fec36bd5112e0d86 | 76,103 |
def screen_and_build_provider_sync_create_event(provider):
"""Determine if the source should be queued for synchronization."""
provider_event = {}
screen_fn = SCREEN_MAP.get(provider.source_type)
if screen_fn and screen_fn(provider) and not provider.pending_delete:
provider_event = {"operation":... | 76b82223e83eac4cf074145305dd794939f4b3d7 | 76,104 |
def read_information_file(prefix, bath, pot):
""" read the gradient information file from its filesystem path
"""
return INFORMATION_FILE.read([prefix, bath, pot]) | b2575f2a2172108e6280e9ef45ded4c37bc11f30 | 76,106 |
def _do_get_training_dataset_path(training_dataset, featurestore_metadata, training_dataset_version=1):
"""
Gets the HDFS path to a training dataset with a specific name and version in a featurestore
Example usage:
>>> featurestore.get_training_dataset_path("AML_dataset")
>>> # By default the libr... | d6537fbf634cab7de57d6f5d3546e511c2cbe0b2 | 76,107 |
import numpy
def get_detJ(xi, cube):
"""Get the determinant of the transformation matrix.
"""
# For d==2, the result can be computed with
# ```
# J0 = (
# - numpy.multiply.outer(0.25*(1-xi[1]), quad[0, 0])
# + numpy.multiply.outer(0.25*(1-xi[1]), quad[1, 0])
# - numpy.multi... | 7f3b679b872d6f3ffa0e14ee76e1d58a4f840fc3 | 76,108 |
async def open_remote_endpoint(
host, port, *, queue_size=None, **kwargs):
"""Open and return a remote datagram endpoint.
An optional queue size arguement can be provided.
Extra keyword arguments are forwarded to `loop.create_datagram_endpoint`.
"""
return await open_datagram_endpoint(
... | f150cd1f155b0792e79804ef0c1e142aa58c4448 | 76,109 |
def _http_jar_impl(ctx):
"""Implementation of the http_jar rule."""
all_urls = []
if ctx.attr.urls:
all_urls = ctx.attr.urls
if ctx.attr.url:
all_urls = [ctx.attr.url] + all_urls
auth = _get_auth(ctx, all_urls)
download_info = ctx.download(
all_urls,
"jar/download... | fb2c2b893baa6d0f92a2ac8830c76fd959b08d2c | 76,112 |
def eval_predictions(x, y):
"""
Computes metrics to evaluate model predictions.
Parameters
----------
x: list
list of target/prediction property
y: list
list of target/prediction property
Returns
-------
mae: float
Mean absolute error of pred... | 350c8d1b3542eee5aa4a68ed9662c9cebeb632cd | 76,113 |
import inspect
def inline_help(func):
"""Return function spec and first line of help in line"""
fun_name = '%s%s' % (func.__name__, inspect.signature(func))
fun_doc = func.__doc__.strip().split('\n')[0] if func.__doc__ else ""
return "%s\n\t%s" % (fun_name, fun_doc) | dcc19fa82dbb21735ef2199dbc4f136d722a1621 | 76,114 |
def reverse_complement(seq: str):
"""
Basic reverse complement
"""
complements = {"A": "T", "C": "G", "G": "C", "T": "A"}
return "".join(complements[x] for x in seq[::-1]) | 0f4d62dc08233b7ef93cb0c90a5fa242762e0c5e | 76,115 |
def calculate_average(nums):
"""
Calculates average for an input list of numbers.
Args:
nums: List of numbers
Returns:
Average of input list
"""
return sum(nums) / len(nums) | cfd7379e0f6731b9eecc086801b9b905d8d2b555 | 76,116 |
def MissingNumber3(array, n) :
""" In case we can use an XOR operation """
x1 = array[0]
x2 = 1
for i in range(1, n-1) :
x1 = x1 ^ array[i]
for i in range(2, n+1) :
x2 = x2 ^ i
return x1 ^ x2 | 2c9602c035af9f0269707ce3aab9af3ad2d0e156 | 76,117 |
import av
def track_single_particle(
video_file_name,
estimators,
number_frames_to_be_tracked=0,
frame_normalize=0,
frame_enhance=1,
use_cv2=False):
"""Track single particlee in a video.
Inputs:
video_file_name: video file
network: the pre-trained network
number_frames_to_... | 477ed26c426d9d098c71985ec9f25fc5f73c5a66 | 76,118 |
def prettify(elem):
"""
Return a pretty-printed XML string for the Element.
"""
rough_string = tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | 0635cd8a6777971f2fcae2cbad38c5f11bde13ac | 76,119 |
def _canonicalize_smiles(smiles):
"""Canonicalizes a SMILES string."""
try:
return resolvers.canonicalize_smiles(smiles)
except ValueError:
return smiles | b271ff2fcdebb320121559a1a41e65c8b97487c4 | 76,121 |
def rotation_matrix(angle, axis):
"""
It computes 3x3 rotation matrix from angle at the specified axis.
Input:
angles: [B] tf.float32, angles of rotations
axis: one of {0,1,2}, the axis of rotation.
Output:
R: [B, 3, 3] float32, rotation matrices
"""
_0 = tf.zeros_like(angle); _1 = tf.ones_like(angle)
c = ... | 088c81e2b60b92a72e68b67f681bbfe409cdf600 | 76,122 |
def unescapeEndpointDescription(desc):
"""
Takes escaped endpoint descriptions from our configuration and unescapes
them to pass as a Twisted endpoint description.
"""
result = []
escape = []
depth = 0
desc = iter(desc)
for char in desc:
if char == "\\":
try:
char = desc.next()
except StopIteration... | 6197fded9a1366eeab3da93fd26cd22557f11267 | 76,123 |
def move1(state,b1,dest):
"""
Generate subtasks to get b1 and put it at dest.
"""
if state.pos[b1] == "in-arm":
return [('put', b1,dest)]
else:
return [('get', b1), ('put', b1,dest)] | e2fdfaf4889a5b662b4a5d585464149690dea4c0 | 76,124 |
def compute_min_distance(lng_rad, lat_rad, p0_lng, p0_lat, pm1_lng, pm1_lat, p1_lng, p1_lat):
"""
:param lng_rad: lng of px in radians
:param lat_rad: lat of px in radians
:param p0_lng: lng of p0 in radians
:param p0_lat: lat of p0 in radians
:param pm1_lng: lng of pm1 in radians
:param pm1... | b042d36f9e3de0705bafa3c68a65503e2a83222f | 76,125 |
def createB2Command(bucket, filename):
"""
Create a command that calls the b2 python script
"""
targetName = filename
targetName = replaceIfNeeded(targetName, "\xe4", "a")
targetName = replaceIfNeeded(targetName, "\xf6", "o")
targetName = replaceIfNeeded(targetName, "\xc4", "A")
targetNa... | 40d0a80004fdb6d5d804420612ae9ed8e890f774 | 76,127 |
from typing import List
from typing import Tuple
def append_per_tuple(
dataset_2tuples: List[Tuple[str,str]],
new_val: int
) -> List[Tuple[str,str,int]]:
"""
Given a list of 2-tuple elements, append to every 2-tuple another fixed
item, such that a list of 3-tuples is returned.
"""
dataset_3tuples = []
for (... | f0518a29f9d4d4219a19d41d1dd2dee4d271ee30 | 76,128 |
import time
def hillclimber(rushHourBoard):
"""
Solve the board using the Hill Climber algorithm (see hill_climber.py for details)
"""
# ask if user want to choose the parameters
parameters = input('Do you want input custom parameters? (yes/no): ')
if parameters.lower() == 'yes':
goo... | 88d22aa481cb35f4b89c9309540f03cab2d7557e | 76,130 |
def cidr_mask_to_ip_int(mask_num):
"""
掩码位数转换为整数值
:param mask_num: 掩码位数, 如 16
:return: 一个整数值
"""
cidr_num = int(mask_num)
if 0 < cidr_num <= 32:
return ((1 << cidr_num) - 1) << (32 - cidr_num)
raise ValueError('% is not valid cidr code.' % cidr_num) | d62cd2c52f3a4fdbbceccb0f3fc1b1988754d410 | 76,131 |
def open_rad_obs(path, level):
"""Open a GridRad observation file, filter and remove clutter from the reflectivity, then return reflectivity for the specified level.
Paramters
---------
path : str or os.path object
Path to GridRad observation file
level : int or str
Vertical level i... | fd8aad835f1b954cf171d0d92020d5bb0c9f09d7 | 76,133 |
from typing import Type
from typing import TypeVar
def type_is_list_with_item_type(field_type: Type, dc_field: Field):
"""True if the given type is `typing.List` with an item type specified"""
is_list = hasattr(field_type, "__origin__") and field_type.__origin__ is list
if is_list and isinstance(field_ty... | 782d1c24ce1bc66c8cc2dc31106f8d66033b352b | 76,134 |
def index(array, i, j):
"""
Return minimum index.
"""
if i == j:
return i
k = index(array, i+1, j)
return i if array[i] < array[k] else k | 0c1ab5bb1498002ead3271e4dd414592f4f37cd4 | 76,135 |
def dNdlnM1(M1, z1, M0, z0, **cosmo):
"""
The EPS progenitor mass function (PMF),
dN/dln(M_1) = M_0/M_1 dP/dln(M_1),
i.e., the mean number of progenitors with mass in the logarithmic
mass bin [ln(M_1), ln(M_1)+dln(M_1)].
Strictly speaking, the PMF is dN/dM_1, related to dN/dln(M_1) by
... | 1a87c6963bd949cc8c853379c0ac97238dde934c | 76,136 |
def can_mock_function(parameters):
"""Whether a function with the given parameters can be mocked by googlemock.
Google Mock can't handle the case where a function has a variable number of arguments and
there's also a limit on the max number of arguments.
"""
# I'm not sure this is exactly right, bu... | 67393437a306bfc0e4b21b4db550df19c03c18e7 | 76,138 |
def call_implied_volatility(S0, K, T, r, C0, sigma_est, it=100):
"""
Implied Volatility of European call option in BSM Model.
:param S0:
:param K:
:param T:
:param r:
:param C0:
:param sigma_est:
:param it:
:return:
"""
sigma_step = 0.01 # 1%
direction = 0 # undefi... | f65f34b0af7c0ce84c042070ec721c5542672d2e | 76,140 |
def allocate_shared_from_buffer(buffer):
"""Allocate a shared array for multi-process communication.
Args:
buffer -- the buffer to use for initializing the shared array
Return:
a numpy array which uses shared memory and is initialized to the value of `buffer`
"""
if buffer.dtype.ty... | 6061daae8ca8de937faabaae598b9093e17d4bc7 | 76,142 |
from enum import Enum
def get_type(values):
"""Return the type of the values where type is defined as the modal type in the list.
Args:
values: A list or value to get the type for.
Returns:
The modal type of a list or the type of the element. Can be integer, float, string, datetime, or n... | d2e48138cace07ba8236695359d90a953cd3d3ad | 76,143 |
def pd_state_set(handle,
controller_type, controller_slot, drive_slot, drive_state,
vd_id=None, server_id=1):
"""
Sets the drive state of physical drive
Args:
handle (ImcHandle)
controller_type (str): Controller type
'SAS'
... | d46d308b19cfafef24ba50ade5f48612b0a2bd1c | 76,145 |
def soft_sphere(dr: Array,
sigma: Array=1,
epsilon: Array=1,
alpha: Array=2,
**unused_kwargs) -> Array:
"""Finite ranged repulsive interaction between soft spheres.
Args:
dr: An ndarray of shape [n, m] of pairwise distances between particles.
... | 1a408e57ae108cf5885c69ba3470dd5673809d72 | 76,146 |
def _safe_indexing(X, indices, *, axis=0):
"""Return rows, items or columns of X using indices.
.. warning::
This utility is documented, but **private**. This means that
backward compatibility might be broken without any deprecation
cycle.
Parameters
----------
X : array-like... | 60bdfea31a8f274ee716fff139e65a9e28c91984 | 76,147 |
from typing import Union
def linspace(start: Union[ivy.Array, ivy.NativeArray, Number], stop: Union[ivy.Array, ivy.NativeArray, Number],
num: int, axis: int = None, dev: ivy.Device = None, f: ivy.Framework = None)\
-> Union[ivy.Array, ivy.NativeArray]:
"""
Generates a certain number of ev... | dc139683709b83a8d3741c5fbb6d801b2f9dd224 | 76,148 |
def TestFileAST1():
""" Test FileAST """
t = CT.SetUp("simple_declaration.c")
return CT.ConvertTree(t, "simple_declaration.c") | 7114caeb8a9cae7c1cb0705f525012f25fd94c3a | 76,149 |
def createPiecewiseLinearContinuousScalarSpace(context, grid):
"""
Create and return a space of globally continuous scalar functions defined
on a grid and linear on each element of this grid.
*Parameters:*
- context (Context)
A Context object that will determine the type used to repr... | 8ca5579eb5e83b84a8e55ac60e16000a07ba97d8 | 76,150 |
def parses_as_xml(code: str) -> bool:
"""If it parses as xml, it probably is xml or someting like it"""
if "<" not in code or ">" not in code:
# I don't care if a text fragment is xml in some sense
return False
# pylint: disable=broad-except
# noinspection PyBroadException
try:
... | 8ca8c007f3669152cab25b436d59983cd1a1702b | 76,151 |
def categorical_crossentropy(y_true, y_pred, from_logits=False, label_smoothing=0):
"""
Computes the categorical crossentropy loss.
Parameters
----------
y_true : [type]
Tensor of one-hot true targets.
y_pred : [type]
Tensor of predicted targets.
from_logits : bool, optional... | 2435ba13e8c760745cf20cfa81992058b6a33e19 | 76,152 |
def rfe(x, y, step=0.1, n_features_to_select=10,
permutation=0):
"""sigle rfe"""
estimator = SVC(kernel="linear")
selector = RFE(estimator, step=step,
n_features_to_select=n_features_to_select)
selector.fit(x, y)
# mask=selector.support_
rank = selector.ranking_
re... | b0c1b32cfa2081a4b284538fa64ecfc0ca48f564 | 76,153 |
def calc_COM(molecule_struct):
""" COM calculation for Molecule Structure """
geometry = molecule_struct.get_geo_array()
elements = molecule_struct.geometry['element']
element_numbers = [atomic_numbers[x] for x in elements]
element_masses = np.array([atomic_masses_iupac2016[x]
... | e5f40c86802ad76bea55c015e8929579ca6c7d98 | 76,154 |
from typing import List
import re
from functools import reduce
def parse_text_for_all_weekdays(text_list: List[str]) -> dict:
"""
Parses a list of strings, returning a dict mapping each day's menu to its respective weekday
:param text_list: Week menu splitlines, should not include empty items.
:return... | 9453129f1c6b22afd0421a194c910b22dbe909b0 | 76,155 |
def split_vs_score(avg_micro1, avg_macro1, avg_micro2, avg_macro2, avg_acc1, avg_acc2, avg_auc1, avg_auc2,
test_ratio_arr):
"""
For every type of score plot the graph as explained above.
"""
# you can change borders as you like
fig1 = do_graph_split(avg_micro1, avg_micro2, test_ra... | 03b764c56015826ef6057e26b719253444fa8191 | 76,156 |
def LogWarning(*args, **kwargs):
"""LogWarning(String msg)"""
return _misc_.LogWarning(*args, **kwargs) | 6f0d2df5792dc79f1546ae971afb38f48bc86ac3 | 76,157 |
def compute_surfaces(config, db):
"""
Compute equivalent and check surfaces, and save to disk.
Parameters:
-----------
config : dict
Config object, loaded from config.json.
db : hdf5.File
HDF5 file handle containing all experimental data.
Returns:
--------
np.array(... | b6c5354a42e2fbd9ca0956813dea86fd26ef1ecc | 76,158 |
def running_from():
""" Where is the code running from ?"""
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return "notebook" # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell':
return "terminal" # Termina... | e54e8926c0d2b7f8c09b91eb0fe6f74b11ac408b | 76,159 |
import re
def get_nic_type(interface: str) -> str:
"""Get Nic Type on a certain interface
Args:
interface (str): interface name
Raises:
Runtime: if ethtool not installed on the system
Value: if interface given is invalid
Returns:
str: type of the interface
"""
... | c0b61247b2daaaa67fc2fcd81194ab4320f04c60 | 76,160 |
def convert2pixel_coords(camera_coordinates, intrinsic_matrix):
"""Calculate pixel coords of the 3d box.
Args:
camera_coordinates: (3-dimensional array) camera coords of all objects in the 3d scene.
intrinsic_matrix: (4x4 array): camera intrinsic parameters.
Output: pixel points in 2D coordi... | 405a34d40fbff73ba6b02c98ad18f841e1417ba0 | 76,161 |
from bs4 import BeautifulSoup
def get_img_url(offer_markup):
""" Searches for images in offer markup
:param offer_markup: Class "offerbody" from offer page markup
:type offer_markup: str
:return: Images of offer in list
:rtype: list
"""
html_parser = BeautifulSoup(offer_markup, "html.pars... | b04a1e886fb520f33a325c425dc8afcb4ee58950 | 76,163 |
import torch
def hyper_step(get_hyper_train, model, val_loss_func, val_loader, d_train_loss_d_w, elementary_lr, use_reg, args):
"""Estimate the hypergradient, and take an update with it.
:param get_hyper_train: A function which returns the hyperparameters we want to tune.
:param model: A function which... | be04347e3354eb3c7fb7662a0d40ebae81719df4 | 76,164 |
def sanitize_dirname(dirname, replacement=":"):
""" replace any illegal characters in a directory name and truncate directory name if needed
Args:
dirname: str, directory name to sanitze
replacement: str, value to replace any illegal characters with; default = ":"
Returns:
dirn... | 88e8c4e5b86d55078524740986677e40cdcb340e | 76,165 |
def main(list,file_path):
"""
:param list: list with top k documents names
:param file_path: path to stemmed corpus
:return: temp2: list with most cooccured terms
"""
print len(list)
temp = []
ngram =1
for x in range(len(list)):
with open(str(file_path) + str(list[x]), ... | 6b2bfb7a702939eba65a892b3d648a7381caf7b1 | 76,166 |
def Value(
body=None,
normalizer=None,
inject_actions=False,
inject_actions_n_layers=1,
inject_actions_dim=64,
mode='train',
):
"""Attaches a value head to a model body."""
if body is None:
body = lambda mode: []
if normalizer is None:
normalizer = lambda mode: []
def ActionInje... | dcafb26bf2d69ef69f991ac57f0eda58ca04ecfb | 76,167 |
def sorted(iterable, key=None, reverse=False):
"""Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
"""
result = list(iterable)
... | da629fec69583e7d4e56c1c25d710304d2e2e800 | 76,168 |
def create_saccade_sequence(frames, border_size, color):
"""Create a saccade sequence using border.
Parameters
----------
frames : list
given video sequence
border_size : int
border size in pixel
color : list
A three values list indicates border's color
Returns
... | a63815345d27cbf1c12b841b33bee1d35f27cc8d | 76,169 |
def nlless(parser, token):
"""
Remove all whitespace except for one space from content
"""
nodelist = parser.parse(('endnlless',))
parser.delete_first_token()
return NewlinelessNode(nodelist) | f14303407a793f7defec12f9cbb60fed4d6ba970 | 76,170 |
def to_text(value, encoding='utf-8', errors='ignore'):
"""Convert value to unicode, default encoding is utf-8
:param value: Value to be converted
:param encoding: Desired encoding
"""
if not value:
return ''
if isinstance(value, str):
return value
if isinstance(value, bytes)... | 23e6b32821e457af362a359046a3d397ce17aa3f | 76,171 |
def right_pressed(environment, dir_theta, inc, ambient=0.001):
""" Rotates theta by value inc CW. Function called after <right arrow>
pressed during interactive mode.
"""
environment.clearSources()
environment.updateAmbient(ambient)
update = dir_theta + inc + np.random.normal(scale=0.01 * ... | 2463cf820f564fb1f8152b736fec93b19f55d5c6 | 76,172 |
import torch
def pos_loss(inputs, target, mask, exp=False, use_rank=True, use_mse=False, use_dst=False, with_clip=True):
"""
Args:
inputs: [batch_size, seq_len]
target: [batch_size, seq_len]
mask: [batch_size, seq_len]
exp:
use_rank:
use_mse:
use_dst:
... | 9767396a20cf91eecd73b52ac8d8e72125c214af | 76,173 |
def filter_by_title(combined_list, pref_titles):
"""Include substrings of preferred titles to filter list."""
final_list = []
for dic in combined_list:
for title in pref_titles:
if title in dic['title'].lower():
final_list.append(dic)
return final_list | 3230dd06ed0e8f256cfa86643bde1e45518c9b5b | 76,174 |
def next_cell_state(x, y, board):
"""
Намира състоянието на клетката (0 или 1) през следващото поколение
Текущото състояние на клетката е board[x][y]
Изплзвайте функцията alive_cell_neighbours за да изчислите броя
живи съседни клетки, и чрез тази стойност да определите дали клетката
ще е жива ил... | b544e7e5fdc44faaf836e539a551c9ede6c7df45 | 76,175 |
def count_duplicates(samfile):
"""
Counts the number of duplicate reads in the file.
Looks at the FLAG field of each line in the file, breaks
it into its binary equivalent, and checks whether or not
the bit 10 (first bit = bit 0) has been set. A 1 in bit 10 indicates that
a read is a duplicate from PCR or Illum... | aabab6a2bba693e32031b1da317bf0561038b98f | 76,176 |
def drawPoly(src, points_list):
"""
Args:
src: input image
points_list: several points as a group, and this is a list of groups
Returns: an image
"""
image = src.copy()
reshaped_points_list = list()
for points in points_list:
points = np.asarray(points, dtype=np.in... | f0dd47d0748db33be3970b51f50776e5301ae891 | 76,177 |
import mimetypes
import io
def create_dataset_version(id_, **kwargs):
"""Create dataset's version
:param id_: The ID of the dataset resource
:type id_: str
:rtype: DatasetVersionSerializer
"""
stub = get_datasets_services_stub()
dataset = stub.RetrieveDataset(dataset_pb2.ID(id=id_))
ch... | df3ba5b0abe7084305cbaa6d75d2d88e27f2d0ce | 76,178 |
def get_publish_attribute(segment):
""" Get Publish attribute from input Tag object
Attribute:
segment (flame.PySegment)): flame api object
Returns:
bool: True or False
"""
tag_data = get_segment_data_marker(segment)
if not tag_data:
set_publish_attribute(segment, MARK... | f99d64c819086f797eb7dc3c37ef4931a266615d | 76,179 |
def dict_to_auth_config(data: dict) -> OAuth2AuthConfiguration:
"""Method to convert a dictionary to an Auth config dataclass. Currently only OAuth2AuthConfiguration is supported
but in the future other auth systems will be added.
Args:
data: dictionary containing auth config information
Retur... | 3e3292f0f73b183fe1cbff5f77fa99e0768642d2 | 76,181 |
def valid_string(val):
""" Expects unicode
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
[#x10000-#x10FFFF]
"""
for char in val:
try:
char = ord(char)
except TypeError:
raise NotValid("string")
if char == 0x09 or char == ... | a6e77c257f00d5cde678997917f39466813ab4fb | 76,182 |
def to_url(url: StrURL) -> URL:
"""
Converts a string to a :class:`~.URL` object.
Parameters
----------
url: :class:`str`
The URL to convert.
Returns
-------
:class:`~.URL`
The converted URL.
"""
return URL(url) if isinstance(url, str) else url | 4f045231ef8f46e9abcf7ef13bda728643249a62 | 76,183 |
def _require_message(func):
"""Decorator which forces the object to have an attached message"""
@utils.wraps(func)
def __(self, *args, **kwargs):
if not hasattr(self, "_message") or self._message is None:
raise RuntimeError("A message must be attached to this object")
return func... | f5d513e5da469a1f44f09f18eb8f714a97ebb9ea | 76,184 |
def fwhm2sigma(fwhm):
""" Convert a FWHM value to sigma in a Gaussian kernel.
Parameters
----------
fwhm : array-like
FWHM value or values
Returns
-------
sigma : array or float
sigma values corresponding to `fwhm` values
Examples
--------
>>> sigma = fwhm2sigma(... | a8fe3d2c2a2f28c6bbfedce1740c2549424d3687 | 76,185 |
def clean_file_record(raw_record):
# type: (str) -> str
"""
Removes NUL values from the raw_record
"""
return raw_record.replace('\x00', '') | 6eaad2c7e8e687ea038fe17c7f10618be6ebf4c1 | 76,186 |
def newimage(mode, size):
"""
A minimal reimplementation of the the PIL Image.new function.
Creates an Image object for the given mode and size.
"""
img = Image()
img.mode = mode
img.size = size
if mode=='L':
blank = 0
elif mode=='RGB':
blank = (0,0,0)
img._image_... | 488497af48fe2b95599969b2c8d0bb5b9cf11d5e | 76,187 |
def applyProperMotion(ra, dec, pmra, pmdec, dt, fixes=1):
"""
Apply proper motion to coordinates
Parameters
----------
ra, dec : float or array
Coordinates at reference epoch
pmra, pmdec : float or array
Proper motion in mas/yr.
dt : float
Elapsed time [yr]
f... | ba577f959515283fb1e78021a591084ed7917929 | 76,188 |
import xarray as xr
def _make_transform_dataarrays(translation, rotation):
""" Make translation and rotation DataArrays. """
translation = xr.DataArray(
translation,
{"cartesian_axis": ["x", "y", "z"]},
"cartesian_axis",
name="translation",
)
rotation = xr.DataArray(
... | 8032ec9838b2b0508ac7d3939317b1ce764552c0 | 76,189 |
def qft(N, print_circuit=False):
"""Return a circuit to compute the QFT for N qbits."""
assert N > 0
qft_circuit = QuantumCircuit(N, name="QFT")
if N == 3:
print("Special value N=3 for QFT circuit creation")
# Handle qbit 2
qft_circuit.h(2)
qft_circuit.cu1(pi / 2, 1, 2... | 1c2cde261768bbf4ccd259eb4663e8c516fdad1a | 76,191 |
import binascii
import hmac
import hashlib
def sign_message(message: str, key: str) -> str:
"""Signs a message with a key.
Args:
message:
String of the message we want to sign.
key:
String of the SHA256 hex encoded key we want to use to sign the message.
Retur... | 20eb1a354c9ec452a1f705f6f808082d55b4e331 | 76,193 |
import json
def parse_airdrop_data(data):
"""
parse the airdrop data
"""
airdrops_list = []
out = ''
err = ''
try:
json_data = json.loads(data)
for item in json_data:
address = list(item.keys())[0]
amount = list(item.values())[0]
aird = {... | 730b258031fa45dd309c69b05f2cf4939e7ed242 | 76,194 |
def alpha(args, node, r):
"""Return critical constant for given r, i and dependence assumption"""
value = (node.l * args.alpha * (node.m + r - 1)) / (node.root.l * node.m)
if args.dependence_assumption == POSITIVE:
return value
# Arbitrary dependence otherwise:
c = 1 + sum([1. / (node.m + j)... | 05ed7b12d35e9ebfa96aeaf36e5e7b55e59ad80a | 76,195 |
import mimetypes
def get_content_type(filename):
"""Figures out the content type of the given file."""
return mimetypes.guess_type(filename)[0] or "application/octet-stream" | 62a43b80b988dec999f88752a9945a4f51618672 | 76,196 |
def get_fingerprint(host, port, default=lambda h: None):
"""Find a cached key fingerprint for a given host/port"""
if port != 22:
host = '[%s]:%d' % (host, port)
try:
return fingerprints[host]
except KeyError:
f = fingerprints[host] = get_ssh_key(host) or \
get_ssh_ke... | 789d448909e5006136e71672a0f638c6cf8095c2 | 76,197 |
from typing import Union
import requests
def query_protein(protein_id: str) -> Union[ElementTree.ElementTree, None]:
"""Retrieve the XML entry for a given protein.
Parameters
----------
protein_id :
The UniProt ID of the protein to look up.
Returns
-------
:
An ElementTre... | 3145b14c3a372120ace727aedfff8f99a9c90495 | 76,198 |
def _parse_memory(used_memory):
"""
convert the used memory in bytes to ressource units
:param used_memory: amount of used memory in bytes
:type used_memory: float
:return: number of MRU
:rtype: float
"""
return used_memory / GiB | 5cd0da8070c925db192579fc8c4e9b3d4f48c9f7 | 76,199 |
async def list_requests(
api_request: Request,
auth=Depends(Auth),
) -> list:
"""
List all the requests the current user has access to see.
"""
# get the resources the current user has access to see
token_claims = await auth.get_token_claims()
username = token_claims["context"]["user"]["... | 55d0ac743d7472bf34a5198eedc9699c3a316b22 | 76,200 |
def _footer():
"""HTML page footer."""
footer = """\
<hr />
<a href="%s">Tests index page</a><br />
<a href="%s">Chaste project website</a>
</body>
</html>""" % (_our_url, _trac_url)
return footer | 0dd05378763d80e4eebaf6890c610d13ee599496 | 76,201 |
def get_img_from_byte_stream(binary_stream, is_gray_scale=True):
"""
Возвращает изображение.
Params:
binary_stream - бинарный поток данных изображения
is_gray_scale - флаг определяющий необходимость преобразования
изображения в оттенки серого (черн... | d9f0ee8c80186a1fd9b0e9224ac16f95e03b1521 | 76,202 |
def movie_body_count_r_classify(data_set="movie_body_count"):
"""Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R."""
data = movie_body_count()["Y"]
X = data[["Year", "Body_Count"]]
... | c8a3a9eeaeb30a2883f29ea1d1b7e822f18b74ce | 76,203 |
def prom_registry():
"""
Prometheus Registry for plugin tests
"""
return CollectorRegistry(auto_describe=True) | 7a217f79a837fd205696ef45dacf595db43f62c7 | 76,205 |
import itertools
from typing import Dict
def generate_alternatives(n_persons):
"""
Generate a dictionary of CDAP alternatives.
The keys are the names of the patterns, and
the values are the alternative code numbers.
Parameters
----------
n_persons : int
Returns
-------
Dict
... | 4be033be696db0955db05375eb49206d95a97f07 | 76,207 |
from .xml_backend import XmlBackend as Backend
from .xml_backend_old import XmlBackendOld as Backend
from .csv_backend import CsvBackend as Backend
from .sportstracker_backend import SportstrackerBackend as Backend
def get_backend(name):
"""Returns a backend corresponding to name. Possible names are:
xml, xml... | d4c633b948bb391c382ccde836e6418ab4a95e45 | 76,208 |
def get_calibration_sets(database: Session = Depends(get_database)):
"""Returns calibration sets"""
return crud_calibration_set.get_calibration_sets(database) | 9ed115b5a138b3a7f083599bf8f4ca383b5638d9 | 76,209 |
def get_res_attr_val(api, resource_name, target_attr_name):
"""
Get value of attribute if it exists
:param CloudShellAPISession api:
:param resource_name:
:param target_attr_name:
:return:
"""
target_attr_obj = _get_target_attr_obj(api, resource_name, target_attr_name)
if target_attr... | d029f8c34d78d51936010ee281e746d454e29e98 | 76,210 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.