content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gcp_iam_organization_role_permission_remove_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""
Remove permissions from custom organization role.
Args:
client (Client): GCP API client.
args (dict): Command arguments from XSOAR.
Returns:
CommandResults: outpu... | 5,331,900 |
def MainLoop(N: int, save_every: int = False, plot_histogram: bool = False):
"""MainLoop
Parameters
==========
N: int
Number of iterations
save_every: int or False
if not False, save a snapshot of the simulation every `save_every`
iterations
plot_histogram: bo... | 5,331,901 |
async def test_server_failure_with_error(cli: TestClient) -> None:
"""Test invalid response from RTSPtoWebRTC server."""
assert isinstance(cli.server, TestServer)
cli.server.app["response"].append(
aiohttp.web.json_response({"status": 1, "payload": "a message"}, status=502)
)
client = WebCl... | 5,331,902 |
def command_coverage_html(args):
"""
:type args: CoverageConfig
"""
output_files = command_coverage_combine(args)
for output_file in output_files:
dir_name = 'test/results/reports/%s' % os.path.basename(output_file)
env = common_environment()
env.update(dict(COVERAGE_FILE=ou... | 5,331,903 |
def do_publish(dry_run: bool):
"""Run the gradle command to publish to our maven repo."""
run_command(['./gradlew', 'publish'], dry_run) | 5,331,904 |
def get_hostname(ipv) -> str:
"""
Get hostname from IPv4 and IPv6.
:param ipv: ip address
:return: hostname
"""
return socket.gethostbyaddr(ipv)[0] | 5,331,905 |
def load_model():
"""
Load CLIP model into memory.
Will download the model from the internet if it's not found in `WAGTAIL_CLIP_DOWNLOAD_PATH`.
"""
device = torch.device("cpu")
model, preprocess = clip.load("ViT-B/32", device, download_root=DOWNLOAD_PATH)
return model, device, preprocess | 5,331,906 |
def exception_response(ex: Exception):
"""Generate JSON payload from ApiException or Exception object."""
if not ex:
app.logger.error("Function received argument: None!")
return __make_response(
500,
{
"error" : "Unknown",
"details" : "ap... | 5,331,907 |
def test_raster_module(test_dir):
"""
tests the following functions from the raster module:
spatially_match
cilp_and_snap
project_resample
enf_rastlist
is_rast
raster_overlap
clip_and_snap
null_define
to_nump... | 5,331,908 |
def check(pack, inst):
"""
A function to check if an instruction is present in the packet
Input:
- pack: The packet to be checked
- inst: The instruction
Output:
Returns True if the instruction is present in the packet else Fase
"""
inst_key = getPacketKey(inst[0])
for key ... | 5,331,909 |
def test_calc_eirp():
"""
Unit test for calculating the Equivalent Isotropically Radiated Power.
"""
power = 30 # watts
antenna_gain = 38 # dB
# losses = 4 #dB
assert round(calc_eirp(power, antenna_gain)) == 68 | 5,331,910 |
def find_invalid_filenames(filenames, repository_root):
"""Find files that does not exist, are not in the repo or are directories.
Args:
filenames: list of filenames to check
repository_root: the absolute path of the repository's root.
Returns: A list of errors.
"""
errors = []
for... | 5,331,911 |
def test_constructor():
""" """
args = CfgNode()
args.img_name_unique = True
args.taxonomy = 'oracle' # pretend testing a model training in own taxonomy (oracle),
# not in unified universal taxonomy
args.vis_freq = 1
args.model_path = '/path/to/dummy/model'
data_list = get_dummy_datalist()
dataset_name = 'ca... | 5,331,912 |
def get_score(true, predicted):
"""Returns F1 per instance"""
numerator = len(set(predicted.tolist()).intersection(set(true.tolist())))
p = numerator / float(len(predicted))
r = numerator / float(len(true))
if r == 0.:
return 0.
return 2 * p * r / float(p + r) | 5,331,913 |
def check_ratio_argv(_argv):
"""Return bool, check optional argument if images are searched by same ratio"""
# [-1] To avoid checking 3 places at one, this argument is always last
return bool(_argv[-2] in ARGV["search by ratio"] and _argv[-1] in ARGV["search by ratio"]) | 5,331,914 |
def binary_erosion(input, structure = None, iterations = 1, mask = None,
output = None, border_value = 0, origin = 0, brute_force = False):
"""Multi-dimensional binary erosion with the given structure.
An output array can optionally be provided. The origin parameter
controls the placement of th... | 5,331,915 |
def chord_to_freq_ratios(chord):
"""Return the frequency ratios of the pitches in <chord>
Args:
chord (tuple of ints): see <get_consonance_score>.
Returns:
list of ints:
"""
numerators = [JI_NUMS[i] for i in chord]
denoms = [JI_DENOMS[i] for i in chord]
denominator = get_lc... | 5,331,916 |
def proto_factor_cosine(local_proto, global_proto):
"""
[C, D]: D is 64 or 4
"""
# factor = 1
norm_local = torch.norm(local_proto, dim=-1, keepdim=False)
norm_global = torch.norm(global_proto, dim=-1, keepdim=False) # [C]
factor_refined = torch.sum(local_proto*global_proto, dim=-1, keepdim=F... | 5,331,917 |
def urlparse(d, keys=None):
"""Returns a copy of the given dictionary with url values parsed."""
d = d.copy()
if keys is None:
keys = d.keys()
for key in keys:
d[key] = _urlparse(d[key])
return d | 5,331,918 |
def doFDR(pvalues,
vlambda=numpy.arange(0,0.95,0.05),
pi0_method="smoother",
fdr_level=None,
robust=False,
smooth_df = 3,
smooth_log_pi0 = False):
"""modeled after code taken from http://genomics.princeton.edu/storeylab/qvalue/linux.html.
I did no... | 5,331,919 |
def sequence(ini, end, step=1):
""" Create a sequence from ini to end by step. Similar to
ee.List.sequence, but if end != last item then adds the end to the end
of the resuting list
"""
end = ee.Number(end)
if step == 0:
step = 1
amplitude = end.subtract(ini)
mod = ee.Number(ampl... | 5,331,920 |
def kBET_single(
matrix,
batch,
k0=10,
knn=None,
verbose=False
):
"""
params:
matrix: expression matrix (at the moment: a PCA matrix, so do.pca is set to FALSE
batch: series or list of batch assignemnts
returns:
kBET observed rejection rate
... | 5,331,921 |
def get_eye_center_position(face: Face) -> Tuple[numpy.int64, numpy.int64]:
"""Get the center position between the eyes of the given face.
Args:
face (:class:`~.types.Face`):
The face to extract the center position from.
Returns:
Tuple[:data:`numpy.int64`, :data:`numpy.int64`]:... | 5,331,922 |
def test_request_scope_interface():
"""
A Request can be instantiated with a scope, and presents a `Mapping`
interface.
"""
request = Request({"type": "http", "method": "GET", "path": "/abc/"})
assert request["method"] == "GET"
assert dict(request) == {"type": "http", "method": "GET", "path"... | 5,331,923 |
def fail(msg):
"""Prints the error message and exits"""
sys.stderr.write('\033[91m' + msg + '\033[0m\n')
exit(1) | 5,331,924 |
def esc_quotes(strng):
""" Return the input string with single and double quotes escaped out.
"""
return strng.replace('"', '\\"').replace("'", "\\'") | 5,331,925 |
def gen_fake_game_data():
"""Creates an example Game object"""
game = Game(
gameday_id='2014/04/04/atlmlb-wasmlb-1',
venue='Nationals Park',
start_time=parser.parse('2014-04-04T13:05:00-0400'),
game_data_directory='/components/game/mlb/year_2014/month_04/day_04/gid_2014_04_04_atl... | 5,331,926 |
def kill_entity(entity: EntityID):
"""
Add entity to the deletion stack and removes them from the turn queue.
"""
# if not player
if entity != get_player():
# delete from world
delete_entity(entity)
turn_queue = hourglass.get_turn_queue()
# if turn holder create new... | 5,331,927 |
def extract_data(url,file_path):
"""
extract data from kaggle
"""
#setup session
with session() as c:
#post request
c.post('https://www.kaggle.com/account/login',data=payload)
#open file to write
with open(file_path,'wb') as handle:
#get request
... | 5,331,928 |
def unsafe_load_all(stream):
"""
Parse all YAML documents in a stream
and produce corresponding Python objects.
Resolve all tags, even those known to be
unsafe on untrusted input.
"""
return load_all(stream, UnsafeLoader) | 5,331,929 |
def random_name(url, type):
"""
对文件或文件夹进行随机重命名(防止产生因同名而无法重命名的问题)(具体类型则根据所给的文件类型type决定,用户调用相应的方法后type自动赋值)
:param url: 用户传入的文件夹的地址
:return: 返回文件夹中所有文件或文件夹重命名之前的名字的列表
"""
if not os.path.exists(url):
url=resource_manager.Properties.getRootPath() + resource_manager.getSeparator() +u... | 5,331,930 |
def peakdet(v, delta, x = None):
"""
Converted from MATLAB script at http://billauer.co.il/peakdet.html
"""
maxtab = []
mintab = []
if x is None:
x = arange(len(v))
v = asarray(v)
if len(v) != len(x):
sys.exit('Input vectors v and x must have same length')
if not ... | 5,331,931 |
def jaccard(set1, set2):
"""
computes the jaccard coefficient between two sets
@param set1: first set
@param set2: second set
@return: the jaccard coefficient
"""
if len(set1) == 0 or len(set2) == 0:
return 0
inter = len(set1.intersection(set2))
return inter / (len(set1) + le... | 5,331,932 |
def create_cluster_custom_object(group: str, version: str, plural: str,
resource: Dict[str, Any] = None,
resource_as_yaml_file: str = None,
secrets: Secrets = None) -> Dict[str, Any]:
"""
Delete a custom object in... | 5,331,933 |
def test_greater_than_equal_to_validator_image_container():
""" Test the greater than equal to validator with an image container """
validator = greater_than_equal_to_validator(1.5)
assert str(validator) == "Value(s) must be greater than or equal to 1.5"
image_container = NumpyImageContainer(image=np.a... | 5,331,934 |
def normalize_flags(flags, user_config):
"""Combine the argparse flags and user configuration together.
Args:
flags (argparse.Namespace): The flags parsed from sys.argv
user_config (dict): The user configuration taken from
~/.artman/config.yaml.
Returns:
... | 5,331,935 |
def setup_maxbolthist(ax): # pragma: no cover
"""Builds the simulation velocity histogram
visualisation pane.
Parameters
----------
ax: Axes object
The axes position that the pane should be placed in.
"""
ax.step([0], [0], color="#34a5daff")
ax.set_ylabel("PDF", fontsize=16)
... | 5,331,936 |
def printResultTable(resObj):
"""
Print a result table (similar to the web version) to *stdout*, like::
# ref prop np components(s)
---- -------------------- ------ ---- ----------------------------------------
0 Krolikowska2012 dens 65 1-ethyl-3-meth... | 5,331,937 |
def get_fast_annotations():
"""
Title: Get Fast Annotations
Description : Get annotations for a list of sequences in a compressed form
URL: /sequences/get_fast_annotations
Method: GET
URL Params:
Data Params: JSON
{
"sequences": list of str ('ACGT')
the li... | 5,331,938 |
def to_numeric(arg):
"""
Converts a string either to int or to float.
This is important, because e.g. {"!==": [{"+": "0"}, 0.0]}
"""
if isinstance(arg, str):
if '.' in arg:
return float(arg)
else:
return int(arg)
return arg | 5,331,939 |
def test_slurm_free_format(tmp_path: Path):
"""Test the slurm script generation with the user passes its own script."""
free_format = """#!/bin/bash
#SBATCH -N 1
#SBATCH -t 00:05:00
#SBATCH -p godzilla
module load awesome-package/3.14.15
"""
scheduler = {"name": "slurm", "free_format": free_format}
c... | 5,331,940 |
def get_kde_polyfit_estimator(samples, N=100000, bandwidth=200, maxlength=150000, points=500, degree=50):
"""多項式近似したバージョンを返すやつ 一応両方かえす"""
f = get_kde_estimator(samples, N, bandwidth)
x = np.linspace(1, maxlength, points)
z = np.polyfit(x, f(x), degree)
return (lambda x: np.where(x<=maxlength, np.pol... | 5,331,941 |
def read_tracker(file_name):
"""
"""
with open(file_name, "r") as f:
return int(f.readline()) | 5,331,942 |
def MixR2VaporPress(qv, p):
"""Return Vapor Pressure given Mixing Ratio and Pressure
INPUTS
qv (kg kg^-1) Water vapor mixing ratio`
p (Pa) Ambient pressure
RETURNS
e (Pa) Water vapor pressure
"""
return qv * p / (Epsilon + qv) | 5,331,943 |
def sigmoid_derivative(dA, cache):
"""
Implement the backward propagation for a single SIGMOID unit.
Arguments:
dA -- post-activation gradient, of any shape
cache -- 'Z' where we store for computing backward propagation efficiently
Returns:
dZ -- Gradient of the cost with respect to Z
... | 5,331,944 |
def parse_group(tx: neo4j.Transaction, group: dict):
"""Parse a group object.
Arguments:
tx {neo4j.Transaction} -- Neo4j Transaction
group {dict} -- Single group object from the bloodhound json.
"""
properties = group['Properties']
identifier = group['ObjectIdentifier']
members ... | 5,331,945 |
def get_params(config, alphabet):
"""
:param config: config
:param alphabet: alphabet dict
:return:
"""
# get algorithm
config.learning_algorithm = get_learning_algorithm(config)
# save best model path
config.save_best_model_path = config.save_best_model_dir
if config.test is Fa... | 5,331,946 |
def part2(lines, rounds=100):
"""
>>> data = load_example(__file__, '24')
>>> part2(data, 0)
10
>>> part2(data, 1)
15
>>> part2(data, 2)
12
>>> part2(data, 3)
25
>>> part2(data, 4)
14
>>> part2(data, 5)
23
>>> part2(data, 6)
28
>>> part2(data, 7)
4... | 5,331,947 |
def binary_search(
items,
target_key,
target_key_hi=None,
key=None,
lo=None,
hi=None,
target=Target.any,
):
"""
Search for a target key using binary search and return (found?,
index / range).
The returned index / range is as follows according to t... | 5,331,948 |
def test_wep_open_auth(dev, apdev):
"""WEP Open System authentication"""
hostapd.add_ap(apdev[0]['ifname'],
{ "ssid": "wep-open",
"wep_key0": '"hello"' })
dev[0].connect("wep-open", key_mgmt="NONE", wep_key0='"hello"',
scan_freq="2412")
hwsim_ut... | 5,331,949 |
def func_real_dirty_gauss(dirty_beam):
"""Returns a parameteric model for the map of a point source,
consisting of the interpolated dirty beam along the y-axis
and a sinusoid with gaussian envelope along the x-axis.
This function is a wrapper that defines the interpolated
dirty beam.
Parameter... | 5,331,950 |
def shortest_path(graph, a_node, b_node):
""" code by Eryk Kopczynski """
front = deque()
front.append(a_node)
came_from = {a_node: [a_node]}
while front:
cp = front.popleft()
for np in graph.neighbors(cp):
if np not in came_from:
front.append(np)
came_from[np] = [came_from[cp], ... | 5,331,951 |
def rank_compute(prediction, att_plt, key, byte):
"""
- prediction : predictions of the NN
- att_plt : plaintext of the attack traces
- key : Key used during encryption
- byte : byte to attack
"""
(nb_trs, nb_hyp) = prediction.shape
idx_min = nb_trs
min_rk = 255
... | 5,331,952 |
def purelin(n):
"""
Linear
"""
return n | 5,331,953 |
def arrayDimension(inputArray):
"""Returns the dimension of a list-formatted array.
The dimension of the array is defined as the number of nested lists.
"""
return len(arraySize(inputArray)) | 5,331,954 |
def process_data(records, root) -> bool:
"""Creates the xml file that will be imported in pure."""
for record in records:
item_metadata = record["metadata"]
# If the rdm record has a uuid means that it was imported from pure - REVIEW
if "uuid" in item_metadata:
continue
... | 5,331,955 |
def bitbang_backdoor(d, handler_address, hook_address = 0x18ccc, verbose = False):
"""Invoke the bitbang_backdoor() main loop using another debug interface.
To avoid putting the original debug interface into a stuck state, this
installs the bitbang_backdoor as a mainloop hook on a counter, to spin
the ... | 5,331,956 |
def upload_object(object_location: ObjectLocation, stream: io.BytesIO) -> None:
"""
Upload the given data stream as an object to s3.
:param object_location: Location of the object to create/update.
:param stream: Byte steam of the object data.
"""
s3 = boto3.client("s3")
result = s3.upload_... | 5,331,957 |
def hopcroft(G, S):
"""Hopcroft's algorthm for computing state equivalence.
Parameters
----------
G : fully deterministic graph
S : iterable
one half of the initial (bi)partition
Returns
-------
Partition
"""
sigma = alphabet(G)
partition = Partition(list(G))
p1... | 5,331,958 |
def TVRegDiff(data, itern, alph, u0=None, scale='small', ep=1e-6, dx=None,
plotflag=_has_matplotlib, diagflag=True, precondflag=True,
diffkernel='abs', cgtol=1e-4, cgmaxit=100):
"""
Estimate derivatives from noisy data based using the Total
Variation Regularized Numerical Differe... | 5,331,959 |
def replaceidlcode(lines,mjd,day=None):
"""
Replace IDL code in lines (array of strings) with the results of code
execution. This is a small helper function for translate_idl_mjd5_script().
"""
# day
# psfid=day+138
# domeid=day+134
if day is not None:
ind,nind = dln.where( (l... | 5,331,960 |
def test(
model: nn.Module,
classes: dict,
data_loader: torch.utils.data.DataLoader,
criterion: nn.Module,
# scheduler: nn.Module,
epoch: int,
num_iteration: int,
use_cuda: bool,
tensorboard_writer: torch.utils.tensorboard.SummaryWriter,
name_step: str,
):
""" Test a given mo... | 5,331,961 |
async def test_media_player_update(
hass: HomeAssistant,
ufp: MockUFPFixture,
doorbell: Camera,
unadopted_camera: Camera,
):
"""Test media_player entity update."""
await init_entry(hass, ufp, [doorbell, unadopted_camera])
assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1)
new_came... | 5,331,962 |
def get_grad_spherical_harmonics(xyz, l, m):
"""Compute the gradient of the Real Spherical Harmonics of the AO.
Args:
xyz : array (Nbatch,Nelec,Nrbf,Ndim) x,y,z, distance component of each
point from each RBF center
l : array(Nrbf) l quantum number
m : array(Nrbf) m quantum... | 5,331,963 |
def send_photo(self, user_ids, filepath, thread_id=None):
"""
:param self: bot
:param filepath: file path to send
:param user_ids: list of user_ids for creating group or
one user_id for send to one person
:param thread_id: thread_id
"""
user_ids = _get_user_ids(self, user_ids)
if not... | 5,331,964 |
def references_from_string(string: str) -> List[
Union[InputReference, TaskReference, ItemReference]
]:
"""Generate a reference object from a reference string
Arguments:
string {str} -- A reference string (eg: `{{inputs.example}}`)
Raises:
ValueError: Input string cannot be... | 5,331,965 |
def fillTriangle(canvas, ax, ay, bx, by, cx, cy):
"""
helper for gridViewable
based on
http://www-users.mat.uni.torun.pl/~wrona/3d_tutor/tri_fillers.html
assumes a->b->c is ccw, ax<bx, ax<cx
"""
dxb = (by-ay)/(bx-ax)
dxc = (cy-ay)/(cx-ax)
if cx > bx + 1:
secondx = int(bx)
... | 5,331,966 |
def arrange_images(normalized_posters, blur_factor, blur_radius):
"""
Arranges images to create a collage.
Arguments:
norm_time_posters: tuple(float, PIL.Image)
Normalized instances of time and area for time and posters respectively.
blur_factor:
Number of times to a... | 5,331,967 |
def remove_files(vectors):
"""Remove all files derived from the vectors file."""
for fname in glob.glob("%s.*" % vectors):
os.remove(fname) | 5,331,968 |
def get_zomato_data_for_google_restaurants(rest_dict):
""" Finds restaurants from the Google results that did not
intersect with Zomato results and fills in Google data
for them one at a time
"""
for restaurant in rest_dict.keys():
# Search for matching restaurant using coordinates, name, an... | 5,331,969 |
def make_text(text, position=(0, 0, 0), height=1):
"""
Return a text object at the specified location with a given height
"""
sm = SpriteMaterial(map=TextTexture(string=text, color='white', size=100, squareTexture=False))
return Sprite(material=sm, position = position, scaleToTexture=True, scale=[1,... | 5,331,970 |
def fix_valid(log_date: str) -> None:
"""修复设定is_valid值,正常的设定为1
Args:
log_date: 日期
"""
collection = water_heater.get_summary_save()
for item in collection.find({'log_date': log_date}):
id = item['_id']
print(id)
if item['cumulative_heat_time'] < 0 or item['cumulative... | 5,331,971 |
async def bot_restarter():
""" If bot process is dead, restart """
logger.info('Started bot restarter')
while 1:
await asyncio.sleep(5)
if runner.bot_process is None or runner.bot_process.poll() is not None:
logger.info('Restarting bot because it seems to have ended.')
... | 5,331,972 |
def get_features(user_features, documents, ARGS, BOW = False, Conversational = False, User = False, SNAPSHOT_LEN = False, Questions = False, COMMENT_LEN = True):
"""
Generates Features:
Type of Features:
- BOW: bag of words features
- Conversational: features extracted from the conv... | 5,331,973 |
def incomeStat(headers):
"""
收益统计
:param headers:
:return:
"""
time.sleep(0.3)
url = f'https://kd.youth.cn/wap/user/balance?{headers["Referer"].split("?")[1]}'
try:
response = requests_session().get(url=url, headers=headers, timeout=50).json()
print('收益统计')
print(response)
if response['s... | 5,331,974 |
def t_matrix(phi, theta, psi, sequence):
""" Return t_matrix to convert angle rate to angular velocity"""
if sequence == 'ZYX':
t_m = np.array([[1, np.sin(phi)*np.tan(theta), np.cos(phi)*np.tan(theta)],\
[0, np.cos(phi), -np.sin(phi)],\
[0, np.sin(phi)/np.cos(... | 5,331,975 |
def point_in_fence(x, y, points):
"""
计算点是否在围栏内
:param x: 经度
:param y: 纬度
:param points: 格式[[lon1,lat1],[lon2,lat2]……]
:return:
"""
count = 0
x1, y1 = points[0]
x1_part = (y1 > y) or ((x1 - x > 0) and (y1 == y)) # x1在哪一部分中
points.append((x1, y1))
for point in points[1:]... | 5,331,976 |
def test_location_detail(location: Location):
"""test_location_detail.
Args:
location (Location): location
"""
assert (reverse("api:location-detail",
kwargs={"pk": location.id
}) == f"/api/locations/{location.id}")
assert resolve(
f"/ap... | 5,331,977 |
def parse_prior(composition, alphabet, weight=None):
"""Parse a description of the expected monomer distribution of a sequence.
Valid compositions:
* None or 'none'
No composition sepecified
* 'auto' or 'automatic'
Use the typical average distribution
for proteins and an equipr... | 5,331,978 |
def get_queues(prefix=None):
"""
Gets a list of SQS queues. When a prefix is specified, only queues with names
that start with the prefix are returned.
:param prefix: The prefix used to restrict the list of returned queues.
:return: A list of Queue objects.
"""
if prefix:
queue_iter... | 5,331,979 |
def _over_descriptions(
symbol_table: SymbolTable,
) -> Iterator[Tuple[Optional[Symbol], Description]]:
"""
Iterate over all the descriptions in the meta-model.
The symbol indicates the symbol that encompasses the description (*e.g.*
a class if the description is related to a member or a property).... | 5,331,980 |
def _genNodesNormal(numNodes=None, center=None, standardDeviation=None):
"""
Generate randomized node using Normal distribution within a bounding area
Parameters
----------
numNodes: int
Required, number of nodes to be generated
centerLat: float, Required
Latitude of the center point
centerLon: float, Requi... | 5,331,981 |
def util_test_normalize(mean, std, op_type):
"""
Utility function for testing Normalize. Input arguments are given by other tests
"""
if op_type == "cpp":
# define map operations
decode_op = c_vision.Decode()
normalize_op = c_vision.Normalize(mean, std)
# Generate dataset... | 5,331,982 |
def calc_sub_from_constant(func, in_data, **kwargs):
"""[SubFromConstant](https://docs.chainer.org/en/v4.3.0/reference/generated/chainer.functions.add.html)
See the documentation for [AddConstant](#addconstant)
"""
return _calc(func, in_data, **kwargs) | 5,331,983 |
def mask_distance_matrix(dmat, weight_bins=weight_bins):
"""
Answer: yep, a larger weight is assigned to a pair of residues forming a contact.
I assigned 20.5, 5.4, 1 to the distance 0-8, 8-15, and >15, respectively, for residue pairs (i, j) where |i-j| >=24.
These numbers were derived from simple stati... | 5,331,984 |
def get_output():
"""Return the set output setting."""
return _output | 5,331,985 |
def cash_grouped_nb(target_shape, cash_flow_grouped, group_lens, init_cash_grouped):
"""Get cash series per group."""
check_group_lens(group_lens, target_shape[1])
out = np.empty_like(cash_flow_grouped)
from_col = 0
for group in range(len(group_lens)):
to_col = from_col + group_lens[group]
... | 5,331,986 |
def agreement():
"""Input for Accepting license
"""
form = LicenseForm()
if form.validate_on_submit():
gluu_settings.db.set("ACCEPT_GLUU_LICENSE", "Y" if form.accept_gluu_license.data else "N")
return redirect(url_for(wizard_steps.next_step()))
with open("./LICENSE", "r") as f:
... | 5,331,987 |
def _patch_output():
"""
Patches 'google.protobuf.text_format.PrintFieldValue' to support redacted
fields.
"""
global _PATCHED
if not _PATCHED:
_PATCHED = True
_PrintFieldValue = google.protobuf.text_format.PrintFieldValue
def PrintFieldValueRedacted(field, value, out, *args, **kwargs):
field_... | 5,331,988 |
def p_stmtdelim(p):
"""stmtdelim : mb_stmtdelim NEWLINE
stmtdelim : mb_stmtdelim SEMI""" | 5,331,989 |
def _BuildTargets(targets, jobs_count):
"""Builds target with Clang coverage instrumentation.
This function requires current working directory to be the root of checkout.
Args:
targets: A list of targets to build with coverage instrumentation.
jobs_count: Number of jobs to run in parallel for compilatio... | 5,331,990 |
def enlarge_thumbnails(apps, schema_editor):
"""Enlarge existing thumbnails to the new size."""
File = apps.get_model("core", "File")
for file_ in File.objects.all():
image = Image.open(file_.file)
image.thumbnail((400, 400), Image.ANTIALIAS)
thumb = io.BytesIO()
image.save... | 5,331,991 |
def rotmat2quat(mat: torch.Tensor) -> torch.Tensor:
"""Converts rotation matrix to quaternion.
This uses the algorithm found on
https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion
, and follows the code from ceres-solver
https://github.com/ceres-solver/ceres-solver/blob/master/include/ceres/rot... | 5,331,992 |
def _release_lock():
"""
Release the module-level lock acquired by calling _acquireLock().
"""
if _lock:
_lock.release() | 5,331,993 |
def equalize(image):
"""
Equalize the image histogram. This function applies a non-linear
mapping to the input image, in order to create a uniform
distribution of grayscale values in the output image.
Args:
image (PIL image): Image to be equalized
Returns:
image (PIL image), Eq... | 5,331,994 |
def validate_output(value):
"""Validate "output" parameter."""
if value is not None:
if isinstance(value, str):
value = value.split(",")
# filter out empty names
value = list(filter(None, value))
return value | 5,331,995 |
def start_monitoring_hpc(
config_infra,
ssh_config,
monitoring_options,
simulate,
**kwargs): # pylint: disable=W0613
""" Starts monitoring using the HPC Exporter """
if not simulate and "hpc_exporter_address" in ctx.instance.runtime_properties and \
ctx.inst... | 5,331,996 |
def dummy_img(w, h, intensity=200):
"""Creates a demodata test image"""
img = np.zeros((int(h), int(w)), dtype=np.uint8) + intensity
return img | 5,331,997 |
def getHandler(database):
"""
a function instantiating and returning this plugin
"""
return Events(database, 'events', public_endpoint_extensions=['insert']) | 5,331,998 |
def RegQueryValueEx(key, valueName=None):
""" Retrieves the type and data for the specified registry value.
Parameters
key A handle to an open registry key.
The key must have been opened with the KEY_QUERY_VALUE access right
valueName The name of the registry value. it is opti... | 5,331,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.