content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_all_duplicate(df, column_list): """ Get all duplicated rows. Extract all rows that the return value of 'DataFrame.duplicated' is true. Raises ------ ValueError If the input DataFrame is empty. Parameters ---------- df : DataFrame Base dataframe (required) ...
89daffd32f40a80643736f0d754718345c494e3a
644,591
import os def samefile_simple(path, other_path): """ Fill in for os.path.samefile when it is unavailable (Windows+py2). Do a case-insensitive string comparison in this case plus comparing the full stat result (including times) because Windows + py2 doesn't support the stat fields needed for i...
abe5d0aec62639d1e825950a2f25ad109b483c4b
644,592
def isMixedCase (tok): """Returns true if the token contains at least one upper-case letter and another character type, which may be either a lower-case letter or a non-letter. Examples: ProSys, eBay """ # Clojure original: # (fn [token] ;; ProSys, eBay # (if-not (empty? token) ...
e163d0adc5ce7af2f4bf25afbaf690f30fdb62d1
644,595
import re def get_next_number(num, nums=[]): """ Returns a list of numbers traversed in files """ with open('channel/{}.txt'.format(num)) as f: dat = f.read() pattern = re.compile(r'Next nothing is (\d+)') match = pattern.findall(dat) if match: rnum = get_next_number(match[0], nums=nums) if rnum: ...
c376f520ec8fe6020c7178456731f85e0e99606f
644,596
import statistics def minMaxAvgPerBin(binnedResults, statFunction): """ For each bin in the binned results, find the minimum, maximum, and average of the value of the results determined by statFunction. The constants MMAMin, MMAMax, and MMAAvg are meant for accessing the results tuple data. :param bin...
3cb11ac83d816404e8ae4a32acae5183afb365a1
644,597
def is_heavy_atom(atom): """Check if an atom is neither a hydrogen or a virtual site.""" return not (atom.resname.startswith("H") or atom.resname.startswith("M"))
f78a2b2d849a054b28b33c7590c26319e365f41f
644,598
def get_headers(): """Get autorisation headers""" headers = {} headers["accept"] = "application/json" #headers["Authorization"] = "Bearer {}".format('logic') return headers
2e585a7a619edd73a7ca257f429c115686bc6543
644,599
def split_content(content): """ Split the rule into a list of bags. """ bags = [] # Return an empty list if there is no content. if "no other" in content: return bags # Separate each type of bag. for bag in content.replace("bags", "").replace("bag", "").split(","): # Separat...
e976f35688e3c391afdff309970d7d956e987d60
644,600
import os def resolvePath(file, pathEnviron): """Resolve a file using the passed in path environment or list of paths.""" (dir, basename) = os.path.split(file) if dir: return file # determine if pathEnviron is a list of paths or a path env i.e. .:/bin:/usr/bin if isinstance(pathEnviron, ...
8ec86f433b85aa3245de213497b61ef2b4250a87
644,601
import re def sanitize_output(output): """Redact access tokens from CLI output to prevent error messages revealing them""" return re.sub(r"\"accessToken\": \"(.*?)(\"|$)", "****", output)
07472b6a7289db9400e56d94d5691fb2f09ba416
644,602
def selected_only(bpy_data): """ Filter out all the objects that are not selected """ def selected_in_subtree(parent_obj): return parent_obj.select or any(selected_in_subtree(child) for child in parent_obj.children) bpy_data['objects'] = [obj for obj in bpy_data['objects'] if selected_in_s...
a41c57451963e9ad82dc435d0aeb4e0f4ea860c7
644,603
def braf_v600e_mane_c(): """Create test fixture for BRAF V600E MANE Transcript on c coordinate.""" return { 'refseq': 'NM_001374258.1', 'ensembl': 'ENST00000644969.2', 'pos': (1919, 1919), 'status': 'MANE Select', 'strand': '-', 'coding_start_site': 226, '...
3378062a14614ac83f6b851037d05d84d452db95
644,604
def get_max_locs(paths, he_locs_list, e1wh_locs_list, e1_locs_list, ca_locs_list): """ obtaining the maximum number of locations :param paths: :param he_locs_list: :param e1wh_locs_list: :param e1_locs_list: :param ca_locs_list: :return: """ max_he_locs = 0 m...
6e2802ac1803bccbf653a2d6d95780304d0ca011
644,605
import os import pickle def save_params_pickle(params): """ save copy of params as pickle for reproducibility. """ handle = open(os.path.join(params["dannce_train_dir"], "params.pickle"), "wb") pickle.dump(params, handle) return True
51049a00f2087656348f3b8d61c641a2ff694c90
644,606
import math def slider_to_freq(value): """ convert slider value to frequency (20Hz-20kHz) base-2 logarithmic slider """ return round(math.pow(2, value * 1e-4))
2a72e26bd7d25cb22b1c2a85d0c1332d55fb2135
644,607
import os def get_extension(path: str) -> str: """Return the extension of a file path.""" return os.path.splitext(path)[1]
f5a4c510e7e4f6ee84ec773a79f8dc233757c7dc
644,609
def to_upper(text): """Convert word to uppercase.""" return text.upper().strip()
7721b9881babef2de879471f44ad848c4f51876a
644,610
from typing import Callable from typing import List def loop(func: Callable, reqList: List) -> List: """ Helper function, that iterates over a given result List from an Api call and adds the result by parsing it through the given func :param func: This function is called within the iteration. It shoul...
f08785044ad3d0d57fb3a1b5f8eebf1c790ccd71
644,611
import warnings def obtain_input_shape( input_shape, default_size, min_size, data_format, require_flatten, weights=None ): """ 모델의 입력 shape을 계산/검증하는 내부 유틸리티입니다. Parameters ---------- input_shape : [type] None (디폴트 네트워크 입력 shape 반환), 또는 검증을 위해 사용자가 제공한 shape 중 하나입니다. default_size :...
aa66b9bc56e1ff87edac72938c4b156ab096c99e
644,612
import re import sys def _is_referenced_in_argv(method_name): """ Various test runners allow one to run a specific test like so: python -m unittest -v <test_module>.<test_name> Return True is the given method name is so referenced. :param method_name: Base name of the method to add. ...
06cbf857df40db202374d6110aaa10c98e7cf08a
644,613
def shiftLeft(input, p): """Take a bitstring 'input' of arbitrary length. Shift it left by 'p' places. Left means that the 'p' most significant bits are shifted out and dropped, while 'p' 0s are inserted in the the least significant bits. Note that, because the bitstring representation is little-endian,...
514a1c6f3bd60adc3a095a9dfea9c2468e8a4b38
644,614
def get_y_values(x: int, slopes: list, coordinates, edge_count: int) -> list: """ Calculate the y value of the current x from each edge :param x: x-coordinate of the current node :param slopes:a list of slopes of all edges of the polygon :param coordinates: a list of vertices of the polygon :par...
846fd515706eb17b5a564daab8a293037cae6641
644,615
import subprocess import json def streams_info(segment): """Return ffprobe's info on streams as a list of dicts""" output = subprocess.check_output([ 'ffprobe', '-hide_banner', '-loglevel', 'fatal', # suppress noisy output '-of', 'json', '-show_streams', # get streams info as json segment.path, ]) # outpu...
5f443946494e6f78fd2d2a9268082c70f2f96e5b
644,616
def create_norm_peptide_column_if_needed(row_meta_df, gcp_normalization_peptide_field, gcp_normalization_peptide_id): """If it doesn't already exist, create a new column indicating the norm peptide for each probe. Modifies row_meta_df in-place. Args: row_meta_df (pandas df): gcp_normal...
2b499bb23a186a6c7bff46998a2377fa38b8f114
644,617
def filter_shards(tests, index, shards): """Filters the shards. Watch out about integer based arithmetics. """ # The following code could be made more terse but I liked the extra clarity. assert 0 <= index < shards total = len(tests) quotient, remainder = divmod(total, shards) # 1 item of each remainde...
79ad6215930027542d8faf9265746c6e3d93494f
644,618
def get_peak_indices(uvvis_obj): """Finds indices of unique value/extinction objects at 'peak' scope :param chemdataextractor.model.UvvisSpectrum uvvis_obj : UvvisSpectrum containng peak data :returns list value_peak_indices : UvvisPeak indices pointing to objects solely containing uvvis values ...
f5e14840813c72d83b2ed0ed6f4369822a1da28a
644,619
import six def _process_model_like_filter(model, query, filters): """Applies regex expression filtering to a query. :param model: model to apply filters to :param query: query to apply filters to :param filters: dictionary of filters with regex values :returns: the updated query. """ if q...
25e1588a2ef50cea04556c6b2046c855bb83d620
644,620
def dobro(preco, moeda=''): """ --> Multiplica o valor inserido por 2. :param preco: valor a ser multiplicado :param moeda: qual a moeda a ser exibida :return: valor dobrado """ final = preco * 2 if moeda == '': return f'{final}'.replace('.', ',') else: return f'{moed...
15584b04d670e78740a9886b1be145d159b66d74
644,622
def to_bool(cfg_value): """Convert config file booleans to Python booleans.""" if cfg_value in {"0", "false", "False", "no"}: return False if cfg_value in {"1", "true", "True", "yes"}: return True raise ValueError("Value {} in config file must be boolean in" " a form...
5908a6cc9386678ce7f76b3746b7a42dcaa15964
644,623
import sys import os import subprocess import tempfile def temp_volume(name): """Creates a temporary volume and returns the path to it. Notes: Darwin: The MacOS implementation creates a ram drive. Win32: The Windows implementation creates a temporary directory and ...
0fbda4013f42a20d89b9528b031a59d382b3052e
644,625
def solve_game(best_actions, game, state): """Returns the value of the state (to both players) and the optimal move to play in this state. Fills in the dictionary 'best_actions' with the best actions to take in all the states that are descendants of state (including state). """ if game.is_termin...
78fad694b533f3ef9ddcc70546b38a271181add1
644,627
def GeraDicionário(): """ Carrega o arquivo com a lista de palavras e com isso gera um dicionário, que é uma lista contendo todas as palavras, e a devolve """ arquivo = open('Palavra.txt', 'r') dicionário = [] print('Carregando palavras para o Dicionário... ') for palavra in arquivo:...
adc6c48633c053811ba881fc6cebda310e6e366d
644,628
def truth(a): """Return True if a is true, False otherwise.""" return True if a else False
b98d494fc05fd1bdf3e63b6e6d64cece0c5c2f2d
644,629
def invert_permutation(perm): """Implement `invert_permutation`.""" return tuple(perm.index(i) for i in range(len(perm)))
5bf59a37e490ab93d5fb2d4d1b40c5c5a5a22348
644,630
import torch def bures_Wasserstein(a_cov, b_cov): """ Minimum of the Frobenius norm of the covariance roots. """ U, S, V = torch.svd(a_cov) S_root = S.clamp(min=0).pow(0.5) root_a_cov = U.mm(torch.diag(S_root)).mm(V.t()) # Interactions cov_prod = root_a_cov.mm(b_cov).mm(root_a_cov) re...
2451ceab3917314d45d62baf2faeb75a51ad7341
644,631
def make_set(*args): """Promise a set.""" return set(args)
95a9ffe00a3e9f2844618cfc1ae500cb711577ea
644,632
def calculate_max_timestamp(target): """ Retrive max timestamp """ if not target.dependency(): return 0.0 if target.max(): return target.max() value = max(target.dependency(), key=lambda item: item.timestamp()).timestamp() return target.max(value)
cc56e910c58dea0ece94747506b60082a621f016
644,633
def manhattan_distance(point_1, point_2): """Return Manhattan distance between two points.""" return sum(abs(a - b) for a, b in zip(point_1, point_2))
48808356b202751ce15481c186c3f981481fee91
644,635
import json def save_json(input_dict, output_file): """save dictionary to file as json. Returns the output file written. Parameters ========== content: the dictionary to save output_file: the output_file to save to """ with open(output_file, "w") as filey: filey.writel...
05d5c8440f5d7e7a021d91136e2277031de53f18
644,636
def dwid_exists(dwid, cursor): """See if a dwid exists in the database or not. If yes, return 1, if not return 0.""" array = (dwid,) cursor.execute('SELECT * from dwids where dwid=?', array) if cursor.fetchone(): return 1 else: return 0
08586088a14cdc11f8308da3d3038667c672fc13
644,637
def is_HoleUD_dict(obj_dict): """Check if the object need to be updated for HoleUD""" if "__class__" in obj_dict.keys() and obj_dict["__class__"] == "HoleUD": # Old label : Hole_Rotor_R0_T0_S0 # Old label : HoleMagnet_Rotor_Parallel_N_R0_T0_S0 return len(obj_dict["surf_list"][0]["label"]...
95158c19774a7dc409ab475906caf4afa3946c3b
644,638
import subprocess import json def k_get(qry): """run kubectl get and return parsed json output""" if not isinstance(qry, list): qry = [qry] # this will raise exception if it fails: output = subprocess.check_output(['kubectl', 'get', '--output=json'] + qry) output = output.decode('utf-8') ...
d3e95bb92b7688e9c752a836a520987cba4c5b94
644,639
def _warning(msg, *a, **kwargs): """Improve the printing of user warnings.""" return str(msg) + "\n"
e1c26e104adaf905e3928c7aed2329956144d795
644,640
import argparse def byte_parser(): """Parse args""" parser = argparse.ArgumentParser() parser.add_argument( "-K", "--key", required=True, type=str, help="API Key for Bytesized Hosting" ) parser.add_argument( "-U", "--url", default="https://bytesized-hosting.com/api/v1/accounts....
cda9cd7606a90ed804f386a0be1432abf14363ca
644,641
import sys def get_cmd_param(index, default=None): """ 取得 shell 參數 """ if len(sys.argv) > index: return sys.argv[index] return default
07d6482b56837ced443944c1925458738c98089a
644,642
import re def timestamp(fstr): """ extract the start time from the path of .et3 file (strings) """ pattern = re.compile(r"(?P<date>\d+-\d+-\d+-\d+-\d+-\d+)") t = pattern.search(fstr) time_start = None if t is not None: time_start = t.group("date") # replace DATA2014-12-28-...
bde9c5ac5092f033679b3bea941b0c544f4e37de
644,643
def test_big_number(): """Check that large literals work properly.""" return """ fn main() { {dest} = 999999999999999999; } """
7266cd6cb268e1032b88eeae12be4e8d49d6c611
644,644
def mult(a, b): """Wrapper for multiplication""" return a*b
1c58cfaa1e3561aaa456abfa9673578abc424f93
644,646
def standardize_name(name: str) -> str: """Remove spaces, hyphens, and make lowercase""" if isinstance(name, str): return name.replace('-', '').replace(' ', '').lower() else: return name
b856eddd4616161a1550d7b8a3f710b966972565
644,647
def get_data(request): """ 获取POST请求中json 数据 :param request: :return: data dict """ json_data = request.json print("=================================================") print(f'json data: \n{type(json_data)}\n{json_data}') print("=================================================") ...
64808b992ed96a6496e15b064ea7232a0d23050c
644,648
def get_rail_id(row): """ Extract specific rail_ids from complex data structure that assigns rail_ids (Sample IDs) to snaptron_ids (exon-exon junctions). Designed to be used as a pd.DataFrame().apply() function. Arguments: row - a row in the junction dataframe Output: a list of sample IDs ...
f45cf4609360b99ea56652f42e7213bfe43f0b50
644,651
import os def up(path, n=1, lastSeparator=True): """Examples: up('C:/Users/SonGuhun') => 'C:\\Users\\' up('C:/Users/SonGuhun', lastSeparator=False) => 'C:\\Users' up('C:\\Users\\SonGuhun\\Documents', n=2) => 'C:\\Users\\' """ return os.path.abspath(os.path.join(path ,"/".join(['..' for i ...
d42df9ad6fc31614655921ec06de20b3bf1c3d20
644,652
import time def get_today(): """ 获取当日的日期 格式为{}/{}/{} """ time_get = time.gmtime(time.time()) return '{}/{}/{}'.format(time_get.tm_year,time_get.tm_mon,time_get.tm_mday),time_get.tm_mday
e2b3c49a5c07561ed86ce44a824a8b0f421d45a2
644,654
import inspect def attempted_operation(): """Gets the command entered by the user (e.g. put).""" curframe = inspect.currentframe() return inspect.getouterframes(curframe, 2)[3].function
48b70849e9c47925e53e737b071659755544f49d
644,655
def partition(array): """ partition split array in half """ return [array[len(array)//2:], array[:len(array)//2]]
713caa069bad18dc5a5a7f69813de34075f8f3eb
644,656
def create_body_dict(name, schema): """ Create a body description from the name and the schema.""" body_dict = {} if schema: body_dict['in'] = 'body' body_dict['name'] = name body_dict['schema'] = schema if 'description' in schema: body_dict['description'] = schem...
dcdb57ea96c0d871ca1481bd523720aaa51d573b
644,657
from sys import platform def normpath(pathname): """Make sure no illegal characters are contained in the file name.""" illegal_chars = ":?*" for c in illegal_chars: # Colon (:) may in the path after the drive letter. if platform == "win32" and c == ":" and pathname[1:2] == ":": ...
ed62abb0ccc01dd65d9cf188d730e49db780f4a2
644,658
import pickle import hashlib def hash_data(data, blocksize=65536): """" Hashes list of data, strings or data """ data = pickle.dumps(data) hasher = hashlib.sha1() hasher.update(data) return hasher.hexdigest()
96262a9e0227010551d28fffd3e85128ddb5348e
644,659
import subprocess def run_client(argv0, *args): """Run the casper client, compiling it if necessary, with the given command-line args""" return subprocess.check_output(argv0 + list(args))
b789526a731000b1d4b764ee7e9780532bab0dc3
644,660
import torch def add_noise(x_data, noise_std_percent): """ Adds normal noise to a dataset @param noise_std_percent tensor with standard deviation of the noise, as percent of the mean of the magnitude for that dimension @return x_data_, same as x_data but with noise added to it """ assert (...
4f9f98f36b829745ac9cec1bae43a0fcd2740954
644,661
def nested_list_map(lis: list, func) -> list: """Nested mapping for a nested list.""" def _nested_fn(obj): if isinstance(obj, list): return list(map(_nested_fn, obj)) else: return func(obj) # assert isinstance(lis, list), type(lis) return _nested_fn(...
5be01276ae0ce51a823a2372ff905f049717a2a2
644,662
def hi_there(): """ Hi There Function """ print("now you are inside the hi_there() function") def greet(): return "now you are in the greet() function" def welcome(): return "now you are in the welcome() function" print(greet()) print(welcome()) print("now you are back in...
d42a246b58b1427905e51011838f100aa96ec494
644,664
def calc_short_input(xdata, names, shortNames): """ Отбор данных по укороченному списку показателей. Аргументы: xdata - NDArray - Исходная матрица данных. names - NDArray - Весь список колонок данных xdata. shortNames - NDArray - Короткий список выбираемых из данных колонок. Возврат:...
87b63a7780e96db066457dc242720addaa3405ce
644,666
import json def get_diagonal_len(pitch, jaw, code_book): """get the diagonal length of the bounding box through Codebook """ with open(code_book) as cb: json_data = json.load(cb) # Codebook format: {"<latitude_1>": {"<longitude_1>": [<width_1>, <height_1>, <diagonal_length_1>]}} di...
c8f6c8ad883c172490d0e72cb41c27a1d35a0942
644,667
def getDocComment(node): """ Returns the first doc comment of the given node. """ comments = getattr(node, "comments", None) if comments: for comment in comments: if comment.variant == "doc": return comment return None
4cc32f84d4e127880f9a137447e2d9401a6fbd6c
644,668
def distance(a, b): """Return the distance between two points (rounded as per TSP datafile)""" return int(abs(a - b) + 0.5)
c1664a48267854bf6c474323520d04188ce0656c
644,669
import os def filenameToModuleName(fn): """ Convert a name in the filesystem to the name of the Python module it is. This is agressive about getting a module name back from a file; it will always return a string. Agressive means 'sometimes wrong'; it won't look at the Python path or try to do an...
99e58d7c0f7c31e89c9ebbb77dbd77d056b2a632
644,670
def find_class_in_dict(cls, d, include=None, exclude=None): """Get a list of keys that are an instance of a class in a dict""" names = [] for key, value in d.copy().items(): if not isinstance(value, type): continue if issubclass(value, cls): if include and include not...
e9d4ad70a51e12d862a073256378e8a8c54c0680
644,671
def summoner_ilha_nublar(): """ Summoner Name: Ilha Nubllar Region: Brazil """ return { 'summoner_name': 'Ilha Nublar', 'summoner_region': 'br1', 'tft_get_matches_by_summoner': [ 'BR1_1882323432', 'BR1_1775035230', 'BR1_1770334549', ...
156aa3a909af85bac3a0a7fdeafa8b2196fdb783
644,673
def generate_pycamp_summary(events): """ イベント情報一覧からレスポンス用のattachementsを生成する """ attachements = [] # 新しい方が上にあるので、逆順で処理する for event in reversed(events): # イベント名、URL、日付 title = "<{url}|{title}> ({started_at:%Y年%m月%d日})\n".format(**event) ptypes = [] for pinfo in even...
f49f19da64990ee06af9b2ed7369ebf53ea07ef9
644,674
import codecs import re def get_replies(message_file, charset=None): """ Finds replies within a message and returns a list containing each reply. Args: message_file (str): The email's filename. charset (str): The optional codec to use for opening the file. Returns: list: ...
56e6f122b0995deff70e302ef9503fb73ca82a5a
644,675
import sqlite3 def search_db(dbname,table): """ @param dbname: name of the database @param table: table to be used for the search @return: the data that was retrieved This function just performs a very simple select all from the table and returns the data """ conn = sqlite3.connect(dbnam...
2a7ca0b5f213a3d52bba205130e04d479925d3ef
644,676
def has_repeating_letter(text): """Check if a string has a repeating letter with one letter in between""" # Check every combination of three letters # and see if the first and third are the same. # If there is any such combination, return True, False otherwise. for i in range(len(text) - 2): ...
29b621526ad56c0a04d94f7a53b20e1486c362ad
644,677
import socket def canonv4(text): """canonicalize an IPv4 address""" if text is None: return None try: addr = socket.inet_pton(socket.AF_INET, text) return socket.inet_ntop(socket.AF_INET, addr) except socket.error: #print 'canonv4 failed on', text return None
aa502532100d0e434eb7a2a5c8b635f73634e56a
644,678
import os def get_file_name_without_path(file_name): """获取文件名 去除路径信息""" return os.path.split(file_name)[1]
222243e075c5110f29e2530fe4e10aaaefe96efe
644,679
def _call_args_nokwargs(func_arg1, call_arg1): """Test utility for args no kwargs case where values passed from call site""" return func_arg1 + call_arg1
34c6c72b9bb579de847a512e5808f552115be796
644,680
def is_lock(lock): """ Tests if the given lock is an instance of a lock class """ if lock is None: # Don't do useless tests return False for attr in ('acquire', 'release', '__enter__', '__exit__'): if not hasattr(lock, attr): # Missing something retur...
d065d54b6c559f9855ef6e37258f0f77b4ebb2b3
644,681
def perfect(number: int) -> bool: """ >>> perfect(27) False >>> perfect(28) True >>> perfect(29) False Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at mos...
17f4b82b1a6e1ad21e106d841f04f0d3da3d1a8c
644,682
import numpy def geo_to_ecef(lat, lon, elev): """ Convert latitude (rad), longitude (rad), elevation (m) to earth- centered, earth-fixed coordinates. """ WGS84_a = 6378137.00000000 WGS84_b = 6356752.31424518 N = WGS84_a ** 2 / numpy.sqrt(WGS84_a ** 2 * numpy.cos(lat) ** 2 + WGS84_b ** 2 *...
64764de2561d1c1221d49c048371ac8e779ebfb8
644,683
import re def get_function_from_statement(statement): """ docstring tbd """ match = re.match(r'.+\(.*\)', statement) function_str = match.group() if match else '' return function_str
728de947d3ef1660435fa8c3f8167db695c2d120
644,684
def filter_df_options(df, options): """ Filters out rows from a dataframe. @param df dataframe @param options options @return filtered dataframe .. runpython:: :showcode: from pymlbenchmark.plotting.plot_helper import filter_df_options ...
ea8d70a71fd8e86a05b014fa4a327cb9b7d5435c
644,685
def printable_str(string): """ Helper function to convert non-printable chars to its ASCII format """ new_str = '' for char in string: if ord(char) >= 32 and ord(char) <= 126: new_str = new_str + char else: new_str = new_str + (r'\x%02x' % ord(char)) return new_...
82bd560a0c2f2f0f477b9640a5d13cb1e5554c2c
644,686
def _verify_none_type(args): """Function for safely handling if a user specifies "None" from the command line. ---------------------------------------------------------------------------- Args: args: argparse object returned by ArgumentParser.parse_args() Returns: argparse object ret...
7f54c7d988a5c7cc46e4948e93a1366ea5f27050
644,687
from typing import Optional import torch def ConvNd( dim: int, in_channels: int, out_channels: int, kernel: int, stride: int = 1, dilation: int = 1, groups: int = 1, bias: bool = True, transposed: bool = False, output_padding: Optional[int] = None, dtype=None, ): """Con...
814152af6be6ad0175fc199fb7f8007063caf438
644,688
def _get_last_layer_units_and_activation(num_classes): """Gets the # units and activation function for the last network layer. # Arguments num_classes: int, number of classes. # Returns units, activation values. """ if num_classes == 2: activation = 'sigmoid' units ...
17b7384218354c616652b9710e874c42deaf8b6a
644,689
import torch def qexp_t(q): """ Applies exponential map to log quaternion :param q: N x 3 :return: N x 4 """ n = torch.norm(q, p=2, dim=1, keepdim=True) n = torch.clamp(n, min=1e-8) q = q * torch.sin(n) q = q / n q = torch.cat((torch.cos(n), q), dim=1) return q
6db3edab4c2bbaf4176625f35381d456ee1aeaa5
644,690
import re def cleanUpTitle(title): """Clean up the title of a potential MediaWiki page. Otherwise the title of the page might not be allowed by the software. """ title = title.strip() title = re.sub(r'[<{\[]', '(', title) title = re.sub(r'[>}\]]', ')', title) title = re.sub(r'[ _]?\(!\)'...
53fba42b1f0d10d8d29ae6c084cefbb902de8710
644,691
def solve1(a, b, EPS=1e-6): """ Returns root of equation a*x + b = 0. """ # a*x + b = 0 if abs(a) < EPS: return () else: return (complex(-b/a),)
a5854fc6118e49ebf8b380903e838b310acc6a4a
644,692
def get_val(op): """Get value of op.""" return op.gate.get_val()
07b1b0ad7e766cb4758c8f2a913c6620178061ef
644,693
import pickle def load_data(pickle_file): """ Load the data from given path. Args: pickle_file: pickle file of the requested data Returns: A tuple of (features, labels) for the given `pickle_file` """ with open(pickle_file, mode='rb') as f: data = pickle.load(f) retu...
4c1f1a56114449feda8cd5450fb6535bb2bd4f65
644,694
def check_FS_true(output_hdul): """ This function checks if the fits file is a Fixed Slit. Args: output_hdul: the HDU list of the output header keywords Returns: result: boolean, if true, the file is assumed to be Fixed Slit """ result = False if "EXP_TYPE" in output_hdul: ...
a58a629e6c4706333a15ad7f8481f24065b8866e
644,695
import torch def boolean_mask(target: torch.Tensor, mask: torch.Tensor): """ Mimick tf.boolean_mask Copied from https://discuss.pytorch.org/t/slicing-tensor-using-boolean-list/7354/3 Parameters ---------- target mask Returns ------- """ x = mask == True # y=torch.aran...
13f4c05d1cf2d312b9de863cbc65b2fe2ff9ed93
644,696
def _flatten_probabilities(probabilities, targets, ignore=None): """ Flattens predictions in the batch """ if probabilities.dim() == 3: # assumes output of a sigmoid layer B, H, W = probabilities.size() probabilities = probabilities.view(B, 1, H, W) B, C, H, W = probabilities...
7da22aea7e8b8caca46316de2dfc2dada8f6ecaa
644,698
def get_key_value(line, sep=":", strip_whitespace=True): """ Split a string into key and value parts. The string must have a separator defined as an argument. By default, the separator is ":". An example of a valid string is "name: John Doe ". The result will be: ("name": "John Doe") [param...
da055a6a31acfe229190fad0dfca8abe3104d3eb
644,699
def pool_list(transport, request, **kwargs): """Gets a list of pools :param transport: Transport instance to use :type transport: `transport.base.Transport` :param request: Request instance ready to be sent. :type request: `transport.request.Request` :param kwargs: Optional arguments for this o...
c55a7eb4e5374cb87a168defbaf6d78414e2229b
644,700
def ranks(x, reverse=False): """ Returns a tuple containing the rank of each element of the iterable `x`. The ranks start at `0`. If `reverse` is `False`, the elements of `x` are ranked in ascending order, and in descending order otherwise. Equal elements will all be assigned the same (lowest-poss...
7d8aa94b42eaf2b699fa113ca105907c40f6dc62
644,701
def to_camel(string: str) -> str: """Convert snake_case to camelCase.""" words = [] for num, word in enumerate(string.split("_")): if num > 0: word = word.capitalize() words.append(word) return "".join(words)
af9967e065573d61b01381aad8c866a402d9e5a0
644,702
def vec2name(ndes, natom): """ get index of the first feature for each element """ v = [] for i in range(natom): v += [ndes * i] return v
605d03a5aef3c312b2d34004d761b6a238e2bafa
644,703
def inrange(value: int, down_limit: int, top_limit: int) -> bool: """ Check if number is in specified range and return bool. """ if value in range(down_limit, top_limit + 1): return True else: return False
305c1b62c8857a4e2a74707e258c056f6b0565f7
644,704
def vowel_count(phrase): """Return frequency map of vowels, case-insensitive. >>> vowel_count('rithm school') {'i': 1, 'o': 2} >>> vowel_count('HOW ARE YOU? i am great!') {'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1} """ d = {} v = set('aeiou') for c in phrase.l...
762fc26228fb77040c25249f0a57f3deefad8362
644,705