content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def resolve_status(code):
"""
Get a label and status for the status code
:param code: The status to resolve
:return: A tuple containing the label and new status
"""
# Default label
status_label = 'info'
if code == 'success':
status_nice = 'Build Succeeded'
status_label ... | 8fc1c77170973c19bd3bb50240a184524c2c06a0 | 651,312 |
import csv
def get_desikan(filepath):
"""Parse the desikan atlas ordering for the 68 cortical regions from the csv file,
or indeed any other csv dictionary.
Args:
filepath (type): full file path.
Returns:
regions: list of region names in order of the desikan atlas.
coords: th... | 10709caceced351634696a841c963f68e3c6fe2b | 651,313 |
import re
def unwiki(wiki):
"""
Remove wiki markup from the text.
"""
wiki = re.sub(r'(?i)\{\{IPA(\-[^\|\{\}]+)*?\|([^\|\{\}]+)(\|[^\{\}]+)*?\}\}', lambda m: m.group(2), wiki)
wiki = re.sub(r'(?i)\{\{Lang(\-[^\|\{\}]+)*?\|([^\|\{\}]+)(\|[^\{\}]+)*?\}\}', lambda m: m.group(2), wiki)
wiki = re.s... | 5f43deca834ec5207b4d8e12d42721c592f22284 | 651,314 |
import re
def is_number(num):
"""
判断是否是数字
:rtype: bool
"""
pattern = re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$')
result = pattern.match(str(num))
if result:
return True
else:
return False | c99128c6ebc12e49fcbf1000bbf8bab1adb2fd9a | 651,315 |
def get_dataset(dashboard):
"""Retrieves the dataset
Parameters:
-----------
dashboard : plsexplain.dashboard.Dashboard
Returns
-------
Callable
The API handler for the dataset
"""
def get_dataset_internal(skip, take):
skip = int(skip)
take = int(take)
... | 144bd9d2168eff06c383f187a7dfcc7a98d00ac3 | 651,316 |
import re
def is_tag(token):
"""Determine if a token is a tag of the format like [i-10] or [o-7]"""
is_tag_re = re.compile('\[[io]-\d+\]', re.IGNORECASE)
return is_tag_re.match(token) | 6639973b4949021f88f3d24857d6af8c83c6595f | 651,317 |
def convert_latitude(x):
"""
Converts latitude-coordinates based on North/East value.
"""
direction = str(x)[-1]
if direction == 'N':
return float(str(x)[:-1])
else:
return -float(str(x)[:-1]) | 5f0255dff28581a4cc451dbc76e28abe3f920a78 | 651,319 |
import io
import numpy
def ReadNPY(zipfile, subFileName):
"""
Reads a saved npy from inside a zip
@param zipfile: ZipFile to read from
@param subFileName: file name
@type zipfile: ZipFile
@type subFileName: str
@return: array
@rtype: numpy.ndarray
"""
arrayFile = io.BytesIO(zipfile.read(subFileName)... | 7ae242ea637ce8b8c2ab62c1538b4b15780f8061 | 651,320 |
def SHPowerL(c, l):
""" Calculate the power for degree l. c is the CILM array.
RETURNS:
scalar value for the power
"""
return (c[:,l,:]**2).sum() | eb5ac44a7f7a9f6fb4cbebb0c581a8b4057fb0b3 | 651,321 |
import wave
import struct
def read_wav(wav_file):
""" retourne 2 sets wav d'un wavefile"""
w = wave.open(wav_file)
n = 60 * 10000
if w.getnframes() < n * 2:
raise ValueError('Wave file too short')
frames = w.readframes(n)
wav_data1 = struct.unpack('%dh' % n, frames)
frames = w.read... | b5f7e6ccb0557f8900d948e628dc048f049497ec | 651,323 |
def bubble_sort(array: list) -> tuple:
""""will return the sorted array, and number of swaps"""
total_swaps = 0
for i in range(len(array)):
swaps = 0
for j in range(len(array) - 1):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
... | c917f88fc0075525ab9c02b2048396be368191ed | 651,324 |
def strip_numbers(text: str):
"""Strip numbers from a piece of text"""
text = text.replace("0", "").replace("1", "").replace("2", "").replace("3", "").replace("4", "").replace("5", "")
text = text.replace("6", "").replace("7", "").replace("8", "").replace("9", "")
return text | ad8ec7a0e706f32e66ec09fffd9155880b039723 | 651,325 |
import string
def rot(s, n):
"""
Caesar cipher
"""
cipher = ''
for c in s:
if c in string.ascii_lowercase:
cipher += string.ascii_lowercase[(string.ascii_lowercase.find(c) + n) % len(string.ascii_lowercase)]
elif c in string.ascii_uppercase:
cipher += string... | 139cb0b091d2f1fe80823334f782697cc9199927 | 651,328 |
def robot_tidy_one(agents, self_state, self_name, cube, box, human):
"""
@param agents:
@param self_state:
@param self_name:
@param cube:
@return:
@ontology_type cube: Cube
"""
return [("robot_tell_human_to_tidy", human, cube, box), ("wait_for_human", cube, box, human)] | e26f5d48f6a63bdace79b3fb609c5087d61d5d36 | 651,329 |
import uuid
def get_rgraph(result, message):
"""Get "ranker" subgraph."""
qedges_by_id = {
qedge['id']: qedge
for qedge in message['query_graph']['edges']
}
kedges_by_id = {
kedge['id']: kedge
for kedge in message['knowledge_graph']['edges']
}
rnodes = result['... | eedbce1f867d8cb2ca0843ed87aa3f777b62d3e9 | 651,330 |
def generate_rod(graph, start_node, routing_config):
"""
Generates a random rod.
"""
dijkstra = graph.generate_dijkstra(start_node, routing_config).choose(routing_config)
(node_id, _) = dijkstra.next()
res = dijkstra.root(node_id)
return res[::-1] | fb176311cc4d551d17ff9e2bd47abbc636890e0b | 651,332 |
import json
def load_ships_json(json_file):
"""Load and decode json"""
print('Load json file: {}'.format(json_file))
with open(json_file, 'r', encoding='utf8') as file:
ships = json.load(file)
return ships | 8944af8dd33981e4863f6046738bc3e85f99d445 | 651,333 |
def updateleafflag(cumulTT=741.510096672,
leafNumber=8.91945383336,
calendarMoments=['Sowing'],
calendarDates=['21/3/2007'],
calendarCumuls=[0.0],
currentdate='29/4/2007',
finalLeafNumber=8.7975820132,
... | 03e28e42555e834d849178dac1f7703a80cf067e | 651,334 |
def _get_outside_corners(corners, board):
"""
Return the four corners of the board as a whole, as
(up_left, up_right, down_right, down_left).
"""
xdim = board.n_cols
ydim = board.n_rows
if corners.shape[1] * corners.shape[0] != xdim * ydim:
raise Exception(
"Invalid numb... | 647a5f42192a312c7a661880d1d2750ebf70e154 | 651,335 |
def unify_walk(a, b, U):
"""
unify_walk(a, b, U) returns an Unification where a and b are unified, given the
unification that already exists in the Unification U. If the unification fails,
it returns False.
There are two ways to expand the functionality of unify_walk. The first way is:
@comm_gu... | 5be31a1d46b36d036cee6fcabfb763c0a3880b36 | 651,336 |
import os
def check_directory_existence(directory_path: str,
sub_directory: str):
"""Concatenates directory path and sub_directory. Checks if the directory path exists; if not, it will create the
directory.
Args:
directory_path: Current directory path
... | d99c1841cceb5671dc6ffcfed43609975e07a14f | 651,337 |
import random
import time
def call_with_retries(function, max_retries=10,
exception_types=(Exception),
_args=(), _kwargs={}):
"""
Call `function` with up to `max_retries` retries. A retry is only
performed if the exception thrown is in `exception_types`.
:p... | 798f9e01cea59df1176537738326a24358695ea1 | 651,338 |
from typing import Optional
from typing import Union
import pathlib
import tempfile
def use_fs_cache(
root: Optional[Union[str, pathlib.Path, bool]] = None
) -> Optional[pathlib.Path]:
"""Use a path in the local file-system to cache blobs and buckets.
This is useful for when you want to avoid fetching la... | 81fb95dd8481c060e939aaf917437ac0c0d7cc40 | 651,339 |
def yper(p):
"""Calculates the y position for a given amount of peroxide."""
return 100 + (p - 12) * -10 | 3d949f34843d9b98a1a2e2cf1ef757eeafe65845 | 651,340 |
def in_by_id(element, collection):
"""Check if element is in collection, by comparing identity rather than equality."""
return any(element is item for item in collection) | 55a0e174493970d55174b38d6bad3f9643ba7068 | 651,341 |
def ImageFromBitmap(bitmap):
"""
Create a :class:`Image` from a :class:`wx.Bitmap`
"""
return bitmap.ConvertToImage() | 396e805ce350bc56a3de42db67cdd8f4dbb971e4 | 651,342 |
import re
def rm_word_repetition(text):
"""
Replace subsequent letters with a length of more than 2
"""
return re.sub(r'(.)\1+', r'\1\1', text) | 0f4763e1cbfb82b6e5b3ba069841ed6e3e0506a3 | 651,343 |
def recursive_check(fcn, inp, ref, max_depth):
"""
The function to apply a custom function fcn (the 1st input) on each element of inp.
fcn should take two inputs: inp (the 2nd input) and ref (the 3rd input).
inp can be a scalar or a (nested with many nested levels) list or tuple or a range.
... | 82821ed92304b1b633f09b27bcd755856e8ef60b | 651,344 |
def _inject_mutations_2D(phi, dt, xx, yy, theta0, frozen1, frozen2):
"""
Inject novel mutations for a timestep.
"""
# Population 1
if not frozen1:
phi[1,0] += dt/xx[1] * theta0/2 * 4/((xx[2] - xx[0]) * yy[1])
# Population 2
if not frozen2:
phi[0,1] += dt/yy[1] * theta0/2 * 4/... | 910513251ad80714f29ddad7d564a6fe90704f12 | 651,346 |
def get_test_path():
"""
:return: a tuple with vcf path and reference fasta path for testing
"""
vcf_path = "/Users/simonelongo/too_big_for_icloud/gnomAD_v3/gnomad.genomes.r3.0.sites.vcf.bgz"
fasta_path = "/Users/simonelongo/too_big_for_icloud/ref_genome/hg38/hg38.fa"
return vcf_path, fasta_path | 70c5dc2b7c2edd2ca78d99bcb9fc284c821fc531 | 651,347 |
def maxPosterior(cur,cell,contin=None):
"""
Returns the max posterior sections of cell
Parameters:
-----------
cur : MySQLdb cursor
cell : str
name of cell
contin : str (optional, defautl = None)
Contin number
"""
if contin:
sql = ("select max(image.IMG_SectionN... | 89da6208831d389d51de0e40706f471a4a0c70f0 | 651,348 |
import os
def get_features_json_files_in_dir(dir_path):
"""Get files within the target dir suffixed with "--features.json".
Strictly for the examples script.
Parameters
-----------
dir_path: str
Path to examples directory.
Returns
-------
list of str
Features JSO... | c87305c1476e5a15d1451b22bc385af9c585bef9 | 651,349 |
def getRemoteParams(dbElem):
"""Get parameters to supply to ktremotemgr to connect to the right DB."""
host = dbElem.getDbHost() or 'localhost'
return ['-port', str(dbElem.getDbPort()),
'-host', host] | 28c8d3dc3b566231aa5e82d04d69d76c434fcf46 | 651,350 |
import os
import fnmatch
def find_files_matching_pattern(pattern, directory = None):
"""Find files matching string pattern
Find files matching string pattern in specified directory.
Default search directory is the current directory
Args :
pattern : pattern to match, accepts wildcard... | a498df3cb6c2ce712eda565cc05cfd6ed235d08c | 651,351 |
def read_int32(val):
"""
Recibe bytes y los convierte a entero
"""
return int.from_bytes(val,"little") | 543cc7c0d41618de03616ff772d3ccd914447fdc | 651,352 |
import torch
import math
def get_rotation_matrix(heading):
"""Get the rotation matrix for the given heading.
Arguments:
heading (float): Rotation in radians.
Returns:
torch.tensor: 2x2 rotation matrix
"""
return torch.tensor([[math.cos(heading), -math.sin(heading)],
... | c58518f40ae9c4483002d32691a3ac2060e35bdf | 651,353 |
def clean_data_frame(data_frame_pair):
"""This function cleans our dataframes"""
# empty array: save cleaned dataframes
clean_family_dataframes = []
# Loop through both family dataframes
for i in range(2):
# dataframe on variable clean_Fi_df
clean_Fi_df = data_frame_pair[i]... | 7e4669594ed4c9674a3da1867dd28942c0416a4b | 651,354 |
def repr_calling(args, kwargs):
"""
Reconstruct function calling code.
"""
li = []
li.extend(repr(a) for a in args)
li.extend('%s=%r' % (k, v) for k, v in kwargs.items())
return ', '.join(li) | dac4771ea4df9a048c63b50ec6c7300f0c6bec6d | 651,356 |
def calc_neighbour_positions(_cell_coord: tuple) -> list:
""" Calculate neighbouring cell coordinates in all directions (cardinal + diagonal).
Returns list of tuples. """
"""Creates and returns coordinates of all cells around the current cell"""
neighbour: list = [
(_cell_coord[0] - 1, _cell_co... | 46b4326f7bfdba17c0c316afeb8c50d829c867e1 | 651,357 |
def tmpdir_repoparent(tmpdir_factory, scope='function'):
"""Return temporary directory for repository checkout guaranteed unique."""
fn = tmpdir_factory.mktemp("repo")
return fn | 90ab3cc6d5484da6cfb9c47de0caf128fa0d6a6a | 651,358 |
def format_includes(includes: list) -> str:
"""Format includes into the argument expected by GCC"""
return " ".join([f"-I{path}" for path in includes]) | eb55d0ed32ade058ce176127d1d695c00f7f373f | 651,359 |
def separateRows(training_rows, data):
""" Return (training set, prediction set) with n% of rows in training set"""
training = data.ix[training_rows]
prediction = data.drop(training_rows)
return (training, prediction) | bb2550914380d93f65c809da4a2f282f8cba2b3d | 651,360 |
import os
def GetPluginPath():
"""This function returns the absolute path to the plugin"""
return os.path.abspath(os.path.dirname(os.path.realpath(__file__))) | 736c78789791ff55d784940092c1ab1b3a90879b | 651,361 |
def _get_keystores_object_type(output_type):
"""
Map config type to custom resource cert type
"""
return {
'p12': 'pkcs12',
'jks': 'jks',
}[output_type] | 0b145494321243f58e5264946c7ddc9c27fec984 | 651,362 |
import os
def parse_filename(filepath):
"""Parse input file path into directory, basename and extension.
Parameters
----------
filepath: string
Input name that will be parsed into directory, basename and extension.
Returns
-------
dirname: str
File directory.
basename... | 7e82eed37ad79368573bc4e197b0e814bd0e4f3f | 651,363 |
def manager_object_factory(person_id, group_id, manager_type_id, active=True):
"""Cook up a fake manager."""
manager = {
'personId': person_id,
'groupId': group_id,
'managerTypeId': manager_type_id,
'active': active,
}
return manager | 840bb611b5d66f4ff0e9e79a7f386e5ccfa8dccb | 651,364 |
def frame_msg(msg: str) -> str:
"""Frame a message with hashes so that it covers five lines."""
return f"\n###\n#\n# {msg}\n#\n###" | 0575810b1199066bb4e0af12d8bad2a3f536aaf3 | 651,365 |
import webbrowser
import asyncio
async def get_oauth_verifier(oauth_token):
"""
Open authorize page in a browser,
print the url if it didn't work
Arguments
---------
oauth_token : str
The oauth token received in :func:`get_oauth_token`
Returns
-------
str
The PIN ... | 1b1cb399e8ac2070bbf6ad73ed585a19b8cbce2c | 651,366 |
import random
def choose(char):
"""change a character"""
# return char.upper() if random.choice([False, True]) else char.lower()
return random.choice([char.lower(), char.upper()]) | 704dd6ffb5d1e004c5eb0b05098bbeedd8dcfdac | 651,367 |
def get_timestamp(imu_dict):
"""The timestamp of a message does not necessarily equal
the timestamp in the message's header. The header timestamp
is more accurate and the timestamp of the message just corresponds
to whenever the bag received the message and saved it.
Args:
imu_dict (dict): ... | 871d9dcfba366c5b30c4261a555874e06de6fe9b | 651,368 |
def upper_triangle(matrix):
"""
Return the upper triangle of a list of list representation of a square matrix
"""
assert len(matrix) == len(matrix[0])
return [i[matrix[:-1].index(i)+1:] for i in matrix[:-1]] | b943b981b5abfe618f08a0b90639819957023193 | 651,369 |
def invert_dictionary(dict, make_unique=False):
"""returns an inverted dictionary with keys and values swapped.
"""
inv = {}
if make_unique:
for k, v in dict.items():
inv[v] = k
else:
for k, v in dict.items():
inv.setdefault(v, []).append(k)
return inv | 4812d4b080609c0722961bd641e465a5e6ed6a71 | 651,370 |
def build_swagger_12_api_declaration_view(api_declaration_json):
"""Thanks to the magic of closures, this means we gracefully return JSON
without file IO at request time.
"""
def view_for_api_declaration(request):
# Note that we rewrite basePath to always point at this server's root.
ret... | c315d5e24d7e21cebb5121e070b36a7ce5fd27fe | 651,371 |
import numpy
def GetPhaseRefractiveIndexRange(mediumProperties):
"""
Returns the minimum and maximum phase refractive indices as tuple
over all ice layers for a given mediumProperties object.
"""
minIndex = None
maxIndex = None
overallMinWlen = mediumProperties.GetMinWavelength()... | 2abb9093d5e6738bbf6d771a059cf856081a1c77 | 651,372 |
from typing import Tuple
from typing import Dict
def get_calibrated_plot_fonts(fig_size: Tuple[int, int]) -> Dict[str, float]:
"""
Takes in figure-size (tuple), and returns dictionary containing fontsizes for all other aspects
of the plot (calculated and set appropriately, based on the figure-size).
T... | cf85c46f321e917b1dedd5e035541946d97c0ab3 | 651,373 |
import logging
def get_ctx_options(conf):
"""Gets the appropriate context options for storing test information.
These context options are passed as keyword arguments to methods including
ndb.Key.get(), ndb.Key.put(), ndb.get_multi(), and ndb.put_multi() to control
how various storage methods are used.
Arg... | 7234946a549b7a65f3baf2addf422563d1c86fba | 651,374 |
def is_a_equal_to_b(num1, num2):
"""Predicate function evaluating whether num1 is equal to num2."""
return num1 == num2 | 3bad0c31241821804348f9db44ce968041dabafe | 651,375 |
def stripMetadataFlags(metadataChunk):
"""Strip binary flags from the start of the metadata chunk.
Arguments:
metadataChunk {bytes} -- This refers only to the first metadata chunk. If there are additional ones they won't have any flags.
Returns:
bytes -- Number of metadata chunks, uint8.
bytes -- Rest of t... | 42ccf91fd3e618d0c40b9206c267e331f4e984ee | 651,376 |
def get_matrix09():
"""
Return the matrix with ID 09.
"""
return [
[1.000000, 1.000000, 0.017276],
[0.046296, 0.022222, 1.000000],
[0.259295, 0.106985, 0.783554],
[0.260509, 0.107106, 0.801962],
[0.090419, 0.044763, 0.245226],
[0.563999, 0.239328, 0.288358... | 7cb555005aa4615ae02ef470e811dc9b9104f9e2 | 651,377 |
import socket
def is_port_available(port: int, host="0.0.0.0"):
"""
Check if a port is available
"""
assert isinstance(port, int)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = True
try:
sock.bind((host, port))
except:
result = False
sock.close()... | 7ecac8160b1e25575e90037f38ae4bcd1213d01d | 651,378 |
def shift_point_by_markersize(axes, x, y, markersize):
"""
Shift overlapping points alonmg x axis by half of the markersize.
This allows to show better plots with errorbars.
"""
inv = axes.transData.inverted()
points = [(i,j) for i,j in zip(x,y)]
pixels = axes.transData.transform(points)
... | fd2e88eee038ef443384b5c520cb30018c9bda47 | 651,380 |
from datetime import datetime
def timestamp():
"""Return a string timestamp."""
return datetime.now().strftime('%Y-%m-%d_%H-%M-%S') | e4cf7b16ce0013aa9b3760d46aec4861b7802b83 | 651,381 |
def pytest_report_header(config):
"""
Pytest hook, see :py:func:`_pytest.hookspec.pytest_report_header` (:ref:`pytest:plugins`).
It's important to see which URL is testing with which user and where are
stored screenshots. It will be displayed before run of tests if you set
some config values like t... | 36c1df0ad6dd4c92910a432bd77f4b930b8e260e | 651,382 |
import argparse
def get_parser():
"""Argument parser."""
parser = argparse.ArgumentParser(
description='Create random samples.')
parser.add_argument('n', type=int)
parser.add_argument('k', type=int)
parser.add_argument('-s', '--seed', type=int,
default=None, help='r... | a97ee6904b386d3b49211b87620b970dc71dd000 | 651,383 |
def find_dupes(facts):
"""Find hosts with duplicate SSH host keys from PuppetDB output"""
hosts_by_key = {}
for fact in facts:
hosts_by_key.setdefault(
fact['value'],
set(),
).add(fact['certname'])
return {
k: v
for k, v in hosts_by_key.items()
... | 720efe02ef8295f74d1cb409d93634400118e997 | 651,384 |
def encode_data(data, tokenizer, punctuation_enc):
"""
Converts words to (BERT) tokens and puntuation to given encoding.
Note that words can be composed of multiple tokens.
"""
X = []
Y = []
for line in data:
word, punc = line.split('\t')
punc = punc.strip()
tokens = ... | 7424d07166adeb5a3c8605a31edcd4d2e3e0a24c | 651,385 |
import re
import os
def get_values(input_line, keyword):
""" Get the values from makefile's line which matched keyword """
values = []
patten = re.compile("\$\(NAME\)_%s.*=\s*(.*)" % keyword)
input_line = input_line.strip()
match = patten.match(input_line)
if match:
tmp = match.group(1... | 0ed61f7504bdaeea2c2ce44d87812441affe7877 | 651,386 |
def get_pad(bbox, padval: int = 0, padprc: float = 0.0) -> tuple:
"""
Calculates the padding values for cutting
:param bbox: boundingbox information
:param padval: padding value (pixel)
:param padprc: padding value (percentage)
:return:
"""
pad = [0, 0]
try:
if padval != 0:
... | 435c2811a2b977fa22f857288c027ba0128b937f | 651,387 |
async def compatabilities(user_id_1, user_id_2):
"""Compatability scores are generated for 2 users given their music tastes.
The compatabilities are generated based on the statistics from the user's
libraries, genres and other music listening tendencies.
### Path Parameter
'user_id_1':
'user_i... | 462504045802e7d108616bca1b14136060e9e601 | 651,389 |
def num_strings(data: bytes) -> int:
"""
return the number of strings in the strings file
Args:
data: strings data from "Strings.txt" file
Returns:
Number of lines in strings output
"""
return data.count(b'\n') | 85c4484bb608567d9463d2e11eff921a9ff4af60 | 651,390 |
def get_heatexchanger():
"""付録 A 暖冷房負荷と外皮性能の算定に係る設定
A.8 熱交換型換気の採用
Args:
Returns:
bool: 熱交換型換気の採用
"""
return False | 73f8f750b04ffbfca053b266059a48cce93ec9b6 | 651,391 |
import random
def choose_duration(simple=False):
"""Returns a random duration in durk units
Args:
simple (bool, optional): Defaults at False. If True, only considers notes of duration 8 or 16 durks. Otherwise, considers durations in list: [1, 2, 3, 4, 6, 8, 12, 16]
Returns:
int... | 5fdfd3379ec4bb2eb79ea2ff560704e579a95d2c | 651,393 |
import argparse
def _parse_args() -> argparse.Namespace:
"""Parses arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Validates JSON.')
parser.add_argument(
'label_spec_json',
help='path to JSON file containi... | 0bf7fc2f7bdadd8fed97049caf9e8667fdeb2efe | 651,394 |
import torch
def onehot_coding(target, device, output_dim):
"""Convert the class labels into one-hot encoded vectors."""
target_onehot = torch.FloatTensor(target.size()[0], output_dim).to(device)
target_onehot.data.zero_()
target_onehot.scatter_(1, target.view(-1, 1), 1.0)
return target_onehot | f71a2ac1c6040b0a9d8a91d697a0b6b4c3840996 | 651,395 |
import logging
def init_basic_root_logger(level=logging.INFO):
"""
Initialize the root logger with basic configuration.
"""
logging.basicConfig()
logger = logging.getLogger() # get root logger as default
logger.setLevel(level)
return logger | a989b0e86a4cbccc79fbef73fa2ab968d4b3ca29 | 651,396 |
def sexagesimal2decimal(raw_num_list):
"""
Reversion process of decimal2sexagesimal
:param raw_num: a list contain 3 numbers
:return: float
"""
return round(
raw_num_list[0] +
raw_num_list[1] /
60 +
raw_num_list[2] /
3600,
10) | b8daccc40bbe7be67c5260443c72570279948682 | 651,397 |
def _get_fontsize(size_name):
"""Return a fontsize based on matplotlib labels."""
font_sizes = {
"xx-small": 5.79,
"x-small": 6.94,
"small": 8.33,
"medium": 10.0,
"large": 12.0,
"x-large": 14.4,
"xx-large": 17.28,
"larger": 12.0,
"smaller":... | d55c8b5d0f90d360b85a7a5edaa4dd1a13390e49 | 651,399 |
def get_digits(number):
"""Get digits in number from left to right."""
digits = []
while number > 0:
digits.append(number % 10)
number = number // 10
return digits[::-1] | c996131f026c097c7d95e636922108faf8ba3fc4 | 651,400 |
from pathlib import Path
from typing import Optional
from typing import List
def ignore_file(path: Path, patterns: Optional[List[str]]) -> bool:
"""Check if path matches ignore patterns.
:param path: path to compar with ignore pattern
:param patterns: list of glob patterns specifying which paths to ignor... | eef7b9288bcc47e6ca1ca6ae421cf19a67353db7 | 651,401 |
import requests
from bs4 import BeautifulSoup
def umc_web_scraper(map_id):
"""Get static copy of HTML from given url and returns it as HTML soup."""
url = f"http://unfortunate-maps.jukejuice.com/show/{map_id}"
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
return soup | d3518f1986a1efc790bad360051c0d928505f2f0 | 651,402 |
def part_one(data):
"""Part one"""
checksum = 0
for row in data.splitlines():
numbers = map(int, row.split())
largest = max(numbers)
smallest = min(numbers)
checksum += largest - smallest
return checksum | c6de2e74e43d4ba2ee9bd9a4204c10623d8f6c81 | 651,403 |
def blend(alpha, base=(255, 255, 255), color=(0, 0, 0)):
"""
:param color should be a 3-element iterable, elements in [0,255]
:param alpha should be a float in [0,1]
:param base should be a 3-element iterable, elements in [0,255] (defaults to white)
:return: rgb, example: (255, 255, 255)
"""
return tuple(int(... | 19587df9f6f0ede7938f7b5a15c348b066656909 | 651,405 |
from typing import Tuple
def get_bollinger_bands(data_points) -> Tuple[float, float, float]:
"""
Returns (upper, middle, lower) bollinger bands
"""
close_average = sum(data_points) / len(data_points)
squared_total = 0.0
for data_point in data_points:
diff = close_average - data_p... | 18ec518a7a0eaaa18215f77b57c29ffbe0829dc3 | 651,406 |
import time
def time_function(f, *args):
"""
Call a function f with args and return the time
(in seconds) that it took to execute.
"""
tic = time.time()
f(*args)
toc = time.time()
return toc - tic | 066a9504d2074a9d59e7f55282e3080244348026 | 651,407 |
def obsolete(func):
"""Mark function as obsolete
Usage
=====
@obsolete
def function(*args, **kwargs)
(...)
"""
def mfunc():
raise RuntimeError("Function '{}' is obsolete".format(func.__name__))
return mfunc | c661044e24225d66ef07cb1c71e45b76a6737fbf | 651,408 |
def parse_rank_specification(s):
"""
Parses info about rank specification, used to filter games by player's ranks.
Returns None (all ranks allowed),
or a set of possible values
(None as a possible value in the set means that we should include games without rank info)
# returns None, all ranks ... | ff7ce2b9940b6cd55bf0fab7bd2f633637fd7cc8 | 651,409 |
import sys
import os
def match_files(files1,files2,mapping):
""" Match files from two sets using the mapping provided
Args:
files1 (list): A list of files for set1
files2 (list): A list of files for set2
mapping (string): The file with the mapping information. This file
... | 6a8f77d440d8742439b03ce657202e91ac367b88 | 651,410 |
from typing import Sequence
from pathlib import Path
def real_words() -> Sequence[str]:
"""Loads a list of real words to search."""
with (Path(__file__).parent / 'words.txt').open() as path:
return tuple(map(str.strip, path.readlines()))[:5] | 230d3d625d112114d9ed088c1743a65b7bb84a7f | 651,411 |
import sys
def rejoin_bytes(sequence): # type: (...) -> bytes
"""Create a bytestring from whatever you get by iterating on one.
This is a workaround for the following situation:
1. In Python 2.7, iterating on a bytestring will give you a sequence of
characters, which you rejoin with ``b'... | bacc5d016b611354719cfbd1d7a10e0333719d24 | 651,412 |
def list_(client, file_=None, name=None, value=None, get_expanded=None, select=False):
"""Get a list of notes from one or more models.
Values will automatically be returned Base64-encoded if they are strings
which contain Creo Symbols or other non-ASCII data.
Args:
client (obj):
cr... | 712f43114e260c3eaff0b601d622fdd2f9723743 | 651,413 |
def ordinary_annuity(p: float, i: float, n: float) -> float:
"""
Calculates the annuity payment given loan principal, interest rate and number of payments
:param p: loan principal value
:param i: monthly nominal interest rate
:param n: number of payments
:return: annuity payment
"""
nume... | 7627c245d21c8bac38d574919b790a1c3e205598 | 651,414 |
def update_ks_file_location_redhat_iso_efi(temppath):
"""This function is to update the kickstart file location in the /EFI/BOOT/grub.cfg file within the RHEL OS ISO file.
Arguments:
temppath {string} -- Path to the custom ISO image file
server_serial_number {string} -- server s... | 1466385a57e4506a116fc29ab4fa3da6e5ebf53c | 651,415 |
import numpy
import copy
def makeCoordsCyclic(coords, dims):
"""
Make coordinates cyclic
Parameters
----------
coords
input coordinates
dims
input dimensions
Returns
-------
new, extended coordinates such that the longitudes cover the sphere and ne... | 36985bfd8845d67c563b4c35755fe9bad54c0272 | 651,417 |
def pager_limit(request, qs, *orders):
"""
传入偏移值offset, 页数量限制limit
"""
total = qs.count()
limit = request.GET.get("limit")
offset = request.GET.get("offset")
limit = int(limit) if limit else 10
offset = int(offset) if offset else 0
if orders:
qs = qs.order_by(*orders)[offset:offset... | 4fbe1add7b288d556a3b73575e844381153d8713 | 651,418 |
def load_order():
"""
Returns a list of the module and sub-module names for asn1crypto in
dependency load order, for the sake of live reloading code
:return:
A list of unicode strings of module names, as they would appear in
sys.modules, ordered by which module should be reloaded first
... | 61cef8b952dea7eaa1bb01eecb2a8cbe96cd1ca2 | 651,420 |
from typing import List
def _join(iterable: List, and_or: str) -> str:
"""Join iterables grammatically."""
return ', '.join(iterable[:-2] + [f' {and_or} '.join(iterable[-2:])]) | cef0c515b5b9af926d4a6612f244569ff5f26fbc | 651,421 |
def get_rp_names(rp):
"""
Converts permissions into something Roblox can read.
Parameters
----------
rp : ro_py.roles.RolePermissions
Returns
-------
dict
"""
return {
"viewWall": rp.view_wall,
"PostToWall": rp.post_to_wall,
"deleteFromWall": rp.delete_f... | 865049663a100f5fbf666df646e89cd3c9c10fc2 | 651,422 |
def downToLocal(poetryList, path):
"""下载诗词保存到本地txt
Args:
poetryList (List): 诗词列表
path (String): 保存路径
Returns:
None
"""
for content in poetryList:
with open(f'{path}' f'{content[0]}.txt', 'w', encoding='utf-8') as file:
file.writelines('\n'.join(content))... | b530e0d3af6975b42276ea9963ca34ceee877568 | 651,423 |
def Julian_centuries_since_2000(jd):
"""
Julian centuries from Jan 1, 2000.
@param jd : Julian date
@type jd : float
@return: float
"""
t = (jd-2451545.)/36525.
return t | 2ff9c9b0be59b60a8bbb3f0f3861449b6896d09d | 651,425 |
def is_pon(item):
"""
:param item: array of tile 34 indices
:return: boolean
"""
if len(item) != 3:
return False
return item[0] == item[1] == item[2] | cb491a057f7fb6bf20ff7862f221b3901c23908e | 651,426 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.