content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def format_schema_tf(schema): """Format schema for an Athena table for terraform. Args: schema (dict): Equivalent Athena schema used for generating create table statement Returns: formatted_schema (list(tuple)) """ # Construct the main Athena Schema formated_schema = [] for...
ba808b145c16f2b13419f7dcdd0c55901da4ec8f
663,776
import time def get_time_by_timestamp(timestamp, time_format='%Y-%m-%d %H:%M:%S'): """ 获取指定时间戳对应的时间字符串,返回指定格式的时间字符串,默认格式YYYY-mm-dd HH:MM:SS """ return str(time.strftime(time_format, time.localtime(timestamp)))
e147f09af6e29a0088a6a84ab7c65e17fa8cfda9
663,777
def add_entities(kb, desc_dict, nlp): """ Adds company entities to KB :param kb: the empty Knowledge Base :param desc_dict: dict with KvK-numbers and SBI-code descriptions of companies :param nlp: the nlp object to retrieve vector of SBI-code description :return: the KB with companies entities ...
58d1d700fb6caca6be159f99ee4a4ee619fd5ec0
663,778
def compare_dicts(dict1, dict2): """ Checks if dict1 equals dict2 """ for k, v in dict2.items(): if v != dict1[k]: return False return True
0a2fa657a80d53e518e9a2f6613c9100396d81e9
663,779
import json def output_json(output): """Return JSON formated string.""" return json.dumps(output, sort_keys=True, indent=2)
32424662588c0353409b47f6a4dac6d9df6ad55b
663,780
import json def handle_event(ext, body): """Handle an event from the queue. :param ext: The extension that's handling this event. :param body: The body of the event. :return: The result of the handler. """ payload = json.loads(body) return ext.obj.event(author_id=payload['author_id'] or N...
36b193d7c04545b284311cf3ad0c55f2f3633c3c
663,781
def title_case(inp_str): """ Transforms the input string to start each word from capital letter Parameters ---------- inp : string string to be changed Returns ------- result : string a string were each word starts from the capital letter """ if isinstance(inp_str, str): ...
82e4da51b818073af84bc4534ca5b604e990cf0d
663,782
def batch_split(batch_size, max_num): """Split into equal parts of {batch_size} as well as the tail""" if batch_size > max_num: print("Fix the batch size to maximum number.") batch_size = max_num max_range = list(range(max_num)) num_splits = max_num // batch_size num_splits = ( ...
5a94908adfba9ba3e0c82598c3be2b739ec99f2c
663,783
import requests import json def mobileFriendlyCheck(request_url, api_key): """ Example of Python talking to Google Search Console URL Testing Tools API. Documentation: https://developers.google.com/webmaster-tools/search-console-api/v1/samples attributes: 'request_url' for the URL to test, 'api_key' for ...
da11ec9877550c271712aa29be76fa8b24296801
663,784
import numpy def dist_array(point, points): """return array of distances from point to each of points """ point = numpy.array(point) points = numpy.array(points) return numpy.sqrt(numpy.add.reduce((points - point)**2, axis=1))
4ada1f9897876b31f8c31d761304d6ddb76ddca6
663,785
import torch def matrix_diag_transform(matrix, fun): """Return the matrices whose diagonal elements have been executed by the function 'fun'.""" num_examples = len(matrix) idx = torch.eye(matrix.size(-1)).bool().unsqueeze(0) idx = idx.repeat(num_examples, 1, 1) new_matrix = matrix.clone() new_...
4e5ee3b11047626093f0b2e4f8ba04e078c78710
663,786
def command_run(command, args): """ 構築したコマンドを実行する """ result = {} for c in command: if not args.rollback: try: result[c.name] = c.run() except Exception as e: print("[{}] \033[31m".format(c.name) + str(e) + "\033[0m") ...
a76aa38d71cbd97f3d42c0800d8d0a6c22eac295
663,787
def numeric(value): """Accept a value to validate, ensure that all characters in string are digits""" if str.isdigit(value): return True, None return False, 'The {} must be numeric.'.format
72e01c6de77f12a3a97890137f41aec19ad8337b
663,788
def seq_matches(seq1, seq2): """ Return True if two sequences of numbers match with a tolerance of 0.001 """ if len(seq1) != len(seq2): return False for i in range(len(seq1)): if abs(seq1[i] - seq2[i]) > 1e-3: return False return True
977cc2194380dcd89d2e75f3491691e50da25a12
663,790
def is_far_from_group(pt, lst_pts, d2): """ Tells if a point is far from a group of points, distance greater than d2 (distance squared) :param pt: point of interest :param lst_pts: list of points :param d2: minimum distance squarred :return: True If the point is far from all others. """ ...
6836792aa32c47833a9839a85306e7d249c6a160
663,791
import torch def get_board_tensor(board_str, black_moves): """ function to move from FEN representation to 12x8x8 tensor Note: The rows and cols in the tensor correspond to ranks and files in the same order, i.e. first row is Rank 1, first col is File A. Also, the color to move next occupi...
bf19b91e4d7d952c6f3a958607436522ca1db872
663,792
import re def unsub_emails(unsub_list, email_list): """ Takes the list of plex user email address and filters out the members of the unsubscribe list. """ excludes = re.split(r",|,\s", unsub_list) email_list = list(set(email_list)^set(excludes)) return email_list
5acdc6472fad2b75244234c646612d2b0f38c727
663,793
import re def slice_marc_shorthand(string: str) -> tuple: """ Splits a string and gives a tuple of two elements containing the Main Number and the subfield of a marc shorthand Calls a regex check to make sure the format is corret :param str string: a string describing a marc shorthand, should look lik...
a80e762fe0c9a6cb3111bb491d9215f75c282c5f
663,794
import requests import sys import math def download_file(path, url, silent): """ Helper to download a file, displaying a handy little progress bar so you know the script isn't just hanging, but is working hard to deliver your software to you. """ response = requests.get(url, stream=True) l...
b78fd624ee1ae6164aeee9e05c5a4a641b0a5831
663,795
import socket def createTestSocket(test, addressFamily, socketType): """ Create a socket for the duration of the given test. @param test: the test to add cleanup to. @param addressFamily: an C{AF_*} constant @param socketType: a C{SOCK_*} constant. @return: a socket object. """ skt...
3b8e9d63e29151adb1bd2d2c4e48d07cb1bd4e6a
663,796
def accepted(message): """ A 202 response is typically used for actions that take a long while to process. It indicates that the request has been accepted for processing, but the processing has not been completed. The request might or might not be eventually acted upon, or even maybe disallowed when processing occ...
8a9acfa1607042121d3379fd615b58e0c04b8e88
663,797
import os def fixext(path, img): """Change the format of files with the wrong extension.""" path, ext = os.path.splitext(path) if img.format: return path + "." + img.format.lower() elif img.mode == 'RGBA': return path + ".png" elif ext.lower() not in [".jpg", ".jpeg", ".png", ".bm...
3d89d82dfdd1836aa3f22a58e579225272806958
663,798
from pathlib import Path def get_texture_type(image_path): """ Gets the PBR texture type from the filename. :param image_path: Path to the image from which to extract pbr type :return: """ filename = Path(image_path) texture_type = filename.stem.split('_')[-1] return texture_type
efe68b7e213200c5cfc40cf10ba2ea4c2b7903dc
663,799
def keyGen(attributes, data): """ Traverses the data and returns the key generated based on the given attributes. **Parameters**: attributes : list A list of attributes which define the key. data : dict The data for which the key has to be generated for. **Retur...
2fee66f6fef0266cbcea7c2d66c67a45d53d21ae
663,800
from datetime import datetime import os def get_filename(cluster_name): """ Build the output filename """ now_date = datetime.now() out_date = now_date.strftime("%Y-%m-%d_%H-%M") outfile_name = "cluster_constants_" + out_date + '.txt' if os.path.exists(outfile_name): os.remove(outf...
d97e2a42cac478544478eab9a7522aacdf49ac24
663,801
def _search(regexp, string): """Search or raise exception is nothing found.""" match = regexp.search(string) if match is None: raise RuntimeError("Cannot match: ", string) return match
f45a0fda002daba723d255c3f4b691c90bf63964
663,802
def ancestors(node): """Return a list of ancestors, starting with the direct parent and ending with the top-level (root) parent.""" result = [] parent = node.getParent() while parent is not None: result.append(parent) parent = parent.getParent() return result
2a5ad411ce0f36bc94d5b8437da0ccbc033de5cf
663,803
import io def jpg_infomation(path): """ 获取jpg图像的信息 https://www.ccoderun.ca/programming/2017-01-31_jpeg/ 0xffd8 :param path: :return: H,W,C """ f = open(path, 'rb') header = [int(v) for v in f.read(2)] if header[0] == 0xff and header[1] == 0xd8: while True: b...
1dc98d8926ddc1597248ad27cb3d87d917181dc0
663,804
def swap(num1, num2): """Pythonic way""" num1, num2 = num2, num1 return num1, num2
42af4ee48d8985ebff923ad5ea03a9a7f82c5bda
663,805
def to_binary_string(input_list): """ Assumes element at index 0 is the LSB. """ return "".join(map(str, reversed(input_list)))
5e19520b2ad54d15f3924db3629e6cd5720766e1
663,806
def calcMitGuideScore(hitSum): """ Sguide defined on http://crispr.mit.edu/about Input is the sum of all off-target hit scores. Returns the specificity of the guide. """ score = 100 / (100+hitSum) score = int(round(score*100)) return score
8c9a40c506e6c6e6bf780b088005542a29e8c328
663,807
def timeout(timeout): """ Condition to be used on Timers. True after the given amount of time has elapsed since this decorator became active. """ def inner(timer, *args, **kwargs): return timer >= timeout return inner
d6cafdbdd94c100f73a927bdb0b31c9d787bc595
663,808
def check_resource_deleted(error_message): """Create a callable to verify that a resource is deleted. To be used with the :meth:`run` function. The callable will raise an :class:`AssertionError` if the chosen resource is shown as existing in the response given to the callable Args: error_m...
73071ec4be55117461b1dd9a57da2ba875bc28ac
663,809
from typing import Callable from typing import Tuple from typing import List import re def substitutions(molecule: str) -> Callable[[Tuple[str, str]], List[str]]: """Returns a function for generating substitutions on molecule.""" def substitute(rule: Tuple[str, str]) -> List[str]: """Perform the rule...
d935140ccb96d9c0d5030ced2cdeca103a2b0940
663,811
def getCurvesListWithDifferentCurveName(originalCurveList, origCurve, newCurve): """ Takes in list of curves, curve name to be replaced, and curve name to replace with. Returns a list with the orginal and new curve names switched in the given curve list """ plentifulCurves_wDEPTH = originalCurveLis...
7e0f4af1d54e416b6b95e0ee30b82876a80320a1
663,812
from typing import Counter def number_of_contacts(records, direction=None, more=0): """ The number of contacts the user interacted with. Parameters ---------- direction : str, optional Filters the records by their direction: ``None`` for all records, ``'in'`` for incoming, and ``'...
06fb9e0ecce538a590eee4e204fd08fb5b187439
663,813
def select_Nair_subjects(candidates): """ Candidates must be dictionary or json structured and have a field called "JID" (from NairAbrahamMorphology.cat) which denotes the object ID for the Nair-Abraham catalog """ indices = [] for idx, candidate in enumerate(candidates): if...
c02cf1d73d5a1e2e747824d5df7ccc43551aa433
663,814
def _is_right_turn(p, q, r): """ Do the vectors pq:qr form a right turn? """ # Use cross product v1x = q['x_cord'] - p['x_cord'] v1y = q['y_cord'] - p['y_cord'] v2x = r['x_cord'] - q['x_cord'] v2y = r['y_cord'] - q['y_cord'] if v1x * v2y - v1y * v2x > 0: return False els...
dbbfee6325958d75f112261bf69b24731662d989
663,815
import torch def log_sinkhorn_iterations(Z: torch.Tensor, log_mu: torch.Tensor, log_nu: torch.Tensor, iters: int) -> torch.Tensor: """ Perform Sinkhorn Normalization in Log-space for stability""" u, v = torch.zeros_like(log_mu), torch.zeros_like(log_nu) for _ in range(iters): u = log_mu - torch.lo...
f87051e65ec22bc5b1edcab7b0961af5323db98d
663,816
def format_summary(a): """a is a vector of (median, min, max, std).""" return "{0:<6.3g} {3:<6.3g} ({1:.3g} - {2:.3g})".format(*a)
3fdc96d9f704007dc745e2c470233fa7b51c8730
663,817
def get_available_directions(character: dict, columns: int, rows: int) -> list: """ Get the list of available directions. :param character: a dictionary :param columns: an integer :param rows: an integer :precondition: character must be a dictionary :precondition: columns >= 0 :precondi...
eec1f32edec917996138c8d5d6428819920b27d8
663,818
import binascii def crc32(string: str) -> str: """Return the standard CRC32 checksum as a hexidecimal string.""" return "%08X" % binascii.crc32(string.encode())
6cc3f534bddf02066f638f86e2404496efb345b3
663,819
def xgcd(a, b): """Calculates the extended greatest common divisor for two numbers (extended Euclidean algorithm). Parameters ---------- a : int First number. b : int Second number. Returns ------- int: The extended greatest common divisor for the two given numb...
d11bcc8b790373c39666cfe8acb2ce9fa82779ea
663,821
def get_slots(intent_request): """ Fetch all the slots and their values from the current intent. """ return intent_request["currentIntent"]["slots"]
b8f140ea3c9473ff7507046f42ceaa770946a2b7
663,822
def rossler(x, y, z, a=0.2, b=0.2, c=5.7): """Compute next point in Rossler attractor.""" x_dot = -y - z y_dot = x + a*y z_dot = b + z*(x-c) return x_dot, y_dot, z_dot
82b9c71f264dee7d832c3f70f4155a8fb2117c19
663,823
import time def current_time(): """returns the current time for use in default as a callable""" return int(time.time())
53e368e42dbb5a48bcdc6b3b25555ed7fd3e2f1d
663,824
def _get_gp_ucb_dim(gp): """ Returns the dimensionality of the dimension. """ if hasattr(gp, 'ucb_dim') and gp.ucb_dim is not None: return gp.ucb_dim elif hasattr(gp.kernel, 'dim'): return gp.kernel.dim else: return 3.0
74ac922d66db4da6743bee97d4321bfa984b2096
663,825
from typing import Dict import os import json def load_result(file_name: str, results_path: str) -> Dict: """ Load the resulting file with a given name """ file_path = os.path.join(results_path, file_name) with open(file_path, 'r') as f: result_dictionary = json.load(f) return result_dictionar...
49fedef3d94805793e3bccdd191d196f2e7987e5
663,826
def find_cntrs(boxes): """Get the centers of the list of boxes in the input. Parameters ---------- boxes : list The list of the boxes where each box is [x,y,width,height] where x,y is the coordinates of the top-left point Returns ------- list Centers of each...
accd05af1a4e9fdb05ea8a644c6933a69a45f9a7
663,827
def _is_bazel_external_file(f): """Returns True if the given file is a Bazel external file.""" return f.path.startswith('external/')
ed843d2937efc92ed84132686b8135476ba96b73
663,828
def get_formatted_name(first, middle, last): """Generate a neatly formatted full name""" full_name=f"{first} {middle} {last}" return full_name.title() """this version works for people with middle name but breaks for people with only first and last names"""
75291005b2ad0650e2e1aa4c828dfd2411e01f9b
663,829
def fork(*args, **kwargs): """ Forks a new instance of Nuke optionally with the contents of the named file. """ return None
fa82abf68442082709acd62a418f37a438cb5d47
663,830
def str_set_of_candidates(candset, cand_names=None): """ nicely format a single committee """ if cand_names is None: namedset = [str(cand) for cand in candset] else: namedset = [cand_names[cand] for cand in candset] return "{" + ", ".join(map(str, namedset)) + "}"
f217354b6241b9c06e9b6b91ab66426fadb9e2bd
663,831
import re from typing import OrderedDict def get_example_sections(example): """Parses a multipart example and returns them in a dictionary by type. Types will be by language to highlight, except the special "__doc__" section. The default section is "html". """ parts = re.split(r'<!-- (.*) -->', ...
a28ede469e82755528013a3b1cc08a56ed024577
663,834
def square(x): """Returns the element-wise square of the input. Args: x (~chainerx.ndarray or scalar): Input data Returns: ~chainerx.ndarray: Returned array: :math:`y = x * x`. A scalar is returned if ``x`` is a scalar. Note: During backpropagation, this function propa...
e449dada65d469ea6592bf5fe34f455539258d31
663,835
import csv import operator def read_training_history(path, ordering=None): """Read training history from the specified CSV file. Args: path (str): Path to CSV file. ordering (str): Column name to order the entries with respect to or ``None`` if the entries should remain unordered....
7fb53ada411e08ff3723231311a639cb895d8cd6
663,836
def getMatrix(net, verbose, matrix, MatrixSum): # , mtxplfile, mtxtfile): """ This method is to read matrix from the given file. """ matrixPshort = [] startVertices = [] endVertices = [] Pshort_EffCells = 0 periodList = [] ODpairs = 0 origins = 0 dest = 0 CurrentMatrixS...
3c05471d9ef074a361dab06fe0c5859cef2b123e
663,837
import pickle def dump_object(value): """Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else. """ t = type(value) if t == int: return str(value).encode("ascii") return b"!" + pickle.dumps(value)
3f77ea453da5deb5d693393220c4be75254b7832
663,838
def diff(a, b): """ Takes the difference of two numbers Arguments --------- a : int, float b : int, float Returns ------- d : float difference between a and b """ return a - b
c6b30403da67f1f1a27efc59243b5b5c46f90f20
663,839
def get_labels(file_path, known_classes=('normal', 'bacteria', 'virus'), default='normal'): """get labels from filepath""" base = file_path.stem for k in known_classes: if k in base: return k return default
9718c97115f3812199cabed1875381a80c1d1e1c
663,840
import six def merge_config(a, b): """Merges config b in a.""" for k, v in six.iteritems(b): if k in a and isinstance(v, dict): merge_config(a[k], v) else: a[k] = v return a
f23c57aac3baeb26c819d1c0faf87a7e4263d1c1
663,841
def _cert_type_from_kwargs(**kwargs): """Return cert type string from kwargs values""" for k in ('admin', 'creator', 'initiator', 'platform'): try: if k in kwargs['user_type'] and kwargs['user_type'][k]: return k except LookupError: if k in kwargs and kwa...
c4f055eee201dcacd5590afb5b4f9f65edca3c9f
663,842
import numpy def _compare_chunk_dicts(first_dict, second_dict): """Compare two dictionaries, mapping chunk index to either hours or months. :param first_dict: First dictionary. :param second_dict: Second dictionary. :return: are_dicts_equal: Boolean flag. """ first_keys = list(first_dict.key...
0e3aa22a54f6ed031f9d3ead4c16954146b5876c
663,843
def export(*args, **kwargs): """Decorator, use to mark exportable methods.""" def wrapper(method): method.export_params = [ args, kwargs ] return method return wrapper
e3910d56cb179f7b316fd6c8569e6bfa0b2b2474
663,844
def readPhraseIndexFromFiles (filenames): """Takes a list of files; reads phrases from them, with one phrase per line, ignoring blank lines and lines starting with '#'. Returns a map from words to the list of phrases they are the first word of.""" phraseIndex = dict() for filename in filenames: ...
c2968c8d7613c501c7c6bd37ead7017ded57be09
663,845
def campaign_news_item_save_doc_template_values(url_root): """ Show documentation about campaignNewsItemSave """ required_query_parameter_list = [ { 'name': 'voter_device_id', 'value': 'string', # boolean, integer, long, string 'description': ...
4a44bf91bf2398aa69e20c767e9fe73ee939af29
663,847
import os import shutil def copy_directory(path_src: str, path_dst: str): """copy directory Arguments: path_src {str} -- copy source directory path_dst {str} -- copy destination directory """ if not path_src or not path_dst: print(f"path_src could be empty. path_sr...
6fed7d5c4ec25a78049b082a976ccee4710dfac2
663,848
def _escape(value): """Dirty hacks to escape according to ParaView expectations""" value = value.replace("\n", "\\n") value = value.replace("\"", "\\\"") value = '"' + value + '"' return value
8a65c442902d3fd2bb81010e3c25537be2333b65
663,849
def first_plus_last(num: int) -> int: """Sum first and last digits of an integer.""" as_string = str(num) return int(as_string[0]) + int(as_string[-1])
b9140d7c4a46d10d928d465445aa10953e458379
663,850
def extract_name(row): """ Helper function for comparing datasets, this extracts the name from the db name Args: row: row in the dataframe representing the db model Returns: name extracted from agency_name or np.nan """ return row['agency_name'][:row['agency_name']....
84d525d008cf35e4ee0b1347caf0909a67cad1e3
663,852
import re def process_headers(txt, case='sentenceCase'): """Get headers""" in_code_block = False #Markdown processor ignores whitespace at start and end of a markdown cell #txt = txt.strip() newtxt = [] #We will see how to improve the handling of code blocks in markdown cells later for l...
b730d6108c5d6bbdcc35f48257c10899560ed109
663,853
from typing import Dict def __construct_robot_message_subject(serial_number: str, uuid: str) -> Dict[str, str]: """Generates a robot subject for a plate event message. Arguments: serial_number {str} -- The robot serial number. uuid {str} -- The robot uuid. Returns: {Dict[str, str...
94c08e3b32608a62b7504b43f2faeac141ead6c6
663,854
import os def report_dir(tmpdir_factory): """ `tmpdir` fixture is somehow failing for this module, so this fixture explicitly makes sure that given basetemp exists. """ basetemp = tmpdir_factory.getbasetemp().strpath if not os.path.exists(basetemp): os.makedirs(basetemp) return tmp...
832d98ca145febfcfe7e39957fede61c06ed392f
663,855
def cap_text(text): """capitalize() upper cases the first letter of a string.""" return text.capitalize()
89266c34ee581ec31152fc480762a13df61b10c6
663,857
def drop_features(df): """Drop extra features not engineered""" return df.drop(['Ticket', 'Name', 'Age', 'Embarked', 'Pclass', 'Sex', 'Cabin', 'Fare', 'SibSp'], axis=1)
a634deb561eebbc3e3717cafa3f2d040a527ccee
663,858
import torch def parameters_to_vector(model: torch.nn.Module): """Given a torch model returns a torch tensor with all its parameters""" return torch.cat([p.data.view(-1) for p in model.parameters()], dim=0)
7042c338f8f4161fee9663e04c6b6b2144db1de4
663,859
import torch def squash(caps_poses, squashing_type): """ The non-linear function to ensure that short vectors get shrunk to almost zero length and long vectors get shrunk to a length slightly below 1 (only for dynamic routing). :param caps_poses: The capsules poses, shape [b, B, ih, iw, is0, is1] ...
6943c1cc90a7a93a848a6d413e8730615cb40a6c
663,860
import re def get_level(line, indent) : """ Return the level of indentation of a given line """ level = 0 while line.startswith(indent) : line = line[len(indent):] level += 1 if re.match(r"^(\s+)", line) : raise Exception("Syntax Error") return level
3fbaf5f2c142af988d3ba341bcfa9d8a43c584d8
663,861
def construct_fasta_entry(host_id, sequence, description=None, wrap=None): """Returns a FASTA-formatted entry for the sequence. Parameters ---------- host_id : int Host ID of target host sequence : iterable If sequence is a list of single characters, the list will be joined ...
9cdb3118057b72e3b0e742540260d1bb2b72b61f
663,862
def mesh_merge_faces(mesh, faces): """Merge two faces of a mesh over their shared edge. Parameters ---------- mesh : :class:`compas.datastructures.Mesh` faces : list of face identifiers Returns ------- int """ u, v = None, None for i, j in mesh.face_halfedges(faces[0]): ...
2e72d412544f089fda1d76d6ccb54ab3334d7674
663,863
def get_network_device_id(operands): """ Return the id (ordinal) of the device the tensor network is on, or None if it is on the CPU. """ device_id = operands[0].device_id if not all(operand.device_id == device_id for operand in operands): devices = set(operand.device_id for operand in opera...
09202857b5e29da4359ef784008aed46461e7836
663,864
def get_triangular(n: int) -> int: """Get `n`-th triangular number Args: n: Index of triangular number Examples: >>> print(get_triangular(10)) 55 """ return n * (n + 1) // 2
e1151418e3328eb358a592af187240f6a2a09989
663,865
def sort_bl(p): """Sort a tuple that starts with a pair of antennas, and may have stuff after.""" if p[1] >= p[0]: return p return (p[1], p[0]) + p[2:]
d30582c7d05fd5ab151d3adf24c122f1199ad5a0
663,866
def round_down(x, n): # type: (int, int) -> int """Round down `x` to nearest `n`.""" return x // n * n
b60c94ddae5a852d5d0c750e574de151f045648c
663,867
import torch def normalize(tensor, min=None, max=None): """ Normalize the tensor values between [0-1] Parameters ---------- tensor : Tensor the input tensor min : int or float (optional) the value to be considered zero. If None, min(tensor) will be used instead (default is Non...
46f413ffc1aacde12ab6f8d95bba105fc58f86d3
663,868
def outline_ci_elem(elem, _lvl=0, brief=False, doSort=False, includeLineNos=False): """Return an outline of the given codeintel tree element.""" indent = ' ' result = [] def _dump(s): if includeLineNos: startline = elem.get("line") lineend = elem.get("lineend") ...
088d9cedd0535f244cfaf897793022b250e2db0e
663,869
def dict_get(dictionary, *args, **kwargs): """Return first value in dictionary by iterating through keys""" for key in args: try: return dictionary[key] except KeyError: pass if 'default' in kwargs: return kwargs['default'] else: raise KeyError
70acb6fe763c6aea7601f2a2f2a148bb73d13d91
663,870
import random import math def GetSample(gan_params): """Get one sample for each range specified in gan_params.""" ret = {} for param_name, param_info in sorted(gan_params.items()): if param_info.is_discrete: v = random.choice(param_info.range) else: assert isinstance(param_info.default, floa...
b623b6fdae3c17d3cad38bea70439fbb3fc4f71b
663,871
def tag_filter(tag_list, base_df): """Search with tags. Args: base_df (DataFrame): Search target. tag_list (list): List of search tag. Returns: (DataFrame): Searched DataFrame. """ result_df = base_df for tag in tag_list: mask = result_df["tag"].apply(lambda x:...
fe6a9f075d859167d3ec160b96c7f839db394154
663,872
def getTwitchUsernames(): """ Returns: List of usernames. """ with open('./streamers.csv', 'r') as f: return [(line.split(',')[0], line.split(',')[1]) for line in f.read().split('\n') if len(line) > 0]
df7498a68b0596abf75e04a2fbda6e2799d3e3ba
663,873
import os from datetime import datetime def file_mtime_utc(file_name): """ Return a timezone-unaware datetime in UTC for the last modified time of a file. """ mtime = os.path.getmtime(file_name) date = datetime.utcfromtimestamp(mtime) return date.replace(tzinfo=None)
fe009f35a46d3fe8ba0c89d4d7f287d00e6b2d05
663,874
import json def decode_predictions(preds, top=5): """Decode the prediction of an ImageNet model. # Arguments preds: Numpy tensor encoding a batch of predictions. top: integer, how many top-guesses to return. # Returns A list of lists of top class prediction tuples `(class...
0478877a61a7d5f36eae93e4e6590c2b0668a8ef
663,875
def get_num(x): """Grab all integers from string. Arguments: *x* (string) -- string containing integers Returns: *integer* -- created from string """ return int(''.join(ele for ele in x if ele.isdigit()))
102c07a64f18fa10696903c41ab9d661caccc9de
663,876
def reverse_complement(seq): """Return reverse complement of a dna sequence.""" bases_dict = { 'A': 'T', 'a': 't', 'C': 'G', 'g': 'c', 'G': 'C', 'c': 'g', 'T': 'A', 't': 'a'} return "".join([bases_dict[base] for base in reversed(seq)])
f64c2b5a003d6a36a1a615657efc4b1cbbf3c709
663,877
def list_get(): # noqa: E501 """Get list of all convertes and their possible targets # noqa: E501 :rtype: str """ return "Something cool"
01aa70591818e146916a6f377a2d70d60506b7a5
663,878
from typing import Set def config_files() -> Set[str]: """ Return a set of the names of all the PyTorch mypy config files. """ return { 'mypy.ini', 'mypy-strict.ini', }
a3073c3292fe0abbdf424c0661fba62375e508a8
663,879
def forward_until(source, start, symbol): """ forward util a symbol """ count = len(symbol) length = len(source) + 1 - count result = [] while start < length and source[start:start + count] != symbol: if source[start] == '\\': if start + 1 < length: result.app...
7f07fc7dac894505fff3e33bec0f3930bb6e1562
663,880
import pipes def tokens_to_string(tokens): """ Build string from tokens with proper quoting. :param tokens: list of string tokens :return: space-separated string of tokens """ return ' '.join(map(pipes.quote, tokens))
aac25e891e8bc39bd18f159fdcd19a466d82f9f1
663,881
def unique_dot_keys(experiment_keys): """ Return the first run of each dot, given all experiments. """ result = list() for key in sorted(experiment_keys): if key[:2] not in map(lambda x: x[:2], result): result.append(key) return(result)
53ddc58e43eb628d49c1347937f1932345658f26
663,882
def _checkFileEndingGeneric(file_: str, ending: str) -> bool: """ generic function that checks if file_ ends with param 'ending' """ return file_.endswith(ending)
412716c9f8250076944881f82b6ede860dba7e38
663,883