content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def leap(year):
"""Return true if the year was a leap year under the system of Sarkawag"""
if year < 533:
return False
return year % 4 == 0 | 010a61af2331dc07d1f04a5645f6e8b4172cbaf2 | 645,506 |
import uuid
def _generate_random_basename():
"""Генерирует случайный basename."""
return uuid.uuid4().hex.upper()[0:6] | 72327ab579a108f4382b7083388373e51ee05b43 | 645,507 |
import os
def parse_args(parser):
"""
:param parser: ArgumentParser
Object that holds cmd arguments.
:return: tuple
Values of arguments.
"""
args = parser.parse_args()
input_path = str(args.input_path)
assert os.path.exists(input_path)
return input_path | 61207beff866efbb8ebe7def5eed1ca2d2ce5fe1 | 645,508 |
def input_validation(input):
"""
This function is used to test the stock ticker inputs and validate that they
pass the two key characteristics tests: being less than 5 characters in length
and having no digits.
@param: input is a string argument that represents the given input the c... | b89845fcdaa7f11781d24f500767645e51b97100 | 645,510 |
def get_currency_for_stripe(currency):
"""Convert Saleor's currency format to Stripe's currency format.
Stripe's currency is using lowercase while Saleor is using uppercase.
"""
return currency.lower() | 733a12d69af02d6ed3c55d5a2328cf55cc58b75b | 645,511 |
def hinderedRotor(scanLog, pivots, top, symmetry=None, fit='best'):
"""Read a hindered rotor directive, and return the attributes in a list"""
return [scanLog, pivots, top, symmetry, fit] | 8bf0a44f5daaf1276aaf5a3d311c153ca6242267 | 645,512 |
import io
def tour_WIN_TT_to_param(inst, isStringIO=True):
"""
Convert WIN_TT values to a GMPL representation of a parameter.
Used by `solvemwts` in Phase 2 dat file creation.
:param inst: Model instance
:param isStringIO: True (default) to return StringIO object, False to return string
:ret... | 3ad9e31ce6baed988aac11f64e6c10361db82f9e | 645,513 |
import os
def get_names_in(directory):
"""A list of names for all items in that directory"""
try:
return os.listdir(directory)
except (IOError, OSError):
return [] | 8c2b9e94965bc00cd18d5473c264e46ed5af3f8c | 645,514 |
def _forward_attr(attr):
"""Return True if attribute should be passed to legacy class"""
# Pass Iterable magic methods on to the Numpy array. We can't pass
# `__getitem__` (and consequently `__setitem__`, `__delitem__`) on because
# `Statevector` implements them itself.
if attr[:2] == '__' or attr ... | 27df02a786e03264133da6b83eb365f425a08c4c | 645,517 |
import requests
def get_worldstate():
"""Get world state json.
Return a very complicated nested array
"""
wsurl = 'http://content.warframe.com/dynamic/worldState.php'
ws = requests.get(wsurl, timeout=30).json()
return ws | a84711418f916beb67c4d05992f2472a3d93611d | 645,518 |
import re
def getWineConsumption(html):
"""
Parameters
----------
html : string
Returns
-------
capacity : int
"""
result = re.search(r'GlobalMenu_WineConsumption"\s*class="rightText">\s*(\d+)\s', html)
if result:
return int(result.group(1))
return 0 | 79895bb092e54bc238a1cf91a85c6709ab8de10a | 645,519 |
import os
def _preprocess(string, environ=None):
"""Preprocesses a string.
Preprocesses a string, by replacing `${VARNAME}` with
`os.environ['VARNAME']` and ~ with the path to the user's
home directory.
Parameters
----------
string : str
String object to _preprocess
environ :... | 5127351c3318ef681fb34da379114015d75d0daa | 645,521 |
import os
import subprocess
def simple_bwa(input_file, temp_dir, reference_file):
"""
Simple BWA
"""
bwa_output = os.path.join(temp_dir, input_file.samples_name + ".align_to_ref.bam")
bwa_command = " bwa mem {0} {1} | samtools view -bS - > {2}".format(reference_file, input_file.pilon_fasta, bw... | 70b2bd59376152e35ee32e3f8ec1b926af2b6a0c | 645,522 |
import os
from pathlib import Path
def recursively_create_path(dict_input: dict) -> dict:
"""Convert all the entries of the dict_input that are file into Path objects."""
for key, val in dict_input.items():
if isinstance(val, str):
if os.path.isdir(val) or os.path.isfile(val):
... | ea05731255be197f2d6dbda6c5fd17115704a1f8 | 645,523 |
def determineLeadValidity(playedCards, card, hand):
"""
Given the cards that have been played so far, as well as the player's hand,
determine whether the card they have attempted to lead is valid.
"""
# must lead 2C if have it for first trick
if "01c" in hand and card != "01c":
return [F... | 918dfebb0d2ad0de4cb848b9882215ea1e192241 | 645,524 |
def get_gnupg_keys():
"""
:status 501: NotImplemented
"""
return {'gnupg-keys': []}, 501 | 85b0a0e77c35de097175350c8a9200a10d2a5d2f | 645,525 |
def process_prediction(action, objects, pad, vocab_action, clean_special_tokens, predict_object=True):
"""
process a single trajectory, return it as a dict
"""
# remove padding tokens
if pad in action:
pad_start_idx = action.index(pad)
action = action[:pad_start_idx]
objects ... | bf498962f944bba8ed5807d7d0b57693c9c44c8e | 645,526 |
def get_all_portals(light_ob):
"""Return a list of portals
Args:
light_ob (bpy.types.Object) - light object
Returns:
(list) - list of portals attached to this light
"""
portals = list()
if light_ob.type != 'LIGHT':
return portals
light = light_ob.data
rm = light.r... | 0f77f0cdfec3e90bfbb26744e744b0e8f3ae35bf | 645,527 |
def get_mask_file(img_file):
"""Takes an image file name and returns the corresponding mask file. The mask represents
pixels that belong to the object. Default implentation assumes mask file has same path
as image file with different extension only. Write custom code for getting mask file here
... | 9f0185817ae8dd6b0858eb9f336609e29226679e | 645,528 |
def choose_play(dr,dp,ds):
""" It will return a boolean if it's confident and otherwise some other value """
choose = ""
valid = False
best = min(dr, dp, ds)
others = sorted([dr,dp,ds])[1:]
confidence = sorted([(x/best) for x in others])
if confidence[0] > 2.3:
valid = True
... | 1c38bf122850a051001a07fac66e12f35e96d6bb | 645,529 |
def any_builtin():
"""any: Check if at least one element is true."""
return any((None, False, 0, [], {}, tuple(), ...)) and "which one is true?" | d23587d5c59da32b7033e1cf5e7e395782458b00 | 645,530 |
import os
def is_ci_server():
"""
For skipping some long tests locally, but not on completely CI
"""
return 'CI' in os.environ | 795a92e5cdf4ba617f728172aab5ec262354af33 | 645,531 |
def monthly_std_error(merged_data):
"""Calculates monthly seasonal standard error of the timeseries data in a DataFrame
Parameters
----------
merged_data: DataFrame
A pandas DataFrame with a datetime index and columns containing float type values.
Returns
-------
DataFrame
... | c9ed4ef211b045f4d9a96839a722e77a5a65413f | 645,532 |
def decode_data_item(row, group, byteorder) -> int:
"""Converts the bytes of data items into an integer."""
return int.from_bytes(row[group], byteorder=byteorder) | bfbb10204720b603858278d70689eb0640f157ad | 645,533 |
def exists_position(layout, row, column):
"""
Checks whether given row and column indices represent a valid position in
the layout.
Check whether row is inside the range od rows, check whether the column is
at or below the right edge of the keypad and finally check the left edge is
not a placeho... | 5cebd778a311992551c0bf74cd074b804cafdd99 | 645,535 |
import torch
def function_4(X: torch.Tensor) -> torch.Tensor:
""" Returns a torch tensor where the ith-element is the i-th true function evaluated at x"""
f4 = X
return f4 | c008651865b0cbd79f0c2a7ba33290a75a67420c | 645,536 |
def flatten_rsig(rsig):
"""
Rsig -> byte array
:param rsig:
:return:
"""
res = b""
for i in range(len(rsig.asig.s0)):
res += bytes(rsig.asig.s0[i])
for i in range(len(rsig.asig.s1)):
res += bytes(rsig.asig.s1[i])
res += bytes(rsig.asig.ee)
for i in range(len(rsig... | ec0782fee2e9306c55709f856ec5f72e7bc14e74 | 645,537 |
import string
import random
def generate_random_string(length=8):
"""
Generate a random string
"""
char_set = string.ascii_uppercase + string.digits
return ''.join(random.sample(char_set * (length - 1), length)) | ff89304b3d695a6fcc22d2ee1b9e603eaf2b3a6d | 645,538 |
import configparser
def simulation_configuration(path):
"""
Reads an ASCII file with relevant parameters for simulation.
Parameters
----------
path : string
Path to ASCII file.
Returns
-------
can_params : dict
Parameters for cantilever properties. The dictionary contains:
amp_invols = float (in m/V)... | 650723c92ab53d93b1b6c036dd5bb5b2b59b46ee | 645,539 |
from typing import Any
def remove_mark__torchscript(ctx, xs: Any, *args, **kwargs):
"""Disable all marks for TorchScript backend.
As the Node `mark` is not able to be traced, we just return original input
for the function `mark_tensors`.
Args:
xs (Any): Input structure which contains tensor.... | 8599d6ce3924e548d6c634d93b2019b85afb2d61 | 645,540 |
import re
def normalize_tainted_string(questionablestring):
"""
Trim, remove any non alphanumeric character and lower-case a questionable string
:param questionablestring: tainted string
:return: the normalized string
"""
return re.sub('\s+', ' ', re.sub('[\W_]+', ' ', questionablestring.lower... | bfc682d6447035e08a2de132e12c36863186a874 | 645,541 |
def mobius_inverse(a,b,c,d):
"""
Inverse of a Mobius transformation.
Parameters
----------
a : complex number
b : complex number
c : complex number
d : complex number
Returns
-------
function from C -> C
"""
return lambda z: (d*z - b)/(-c*z + a) | a628ed97b8ae42d79d3392e51afdd740212c3a60 | 645,542 |
import heapq
def update_locs(old_hit,new_hit):
"""changes start and stops to samllest locs is smaller then utr"""
new_gene = old_hit
new_gene["locs"] = old_hit["locs"] + new_hit["locs"]
new_gene["locs"].sort()
locs_start = new_gene["locs"][0][0]
locs_end = new_gene["locs"][-1][1]
new_gene[... | 4ad551e375a694a6c3e1032a68f69868a3c4459a | 645,543 |
def edge_correction(merge, d, pm, tf, art):
"""
generates strings for all left out or incorrect edges due to merge nodes
:param merge: merge node with all individual nodes
:param d: list of differences in the nodes
:param pm: plus or minus depending on whether an edge is added or subtracted in the c... | d1267be94f4dfe5507f710f836a503dccd1ffdf2 | 645,544 |
def _match_topic(subscription, topic):
""" Returns if topic matches subscription. """
if subscription.endswith('#'):
return (subscription[:-2] == topic or
topic.startswith(subscription[:-1]))
sub_parts = subscription.split('/')
topic_parts = topic.split('/')
return (len(sub... | fe124cbb805815a80df0c47c9e59f43e86fb5cfc | 645,545 |
from typing import Iterable
from typing import Tuple
from typing import Pattern
from typing import Optional
def pattern_match(string: str, patterns: Iterable[Tuple[Pattern[str], str]]) -> Optional[str]:
"""
Returns the replacement string when a pattern matches the string query
:param string: string to se... | f8b5c60fa02c53f5e644851ab23a7fcdea8abe59 | 645,546 |
import socket
import re
def get_environment():
"""
Detect host environment: HX, OY, PG or DEV.
"""
hostname = socket.gethostname()
match = re.search(r'ves-(\w+)-\w+\.ebi\.ac\.uk', hostname)
if match and match.group(1) in ['hx', 'pg', 'oy']:
env = match.group(1)
else:
env = ... | 3382819aaf3761b6e762ba4f6a9c069c19427c0e | 645,548 |
def terminal_errors_except(*args):
"""
Returns a ``can_retry`` function for :py:func:retry` that only retries if
errors the ``Exception`` types specified.
:return: a function that accepts a :class:`Failure` and returns ``True``
only if the :class:`Failure` wraps an Exception passed in the args.... | f928574ca644bdf6556751e32e46fc12c55f007c | 645,549 |
def _del_temp(beta, rhat_dot_dgam, dgam0):
"""Returns the small correction in surface temperature
See Eqn (10) from Jackson+ (2012) ApJ.
Args:
beta (float): gravity-darkening exponent, probably 0.07 or 0.25
rhat_dot_dgam (numpy array): dot product between the unit location
vect... | 76cd0e33396b167653ad48b4aee1e24493c791a2 | 645,550 |
def to_real_panel(panel):
"""2次元配列から7SegArmorの実配列への変換
<armor0> <armor1> <armor2>
panel[0][0:8] panel[0][8:16] panel[0][16:24]
panel[1][0:8] panel[1][8:16] panel[1][16:24]
panel[2][0:8] panel[2][8:16] panel[2][16:24]
panel[3][0:8] panel[3][8:16] panel[3][16:24]
... | 43492830bc773c0b835a7e07741059a5ab3d1d69 | 645,552 |
def selectionSort(li):
"""Find the smallest element and put it in the first position, then find
the second smallest and put it in the second position and repeat until you
get to the last position.
>>> selectionSort([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> selectionSort([5, 4, 3, 2, 1])
[1, 2, 3... | c6717c3fb7eb3bf924df54f8944dbbcff22cba86 | 645,553 |
def capitalize(string):
""" helper function to create capitalized copy of string. """
return string[:1].upper() + string[1:] | 60f11ae2c60809b36e3ff2be7881ae7dfd606d08 | 645,554 |
def _p2(x, prec=2, formatting=''):
"""Helper to print depending on the type nicely. For some
reason %.2g for 100 prints exponential form which is ugly
"""
if isinstance(x, int):
s = "%d" % x
elif isinstance(x, float):
s = ("%%.%df" % prec % x).rstrip('0').rstrip('.').lstrip()
... | ab8bd7ecc10ededa1d2dd6220c00a46bdb53caaf | 645,555 |
def align_up(offset, align):
"""Align ``offset`` up to ``align`` boundary.
Args:
offset (int): value to be aligned.
align (int): alignment boundary.
Returns:
int: aligned offset.
>>> align_up(3, 2)
4
>>> align_up(3, 1)
3
"""
remain = offset % align
if ... | f74c2c3fba775d6bb15b7faf369e8706ecccc610 | 645,556 |
def _fix_coordinates(cube, definition):
"""Fix coordinates."""
axis2def = {'T': 'time', 'X': 'longitude', 'Y': 'latitude'}
for axis in 'T', 'X', 'Y':
coord_def = definition.coordinates.get(axis2def[axis])
if coord_def:
coord = cube.coord(axis=axis)
if axis == 'T':
... | e75dbf517a18695d5b3c1d84c347c67782f24bef | 645,557 |
def much_consistency(df):
""" Helper function to handle known inconsistencies in raw data files
:param df: A pandas dataframe, BLS OEWS data set
:return df: A pandas dataframe
"""
# Force lower case column headers
df.columns = map(str.lower, df.columns)
print("...Forced column headers to ... | 009cf2972a6155296af7667b2c614c43c314683c | 645,558 |
def zplsc_c_tilt(counts, a, b, c, d):
"""
Description:
Compute the tilt from the counts passed in from the zplsc A series.
This Code was from the ASL MatLab code LoadAZFP.m
Implemented by:
2017-06-23: Rene Gelinas. Initial code.
:param counts:
:param a:
:param b:
... | 22aeac1ba660126df4c7d4315fa32097981fd66b | 645,559 |
def sanitize_webscrape_name(name):
""" Sanitizes webscrape powerplant names by removing unwanted
strings (listed in blacklist), applying lower case, and deleting
trailing whitespace.
Parameters
----------
name: str
webscrape plant name
Returns
-------
name: str
sani... | b4be5d8a25402e72011d20a4b652e6b5ca39650e | 645,560 |
import os
def ip_cache_setup(opts):
"""Ensure that our cache directory exists, return cache file path."""
if not os.path.exists(opts.ip_cache):
os.makedirs(opts.ip_cache)
return os.path.join(opts.ip_cache, opts.service_plugin + '.ip') | c065f769ccccb90ec0499007b95b9a3afda2d963 | 645,561 |
import torch
def apply_gaussian_noise(img, amplifier=0.1):
"""
Applies gaussian noise to given image.
:param img: input image to add noise.
:param amplifier: noise amplifier to control noise.
:return: noisy image
"""
noise = torch.randn_like(img)
return (amplifier * noise) + img | bee094f6f305b97db0e61cbd9062de10b8a09ac9 | 645,562 |
import sys
def encode_utf8(u):
""" Encode a UTF-8 string to a sequence of bytes.
Args:
u (str) : the string to encode
Returns:
bytes
"""
if sys.version_info[0] == 2:
u = u.encode('utf-8')
return u | 2bbe2b92a73ab5330efa4f1b2e5620b9d140fea8 | 645,563 |
import random
def decide_crop_area(img_size: tuple, crop_size: tuple):
"""画像とGTマップでクロップする箇所を揃えるための箇所の決定をする
Args:
img_size --- 画像サイズ (W, H)
crop_size --- クロップサイズ (W, H)
Return:
top --- クロップ箇所の左上 width座標
left --- クロップ箇所の左上 height座標
""... | 8c8ae15eda7ffcb5c69db731abc8055c0ef01c4e | 645,564 |
import socket
def dns_resolve(ip_addr):
"""Safe DNS query."""
try:
name = socket.gethostbyaddr(ip_addr)[0]
except (socket.herror, socket.gaierror):
# 1: IP not known
# 2: Probably badly formated IP
name = None
return name | 1714e408043cc9cdc6f5c4fa6fd352a0db50ac5b | 645,565 |
def valid_number(board, number, position):
"""
return if the number fit in the position
param board: 2d list of ints
param position: (row, col)
param number: integer
return: boolean
"""
for i in range(9):
if board[position[0]][i] == number and position[1] != i:
return... | 5ed7733bd4c4c264ba9d10b8343c500a18a0c2ca | 645,567 |
def find_by_name(arr, name):
"""__name__から要素を検索して返す。"""
for x in arr:
if x.__name__ == name:
return x
raise ValueError(f'"{name}" is not exist in [{arr}]') | 543d01b3369e94ce9a5ec7d27e9e4bfe214e4012 | 645,568 |
def signed_nibble(x) -> int:
"""Converts an unsigned nibble to a signed nibble."""
return (x | ~7) if (x & 8) else (x & 7) | 464e42528b64a77b8d631b33ee28da2bedf5a9fe | 645,569 |
def generarTexto(f, k,vMn, vMx):
"""
Función que nos permite generar el texto correspondiente para cada mapa
param: f: fecha
param: k: nombre de la columna
param: vMn: valor mínimo
param: vMx: valor máximo
"""
titulo = ""
if k == "Rain":
titulo = "Precipitación acumulada en 24h de {} a {} mm\n Pronóstico vál... | 3f4cfc37af9e389feee1c6587910242ceb38c9ba | 645,570 |
import argparse
def parse_arguments():
""" parse arguments """
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("train_f", help="path to train corpora")
parser.add_argument("eval_f", help="path to eval file")
parser.add_argument("test_f", help="path to test file")
par... | d6980f094869102d4128054f1dcf546ee9f92f8b | 645,571 |
def _check_not_in(obj, string):
"""
The 'i' substring of the list 'obj' must not be in 'string
:param obj: list of substring
:param string: element that needs to be checked
:return: False if a 'obj' substring is contained in 'string', True otherwise
"""
for i in obj:
if i in string:
... | 5e0958a63dc089abb7809044e3d68ecb5216e013 | 645,572 |
import math
def calc_eyebrow_coordinates(anchor_point, length, angle, width):
"""
Calculates points of eyebrow
:param anchor_point: a bottom right (bottom left) point
:param length: eyebrow length x
:param angle: brow angle
:param width: eyebrow thickness
:return: coordinates
"""
x... | 620ac9f52bbec246fe0704222b931bdbf1e46289 | 645,573 |
def get_role_label(role):
"""
>>> get_role_label(('arn:aws:iam::123:saml-provider/Shibboleth',\
'arn:aws:iam::123:role/Shibboleth-PowerUser', 'zalando-stups'))
'AWS Account 123 (zalando-stups): Shibboleth-PowerUser'
"""
if not role:
return ''
provider_arn, role_arn, name = role
... | ccdf4db20e5c274fc1dcd392b2cd0f6efaf12483 | 645,574 |
def normalise_bytes(buffer_object):
"""Cast the input into array of bytes."""
return memoryview(buffer_object).cast("B") | 87f5ff72d5d3e9ed796444c365e18d331103d0e4 | 645,575 |
def find_strongest_bot(bots):
"""Find bot with largest radius."""
return max(bots, key=lambda bot: bot.radius) | 3318e4a5ae94b5889426f5414697ab5098501dea | 645,576 |
def retirer_client(dfc, num_permis):
"""
supprime un client de la base de donnees
in :
dfc : dataframe de la base de donnees des clients
num_permis : numéro du permis du client à retirer
"""
mask = dfc['num_permis'] != num_permis
return(dfc[mask]) | dc5f500d7e910e31964432b026ad91f932088d18 | 645,577 |
import os
def get_postgresql_cfg():
"""
Returns PostgreSQL config if should be used based on the environment
settings if not return none.
"""
use_postgresql = os.environ.get('TEST_USE_POSTGRESQL', '') == 'true'
if use_postgresql:
pg_db_config = {'dbaddress': 'localhost',
... | 399a6e4e0744f71a4dcf1cdaeb9a326374813b52 | 645,578 |
import pathlib
import json
def _get_image_files_list():
"""
Get a list of all images from `data/json` folder.
"""
images_list = []
# find all images
json_files = sorted(pathlib.Path('data/json').glob('data*.json'))
for json_file in json_files:
with open(json_file, 'r') as read... | 28fd573c6c6fe1e6b286106a2851e8d4ac24808c | 645,579 |
import operator
def iterative_is_sorted(a, rev=False) -> bool:
"""Iterative alternative to is_sorted.
Time complexity: O(n)."""
if len(a) < 2:
return True
op = operator.gt
if rev:
op = operator.lt
for i in range(len(a) - 1):
if op(a[i], a[i + 1]):
return ... | ad044231f83553c36baf3e0ac352ed1992cdac02 | 645,580 |
def get_formatted_city_country(city, country, population=''):
"""Generate a neatly formatted city and country."""
city_country = city.title() + ', ' + country.title() + ': ' + population
return city_country | 830ba375b0cf7e2d0c14753e67b0b6d5fed21c44 | 645,581 |
def list_set_bits(r, expected_length):
"""Return list of positions of bits set to one in given data.
This method is used to read e.g. violated zones. They are marked by ones
on respective bit positions - as per satel manual.
"""
set_bit_numbers = []
bit_index = 0x1
assert (len(r) == expecte... | 8e814ca00e751391dfd7448fa30180eb3a2883f7 | 645,582 |
from itertools import compress
def list_contains(list_of_strings, substring, return_true_false_array=False):
""" Get strings in list which contains substring.
"""
key_tf = [keyi.find(substring) != -1 for keyi in list_of_strings]
if return_true_false_array:
return key_tf
keys_to_remove = ... | f901a88839b48f219c6758dd89e1bc65f6b4a6f0 | 645,583 |
import os
def dir_is_empty(path):
"""
Check if the given directory is empty.
May raise a FileNotFoundError or a NotADirectoryError exception.
"""
for entry in os.scandir(path):
return False
return True | c9b0a4ed74767748c1e655f223c212b22b47f09c | 645,584 |
def capitalize(string: str) -> str:
"""
Capitalizes a string by leveraging the capitalize() method.
The behavior of this function differs from he previous
functions because the capitalize() method also converts all
other characters int he string to lowercase.
:param string: an input string
... | 4a992c6d1fef98402429ef0bff7a5aa16a8a7860 | 645,585 |
def dmp_zz_wang_non_divisors(E, cs, ct, K):
"""Wang/EEZ: Compute a set of valid divisors. """
result = [ cs*ct ]
for q in E:
q = abs(q)
for r in reversed(result):
while r != 1:
r = K.gcd(r, q)
q = q // r
if K.is_one(q):
... | 996146ab9c79df6cc6324894596c9b43a1a6be14 | 645,586 |
def naive_backtrace(B_matrix):
"""
"""
i, j = B_matrix.shape[0]-1, B_matrix.shape[1]-1
backtrace_idxs = [(i, j)]
while (i, j) != (0, 0):
if B_matrix[i,j][1]:
i, j = i-1, j-1
elif B_matrix[i,j][0]:
i, j = i-1, j
elif B_matrix[i,j][2]:
i, j = i, j-1
backtrace_idxs.append((i,j))
return backtrac... | 2f25ca732856f2fba7afcf6cbfb6ff036d1d8127 | 645,588 |
import json
def agg_all(run_dir, solved, map_fct, agg_fct):
""" Calculate aggregates over all runs.
Args:
run_dir: directory containing benchmark results
solved: whether to consider only successful tries
map_fct: maps tries to values for aggregation
agg_fct: function used ... | 6cb1771c1aa322cee596f7bc3c3aba181c603a12 | 645,590 |
def two_2d_minimum_cost_path():
"""
Find the minimum cost path in a 2D array (moving right or bottom)
Complexity: O(N^2)
"""
cost = [[5, 4, 10, 2], [3, 1, 5, 6], [10, 2, 5, 3], [3, 1, 1, 7]]
min_cost = [[0] * 4 for _ in range(4)]
min_cost[0][0] = cost[0][0]
for j in range(1, 4):
... | 87c495a1cd8f364243d72d558e380613fe2a1c5d | 645,591 |
import os
import importlib
def load(dataset, model_name, model_file, data_parallel=False):
"""
Dynamically invokes the load function of the dataset specified
Example: cifar10 -> Invoke load function of datasets.cifar10.model_loader
Args:
dataset: the name of the dataset
model_na... | 0584fe72d0f1f72c73ebb6650467cc2851991d9e | 645,593 |
import json
def _record_message(record):
"""Return the message part of the given SNS record."""
source = record["EventSource"]
if source == "aws:sns":
return json.loads(record["Sns"]["Message"])
raise ValueError(f"Unsuported 'EventSource' {source}. Supported types: 'aws:sns'") | ab2c68bc464f32bbb02cf1848dbd79adefe46d15 | 645,594 |
from typing import Any
from typing import Sequence
def listify(thing: Any) -> list:
"""Always a list, for things that want lists. use with care."""
if isinstance(thing, str) or (not isinstance(thing, Sequence)):
return [thing]
return list(thing) | 302fac5b6e1eac0e2f167ebc8ada2a10269725e6 | 645,595 |
def function_with_args(func, *args):
"""
Returns a function that calls a function with the specified arguments.
The returned function still takes one argument representing the first
positional argument.
This is mostly a helper function for using agg_grid with functions
requiring more informatio... | e098d678ff2d9d52810f0c915620b5a272373ccc | 645,596 |
def count_increased_depths(filename: str) -> int:
"""Tally the number of times a depth increased compared to the previous
depth reading. Iterate over the inputs only once (during initial file read)
and perform calculations simultaneously.
"""
prev_depth = 0
# ignore the initial jump from 0 -> fi... | 8149e9629fa3aea07743b64495b3634a3ac30b53 | 645,597 |
def compress_secp256k1_public(point):
"""
Returns a 33-byte compressed key from an secp256k1 public key,
which is a point in the form (x,y) where both x and y are 32-byte ints
"""
if point.y % 2:
prefix = b'\x03'
else:
prefix = b'\x02'
return prefix + point.x.to_bytes(32, byt... | 39c914c85886f7987c51a9136a3e930cf42eaf38 | 645,598 |
def traversal_ops(op, graph, target_op_idx):
""" Get all operators in the multi-path from op to target op. """
pattern_ops = []
pattern_ops_type = []
visited = []
pq = [op]
while pq:
cnt = len(pq)
level = []
for _ in range(cnt):
cur = pq.pop(0)
lev... | 90339020ef95a1319006a6da41458fcce9e268db | 645,599 |
def serialize_json(obj):
"""
A helper method for serializing Cytoscape.js elements in desired json form.
:param obj: Object to serialize
:return: JSON string representation of obj
"""
# handle concrete class serialization
if hasattr(obj, '__metaclass__') and obj.__metaclass__.__name__ == 'El... | f1430965af7964c8f5b070f27637ea538be4e82f | 645,600 |
import six
def _parse_message_data_sets(data_sets):
"""
Parse the message data sets and extract the messages
:type data_sets: :class:`list` of :class:`str`
:param data_sets: Resource bundle string extracted from the egg file
:rtype: :class:`dict` of :class:`str`, :class:`str`
:return: Dictio... | eceec5ba86db5d65459e5520ac4d77d68310f3f7 | 645,601 |
def drawPolyline(
page,
points,
color=None,
fill=None,
dashes=None,
width=1,
morph=None,
lineCap=0,
lineJoin=0,
roundCap=None,
overlay=True,
closePath=False,
):
"""Draw multiple connected line segments.
"""
img = page.newShape()
Q = img.drawPolyline(points... | f72794d965d733107228ed7e84755be723fe4b2f | 645,602 |
import os
def IsWindows():
"""Returns true if the platform is Windows."""
return os.uname()[0].startswith("CYGWIN_NT") | 0fb6d2da20a59f5faa08f4572a0d81e596804d33 | 645,605 |
def space_pad(number, length):
"""
Return a number as a string, padded with spaces to make it the given length
:param number: the number to pad with spaces (can be int or float)
:param length: the specified length
:returns: the number padded with spaces as a string
"""
number_length = len(... | 998a9de2644f69bc10feae0d4d3322ca5665f89f | 645,606 |
import re
def ecm_kw_regex_select(ecm_names_list, list_of_match_str):
"""Identify matching, non-matching ECM names using a list of search terms
This function searches a list of ECM names to find all of the ECM
names that have the words specified by the user as search terms.
This function is used to i... | dcc7dd512db184c7e09a91b0fed41151b0b420bd | 645,607 |
def _extract_batch_length(preds):
"""Extracts batch length of predictions."""
batch_length = None
for key, value in preds.items():
batch_length = batch_length or value.shape[0]
if value.shape[0] != batch_length:
raise ValueError('Batch length of predictions should be same. %s has '
... | ebe13b576efa213f15522da838fdd184fd19fe7f | 645,608 |
import os
def get_training_dir(output_dir, name):
"""
finds a suitable subdirectory within `output_dir` to
save files from this run named `name`.
:param output_dir: global output directory
:param name: name of this run
:return: path to file of the form /path/to/output/name-X
"""
base =... | 4bb0034e3d0e64a2c4c08628e6377ffb592acac7 | 645,609 |
def update_window_based_cooc_matrix(cooc_mat, freq_words, sentence, window_size, directional):
"""
Updates the co-occurrence matrix with the current sentence
:param cooc_mat: the co-occurrence matrix
:param freq_words: the list of frequent words
:param sentence: the current sentence
:param windo... | 82d66e289319a02912e77fbc7fb4903b576f1956 | 645,610 |
def tupleify_state(state):
"""
Returns the state as a tuple
"""
temp = []
for row in state:
temp.append(tuple(row))
return tuple(temp) | ae311fe1c9eba3c5d8aef3f8519b0d722089cb42 | 645,611 |
def lock_params(access_mode):
"""Returns parameters for Action Lock"""
return {'_action': 'LOCK', 'accessMode': access_mode} | 4918b5d4028389ce4325171d414ab9b7bb1225f5 | 645,612 |
def minus(set1, set2):
"""Given the two sets, returns set1 - set2."""
return set1 - set2 | 546a8d0b520ab217c95a97e2da74543efd9c592b | 645,613 |
import torch
def mask_test_mixin__simple_test_mask(ctx, self, x, img_metas, det_bboxes,
det_labels, **kwargs):
"""Rewrite `simple_test_mask` of `BBoxTestMixin` for default backend.
This function returns detection result as Tensor instead of numpy
array.
Args:
... | 4243703f2dd6cc3f5ebcda0c7927ccf9cb5de9f7 | 645,614 |
def count_perturbations(perturbed_nodes_by_t):
"""
Count number of perturbations.
:param perturbed_nodes_by_t: dict (by time step) of dicts (by node) of node states
:return: number of perturbations
"""
return sum(len(current_perturbed_nodes)
for current_perturbed_nodes in perturb... | 6de029c0d9f05ff561566ea894a930fadc018233 | 645,615 |
def TimeToString(dt):
"""Convert a DateTime object to an ISO8601-encoded string."""
return dt.isoformat() + 'Z' | b374c750fedb8b17c1aee946639e2c2b21a5ffa6 | 645,616 |
def wrap_env(env,wrappers):
"""Wrap environment
:env: Environments
:returns: Environment
"""
for i in range(len(wrappers)):
if isinstance(wrappers[i], tuple):
env = wrappers[i][0](env,
agent_view_size = wrappers[i][1])
else:
env = wrap... | 015545f921e1230b5be0c27b9b3afddb4e9aa154 | 645,617 |
import torch
def get_device(model):
"""
Extract the device to run on from the model.
:param model: The model to train.
:return: String. The name of the device.
"""
if next(model.parameters()).is_cuda:
return 'cuda:{}'.format(torch.cuda.current_device())
else:
return 'cpu' | 587c71966da8c115883977c87b79449d6d586658 | 645,618 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.