content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import re def remove_space(text): """ remove extra spaces and ending space if any """ text = re.sub('\s+', ' ', text) text = re.sub('\s+$', '', text) return text
18e27fb568d02575e9fb177878c4e054fc2ac116
620,723
def is_leap(year: int) -> bool: """ Tests if the year is leap. :param year: int. Year to be tested. :return: bool. If the year is leap. """ if (year % 4) == 0: if (year % 100) == 0: return bool((year % 400) == 0) return True return False
62ace2a3701fb402e8e31684b2b7d2ef2fd983b0
620,724
def file_create(path, content): """ Create a new file at the given absolute path with the given content """ with open(path, 'w') as file_conf: file_conf.write(content) return path return False
6d66c8c98b20ca5e59ccc23224310ebbdcea53b4
620,726
def value_to_bit_matrix(a, s=(8, 8)): """ convert a from n-bit wide value to s[0] x s[1] bit matrix""" bit_matrix = [[0] * s[1] for i in range(s[0])] for i in range(s[0]): for j in range(s[1]): index = j + i * s[0] bit = (a & (1 << index)) >> index bit_mat...
5f096dee912c669300e2182230d614ae5cb4b0c7
620,729
def BDEUnlockVolume(bde_volume, path_spec, key_chain): """Unlocks a BDE volume using the path specification. Args: bde_volume (pybde.volume): BDE volume. path_spec (PathSpec): path specification. key_chain (KeyChain): key chain. Returns: bool: True if the volume is unlocked, False otherwise. "...
8253bf8e2061f3af833e2760d99dfc48f1f016cf
620,731
def parse_rdp_assignment(line): """Returns a list of assigned taxa from an RDP classification line """ toks = line.strip().split('\t') seq_id = toks.pop(0) direction = toks.pop(0) if ((len(toks) % 3) != 0): raise ValueError( "Expected assignments in a repeating series of (ran...
aa7bf1ae5d26b32f01e7a94a7c38f281868a72d0
620,736
def clean_link_text(link_text): """ The link text sometimes contains new lines, or extrananeous spaces, we remove them here. """ return link_text.strip().replace('\n', '').replace('\r', '')
09de717a280c26cb3d272fd40dcdbe8091a5a002
620,738
def get_entry(folder): """Find the name of the proof in the proof Makefile.""" with open('{}/Makefile'.format(folder)) as makefile: for line in makefile: if line.strip().lower().startswith('entry'): return line[line.find('=')+1:].strip() if line.strip().lower().s...
b43de9d51758c0d1dde179599033a7b8bde899ab
620,739
import pathlib def chromium_third_party_googletest_repo_path( chromium_verifier_repo: pathlib.Path) -> pathlib.Path: """Returns the path of third_party/googletest in chromium repo""" return chromium_verifier_repo / 'third_party' / 'googletest' / 'src'
1f55a54a4708c03c7129e5a1c7178c6ef5aa5567
620,740
def get_dict_info(dictionary, info_to_get): """Returns list containing data from given dictionary.""" return [dictionary.get(info) for info in info_to_get]
72269a8c0eb64394029609d5ea127514b54e4bf6
620,743
import csv def get_version_groups(csv_dir, pkm_versions): """Get the groups that classify games versions. Args: csv_dir (pathlib.Path): Path to csv directory. pkm_versions (list): List of dict containing infos to build pokediadb.models.Versionobject. Returns list: Ret...
0992e0ccf80dc599bdd5b3f8a3b630c2ba6becf5
620,751
import random import string def get_random_string(length:int) -> str: """Creates a random string from ascii letter characters""" return ''.join(random.choice(string.ascii_letters) for x in range(length))
adc8f78de1313d7bbf0353aa00ed637d14f5043e
620,752
def depends_directly_on(dependencies): """Takes a dependency dictionary d and "inverts" it so that d[section] will return the other sections which depend directly on that section""" depends_on = {s: set() for s in dependencies.keys()} for s, dependencies in dependencies.items(): for dep in depe...
b511ecc822e9c2a40ec5edd3bc744db3407864d9
620,754
def is_supported_cloud(cloud_type): """Checks if the given cloud is a supported cloud.""" supported_clouds = ['alibaba', 'aws', 'azure', 'gce'] return cloud_type in supported_clouds
1037a825f8df664e20f8d0bcc2adcb29419f95fb
620,756
def _nonnull_dict(**kwargs): """Returns a dict containing all kwargs except thouse having a None value. """ return {key: value for key, value in kwargs.items() if value is not None}
0efc5f7b8ad50144784b27eeb534c1db1bfcab82
620,758
def double_stuff (things) : """ Returns a new list with doubl ethe values than the previous list """ # accum list new_list = [] # iterate over each item in the prev list for thing in things : # double each item new_elem = thing * 2 # add to the new list new_list.app...
df0359924c16e8a7404ebc0caef7f10db6e5e1cf
620,759
import string import random def id_generator(size=6, chars=string.ascii_uppercase + string.digits): """ Generates a random string. :param size: Length of random string. :type size: Int :param chars: Charectors used for random string generation. :type chars: String :return: String, random strin...
3ac1b7650b7bfffa3bcf72408d7c4cf392642a52
620,761
def create_file(filename): """ Create a file with write rights and UTF-8 encoding Args: param1 (string): Filename Returns: Return a file object """ return open(filename, mode="w", encoding="utf-8")
6842b737f94c8adb3f0052766f8f44772ee175f3
620,764
import itertools def get_subsets(item_set, size): """Gets all the subsets of given size that can be formed from the itemset Args: item_set ((int, ...)): Set of items. size (int): Returns: [(int,...), ...] All subsets of size `size` """ return itertools.combinations(item_s...
1f7093309338d6fbd125f0861fadd7107f1bca8f
620,765
def dequantize(x, scale_factor, num_levels=255): """ Reverse operation of quantize_to_int Parameters: - x: np.array(dtype=int), quantized vector in integer representation - scale factor: float input will be mapped to this range - num_levels: int: number of quantization levels, must be odd ...
eae2722c2969597c9b949ab7d94177b9a399510c
620,768
def full_shape(dim, shape, fill): """Returns a shape of at least dim dimensions""" return ([fill] * (dim - len(shape))) + shape
0883651dccb2f5ca6adddd0fba8445d84e1ad32d
620,771
def make_normal_initializer(mean, std): """make normal initializer param of make_table_options Args: mean (float): A python scalar. Mean of the random values to generate. std (float): A python scalar. Standard deviation of the random values to generate. Returns: dict: initializer p...
f51b8037363217528bf1033c54e989b143c8e15c
620,774
def capitalize(s: str) -> str: """Capitalize the first character of a string.""" if s == '': return '' else: return s[0].upper() + s[1:]
224ff2568f65e66adea2269bfd89822efedaf510
620,775
import asyncio import random async def task_coro(pid): """Coroutine non-deterministic task""" await asyncio.sleep(random.randint(0, 2) * 0.1) print('Task %s done' % pid) return random.choice([True, False, False, False, False, False, False, False, False, False, False, False])
f88861797c5d36608b7d2ff7a4ccf79e64132062
620,779
def is_job_config(config): """ Check whether given dict of config is job config """ try: # Every job has name if config['config']['job']['name'] is not None: return True except KeyError: return False except TypeError: return False except IndexError...
6efa08f0c3cb7bd531fe9cb8f4784aeed4efeb0b
620,780
import re def select_structs(innerclass_list): """Select structures from innerclass list. Args: innerclass_list: raw list with unions and structures extracted from Dogygen's xml file. Returns: Doxygen directives with structures selected from the list. Not...
844156fb1b3eddfcb81affb59e8e6d9911c93483
620,782
from typing import Type def is_dataclass(type_: Type) -> bool: """ Check whether a type is a dataclass :param type_: the type to check """ return hasattr(type_, '__dataclass_fields__')
37fb7058e126028cf75d0e8802d6866df09920db
620,784
import requests import json def get_routes(switchuser, switchpassword, url): """ Here's a function that takes in a common set of information, does one thing and then returns the result. :param switchuser: A string that contains the username to access the device :param switchpassword: A string that co...
a6537efb06677315349ec3fcac2363783ed7d6a1
620,787
def _find_neighbors_relations(node, relations, nodes): """ Find all neighbors and relation for this node. :param node: the node we search the neighbors and relations for :param relations: a list of all relations :param nodes: a list of all nodes :return: a pair (neighbors, relations) """ ...
d6ac3da97069ccf7906cfc3fa317c178ed655b14
620,788
def _x_proto_matcher(art): """ Is this artifact the x.proto file? """ return art['name'].endswith('.proto')
0bc7e19c91fcc95bf6a3f7ee411386dcdd81f004
620,789
def get_allegation_data(document): """ Parse an lxml document for allegations and return a list. :param document: :return: """ # Setup return structure allegation_list = [] try: # Find element and parse <li>s allegation_div = document.find_class("view-allegations").pop(...
8ccad0ef00e7613f6d6ff3fd3c64f52fb7828883
620,790
def json_headers(app): """JSON headers.""" return [ ('Content-Type', 'application/json'), ('Accept', 'application/json'), ]
29dc0c8f54fa80e9b8f033c0a1a6d9f414fdc8f4
620,791
def icon_name(resolution): """Create file name from image resolution. Args: resolution (str): resolution of the image. Returns: icon_name (str): File name of an icon for .iconset. """ return 'icon_' + resolution + '.png'
f8fbf3df79e9c65af1078f11a39912b257978ade
620,794
import operator import itertools def listadvanced_bool(lst, barr, bnot=False): """Advanced list indexing: boolean array Args: lst(list): barr(array or bool): array of booleans Returns: list """ if bnot: barr = map(operator.not_, barr) return list(itertools.comp...
1f0e00927f47d3b40ce43030a2d6e8560d706f29
620,796
def lerp(min, max, rat): """ Interpolate between `min` and `max` with the 0-1 ratio `rat`. """ return min+(max-min)*rat
a92697f59758f9842a7c6ca70cdbcbc5bd98163f
620,797
def apply_nd(fn, input): """ Apply fn whose output only depends on the last dimension values to an arbitrary n-dimensional input. It flattens dimensions except the last one, applies fn, and then restores the original size. """ x_size = input.size() x_flat = input.view(-1, x_size[-1]) ...
9508dfaf864f51a13ccb3f2d946ff3349ad9a4d4
620,799
import math def calculate_distance(p1, p2): """ Calculate euclidian distance between two points. """ x1, y1, z1 = p1 x2, y2, z2 = p2 return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2)
75b01e25e9cd6b45459ef5c53e776e4ed74184de
620,801
def get_download_total(rows): """Return the total downloads, and the downloads column""" headers = rows.pop(0) index = headers.index('download_count') total_downloads = sum(int(row[index]) for row in rows) rows.insert(0, headers) return total_downloads, index
7b3f4ef0acba2a26b7531a0c32c6d10d46d56ef3
620,802
import statistics def calculate_altitudes_and_speeds(positions, altunits='M'): """ calculate the highest, fastest and lowest values for speed and altitude Args: positions(list): list of dicts, each dict is a position report altunits(str): altitude units, default is metres (M) Returns...
505dbccb561c9b43a925c5f63e8f21f8e8657a1f
620,808
def transform_users(response_objects): """ Strips list of API response objects to return list of group objects only :param response_objects: :return: list of dictionary objects as defined in /docs/schema/gsuite.md """ users = [] for response_object in response_objects: for user in respo...
940bbf3c46bff21e7db71e55163d69ef13c4123d
620,809
import json def GetErrorMessage(stdout): """Extract a message field from JSON output if present.""" try: return json.loads(stdout)['message'] except (ValueError, KeyError): return stdout
54656974a891e7c7eefc03ae8fb8b200907b123c
620,810
def add_attrs(widget_or_field, attrs, is_replace=True): """Add attributes from attrs to widget_or_field :param widget_or_field: object it can be a widget, field :param attrs: dict name, value map that contains all the attributes want to be added :param is_replace: whether replace the origin value,...
92263e6195eda557a1180975a664fcf7aed139e5
620,811
def save_csvs(csm, tables_rows): """ write relational tables to csv files. tables_rows -- dict {table_name: [rows]} of tables of rows to save""" written = {} for table_name in tables_rows: written[table_name] = csm.write_csv(table_name, tables_rows[tab...
8a059a0331d7668bcd593521a5b1e6a406b2d251
620,813
from pathlib import Path def get_image_path(instance, filename): """ callable to define the image upload path according to the type of object: segment, route, etc.. as well as the id of the object. """ return Path("images", instance.__class__.__name__, str(instance.id), filename)
e1d632ea13d779b3a5169be8257b23772061eb3d
620,815
def FilterInstances(instances, service=None, version=None, instance=None): """Filter a list of App Engine instances. Args: instances: list of AppEngineInstance, all App Engine instances service: str, the name of the service to filter by or None to match all services version: str, the name of the ...
05ff001449ac6968c92d68caee922b384b74d656
620,816
def dict_remove_key_safe(d, key, default=None): """ removes a key from dict __WITHOUT__ side effects Returns: - copy of dict, without key - value (if it was there) """ d = d.copy() value = d.pop(key, default) return (d, value)
6453bdc22b4c156bc2ebf85119f3cd8cf2c1d03f
620,818
def build_output_type_set(output_type_list, config): """Builds set of output types. Args: output_type_list: list, possible output image types. config: dict, user passed parameters. Returns: Set of requested output image types. """ output_types = set() for output_type in...
f8fddb6c2b536185afac2f06002c0c6fb45d5d29
620,819
def get_valid_example_ids(example_ids, global_ids, incremental = None): """func({example_ids}, {global_ids}, bool) -> [valid_identifiers] Compares the dictionary of a source example with all its possible identifiers against the dictionary with all the available documentation identifiers and returns a filte...
381b20e463e58772ba8ed2c00c1b214499e4c57d
620,823
import json def jsonify(v, indent=2, sort_keys=True): """Turns python object `v` into a pretty printed JSON string Parameters ---------- v : object * python object to convert to JSON indent : int, 2 * number of spaces to indent JSON string when pretty printing sort_keys : bo...
2da6b7ccfdc46504ab0647d1ae8f7e53b3cef51f
620,825
def binarize(a, a_bin, M): """Generates binarization constraints for variable a. Parameters ---------- a : str Variable to be binarized. a_bin : str Identifier of the binarized variable. M : int An upper bound on a. Returns ------- List[str] A list h...
df910c1c36d7d84ff73b6e5257196db880ec27ea
620,827
def interpolate_colors(a, b, bias): """takes two RGB tuples and returns a componentwise weighted average""" return ( int(a[0] * (1 - bias) + b[0] * bias), int(a[1] * (1 - bias) + b[1] * bias), int(a[2] * (1 - bias) + b[2] * bias), )
6b48f7ce449b650d3d390a5117fc478e7819c908
620,828
def cluster_info(c, attr=None): """Display info of subgraphs in a VertexClustering""" return {'modularity': c.modularity, 'n': len(c.sizes())}
2c383a8ba7901b153e01f2f08d80b3dfb61463d7
620,829
def get_separation_score(results): """ For a Solr response, compute the separation score which is derived from the ratio between the two first Solr scores. """ score1 = results[0]['score'] score2 = results[1]['score'] return (1 - score2 / score1)
1fc53bb05eb012d15ea1abb26838e2c4a6c04847
620,831
def rm_spaces(filename): """ Replaces all spaces with underscores in a filename. """ return filename.replace(' ', '_')
1a63771250d9076e9a6120dc7a4451c0aa4dbe3c
620,834
def apply_backward_euler(Delta_t, u): """ Apply the backward Euler (fully implicit, first order) time discretization method. """ u_t = (u[0] - u[1])/Delta_t return u_t
09b5a93fc47bcd211086b944cccd2616ea96b1c9
620,836
def heads(token): """ Return the heads of a token, from the root down to immediate head :param token: spacy token :return: the heads of the token """ hs = [] while token is not token.head: token = token.head hs.append(token) return hs[::-1]
30d4877f47c333c54cf6f713efd1da107defeb7b
620,839
def input_format(line): """ Converts a string into a list of vertices and a point Receive an entry with this format with this format '1 1, 3 2, 1 4, 3 4 | 3 3 ' Returns: list = [(1,1), (3,2), (1,4), (3,4)] and a point = (3,3) :param line: :return: list, point """ line_strip = li...
61c6ec5bc6e655ee193f63de286e64727220d2cf
620,840
def base_loss_name_normalizer(name: str) -> str: """Normalize the class name of a base BaseLoss.""" return name.lower().replace('loss', '')
aac3a89f224b1df791c21bd5b12bd2fd8856a6af
620,841
def unique_hosts_count(rdd): """ Return the number of unique origin hosts return type: int """ unique_hosts = rdd.map(lambda line: line.split(' ')[0]) return unique_hosts.distinct().count()
ca88f95f2ad5dadcd89ed7e9dca81ff371430a4c
620,843
def deleteAllInUsed(total, used): """ Return the list "total" after removing all appearances of elements in "used". Parameters ---------- total : list-like of any The original list from which we want to remove some elements. used : iterable of any The elements we want to remove ...
4adfdd8cebcd84aa550dfb31e25d54e241b1794d
620,846
def requirements_satisfied(items_counter, requirements): """ Checks if items in requirements are present in basket (items_counter) Args: items_counter (collections.Counter): items in basket with number of occurrences requirements (collections.Counter): items and quantity require...
ad9f0cf06b1c37ecebd6648dfccfa28556fe7c5d
620,850
def slash_join(*args): """ Joins together strings and guarantees there is only one '/' in between the each string joined. Double slashes ('//') are assumed to be intentional and are not deduplicated. """ def rmslash(path): path = path[1:] if len(path) > 0 and path[0] == "/" else path ...
2963432bacc74817bc4570e94c31af32b2af4b49
620,855
def get_estimated_max_weight(weight, num_reps): """Returns the estimated max weight based on weight and reps.""" estimated_max = weight * (1 + num_reps / 30.0) return float("{0:.2f}".format(estimated_max))
28a608ee34173b66008f2ba2d7a761ca7b758739
620,857
def unescape_bytes(bytestr): """ Returns a variant of the given bytestring that has C escapes replaced with their ASCII values. >>> unescape_bytes(b'\\0') b'\x00' """ return bytestr.decode('unicode_escape')
a628b9433c409d5180a793c266ba48774239ee41
620,859
def sort_dict(d, reverse=False): """ Return sorted dict; optionally reverse sort. """ return dict(sorted(d.items(), key=lambda x: x[1], reverse=reverse))
a9ba36609f52e3ce3acc38ef7001a3ff90797475
620,860
def remove_duplicates(input_features): """ Remove duplicate entries from layer list. :param input_features: A list of layers :return: Returns a list of unique feature tensors (i.e. no duplication). """ feature_name_set = set() non_duplicate_feature_set = [] for feature in input_features:...
4c422bdeb266dff86283a9588f0a987f7884af25
620,861
def _get_external_id(account_info): """Get external id from account info.""" if all(k in account_info for k in ('external_id', 'external_method')): return dict(id=account_info['external_id'], method=account_info['external_method']) return None
71fabd59f7c0ad21b8ced101ac8251b82f68d64f
620,864
def steps(distribution): """ Returns the steps of given distribution. Parameters ---------- distribution : array_like Distribution to retrieve the steps. Returns ------- tuple Distribution steps. Examples -------- Uniformly spaced variable: >>> y = np....
07cacc5b85b6ec779112893d5409ec18a21a88aa
620,870
def detectTextTwgoCancelled(frame): """Return an empty string if there is no cancelled message in this text TWGO frame. Otherwise return string with cancellation details. Args: frame (dict): Contains a text TWGO frame. Returns: (str): '' if there is no cancellation associated ...
f038395df54e566fc1afe710609a15760c166fd4
620,876
from typing import Dict from typing import List def check_entry_exists(session, entry: Dict, schema_name: str, table: str) -> List[int]: """Queries target database for a matching entry. Generates query dynamically according to the given metadata entry. A downside of this approach is that the index is not...
361722d69fd7d4dd0ebff06bda8c913b91cdeaea
620,877
def get_min_bbox(box_1, box_2): """Get the minimal bounding box around two boxes. Args: box_1: First box of coordinates (x1, y1, x2, y2). May be None. box_2: Second box of coordinates (x1, y1, x2, y2). May be None. """ if box_1 is None: return box_2 if box_2 is None: ...
de156295fdba98baf9db6cb4f83306dba130a7b3
620,878
import math def binomial(i, n): """Binomial coefficient""" return math.factorial(n) / float( math.factorial(i) * math.factorial(n - i))
8a13862ceea82c6f00797e953715ee38ec5440a2
620,879
import re def get_field(doc: str, name: str): """Parse ReST field from document :param str doc: string of whole document :param name: name of field excluding the surrounding `:` :return: value of field :rtype: str """ match = re.search(':{}: (.*)$'.format(name), doc, re.IGNORECASE | re.MU...
37f9de4340117c0da506a3f57be126a691b90b61
620,885
def extract_entities(openapi_str): """ Extract entities from an OpenAPI string, where entities are defines as anything within "```" :param openapi_str: The OpenAPI str :type openapi_str: ```str``` :return: Entities :rtype: ```List[str]``` """ entities, ticks, space, stack = [], 0, 0, [...
47f3b7ec9a9a282bcc90ca35669687e62fd031ea
620,889
def get_topics_by_datatype(bag): """ Get all the message types in the bag and their associated topics. @param bag: bag file @type bag: rosbag.Bag @return: mapping from message typename to list of topics @rtype: dict of str to list of str """ topics_by_datatype = {} for c in bag._g...
c1c0b92408f22a96f2127a757126b4d1e8f3f344
620,890
def find_new_news(excluding_seen_news, existing_news): """ Finds new news from the API that is not currently in the list """ # https://stackoverflow.com/questions/7271482/getting-a-list-of-values-from-a-list-of-dicts existing_news_titles = list(map(lambda d: d['title'], existing_news) ) return...
c4ed15e1d149ce5d1674d8631a51f6eeec2cddf9
620,891
def capitalize_string(s: str) -> str: """Capitalise all parts of a string divided by "_" or " " """ split = [] for part in s.split("_"): split.extend(part.split()) return " ".join([part.capitalize() for part in split])
2b2221295c2a9d2e04eba340f18f7bc3481bc728
620,895
def _check_keys_contain(result_keys, target_keys): """Check if all elements in target_keys is in result_keys.""" return set(target_keys).issubset(set(result_keys))
1e6df8a59db802bca1980908f533647c488e156d
620,897
def list(client, user_id, group_id): """Get security credentials of user.""" credentials = client.user.credentials.list( method="GET", userId=user_id, groupId=group_id ) return credentials
46d6f56f53ef902bc9f059679e7d50c7a9ffe949
620,898
def Duffing1D_Hamiltonian(t, u, PARAMETERS = [1, 1]): """ Returns Hamiltonian for the Duffing oscillator. PARAMETERS = [alpha, beta] Functional form: H = 1/2*p_x**2 - alpha*x**2 + beta*x**4), with u = (x, p_x). Parameters ---------- t : float Time. (This Hamiltonian is independent of ti...
e94d403e9a06dccaa50d2750ddbf933b717de43b
620,901
def identity(x, **kwargs): """ >>> identity('anything') 'anything' """ return x
33a30338a361b4c1dffbcf65ed0cc02df438b945
620,902
def bounding_box(bw, bh, w, h): """ Returns a tuple (new_width, new_height) which has the property that it fits within box_width and box_height and has (close to) the same aspect ratio as the original size """ new_width, new_height = w, h if bw and new_width > bw: new_width = bw ...
dda847591d75715a11476b9edd4316445807ba8d
620,906
def identity_filter(data): """Return data iterator without any processing""" return iter(data)
e8a35ffb44138087a8e14d0359ec2a25a4233c80
620,908
def __get_page_component_classname_from_page_data(page_data): """Return a generated page component classname from json page data.""" return "{}{}".format(page_data["style"].capitalize(), str(page_data["id"]).zfill(2))
f18ac5ac0d2303d65b58269af6b2e7bb91204901
620,910
def remove_job_if_exists(update,context,name): """Remove job with given name. Returns whether job was removed.""" current_jobs = context.job_queue.get_jobs_by_name(name) if not current_jobs: return False for job in current_jobs: job.schedule_removal() return True
a903e39ba8d1e6c4b808a0774835a2aa75159e7a
620,911
def try_strftime(x, *args, **kwargs): """Try strftime. In case of failure, return an empty string""" try: return x.strftime(*args, **kwargs) except: return ''
87bdbc9e61003c4af90608b0e46e084b2e81ef1a
620,914
import uuid def get_exec_path(model, model_size, batch_size, batches_per_step, filenames, use_generated_data, use_tmp_execs): """ Return the path to compiled graph based on model parameters or random name if that was requested by setting an option. """ if use_tmp_execs: r...
d8779693bde98716f8490f4ab38d7bcac9a266f2
620,918
from typing import List def serial_order_to_spatial(hole_sequence: List[int], seq_positions: List[int]) -> List[int]: """ Converts a first-phase hole sequence and a list of serial order positions (at the choice phase) into a list of spatial holes at test. Args: hol...
23a8c158ba0821ea2960091d4b9fa8974f368249
620,919
def is_constructed(val): """Check if a tag represents a "constructed" value, i.e. another TLV""" return val & 0b00100000 == 0b00100000
ba186716595c1741a03b7e041fac7fde76399f3f
620,920
def TableResourceToReference(bigquery_messages, resource): """Converts a Resource for a table to a TableReference message. Args: bigquery_messages: The messages module for the Bigquery API. resource: the Resource Returns: the message """ return bigquery_messages.TableReference( projectId=r...
e37ed269d5c37af53e0633fe722005371ff4065d
620,923
def answer_yn(question=None): """Prints a simple yes or no question and returns bool""" while True: answer = input(question or 'Are you sure? Y/n').lower() if answer == '' or answer == 'y' or answer == 'yes': return True elif answer == 'n' or answer == 'no': retur...
a35d55101e72608de635e13e34edb90a73ba6696
620,924
def is_variant(call): """Check if a variant position qualifies as a variant""" if call == 1 or call == 3: return True else: return False
b09bda05a58aec66a8be56896c6a7e1da70642ee
620,925
def sort_categories(a, b, categories_list): """Sorts a list of dictionaries with category keys according to their value and order in the categories_list. If not found, alphabetic order is used. """ index_a = categories_list.index(a["category"]) index_b = categories_list.index(b["category"]) ...
7109644135660f02c61215560afae1902c86dda1
620,928
def gen_isempty(gen): """ Returns an identical generator and False if it has at least one value, True if it's empty :param gen: generator, any generator :return: (generator, Boolean), returns the same generator, and True if empty, False if not """ try: item = next(gen) def my_generator(): yield item yi...
249904ed1a1fb6caa473f9e70cad518d6508b84d
620,932
from typing import Any import json def json_load(obj: str, error: bool = True, **kwargs) -> Any: """Deserialize a json str into an object. Args: obj: str to deserialize into obj error: if json error happens, raise it **kwargs: passed to :func:`json.loads` """ try: retu...
bd64e1407597c82ee9ba1b9d7d65bb75697ba3ed
620,934
def rule2columns(rule,lhs,rhs,history,grammar,automaton,w,run,begin=0,end=None): """ Given a rule and a bunch of info about run, windows, grammar, etc, builds a dict for a dataframe for the rule Dataframe includes how rule probability changed during training, for each run of Windows for each t...
3115628a580ec178d96ff2e5ff77301fcf38d26d
620,936
def logging_lvl_to_kaldi_lvl(lvl: int) -> int: """Convert logging level to kaldi level""" if lvl >= 10: lvl = max(-3, (lvl - 20) // -10) else: lvl = 11 - lvl return lvl
49063875491479b1c986d58e97781c83d4a74b2c
620,937
import requests def retrieve_episode_html(url): """Retrieve the HTML for the given episode playlist URL.""" response = requests.get(url) return response.content
6d6beb106cf036c133ed5e056cba1b161d42a844
620,938
def max2(a, b): """ Wrapper around the max built-in that is robust to None. """ if a and not b: return a elif b and not a: return b else: return max(a, b)
9b1c76e9ba5949712f813bea0eaf82cfe4c36f7f
620,941
import re def string_to_color(s): """ Converts color string to tuple. '10,20,30' - (10,20,30) Returns None when error. """ m = re.match(r"(0|[1-9][0-9]{0,2}),(0|[1-9][0-9]{0,2}),(0|[1-9][0-9]{0,2})", s) if not m: return None a = map(int, m.groups()) if any(map(lambda v: v >...
325b759c6ca1c93526b9f1afa1b12779b5ea7feb
620,949