content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _bytes_chr_py3(i): """ Returns a byte string of length 1 whose ordinal value is i in Python 3. Do not call directly, use bytes_chr instead. """ return bytes([i])
b6cd1e5e7214d02c29a594e639fbddac901a1362
12,593
def guess_type(v, consumer='python'): """Guess the type of a value (None, int, float or string) for different types of consumers (Python, SQLite etc.). For Python, use isinstance() to check for example if a number is an integer. >>> guess_type('1') 1 >>> guess_type('1', 'sqlite') 'integer' ...
a9361d5ce7f070f09dca267afb4ffcae866040eb
12,595
import torch def array_from_skew_matrix(x, device=torch.device("cpu"), dtype=torch.float32): """ Receives a skew matrix and returns its associated 3-element vector (array). :param x: Skew matrix (3x3) :return: Associated array (3-element). :param device: Device to allocate new tensors. Default: torch...
54dcb699db154e8c995dc324888b633451cfb7fc
12,596
def binary(img,th=128): """generate binary image Args: img : image array th : threshold """ img[img<th] = 0 img[img>=th] = 255 return img
627c3fc928886facbae8ca4cf692f543f4cbca40
12,597
import json def hello(event, context): # pylint: disable=unused-argument """Hello lambda function. Args: event (dict): Contains information from the invoking service (service defines the event structure) context (obj): Contains methods and properties that provi...
fabe319ab98cfcdd9208b021a6b4e42d6aa46a05
12,599
from typing import List from typing import Dict def single__intent_topk_precision_score( intent_prediction: List[Dict[str, str]], y_true: List[str], k: int = 1, ) -> float: """Compute the Precision of a single utterance with multi-intents Precision of a single utterance is defined...
3b67849670f80a3fa148249a6fe41ce4627546e5
12,602
def _deal_with_axis(obj, axis): """Handle the `axis` parameter Parameters ---------- obj: DimArray object axis: `int` or `str` or `tuple` or None Returns ------- newobj: reshaped obj if axis is tuple otherwise obj idx : axis index name : axis name """ # before apply...
ae0eec4bdf7f172f9617e9f9d1330d75b08f8e97
12,610
def simple_bet(pressure, n_monolayer, c_const): """A simple BET equation returning loading at a pressure.""" return (n_monolayer * c_const * pressure / (1 - pressure) / (1 - pressure + c_const * pressure))
601701b608a48fe634d028023068fcadc636499b
12,613
from typing import Container from typing import Iterable def match_tags(search: Container[str], tags: Iterable[str]): """Check if the search constraints satisfy tags. The search tags should be uppercased. All !tags or -tags cannot be present, all +tags must be present, and at lest one normal tag mus...
0a6ee5f233900eb50ad72613aa73f227a836b4dd
12,617
from typing import Dict from typing import Any from typing import Iterator from typing import Tuple def flatten(dictionary: Dict[str, Any]) -> Dict[str, Any]: """ >>> flatten({'foo':{'bar':{'baz': 0}, 'deadbeef': 1}, '42': 3}) {'foo.bar.baz': 0, 'foo.deadbeef': 1, '42': 3} """ def iterate(data: Di...
401f2f8894690a0c1171d26378ac4a5178dd705a
12,621
def subdivide_stats(data): """ If a key contains a ., create a sub-dict with the first part as parent key """ ret = {} for key, value in data.items(): if '.' in key: parent, subkey = key.split('.', 2) if parent not in ret: ret[parent] = {} ...
65e47db5c75118c1939a8ecdd3ad581a053da893
12,625
import re def parentdir(file_path): """ Get the parent directory of a file or directory. Goes by the path alone, so it doesn't follow symlinks. On Windows, paths must be converted to use / before passing. This function is not the same as os.path.dirname(); for example, dirname will not giv...
baec28e9b6f0017566b91cd2b442a9eb783a144f
12,627
def _Int(s): """Try to convert s to an int. If we can't, just return s.""" try: return int(s) except ValueError: assert '.' not in s # dots aren't allowed in individual element names return s
8f7fcf70717fe30ba991c8cff63cecefe5c01daf
12,628
def strlist_with_or (alist): """Return comma separated string, and last entry appended with ' or '.""" if len(alist) > 1: return "%s or %s" % (", ".join(alist[:-1]), alist[-1]) return ", ".join(alist)
1202e76d34f84618bb6b310bbc43c835f3c94104
12,629
def values_dict(items): """Given a list of (key, list) values returns a dictionary where single-element lists have been replaced by their sole value. """ return {k: v[0] if len(v) == 1 else v for k, v in items}
7abcf62ab334cecc6e6996bad73ff10e5eecdf89
12,636
def DetermineServiceFromUrl(url): """Takes a DFA service's URL and returns the service name. Args: url: string The DFA service's URL. Returns: string The name of the service this URL points to. """ return url.split('/')[-1]
213e1a4dbb5eb3ed643e0ace300b4ac5b6c6c745
12,640
def scrub_response(response): """ Drop irrelevant headers. """ headers = response["headers"] for header in [ "CF-Cache-Status", "CF-RAY", "Cache-Control", "Connection", "Date", "Expect-CT", "NEL", "Report-To", "Server", ...
8f1a9f9499df1fbaf7147ccdda8c7854c4c638ec
12,646
def check_necessary_conds(val_inf, muls): """ The necessary conditions for a rational solution to exist are as follows - i) Every pole of a(x) must be either a simple pole or a multiple pole of even order. ii) The valuation of a(x) at infinity must be even or be greater than or equal to 2....
58463ac2855d07eb36e1850cec3208d69d5a545c
12,647
def get_rect_footprint(l_m=4.8, w_m=1.83): """ Get rectangular footprint of length (x, longitudinal direction) and width (y, lateral direction) l_m : length (default 4.8) w_m : width (default 1.83) Return Values ============= footprint_x : tuple of x coordinates of the footprint footpr...
dd40304c404226543023c1f81bca5aac81e70eec
12,649
def _parse_source_file_list_blob_key(blob_key): """Parse the BLOB key for source file list. Args: blob_key: The BLOB key to parse. By contract, it should have the format: `${SOURCE_FILE_LIST_BLOB_TAG}.${run_id}` Returns: - run ID """ return blob_key[blob_key.index(".") + 1 :]
a7f5c7ccee1404e17b90cb6cd58922ec162d33e3
12,652
def prop_FC(csp, newVar=None): """ Do forward checking. That is check constraints with only one uninstantiated variable. Remember to keep track of all pruned variable,value pairs and return """ constraints = csp.get_cons_with_var(newVar) if newVar else csp.get_all_cons() pruned = [] for...
3956cf0ae03a03c0dbc3504ab2ed2a20b8343d90
12,654
def pad(val: str) -> str: """Pad base64 values if need be: JWT calls to omit trailing padding.""" padlen = 4 - len(val) % 4 return val if padlen > 2 else (val + "=" * padlen)
3ab1c91fde1522f15a766730f73e44c97dbeda1a
12,664
def word_remove(text, wordlist): """ This function takes a list of text strings and a list of words. It returns the list of text strings with the words appearing in the wordlist removed. """ # Create new emoty list for the cleaned text clean_text = [] # Seperate ALL words from each other an...
8dac46d54345efedf7bb117af3e4eb67704c0f85
12,666
def fs_write(obj, file_path): """ Convenience function to write an Object to a FilePath Args: obj (varies): The Object to write out file_path (str): The Full path including filename to write to Returns: The object that was written """ try: with open(str(file_path), 'w')...
c94db2399283a26529bf4416f5b05a93fafb4e07
12,667
import json def get_json(inp_dict): """Converts a given dictionary to prettified JSON string. Parameters ---------- inp_dict: map Input dictionary to be converted to JSON. Returns ------- Prettified JSON string """ return json.dumps(inp_dict, indent=4)
9404064536a12595fe9b601363eee07b09a97bc8
12,668
import calendar def month_delta(date, months): """Add or subtract months from date.""" day = date.day # subtract one because months are not zero-based month = date.month + months - 1 year = date.year + month // 12 # now add it back month = month % 12 + 1 days_in_month = calendar.monthr...
afa064af13c67be776a7f01ce48fc6ed2f33f581
12,672
def get_attribute(obj, key): """ Get an attribute from an object, regardless of whether it is a dict or an object """ if not isinstance(obj, dict): return getattr(obj, key) return obj[key]
bb20ac5809cf89b8043ff1fc60b9e4775ca95d18
12,673
from typing import List def compute_sigma_for_given_alpha(bundles:List[float],alpha:float)->float: """ This is a helper function to compute_alpha5_using_binary_search. the function computes one side of the inequality . :param bundles: valuations of the bags from B1 to Bk, were k is number of agents ...
08ae1c84f13de03b5404158de146b05b9efbfdce
12,681
def _makeScriptOrder(gpos): """ Run therough GPOS and make an alphabetically ordered list of scripts. If DFLT is in the list, move it to the front. """ scripts = [] for scriptRecord in gpos.ScriptList.ScriptRecord: scripts.append(scriptRecord.ScriptTag) if "DFLT" in scripts: ...
6c67698c3d084c8e8f038e05a8d8e53811220a15
12,684
import torch from typing import Tuple from typing import List def concat_enc_outs( input: torch.LongTensor, enc_out: torch.Tensor, mask: torch.BoolTensor, embedding_size: int, padding_idx: int, ) -> Tuple[torch.Tensor, torch.BoolTensor]: """ Concatenate Encoder Outputs. Does the whole...
6b1794966229a8f7658afcb70a5e91a652e6b1c5
12,685
import math def poids_attirance(p, dist): """ Calcule le poids d'attraction d'une neurone vers une ville. """ d = p[0] * p[0] + p[1] * p[1] d = math.sqrt(d) d = dist / (d + dist) return d
4a997566d19dc7e436a3a1704be7b5ac74424266
12,688
def dedup(records): """Remove any identical records from the list. Args: records (list(dict)): the list of dicts to be filtered. Returns: list(dict): the list of records with any duplicates removed. The list returned contains records in the same order as the original list. """ ...
f3aadddf1458a08d36331a74722e12057d8ab8f9
12,689
import inspect def is_functional_member(member): """ Check whether a class member from the __dict__ attribute is a method. This can be true in two ways: - It is literally a Python function - It is a method descriptor (wrapping a function) Args: member (object): An object in t...
268068600689a7935c9a8b26aa14ca09f9679228
12,690
def convert_x1y1x2y2_to_XcYcWH(box): """ Convert box from dictionary of {"x1":,"y1":,"x2":,"y2"} to {"x_centre":,"y_centre":,"width":,"height":} Assumption 1: point 1 is the top left and point 2 is the bottom right hand corner """ assert box["x1"] <= box["x2"] assert box["y1"] <= box["y2...
e7da7353b64b969b4c51dc7ece06729b05bad31e
12,691
def edit_distance(s1: str, s2: str) -> int: """The minimum number of edits required to make s1 equal to s2. This is also known as the Levenshtein distance. An edit is the addition, deletion, or replacement of a character. """ if not s1: return len(s2) if not s2: return len(s1) M = [[0 for _ in...
bd433f8b52dd9826032ced7ece0fb7df8b5ad8cc
12,697
def _remap_cortex_out(cortex_out, region, out_file): """Remap coordinates in local cortex variant calls to the original global region. """ def _remap_vcf_line(line, contig, start): parts = line.split("\t") if parts[0] == "" or parts[1] == "": return None parts[0] = contig...
03357f276c6733508f17197a3300f1d55271e486
12,699
def _album_is_reviewed(album, user_key): """Check if an album has been reviewed. Args: album: An Album entity user_key: A stringified user key, or None. Returns: If user_key is None, returns True if and only if the album has any reviews at all. If user_key is not None, retu...
fd3b495ccdbc7a61398bc63a28fd5ab8378152f0
12,701
import sqlite3 def load_history_db(history_db): """ Load simulation history from provided db. In case no db is given, returns an empty history :param history_db: :return: """ history = {} if history_db is not None: conn = sqlite3.connect(history_db) cursor = conn.cursor() ...
06055c6c48f8757513808e44d85f802ab0acd456
12,702
def upload_location(instance, filename, **kwargs): """Upload location for profile image""" return f"accounts/{instance.username}/{filename}"
c662bbb095f8180aa330a2566c9d9aaf372712b0
12,704
import collections from typing import Mapping def namedtuple(typename, field_names, default_values=()): """ Overwriting namedtuple class to use default arguments for variables not passed in at creation of object Can manually set default value for a variable; otherwise None will become default value ""...
b0fba5ba73037e7bdb5db05d10a8b96f953fc829
12,708
def length_along_path(pp, index): """ Get the lenth measured along the path up to the given index. """ index = min(index, len(pp) - 1) # beware of the end diff_squared = (pp[:index] - pp[1:index+1]) ** 2 distances = diff_squared.sum(1) return (distances ** 0.5).sum() # == sum(pp[j].distance...
a7eea4b411860c51fb5f64a690a9d4832c8b98a9
12,709
def isWithin(rect1, rect2): """Checks whether rectangle 1 is within rectangle 2 Parameters: rect1: list of coordinates [minx, maxy, maxx, miny] rect2: list of coordinates [minx, maxy, maxx, miny] Returns: True if rect1 within rect2 else False """ minx1, maxy1,maxx1, miny1 = r...
d7adca34b7cfb4294316090e18c164db0a34e818
12,714
def doolittle(matrix_a): """ Doolittle's Method for LU-factorization. :param matrix_a: Input matrix (must be a square matrix) :type matrix_a: list, tuple :return: a tuple containing matrices (L,U) :rtype: tuple """ # Initialize L and U matrices matrix_u = [[0.0 for _ in range(len(matrix...
03ba90c29dfb67ffe1edf939b49f3ab537931831
12,715
def getRequest(request): """ Get an openid request from the session, if any. """ return request.session.get('openid_request')
f6ebcb13e631365f53ae3a362eaf2dba614d7344
12,719
def flatten_df(df): """Flatten the df to an array Args: df(pd.DataFrame): a dataframe Returns: an array """ return df.values.flatten()
4faedf1059fa60c2ee3af95cd6f01e7d3cadd97e
12,723
from typing import Counter def duplicated(v): """Returns a generator expression of values within v that appear more than once """ return (x for x, y in Counter(v).items() if y > 1)
bf854dfde83c9d998f3f0b5f5553254be6347a4c
12,727
def _readonly_array_copy(x): """Return a copy of x with flag writeable set to False.""" y = x.copy() y.flags["WRITEABLE"] = False return y
ffd973bb354a642362a7382934f879c9dfa95c3b
12,728
import re def str_list_to_list_str(str_list, regex_pattern='[A-Z]\d+'): """ Turn a string of a list into a list of string tokens. Tokens determined by regex_pattern """ p = re.compile(regex_pattern) return p.findall(str_list)
99d3bbccadc0676dac6854ee717f8aef3bb878a6
12,729
def flagger(value): """ Conversion routine for flags. Accepts ints or comma-separated strings. :param str value: The value to convert. :returns: A value of an appropriate type. """ try: # Convert as an integer return int(value) except ValueError: # Convert as ...
cdc3fab338fd7f25499e25593302fb209f9be2a4
12,732
import time def time_func(func, kwargs): """ Time a function. Return the time it took to finish and subsequent result. """ start = time.time() res = func(**kwargs) finish = time.time() - start return finish, res
78f73058a90048f8de24915f1f8ba56bda79cc6a
12,734
def gen_end(first_instruction_address): """ Generate an end record. """ # specify the size of each column col2_size = 6 # content for each column col1 = "E" col2 = hex(first_instruction_address)[2:].zfill(col2_size).upper() return col1 + col2
d5df69b33cfb4f99aa9dbc5e003b713637fa1eff
12,738
def variantMetadata_object(processed_request): """ Builds the variantAnnotation object. Since we only have one model for this object we keep it simple. """ beacon_variant_metadata_v1_0 = { "default": { "version": "beacon-variant-metadata-v1.0", ...
4bf6dc519fcca02ea63d0f94af55adffe29ad9f8
12,744
def find_closest_stores(friends, stores): """ Finds the closest store to each friend based on absolute distance from the store. Parameters: friends: Dictionary with friend names as keys and point location as values. stores: Dictionary with store names as keys and point l...
ca879f6f442a4d734bf9e3c7b0313cd31ea2a026
12,748
def bash_quote(*args): """Quote the arguments appropriately so that bash will understand each argument as a single word. """ def quote_word(word): for c in word: if not (c.isalpha() or c.isdigit() or c in '@%_-+=:,./'): break else: if not word: ...
cb25adb60ea98cb6887e89a6a4f5097bb8f4843f
12,752
def get_area(root): """Extracts the ash cloud total area Values returned are in this order" 1. Total ash area 2. Total ash area unit""" area = root.alert.total_area.attrib.get('value') area_unit = root.alert.total_area.attrib.get('units') return area, area_unit
ea5a908e4226359aeb962f66c4ed4691d8d93a1b
12,754
def question_data_path(instance, filename): """Returns Questions data path.""" # question data will be uploaded to MEDIA_ROOT/question_<id>/<filename> return 'question_{0}/{1}'.format(instance.title.replace(" ", "_"), filename) # return 'question_{0}/{1}'.format(inst...
dc268bb4e3ff0d00ac3bb8ba8299ce0629951487
12,757
def _compscale(data): """ Automatically computes a scaling for the wavefunctions in the plot. Args: data (dict): The data neccesarry for computing the scale factor. Needs to contain 'wfuncs' and 'energies'. Returns: scale (float): The computed scale. """ wfuncs = d...
0c33313c86c38568a1713de28e5f5b44b2b0207c
12,758
from functools import reduce def equal(list_): """ Returns True iff all the elements in a list are equal. >>> equal([1,1,1]) True """ return reduce( lambda a, x: a and (x[0] == x[1]), zip(list_[1:], list_[:-1]), True, )
65b8a9b5652ecd6b3cc9709dd7e56b4e1258caf4
12,760
def stocking_event_dict(db): """return a dictionary representing a complete, valid upload event. This dictionary is used directly to represent a stocking event, or is modified to verify that invalid data is handled appropriately. """ event_dict = { "stock_id": None, "lake": "HU", ...
bed85f03438700754d52a0d858d7a41ee5079406
12,762
async def consume_aiter(iterable): """consume an async iterable to a list""" result = [] async for item in iterable: result.append(item) return result
897c8e9380f9c631f2dd8721884ec1ccbe462d48
12,769
import ipaddress def validate_ip(ip): """ Checks if an IP address is valid for lookup. Will return False if an IP address is reserved or invalid. Resource: https://en.wikipedia.org/wiki/Reserved_IP_addresses """ try: return not ipaddress.ip_address(ip).is_private except Value...
5d10a41e6bc6d645cbef24e8e4128baaf67aa997
12,772
def add_links(self, value): """ This creates a Link header from the links Parameters ---------- self : lib.schema.riak.objects.Link The Link schema object value : dict The headers of the request to add the links to """ links = getattr(self, 'links', []) if links: ...
3d507ce928b227399ca325d5a55cab6b5ae07791
12,777
import json def getUrnJson(data): """Returns URN to entity in JSON data""" decodedJson = json.loads(data) return decodedJson["urn:lri:property_type:id"]
af1761acb9322f295af3500cc4ecc519da16d7b1
12,781
def type_to_str(_type : type | tuple, sep : str =" or "): """ Converts type or tuple of types to string e. g. <class 'bin_types.functions.Function'> -> function For tuples will separate types with argument sep, standard sep is " or " """ if isinstance(_type, tuple): types = [] ...
04589e24aef9db1d302b8d4d439d7d5e1ba70e49
12,782
def Imu_I0c1c2c3c4(mu, c): """ I(mu, c) where c = (I0, c1, c2, c3, c4) """ return c[0]*(1-c[1]*(1-mu**0.5)-c[2]*(1-mu)-c[3]*(1-mu**1.5)-c[4]*(1-mu**2.))
6553deaff09f4a3e00364b271095b5e80472b3a1
12,789
def isinstance_qutip_qobj(obj): """Check if the object is a qutip Qobj. Args: obj (any): Any object for testing. Returns: Bool: True if obj is qutip Qobj """ if ( type(obj).__name__ == "Qobj" and hasattr(obj, "_data") and type(obj._data).__name__ == "fast_cs...
3c140e012d0df97852e84c50a37e6464e107fe2e
12,790
def get_color_specifier(basecolor, number): """Build an OpenGL color array for the number of specified vertices.""" color = [float(x) for x in basecolor] if len(color) == 3: return ("c3d", color * int(number)) elif len(color) == 4: return ("c4d", color * int(number))
b7c14272aa393c66fdedc109b90f9c8fce6118b0
12,791
def _unlParseNodePart(nodePart): """ Parse the Node part of a UNL Arguments: nodePart: The node part of a UNL Returns: unlList: List of node part parameters in root to position order. """ if not nodePart: if nodePart is None: return None ...
443c7f67b5deae47448bf93ff874acfb77cb83c3
12,796
def calc_raid_partition_sectors(psize, start): """Calculates end sector and converts start and end sectors including the unit of measure, compatible with parted. :param psize: size of the raid partition :param start: start sector of the raid partion in integer format :return: start and end sector i...
a96e442d5915a108fbbf18838e2c4a311677eced
12,799
def chunks(sentences, number_of_sentences): """ Split a list into N sized chunks. """ number_of_sentences = max(1, number_of_sentences) return [sentences[i:i+number_of_sentences] for i in range(0, len(sentences), number_of_sentences)]
a11c06c60e2230b611fd669a1342e17970e27ba5
12,800
import torch def pos_def(ws, alpha=0.001, eps=1e-20): """Diagonal modification. This method takes a complex Hermitian matrix represented by its upper triangular part and adds the value of its trace multiplied by alpha to the real part of its diagonal. The output will have the format: (*,2,C+P) ...
f18cc9087d8ad0cef859b57d524b453ad11dd429
12,801
def dot_s(inputa,inputb): """Dot product for space vectors""" return inputa[:,0]*inputb[:,0] + inputa[:,1]*inputb[:,1] + inputa[:,2]*inputb[:,2]
7991192fa07b953cd2e8e3d5439769eebf0e1608
12,803
import pickle def pickle_serialize(data): """ Serialize the data into bytes using pickle Args: data: a value Returns: Returns a bytes object serialized with pickle data. """ return pickle.dumps(data)
9c8809ab7bbd0375e9d94d6baae95e26166e6c56
12,805
def strip_cstring(data: bytes) -> str: """Strip strings to the first null, and convert to ascii. The CmdSeq files appear to often have junk data in the unused sections after the null byte, where C code doesn't touch. """ if b'\0' in data: return data[:data.index(b'\0')].decode('ascii') ...
c315e84debe7eef239afd4c856d45f4d2a776af2
12,810
def getTitles(db): """ Gets all the books titles in the whole database :param db: database object :return: sorted books titles """ data = [] for book in db.find('books'): data.append(book['Title']) return sorted(data)
f63d2138cef4d2ad51767ad62abacce5169bb3a2
12,813
def give_coordinates(data): """ Get ground-truth coordinates (X,Y,Z, room label) where the measurement was taken, given the JSOn structure as an input. """ message = {} message['true_coordinate_x'] = data['raw_measurement'][1]['receiver_location']['coordinate_x'] message['true_coordinate_y'] = data['raw_m...
d412afbe08d4b1660ab9a12d1e567e4c4e4258fc
12,816
def orders_by_dow(data_frame): """ Gives orders_count by day of week. :param data_frame: DataFrame containing orders data. :return: DataFrame of order_ids count by day of week. """ grouped = data_frame.groupby(['order_dow'], as_index=False) # count by column: 'order_id' count = grouped.agg(...
bfca97ced614fb8c309f8edc482fc2136914759b
12,818
def is_user_logged(app): """Check for auth_tkt cookies beeing set to see if user is logged in.""" cookies = app.cookies if 'auth_tkt' in cookies and cookies['auth_tkt']: return True return False
67e670fd70787b35bc9b8d9a724512bfc4e7bac8
12,819
import re def mqtt_wildcard(topic, wildcard): """Returns True if topic matches the wildcard string. """ regex = wildcard.replace('.', r'\.').replace('#', '.*').replace('+', '[^/]*') if re.fullmatch(regex, topic): return True return False
fd7a3a5e8af1e6172decd62f2ba8294dfe07124c
12,824
def distinct_brightness(dictionary): """Given the brightness dictionary returns the dictionary that has no items with the same brightness.""" distinct, unique_values = {}, set() for char, brightness in dictionary.items(): if brightness not in unique_values: distinct[char] = brightnes...
7f7bb5dba9bab113e15cc4f90ddd4dfda7bb5f01
12,826
import torch def norm(x): """ Normalize a tensor to a tensor with unit norm (treating first dim as batch dim) :param x: :return: """ b = x.size()[0] n = torch.norm(x.view(b, -1), p=2, dim=1) while len(n.size()) < len(x.size()): n = n.unsqueeze(1) n.expand_as(x) retu...
b40ba939c80db85e2ac8377b21ea7a17589b1c0f
12,828
def get_unobs_nd_names(gname): """ For a graph named gname, this method returns a list of the names of its unobserved nodes (i.e., either [], or ["U"] or ["U1", "U2"]) Parameters ---------- gname : str Returns ------- list[str] """ if gname in ["G2", "G3", "G5", "G6", "G10...
3450293f464b1e7cc7ab343888a606bd96d0f094
12,830
from typing import Counter def getRepeatedList(mapping_argmat, score_mat_size): """ Count the numbers in the mapping dictionary and create lists that contain repeated indices to be used for creating the repeated affinity matrix for fusing the affinity values. """ count_dict = dict(Counter(mapp...
fa2449379bf8bf2051c2492d56de11c2ee0191e4
12,837
def _get_text_alignment(point1, point2): """Get the horizontal and vertical text alignment keywords for text placed at the end of a line segment from point1 to point2 args: point1 - x,y pair point2 - x,y pair returns: ha - horizontal alignment string va - vertical alignment s...
317860030bf86750207bc891c236ad2618c686b1
12,839
def normalize_rectangle(rect): """Normalizes a rectangle so that it is at the origin and 1.0 units long on its longest axis. Input should be of the format (x0, y0, x1, y1). (x0, y0) and (x1, y1) define the lower left and upper right corners of the rectangle, respectively.""" assert len(rect) == 4, '...
b1a011948adb52bb6dea068116ab3a564ab2a1f8
12,840
import inspect import warnings def valid_func_args(func, *args): """ Helper function to test that a function's parameters match the desired signature, if not then issue a deprecation warning. """ keys = inspect.signature(func).parameters.keys() if set(args) == set(keys): return True ...
4872817033ea55881442e69711b620b2853407f1
12,843
import shutil def binary_available() -> bool: """Returns True if the GitHub CLI binary (gh) is availabile in $PATH, otherwise returns False. """ return shutil.which("gh") is not None
e959757ccce6d162b225fd6ef986a7e248c606fa
12,845
def get_file_date_part(now, hour) -> str: """ Construct the part of the filename that contains the model run date """ if now.hour < hour: # if now (e.g. 10h00) is less than model run (e.g. 12), it means we have to look for yesterdays # model run. day = now.day - 1 else: d...
42c2beddccba755f66061364463f8ad759d3c020
12,851
from pathlib import Path import tempfile def get_basetemp() -> Path: """Return base temporary directory for tests artifacts.""" tempdir = Path(tempfile.gettempdir()) / "cardano-node-tests" tempdir.mkdir(mode=0o700, exist_ok=True) return tempdir
e34ffc5cae1373977f1b46ab4b68106e1bef3313
12,852
def mutate_string(string, pos, change_to): """ Fastest way I've found to mutate a string @ 736 ns >>> mutate_string('anthony', 0, 'A') 'Anthony' :param string: :param pos: :param change_to: :return: """ string_array = list(string) string_array[pos] = change_to retur...
c6119076411b57f9ded2e899d40b6b82bb5f7836
12,855
def with_last_degree(template_layers_config, degree): """ Change the degree of the last -- or actually penultimate -- layer in a layered micro-service application, while keeping the average service time for a user request constant. """ assert len(template_layers_config) >= 2 layers_config = ...
f09bec9e27586349c679a66070bc4bac0dcba5d1
12,859
def GetErrorOutput(error, new_error=False): """Get a output line for an error in regular format.""" line = '' if error.token: line = 'Line %d, ' % error.token.line_number code = 'E:%04d' % error.code error_message = error.message if new_error: error_message = 'New Error ' + error_message retur...
4661c74fcef9f13c0aad3d74e827d9eea20f86ef
12,861
def deunicode(s): """Returns a UTF-8 compatible string, ignoring any characters that will not convert.""" if not s: return s return str(s.decode('utf-8', 'ignore').encode('utf-8'))
baaf99acec746c266059c07e03a1ee4a7e76f46a
12,862
def constructUniformAllelicDistribution(numalleles): """Constructs a uniform distribution of N alleles in the form of a frequency list. Args: numalleles (int): Number of alleles present in the initial population. Returns: (list): Array of floats, giving the initial freq...
45e834d2129586cb6ff182e1a8fe6ecb1ae582ae
12,864
def id_record(rec): """Converts a record's id to a blank node id and returns the record.""" rec['id'] = '_:f%s' % rec['id'] return rec
1ee5a9e9600299b56543c92a77cadb1826bb9bb7
12,868
def obj_ext(value): """ Returns extention of an object. e.g. For an object with name 'somecode.py' it returns 'py'. """ return value.split('.')[-1]
7ef6f1009145a0acc543130c41d2082a14412b6d
12,869
import torch def binary_hyperplane_margin(X, Y, w, b, weight=1.0): """ A potential function based on margin separation according to a (given and fixed) hyperplane: v(x,y) = max(0, 1 - y(x'w - b) ), so that V(ρ) = ∫ max(0, y(x'w - b) ) dρ(x,y) Returns 0 if all points are at least 1 away from ...
0f038dc2ae9def9823b3f440a087ede52dcee717
12,870
def get_homologs(homologs_fname): """Extract the list of homolog structures from a list file :param homologs_fname: file name with the list of homologs :type homologs_fname: str :returns homologs_list containing the pdb codes of the homolog structures in the input file :rtype tuple """ hom...
1db108f30a3ef274cba918c5e1c056c6797a5bca
12,874
def _GetFields(trace=None): """Returns the field names to include in the help text for a component.""" del trace # Unused. return [ 'type_name', 'string_form', 'file', 'line', 'docstring', 'init_docstring', 'class_docstring', 'call_docstring', 'length', ...
acf8a1c62853f7648082689002b3ced2689892fe
12,877
def get_valid_values(value, min_value, max_value): """Assumes value a string, min_value and max_value integers. If value is in the range returns True. Otherwise returns False.""" valid_values = [i for i in range(min_value, max_value + 1)] try: value = int(value) except ValueError: ...
4385f8328cfbe6497f7a723be37e54f0a86f9fbf
12,883