content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def extract_tty_phone(service_center): """ Extract a TTY phone number if one exists from the service_center entry in the YAML. """ tty_phones = [p for p in service_center['phone'] if 'TTY' in p] if len(tty_phones) > 0: return tty_phones[0]
9c4d349e0c75b1d75f69cb7758a3aac7dca5b5a5
702,311
from pathlib import Path def get_data_dir() -> str: """Get a filepath to the drem data directory. Returns: str: Filepath to the drem data directory """ cwd = Path(__file__) base_dir = cwd.resolve().parents[3] data_dir = base_dir / "data" return str(data_dir)
16e1bf3d8eab4c4f58ec90f832fd15809bdbbbca
702,312
import shutil def get_unshare_path(): """Find the path to the unshare utility.""" return shutil.which('unshare')
5ca2f1a9bdd8cc107c00be137c6dc3ca0a6f0db7
702,313
def l3_interface_group_id(ne_id): """ L3 Interface Group Id """ return 0x50000000 + (ne_id & 0x0fffffff)
00576c8c33fc965d759abc2aa00aa8f46b930a07
702,314
def make_tag_list(tag_dict): """ make list from tag dictionary """ tag_list = tag_dict.keys() # needless because keys doesn't overlap. # tag_list = list(set(tag_list)) # but, in python3, type of tag_list is not list, it is dict_key. tag_list = list(tag_list) tag_list.sort() return tag_list
3dc825c1ac9cf9b6a1d2df5d4b46f2755b267381
702,315
def sentinel(name): """Create a unique, one-off object with a useful repr""" def __repr__(_): return f'<{name}>' return type(name, (), {'__repr__': __repr__})()
6abe44a5b72bf7d5685c3d7ca97caf0b9c2ee49b
702,316
def datestr(datetime_inst): """ make iso time string from datetime instance """ return datetime_inst.isoformat("T")
027dbaa0c3223261f4afd4e2f3aab45611eab265
702,317
import math import torch def wrap_phi_to_2pi_torch(x): """Shift input angle x to the range of [-pi, pi] """ pi = math.pi x = torch.fmod(2 * pi + torch.fmod(x + pi, 2 * pi), 2 * pi) - pi return x
0905134f4cce5aae13f91e9e7900dd053a5861aa
702,318
def FixAbsolutePathInLine(line, relative_paths): """Fix absolute paths present in |line| to relative paths.""" absolute_path = line.split(':')[0] relative_path = relative_paths.get(absolute_path, absolute_path) if absolute_path == relative_path: return line return relative_path + line[len(absolute_path):]
e0db0d2f3a0973b4db5f3e551f164481861c0b56
702,319
def loss(_sender_input, _message, _receiver_input, receiver_output, labels, _aux_input): """ Accuracy loss - non-differetiable hence cannot be used with GS """ acc = (labels == receiver_output).float() return -acc, {"acc": acc}
85c7d614e004c6c5349c4f42eb99155b7c7aee48
702,320
def lazyprop(func): """Wraps a property so it is lazily evaluated. Args: func: The property to wrap. Returns: A property that only does computation the first time it is called. """ attr_name = '_lazy_' + func.__name__ @property def _lazyprop(self): """A lazily evaluated propery. """ if not hasattr(self, attr_name): setattr(self, attr_name, func(self)) return getattr(self, attr_name) return _lazyprop
b14f82b196177be207923744dda695d6aa70248f
702,321
def extract_range(s): """ Extract range from string""" ranges = s.split(',') if len(ranges) > 1: return (int(ranges[0]), int(ranges[1])) else: return (int(ranges[0]), None)
2a0fea0bdbd40a9fc998fa0b1e2af97be1cbd980
702,322
import os def create_output_path(filename, outdir=None): """ Given a filename for keypoints and descriptors, create an output directory with _kps.h5 appended. Parameters ---------- filename : str The filename or full path outdir : str An optional output path Returns ------- outh5 : str Path of the output h5 file """ image_name = os.path.basename(filename) image_path = os.path.dirname(filename) if outdir is None: outh5 = os.path.join(image_path, image_name + '_kps.h5') else: outh5 = os.path.join(outdir, image_name + '_kps.h5') return outh5
102efd0ee8a523ac5050bcec5d6a1a41670d5203
702,323
import sys def _get_python_executable() -> str: """Returns Python executable. Returns: Python executable to use for setuptools packaging. Raises: EnvironmentError: If Python executable is not found. """ python_executable = sys.executable if not python_executable: raise EnvironmentError("Cannot find Python executable for packaging.") return python_executable
90bcc7a8c4f57d092aca81720f68f005a1974f60
702,324
def simpleCollision(spriteOne, spriteTwo): """ Simple bounding box collision detection. """ widthSpriteOne, heightSpriteOne = spriteOne.image.get_size() rectSpriteOne = spriteOne.image.get_rect().move( spriteOne.pos.x - widthSpriteOne / 2, spriteOne.pos.y - heightSpriteOne / 2) widthSpriteTwo, heightSpriteTwo = spriteTwo.image.get_size() rectSpriteTwo = spriteTwo.image.get_rect().move( spriteTwo.pos.x - widthSpriteTwo / 2, spriteTwo.pos.y - heightSpriteTwo / 2) return rectSpriteOne.colliderect(rectSpriteTwo)
b6084ad260e084effb11701a6b859e0a58c9d19b
702,325
def gen_path(base, code): """ Generate a path for give base path and code used in data generation """ #return os.path.join(base, code[:2], code[:3]) return base
e05790a740b7ab0f83ba5db020598c20d0f89520
702,326
import numbers import json import base64 def encode(d): """Encode an object in a way that can be transported via Mesos attributes: first to JSON, then to base64url. The JSON string is padded with spaces so that the base64 string has no = pad characters, which are outside the legal set for Mesos. """ if isinstance(d, numbers.Real) and not isinstance(d, bool): return repr(float(d)) else: s = json.dumps(d, sort_keys=True) while len(s) % 3: s += ' ' return base64.urlsafe_b64encode(s.encode('utf-8')).decode('ascii')
b1018b9eba2f136f9281dcb936d0903290abd505
702,327
def a2str(a): """ formatting for 1 or 2 dimensional numpy arrays of booleans """ if len(a.shape) == 1: return "".join(map(str, a)) elif len(a.shape) == 2: return "\n".join(map(lambda row: "".join(map(str, row)), a))
589cbc72bc1c3379f74a924f14b304d91a517157
702,328
def __read_dataset_item(path): """Reads data set from path returns a movie dict. Parameters ---------- path : str Absolute path of the MovieLens data set(u.data). Returns ------- rating_dict : dict Returns a dict of users, movies and ratings. { string:movie = { string:user = int:rating } } """ rating_dict = {} with open(path, "r") as reader: lines = reader.readlines() for line in lines: x = line.split(sep="\t") user = x[0] movie = x[1] rating = int(x[2]) if movie not in rating_dict: rating_dict[movie] = dict() rating_dict[movie][user] = rating else: rating_dict[movie][user] = rating return rating_dict
a87baecc5b0c28675bc715aab646bf41e4b40f96
702,329
def get_manifest_indexes(manifest, channel, column): """Get the indices for channel and column in the manifest""" channel_index = -1 for x in range(len(manifest["channels"])): if manifest["channels"][x]["channel"] == channel: channel_index = x break if channel_index == -1: raise Exception(f"Channel does not exist: {channel}") column_index = -1 for x in range(len(manifest["channels"][channel_index]["columns"])): if manifest["channels"][channel_index]["columns"][x]["name"] == column: column_index = x if column_index == -1: raise Exception(f"Column does not exist in channel {channel}: {column}") return channel_index, column_index
63d82417b1e106d408866933bce776c272b2e77d
702,330
import torch def query_ball_point(radius, nsample, xyz, new_xyz): """ Input: radius: local region radius nsample: max sample number in local region xyz: all points, [B, N, 3] new_xyz: query points, [B, S, 3] Return: group_idx: grouped points index, [B, S, nsample] """ device = xyz.device B, N, C = xyz.shape _, S, _ = new_xyz.shape group_idx = torch.arange(N, dtype=torch.long).to(device).view(1, 1, N).repeat([B, S, 1]) dists = torch.cdist(new_xyz, xyz) if radius is not None: group_idx[dists > radius] = N group_idx = group_idx.sort(dim=-1)[0][:, :, :nsample] group_first = group_idx[:, :, 0].view(B, S, 1).repeat([1, 1, nsample]) mask = group_idx == N group_idx[mask] = group_first[mask] return group_idx
e74992747103d11b6618ecf7daf035c4f83e9911
702,331
def is_bounded(coord, shape): """ Checks if a coord (x,y) is within bounds. """ x, y = coord g, h = shape lesser = x < 0 or y < 0 greater = x >= g or y >= h if lesser or greater: return False return True
0a0b6921fcdf285c89b5021d113585ff38255013
702,332
from typing import Optional def bool_to_int(bool_value: Optional[bool]) -> Optional[int]: """Cast bool to int value. :param bool_value: some bool value :return: int represenation """ if bool_value is None: return bool_value return int(bool_value)
fde6cda3dc8909638bb315451a09938224f2f306
702,333
from typing import Any def arghash(args: Any, kwargs: Any) -> int: """Simple argument hash with kwargs sorted.""" sorted_args = tuple( x if hasattr(x, "__repr__") else x for x in [*args, *sorted(kwargs.items())] ) return hash(sorted_args)
c3e95c63831c958bb2a52cabad9f2ce576a4fed8
702,334
import os import re def _applyReplacements(cfile, replacements): """Applies custom replacements. Argument cfile is string. Argument replacements is a list of dicts, with keys "match", "replacement", and (optional) "is_regex" """ for rep in replacements: if not rep.get('with_extension', False): # By default, preserve extension cfile, cext = os.path.splitext(cfile) else: cfile = cfile cext = "" if 'is_regex' in rep and rep['is_regex']: cfile = re.sub(rep['match'], rep['replacement'], cfile) else: cfile = cfile.replace(rep['match'], rep['replacement']) # Rejoin extension (cext might be empty-string) cfile = cfile + cext return cfile
647e541eee027de21e171be570a2abc60c889cf2
702,335
def _get_pcluster_version_from_stack(stack): """ Get the version of the stack if tagged. :param stack: stack object :return: version or empty string """ return next((tag.get("Value") for tag in stack.get("Tags") if tag.get("Key") == "Version"), "")
86106e52ea6ef8780c8aa8f514e0708dd53fb8e3
702,336
import json def extract(spark, source): """Return an RDD[String].""" rdd = spark.sparkContext.textFile(source) return rdd.map(lambda x: json.loads(x))
fef96d6cae65551a6879396ea699acfd2e4cda4b
702,337
def _remove_leading_zeroes_in_field(string): """If blank-separated fields are integer, remove the leading zero.""" split = string.split(" ") for i, field in enumerate(split): if field.isdigit(): split[i] = f"{int(field)}" return " ".join(split)
48ba659b25809f19a0c3ed722d6201ffef73c409
702,338
def kmp(pattern, text): """Knuth-Morris-Pratt substring matching""" pattern_length = len(pattern) matched, subpattern = 0, [0] * pattern_length for i, glyph in enumerate(pattern): if i: while matched and (pattern[matched] != glyph): matched = subpattern[matched - 1] matched += (pattern[matched] == glyph) subpattern[i] = matched matched, results = 0, [] for i, glyph in enumerate(text): while matched and pattern[matched] != glyph: matched = subpattern[matched - 1] matched += (pattern[matched] == glyph) if matched == pattern_length: results.append(i + 1 - matched) matched = subpattern[matched - 1] return results
4f2a30a7a92d2e5890d9c257626c37201b281fec
702,339
def istext(obj): """ Deprecated. Use:: >>> isinstance(obj, str) after this import: >>> from future.builtins import str """ return isinstance(obj, type(u''))
60f3d751f22ad4d120ce7624dd9a07d2c841e206
702,340
def crc16(string, value=0): """CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1 @param string: Data over which to calculate crc. @param value: Initial CRC value. """ crc16_table = [] for byte in range(256): crc = 0 for _ in range(8): if (byte ^ crc) & 1: crc = (crc >> 1) ^ 0xA001 # polly else: crc >>= 1 byte >>= 1 crc16_table.append(crc) for ch in string: value = crc16_table[ord(ch) ^ (value & 0xFF)] ^ (value >> 8) return value
e31ddafc6216b682d9cd0ac24a9fb634f1be1fb8
702,341
def chunks(seq, size): """Breaks a sequence of bytes into chunks of provided size :param seq: sequence of bytes :param size: chunk size :return: generator that yields tuples of sequence chunk and boolean that indicates if chunk is the last one """ length = len(seq) return ((seq[pos:pos + size], (pos + size < length)) for pos in range(0, length, size))
25abe8afdb032af0e2b10dbd3c03b369d862813f
702,342
def secondYAxis(requestContext, seriesList): """ Graph the series on the secondary Y axis. """ for series in seriesList: series.options['secondYAxis'] = True series.name= 'secondYAxis(%s)' % series.name return seriesList
d1c34f16da1f2142021c845afffb63b595e2ce69
702,344
def evaluate(bounds, func): """ Evaluates simpsons rules on an array of values and a function pointer. .. math:: \int_{a}^{b} = \sum_i ... Parameters ---------- bounds: array_like An array with a dimension of two that contains the starting and ending points for the integrand. func: function A function being evaluted in this integral Returns ------- integral: float The integral of function (func) between the bounds """ if len(bounds) != 2: raise ValueError("Bounds should be a length of two, found %d." % len(bounds)) a = float(bounds[0]) b = float(bounds[1]) ya = func(a) yb = func((a + b) / 2) yc = func(b) I = (b - a) * (ya + 4 * yb + yc) / 6.0 return I
af5102d37c1943420a0ff3fff980342ee8c9dad9
702,345
import hashlib def get_dataset_id(settings): """ Creates and returns an unique ID (for practical purposes), given the data parameters. The main use of this ID is to make sure we are using the correct data source, and that the data parameters weren't changed halfway through the simulation sequence. """ hashing_features = [ settings['max_time'], settings['sample_freq'], settings['beamformings'], settings['power_offset'], settings['power_scale'], settings['pos_grid'], settings['pos_shift'], settings['keep_timeslots'], ] hash_sha256 = hashlib.sha256() for feature in hashing_features: if isinstance(feature, list): inner_features = feature else: inner_features = [feature] for item in inner_features: if isinstance(item, float): item = "{:.4f}".format(item) hash_sha256.update(bytes(item, encoding='utf8')) else: hash_sha256.update(bytes(item)) return hash_sha256.hexdigest()
a696f0f85c8ee9c3cab975838db520cc061dfaf4
702,346
import torch def instance_masks_to_semseg_mask(instance_masks, category_labels): """ Converts a tensor containing instance masks to a semantic segmentation mask. :param instance_masks: tensor(N, T, H, W) (N = number of instances) :param category_labels: tensor(N) containing semantic category label for each instance. :return: semantic mask as tensor(T, H, W] with pixel values containing class labels """ assert len(category_labels) == instance_masks.shape[0], \ "Number of instances do not match: {}, {}".format(len(category_labels), len(instance_masks)) semseg_masks = instance_masks.long() for i, label in enumerate(category_labels): semseg_masks[i] = torch.where(instance_masks[i], label, semseg_masks[i]) # for pixels with differing labels, assign to the category with higher ID number (arbitrary criterion) return semseg_masks.max(dim=0)[0]
127c9b9ff3d1044b1c5e1e8650ed493f8a4bc6de
702,347
import time def fix_end_now(json): """Set end time to the time now if no end time is give""" if 'end' not in json or json['end'] is None: json['end'] = int(time.time()) return json
2c126e00ac293c6a511cb86457d60536f1d690ef
702,348
def topics_to_calldata(topics, bytes_per_topic=3): """Converts a list of topics to calldata. Args: topics (bytes[]): List of topics. bytes_per_topic (int): Byte length of each topic. Returns: bytes: Topics combined into a single string. """ return b''.join(topic.to_bytes(bytes_per_topic, byteorder='little') for topic in topics)
2d500016963934fdbc60b388632b817624d5ad8d
702,349
def remove_basic_block_assembly(pydot_cfg): """ Remove assembly text from the CFG's basic blocks """ # Avoid graph and edge nodes, which are the 1st and 2nd nodes nodes = pydot_cfg.get_nodes()[2:] for n in nodes: n.set_label("") return pydot_cfg
3ca5d7fcd46dc96bff92aea67b47afbe53accc40
702,350
def construct_array(nums): """ :param nums: array :return: mul array """ l = len(nums) ans = [1 for _ in range(l)] p = q = 1 for i in range(l): ans[i] *= q ans[-i - 1] *= p q *= nums[i] p *= nums[-i - 1] return ans
5327945cbb83290af94efcce07e4ae391fb3da45
702,351
import argparse import os import json import shutil def main(): """ Use pw_module_tests.testinfo.json files to find and copy fuzzers. """ parser = argparse.ArgumentParser() parser.add_argument('--buildroot') parser.add_argument('--out') args = parser.parse_args() print(' buildroot: ' + args.buildroot) print(' out: ' + args.out) testinfo = os.path.join(args.buildroot, 'obj', 'pw_module_tests.testinfo.json') tests = [] with open(testinfo) as json_file: tests = json.load(json_file) for test in tests: if test['type'] != 'fuzzer': # Skip unit tests continue fuzzer = test['test_name'] objdir = test['test_directory'] module = os.path.basename(objdir) if module == 'pw_fuzzer': # Skip examples continue src = os.path.join(args.buildroot, objdir, fuzzer) dst = os.path.join(args.out, '{}_{}'.format(module, fuzzer)) print('Copying {} to {}'.format(src, dst)) shutil.copy(src, dst) return 0
bcbbda75629e9186d37387ccad02b5560ad4342c
702,352
def return_point(m, n, p): """ m is the index number of the Hammersley point to calculate n is the maximun number of points p is the order of the Hammersley point, 1,2,3,4,... etc l is the power of x to go out to and is hard coded to 10 in this example :return type double """ if p == 1: return m / n v = 0.0 for j in range(10, -1, -1): num = m // p ** j if num > 0: m -= num * p ** j v += num / (p ** (j + 1)) return (v)
73b1c75d6b4ebdc6a0616d9a7b2d6207a4728316
702,353
def OverscanTrim(d,ds): """ Overscan correct and Trim a refurbished HIRES image """ ds = ds.split(',') dsy = ds[0][1:] dsx = ds[1][:-1] dsy = dsy.split(':') dsx = dsx.split(':') x0 = int(dsx[0])-1 x1 = int(dsx[1]) y0 = int(dsy[0])-1 y1 = int(dsy[1]) newdata = d[x0:x1] newdata = newdata[:,y0:y1] newdata = newdata[:4000,:] return newdata
ceb434ca75f458c43137b73b89c0f0242bfe7e93
702,354
import re def __tokenize(syntax) -> list: """ Validate and tokenize the syntax. Valid syntax: snake_case_words, integers, plus, minus. """ if not re.match(r"^[\w\d\s\+-]+$", syntax): raise SyntaxError("Invalid syntax.") syntax = re.sub(r"\s*([+-])\s*", r" \g<1> ", syntax) return syntax.split()
68e79222987771d964ac0d39e38c425d710d3765
702,355
def indent(yaml: str): """Add indents to yaml""" lines = yaml.split("\n") def prefix(line): return " " if line.strip() else "" lines = [prefix(line) + line for line in lines] return "\n".join(lines)
815babb29378f1cfac6ada8258322df92235fc9e
702,356
def get_rbac_role_assigned(self) -> dict: """Get list of accessible menus based on the current session permissions .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - rbacRole - GET - /rbac/role/menuAssigned .. note:: Returns HTTP 204 Empty Response if nothing is assigned :return: Returns dictionary of current session accessible menus :rtype: dict """ return self._get("/rbac/role/menuAssigned")
91d0dcbded36b857a0dc0ddfeaa2815516d162f6
702,357
def _has_sectors(tax_name: str, ignore_sectors: bool) -> bool: """Determine whether we are doing a sector-based forecast.""" return tax_name in ["birt", "sales", "wage", "rtt"] and not ignore_sectors
5725693c514937988b4e668c699606cb3ab46d10
702,359
import os import pathlib def getFile(path): """ Retrieve the path to one of the reference or example files Relies on the environment variable ``SERPENT_TOOLS_DATA`` to find the data files. Parameters ---------- path : str The name of the file without any additional directory information Returns ------- str Path to a data file that can be read with one of the readers or with :func:`serpentTools.read` Raises ------ IOError If no match for ``path`` exists """ datadir = os.environ.get("SERPENT_TOOLS_DATA") if datadir is None: raise EnvironmentError("""serpentTools.data functions rely on the environment variable SERPENT_TOOLS_DATA to find data files. To use these functions for testing and examples, set this environment variable""") fullPath = pathlib.Path(datadir) / path if not fullPath.is_file(): raise FileNotFoundError( "Data file {} could not be found in {}".format(path, datadir)) return str(fullPath)
09fba05e5be7fbb6bb6c8d40acafa71d2018cf29
702,361
def numPointsInSpans(spans): """ ARC112B >>> numPointsInSpans([(1, 3)]) 3 >>> numPointsInSpans([(1, 3), (5, 7)]) 6 >>> numPointsInSpans([(1, 3), (3, 5)]) 5 >>> numPointsInSpans([(1, 3), (2, 5)]) 5 """ timeline = [] for start, end in spans: assert start <= end timeline.append((start, 0, 1)) timeline.append((end, 1, -1)) prevStart = None value = 0 ret = 0 for position, _, diff in sorted(timeline): prevValue = value value += diff if prevValue == 0 and value > 0: prevStart = position elif prevValue > 0 and value == 0: ret += position - prevStart + 1 return ret
e1ffecb3a1d4147f4b15256278f398c5213df200
702,363
def merge_import_policies(value, order=""): """ Merges and returns policy list for import. If duplicates are found, only the most specific one will be kept. """ if not hasattr(value, "merged_import_policies"): raise AttributeError("{value} has not merged import policies") return value.merged_import_policies(order == "reverse")
adaaf5626e09022b36b69b332fb85788665c114e
702,364
def disqus_dev(context): """ No longer supported by Disqus """ return {}
9d823582b4ddc4e3bed992ef203642641ef83486
702,365
def min_sentence_set(): """ minimum query """ return {'hello', 'world'}
6ec3b76f47c9596422c473b4401ce4124806ec1c
702,366
def _sort_student(name: str) -> str: """ Return the given student name in a sortable format. Students are sorted by last name (i.e., last space-split chunk). """ return name.lower().split()[-1]
92747346e0e6ded9715761b8907ccb8ab33da742
702,367
import re def is_gcd_file(filename: str) -> bool: """Checks whether `filename` is a GCD file.""" if re.search('(gcd|geo)', filename.lower()): return True return False
3022bd165683cde609d1f866c3ce655e84561dc4
702,368
from pathlib import Path def _test_path(fn): """Leads to files saved in the data folder Parameters ---------- fn: str The whole filename. Returns ------- The path of the file in the current working system. """ return Path(__file__).parent / "data" / fn
2f6d7e6b952c40e8fe8cefd1c0c8f0c000e02fdd
702,369
def yes_or_no(msg, *params, yes=True, certain=False, third_choice=False): """Query yes, no or display with message. Args: msg (str): Message to be printed out. yes (bool): Indicates whether the default answer is yes or no. """ choices = " [Y/n]?" if yes else " [yes/N]" if certain else " [y/N]?" if third_choice == True: choices = " [Y/d/n]?" if yes else " [yes/d/N]" if certain else " [y/d/N]?" print(msg.format(*params) + choices, end=" ") choice = input().lower() answer = True if yes else False if yes and choice == "n": answer = False if not yes and not certain and choice == "y": answer = True if not yes and certain and choice == "yes": answer = True if choice == "d": answer = "d" return answer
42058dd0ed2fb606444233e13551d6d5f11a90a7
702,370
def _magni_test_var_in_globals_func(*args, **kwargs): """Test function used in some tests.""" return 'magni_test_var' in globals()
c4209abbc865e65644df919678dd11ddbad24e7e
702,371
def overlap(layer, interval): """ calculate the thickness for a layer that overlapping with an interval :param layer: (from_depth, to_depth) :param interval: (from_depth, to_depth) :return: the overlapping thickness """ res = 0 if layer[0] >= interval[0] and layer[1] <= interval[1]: # cover the whole interval res = interval[1] - interval[0] elif layer[1] >= interval[0] or layer[0] <= interval[1]: # this segment is not in the interval pass elif layer[0] <= interval[0] and layer[1] >= interval[1]: # inside the interval res = layer[1]-layer[0] elif layer[0] >= interval[0] and layer[1] >= interval[1]: # lower part of the layer is overlapped res = interval[0] - layer[1] else: res = layer[0] - interval[1] return res
f77fdc433f79cf7990416a97cc9edfcbcc860585
702,372
import zipfile def _extract_info(archive, info): """ Extracts the contents of an archive info object ;param archive: An archive from _open_archive() :param info: An info object from _list_archive_members() :return: None, or a byte string of the file contents """ if isinstance(archive, zipfile.ZipFile): fn = info.filename is_dir = fn.endswith('/') or fn.endswith('\\') out = archive.read(info) if is_dir and out == b'': return None return out info_file = archive.extractfile(info) if info_file: return info_file.read() return None
3014a9e85077f33522aaf466c9bef3bd020d252b
702,373
def _space_all_but_first(s: str, n_spaces: int) -> str: """Pad all lines except the first with n_spaces spaces""" lines = s.splitlines() for i in range(1, len(lines)): lines[i] = " " * n_spaces + lines[i] return "\n".join(lines)
36da5eb15a9ab5fa473831b5440ffa88495f6cac
702,374
import argparse import sys def parse_args(): """ Parse command-line arguments.""" parser = argparse.ArgumentParser(description='''Identify family distribution with unmasked Ensembl ID''') parser.add_argument( '-i','--input', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help='An input file (CSV).') parser.add_argument( '-o','--output', nargs='?', default=sys.stdout, help='Basename for output file (CSV).') return parser.parse_args()
54de56cab2708bb82c32808e7961295f3e427ba4
702,375
def fix_brackets(placeholder: str) -> str: """Fix the imbalanced brackets in placeholder. When ptype is not null, regex matching might grab a placeholder with } missing. This function fix the missing bracket. Args: placeholder: string placeholder of RuntimeParameter Returns: Placeholder with re-balanced brackets. Raises: RuntimeError: if left brackets are less than right brackets. """ lcount = placeholder.count('{') rcount = placeholder.count('}') if lcount < rcount: raise RuntimeError( 'Unexpected redundant left brackets found in {}'.format(placeholder)) else: patch = ''.join(['}'] * (lcount - rcount)) return placeholder + patch
5fa4a83eeca676c58c33038add62a0c5bed7fe8b
702,376
def ParseRangeHeader(range_header): """Parse HTTP Range header. Args: range_header: A str representing the value of a range header as retrived from Range or X-AppEngine-BlobRange. Returns: Tuple (start, end): start: Start index of blob to retrieve. May be negative index. end: None or end index. End index is exclusive. (None, None) if there is a parse error. """ if not range_header: return None, None try: range_type, ranges = range_header.split('=', 1) if range_type != 'bytes': return None, None ranges = ranges.lstrip() if ',' in ranges: return None, None end = None if ranges.startswith('-'): start = int(ranges) if start == 0: return None, None else: split_range = ranges.split('-', 1) start = int(split_range[0]) if len(split_range) == 2 and split_range[1].strip(): end = int(split_range[1]) + 1 if start > end: return None, None return start, end except ValueError: return None, None
ad37fd1532edd9519073c93aa73402b3c7d0a404
702,377
from typing import Any from typing import List def init_args( cls: Any, ) -> List[str]: """ Return the __init__ args (minus 'self') for @cls Args: cls: class, instance or callable Returns: The arguments minus 'self' """ # This looks insanely goofy, but seems to literally be the # only thing that actually works. Your obvious ways to # accomplish this task do not apply here. try: # Assume it's a factory function, static method, or other callable args = cls.__code__.co_varnames except AttributeError: # assume it's a class args = cls.__init__.__code__.co_varnames # Note: There is a special place in hell for people who don't # call the first method argument 'self'. if args[0] == 'self': args = args[1:] return args
2d867049f3c1f4937d0d8a7042315644cef219ae
702,378
import re def create_url(url): """ modifying the given url so that it returns JSON data when we do a GET requests later in this script """ # extract the branch name from the given url (e.g master) branch = re.findall(r"\/tree\/(.*?)\/", url)[0] api_url = url.replace("https://github.com", "https://api.github.com/repos") api_url = re.sub(r"\/tree\/.*?\/", "/contents/", api_url) api_url = api_url+"?ref="+branch return api_url
682343d1e7462ef224865b659357716e55cd22cd
702,379
import secrets def generate_token_urlsafe(unique=False, nbytes=32): """Generate an URL-safe random token.""" return secrets.token_urlsafe(nbytes=nbytes)
5bdab6879f241a7459653e5ec363110263f0c171
702,380
import re def parse_multiline(element, poe_implicit_split = False): """ Get data from a row & regroup tag-separated string (<br/>) in a list poe_implicit_split: <number>( to )<number> for Implicit Mods extraction (optional) """ res = [] for data in element: content = [] for x in data.strings: if poe_implicit_split: to_block = re.split(" to (?=\d)", x) if len(to_block) > 1: content.append(to_block) continue content.append(x) if len(content) == 1: content = content[0] if not content: content = '' res.append(content) return res
ef59fe17a3b221086276baa67448d0870b838f71
702,381
def score_sig_1D_base(true_signatures, pred_signatures): """ percent of mutations with the right signature Parameters ---------- true_signatures: iterable array-like of length N (number of mutations), with the true signature for each mutation pred_signatures: iterable array-like of length N (number of mutations), with the predicted signature for each mutation """ N = len(true_signatures) return sum(true_signatures == pred_signatures) / N
cd04cef1c7eecea8da804fe631fedc18c33b4d11
702,383
def compute_apparent_power(f, j, seconds_per_file, values): """ Apparent power is the product of the voltage RMS and the current RMS. """ cs = [n for n in list(f) if 'current' in n] apparent_power = dict() for cs_i, _ in enumerate(cs): if 'voltage' in list(f): voltage_name = 'voltage_rms' else: voltage_name = 'voltage_rms{}'.format(cs_i + 1) current_rms_name = 'current_rms{}'.format(cs_i + 1) apparent_power_name = 'apparent_power{}'.format(cs_i + 1) voltage_rms = values[voltage_name][j:j + seconds_per_file] current_rms = values[current_rms_name][j:j + seconds_per_file] apparent_power[apparent_power_name] = voltage_rms * current_rms return apparent_power
76f7b903bce2f340d0494524f3d0d2ad40e6422e
702,384
import decimal def _dict_decimal_to_float(my_dict): """If any values in dictionary are of dtype 'Decimal', cast to float so can be JSONified. """ for key, val in my_dict.items(): if isinstance(val, decimal.Decimal): my_dict[key] = float(val) return my_dict
7d1741322782c49b9b8a6a7369344797439ff00b
702,385
def string2cycles(string): """ Convert string from user input to permutation in cycle notation as list :param string: Permutation as string :type string: string :return: Returns permutation in cycle notation as list :rtype: list """ groups = string.split(')(') items = [] for i in range(0, len(groups)): groups[i] = groups[i].replace('(', '').replace(')', '').lstrip().rstrip().split(' ') temp = [] for j in groups[i]: temp.append(int(j)) items.append(temp) return items
5a10f270fb934a1b22f61e84e61f679f2cad5f79
702,386
def from_args(it, key, lo, hi, prefix, reverse, max_, include, max_phys): """This function is a stand-in until the core.py API is refurbished.""" if key: it.set_exact(key) return it.forward() elif prefix: it.set_prefix(prefix) else: if lo: it.set_lo(lo) if hi: it.set_hi(hi, include) if max_: it.set_max(max_) if max_phys: it.set_max_phys(max_phys) if reverse: return it.reverse() else: return it.forward()
859e716e5eb32be10806de400b97fdf0e4770ed4
702,388
def bump_version(version_array, level): """ Perform ++1 action on the array [x, y, z] cell, Input values are assumed to be validated :param version_array: int array of [x, y, z] validated array :param level: string represents major|minor|patch :return: int array with new value """ if type(version_array) != list: raise ValueError("Error, invalid version_array: '{}', " "should be [x, y, z].".format(version_array)) if level == 'major': version_array[0] += 1 version_array[1] = 0 version_array[2] = 0 elif level == 'minor': version_array[1] += 1 version_array[2] = 0 elif level == 'patch': version_array[2] += 1 else: raise ValueError("Error, invalid level: '{}', " "should be major|minor|patch.".format(level)) return version_array
8a26db1694cf777915cc8c170355fd77ea4e9e66
702,389
def _get_timestep_lookup_function(control_loop_period, memory_loc, rtf_key): """ Creates a customized timestep lookup function for a SynchronizedTimedLoop :param control_loop_period: duration in [s] of each timed loop :param memory_loc: location in shared memory to get() data from :param rtf_key: key for dictionary to plug into memory location :return: a customized function that takes no arguments and returns a desired_dt based on the scaling from the real_time_factor """ def timestep_lookup_function(): data = memory_loc.get() real_time_factor = data[rtf_key][0] desired_dt = control_loop_period / real_time_factor return desired_dt return timestep_lookup_function
500e61c0cbb38012bbce18dfc6f648c78a4b3f36
702,390
def daemonize(func): """ A function wrapper that checks daemon flags. This wrapper as it is assumes that the calling class has a daemon attribute. """ def _wrapper(self, *args, d_init=False, **kwargs): if d_init: self.daemon.d_init.append((func, self, args, kwargs)) return func(self, *args, **kwargs) return _wrapper
3f7b52c319be0a570e8c4843d061e1d0387982af
702,391
def get_cursor(connection): """ Gets a cursor from a given connection. :type MySQLdb.connections.Connection :param connection: A mysql connection :rtype MySQLdb.cursors.SSDictCursor :return A mysql cursor """ return connection.cursor()
dc1e9b99bff6b43eb324161026196358d318f59c
702,392
def _popup_footer(view, details): """ Generate a footer for the package popup that indicates how the package is installed. """ return """ {shipped} <span class="status">Ships with Sublime</span> &nbsp; &nbsp; {installed} <span class="status">In Installed Packages Folder</span> &nbsp; &nbsp; {unpacked} <span class="status">In Packages Folder</span> """.format( shipped="\u2611" if details["is_shipped"] else "\u2610", installed="\u2611" if details["is_installed"] else "\u2610", unpacked="\u2611" if details["is_unpacked"] else "\u2610")
8f159f75990e87c8d431bb2dd1d01e648079ac96
702,393
def trycast(new_type, value, default=None): """ Attempt to cast `value` as `new_type` or `default` if conversion fails """ try: default = new_type(value) finally: return default
d670f545fb1853dfd95da1de961e44ee5a477c5f
702,394
def _generate_wireless_settings_data(settings): """Generates a wireless settings data array to push to the router from the given wireless settings.""" settings.ensure_valid() data = {'ssid1': settings.ssid, 'channel': settings.channel, 'Save': 'Save'} if settings.is_enabled: data['ap'] = 1 if settings.is_broadcasting_ssid: data['broadcast'] = 2 # preserve some of the params we don't handle for k in ('region', 'mode', 'chanWidth', 'rate'): data[k] = settings.get_internal_param(k) # WDS (WLAN bridging) related settings # we'll clear them all by default merge_with = {'brlssid': '', 'brlbssid': '', 'keytype': 1, 'wepindex' 'authtype': 1, 'keytext': ''} data = dict(data, **merge_with) return data
d41d13f56ecd813d01d2c9223db0b69ad26af5ae
702,395
def dummy_house(): """ Sample dataset that will be used to alter and make prediction on """ return { "Id": 34, "MSSubClass": 20, # Identifies the type of dwelling involved in the sale. "LotFrontage": 70.0, # Linear feet of street connected to property "LotArea": 10552, # Lot size in square feet "OverallQual": 5, # Rates the overall material and finish of the house "OverallCond": 5, # Rates the overall condition of the house "YearBuilt": 1959, # Original construction date "YearRemodAdd": 1959, # Remodel date (same as construction date if no remodeling or additions) "MasVnrArea": 0.0, # Masonry veneer area in square feet "BsmtFinSF1": 1018, # Type 1 finished square feet "BsmtFinSF2": 0, # Type 2 finished square feet "BsmtUnfSF": 380, # Unfinished square feet of basement area "TotalBsmtSF": 1398, # Total square feet of basement area "1stFlrSF": 1700, # First Floor square feet "2ndFlrSF": 0, # Second floor square feet "LowQualFinSF": 0, # Low quality finished square feet (all floors) "GrLivArea": 1700, # Above grade (ground) living area square feet "BsmtFullBath": 0, # Basement full bathrooms "BsmtHalfBath": 1, # Basement half bathrooms "FullBath": 1, # Full bathrooms above grade "HalfBath": 1, # Half baths above grade "BedroomAbvGr": 4, "KitchenAbvGr": 1, "TotRmsAbvGrd": 6, # Total rooms above grade (does not include bathrooms) "Fireplaces": 1, # Number of fireplaces "GarageYrBlt": 1959.0, # Year garage was built "GarageCars": 2, # Size of garage in car capacity "GarageArea": 447, # Size of garage in square feet "WoodDeckSF": 0, # Wood deck area in square feet "OpenPorchSF": 38, # Open porch area in square feet "EnclosedPorch": 0, # Enclosed porch area in square feet "3SsnPorch": 0, # Three season porch area in square feet "ScreenPorch": 0, # Screen porch area in square feet "PoolArea": 0, # Pool area in square feet "MiscVal": 0, # $Value of miscellaneous feature "MoSold": 4, # Month Sold (MM) "YrSold": 2010, # Year Sold (YYYY) "SalePrice": 165500, }
d1360a8709712746f07f92df85a8d704bccd797c
702,396
def construct_description(prefix: str, suffix: str, items: list): """Construction of complete description with prefix and suffixx. Args: prefix (str): prefix suffix (str): suffix items (list): itesm Returns: str: complete description string """ item_str = ','.join(items) return f'{prefix}{item_str}{suffix}'
61eec7c2f40bf3b4857cdd682e52aabac1f2ec76
702,398
def read_cookies_file(filename): """read cookie txt file :param filename: (str) cookies file path :return: (dict) cookies """ with open(filename, 'r') as fp: cookies = fp.read() return cookies
79ce16fabdec49a7b7b60b4d8bd5346798f03edf
702,399
from typing import Union def kind_div(x, y) -> Union[int, float]: """Tries integer division of x/y before resorting to float. If integer division gives no remainder, returns this result otherwise it returns the float result. From https://stackoverflow.com/a/36637240.""" # Integer division is tried first because it is lossless. quo, rem = divmod(x, y) if not rem: return quo else: return x / y
97343b68051291acc5a614d086d09f59f9b9abfd
702,400
from itertools import chain import os def parse_feedstock_file(feedstock_fpath): """ Takes a file with space-separated feedstocks on each line and comments after hashmarks, and returns a list of feedstocks :param str feedstock_fpath: :return: `list` -- list of feedstocks """ if not (isinstance(feedstock_fpath, str) and os.path.exists(feedstock_fpath)): return list() try: with open(feedstock_fpath, 'r') as infile: feedstocks = list( chain.from_iterable(x.split('#')[0].strip().split() for x in infile) ) except: return list() return feedstocks
0c6bd403c07c97256db9fd310ceaf2476b2b78f3
702,401
def get_first_node_of_tree(root_node): """root_node's rhythm is #4""" return root_node.sons[0].sons[0].sons[0].sons[0].sons[0]
3dc2d8cb4a2ea006c35cc3fcfdf5efde5c21bb78
702,402
def rat_fun(x, poles): """ Computes the value of a rational function with poles in poles and roots in -poles; see Definition 8.29 from the doctoral thesis "Model Order Reduction for Fractional Diffusion Problems" for a precise definition. Parameters ---------- x : float The argument of the rational function. poles : list A list of poles. Returns ------- val : float The value of the rational function at x. """ val = 1 for pole in poles: val *= (x + pole) / (x - pole) return val
48e14764595f1242e65908d8008ada2ac64a4a90
702,403
def createCode(videoNameList, fileUrlList, videoIdList, codeFile): """ 参数:文件名称列表,文件链接列表,文件id列表,代码文件 功能:将已有数据批量写入代码并形成列表 返回值:代码列表 """ codeList = [] for i in range(len(videoNameList)): codeF = open(codeFile, "r", encoding = "utf-8") code = codeF.read() codeF.close() codeList.append(code.format(fileUrlList[i], videoNameList[i], "github id: "+videoIdList[i])) return codeList
6c6bc86e971975a1c9524a201c74c2fcfec7c1fc
702,404
def _optargs_to_kwargs(args): """Convert --bar-baz=quux --xyzzy --no-squiz to kwargs-compatible pairs. E.g., [('bar_baz', 'quux'), ('xyzzy', True), ('squiz', False)] """ kwargs = [] for arg in args: if not arg.startswith('--'): raise RuntimeError("Unknown option %r" % arg) elif '=' in arg: key, value = arg.split('=', 1) key = key[2:].replace('-', '_') if value.isdigit(): value = int(value) elif arg.startswith('--no-'): key, value = arg[5:].replace('-', '_'), False else: key, value = arg[2:].replace('-', '_'), True kwargs.append((key, value)) return kwargs
f0523442f3de88d123c0d968a770f817084149df
702,405
import csv def _get_reader(file): """Get CSV reader and skip header rows.""" reader = csv.reader(file) # Skip first 3 rows because they're all headers. for _ in range(3): next(reader) return reader
588328d9ccb5af32abad0c0d8fe8c4489d306c12
702,406
from typing import Counter def add_intersection_delay(G, intersection_delay=7, time_col = 'time', highway_col='highway', filter=['projected_footway','motorway']): """ Find node intersections. For all intersection nodes, if directed edge is going into the intersection then add delay to the edge. If the highest rank road at an intersection intersects a lower rank road, then the highest rank road does not get delayed. This assumes the highest rank road has the right-of-way. :param G: a base network object (nx.MultiDiGraph) :param intersection_delay: The number of seconds to delay travel time at intersections :filter: The filter is a list of highway values where the type of highway does not get an intersection delay. :returns: a base network object (nx.MultiDiGraph) """ highway_rank = { 'motorway': 1, 'motorway_link': 1, 'trunk': 1, 'trunk_link': 1, 'primary': 2, 'primary_link': 2, 'secondary': 3, 'secondary_link':3, 'tertiary': 4, 'tertiary_link': 4, 'unclassified': 5, 'residential': 5, 'track': 5 } G_copy = G.copy() node_intersection_list = [] for node in G.nodes: #print(G_reflected_time.degree(node)) # if degree is greater than 2, then it is an intersection if G.degree(node) > 2: node_intersection_list.append(node) for intersection in node_intersection_list: pred_node_dict = {} for pred_node in G.predecessors(intersection): for edge in G[pred_node][intersection]: #print(pred_node, intersection) new_key = G_copy[pred_node][intersection][edge].get(highway_col) # it's possible that the highway can have more than one classification in a list if isinstance(new_key, list): new_key = new_key[0] pred_node_dict[pred_node] = highway_rank.get(new_key) # update all 'None' values to 5 pred_node_dict = {k:(5 if v==None else v) for k, v in pred_node_dict.items() } pred_node_dict = dict(sorted(pred_node_dict.items(), key=lambda item: item[1], reverse=False)) #print(pred_node_dict) first_element_value = pred_node_dict[next(iter(pred_node_dict))] res = Counter(pred_node_dict.values()) if res[first_element_value] <= 2: #print('skip') # remove all elements with same value pred_node_dict = {key:val for key, val in pred_node_dict.items() if val != first_element_value} else: pred_node_dict = pred_node_dict #print(f"print pred_node_dict again: {pred_node_dict}") for pred_node,value in pred_node_dict.items(): #for pred_node in G.predecessors(intersection): #print(pred_node) #print(intersection) #print(G[pred_node][intersection]) for edge in G[pred_node][intersection]: if G_copy[pred_node][intersection][edge].get(highway_col) not in filter: G_copy[pred_node][intersection][edge][time_col] = G[pred_node][intersection][edge][time_col] + intersection_delay return G_copy
536ac0d22fcccf9426140e7b4de6367a029c41a6
702,407
def left_justify_string(keyword, value): """Returns a string with dotted separation. """ return '%s' % keyword .ljust(40, ".") + ": " + '%s\n' % value
dc9c59224ee2c62e2c55093792f352f80df5c4b2
702,408
import pathlib def write_text(path: str, data: str, encoding=None, append=False): """write text `data` to path `path` with encoding e.g j.sals.fs.write_text(path="/home/rafy/testing_text.txt",data="hello world") -> 11 Args: path (str): path to write to data (str): ascii content encoding ([type], optional): encoding. Defaults to None. append (bool, optional): indicate whether to open the file in append mode or not. Returns: int: returning the number of characters written. """ p = pathlib.Path(path) mode = "at" if append else "wt" with p.open(mode=mode, encoding=encoding) as f: return f.write(data)
1d64c9494ee87c3ce0f0ad33466e260c1d7e43bd
702,409
def get_first_index_greater_than_benchmark(arr, benchmark, reverse=False): """ 获取在数组 arr 中第一个大于基准值的索引。reverse 控制反向查找或正向查找 Args: arr(list): benchmark(): reverse(bool): Returns: """ if reverse: start = len(arr) - 1 stop = -1 step = -1 else: start = 0 stop = len(arr) step = 1 for i in range(start, stop, step): if arr[i] > benchmark: return i return -1
8bc6fd64e07428af68da4dd39e1f44db856e55d8
702,410
import argparse def local_args(): """ Create an argparse namespace to create a local dask cluster. """ args = argparse.Namespace() args.num_procs = 1 args.num_threads_per_proc = 1 args.cluster_location = "LOCAL" args.client_restart = False return args
2c9d9d260a1994bfa794d356babe101af9722521
702,411
def fixture_packages_with_trailing_spaces(): """ A packages dictionary with trailing spaces on some items """ packages = { "basic": ["package-one ", "package-two"], "complex": ["package-three", "package-four", "package-five"], } return packages
cdf80f2f45ad339aeb8da40c175ad26b10e1e1c6
702,413
def dice(a, b): """ "Entity-based" measure in CoNLL; #4 in CEAF paper """ if a and b: return (2 * len(a & b)) / (len(a) + len(b)) return 0.
ef650786ad86e0e60a3b80c99445bc95b2b5187d
702,414
def traverseFilter(node,filterCallback): """Traverse every node and return a list of the nodes that matched the given expression For example: expr='a+3+map("test",f())' ast=SeExprPy.AST(expr) allCalls=SeExprPy.traverseFilter(ast.root(),lambda node,children: node.type==SeExprPy.ASTType.Call) allMapNodes=SeExprPy.traverseFilter(ast.root(),lambda node,children: node.type==SeExprPy.ASTType.Call and node.value=="map") allVarRefs=SeExprPy.traverseFilter(ast.root(),lambda node,children: node.type==SeExprPy.ASTType.Var) """ ret=[] children=node.children() if filterCallback(node,children): ret.append(node) for childNode in children: ret.extend(traverseFilter(childNode,filterCallback)) return ret
751810f0eb54b4aa08cf020f34649780bd208d81
702,415
def int2bin(n,digits=8): """ integer to binary string""" return "".join([str((n >> y) & 1) for y in range(digits-1, -1, -1)])
13e8ad69a1f8523c647376473605f581369488d9
702,416
def replace_digits(p, digits): """If p contains more than one of the same digit, replace them will all other possible digits.""" if 0 in digits: other_digits = [str(d) for d in list(range(1, 10)) if str(d) != str(p)[digits[0]]] else: other_digits = [str(d) for d in list(range(10)) if str(d) != str(p)[digits[0]]] generated_numbers = [] p_d = [str(d) for d in str(p)] for od in other_digits: for d in digits: p_d[d] = od generated_numbers.append(int("".join(p_d))) return generated_numbers
e29c2e95d043f07aefb538c71f57bbe7d857b086
702,417
def active_piece(piece): """ Validate piece as active. """ return piece & 1 and piece & 0xE
bb9740b3eabfade4fa6f2a810243965e03c64d2e
702,418