content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import itertools def possible_pairs(s, mirrors=True): """Return possible pairs from a set of values. Assume `s = ['a', 'b']`. Then return examples for the following calls are: * `possible_pairs(s)` returns `[('a', 'b'), ('b', 'a')]` * `possible_pairs(s, mirros=False)` returns `[('a', 'b')]` ...
146f006f4d9cf7546383319ba30fa4051916a26c
660,898
def read_token_file(filename): """ Read a token file and return the oauth token and oauth token secret. """ with open(filename) as f: return f.readline().strip(), f.readline().strip()
92d73e88dda883712b9bc2f5e1700bc003c1a181
660,900
def string_to_int(value): """Converts a string to an integer Args: value(str): string to convert Return: The integer representation of the nummber. Fractions are truncated. Invalid values return None """ ival = None try: ival = float(value) ival = int(ival) e...
d9b251be776d721d25ec35bf7fa558e4e3b68f00
660,904
def find_cell (nb, cell_name): """ find a named cell within a notebook """ for cell in nb.cells: if ("name" in cell.metadata) and (cell.metadata["name"] == cell_name): return nb.cells.index(cell), cell return None, None
ac0e275ce44949086b8b59b0f6b961a2a239342b
660,908
from functools import reduce def convex_hull(points): """ Returns points on convex hull in counterclockwise order according to Graham's scan algorithm. Reference: https://gist.github.com/arthur-e/5cf52962341310f438e96c1f3c3398b8 .. note:: This implementation only works in 2-dimensional space. :para...
a53a23aa27339968c957fba2f3dd975dcfad18de
660,909
def prod_in_offsets( backend, offsets, content, mask_rows=None, mask_content=None, dtype=None ): """Summary >>> j = awkward.fromiter([[1.0, 2.0],[3.0, 4.0, 5.0], [6.0, 7.0], [8.0]]) >>> mr = numpy.array([True, True, True, False]) # Disable the last event ([8.0]) >>> mc = numpy.array([True, True, Tr...
1b8d4f6d3320c0313a385e1503668026fb9734a8
660,910
from typing import OrderedDict def skip_nan_tracks(tracks): """Filter tracks Args: tracks: dictionary or OrderedDict of arrays with ndim >=2 and same second dimension Returns: OrderedDict of tracks """ if tracks is None: return tracks if isinstance(tracks, OrderedDict): ...
0bfbdccf20ce7f3d4c90391bb13af0dfe3934a5f
660,911
def delete_file_nokia_sros(ssh_conn, dest_file_system, dest_file): """Delete a remote file for a Nokia SR OS device.""" full_file_name = "{}/{}".format(dest_file_system, dest_file) cmd = "file delete {} force".format(full_file_name) cmd_prefix = "" if "@" in ssh_conn.base_prompt: cmd_prefix ...
ef7a5152ed01640782b30a3509df5d8a9a7cfacf
660,914
def winCheck(board, marker): """ Check if someone win """ # check lignes return((board[1] == board[2] == board[3] == marker) or (board[4] == board[5] == board[6] == marker) or (board[7] == board[8] == board[9] == marker) or # check cols (board[1] == board[4] == board[7] == marker) o...
756808d5836d38b9d69d852db09ef36dfd767b99
660,915
def list_to_dict(l): """Convert list to dict.""" return {k: v for k, v in (x.split("=") for x in l)}
f806e238f73d6874f8e657c2b87aeb8cd6e44688
660,918
def sql_compile(dialect, statement, incl_literal_binds=True): """Compile a statement for the given dialect.""" return statement.compile( dialect=dialect, compile_kwargs={'literal_binds': True} if incl_literal_binds else {} )
81a538ede7ffa10b99cd4ceacd520d932196564d
660,921
def is_string(s): """Check if the argument is a string.""" return isinstance(s, str)
050be89ec88be7a6067464d4ad846acbf560d119
660,923
def find(predicate, iterable, default=None): """Return the first item matching `predicate` in `iterable`, or `default` if no match. If you need all matching items, just use the builtin `filter` or a comprehension; this is a convenience utility to get the first match only. """ return next(filter(pre...
70d0d4265d7ef70e3ff041794712990b2dfc10c6
660,928
def check_image_counter(name): """ Note: This method is only ever entered if there actually is a name as well as there will never be a .fits at the end. Pre: Takes in an image name as a string and sees if the standard iterator is on the end of the image name. Post: Returns a boolean of whether t...
32ed2eb702009694c9d9b8dd0a6a7f9eeea18881
660,930
def truncate_string(string, length=80, title=True): """ Returns a truncated string with '..' at the end if it is longer than the length parameter. If the title param is true a span with the original string as title (for mouse over) is added. """ if string is None: return '' # pragma: no cov...
9eaf25dcac23f1bd3c8839e8389e98e598e2b402
660,932
def gen_data_dict(data, columns): """Fill expected data tuple based on columns list """ return tuple(data.get(attr, '') for attr in columns)
b43e29a4365a9d9e418aeb7dfe2a3452fbe173d3
660,937
def validToken(token): """ Return True if token is in hex and is 64 characters long, False otherwise """ if len(token) != 64: return False try: token.decode("hex") except TypeError: return False return True
1fa264acc43dd67ba400ddb50ccf3aaa04f33300
660,938
def ip_to_num(ip): """ Convert an IP string to a number value. :param ip: IP string to convert :return: A number representation of the IP address """ s = ip[0].split(".") return int(s[0]) << 24 | int(s[1]) << 16 | int(s[2]) << 8 | int(s[3])
1a0136146064c4fc587c51d5d46ec9a47874cc80
660,939
def strip_rule(line): """ Sanitize a rule string provided before writing it to the output hosts file. Some sources put comments around their rules, for accuracy we need to strip them the comments are preserved in the output hosts file. Parameters ---------- line : str The rule prov...
788bb56aa566bc6089e70fe40aeac4a39aac70ed
660,945
def get_key(dictionary, field): """Gets an key of an dictionary dynamically from a name""" return dictionary[field]
1690b657738a722f4028ea393e9e863eb430e54d
660,947
import math def calculate_sum(*pairs): """ Computes a derived estimate and its MOE for the aggregation of all the arguments. Args: pairs (list): a list of two-item sequences with a U.S. Census bureau count estimate and its margin of error. Returns: A two-item sequence...
afe05bac060fa61f7d31aa19297af2e48362603d
660,952
def val(section, key): """ Return value of section[key] in units specified in configspec Args: section (:class:`qcobj.qconfigobj.QConfigObj`.Section`): instance key (string): valid key for `section` Returns: values in section[key] converted to units defined in c...
5b28d7ba9d1abcf42eecaa1af0a3b13f03dd44e6
660,953
from io import StringIO def print_elastic_ips(ec2, region): """ Print a list of UN-attached Elastic IP addresses :param ec2: The boto3 ec2 client :param region: The region to search in :return: The nicely formatted list of EIPs to print """ addresses_dict = ec2.describe_addresses() fo...
771e9d074472b71aa310ad3ad20b76f57559020f
660,955
def remove_invalid_attributes(obj, data): """ remove the attributes of a dictionary that do not belong in an object """ _data = {} for name, value in data.items(): if hasattr(obj, name): _data[name] = value return _data
89a401ba1f52bf155b74e03f00376a246641d946
660,964
import csv def split_csv_size(csv_file, size, folder, keepheader=True): """[Split a large csv file into small csv files with certain rows in each small csv file] Arguments: csv_file {[Path]} -- [the Path object for the large csv file to split] size {[int]} -- [number of observations in ea...
2eea6c09325750b0da96b8267f9dea17ca6d8439
660,966
def get_key_paths(data_dict, keys_to_consider=None, keys_not_to_consider=None, root_path=None): """ Example: get_key_paths({ 'a' : { 'b': 1 }, 'c' : 2 }) returns: ['a.b', 'c'] :param data_dict: (Nest...
c3548b24aaf49e2e5f5632f503a5fd32d38eb00b
660,967
def loadrepr(reprstr): """Returns an instance of the object from the object's repr() string. It involves the dynamic specification of code. >>> obj = loadrepr('datetime/datetime.datetime.now()') >>> obj.__class__.__name__ 'datetime' """ module, evalstr = reprstr.split('/') mylocals = l...
c0eaa039c3575992702a2a76cca2e9756561c833
660,968
def _get_axis_num(nrow, row, col): """ computes axis number Parameters ---------- nrow : int number of rows row : int row number col : int column number """ return (nrow * row + col) + 1
7ea99ef5960677e2b1769995080b598763e7a680
660,971
import pytz from datetime import datetime def is_it_june() -> bool: """ determines if it is currently June in Madison, Wisconsin Returns: True if it is June, False otherwise """ tz = pytz.timezone("US/Central") the_now = datetime.now(tz) return datetime.date(the_now).month == 6
e1018f1ec92fd7fadf9b305d338dfdf234d3db46
660,974
def avp_from_rhmin_rhmax(svp_temperature_min, svp_temperature_max, relative_humidity_min, rh_max): """ Estimate actual vapour pressure (*ea*) from saturation vapour pressure and relative humidity. Based on FAO equation 17 in Allen et al (1998). :param svp_temperature_min: Saturation vapour pressur...
556669e20ab4f2e3562f45a151cc292f1cb3bbb5
660,975
def cut_and_paste_segment(seq, start, end, new_start): """Move a subsequence by "diff" nucleotides the left or the right.""" sub = seq[start:end] diff = new_start - start if diff > 0: return seq[:start] + seq[end : end + diff] + sub + seq[end + diff :] else: return seq[: start + diff...
03daaac096f26994ef52be3a0249660ea391f36e
660,978
def get_n_document_from_yaml(yaml_generator, index=0): """ Returns n document from yaml generator loaded by load_yaml with multi_document = True. Args: yaml_generator (generator): Generator from yaml.safe_load_all index (int): Index of document to return. (0 - 1st, 1 - 2nd document) ...
2eb44fc0521fbb2782c63fc317d9c0f2801bc4d3
660,982
def typedvalue(value): """ Convert value to number whenever possible, return same value otherwise. >>> typedvalue('3') 3 >>> typedvalue('3.0') 3.0 >>> typedvalue('foobar') 'foobar' """ try: return int(value) except ValueError: pass try: retu...
96f4ae19004202ef2cf2d604e742693ebaebe2ed
660,984
import random def generate_hex_colour(ex_prop: float = 10.0) -> str: """ Generates a random hex color sampled from a partitioned color space Args: ex_prop (float): Head & tail-end proportions to exclude from sampling. This is to make sure that the generated colours are of a certain ...
a9e7fe7c3b537f82919fa678a5a6712d6c92b420
660,985
def herfindahl_hirschman_index(distribution): """Herfindahl–Hirschman Index Args: distribution (list): wealth distribution in the market Returns: (float): Herfindahl–Hirschman Index (HHI), market concentration degree 0 <= HHI < 1, HHI = 0, perfectly competitive ...
2822951809946604635d43ab939639e5e4cb0fee
660,987
def values_to_string(input_values): """Method that takes a list of values and converts them to a '|'-delimted string""" token_list = [] for value in input_values: token_list.append(str(value)) return '|'.join(token_list)
0ed4de389311caf25ac9d32a513f4a59e6efd05a
660,990
def get_user_dict(profile_dict): """Collect parameters required for creating users.""" return {k: profile_dict[k] for k in ('email', 'first_name', 'last_name', 'institution')}
e100425c353df505d87c49302a21660094daa660
660,995
def pretty_list(the_list, conjunction = "and", none_string = "nothing"): """ Returns a grammatically correct string representing the given list. For example... >>> pretty_list(["John", "Bill", "Stacy"]) "John, Bill, and Stacy" >>> pretty_list(["Bill", "Jorgan"], "or") "Bill or Jorgan" >...
cd66fe33026a8548d3dc9916070b15524d189f79
660,996
def clear_sentences(data): """ Cleaning sentences, removing special characters and articles """ sentences = list() for record in data: sentence = record['reviewText'] sentence = sentence.lower() for char in "?.!/;:,": sentence = sentence.replace(char, '') ...
91afa65c70be9386a658d0c74f317f647110740b
660,997
def _engprop(l): # {{{1 """Return the engineering properties as a LaTeX table in the form of a list of lines.""" lines = [ " \\midrule", " \\multicolumn{6}{c}{\\small\\textbf{Engineering properties}}\\\\[0.1em]", " \\multicolumn{3}{c}{\\small\\textbf{In-plane}} & ", ...
39e5f4bb61d4eee6fee7523921a8674bd31d9704
660,998
def space_tokenize_with_bow(sentence): """Add <w> markers to ensure word-boundary alignment.""" return ["<w>" + t for t in sentence.split()]
888587477d8474a2cfdd248b5bb7ea492e0e0986
661,002
import collections def _common_observations(physics): """Returns the observations common to all tasks.""" obs = collections.OrderedDict() obs['egocentric_state'] = physics.egocentric_state() obs['torso_velocity'] = physics.torso_velocity() obs['torso_upright'] = physics.torso_upright() obs['imu'] = physic...
d2ec73f268cac80acbf1e0eaac54eef261f39cd4
661,003
def chunk_generator(l, batch_size): """ Given any list and a batch size, returns a list of lists where each element is a list containing N (BATCH_SIZE) elements. ----------------------------------------------------------- :param l: a 1-D list batch_size: Batch size of a chunk ---...
bcbd128cb5bdc2efe0600f8a378d2b856a642028
661,004
def extract_literal_string(memory,address,ztext): """ Extract the literal string from the given memory/address and return the new address + string """ zchar_start_address = address text, next_address = ztext.to_ascii(memory,zchar_start_address,0) return next_address,text
67ab2340af180803231a2b9e9c7a6dd4fddc3ecc
661,005
def wrap_image(img_path, trailing_br=False, **kwargs): """Return a <img> markup, linking to the image in a URL""" _width = kwargs.get('width', '') _style = kwargs.get('style', '') if _style != '': _style = ' style="' + _style + '"' if str(_width) != '' : _width = ' width='+str(_wid...
860fc64c29010d386a981a178001962d2fb851d7
661,007
def _generate_barcode_ids(info_iter): """Create unique barcode IDs assigned to sequences """ bc_type = "SampleSheet" barcodes = list(set([x[-1] for x in info_iter])) barcodes.sort() barcode_ids = {} for i, bc in enumerate(barcodes): barcode_ids[bc] = (bc_type, i+1) return barcode...
90974c46b4a553e389ef9a18895a4110542ac3e0
661,008
from typing import Dict from typing import Any from typing import Optional def find_namespace( namespace: str, discovery_map_data: Dict[str, Any], ) -> Optional[Dict[str, Any]]: """Find the service-colors list for the given namespace.""" for namespace_obj in discovery_map_data['namespaces']: ...
3192434d77e3bbd59fcb36bed98198105564cdaa
661,009
def find_test_index(test, selected_tests, find_last_index=False): """Find the index of the first or last occurrence of a given test/test module in the list of selected tests. This function is used to determine the indices when slicing the list of selected tests when ``options.first``(:attr:`find_last_index...
c09008bd13840a72e976420442a3c794bada8341
661,010
def add_mpos_2site(mpo1, mpo2): """Sum of two 2-site MPOs acting on the same pair of sites. """ return (mpo1[0] + mpo2[0], mpo1[1] + mpo2[1])
e27354ef2c2f642a60ded9768153d12912016c3f
661,011
def calc_J(df_clust): """Calculate the total angular momentum of the cluster:: N J = Σ r_i × m_i * v_i i=1 :param df_clust: cluster data - position, velocity, and mass :type df_clust: pyspark.sql.DataFrame, with schema schemas.clust :returns: J, broken into components ...
a51291633c009d833e80cdee5deafa3e61bcae42
661,012
def levi_civita(tup): """Compute an entry of the Levi-Civita tensor for the indices *tuple*.""" if len(tup) == 2: i, j = tup return j-i if len(tup) == 3: i, j, k = tup return (j-i)*(k-i)*(k-j)/2 else: raise NotImplementedError
006e3c6c23e0a230a0ca3b12684f653e595ece11
661,013
def triangleType(x, y, z): """ Determine if the triangle is valid given the length of each side x,y,z. :param x: First side of triangle :param y: Second side of triangle :param z: Third side of triangle :returns: Whether a triangle is an 'Equilateral Triangle', 'Isosceles Tria...
b2530e79cc693c00d829ad68bbb10fff96e89ab6
661,014
def to_bin_centers(x): """ Convert array edges to centers """ return 0.5 * (x[1:] + x[:-1])
1f0a88243fd2f4d77295e0ed88004a1a8d1cdba7
661,018
from typing import Any import json def json_pretty_print(parsed: Any) -> str: """ Pretty print a json object. :param parsed: a json object :return: a prettified json object """ if isinstance(parsed, str): parsed = json.loads(parsed) # `ret = pprint.pformat(parsed) ret = json.d...
25e9c2f8d5c168379c7da6b0e4c16a09d84503d7
661,020
def isinteger(number): """ This method decides if a given floating point number is an integer or not -- so only 0s after the decimal point. For example 1.0 is an integer 1.0002 is not.""" return number % 1 == 0
75c8e1a86d069609c069b2c33b0eb0ca02adf458
661,023
def _int_to_bin_str(value): """ This function returns the integer value in binary string of length 16. :param value: integer value to be converted to binary string. :return: None if 0 > value > 2^16-1 """ if 0 < value < (2**16): bits = bin(value)[2:] return ('0'*16)[len(bits):] +...
11c0142a34315134f995442034d49b169e8c1f20
661,024
def _median3(comparables, lo, mid, hi): """Sort the three elements of an array in ascending order in place and return the middle index Arguments: comparables -- an array of which the elements can be compared lo -- index 1 (inclusive) mid -- index 2 (inclusive) hi -- index 3 (inclus...
dba0a932b71e438ea3783556b1f28c6c9efb267e
661,028
import pytz def _make_timezone_naive_utc(datetime_object): """ If a given datetime is timezone-aware, convert to UTC and make timezone=naive """ if (datetime_object.tzinfo is not None) and (datetime_object.tzinfo.utcoffset(datetime_object) is not None): # Convert to UTC utc_time = datetime_ob...
b5ec2498907ec0f20159a339094862a26e64be8f
661,031
import logging def aggregate_metrics(raw_metrics, default_strategies, metric_strategies=None): """Aggregate raw TensorBoard metrics according to collection config. Available aggregation strategies: `final`, `min`, `max`. Args: raw_metrics: dict mapping TensorBoard tags to list of MetricPoint. default_...
78961acd181866db556cf679a51b7e183030fbba
661,032
def create_n_ride_data(size): """Create n ride request and return as a list""" ride_data = [] for i in range(size): ride_data.append({ "start_location": "Start from here%d" % i, "end_location": "End here%d" % i, }) return ride_data
c2891052385fee2b93190ab3791bb9b87c44ba23
661,037
def hmsm_to_days(hour=0, min=0, sec=0, micro=0): """ Convert hours, minutes, seconds, and microseconds to fractional days. """ days = sec + (micro / 1.e6) days = min + (days / 60.) days = hour + (days / 60.) return days / 24.
127cc131b6a1ee31f411fc9493601dc6c09fe786
661,041
def get_probe_2(table_name='filtered_links_dated'): """Create SQL query to select repo_id, linked_repo_id, and created_at from table_name.""" inputs = (table_name,) qry = "SELECT repo_id, linked_repo_id, created_at FROM %s" return qry, inputs
1fe6172041d334a22b987e0b11fb2ed14a802e63
661,043
def init_bitstring_groundstate(occ_num: int) -> int: """Occupy the n lowest orbitals of a state in the bitstring representation Args: occ_num (integer): number of orbitals to occupy Returns: (integer): bitstring representation of the ground state """ return (1 << occ_num) - 1
dba19dc9fb3930d85dc47998e375de394d4c062d
661,044
def is_name_private(name, public=None): """ Answers whether the name is considered private, by checking the leading underscore. A ist of public names can be provided which would override the normal check """ if public and name in public: return False return name.startswith('_')
879fbfadc43c45dc67c4199da12a7994349ef1da
661,046
def get_str(db,name): """ Get a string from the redis database. """ data_unicode = db.get(name) return str(data_unicode)
53a1bd62bc6b5e23c5d265ff12e16a42ee9d01fd
661,048
def mask(arr,pixels,val=0): """Mask an array arr based on array pixels of (y,x) pixel coordinates of (Npix,2)""" arr[...,pixels[:,0],pixels[:,1]] = val return arr
3acc519fd7596b6be406723b54d021cf5f31de9b
661,049
import logging def INFO(target): """A decorator to set the .loglevel attribute to logging.INFO. Can apply to either a TestCase or an individual test method.""" target.loglevel = logging.INFO return target
8bf2061b248a457131486687a32440ce68d173b5
661,055
def dict_apply_listfun(dict, function): """Applies a function that transforms one list to another with the same number of elements to the values in a dictionary, returning a new dictionary with the same keys as the input dictionary, but the values given by the results of the function acting on the input dictionary...
1d6fb556d566e01c1547a36b548de9d8ccd22976
661,056
def file_names(inp_fname): """Return the linkname and filename for dotfile based on user input. """ link = inp_fname if inp_fname.startswith('.') else ".{}".format(inp_fname) return link, "dot{}.symlink".format(link)
fe639780abf1537b79e6e71ddc08d44223c4ba00
661,057
def create_dict(key_list, val_list): """ The function creates dictionary from given key_list and value_list :param key_list: :param val_list: :return: Dictionary of type (key:val) """ temp_dict = {} for arg in range(len(key_list) - 1): temp_dict[key_list[arg]] = val_list[arg] ...
b590ff3ea0d168d7c9f1dc9a49c9d05428194d2e
661,058
import torch def krylov(L, A, b): """ Compute the Krylov matrix (b, Ab, A^2b, ...) using the squaring trick. """ x = b.unsqueeze(-1) # (..., N, 1) A_ = A done = L == 1 while not done: # Save memory on last iteration l = x.shape[-1] if L - l <= l: done = True ...
5850ca6415af7e03af178d956e8649c66a5046fd
661,059
def miles2km(miles): """ Converts miles to kilometers. Args: miles: A distance in miles. Returns: The equivalent distance in kilometers. """ return miles*1.60934
77cfb24e230a2670c9f3cc7aea5cdbea94e2ee0b
661,060
def file2list(filename): """Load text file and dump contents into a list""" listOfFiles = open( filename,'r').readlines() listOfFiles = [i.rstrip('\n') for i in listOfFiles if not i.startswith("#")] return listOfFiles
61ca2515eefc8012931369469156180887235c7d
661,061
import torch def optimizer_to(optimizer, device="cpu"): """ Transfer the given optimizer to device """ for param in optimizer.state.values(): if isinstance(param, torch.Tensor): param.data = param.data.to(device) if param._grad is not None: param._grad.d...
4a75e1103f01167c3683e9b34c72fa19cdac57e8
661,067
def append(base, suffix): """Append a suffix to a string""" return f"{base}{suffix}"
bca492f0a2ed44a670b0bf70132e2214e56bfd88
661,068
import textwrap def _wrap_text(text): """ Wrap text at given width using textwrap module. Indent should consist of spaces. Its length is deducted from wrap width to ensure exact wrapping. """ wrap_max = 80 indent = ' ' wrap_width = wrap_max - len(indent) return textwrap.fill(text, w...
1c8ad1401e229bec60eb7b82acecd72811689fc2
661,071
def read_txt_file(fname): """ read a txt file, each line is read as a separate element in the returned list""" return open(fname).read().splitlines()
af0be81903c6ffa8a574b8e33b842e62ae4a5bc8
661,074
def RK4(f, y_i, t_i, dt): """Performs Runge-Kutta integration. Parameters ---------- f : callable Derivative function. y_i : ndarray Current state. t_i : float Current time. dt : float Time step. Returns ------- y_j : ndarray State at ...
e4834cae4236725f117786620aa797b9cdc2a963
661,076
import requests from bs4 import BeautifulSoup def scrape_url(url): """ Scrap the content from the input URL using Beautiful Soup. """ # Retrieve the data using a request r = requests.get(url) # Get the content in HTML format html = r.text # Parse the HTML file with BS4 soup = Be...
1ea4f7b035d1c185013a2cb217ac519c758a9189
661,078
import random def random_num_generator(length, repeatable=False): """ Generate a number in specific length. If repeatable is true, the number in different position can be the same one. :type length: int :param length: the length of the number :type repeatable: boolean :param repeatable: ...
136d8c0d7d9c9b8159b32fcb7abb174b8babbcb4
661,080
import math def calculate_open_channel_flow(channel, water_level_outside, water_level_inside): """ This functions calculates discharge past a barrier in case it is connected through an open channel :param channel: connecting body of water between outside water level and inside water level :param wate...
848385075ea5cf914864426e516999def4d71c7f
661,081
def get_label_mapped_to_positive_belief(query_result): """Return a dictionary mapping each label_id to the probability of the label being True.""" return {label_id: belief[1] for label_id, belief in query_result.items()}
49d14b37318fa7b4d1a24ef135d1eaef7c2276a1
661,082
def load_sentences(file, skip_first=True, single_sentence=False): """ Loads sentences into process-friendly format for a given file path. Inputs ------------------- file - str or pathlib.Path. The file path which needs to be processed skip_first - bool. If True, skips the first line. sin...
7dc454ece4462d40f039f5ae14de2d711a6a582d
661,084
import base64 def base64url_decode(data): """ base64-decodes its input, using the modified URL-safe alphabet given in RFC 4648. """ return base64.b64decode(bytes(data, encoding='ASCII'), altchars='-_')
372792e910759dcd9516bb410712ad130ba9c276
661,086
import re def ends_with_blank_line(contents): """ Returns true if the given string ends with a line that is either empty or only composed of whitespace. """ return re.search('\n\s*\n\Z', contents) is not None
1426d3de0f04b2028cfc53cdd9b27e2be9c52859
661,090
def get_native_ranges(my_core, meshset, entity_types): """ Get a dictionary with MOAB ranges for each of the requested entity types inputs ------ my_core : a MOAB Core instance meshset : a MOAB meshset to query for the ranges of entities entity_types : a list of valid pyMOAB types to be...
5e4b0ff3838b11f3838de2dfe8b32828780327f1
661,091
def get_list_from_file(file_name): """read the lines from a file into a list""" with open(file_name, mode='r', encoding='utf-8') as f1: lst = f1.readlines() return lst
a7ac0fdeb6eae012962ba1e96fe390d1ddddfabc
661,093
def _coerce_field_name(field_name, field_index): """ Coerce a field_name (which may be a callable) to a string. """ if callable(field_name): if field_name.__name__ == '<lambda>': return 'lambda' + str(field_index) else: return field_name.__name__ return field_...
65d1b8c5d64627863de89295bdc4413f7bc443eb
661,094
def get_source_inputs(tensor, layer=None, node_index=None): """Returns the list of input tensors necessary to compute `tensor`. Output will always be a list of tensors (potentially with 1 element). Arguments: tensor: The tensor to start from. layer: Origin layer of the tensor. Will be de...
1c8f6eae98bf5325bdc653e125b514defa68c58c
661,095
from typing import List def compare_lists(local_list: List[str], remote_list: List[str]) -> List[str]: """ Comapre local and remote list of files and return the list of local files not stored in remote database. :param local_list: list of names of local files :param remote_list: list of names of remot...
405a9e7e47292fcb93e4fbf07d09aead3023a14c
661,096
def num_param_Gauss(d): """ count number of parameters for Gaussian d-dimension. input d [int] : dimension of data """ return 0.5 * d * (d + 3.0)
84a967bff81277ec8c391a5a504e3a8a6747a22a
661,100
def obtain_list_db_tickers(conn): """ query our Postgres database table 'symbol' for a list of all tickers in our symbol table args: conn: a Postgres DB connection object returns: list of tuples """ with conn: cur = conn.cursor() cur.execute("SELECT id, ticker FR...
7a6c59c56c6b1c2b15e19438f8c0e1053119c014
661,103
def update_dict_deep(original, new_values): """ Updates dict *in-place* recursively, adding new keys in depth instead of replacing key-value pairs on top levels like `dict.update()` does. Returns updated dict. """ for key in new_values: if key not in original: original[key] = new_values[key] elif isinstance...
f7fcac11f7745ee803ec4f66eb653b31deda657a
661,104
def get_int_with_default(val, default): """Atempts to comvert input to an int. Returns default if input is None or unable to convert to an int. """ if val is None: return default try: return int(val) except ValueError: pass return default
474b7b7d7c8b2ccd4966740aefbbcd5a5e3a956a
661,107
def limitaxis(c,maxc,minc=0): """ Limit value in axis. :param c: value :param maxc: max c value. :param minc: min c value. :return: limited c value c E [minc,maxc] """ if c > maxc: c = maxc if c < minc: c = minc return c
d02715f22515ccb3d3e8848bde8d0665b72e7531
661,108
def _get_cache_value(key): """ Returns a value for a cache key, or None """ address = None try: with open(key) as f: address = f.read() except FileNotFoundError: address = None return address
fccea8e21f8a8bb456d4a45f3f38a5434888b911
661,109
import random import string def RandomString(length): """Returns a randomly generated string of ascii letters. Args: length: The length for the returned string. Returns: A random ascii letters string. """ return ''.join([random.choice(string.ascii_letters) for unused_i in range(l...
65c6a198887dd7a2916206370201b136f47bfbba
661,110
def generate_fake_oco_status(random_state, size): """ Generate random OCO status, mostly assigned to 200 with some 300 status codes during a random range between 4 and 50 ticks """ values = [200] * size picked_error_values_indexes = random_state.choice( size, round(0.001 * len(values)), ...
3dc056b2f08dd33de9ed2e5736fd2998fb3d14ff
661,115
def is_superset(obj1, obj2, path=""): """ Checks whether obj1 is a superset of obj2. Parameter *obj1*: Superset object Parameter *obj2*: Subset object Parameter *path*: Should be "" in initial call Return value: Returns a tuple with 2 arguments. The first argument is a boolean which is true, if o...
01f062e3df86eb51730ecbb25f654299fb9c767d
661,125
def get_file_and_head(filename, n_head=5): """Get the contents of a file, and the head. Parameters ---------- filename: str The name of the file to read. n_head: int The number of lines to include in the head. """ with open(filename, "r") as fp: content = fp.read() ...
034b6fda7c977ff97ed62644835a0250b030b226
661,127