content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def string(mat): """ Convert the Cartesian matrix """ if mat is not None: mat_str = '' for row in mat: mat_str += ' '.join('{0:>8.3f}'.format(val) for val in row) mat_str += '\n' mat_str.rstrip() else: mat_str = '' return mat_str
ebfe509126ac778a58248d6ddda8d75598f919df
651,427
import torch def batchwise_lp_project(x, lp, lp_bound, dim=0): """ Projects x (a N-by-(...) TENSOR) to be a N-by-(...) TENSOR into the provided lp ball ARGS: x : Tensor (N-by-(...)) - arbitrary style lp : 'inf' or int - which style of lp we use lp_bound : float - size of lp bal...
3d18179585e641e7a207fc1294414398b6b01064
651,428
def loadInstructionTrace(fileName="gdb.txt"): """ Parses the 'gdb.txt' file and returns assembly instructions in a list """ iTrace = [] # Get text from file allText = open(fileName).read() allText = allText[allText.find("Breakpoint 1"):] # Split into lines allLines = allText.split('\n') ...
994c63488a71920a7c6b112c89a7ee196eea5069
651,429
def services_type(loader): """ Returns a function which validates that services string contains only a combination of blob, queue, table, and file. Their shorthand representations are b, q, t, and f. """ def impl(string): t_services = loader.get_models('common.models#Services') if set(strin...
e3d6c34e4c0e3b42369199aac5c0b5817b202634
651,430
def dump_queue(queue): """ Empties all pending items in a queue and returns them in a list. """ result = [] queue.put("STOP") for i in iter(queue.get, 'STOP'): result.append(i) return result
806db0443d671bc7b4bfe8054d903c46ba10eaa9
651,432
import functools def _merge_set(series): """Merge set list.""" return functools\ .reduce(lambda x, y: list(set(list(x) + list(y))), series.tolist())
dda9015cd082231384d058f3b0025d9c8f5ce080
651,433
def iterable(arg): """ Simple list typecast """ if not isinstance(arg, (list, tuple)): return [arg] else: return arg
6502eb92507e30fcc5bf54c3d40937b4236573ab
651,434
def complement(predicate): """Generates a complementary predicate function for the given predicate function. :param predicate: Predicate function. :returns: Complementary predicate function. """ def _negate(*args, **kwargs): """Negation.""" return not predicate(*args, **kwargs) retu...
f8538057044a95a40133110c801459545c2d3776
651,436
import os import uuid def docker_compose_function_project_name(): """Generate a project name using the current process PID. Override this fixture in your tests if you need a particular project name. This is a function scoped fixture. The project name will contain the scope""" return "pytest{}-functio...
bfbf834b65262471705320d9e6a41bd2a25d744c
651,437
import os def ssl_certs_generated(cert_file: str, key_file: str) -> bool: """ If the certificate and key files are generated. Args: cert_file (str): Path to certificate file key_file (str): Path to key file Returns: bool: Both certificate and key file exist """ return...
cb5245259efaadfb65a3dd2af86b2bcacc1b4df9
651,438
from shutil import rmtree import os def _remove(path): """ remove asset if it is a dir or a file :param str path: path to the entity to remove, either a file or a dir :return str: removed path """ if os.path.isfile(path): os.remove(path) elif os.path.isdir(path): rmtree(p...
d4c445a9ae6ddac2e5e2a99a8afb1e76d6d4694c
651,439
import math def pi_2_pi(angle): """ :param angle: 弧度制 :return: 转换成[-pi,pi] """ return (angle + math.pi) % (2 * math.pi) - math.pi
b6b65aa07de42bfa941fe1f42d7e72ba3633a7d0
651,440
import tempfile import os def setupTmpBaseDir(baseDirPath=""): """ Create temporary directory """ # create temp directory at /tmp/bluepea...test if not baseDirPath: baseDirPath = tempfile.mkdtemp(prefix="bluepea", suffix="test", dir="/tmp") baseDirPath = os.path.abspath(os.path.expand...
93e266f38fc3019fc5b5247a01e7b32142c8280c
651,441
def mytask(data, *args, **kwargs): """Simple task which returns reverse string """ return data[0][::-1]
cfc26959910d1e8cbc638e6426fd0b519d752295
651,443
import numpy def remove_deletions_and_skips(ary, sentinel_index): """Remove all instances of skip and deletion characters from an array. This is helpful when defining clusters. We don't want meaningless values affecting the clustering. Args: ary: training numpy array sentinel_index: ...
c03d7a2c32f97c2d130ee2562ec01fd494cd889f
651,444
def unpack_point_msg(msg, stamped=False): """ Get coordinates from a Point(Stamped) message. """ if stamped: p = msg.point else: p = msg return p.x, p.y, p.z
9c73105be73cbcdc55cef0f268851567dcbcd822
651,445
def Transition( state_table ): """Decorator for indicating the method causes a state transition. Decorator is applied to methods of the state machine class. Invokeing the method can cause a transition to another state. Transitions are defined using the nextStates method of the StateTable class """ s...
3fa8b4c7c183f9048147f56e7d12a1166a58617f
651,446
import uuid def uuid_from_string(idstr): """Convert an uuid into an array of integers""" if not idstr: return None hexstr = uuid.UUID(idstr).hex return [int(hexstr[i:i+2], 16) for i in range(32) if i % 2 == 0]
4a2bb28068b86394ebae213951eb4bf6a3875fb7
651,447
def _return_or_write(context, string): """Helper function so that these functions can be called from either Mako Python blocks, or from Mako templates themselves. """ if context is None: return string else: context.write(str(string)) return ''
c7b7d551f1bd1bb584ae0854a443179c032a5061
651,448
import string import random def random_string_generator(size=6, chars=string.ascii_uppercase + string.digits): """ Generate random string Args: size: length of the string chars: sequence of chars to use Returns: random string of length "size" """ return ''.join(random.choice(c...
4b9e9ef10664c57b6839f549f6ca9aac9fa78fdc
651,449
import math def compute_colors(n, cols): """Interpolate a list of colors cols to a list of n colors.""" m = len(cols) lst = [] for i in range(n): j = math.floor (i * (m - 1.0) / (n - 1.0)) k = math.ceil (i * (m - 1.0) / (n - 1.0)) t = (i * (m - 1.0) / (n - 1.0)) - j (r0...
121f2080faa3ca9d574572a47c231fc525ee74fe
651,450
def issubstring(s1, s2, *args, **kwargs): """Is s1 a substring of s2""" return s2.count(s1) > 0
9a3aad1e3f46677457d78e9169c241577102200e
651,451
def common_characters(w1, w2): """ Parameters: ---------- w1: str w2: str Returns: -------- int: Number of characters common between two strings """ ws1 = set(w1) ws2 = set(w2) return len(ws1.intersection(ws2))
dcb3aa3f06bf2057532527be52cf545e1affb9f6
651,452
def topic_filename(topic: str) -> str: """ Returns the filename that should be used for the topic (without extension). """ # Remove commas and replace spaces with '-'. return topic.replace(",", "").replace(" ", "-")
4d8c20d4ee82fdd33238b90f1021e50f8e16817c
651,453
def get_obj_in_upper_tree(element, cls): """Return the first object in the parent tree of class `cls`.""" if not hasattr(element, '_parent'): raise ValueError('The top of the tree was reached without finding a {}' .format(cls)) parent = element._parent if not isinstance(...
289606cc860407db4ce1ff68c5004004d683b883
651,454
import binascii def dec( msg, k ): """ Lets decode xor with a key k ... """ b = format( msg ^ k, 'x' ) return binascii.unhexlify( ( '0' * (len( b ) % 2 )) + b )
35cb02ffaef8b864856edc4eafe4e263e1a86ea4
651,456
def pc(): """Symbolic accessor for the program counter""" return 'PC',
fc999e7668ac0a349f36b45c072e6e04fc7398de
651,457
def get_published_file_entity_type(tk): """ Return the entity type that this toolkit uses for its Publishes. .. note:: This is for backwards compatibility situations only. Code targeting new installations can assume that the published file type in Shotgun is always ``PublishedFi...
864ce47673991a9cac15b52b0edf2c11148cc08e
651,460
def tokenize(chars): """ Convert a string of characters into a list of tokens. """ return chars.replace('(', ' ( ').replace(')', ' ) ').split()
daf16f256d2b322c4d12cc0d32161f1394b28b88
651,461
import json def set_config(config_name): """ Config parse :param config_name: config file name :type config_name: str :return: parsed config :rtype: dict """ try: return json.load(open(config_name, 'r')) except FileNotFoundError: print('%s %s' % (config_name, 'no...
eb4e53018efb6b3f0db4a0cfa587493fdf80bf52
651,462
def factors(n): """Returns a list of the factors of n.""" res = set() res |= {1, n} for i in range(2, int(n**.5)+1): if not n % i: res.add(i) res.add(n//i) res |= factors(n//i) return set(res)
786fdd2e309da1c4052de45e3b6e814a7f8ef835
651,463
def _map_create_proxy(cls, factory, args, kwargs): """ Support pickling of kwargs in TableProxy.__reduce__ """ return cls(factory, *args, **kwargs)
c3276710f712d100155eec7f74e740e5ec9851b8
651,464
import os def yml_path() -> str: """ determine path of YML file to persists tokens :return: path to YML file :rtype: str """ return os.path.join(os.getcwd(), f'{os.path.splitext(os.path.basename(__file__))[0]}.yml')
b07e7f8095bf0504883410f28aaac42fa7bc954f
651,465
from functools import reduce def _get_elements(node2elements): """ Return a set of elements from the node to (set of) elements dictionary. >>> sorted(_get_elements({'a':{1, 2}, 'b':{2, 3}, 'c':{1}, 'd':{4}})) [1, 2, 3, 4] """ return reduce(set.union, node2elements.values())
a793c8df42516eb1ccd1a650a76e9be24cb88713
651,466
import pickle def load_pickle(filename): """ Args: filename (str): name of the pickle file to be loaded Returns: file: """ with open(filename, 'rb') as f: file = pickle.load(f) return file
a1138639638e39275aa9f9819a4cae74f936be39
651,467
def hsv_to_rgb(h, s, v): """Convert HSV values RGB. See https://stackoverflow.com/a/26856771. :param h: Hue component of the color to convert. :param s: Saturation component of the color to convert. :param v: Value component of the color to convert. :rtype: tuple ""...
0b74f5ccbff722a139bea316c41f644aa2d7a36d
651,468
def next_byte(server_socket): """ This method reads in one byte. :param server_socket: the socket to read one byte from :return: a byte object of the single byte read in """ return server_socket.recv(1)
ee04743e53c6893a2c4627e5c28d2ea88617668c
651,469
def cleanupQuotes(text): """ Removes quotes if text starts and ends with them Args: text (str): Text to cleanup Returns: Text with quotes removed from start and end (if they existed) or original string (if not) """ if text.startswith('"') and text.endswith('"'): return text[1:-1] else: return text
6079cd9491e248f20d645ebc1fb9c99d073e18ac
651,470
def max3(a,b,c): """a,b,c의 최댓값을 구하여 반환""" #아마 함수를 입력할때 추가로 설명같은 란이 들어가는것 같다. maximum=a if b>maximum: maximum=b if c>maximum: maximum=c return maximum
190f0fd8f13d40ae53c43ef0b56591975a967a27
651,471
def truncate_to_fit(text, len): """ Truncate text to specified length. """ return text[:len]
f93dc690075cf1417ff64a15a3b2ec9a26b117b3
651,473
def add_headers(response): """ This function adds headers to outbound requests to increase the security posture in the browser """ response.headers["Cache-Control"] = "public, max-age=31536000" response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains" response.hea...
48173a4660d0c24903ae203dc49949193436f645
651,475
import sys def main_is_frozen(): """ Determines whether scripts are executed using pyInstaller or actual scripts. :return: True if using py2exe or pyinstaller or False if using scripts""" return (hasattr(sys, '_MEIPASS'))
54bed85f73a37580cf77e9d330d9c055b887d414
651,477
def hits_at_k(preds, ans, k): """accepts list of predictions and answers""" preds_k = preds[:k] any_in = lambda a, b: bool(set(a).intersection(b)) return any_in(preds_k, ans)
dc1e48f87cc63935d90002d499e81e77d796b25d
651,478
def _abberation_correction(R): """Calculate the abberation correction (delta_tau, in degrees) given the Earth Heliocentric Radius (in AU)""" return -20.4898/(3600*R)
7fea54c0bc6fffc9e8ab40057b011da327fe0bd7
651,479
def get_photo_rel_url(album_name, filename): """ Gets path of source photo relative to photos basedir :param album_name: :param filename: :return: """ return "%s/%s" % (album_name, filename)
0e3fbb3bf58c7fddabffc995eaa10d9b86cb8fb0
651,480
def iconset_from_class(value): """ extracts the iconset from a class definition "fa-flask" -> "fa" :param value: :return: """ if '-' in value: return value.split('-')[0] return ''
b03e0642a2e6e4fa784b71a4d65bfdbfd509ba5e
651,481
def exists_lod(lst, key, val): """is key-value in list of dicts""" return any(d[key] == val for d in lst)
eb42d22ca7adeeadd113966ddf4202495c267254
651,482
def process_mpls_ldp(mpls_ldp): """Process data in mpls_ldp object.""" # format string for prefixes prefix_row = "{prefix}, rev {rev}\n" local_binding_row = " Local binding: label: {label}\n" peers_row = " Remote bindings: ({num_peers} peers)\n" # format string for peer header ...
671549374d38fe011568b506bd99d0e52a9443bf
651,483
import os def _find_in_path(path, file): """ Utility method for finding a filename-string in a path Args: :path: the path to search :file: the filename to search for Returns: True if the filename was found in the path, otherwise False """ for p in path.split(os.paths...
c8648d3a28af66b55a030cc62c20759caa870473
651,484
import functools import sys import itertools def wraps_safely(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS): """This function is safe version of `functools.wraps` in Python2 which skips wrapping functions for the attributes that do not exist.""" if sys.version_info[0] > 2: return functools.wrap...
7bc44e6a63767e79aea7c20c6d138ee185111b3d
651,485
def cipher(imput_string, shift_key): """ Implementation of Crypto Technique. Params: input_string (required), shift_key (required) Returns: encrypted_string :type imput_string: str :type shift_key: int """ # Initialise str to store the encrypted message ...
1ebe326e94681288d810f568db58b0c937c94f3e
651,486
def make_vertical_bar(percentage, width=1): """ Draws a vertical bar made of unicode characters. :param value: A value between 0 and 100 :param width: How many characters wide the bar should be. :returns: Bar as a String """ bar = ' _▁▂▃▄▅▆▇█' percentage //= 10 if percentage < 0: ...
d6001a5af2ad298f95ca4b32a45cef36c3587c09
651,488
def scoring_to_mean(ts): """ provide mean of scoring to info """ return ts.groupby(level=["team", "pos"]).mean().unstack()
886644b250d44d123bbe1d28ced376c0045a1432
651,489
import string def col2num(col): """ convert column in excel to number. Input = 'K'; output = 11 """ num = 0 for c in col: if c in string.ascii_letters: num = num * 26 + (ord(c.upper()) - ord('A')) + 1 return num
dc455f90ede0b0be933502a21ab261f071a4c9e4
651,490
def getSplitDataSet(dataSet, axis, value): """ 将哪一轴axis的数据作为分类类型,label为vale的数据作为一组数据 :param dataSet: :param axis: :param value: :return: """ splitDataSet = [] for rowdata in dataSet: if rowdata[axis] == value: temp = rowdata[:] del (temp[axis]) # 去除已经...
750c77e8974239426208e39d36668b4a6bbe5f89
651,491
def basic_wrapper( function ): """ Simple decorating wrapper function. """ #========================================================================= def callback( context ): """ The callback function with a single call-time context argument. """ return '<tag>{}</tag...
cc920f9ebd89bff683ce5c892911b7e6c99114e6
651,493
import torch def images_to_levels(target, num_level_grids): """Convert targets by image to targets by feature level. [target_img0, target_img1] -> [target_level0, target_level1, ...] """ target = torch.stack(target, 0) level_targets = [] start = 0 for n in num_level_grids: end = s...
fca57e9b3f3e41a58139daf1d94e731d1c36cda3
651,494
def get_primes(n_primes, st=2): """ Get N prime numbers """ _prims = [] x = st while len(_prims) < n_primes: if all([x%y > 0 for y in range(2,x)]): _prims.append(x) x+=1 return _prims
651298ef193e76604958ce7a50d558ba08c66bea
651,495
def _get_file_rows_cols(rows=None, cols=None, ann_info=None, rsc_data=None): """Wrapper function to find file width for different satellite types""" if rows is not None and cols is not None: return rows, cols elif (not rsc_data and not ann_info) or (rsc_data and ann_info): raise ValueError( ...
0398979a68929ef7a2d90c7dee25b0ab5629d6c5
651,496
import os def updir(path, count): """Returns the path count directories above path.""" for _ in range(count): path = os.path.dirname(path) return path
e20411834f74f9259330edc4d46652603606efd1
651,498
import os def GetCheckoutDir(out_dir): """Returns absolute path to the checked-out llvm repo.""" return os.path.join(out_dir, 'tools', 'clang', 'third_party', 'llvm')
2837bb9ef93348861b197ae53a42b585b2ff2023
651,499
import re def _read_properties(file): """Read database properties from *file*, returning :class:`dict`.""" properties = dict() for line in file.read_text().split("\n"): match = re.search(r"([^\s]+)\s*=\s*(.+)\s*", line) if match is not None: properties[match.group(1)] = match.g...
c2977008e2b9f2643b48a89de97ce91295fd5f58
651,500
import time def timestamp(): """returns a timestamp""" return time.strftime('%Y%m%d%H%M%S')
10de7da918a60163436662e639f252bfe705d9e3
651,501
from datetime import datetime def timestamp(blank): """ What's the current date and time? """ today = datetime.today() return today.strftime("%A %b. %d, %-I:%M %p")
d1c19109521a7af89f8d42f011f82dfb27f84ae1
651,502
def inversao(num): """ Funcao para inverter o numero `param` num: numero para ser invertido """ aux = 0 while (num > 0): remainder = num % 10 aux = (aux * 10) + remainder num = num // 10 return aux
4d240401845b96e5a878140f0cc1dff0f9e5b433
651,503
def is_shared_library(f): """Check if the given File is a shared library. Args: f: The File to check. Returns: Bool: True if the given file `f` is a shared library, False otherwise. """ return f.extension in ["so", "dylib"] or f.basename.find(".so.") != -1
8045a89fd19f3c1bdc9054fd824df6c1d6be302a
651,504
import jinja2 def get_jinja_loader(user_template_path=None, current_theme=None, plugin_template_paths=None): """ Set up the Jinja template loaders, possibly allowing for user overridden templates. (In the future we may have another system for providing theming; for now this i...
7e2dab3559bbd2b3d97dc2bd5aa1161a216c0c2b
651,506
def generate_trail(wire_directions): """Given a list of wire directions, generate a set of coordinate pairs for the wire's path""" trail = set() current_location = (0, 0) for direction in wire_directions: heading = direction[0] distance = int(direction[1:]) while distance > 0: ...
151faa19b9898449dbd6b51528d0a7674b204773
651,507
def song_decoder(song): """ Removes 'WUB' from a string to find the true message of the song. :param song: The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters :return: the words of the initial song that Polycarp...
7dd1ffed422f7fcab6efe00cabe84a8a5493b7e7
651,508
def str_starts_with_any_in_list(string_a, string_list): """ Check if string_a starts with any string the provided list of strings """ for string_b in string_list: if string_a.startswith(string_b): return True return False
c687ea09f9ce011cf3301d98a13bb23378e9acbc
651,509
import importlib def load_class(package, bridge_name): """ dynamically load a class from a string """ module_name = bridge_name.lower() + "_loader" module_path = package + "." + module_name class_str = bridge_name+"ClassLoader" module = importlib.import_module(module_path) return getat...
130c1c5ac7ceb94de580878052ea2860c6cea080
651,510
def check_monotonic(a): """ Parameters ---------- a input array Returns -1 -- for monotonic, non-increasing 0 -- for non-monotonic 1 -- for monotonic, non-decreasing ------- >>> check_monotonic([1,2,3]) 1 >>> check_monotonic([3,2,1]) -1 >>...
260b174bf610b12f061be64d4715e0de03f14548
651,511
def trim_markers(tree): """Remove unused marker elements from diagram """ ns_map = {"svg": "http://www.w3.org/2000/svg"} used_marker_ids = [] # Identify markers that the diagram actually uses elements = tree.xpath("//*") for element in elements: attrs = element.attrib start...
5656956c0eedb07b9b221ee048adcf879728ef22
651,512
import os def _get_profile_paths(input_dir, input_extension): """Finds all the profiles in the given directory (recursively).""" paths = [] for dir_path, _sub_dirs, file_names in os.walk(input_dir): paths.extend([ os.path.join(dir_path, fn) for fn in file_names if fn.endswith(input_e...
d32ca3c63c49679f60c8a1c8cf25e074b3adb029
651,513
def format_report(count, new_inst, del_inst, svc_info): """ Given a service's new, deleted inst, return a string representation for email """ needed = False body = '' if new_inst is not None and len(new_inst) > 0: needed = True body += '\n\n New Instances: ' for inst in ...
af4228c354393164d8bf48698479262c5470afcd
651,514
def _get_updated_roles_data(role_id, person_ids, role_list): """Get person email for the updated roles""" data = [] for person_id in person_ids: for role in role_list: if role['ac_role_id'] == role_id and role['person_id'] == person_id: if 'person_email' in role: data.append(role['pers...
5fe904825a369899d12ee9c48c6705cd41740a91
651,515
import math def p_to_q(p): """ Turn error probability into Phred-scaled integer """ return int(round(-10.0 * math.log10(p)))
d60ee7bb434a599d641ca61156361779955e09bd
651,516
def _make_credentials_property(name): """Helper method which generates properties. Used to access and set values on credentials property as if they were native attributes on the current object. Args: name: A string corresponding to the attribute being accessed on the credentials attrib...
17692cb4cf0ea072d4345d60106bb04c0ad030bd
651,517
import pytz def to_utc(dt): """This converts a naive datetime object that represents UTC into an aware datetime object. :type dt: datetime.datetime :return: datetime object, or None if `dt` was None. """ if dt is None: return None if dt.tzinfo is None: return dt.replace(tz...
bb06d553a02453f6701f175eb6d15d63134776cb
651,518
import os def file_exists(name): """ Returns true if the file currently exists. """ return os.path.exists(name)
88b533ce806ff60ae422c92b965b54788a3ea866
651,519
def fidelity(adata, name, groupby='label'): """look in .obsp[name_connectivities] for connectivity data and see how well it preserves the given labelling""" labels = adata.obs[groupby].values adj = (adata.obsp[name+'_'*(len(name)>0)+'connectivities']>0) edgelist = zip(*adj.nonzero()) good_edges=0...
ddfc0341a65b11a6844bfb4a331ce9ee7a77cfa9
651,520
def is_build_at_least(current_version, other_version): """Returns whether or not |current_version| is at least as new as |other_version|.""" if current_version is None: return False # Special-cases for master builds. if current_version == 'MASTER': # If the current build is master, we consider it at ...
35ad45e7d422f7717f266d3967d6e5c04d475fe2
651,521
import torch def qlog_t(q): """ Applies the log map to a quaternion :param q: N x 4 :return: N x 3 """ n = torch.norm(q[:, 1:], p=2, dim=1, keepdim=True) n = torch.clamp(n, min=1e-8) q = q[:, 1:] * torch.acos(torch.clamp(q[:, :1], min=-1.0, max=1.0)) q = q / n return q
fbb7b3d7956b3e96921fc8c36647f3f695e539a1
651,522
import pathlib def quandl_apikey_set(apikey, filename=None): """Store the Quandl Token in $HOME/.updoon_quandl Parameters: ----------- apikey : str The API Key from the Quandl Website. See https://www.quandl.com/account/api filename : str Absolute path to the text where t...
e3f9ecee89f51e8107f482e7b175a0220d2f2fb7
651,524
def linearize(func): """ Return a linearized from of the IR and a dict mapping basic blocks to offsets. """ result = [] blockstarts = {} # { block_label : instruction offset } for block in func.blocks: blockstarts[block.name] = len(result) result.extend(iter(block)) retu...
097e81aa03a28c570a26e29582bbce23616e1753
651,525
import torch def compute_argmax(ten): """Compute argmax for 2D grid for tensors of shape (batch_size, size_y, size_x) Args: ten (torch.[cuda].FloatTensor): (batch_size, size_y, size_x) Returns: indices (torch.[cuda].LongTensor): (batch_size, 2) index order: (y, x) """ batch_size ...
d69c6ae13dfa2aef27a7e6ed621e928c146c0554
651,526
from typing import List import os def find_files(path: str, ext: str, recursive: bool = True) -> List[str]: """Search and return files with extension.""" abs_paths = [] ext = ext.replace(".", "") def does_file_ext_match(path): fp = os.path.basename(path) if fp.split(".")[1] == ext: ...
ddf8af57e7ecd1813c8177a918e4e2b6a305587a
651,527
from typing import Any import fsspec def hdfs_connect(*args: Any, protocol: str = "webhdfs", **kwargs: Any) -> Any: """Connect to HDFS using `fsspec`. This function is a thing wrapper around `fsspec.filesystem`. All arguments are forwarded to that API. """ return fsspec.filesystem(protocol, *arg...
3b6ff9133528c6aa45e901aa21719fe35ad2f0fc
651,528
def get_cbmc_info(n_insert, n_dihed, cutoffs): """Get the CBMC_Info section of the input file Parameters ---------- n_insert : int number of insertion sites to attempt for CBMC n_dihed : int number of dihedral angles to attempt for CBMC cutoffs : list list containing CBM...
769640657d46b1862dedd952f15b97dba80420b4
651,529
def has_active_balance_differential(spec, state): """ Ensure there is a difference between the total balance of all _active_ validators and _all_ validators. """ active_balance = spec.get_total_active_balance(state) total_balance = spec.get_total_balance(state, set(range(len(state.validators))))...
24b0f4d4289e2b683d96c446010a32b50dad1b33
651,530
def mention_uri_to_resource_uri(mention_uri): """ Converts a given mention URI into a resource URI by simply removing the suffix starting with "#". For instance, the mention URI 'http://en.wikinews.org/wiki/Mexican_president_defends_emigration#char=615,622' is transformed into the resource URI 'ht...
4a9dbafc21ed8ade488947e920c1962687903298
651,532
from typing import Union def to_boolean(envvar: Union[str, bool]) -> bool: """ Coerce the input to a boolean. >>> to_boolean("True") True >>> to_boolean("FALSE") False NOTE: An empty string is interpreted as False: >>> to_boolean("") False Booleans are returned as-is: ...
c373dae669127f6e0a823b21eef8311e76de0493
651,534
def get_top_k_snps_in_each_window(df_snps, k=1): """ :param df_snps: this datafram must have following columns: ["safe","ordinal_pos","window"]. :param k: :return: return top k snps in each window. """ return df_snps.loc[df_snps.groupby('window')['safe'].nlargest(k).index.get_level_values(1), :...
574dd8ffea52e4645c6698965e0ffffeaa300c9d
651,535
import zipfile def _ExtractZipEntries(path): """Returns a list of (path, CRC32) of all files within |path|.""" entries = [] with zipfile.ZipFile(path) as zip_file: for zip_info in zip_file.infolist(): # Skip directories and empty files. if zip_info.CRC: entries.append( (zip_i...
4ba4742964f553c75e7d97e07e15119efd6c96cb
651,537
def get_dicom_path_by_index(idx, metadata_case): """ Key of metadata_case is the path of origin dicom file """ keys = list(metadata_case.keys()) k = keys[idx] return k
95c4bbfeee03dae90ba47fcc497e0657f9a3cbb4
651,538
import subprocess def RunShellCommand(cmd, cwd='.'): """ executes a command :param cmd: A string to execute. :param cwd: from which folder to run. """ stdout_target = subprocess.PIPE stderr_target = subprocess.PIPE proc = subprocess.Popen(cmd, shell=True, ...
5effc8291103042f1252cb0aa7baff65fc3aef11
651,539
import itertools import functools def get_occurrence_ids(event_hashes): """ Generates all event hashes for the given events determined by the properties of the event. """ def add_combinations(agg, i): occurrence_lists = list(itertools.combinations(event_hashes, i+1)) occurrence_ids = [...
2805ecf88f4f9393ce6f4e03f644daacc2e45038
651,540
def dump_field_label(value): """dump field_label""" return value
5e53ebfeb53f3b61ca0a41b5b2177be510db411b
651,541
def get_icon(icon: str) -> str: """ Get icon unicode from dictionary. Parameters: icon (str): icon code from API response. Returns: (str): icon unicode. """ icons = {"01": ":sun:", "02": ":sun_behind_cloud:", "03": ":cloud:", "04": ":cloud:", "09": ":cloud_with_rain:", "10": ":sun_behind_r...
2964c7573086ec86d6d22df6ea3fb35380bbd950
651,542
import shlex import subprocess def run_command(command_string): """Use shlex and subprocess to run a command, return tuple of strings (stdout, stderr)""" command = shlex.split(command_string) process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = ...
e2015db4bcfedc086da0ea8ee37cc3affde8e15a
651,543