content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def format_geometry(rect): """Format a geometry as a X11 geometry specification""" w = rect.width() h = rect.height() x = rect.x() y = rect.y() return f"{w}x{h}{x:+d}{y:+d}"
62156c7c2ff0339477f48181c1cd278471b3a2c2
569,938
from typing import Tuple from typing import List def get_all_optimisation_params(config: dict) -> Tuple[List[float], List[int]]: """Get all coverage distances (thetas) and numbers of sensors to create optimised networks for. Parameters ---------- config : dict Parameters as loaded by util...
029bdb43affe50d8b70acc25801b28dccfa90882
569,939
def is_cpp(file): """ Returns True if file looks like a C++ file (header of .cpp) """ # return "cpp" == file.split(".")[-1] return file.split(".")[-1] in ["cpp", "cc", "c"]
1eeb77f1e0cff85c671340d92860854331034bc8
569,940
def is_asteroid_complex(tensor, dim: int = -2): """Check if tensor is complex-like in a given dimension. Args: tensor (torch.Tensor): tensor to be checked. dim(int): the frequency (or equivalent) dimension along which real and imaginary values are concatenated. Returns: ...
ed08c8c07d91a1251885a32b74306f08d4509eb8
569,941
def width(region): """ Get the width of a region. :param region: a tuple representing the region with chromosome, start, end as the first 3 columns :return: an int """ return region[2] - region[1]
95c3fbbe0bc4fc69f7092608885fdb515b9f43b1
569,943
import pickle def deserialise_from(path): """ Deserialises a pickleable object from a file. :param path: a str - the path of the file. :returns: the deserialised Python object. """ with open(path, "rb") as file: return pickle.load(file)
934013f6ee98c45ae6bfc46a972a65c3180fcd4a
569,944
import re def _remove_leading_indent(content): """ Remove leading indent from a block of text. Used when generating descriptions from docstrings. """ whitespace_counts = [len(line) - len(line.lstrip(' ')) for line in content.splitlines()[1:] if line.lstrip()] # uninde...
924100026b1ed67e4944dddbd517331acaa3a70f
569,945
import math def cost_default_edge_weight(_: float) -> float: """ For a cost default, we assume the edge does not exist: this results in a cost of positive infinity. """ return math.inf
5ad762e12e8bc163c17dd2a8cc024ec8b71a0d4d
569,948
import time def current_milli_time() -> int: """ Simulate Java.lang.System.currentTimeMillis() Method :return: The current time in milliseconds :rtype: int """ return round(time.time() * 1000)
773b3ae85de679b397a860a6999dbeaf530fcfb9
569,950
def is_even(number): """ Return True if a number is even, False if odd. """ return not number % 2
d7a5ec32b18683bef19a8c2a361efe5fbd4b00ec
569,952
def bin_to_hex(bin_str: str, width: int = 8) -> str: """Converts binary string to hex string Parameters ---------- bin_str : str binary string to convert width : int, optional width of hex output (used for zero padding), default=8 Returns ------- str hexadecima...
658607596eb9a6c78714f5cca8cc0b0911260953
569,953
import inspect def get_valid_instance_from_class(obj_or_class, valid_class_types=None, *instance_args, **instance_kwargs): """ 2-Step function to instantiate/validate a given parameter. First step: check if `obj_or_class` is a class or an instance. If it is a class, create a new instance of that clas...
288e8d7fbb3964f2f344ad146379271e9f9e2b2c
569,955
def _compute_gaussian_zcdp(sigma: float, sum_sensitivity_square: float) -> float: """Computes zCDP of Gaussian mechanism.""" return sum_sensitivity_square / (2 * sigma**2)
ee57f6ed84761dfb17685f687df3b175f6ef92d6
569,957
def TTD_TTDS_rule(M, i, j, w, t): """ Coordinate TourTypeDayShift and TourTypeDay variables for each day of each week :param M: Model :param i: window :param j: day :param w: week :param t: tour type :return: Constraint rule """ return sum(M.TourTypeDayShift[i, t, k, j, w] ...
a7e03543d2ca4e782ca4b12e136eeb65c6968efb
569,959
def get_task_runs(task, task_run_json, unique=True): """ Search through items from task_run.json to find matching objects for input task :param task: input task object :type task: dict :param task_run_json: task_run.json converted to a JSON object via json.load() or common.load_json() :type ta...
fe9571a07b50aff80c26a50ef4f40098023a214f
569,963
def list_or_string(value): """ Converts the value into a list of strings. If the value is not iterable, a one-element list with stringified value will be returned. """ if isinstance(value, str): return [value] else: try: return list(value) except ValueError: ...
524ffd6263627d67570bb409e10db8ef2608206a
569,965
def get_list_b_nodes_without_area(city): """ Returns list of building node ids without area parameter. Requires osm call to generate city obejct, first! Parameters ---------- city : object City object generated with osm call Returns ------- list_missing_area : list (of ints...
c592054fc2283fa8ea490fb49f776484e313fcfa
569,966
def bit_to_ascii(bit_string: str) -> str: """ Converts a given string of bits to a string of ASCII characters. :param bit_string: a string of 0s and 1s, dividable by 8. :return: """ assert len(bit_string) % 8 == 0 n = int(bit_string, 2) result = n.to_bytes((n.bit_length() + 7) // 8, 'bi...
ad0230b2466e626c8c3027c6a256cf2b2020a77d
569,968
import uuid def generate_prefix_uuid(prefix, length=16): """ 创建一个带指定前缀的类有序uuid标识,最小长度8时,测试碰撞概率如下 Linux 3.10.0-693.17.1.el7.x86_64 length=8 100w碰撞0 length=8 1000w碰撞0 length=8 1500w碰撞0 :param prefix: 前缀 :type prefix: string :param length: 随机串长度 :type length: int :returns: U...
07b50fe64b7988ba042b4395f4a4adee3a490452
569,972
import tempfile def _tmpfile(content): """Returns the path to a temp file with the given contents.""" tmp = tempfile.mkstemp()[1] with open(tmp, 'w') as f: f.write(content) return tmp
2f6eb60a434293574af2dd77d69410d5dfea0faa
569,976
import re def get_sale_head(this_report): """Return the date of the livestock sale.""" report_head = this_report.find('div', id = 'txt_117') report_head = report_head.p.get_text() report_head = report_head.split('-') for string in report_head: if re.search(r'hd|head',string,re.IGNORECASE)...
83ad8b7f8cce95b25259497782f29e49e857efe8
569,984
from typing import Optional import torch def get_n_byte_tensor(n: int, device: Optional[torch.device] = None) -> torch.Tensor: """Returns a torch.int8 tensor of size n. Args: n: size of the tensor to allocate device: torch.device to allocate tensor on Returns: torch.int8 tensor o...
b1923b766ffdb7c82850f317bfc2c8755231ada0
569,985
def add_checked_summary(message, number_arrays, number_controllers): """ Adds ending summary information on how many arrays were checked""" message += " [%s array" % number_arrays if number_arrays != 1: message += "s" message += " checked on %s controller" % number_controllers if number_con...
166f286f042b745f1ce620d4335df65b36e23473
569,990
def mocked_fetch_public_keys_1(app): """Mock for the function fetch_public_key().""" return [{}]
6a51e54ac31dae64a73afeb61b51a32b5c976d9c
569,994
def n_rows_cols(pixel_index, block_size, rows_cols): """ Adjusts block size for the end of image rows and columns. Args: pixel_index (int): The current pixel row or column index. block_size (int): The image block size. rows_cols (int): The total number of rows or columns in the ima...
af602b470489f700ac5478f38d1aa9fd84b6104b
570,001
def match_bond_type(bt, t1, t2): """Compare bond type tuple bt to (t1,t2) and return True/False""" return (bt[0] == t1 and bt[1] == t2) or (bt[0] == t2 and bt[1] == t1)
ff602eaafb1165dda70023961dcc709650566f50
570,002
def simple_plotter(sim_array, plot_array): """ This function fills the plot array with values (0-1) for the coloring of the different chromaphores. For the simple case, the following is observed: White pixels are empty nodes ('S' in original paper, 0 in sim_array) Yellow pixels are xanthoph...
f4998d00bbb8dfe3bc0d7dbd4cb4842257f07fb7
570,008
import re def _naive_tokenize(s): """Tokenize a string, separating words, spaces and punctuations.""" # Spaces and punctuation marks are all retained, i.e. direct concatenation # of all the tokens in the sequence will be the original string. seq_tok = [tok for tok in re.split(r"([^a-zA-Z0-9])", s) if tok] r...
c251e72686c8f0372790607a4b22f20d1d003a98
570,012
def mesh_dual(mesh, cls=None): """Construct the dual of a mesh. Parameters ---------- mesh : Mesh A mesh object. cls : Mesh, optional [None] The type of the dual mesh. Defaults to the type of the provided mesh object. Returns ------- Mesh The dual mesh o...
8e9441bdecb55e86f7d522d582594e68e9f53365
570,014
def exc_log_str(exception) -> str: """ Format an exception as a "nice" one-liner string (does not include stack trace). """ return "{}: {!s}".format(type(exception).__name__, exception)
17fe59fd6610d913a694b64a181143446d933a63
570,016
def points_per_group(points, grouper_col, ct_col="Núm. Pts."): """Count the points in the given group Parameters ---------- points : pandas DataFrame Point observations grouper_col : str Column in `points` that you want to use to group, usually 'geo_field' or similar ct_col : st...
b8bd9804051ebaabf3413efb615e3c3c380a8b5a
570,017
def load_file_from_disk(filename): """Loads a file from disk""" with open(filename, "r") as handle: return handle.readlines()
9bdb695a9fd7b6568ce637e7e9e24368444529f5
570,023
def complete_home_staytime(mmprox, missing_seconds, minus_sleep=True): """ Add missing seconds to home patch staytime Input ----- mmprox: pandas DataFrame Mobility matrix with postal codes as indices and as column heads, and visit counts or visit lenghts as values missing_seconds: p...
3170877eaf1ff021ac7813d15236dfa2205b2d20
570,024
import re def Substitute_Dates(sentence): """ Substitutes all dates with special token. Formats taken from http://php.net/manual/en/datetime.formats.date.php """ daysuf = r"(st|nd|rd|th)" dd = r"([0-2]?[0-9]|3[01])" + daysuf + r"?" DD = r"(0[1-9]|[1-2][0-9]|3[01])" m = r"(january|february|march|april|may|june...
86fc62d846b49a90c93b50ad0d1690ef79602722
570,027
def argmax(array): """ Returns the index of the biggest element in array. """ return array.index(max(array))
94bceb72fb36a5bd4e6aafbe3eb8b75ec1833a79
570,028
def parse_seat(seat): """ Parse a string describing a seat in binary representation, and return a dictionary """ row = int(seat[0:7].replace("F", "0").replace("B", "1"), 2) column = int(seat[7:10].replace("L", "0").replace("R", "1"), 2) return {"row": row, "column": column, "seat_id": row * 8 + ...
cee056341fb94231fdf07c3b7dfd33ceb25c5681
570,029
import json def read_json(path_json): """ Read Json File :param path_json: path to json :returns mapping_json: json file contents as dict """ with open(path_json) as json_file: mapping_json = json.load(json_file) return mapping_json
169f46c8f51b61ea1320d02c64aafe241ae9eb76
570,030
def _idsfn(test): """ Return id for current example being tested """ return test.name
26c8317e5f5e47f277a25bb3a1f2c9640fb6d89d
570,031
def join_year_month(year, month): """Joins year and month for parsing with pd.to_datetime.""" return str(year) + '-' + str(month)
f401d4e6e37fb2aeaa1af492114546aeb30df87d
570,033
def add_hex_strings(input1: str, input2: str = "0") -> str: """Return sum of two hex strings. Args: input1 (str): Hex formatted string. input2 (str, optional): Hex formatted string. Defaults to "0". Returns: str: Hex string sum. """ if input1 is None: return "" ...
b29bc215cde0c2b2c26b35f36e00b8c232a58d5d
570,034
def get_crop_shape(dataset_name): """Returns cropping shape corresponding to dataset_name.""" if 'MPISintel' in dataset_name: return (384, 768) elif 'KITTI' in dataset_name: return (320, 896) else: raise ValueError('Unknown dataset name {}'.format(dataset_name))
18368554e9e4d8c6e3cc964df58b2abfe69d404b
570,036
import gzip def get_opener(filename): """ Auto gzip decoder. Returns an open filehandle in binary mode. """ # Can't rewind stdin. Assume plain text. if filename == '/dev/stdin': return open(filename, 'rb') with open(filename, 'rb') as f: if f.read(2) == b'\x1f\x8b': ...
0a9bd080c13829ae69176855d48a68cb2b81fc7b
570,042
def clip_line_poly(line, clip_poly): """Clip a line features by the provided polygon feature. Parameters ---------- line : GeoDataFrame The line features to be clipped. clip_poly : GeoDataFrame The polygon used to clip the line. Returns ------- clipped : GeoDataFrame ...
b12edd01488030174187dd91f208ca3db81aa3c0
570,047
def n_colors(graph): """The number of distinct colors used on vertices of 'graph'.""" return len(set([graph.node[i]['color'] for i in graph.nodes()]))
d4657511df82a4f9e0f56d418df736ebd9a3a57a
570,048
import asyncio def _default_task_factory(loop, coro): """Default function to create a new task.""" return asyncio.tasks.Task(coro, loop=loop)
fe490a02cfe24e84683850f4a93978480da72ec8
570,055
def index(fks, id): """Looks for the id on fks, fks is an array of arrays, each array has on [1] the id of the class in a dia diagram. When not present returns None, else it returns the position of the class with id on fks""" for i, j in fks.items(): if fks[i][1] == id: return i ...
233e625bbb4f3389ca4dce81f33d8824b5db9976
570,057
def is_relevant_asset(asset: dict): """ Returns if an asset is relevant for this process. For being relevant the asset name needs to contain "windows" or "linux" :param asset: The asset information as it is available in the samples directory. :type asset: dict :return: """ return "linux" in ...
de142fdcc0cb096899d5124a16a2cbd722879e2b
570,062
def set_show_layout_shift_regions(result: bool) -> dict: """Requests that backend shows layout shift regions Parameters ---------- result: bool True for showing layout shift regions """ return {"method": "Overlay.setShowLayoutShiftRegions", "params": {"result": result}}
0935bad907d315e89918408029193beb4b52c8a8
570,064
def _check_type(obj, type, range): """ Function to check the type of object and if the object is betwwen a range: obj (obj): the pobject to be checked type: the type of the object range: (list): the range (a list with 2 elements; min and max) of the which the number should be checked; eg: [0,1] ...
112a5128c67bfb7a7f5a29fd5a9d9ab625c6f411
570,065
import torch def coordinates_to_flow_field(coordinates): """ This function shift the coordinates to a flow field :param coordinates: tensor with size [h, w, 2], coordinates starts from 0 :return: a tensor that has the same size with coordinates, contain the flow filed. Values: x: -1, y: -1...
6eb6f69f27186dbc0c6a870c5e2ac07264253f35
570,067
def ping(request, value): """Helper function to simpliy test the API. Answers with the same value. Once API limitations are in place this method will continue to be "free" and as such suitable for connection checking. """ return dict(value=value)
4fb4dc8fd1f7b0545010e5696e7ba15f2ee988ff
570,069
import codecs def _as_unicode(s): """Turn byte string or unicode string into a unicode string (PRIVATE).""" if isinstance(s, str): return s # Assume it is a bytes string # Note ISO-8859-1 aka Latin-1 preserves first 256 chars return codecs.latin_1_decode(s)[0]
4670d72c71aeab92a503d3f95078fea743126f0d
570,071
import inspect from typing import Counter from functools import reduce def find_lowest_subclasses(candidates): """ This function takes a list of classes, and returns only the ones that are are not super classes of any others in the list. i.e. the ones that are at the bottom of the specified mro of cla...
9625ce4e5b610c94022454e55d3b163095448767
570,072
def pullCountryName(countryObj): """ Pull out the country name from a country id. If there's no "name" property in the object, returns null """ try: return(countryObj['name']) except: pass
20f772dc9c692aed85522607c9b266c2f9892210
570,076
import math def strsqrt(inputval): """Return the square root of the input as a string.""" return str(math.sqrt(inputval))
10d499cda6f37baa4868059dcad94785eb7174cd
570,079
import hashlib def hash_bytes(bytes): """Creates a MD5 hash of the 'bytes'""" md5 = hashlib.md5() md5.update(bytes) return md5.hexdigest()
d1c55981112b1b9f4341e6f3cbda2d18a9079d28
570,081
def get_external_stack_name(project_code, stack_name): """ Returns the name given to a stack in CloudFormation. :param project_code: The project code, as defined in config.yaml. :type project_code: str :param stack_name: The name of the stack. :type stack_name: str :returns: The name given ...
c6fbee846c95e89b017bf99ccf6fe103f04d713e
570,089
def instrument_neighbors(dframe): """Create lists of instrument neighbors. Parameters ---------- dframe : pd.DataFrame Dataframe of the sample index. Returns ------- neighbors : dict of lists Map of instrument keys to lists of related indexes. """ return {i: dframe[...
e57242f457846e639837637b20d2a5ee3d3e5989
570,091
import re def valid_cache_key(key: str) -> str: """ Sanitizes a cache key for memcached. """ return re.sub(r"\s+", "+", key)[:250]
85120bf834bdd57d9b5daf4a4fcc81a52320d455
570,092
def sanitize_name(name): """ Remove characters from names that IDA doesn't like :param name: Unsanitized name :return: Sanitized name """ name = name.replace('!', '_') name = name.replace('@', '_') return name
a1e74e7aa7a56ffac5dbf2c3130b94f736608623
570,093
import base64 def decode_base64(request, value): """Decodes base64url-encoded string""" encoded = value.encode('utf-8') # base64 expects binary string as input return base64.urlsafe_b64decode(encoded).decode('utf-8')
34b268249f90c7f640b216d9e3a11700d9293f71
570,098
def get_vert_opposites_per_edge(mesh_v, mesh_f): """Returns a dictionary from vertidx-pairs to opposites. For example, a key consist of [4,5)] meaning the edge between vertices 4 and 5, and a value might be [10,11] which are the indices of the vertices opposing this edge.""" result = {} for f in...
02abd44824ccd959f955cb96d8ca0de049dbe787
570,099
def get_players(string): """ Parses a string representing the number of other players (i.e. excluding the player) in the round. Currently supports only 1-9 other players. Returns a string in the correct form for the lookup table. Returns None if the input could not be parsed. """ if "nine" i...
834a2cd5210e6a08dc2bc45bb90503938985dc6d
570,103
def PC_AC1_calc(P, TOP, POP): """ Calculate Percent chance agreement for Gwet's AC1. :param P: number of actual positives per class :type P: dict :param TOP: number of positives in predict vector per class :type TOP: dict :param POP: population or total number of samples per class :type...
e91befedb3a366f258b6399badd99c29f2a52725
570,104
def parse(file_name, int_cols): """ Parses the CSV file specified by file_name and returns the data as a list of dictionaries where each row is represented by a dictionary that has keys for each column and value which is the entry for that column at that row. Also takes a list of column names t...
49c0f0e749ea804260cc747e8c714170f5401550
570,105
def get_w(height: int, aspect_ratio: float = 16 / 9, *, only_even: bool = True) -> int: """Calculates the width for a clip with the given height and aspect ratio. >>> get_w(720) 1280 >>> get_w(480) 854 :param height: Input height. :param aspect_ratio: Aspect ratio for the calculati...
7afc34e29244287db1fea4259416ebbbe3743233
570,107
def _dls(path: list, goal: str, depth: int): """ Return the depth limited search path from a subpath to the goal. Args: path: the current path of Nodes being taken goal: the label of the goal node depth: the depth in the graph to search Returns: the path if it exists, none othe...
112d703a0cb58b4ab0d054519d99b5dd00a5af87
570,109
def GetURLOfHotlist(cnxn, hotlist, user_service, url_for_token=False): """Determines the url to be used to access the given hotlist. Args: cnxn: connection to SQL database hotlist: the hotlist_pb user_service: interface to user data storage url_for_token: if true, url returned will use ...
e56b805728eb0d8d12f76a2b1961b5946029cd47
570,110
import re def get_multi_fields(pattern, o): """Extract multiple regex fields from a string.""" if isinstance(pattern, str): pattern = re.compile(pattern) m = pattern.search(o) if m: return m.groups() else: return None
79175ab4721f1f11d1330769f54ddc6dec6ee4a7
570,111
def filter_networks(networks, wanted): """ Return a list of desired Network objects. :param networks: list of Network dicts :param wanted: list of cidrs you want """ return [ n for n in networks if '%s/%s' % ( n['network_address'], n['prefix_length'] ...
cbb502f14f77adff50bf3017af8fa6444ef3de31
570,113
def checkListOfObjects(coord, pred): """ This method provides checking list of geojson objects such Multipoint or MultiLineString that each element of the list is valid geojson object. This is helpful method for IsValid. :param coord: List of coordinates :type coord: list :param pred: P...
4b3c3184f222c22db26f9fb8f6ce937f27815a28
570,116
def parse_file(file_name, res=False): """ Parses file and returns the positive instances for each query. :param file_name: Name of file to be parsed :return lists of lines [[qid, label, en_id, ...], ...], lines with null entities are separated """ null_lines = [] file_lines = [] efile =...
bcdc00fab0af192a24b39c186af72e3e0509c57b
570,117
def validate_tabular_choices(dep_var, cont_inputs, int_inputs): """ Checks to see if user choices are consistent with expectations Returns failure message if it fails, None otherwise. """ if dep_var in cont_inputs: return 'Dependent variable should not be continuous' if dep_var in int_in...
3d544e3c69b4f996c85b1bc8e65976fbccb2d932
570,119
def sysex(data): """Make sysex data.""" return [0xf0] + list(data) + [0xf7]
848bbc53cf2f0611d0c5449e6f7780fae04bc73f
570,121
from typing import List def to_string(objects: List[object], sep: str=", ") -> str: """ Converts a list of objects into a single string >>> to_string([1, 2, 3]) '1, 2, 3' """ return sep.join(map(str, objects))
6faa7a1156f5d3e3af006a09da5733b50e1f6a0f
570,122
def oxford_join(iterable, sep=", ", couple_sep=" and ", last_sep=", and ", quotes=False): """ Joins a list of string to a comma-separated sentence in a more english fashion than the builtin `.join()`. Examples: ```python from flashback.formatting import oxford_join oxford_join(...
0a1af3a211846225e84e2120c9974994f2fbefe9
570,123
from typing import List def create_query(users: List[str], include_retweets=False): """ Creates the query string for fetching tweets from a given list of users :param users: the list of users :param include_retweets: whether to include retweets or not :return: the query string """ return "...
d9cff20e172715eac48487298d6cb2d0870eaf9d
570,128
def a_record(query, ipaddr): """ Formats an A record using fields in 'query' and ipaddr, suitable for printing in a 'DATA' reply to pdns. Example: ndt.iupui.donar.measurement-lab.org IN A 60 -1 192.168.1.2\\n """ reply = "%(name)s\t" reply += "%(class)s\t" reply += "A\t" reply ...
1054af3028644e856b611757980365f7abb9742e
570,129
def __format_exposuretime_tuple(_time): """format ExposureTime tuple to short printable string fractions over or equal 1 second are marked with s, e.g. 8s fractions below 1 second are broken down to the divisor, this is a bit incorrect but short and common e.g. in cameras (and we want to have a shor...
6bae1c5224007ac6a0b8800fa2efc057b8673084
570,130
def is_top_author(s, tops): """Whether any member of `s` is member of `tops`.""" try: s = set([int(a) for a in s]) return int(len(s.intersection(tops)) > 0) except TypeError: return 0
af330fa4fdda89aaf661dadb66ba49d9bf20bcc5
570,133
def splitted(_set): """ Transforms a set {0,1,2} into a list of singletons [[0],[1],[2]]""" splitted = [] for el in _set: splitted.append([el]) return splitted
3868dff1463856697c32d5bf8970217bd06edcf2
570,135
import time def generate_snapshot_name(db_name, application_name): """Function to generate a snapshot name. Args: db_name (str): The name of the original db of the snapshot. application_name (str): The name of the application. Returns: str: The generated snapshot name in the fo...
6f8d465cb1dc4151191505bee21bf04342813eb1
570,136
def bytes_r(b): """Reverse a bytes-like object.""" return bytes(reversed(b))
c2adaa08f0b72385a5c2366eae468d5d3ef793bf
570,138
def get_precip_data(cell): """ Parse a precip data cell. """ tc = [s.strip() for s in cell.itertext()] for i, t in enumerate(tc): if t in {'---', ''}: tc[i] = float('nan') elif t.endswith('%'): tc[i] = float(t[:-1]) else: tc[i] = float(t) ...
3a2deed17ad45ac752937dd6c03837d6bd395375
570,140
def totalcost(endclasses): """ Tabulates the total expected cost of given endlcasses from a run. Parameters ---------- endclasses : dict Dictionary of end-state classifications with 'expected cost' attributes Returns ------- totalcost : Float The total expected cost of ...
0ddffda6ee537d9f5159ad722ffb4925df39e035
570,142
def isolate_dates(data, sdt, edt): """ Isolate data in specified date range :arg data: the data to be subsetted. Has a column named 'date' :type data: pandas dataframe :arg sdt: the start date of the subset :type sdt: datetime object :arg edt: the end date of the subset :type edt: datetim...
54aef443cbf13704fc8f26e38d06b563cd38e67a
570,145
def get_fraction(dist, r_max, diameter): """Compute what fraction of a point of the provided diameter at distance dist is contained in a sphere of radius r_max.""" if dist < r_max - diameter / 2: return 1 if dist > r_max + diameter / 2: return 0 else: return -dist / diameter ...
e6878dcf808a095bd99dcd814a850048f91b2252
570,151
def is_valid_iyr(issue_year): """Checks for valid Issue Year.""" if issue_year.isdigit() and (2010 <= int(issue_year) <= 2020): return True else: return False
52801fb697e99139e61f762b62bc8bc42ced6267
570,152
def _ActiveLines(lines): """Return all non-commented lines. For example: # This is a comment This would be dnsmasq configuration Would result in returning: ['This would be dnsmasq configuration'] Args: lines: the array of lines, as read from open().readlines(). Returns: A list of active...
22668f362b5afd97775f066161165447aa33bb7a
570,156
def mod_abs_diff(a, b, base): """Shortest distance between `a` and `b` in the modular integers base `base`. The smallest distance between a and b is returned. Example: mod_abs_diff(1, 99, 100) ==> 2. It is not 98. mod_abs_diff is symmetric, i.e. `a` and `b` are interchangeable. Args: ...
db447eed40ae3e6a0424ba79d2b3756c7932868a
570,157
def add_vec(vec1, vec2): """return vector sum of 2 vectors""" return vec1[0] + vec2[0], vec1[1] + vec2[1]
f9e79b53ffd20c81f5ef917d13d25031d975ed4e
570,158
def extract_suggest_items(res) -> list: """Formatting items from search to suggest format.""" items = [] es_hits = res['hits']['hits'] if es_hits: for elem in es_hits: hit = elem['_source'] item_dict = { 'page_title': hit['page_title'], '...
399543441b672b726732c2f5c122065eb02d89ad
570,159
def try_parse_bool(possible_bool): """Try to parse a bool.""" if isinstance(possible_bool, bool): return possible_bool return possible_bool in ["true", "True", "1", "on", "ON", 1]
66b515c6e2b3d07af0b3a5501295aca870d86e5f
570,161
def group_consecutives(vals, step=1): """Return list of consecutive lists of numbers from vals (number list).""" run = [] result = [run] expect = None for v in vals: if (v == expect) or (expect is None): run.append(v) else: run = [v] result.append(...
11b68e72319cebda0742d7370e08ba8fac4f46cd
570,168
import re def get_path_name_regex(pattern: str) -> str: """Return the regex pattern for output names.""" return '[0-9a-f]'.join([re.escape(part) for part in pattern.split('%')])
3292ad95d5692f12df1bd3db5bbe36e4b5f32fba
570,170
import requests def requests_body_provider(href): """Get the content body of a page identified by an href. This implementation uses the requests library to fetch content. If the response is not a 2XX then None will be returned instead. Args: href (str): The location of a web page for which t...
3cc61e5a3f5ceca641ab23ff66bc13caf3c72581
570,171
from typing import List from typing import Hashable def merge_ranked(lists: List[List[Hashable]]) -> List[Hashable]: """ For multiple lists of ranked feature names/IDs (e.g. for different targets), work through the lists and merge them such that each feature is included once according to its highest rank ...
c105079a869dc4c4385f677dfc8f44cf93491f20
570,178
from typing import Callable import inspect from typing import Tuple def is_context_provider(func: Callable) -> bool: """Check whether a function is a valid benchmark context provider. A context provider is a function that takes no arguments and returns a 2-tuple of context name and value.""" func_sig ...
e8540f324b970c0484717248d619e58cdbae5b22
570,182
def group_bits(byte, step=2): """ Group the bits from a byte / bigger sequence of bits into groups by length "step" :return: a list of groups """ bits_groups = [] for i in range(0, len(byte), step): bits_groups.append(byte[i:i + step]) return bits_groups
5bf2ced57954b1fcd12a7bd167f100adbf55939f
570,190
import random def create_split(train_dict, split_size = .10, seed = 7): """ Function to create validation data from existing train data. Args: train_dict: Dictionary containing training images. split_size: Validation size. seed: Random seed for reproducing splits. Example: create_spli...
2c61830c6fe76042422cb2e3d7d311f43825fb1e
570,193