content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def until(n, filter_func, v): """Build a list: list( filter( filter_func, range(n) ) ) >>> list( filter( lambda x: x%3==0 or x%5==0, range(10) ) ) [0, 3, 5, 6, 9] >>> until(10, lambda x: x%3==0 or x%5==0, 0) [0, 3, 5, 6, 9] """ if v == n: return [] if filter_func(v): ret...
1996d5a27f964267122604937fa1163fa0da20cd
664,441
def hexescape(char): """Escape char as RFC 2396 specifies""" hex_repr = hex(ord(char))[2:].upper() if len(hex_repr) == 1: hex_repr = '0%s' % hex_repr return '%' + hex_repr
a58d6d028d744c4c4361d5925cc82e496a50525b
664,442
def matrix_to_text(mat): """ Convert matrix array to text using spaces/newlines as col/row delimiters """ rows = [] for row in mat: rows.append(" ".join([str(v) for v in row])) return "\n".join(rows)
ba1451374eae210ad37e227b4095c73b128c567d
664,443
import sys from pathlib import Path def mypath() -> Path: """ Get the root folder path for the project. Returns ---- path: Path Root folder path for the project. """ return Path(sys.prefix) if hasattr(sys, "frozen") else \ Path(__file__).parent.parent
9c1b44be3ca3a8c46b43b4c0f154157bede605e3
664,444
def clean_data(df): """ Function to load the data sets and clean the data (so as to give column names corresponding to the different categories). Args: The merged dataframe containing the messages and the categories Returns: Dataframe that has the messages and one column for each...
9be4b0742be254ea061e6343292b71758b8269c7
664,445
def drelu(x): """ dReLu(x) = 1 if (x>0), 0 otherwise """ return (x > 0).float()
9b69826bd52f3f0875799bac571977ade6cf129b
664,446
import random def add_parameter_noise(cfg, noise_ratio): """ Add noise to the hyperparameters of the Dynamic DropConnect model. This changes the input dictionary in-place. Args: cfg: Dictionary containing the configuration with all hyperparameters noise_ratio: Ratio of noise relative ...
c46a96dbcd6f468c825f0a9fe0457ab7566541ed
664,447
import requests def get_latest_flexget_version_number(): """ Return latest Flexget version from http://download.flexget.com/latestversion """ try: page = requests.get('http://download.flexget.com/latestversion') except requests.RequestException: return ver = page.text.strip() ...
e17c1a9118ea7c4348eaa153ae1a93f587d5d8fc
664,448
import re def get_currents( content ): """ Gets the currents from an Igor file :param content: The content to search :returns: A numpy array of the currents """ j_search = 'WAVES\s*PhotoCurrent1\nBEGIN\n(.*)\nEND' match = re.search( j_search, content, flags = ( re.IGNORECASE | re.DOTALL )...
a2988fbdbe91262899fbd709b4d0d03729170b84
664,449
def Array( *args ): """This is just sugar coating so that code from OOoBasic which contains the Array() function can work perfectly in python.""" tArray = () for arg in args: tArray += (arg,) return tArray
54f95f878337414d52ea85bd1ac4042f53bf7d09
664,450
import numpy def calcB(A): """ DO NOT USE EXCEPT FOR SMALL NETWORKS, ERROR CHECKING!!!!! B_ij = A_ij - P_ij P_ij = k_i * k_j / 2m """ n = A.shape[0] j = A.sum(axis=1) two_m = A.sum() P = numpy.dot(j.reshape((n,1)), j.reshape((1,n))) / two_m B = A - P return B
97ce03b85a6dd90bbb1a61ae097bb4c03ebecbf9
664,451
import math def legend_scaler(legend_values, max_labels=10.0): """ Downsamples the number of legend values so that there isn't a collision of text on the legend colorbar (within reason). The colorbar seems to support ~10 entries as a maximum. """ if len(legend_values) < max_labels: le...
b23b4aad87121a0bc4a9ba3a504d49398d55b218
664,452
def reduce_noise(adjmatrix, n_concepts, noise_thresold): """ Sometimes you need to remove the links with significantly low weights to avoid messiness. noise threshold is a number in [0,1] which defines a boundary below which all links will be removed from the FCM. E.g. noise_thresold = 0.15 means that a...
26567b6e1aab65c6ece015e5a563b1bc3aed356e
664,453
from typing import Counter def get_vocab(lst, vocab_size): """ lst: list of sentences """ vocabcount = Counter(w for txt in lst for w in txt.lower().split()) vocabcount = vocabcount.most_common(vocab_size) word2idx = {} idx2word = {} for i, word in enumerate(vocabcount): word2i...
cbff17e9d3d8c49421f88bb9e983bd86100682bc
664,455
def resample(df_ohlc, frequency='H'): """Function to change frequency and fill the gaps""" df_ohlc = df_ohlc.resample(frequency).ffill() df_ohlc = df_ohlc.fillna(0) return df_ohlc
7f0874a80eacd651a16dc0ea5e37942f9f6390f7
664,456
def _include_file_data(login, record): """Ensure that 'files' field is present in the input record""" if 'files' not in record: if 'files' in record.get('links', {}): url = record['links']['files'] elif 'id' in record: url = login.base_url + 'api/deposit/depositions/{0}/f...
578c75ed34460c408fe52f28ea5fdf38de57ef6b
664,457
def get_n_beads(n, i1 ,i2): """ given length of the ring polymer (n) and the starting-ending positions (i1, i2) returns the length of the segment of the smaller length :param n: number of elements :type n: int :param i1: starting position :type i1: int :param i2: ending position :ty...
5dee01efe31f9d98972dcdc997ad60ea1ba45b39
664,458
def variation_length(lastz_cig): """Determines how long the mapping is (sum of insertion/deletion/match), based on the lastz cig. Args: lastz_cig (string): a lastz cigar, e.g. "M50D3I5M30" Returns: int: sum of I+D+M in cigar. """ # Parsing cigars: # indices 0, 2, 4,... are ...
f353f7f9aced4c7d36f5058aa35eb2e27a8601f4
664,459
def next_indentation(line, tab_length): """Given a code line, return the indentation of the next line.""" line = line.expandtabs(tab_length) indentation = (len(line) - len(line.lstrip(" "))) // tab_length if line.rstrip().endswith(":"): indentation += 1 elif indentation >= 1: if line...
3791da54243c067a56bf21df23fbcb4d22516e70
664,460
from datetime import datetime def normalize_entity(in_dict): """Converts BlitzDB Document to standard dictionary Parameters ---------- in_dict : dict BlitzDB Document-compatible dictionary of values Returns ------- dict normal dictionary of values, output of to_dictionary...
bee7f9667c24e4296b6d4e5ceaeed29f839df123
664,461
def MAPE(y_true, y_pred): """Mean Absolute Percentage Error Calculate the mape. # Arguments y_true: List/ndarray, ture data. y_pred: List/ndarray, predicted data. # Returns mape: Double, result data for train. """ y = [x for x in y_true if x > 0] y_pred = [y_pred[i]...
f9323cf6a02264b528dcdd70b0c6aa02e8f21506
664,463
def formatDuration(context, totminutes): """ Format a time period in a usable manner: eg. 3h24m """ mins = totminutes % 60 hours = (totminutes - mins) / 60 if mins: mins_str = '%sm' % mins else: mins_str = '' if hours: hours_str = '%sh' % hours else: hou...
f4a7ee4f8e6b4eb6ed37b005f0d2cb2b9925169b
664,465
def split(value, sep=' '): """ The ``split`` template filter splits a given string by spaces. If you want to split by something else, provide the devider as a argument to the filter. .. code-block:: text {{ "foo bar"|split }} {{ "foo-bar"|split"-" }} """ return value.split(sep...
b25811a92853b2f89f920423a2e3fc0ef7c04dce
664,466
def findpop(value, lst): """ Return whether `value` is in `lst` and remove all its occurrences """ if value in lst: while True: # remove all instances `value` from lst try: lst.pop(lst.index(value)) except ValueError: break return True # ...
eae11883a50d585fa7e319902b77e1f5e4143c52
664,467
def get_by_name(name): """Returns an alias by name Params: name - The name of the alias """ return "TO BE IMPLEMENTED"
f33025d946237478fb9e8feae64c0233f94ce272
664,468
from typing import Any def health() -> Any: """Returns an ok status for uptime monitoring purposes""" return {"status": "ok"}
496104e7d051fb7e50a6a9e9ec75c38f0dcf14bf
664,469
def replace_full_stop(string: str) -> str: """ Replace full width full stop character with Japanese dot character. :param string: String to be processed :type string: str :return: Result string :rtype: str **Example:** .. code-block:: python string = "Hello.World" res...
8b8cad94015076834827acb7a48e6840ebc0914d
664,470
def parseReplacements(config): """Parses the replacements of the program.""" replacements = {} for key, val in config.items(): if isinstance(val, str): # Escape string so that it is not divided into multiple command arguments replacements[key] = "\"{}\"".format(val) e...
e787b7623665da4de27cd1e2a842587c6ed24015
664,471
def rtree_contains_prefixes(rtree, prefixes): """ Check that the given RoutingTableTree contains only the prefixes from the given list """ if rtree.count(blank=False) != len(prefixes): return False for prefix in prefixes: node = rtree.search(prefix=prefix, create=False) ...
34aa49b376fef2ffec02f90d8de0909875fa9391
664,472
import math def haversine(coord1, coord2): """use the Haversine function to determine the distance between two points in the WGS84 coordinate system. Returns the distance between the two points in meters. Source: https://janakiev.com/blog/gps-points-distance-python/ coord1: (lat, lon) coord...
611f242ead6ee90fba2c564f64d0869e77f7cdb2
664,473
def cents_to_eur(val): """ This function divides a float value over 1000 :param val: str :return: Float """ return float(val) / 1000
fdc4b53ca7c4373734f043715935481eae1868ae
664,474
from pathlib import Path def paths(base, network): """ Get the paths for the network directory, the wallet database file, and the blockchain database file. """ netDir = Path(base) / network dbPath = netDir / "wallet.db" dcrPath = netDir / "dcr.db" return netDir, dbPath, dcrPath
e97ac57993cde197ecd9f40145993d6bd3d0f4ab
664,476
import numpy def weighted_mean_and_std(x, w): """Return the mean and standard deviation of the data points x, weighted by the weights in w (which do not need to sum to 1).""" w = numpy.array(w, dtype=float) w /= w.sum() x = numpy.asarray(x) weighted_mean = (w*x).sum() squared_diff = (x - w...
e2b46520ee2b7f47c244fdd214910ca53d2ed011
664,477
def get_accuracy_count(data_list, optimal_distance): """ Processes data list from file to find accuracy count. Returns accuracy count. """ count = sum(1 for i in data_list if optimal_distance in i) return count
7b1503ac9af9dce156cdc60fa918d4e31ea96734
664,479
def mult_a_b(a, b): """Test function to be defined in-database as a UDF and used via ibis UDF""" return a * b
fd257503140c7d1f3c21a91a4e7f7d3732e0f295
664,480
def _detect_cycles(node, graph, visited, ps_stack): """ Perform DFS on PricingServices dependecy graph looking for cycles Params: node: PricingService graph: dict with adjacency list of PricingServices visited: set of already visited PricingServices during graph traversal ps...
d262533f1970c5fd674f0edf390e467444f3a34a
664,481
from datetime import datetime def timestamper(): """ Make a timestamp. """ timestamp = datetime.now() return (timestamp)
4676d4bc58632731ac5bc70cf94ab1601ccf03cb
664,482
import io import json import logging import sys def load_har_log_entries(file_path): """ load HAR file and return log entries list Args: file_path (str) Returns: list: entries [ { "request": {}, "response": {} ...
7c23f39bd4557f7971b50c33437ea65706c918cf
664,483
def door_handle_horizontal_01(direction, side, offset=0): """ side 1 -> inside """ verts = [(0.015, -0.003, -0.107), (0.008, -0.002, -0.007), (0.015, -0.002, -0.107), (0.019, -0.002, -0.026), (-0.015, -0.003, -0.107), (-0.007, -0.002, -0.007), (-0.015, -0.002, -0.107), (-0.018, -0.002, -0.02...
207737c6e98ee8dc8567ef11d69b65065df10010
664,484
from typing import Any def u(x: Any) -> str: """Convert x to string.""" if isinstance(x, str): return x return str(x)
b7ae9c8d29b367d8b4f670b35b91acbda80182da
664,485
from typing import List def bytes_to_ips(data: bytearray, sequence: int) -> List[str]: """Encode a little-endian bytearray into a list of multicast IPv4 addresses.""" output = [] if len(data) & 1: data.append(0) # split data into segments of 2-byte characters for i in range(0, len(data), ...
8c23ae8ecb0b7fd9a48b2b6be602b6ee8223e84d
664,486
import os def getOutputPrefix(oldname, outputDir, oldPrefix): """ get output path prefix oldname: filename to be converted outputDir: output directory name oldPrefix: file's path will need to cut the prefix first e.g.: path/b.ext -> output/b ( prefix is path ) e.g.: path/to/c.ext -> output/to/...
a66a69e77a00789b5b4d45f2799592ebfa52a06e
664,487
def validate_int(string_input): """by pass the ValueError exception for the int convertion and return True or False""" try: int(string_input) except ValueError: return False return True
22e055200d63e838922ac9f96fbb62d68895ea9b
664,488
def to_vec(rho): """ Take an input rho vector and flatten it into a column """ return rho.flatten()
ae0b3aa8b348e1c2339d17f7d6b617fdb0ee5593
664,489
from typing import List from typing import Optional def task_list(items: List[str], items_to_check: Optional[List[int]] = None) -> str: """Creates a task list in GitHub Flavored Markdown where each item can be checked off. This task list cannot be used inside a table. :param items: The items in the task ...
92120e73ac5421479f28621e01b78a54ec3d647a
664,490
import hashlib def _get_data_and_md5_bulk(container, obj_hashkeys): """Get the MD5 of the data stored under the given container as a single bulk operation. :param container: a Container :param obj_hashkeys: a list of object hash keys :return: a dictionary where the keys are the object hash keys and t...
e0ae17ba3b4c64cdefbe0bc494afa35c2c05e287
664,491
import time def _get_time_ms(): """ Returns the current time in ms. """ return time.time() * 1000
8bc5d358355f182ca747768712153a2f0c592d36
664,492
import os def make_paths_safe(params): """Given a parameter dictionary, loops through the keys and replaces any \\ or / with os.sep to promote OS agnosticism """ for key in params.keys(): if isinstance(params[key], str): params[key] = params[key].replace("/", os.sep) pa...
f3e0d269d45b9049ce66b3ba39bb4facac108f23
664,493
def events_event_id_delete(event_id: str): """Deletes an event.""" return '', 204
616c11087c55f81ea072eb03d083963e28e62076
664,494
def construct_sliding_windows(sequence_length, sliding_window_size): """ construct sliding windows for BERT processing :param sequence_length: e.g. 9 :param sliding_window_size: e.g. 4 :return: [(0, 4, [1, 1, 1, 0]), (2, 6, [0, 1, 1, 0]), (4, 8, [0, 1, 1, 0]), (6, 9, [0, 1, 1])] """ sliding_...
4a3e2076aa57c2dc5a5061473bcec5bdcd1d1c1b
664,495
def is_palindrome(n): """ Fill in the blanks '_____' to check if a number is a palindrome. >>> is_palindrome(12321) True >>> is_palindrome(42) False >>> is_palindrome(2015) False >>> is_palindrome(55) True """ x, y = n, 0 f = lambda: y * 10 + x % 10 while x >...
a20e69502c7609131e2fe27d1b92fe1563558c38
664,496
import os def get_hindcast_prefix(date, res='h', version='201905'): """Construct hindcast results prefix given the date, resolution and version e.g., /results/SalishSea/nowcast-green.201905/ddmmmyy/SalishSea_1h_YYYYMMDD_YYYYMMDD :arg date: date of hindcast record :type date: :py:class:`datetime.datet...
038bc695b56acaef9f6d118235f074ad53a4f7ce
664,497
import numpy def _normalize_default(value, dtype): """Return `value` as a valid default of NumPy type `dtype`.""" # Create NumPy objects as defaults # This is better in order to serialize them as attributes if value is None: value = 0 basedtype = dtype.base try: default = nump...
e0e703d64d0ef4e764955976ab6c1bab3723b3a0
664,498
def perm_to_string(p): """ Convert p to string, slightly more compact than listprinting. """ s = "(" for x in p: s = s + "%2d "%x s += ")" return s
3d2f99e0c5822a8f831147981d6b35c5061727a4
664,499
import re def xisabs(filename): """ Cross-platform version of `os.path.isabs()` Returns True if `filename` is absolute on Linux, OS X or Windows. """ if filename.startswith('/'): # Linux/Unix return True elif filename.startswith('\\'): # Windows return True elif re.match(r'\w:[\\/]'...
5aa82aa621dea7fb81316ea7c9d0bb9f0a9c2df7
664,500
from typing import Set import re def parseAP(formula: str) -> Set[str]: """从LTL公式解析出原子命题集合""" ap_list = re.split('[()XGFUR∧∨]', formula) ret = set(ap_list) ret -= {'', 'True', 'False'} return ret
9df5ac2d1bb4f0a6b2c5dacb83b981dd26847e90
664,501
def hot_cold_process( curr_yr, p_cold_rolling_steel, assumptions ): """Calculate factor based on the fraction of hot and cold rolling processes in steel manufacturing. The fraction of either process is calculated based on the scenario input of the future share of cold rolllin...
3fd125c0ab3a3ba26bb4eb0fcd33781de0ea08db
664,502
def sysRequirements(df, test, orchest): """ This takes the config file dt and multiplies it to be the length of the dataframe in multiples of a day """ # print("Shape =>", df.shape[0]/ len(orchest)) # N = df.shape[0] / len(orchest) # df['Orchastration Requirements'] = list(map(lambda x: x*N, o...
64a71b2a8dc652e28ed9fd0516e4deae7890a74c
664,503
def mcari(b3, b4, b5): """ Modified Chlorophyll Absorption in Reflectance Index \ (Daughtry et al. 2000). .. math:: MCARI = ((b5 - b4) - 0.2 * (b5 - b3)) * (b5 / b4) :param b3: Green. :type b3: numpy.ndarray or float :param b4: Red. :type b4: numpy.ndarray or float :param b5: Red-e...
827157f808afedef492b299f64cac6dda64f95c6
664,505
def get_object_or_none(model_class, name): """ Returns the object or None. """ try: return model_class.objects.get(name=name) except model_class.DoesNotExist: return None
72e6af4f8de00095b4f04427e5316add8c82b362
664,506
def findAllPaths(g, start_vertex, end_vertex,poids=0, path=[]): """ find all paths from start_vertex to end_vertex in graph """ graph = g.gDict() path = path + [start_vertex] if start_vertex == end_vertex: return [(path,poids)] if start_vertex not in graph: return [] pa...
781147615b7110b8e9584f3a07c0f753db53eac6
664,507
def connection_type(proxies): """Returns a string describing the connection type for use in metrics. """ request_scheme = 'https' if proxies is None: return 'direct/%s' % request_scheme proxy_scheme = proxies['http'].split('://')[0] return '%s-proxy/%s' % (proxy_scheme, request_sche...
c4796c49532cefbdee3d4fdc745869bcd51a07ef
664,508
def selectSynsetForSentenceByAverageSimilarity( sent, sentences, synsets, model ): """ Select synset for the sentence using average similarity. (1) sent is current sentence (2) for each synset (3) calculate dist( lemmas of sentence, synonyms of synset) (4) select the most sim...
1d93a1e238e0682ebbe6904f780c551d233d8fdd
664,509
def _scale_size(size, scale): """Rescale a size by a ratio. Args: size (tuple[int]): (w, h). scale (float): Scaling factor. Returns: tuple[int]: scaled size. """ w, h = size return int(w * float(scale) + 0.5), int(h * float(scale) + 0.5)
878f7646c1dd0f545a406b758fa45d5bc1a316cf
664,510
import os import requests def make_request(request_url): """ Send a GET request :param request_url: request url to get :return: response """ headers = {"X-API-KEY": os.environ.get('OS_API_KEY', '')} response = requests.request("GET", request_url, headers=headers) return response.json()
4b100deb58cea8b353439ed94415486ef2e7c28d
664,511
import argparse def get_args(): """get arguments""" parser = argparse.ArgumentParser( description='Graph through sequences', formatter_class=argparse.ArgumentDefaultsHelpFormatter) #positional argument statement parser.add_argument( 'fasta', metavar='str', help = '...
4cee71aae1635e898d7802d8fcc80aceef923b86
664,512
def remove_digits(s): """ Returns a string with all digits removed. """ return ''.join(filter(lambda x: not x.isdigit(), s))
42abd1c827f48fe9c22c50aa37944b54781df448
664,513
def transmogrify(cls, obj): """ Upcast a class to a different type without asking questions. """ if "__init__" not in obj.__dict__: # Just assign __class__ to a different value. new = obj new.__class__ = cls else: # Run constructor, reassign values new = cls()...
21bd5f034de8c31d63ad24de3b30f0c8e8922317
664,514
import os import fnmatch import io import yaml def get_holidays(): """ Loop through all conf files for every country and return all holidays :return: array """ countries = [] errors = [] walk_dir = "./conf" for root, dirnames, filenames in os.walk(walk_dir): for filename in fnm...
c6a98bf236a62055058b13434e38a3c1896e50e3
664,515
def _ParseGnArgs(args_path): """Returns a list of normalized "key=value" strings.""" args = {} with open(args_path) as f: for l in f: # Strips #s even if within string literal. Not a problem in practice. parts = l.split('#')[0].split('=') if len(parts) != 2: continue args[parts...
8fa1dc16b4c114a37dbe8e1085938410d40fc302
664,516
def parameters_analyser(string_instruction): """ Return a list with the parameters of the instruction. A post treatment may be required for some instruction """ return string_instruction.split(', ')
7197db221a9d154804ac0b0a93fd8d8c224ed632
664,517
import argparse def get_args(): """ Parse and return the inputs arguments. """ parser = argparse.ArgumentParser( description='SMuRF ATCA Monitor') parser.add_argument( '--shelfmanager', '-S', type=str, required=True, dest='shelfmanager', help='Node ...
981e724e07da1a86fdd3e42972a9725258e814f7
664,518
import copy def merge_qedges(qedges1: dict, qedges2: dict) -> dict: """Merge qedges: the keys must be the same and the values must be the same. If a key is unique to one edges dict, then the edge will be concatenated to the new edges dictionary. If a particular key exists in both messages but the valu...
0c026e9529f6d66cdec168aa4594df521176a8a4
664,519
def rekey_map(mapping, replacements): """Given an iterable of destination/source pairs in replacements, create a new dict that is the same as the original except for the new key names.""" result = dict(mapping) for dst, src in replacements: value = result[src] result[dst] = value ...
3518f824b31949cc913c4a02ba9537929224765f
664,520
def create_olists(org_lists, org_detail, org_ids, ltype=0, i_type=0): """Method to create org list of units, sub-units and sub-sub-units.""" inst_types = ['TNRH', 'TNRB', 'TNRR', 'TNRS', 'TNAP', 'TNRC'] try: if ltype == 0: for org_list in org_lists: unit_id = org_list.org...
9202bd373dab061ac4535bba9109cf81ca733402
664,521
import torch def expm1(input_): """Wrapper of `torch.expm1`. Parameters ---------- input_ : DTensor or STensor. Input tensor. """ return torch.expm1(input_._data)
40f4cd8e6a8a28b2eab75d071fd8044fce4d0e47
664,522
def parseOperator(value): """ Returns a search operator based on the type of the value to match on. :param value: to match in the search. :return: operator to use for the type of value. """ if type(value) == str: return " LIKE " else: return "="
6a82551878b1733db8c08424acf8d8f9a49bcb61
664,523
def voxelnet__extract_feat(ctx, self, voxels, num_points, coors, img_metas=None): """Extract features from points. Rewrite this func to remove voxelize op. Args: voxels...
0f1a023df83dd9c7f2d15761470556d829a07b3c
664,524
def token_lookup(): """ 准备标点符号的键值对 """ return { '。':'||句号||', ',':'||逗号||', ':':'||冒号||', '!':'||感叹号||', '?':'||问号||', '(':'||左括号||', ')':'||右括号||', '--':'||引号||', '\n':'||回车||', ...
f2da895c557da74b79e568aa24b135609e8c5b66
664,525
def unique_list(lst): """Make a list unique, retaining order of initial appearance.""" uniq = [] for item in lst: if item not in uniq: uniq.append(item) return uniq
8710247b83deccbdd6cff7757981bd30b9e874c5
664,526
def sign(x): """Returns -1 if x < 0, 1 otherwise Error Conditions: - raises TypeError if x is not a number """ abs(x) # checks type of argument if x < 0: return -1 else: return 1
6156b3fea546bf7c88b026d9e2b36cfad8e1dc65
664,528
def get_filenames_add_username(files, username): """ Adds the username to the end of a file name :param files: List of file names :param username: Username to append :return: filename with appended username """ filenames = [] for file in files: filenames.append(file + username...
acf376ab3447f16448b0d6f4cc3e745091d2f84f
664,529
def sortedby(item_list, key_list, reverse=False): """ sorts ``item_list`` using key_list Args: list_ (list): list to sort key_list (list): list to sort by reverse (bool): sort order is descending (largest first) if reverse is True else acscending (smallest first)...
8efca95c32256e3f7b96c9e101f3d7b596bb572f
664,531
import os def changeBaseDir(path, newBaseDir): """Given a path and a new base directory, swaps out the first directory in the path with the new base directory. The given path is unchanged if newBaseDir is None Ex: changeBaseDir('foo/bar/path.txt', 'someOtherDir') --> 'someOtherDir/bar/path.txt' Args: path ...
9d1b96edb423f950dd8aea4f6b94068f20e49b9b
664,532
def FWHMgeom2FWHMeff(FWHMgeom): """ Convert FWHMgeom to FWHMeff. This conversion was calculated by Bo Xin and Zeljko Ivezic (and will be in an update on the LSE-40 and overview papers). Parameters ---------- FWHMgeom: float The geometric FWHM value, as measured from a typical PSF pr...
882345c03c5e8c2fa789ff796f0f4261c883c8e7
664,533
def selector(selection_string: str, options: "list[str]", default = None) -> str: """ Asks the user for an option within a list of provided options and an optional default and returns their response """ while True: if default: input_string = f"{selection_string} ({', '.join(options)}...
6f712b433762bdf6e198df05ef181700d3b83bfd
664,534
def first(x): """Returns the first time step of all sequences in x.""" return x.dimshuffle((1,0,2))[0]
f31785f01d271fce5bf38f1c18df5cf7e38333a8
664,535
def ExportFormat_Array(): """ Export file format options""" ExportFormat_List = ['png', 'svg', 'eps', 'pdf'] return ExportFormat_List
e5750c4ab66af95bfd05c357eb6a06d90c1022a6
664,537
def isPowerOfFour1(n): """ 二进制写法 1 4:100 16:2^4:10000 64:01000000 :param n: :return: """ mask = 0xaaaaaaaa print(n&(n-1))# 是否为10000格式 return n > 0 and (n & (n - 1)) == 0 and (n & mask) == 0
c827fa86e0c83beb1ed72a22d7221a431d5b1b96
664,538
import os def samedir(fn): """ return abspath of fn in the same directory where this python file stores """ return os.path.abspath(os.path.join(os.path.dirname(__file__), fn))
90c35f2304cb2fd1b315d5e59f80b6cd3fafa38f
664,539
import torch def exact_gaussian_kernel(x1, x2): """Computes exact Gaussian kernel value(s) for tensors x1 and x2.""" x1 = torch.tensor(x1, dtype=torch.float32) x2 = torch.tensor(x2, dtype=torch.float32) x1_squared = torch.sum(x1 ** 2, list(range(1, len(x1.shape)))) x2_squared = torch.sum(x2 ** 2, ...
cb80d07328cdc06c9509df8add93be2a30a9a1df
664,540
def get_depth(node): """ Helper function to get depth of node from root """ depth = 0 while node.parent: node = node.parent depth += 1 return depth
8e2cc2142af1f6a34cdf25d8eae34b2956d0ca1d
664,542
import sys def validator_for_main(user_input): # pragma no cover """Check that input is 'TY' or 'RE'.""" if user_input == 'Q': sys.exit() return user_input == 'TY' or user_input == 'RE'
7cc6e769134524d1f5d966b59d9e35350ba638cb
664,543
def parametrization_name_func(func_name, kwargs): """ Method name generator for parametrized testcases. >>> import collections >>> parametrization_name_func('test_method', collections.OrderedDict(('foo', 5), ('bar', 10))) 'test_method__foo_5__bar_10' :param func_...
c9b2092a2e7eab80f3ec44733f03df5a2a0d1931
664,544
def yaff_input_key(cluster, key): """Convert keys on input from .yaff.""" try: # check for codepoint (anything convertible to int) cluster.codepoint = int(key, 0) return cluster except ValueError: pass try: # accept decimals with leading zeros cluster.code...
09cd2c86cd585b50a11b2efc69c97a1297a95d43
664,545
def fourSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ nums.sort() sum_target = [] first = 0 while first < len(nums)-3: sec = first + 1 while sec < len(nums)-2: third = sec+1 fourth = len(nums)-1 ...
8648d3563e75456b67685411147e7972c165fc99
664,546
def union(root1, root2): """Perform a weighted union between root1 and root2. Args: root1 (Root): root of the first cluster in the union root2 (Root): root of the second cluster in the union Returns: NoneType or (Root, Root): If root1 and root2 are same, returns None; e...
c3c7b744fceb8605d280154f7ec7fe83052dddf5
664,547
def _extract_2fold(codon, aa): """ This function embeds a pair of bits in 2/3 fold degenerative codon. :param codon: watermarked codon :param aa: amino acid information. :return: extracted bit 0 or 1. """ if codon == aa["codons"][0].lower(): return '0' else: return '1'
ff06ae1175b37c62d5d1cc7ab9908d76056ed9bf
664,548
def dispatch(result): """DB query result parser""" return [row for row in result]
fddf04544a887598f1debf075d5655e57077b1b3
664,550
def hex_to_ip(s): """ '7f000001' => '127.0.0.1'""" try: ip = map(lambda n: s[n:n+2], range(0, len(s), 2)) ip = map(lambda n: int(n, 16), ip) return '.'.join(map(str, ip)) except: return ''
7db80d0be1fefb7d2d773d2c1993b3cf9afbc969
664,551