content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_to_scio_submit_post_data():
"""Test that the maps to send to scio is on the correct form"""
tests = [(b'\x00\x00', 'test.txt', 'AAA='),
(b'test', 'something.bin', 'dGVzdA=='),
(b'\x00\xFF\x0A', 'thisisafile.pck', 'AP8K')]
for byte_content, file_name, encoded_content in t... | 5,356,000 |
def fix_unused(model, signal):
"""Unused states decided MAP or viterbi usage"""
# model.algorithm = 'map'
# pred = model.predict(signal)
# usage = np.bincount(pred,minlength=model.n_components)
# treshold = np.sort(usage)[model.n_components//10]
#
# ids = np.argwhere(usage <= treshold).flatt... | 5,356,001 |
def search_transitions_in_freq_range(freq_min, freq_max, atomic_number,
atomic_mass, n_min=1, n_max=1000,
dn_min=1, dn_max=10, z=0.0,
screening=False, extendsearch=None):
"""
-------------------------... | 5,356,002 |
async def test_async__rollback():
"""Should rollback basic async actions"""
state = {"counter": 0}
async def incr():
state["counter"] += 1
return state["counter"]
async def decr():
state["counter"] -= 1
async def fail():
raise ValueError("oops")
try:
w... | 5,356,003 |
def _solve_checkpoint_challenge(_bot):
"""Solve the annoying checkpoint_challenge"""
# --- Start challenge
time.sleep(3)
challenge_url = _bot.last_json['challenge']['api_path'][1:]
try:
_bot.send_request(
challenge_url, None, login=True, with_signature=False)
except Exception... | 5,356,004 |
def write_to_csv(csv_name, df, append=True, index=True, sep=';'):
"""Create CSV file or append data to it.
Parameters
----------
csv_name : str
Name of file.
df : DataFrame
Sata saved to file.
append : bool
If False create a new CSV file (default), else append to it.
... | 5,356,005 |
def simplify(func, cfg):
"""
Simplify control flow. Merge consecutive blocks where the parent has one
child, the child one parent, and both have compatible instruction leaders.
"""
for block in reversed(list(func.blocks)):
if len(cfg.predecessors(block)) == 1 and not list(block.leaders):
... | 5,356,006 |
def is_referenced(url, id, catalog_info):
"""Given the url of a resource from the catalog, this function returns True
if the resource is referenced by data.gouv.fr
False otherwise
:param :url: url of a resource in the catalog
:type :url: string"""
dgf_page = catalog_info['url_dgf']
... | 5,356,007 |
def tags_to_ascii(filepaths):
"""
Receives a list of mp3 files (by their paths) and updates all their tags, so
that name of the Artists, Album, Genre, etc. use only ASCII characters.
It also removes some unnecessary information like composer or comments. This is
a program to automate the procce... | 5,356,008 |
def create_sema3d_datasets(args, test_seed_offset=0):
""" Gets training and test datasets. """
train_names = ['bildstein_station1', 'bildstein_station5', 'domfountain_station1', 'domfountain_station3', 'neugasse_station1', 'sg27_station1', 'sg27_station2', 'sg27_station5', 'sg27_station9', 'sg28_station4',... | 5,356,009 |
def adjust_learning_rate(optimizer, step, args):
"""
Sets the learning rate to the initial LR decayed by gamma
at every specified step/epoch
Adapted from PyTorch Imagenet example:
https://github.com/pytorch/examples/blob/master/imagenet/main.py
step could also be epoch
... | 5,356,010 |
def sigmoid(z):
"""sigmoid函数
"""
return 1.0/(1.0+np.exp(-z)) | 5,356,011 |
def worker_init_fn(worker_id):
"""Pytorch worker initialization function."""
np.random.seed(np.random.get_state()[1][0] + worker_id) | 5,356,012 |
def main(parseinfo):
"""Start a parser"""
parseengine = LiveParser()
parseengine.parse_file(parseinfo) | 5,356,013 |
def export_fixtures(app=None):
"""Export fixtures as JSON to `[app]/fixtures`"""
if app:
apps = [app]
else:
apps = frappe.get_installed_apps()
for app in apps:
for fixture in frappe.get_hooks("fixtures", app_name=app):
filters = None
or_filters = None
if isinstance(fixture, dict):
filters = fixtu... | 5,356,014 |
def beamformerFreq(steerVecType, boolRemovedDiagOfCSM, normFactor, inputTupleSteer, inputTupleCsm):
""" Conventional beamformer in frequency domain. Use either a predefined
steering vector formulation (see Sarradj 2012) or pass your own
steering vector.
Parameters
----------
steerVecType : (one... | 5,356,015 |
def createNewPY():
"""trans normal pinyin to TTS pinyin"""
py_trans = {}
input_pinyin_list = IO.readList(r'docs/transTTSPinyin.txt')
for line in input_pinyin_list:
line_array = line.split(',')
py_trans[line_array[0]] = line_array[1]
return py_trans | 5,356,016 |
def state_processing_do(app, cfg):
"""Blink smile display
"""
app.pimoroni_11x7.blink_scroll_display(interval=0.5) | 5,356,017 |
def search_wheelmap (lat, lng, interval, name, n):
"""Searches for a place which matches the given name in the
given coordinates range. Returns false if nothing found"""
# Calculate the bbox for the API call
from_lat = lat - interval
to_lat = lat + interval
from_lng = lng - interval
to... | 5,356,018 |
def get_entity_contents(entity: Dict) -> Dict:
"""
:param entity: Entity is a dictionary
:return: A dict representation of the contents of entity
"""
return {
'ID': entity.get('id'),
'Name': entity.get('name'),
'EmailAddress': entity.get('email_address'),
'Organizatio... | 5,356,019 |
def t68tot90(t68):
"""Convert from IPTS-68 to ITS-90 temperature scales,
as specified in the CF Standard Name information for
sea_water_temperature
http://cfconventions.org/Data/cf-standard-names/27/build/cf-standard-name-table.html
temperatures are in degrees C"""
t90 = 0.9... | 5,356,020 |
def get_sort_accuracy_together(fake_ys, y):
"""
Args:
fake_ys (np.ndarray): with shape (n_results, n_sample,).
y (np.ndarray): with sample (n_sample,).
Returns:
corr (np.ndarray): with shape (n_result,)
"""
y_sort = np.sort(y)
y_sort2 = np.sort(y)[::-1]
fake_ys =... | 5,356,021 |
def random_account_number():
"""
Generate random encoded account number for testing
"""
_, account_number = create_account()
return encode_verify_key(verify_key=account_number) | 5,356,022 |
def get_recommendation_summary_of_projects(project_ids, state, credentials):
"""Returns the summary of recommendations on all the given projects.
Args:
project_ids: List(str) project to which recommendation is needed.
state: state of recommendations
credentials: client credentials.
"""
recommen... | 5,356,023 |
def suppress_stdout():
"""
Suppress the standard out messages.
"""
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = devnull
sys.stderr = devnull
try:
yield
finally:
sys.stdout = old... | 5,356,024 |
def selection_filter(file_path):
"""
获得经过filter方法获得的特征子集
f_classif, chi2, mutual_info_classif
"""
df = pd.read_csv(file_path)
delete_list = ['id']
df.drop(delete_list, axis=1, inplace=True)
feature_attr = [i for i in df.columns if i not in ['label']]
df.fillna(0, inplace=True)
# ... | 5,356,025 |
def cnndm_eval(ratio):
"""Evaluation for the CNN/DailyMail dataset"""
for model_name in MODELS:
print("Evaluating \"{}\"".format(model_name))
print("=" * 20)
with open(str(RESULTS_DIR / "cnndm_use_{}_{}.pred".format(
model_name, int(ratio*100)))) as fin:
predi... | 5,356,026 |
def setup():
"""
Install Supervisor and enable/disable configured programs
"""
install()
configure() | 5,356,027 |
def _process_voucher_data_for_order(cart):
"""Fetch, process and return voucher/discount data from cart."""
vouchers = Voucher.objects.active(date=date.today()).select_for_update()
voucher = get_voucher_for_cart(cart, vouchers)
if cart.voucher_code and not voucher:
msg = pgettext(
'... | 5,356,028 |
def is_insertion(ref, alt):
"""Is alt an insertion w.r.t. ref?
Args:
ref: A string of the reference allele.
alt: A string of the alternative allele.
Returns:
True if alt is an insertion w.r.t. ref.
"""
return len(ref) < len(alt) | 5,356,029 |
def rm_network(c):
"""Destroy local test network."""
print('Stopping local test network and removing containers')
with c.cd('images'):
c.run('sudo docker-compose down -v', hide='stderr')
c.run('sudo rm -rf volumes/stellar-core/opt/stellar-core/buckets')
c.run('sudo rm -f volumes/ste... | 5,356,030 |
def identify_fast_board(switches: int, drivers: int) -> Optional[FastIOBoard]:
"""Instantiate and return a FAST board capable of accommodating the given number of switches and drivers."""
if switches > 32 or drivers > 16:
return None
if switches > 16:
return None if drivers > 8 else FastIO32... | 5,356,031 |
def show():
"""Show the registered controllers."""
Registry().show_controllers() | 5,356,032 |
def fit(
model_fn,
train_input_fn,
epochs,
verbose,
callbacks,
eval_input_fn,
class_weight,
steps_per_epoch,
validation_steps,
**kwargs
):
"""Trains networks using Keras models."""
log_parameters(logger)
# Train
save_callback = [
c for c in callbacks if i... | 5,356,033 |
def encode_hop_data(
short_channel_id: bytes, amt_to_forward: int, outgoing_cltv_value: int
) -> bytes:
"""Encode a legacy 'hop_data' payload to bytes
https://github.com/lightningnetwork/lightning-rfc/blob/master/04-onion-routing.md#legacy-hop_data-payload-format
:param short_channel_id: the short chan... | 5,356,034 |
def extract_all_patterns(game_state, action, mask, span):
""" Extracting the local forward model pattern for each cell of the grid's game-state and returning a numpy array
:param prev_game_state: game-state at time t
:param action: players action at time t
:param game_state: resulting game-state at tim... | 5,356,035 |
def wrapper_subcavities(final_cavities, cav_of_interest, grid_min, grid_shape, cavities, code, out, sourcedir, list_ligands,
seeds_mindist = 3, merge_subcavs = True, minsize_subcavs = 50, min_contacts = 0.667, v = False,
printv = False, print_pphores_subcavs = False, export_subcavs = False, gridspace = 1.0, frame = N... | 5,356,036 |
def generate_datafile(lists_of_systems, output_dir, filename):
"""
take in a list of lists which contains systems
generate one input data file per list
"""
result = []
for index, list_of_sys in enumerate(lists_of_systems):
output_filename = filename + "_" + str(index) + ".xml"
... | 5,356,037 |
def cond(*args, **kwargs):
"""Conditional computation to run on accelerators."""
return backend()['cond'](*args, **kwargs) | 5,356,038 |
def get_testfile_paths():
"""
return the necessary paths for the testfile tests
Returns
-------
str
absolute file path to the test file
str
absolute folder path to the expected output folder
"""
testfile = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'test_d... | 5,356,039 |
def singleton(cls):
"""Decorator that provides singleton functionality.
>>> @singleton
... class Foo(object):
... pass
...
>>> a = Foo()
>>> b = Foo()
>>> a is b
True
"""
_inst = [None]
def decorated(*args, **kwargs):
if _inst[0] is None:
_inst[... | 5,356,040 |
def _with_factory(make_makers):
"""Return a decorator for test methods or classes.
Args:
make_makers (callable): Return an iterable over (name, maker) pairs,
where maker (callable): Return a fixture (arbitrary object) given
Factory as single argument
"""
def wrap(test_func)... | 5,356,041 |
def timeItDeco(func):
""" Decorator which times the given function. """
def timing(*args, **kwargs):
""" This function will replace the original function. """
# Start the clock
t1 = time.clock()
# Run the original function and collect results
result = func(*args, **kwa... | 5,356,042 |
def apply_haste(self: Player, target: Player, rules: dict, left: bool) -> EffectReturn:
"""
Apply the effects of haste to the target:
attack beats attack
"""
# "attack": {"beats": ["disrupt", "area", "attack"], "loses": ["block", "dodge"]}
if left:
# Remove attack from the attack: loses ... | 5,356,043 |
def get_mean_cube(datasets):
"""Get mean cube of a list of datasets.
Parameters
----------
datasets : list of dict
List of datasets (given as metadata :obj:`dict`).
Returns
-------
iris.cube.Cube
Mean cube.
"""
cubes = iris.cube.CubeList()
for dataset in datase... | 5,356,044 |
def main(args=None):
"""
Main function
:param args:
:return:
"""
# get parser args
if args is None:
args = None if sys.argv[1:] else ['--help']
parser = get_parser()
arguments = parser.parse_args(args=args)
param = Param()
param.fname_data = os.path.abspath(arguments... | 5,356,045 |
async def gen_unique_chk_sum(phone, message, first_dial):
"""Generates a checksum in order to identify every single call"""
return blake2b(
bytes(phone, encoding="utf-8")
+ bytes(message, encoding="utf-8")
+ bytes(str(first_dial), encoding="utf-8"),
digest_size=4,
).hexdigest... | 5,356,046 |
def test_quant_maxpool2d_argmax():
""" Testing """
t_input = get_input_data()
q_input, input_scale, input_zero_point = get_quant_data(t_input.numpy())
pool_size = (2, 2)
strides = (2, 2)
padding = (0, 0)
torch_out, _ = fn.max_pool2d_with_indices(
t_input, kernel_size=2, stride=2, pad... | 5,356,047 |
def getQtipResults(version, installer):
"""
Get QTIP results
"""
period = get_config('qtip.period')
url_base = get_config('testapi.url')
url = ("http://" + url_base + "?project=qtip" +
"&installer=" + installer +
"&version=" + version + "&period=" + str(period))
reques... | 5,356,048 |
def scaled_softplus(x, alpha, name=None):
"""Returns `alpha * ln(1 + exp(x / alpha))`, for scalar `alpha > 0`.
This can be seen as a softplus applied to the scaled input, with the output
appropriately scaled. As `alpha` tends to 0, `scaled_softplus(x, alpha)` tends
to `relu(x)`.
Note: the gradient for this ... | 5,356,049 |
def get_choice(options):
"""Devuelve como entero la opcion seleccionada para el input con mensaje message"""
print(options)
try:
return int(input("Por favor, escoja una opción: "))
except ValueError:
return 0 | 5,356,050 |
def _listminus(list1, list2):
"""
"""
return [a for a in list1 if a not in list2] | 5,356,051 |
def pdf_to_hocr(path, lang="fra+deu+ita+eng", config="--psm 4"):
"""Loads and transform a pdf into an hOCR file.
Parameters
----------
path : str, required
The pdf's path
lang: str, optional (default="fra+deu+ita+eng")
Supporter Language of Pytesseract.
config: str, optional (d... | 5,356,052 |
async def fetch_cart_response(cart_id: str) -> httpx.Response:
"""Fetches cart response."""
headers = await get_headers()
async with httpx.AsyncClient(base_url=CART_BASE_URL) as client:
response = await client.get(
url=f'/{cart_id}',
headers=headers,
)
try:
... | 5,356,053 |
def checkHardware(binary, silent=False, transaction=None):
"""
probe caffe continuously for incrementing until missing id
structure:
[
{ "id": 0,
"name": "..",
"log": ["..", "..", "..", ... ]
},
{ "id": 1,
"name": "..",
"log": ["..", ".."... | 5,356,054 |
def is_namespace_mutable(context, namespace):
"""Return True if the namespace is mutable in this context."""
if context.is_admin:
return True
if context.owner is None:
return False
return namespace.owner == context.owner | 5,356,055 |
def get_schularten_by_veranst_iq_id(veranst_iq_id):
""" liefert die Liste der zu der Veranstaltung veranst_iq_id passenden Schularten """
query = session.query(Veranstaltung).add_entity(Schulart).join('rel_schulart')
query = query.reset_joinpoint()
query = query.filter_by(veranst_iq_id=veranst_iq_id)
return q... | 5,356,056 |
def get_station_freqs(df, method='median'):
"""
apply to df after applying group_by_days and group_by_station
"""
#df['DATE'] = df.index.get_level_values('DATE')
df['DAY'] = [d.dayofweek for d in df.index.get_level_values('DATE')]
df['DAYNAME'] = [d.day_name() for d in df.index.get_level_values(... | 5,356,057 |
def faster_symbol_array(genome, symbol):
"""A faster calculation method for counting a symbol in genome.
Args:
genome (str): a DNA string as the search space.
symbol (str): the single base to query in the search space.
Returns:
Dictionary, a dictionary, position-counts pairs of sym... | 5,356,058 |
def crosswalk_patient_id(user):
""" Get patient/id from Crosswalk for user """
logger.debug("\ncrosswalk_patient_id User:%s" % user)
try:
patient = Crosswalk.objects.get(user=user)
if patient.fhir_id:
return patient.fhir_id
except Crosswalk.DoesNotExist:
pass
r... | 5,356,059 |
def makeArg(segID: int, N, CA, C, O, geo: ArgGeo) -> Residue:
"""Creates an Arginie residue"""
##R-Group
CA_CB_length = geo.CA_CB_length
C_CA_CB_angle = geo.C_CA_CB_angle
N_C_CA_CB_diangle = geo.N_C_CA_CB_diangle
CB_CG_length = geo.CB_CG_length
CA_CB_CG_angle = geo.CA_CB_CG_angle
N_CA_C... | 5,356,060 |
def uploadAssignment(req, courseId, assignmentId, archiveFile):
""" Saves a temp file of the uploaded archive and calls
vmchecker.submit.submit method to put the homework in
the testing queue"""
websutil.sanityCheckAssignmentId(assignmentId)
websutil.sanityCheckCourseId(courseId)
# Ch... | 5,356,061 |
def apply_tags(datasets, tags):
"""
Modify datasets using the tags system
Parameters
----------
datasets : PickleableTinyDB
Datasets to modify
tags : dict
Dictionary of {tag: update_dict}
Returns
-------
PickleableTinyDB
Notes
-----
In general, everythi... | 5,356,062 |
def shows_monthly_aggregate_score_heatmap():
"""Monthly Aggregate Score Heatmap Graph"""
database_connection.reconnect()
all_scores = show_scores.retrieve_monthly_aggregate_scores(database_connection)
if not all_scores:
return render_template("shows/monthly-aggregate-score-heatmap/graph.html",
... | 5,356,063 |
def update_logs(user_id,answers,deck):
""" update DB logs
Parameters:
-----------
Returns:
--------
Modify:
-------
"""
con = sqlite3.connect(db_path)
cursor = con.cursor()
cursor.execute('PRAGMA encoding="UTF-8";')
# [{"question":"2 · 7","answer":"14","number_attempts":"0","timestamp":"1601660... | 5,356,064 |
def run(string, entities):
"""Call a url to create a api in github"""
# db = utils.db()['db']
# query = utils.db()['query']
# operations = utils.db()['operations']
# apikey = utils.config('api_key')
# playlistid = utils.config('playlist_id')
# https://developers.google.com/youtube/v3/docs/playlistItems/list
#... | 5,356,065 |
def _sudoku_update(grid, possibilities_list, row, col, paths=None):
"""incremental possibilities update"""
num = grid[row, col]
for row2 in range(9):
for col2 in range(9):
if possibilities_list[row2][col2] is None: # cell already filled
continue
if row == row... | 5,356,066 |
def gamma(surface_potential, temperature):
"""Calculate term from Gouy-Chapmann theory.
Arguments:
surface_potential: Electrostatic potential at the metal/solution boundary in Volts, e.g. 0.05 [V]
temperature: Temperature of the solution in Kelvin, e.g. 300 [K]
Returns:
float
"""
product = sc.elementary_charg... | 5,356,067 |
def import_cmd(project, namespace, data_dir, project_placeholder,
namespace_placeholder, kinds, chunk):
"""Import data to database using previously exported data as input."""
execute_tasks({
'type_task': 'import',
'project': project,
'namespace': namespace,
'data_d... | 5,356,068 |
def calculate_mask(maskimage, masks):
"""Extracts watershed seeds from data."""
dims = list(maskimage.slices2shape())
maskdata = np.ones(dims, dtype='bool')
if masks:
dataslices = utils.slices2dataslices(maskimage.slices)
maskdata = utils.string_masks(masks, maskdata, dataslices)
m... | 5,356,069 |
def Range(lo, hi, ctx = None):
"""Create the range regular expression over two sequences of length 1
>>> range = Range("a","z")
>>> print(simplify(InRe("b", range)))
True
>>> print(simplify(InRe("bb", range)))
False
"""
lo = _coerce_seq(lo, ctx)
hi = _coerce_seq(hi, ctx)
return R... | 5,356,070 |
def quantile(data, num_breaks):
"""
Calculate quantile breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
def scipy_mquantiles(a, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None, limit=()):
""" function copied from scipy 0... | 5,356,071 |
def sort_films(film_list):
"""
This function takes a list of film dictionaries as an argument and sorts each film by category.
Create a dictionary where the keys are the names of the film categories and the values are initially empty lists,
then loop through the list of films and add each film to the li... | 5,356,072 |
def extract_conformers_from_rdkit_mol_object(mol_obj, conf_ids):
"""
Generate xyz lists for all the conformers in conf_ids
:param mol_obj: Molecule object
:param conf_ids: (list) list of conformer ids to convert to xyz
:return: (list(list(cgbind.atoms.Atom)))
"""
conformers = []
for i i... | 5,356,073 |
def create_embedding(name: str, env_spec: EnvSpec, *args, **kwargs) -> Embedding:
"""
Create an embedding to use with sbi.
:param name: identifier of the embedding
:param env_spec: environment specification
:param args: positional arguments forwarded to the embedding's constructor
:param kwargs... | 5,356,074 |
def _init_allreduce_operators(length, split_indices):
""" initialize allreduce communication operators"""
indices = split_indices[0]
fusion = split_indices[1]
op_list = ()
j = 0
for i in range(length):
if j <= len(indices)-1:
temp = indices[j]
else:
temp =... | 5,356,075 |
def plot_load_shape_yd(daily_load_shape):
"""With input 2 dim array plot daily load"""
x_values = range(24)
y_values = list(daily_load_shape[:, 0] * 100) # to get percentages
plt.plot(x_values, y_values)
plt.xlabel("Hours")
plt.ylabel("Percentage of daily demand")
plt.title("Load curve of... | 5,356,076 |
def get_valid_fields(val: int, cs: dict) -> set:
"""
A value is valid if there's at least one field's interval which contains it.
"""
return {
field
for field, intervals in cs.items()
if any(map(lambda i: i[0] <= val <= i[1], intervals))
} | 5,356,077 |
def load_data_multiview(_path_features, _path_lables, coords, joints, cycles=3, test_size=0.1):
"""Generate multi-view train/test data from gait cycles.
Args:
_path_features (str): Path to gait sequence file
_path_lables (str): Path to labels of corresponding gait sequence
coords (int):... | 5,356,078 |
def dir_to_spectrogram(audio_dir, spectrogram_dir, spectrogram_dimensions=(64, 64), noverlap=16, cmap='gray_r'):
""" Creates spectrograms of all the audio files in a dir
:param audio_dir: path of directory with audio files
:param spectrogram_dir: path to save spectrograms
:param spectrogram_dimensions:... | 5,356,079 |
def T_ncdm(omega_ncdm, m_ncdm):
# RELICS ONLY?
"""Returns T_ncdm as a function of omega_ncdm, m_ncdm.
... | 5,356,080 |
def main(config: Config, dry_run: bool = False) -> int:
"""
Main entrypoint into the program. Takes specified snapshots if they don't exist and deletes old entrys as specified.
:param config: The backup manager configuration.
:param dry_run: Flag to indicate that no commands should be run
:return: ... | 5,356,081 |
def generate_initialisation_vector():
"""Generates an initialisation vector for encryption."""
initialisation_vector = Random.new().read(AES.block_size)
return (initialisation_vector, int(binascii.hexlify(initialisation_vector), 16)) | 5,356,082 |
def test_take_18():
"""
Test take: take first, then do fiter, skip, batch and repeat operation
"""
logger.info("test_take_18")
data1 = ds.GeneratorDataset(generator_10, ["data"])
data1 = data1.take(8)
data1 = data1.filter(predicate=filter_func_ge, num_parallel_workers=4)
data1 = data1.s... | 5,356,083 |
def assign_score(relevant_set):
"""Assign score to each relevant element in descending order and return the score list."""
section = len(relevance[0])//3
score = []
s = 3
for i in range(3):
if s == 1:
num = len(relevance[0]) - len(score)
score.extend([s]*num)
... | 5,356,084 |
def visualize_img(img,
cam,
kp_pred,
vert,
renderer,
kp_gt=None,
text={},
rotated_view=False,
mesh_color='blue',
pad_vals=None,
no_text=Fals... | 5,356,085 |
def synchronize_photos(albums, command):
"""
Synchronize photos from the filesystem to the database.
``albums`` is the result of ``scan_photo_storage``.
"""
for (category, dirpath), filenames in albums.items():
album = Album.objects.get(category=category, dirpath=dirpath)
new_keys ... | 5,356,086 |
def _check_file_type_specific_bad_pattern(filepath, content):
"""Check the file content based on the file's extension.
Args:
filepath: str. Path of the file.
content: str. Contents of the file.
Returns:
failed: bool. True if there is bad pattern else false.
total_error_coun... | 5,356,087 |
def _update(__version__, __code_name__, language, socks_proxy):
"""
update the framework
Args:
__version__: version number
__code_name__: code name
language: language
socks_proxy: socks proxy
Returns:
True if success otherwise None
"""
try:
if s... | 5,356,088 |
def conv_noncart_to_cart(points, values, xrange, yrange, zrange):
"""
:param points: Data point locations (non-cartesian system)
:param vals: Values corresponding to each data point
:param xrange: Range of x values to include on output cartesian grid
:param yrange: y
:param zrange: z
:retur... | 5,356,089 |
def createColumnsFromJson(json_file, defaultMaximumSize=250):
"""Create a list of Synapse Table Columns from a Synapse annotations JSON file.
This creates a list of columns; if the column is a 'STRING' and
defaultMaximumSize is specified, change the default maximum size for that
column.
"""
f... | 5,356,090 |
def record(
fn: Callable[..., T], error_handler: Optional[ErrorHandler] = None
) -> Callable[..., T]:
"""
Syntactic sugar to record errors/exceptions that happened in the decorated
function using the provided ``error_handler``.
Using this decorator is equivalent to:
::
error_handler = ge... | 5,356,091 |
def bbox_overlaps_2D(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
"""
# 1. Tile boxes2 and repeate boxes1. This allows us to compare
# every boxes1 against every boxes2 without loops.
# TF doesn't have an equivalent to np.repeate() s... | 5,356,092 |
def _noisy_action_impl(
scene_node: hsim.SceneNode,
translate_amount: float,
rotate_amount: float,
multiplier: float,
model: MotionNoiseModel,
motion_type: str,
):
"""
multiplier is the
ROTATION STD NOISE in case of rotational motion type,
MOTION STD NOISE in case of linear motio... | 5,356,093 |
def decoder(data):
"""
This generator processes a sequence of bytes in Modified UTF-8 encoding
and produces a sequence of unicode string characters.
It takes bits from the byte until it matches one of the known encoding
sequences.
It uses ``DecodeMap`` to mask, compare and generate values.
... | 5,356,094 |
def calculate_exvolume_redfactor():
"""
Calculates DEER background reduction factor alpha(d)
See
Kattnig et al
J.Phys. Chem. B, 117, 16542 (2013)
https://doi.org/10.1021/jp408338q
The background reduction factor alpha(d) is defined in Eq.(18)
For large d, one can use the limiting... | 5,356,095 |
def get_successors(graph):
"""Returns a dict of all successors of each node."""
d = {}
for e in graph.get_edge_list():
src = e.get_source()
dst = e.get_destination()
if src in d.keys():
d[src].add(dst)
else:
d[src] = set([dst])
return d | 5,356,096 |
def main(options):
"""
The primary modes of operation are:
* run query & save output, read cache, plot results
--query <foo>
* read cache or csv file, plot results
--csvfile <foo.csv>
* merge csv files, noplot
--mergefiles <foo1.csv> --mergefiles <foo2.csv> --outp... | 5,356,097 |
def readDataTable2o2(request):
"""Vuetify練習"""
form1Textarea1 = request.POST["textarea1"]
template = loader.get_template(
'webapp1/practice/vuetify-data-table2.html')
# -----------------------------------------
# 1
# 1. host1/webapp1/templates/webapp1/practice/vuetify-data-table2.... | 5,356,098 |
def dump_variables2json(var_list, write_file):
"""Dump the variable list object to JSON."""
with open(write_file, 'w') as file:
json.dump(var_list, file, indent=2) | 5,356,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.