content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _human_readable(size_in_bytes): """Convert an integer number of bytes into human readable form E.g. _human_readable(500) == 500B _human_readable(1024) == 1KB _human_readable(11500) == 11.2KB _human_readable(1000000) == """ if size_in_byt...
e718b1cc047a1a7793e5c6a88d4251c17bf5fd0d
656,221
def flatten_list(a, result=None): """Flattens a nested list. >>> flatten_list([ [1, 2, [3, 4] ], [5, 6], 7]) [1, 2, 3, 4, 5, 6, 7] """ if result is None: result = [] for x in a: if isinstance(x, list): flatten_list(x, result) else: result...
81dc2911951b8d2611b18219da92cbed1e64fa4a
656,222
import itertools def record_list(games, wins): """ Inputs: games (integer) - total number of games played wins (integer <= games) - total number of games won Returns: record_list (list) - all possible ways record could be achieved as binary """ record = list() losses =...
f6fc39d0b2db81519b5919dbf745f5e2fb99d3e1
656,224
import io def spit(path, txt, encoding='UTF-8', append=False): """ Write a unicode string `txt` to file `path`. By default encoded as UTF-8 and truncates the file prior to writing Parameters ---------- path : str File path to file on disk txt : unicode Text content to wr...
75b406f81068006aba61f34395590b8a1948a469
656,229
def check_na(df, norm=False): """quick check the missing value stats for each column in a df.""" if norm: return df.isna().sum()/df.shape[0] else: return df.isna().sum()
da716cff19e0dbbcf09258624bc7f9cfdcc605cd
656,231
def indice_to_pos(image_size, indice): """Converts indice of a pixel in image(index number in array of pixels) to x,y coordinates. Args: image_size: indice: index number in image's array of pixels. Returns: tuple: pair of values representing x,y coordinates corresponding to given i...
05b46f4f2f5b782de9c9d310f1b3cd92c9ded985
656,232
from typing import List from typing import Dict from typing import Union from typing import Any def extract_outputs(path: List[str], results: Dict) -> Union[Any, List[Any]]: """Pull data out of results according to ref. :param path: The data location. :param results: The data to pull content from. :r...
f60e7f7c9db3a3db72acde26837c9236d7d93a72
656,234
def construct_bap_id(subscription_id, group_name, lb_name, address_pool_name): """Build the future BackEndId based on components name. """ return ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/backendAddressPools...
8d23cf5487a8b8f77f126af6d14961636d6855d1
656,236
def get_channel_block(peer_ex, ord_name, ord_namespace, channel, cmd_suffix): """Get channel block from Peer. Args: peer_ex (Executor): A Pod Executor representing a Peer. ord_name (str): Name of the orderer we wish to communicate with. ord_namespace (str): Namespace where the orderer r...
22787dada06502413ce3134d4cf78188133780ae
656,239
def _check_if_list_of_featuregroups_contains_featuregroup(featuregroups, featuregroup_name, version): """ Check if a list of featuregroup contains a featuregroup with a particular name and version Args: :featuregroups: the list of featuregroups to search through :featuregroup_name: the name...
e25d603d7620f814b08bd1300678cade515396cf
656,242
from typing import Iterable from typing import Tuple def replace(s: str, src_dst: Iterable[Tuple[str, str]]) -> str: """ :param s: string :param src_dst: [(src1, dst1), (src2, dst2), ...] :return: string with srcX replaced with dstX """ for src, dst in src_dst: s = s.replace(src, dst)...
43ba3e4bf2cca55d9d1ac6b0117aea3456b0c3c0
656,245
def _normalize_activity_share_format(share): """ Convert the input share format to the internally format expected by FTS3 {"A": 1, "B": 2} => [{"A": 1}, {"B": 2}] [{"A": 1}, {"B": 2}] => [{"A": 1}, {"B": 2}] """ if isinstance(share, list): return share new_share = list() for key,...
b1289054a10554d858e74a311f8ff327beaa9062
656,247
def _num_columns(data): """Find the number of columns in a raw data source. Args: data: 2D numpy array, 1D record array, or list of lists representing the contents of the source dataframe. Returns: num_columns: number of columns in the data. """ if hasattr(data, 'shape'): # True for numpy arr...
5be48bbc4b7970818c2eac37ad8489b8394af4f9
656,252
def equal(a, b, eps=0.001): """ Check if a and b are approximately equal with a margin of eps """ return a == b or (abs(a - b) <= eps)
f53903dc52ec50957877473b4193f602fe552b9a
656,257
def center_x(display_width: int, line: str) -> int: """ Find the horizontal center position of the given text line Parameters: display_width (int) : The character width of the screen/space/display line (int) : Line of text Returns: (int): Horizontal character number ...
00559aa1f63515856314a5750a159738fd6f59ff
656,260
def Parents(it): """ Return a generator to the parents of all the nodes in the passed iterable. Note that we first use a set to remove duplicates among the parents.""" return iter(set((n.GetParent() for n in it if n.GetParent() != None)))
a0c2d7588e92384913071ea4fb4d09d134f6aa55
656,262
def df_rename_col(data, col, rename_to, destructive=False): """Rename a single column data : pandas DataFrame Pandas dataframe with the column to be renamed. col : str Column to be renamed rename_to : str New name for the column to be renamed destructive : bool If ...
da424f4c7202aa397153a3293f8f24a672c783d9
656,263
def identity(n): """ Return the identity matrix of size n :param n: size of the identity matrix to return :return: identity matrix represented by a 2 dimensional array of size n*n """ return [[1 if i == j else 0 for i in range(n)] for j in range(n)]
82be8893c42c396c50e94f5d7baeee2454f4b449
656,265
def create_coco_dict(images, categories, ignore_negative_samples=False): """ Creates COCO dict with fields "images", "annotations", "categories". Arguments --------- images : List of CocoImage containing a list of CocoAnnotation categories : List of Dict COCO categories ...
21ec7655d7c85a332c04e6f1370be8c9a160a2f5
656,266
def reduce_breed_list(test): """ Input: cleaned dataset returns: a data set with the variable "breeds" reduced for cats and dogs. Removes the "Mix" part of the breed name and stripped white space. Made choice that Domestic Shorthair is equivalent to Domestic Shorthair Mix when it comes to cats...
01ad52a046d8333052514ac0bde98f629f29f1a4
656,268
import itertools def broadcast_lists(list_a, list_b): """Broadcast two lists. Similar behavior as ``gs.broadcast_arrays``, but for lists. """ n_a = len(list_a) n_b = len(list_b) if n_a == n_b: return list_a, list_b if n_a == 1: return itertools.zip_longest(list_a, list_b...
7938cf533bceb388f72940ccdb52053acc3204f2
656,270
def any_endswith(items, suffix): """Return True if any item in list ends with the given suffix """ return any([item.endswith(suffix) for item in items])
d3ca627bcd2fd0f10dd58a3d06129b5a65b75680
656,273
def resolve_value(val): """ if given a callable, call it; otherwise, return it """ if callable(val): return val() return val
fa489c128cbbe5aa4e59cb94bb3ab0ef9246962f
656,276
import json def read_data_from_file(filepath): """ This function reads data from the testbed saved into a file """ data = [] with open(filepath, "r") as file: for json_obj in file: data.append(json.loads(json_obj)) return data
540a0b28a7316a4d9d9dbdb674cfc9b7aedd1416
656,277
def to_iso_date(timestamp): """Convert a UTC timestamp to an ISO8601 string. datetime instances can be constructed in alternate timezones. This function assumes that the given timestamp is in the UTC timezone. Args: timestamp(datetime): A datetime object in the UTC timezone. Returns: ...
b6453dbbddb498debb33137ea953d2b999031e35
656,281
from pathlib import Path import string def kernelspec_dir(kernelspec_store: Path, kernel_id: str) -> Path: """Return path to the kernelspec directory for a kernel with a given ID Parameters ---------- kernelspec_store Path to the place kernelspec store where kernelspec dir should be p...
0fb4f40dd6f54d144f314e64873e1f5dca27731b
656,283
def test_iterable(value): """Check if it's possible to iterate over an object.""" try: iter(value) except TypeError: return False return True
fcd42730d0adb9febc8d01f29a65f463b5932407
656,284
def _write_to(string, path): """ Writes a string to a file on the server """ return "echo '" + string + "' > " + path
5f440ca07b4b9a52f65aec6eff7cf97d8fa54829
656,286
def get_plot_properties_for_trajectory(plot_nums:int, base_color:str='r') -> tuple: """ Get plot properties for trajectory. Args: plot_nums (int): The number of plots. base_color (str): Base color. Returns: tuple: (cs, alphas, linewidths, ...
cdec1d5e7b78cd9954976f8728f0d054c8762f77
656,292
def change_image_mode(img, label, args): """ Change image mode (RGB, grayscale, etc.) """ img = img.convert(args.get("image_mode")) label["image_mode"] = args.get("image_mode") return img, label, args
5be45e3821954fbd297a0bb298e40028bb4a835c
656,300
def get_all_attached_volumes(self): """ Get all the the volumes that are attached to an instance. :param boto.ec2.instance.Instance self: Current instance. :return: List of attached boto.ec2.volume.Volume :rtype: list """ return [v for v in self.connection.get_all_volumes() if v.at...
a7285ec9cb385c75fa93633fef4d66a8fedd8b32
656,301
def get_prob_from_odds( odds, outcome ): """ Get the probability of `outcome` given the `odds` """ oddFor = odds[ outcome ] oddAgn = odds[ 1-outcome ] return oddFor / (oddFor + oddAgn)
b4507dde8285c357cb17c1b749657a2c634efa63
656,305
def p2(max): """Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find...
5e3bf97381dba3789b810b86d5226a7364b7a743
656,307
from typing import Set import re def _replace_stopwords(text: str, words: Set[str], symbol: str = " ") -> str: """ Remove words in a set from a string, replacing them with a symbol. Parameters ---------- text: str stopwords : Set[str] Set of stopwords string to remove. symbol: str...
76a4526e6f93dc08d05dff17898eb1db7f4a610b
656,311
def frags_overlap_same_chrom(frags, start, end): """ get the fragments overlapping the interval [start, end], assuming all fragments in the input table are already on the correct chromosome """ f = frags.loc[((frags["start_pos"] < start) & (frags["end_pos"] > start)) | ((frags["sta...
978e52070e0f28a2ede6497bc7415ec3a9c01646
656,312
def cp_model(k_min: float, mu_min: float, phi: float, cp=0.4) -> tuple: """ Build rock physics models using critical porosity concept. :param k_min: Bulk modulus of mineral (Gpa) :param mu_min: Shear modulus of mineral (Gpa) :param phi: Porosity (fraction) :param cp: critical porosity, default ...
1be141d91969a9acf4e55651d5f676e0807665fc
656,314
def get_items(request, client): """ Get items using the request with the given parameters """ # query results result = client.quick_search(request) # get result pages items_pages = [page.get() for page in result.iter(None)] # get each single item return [item ...
f8b15e7d3f63cb4f1e42bfb15850f07d35fc6fe0
656,320
def split_list(values, split_string=","): """ Convert a delimited string to a list. Arguments values -- a string to split split_string -- the token to use for splitting values """ return [value.strip() for value in values.split(split_string)]
8f0aa4676473d35f84a4ef1b6c7428b482f938d0
656,322
import hashlib def md5(filename: str) -> str: """ Given a filename produce an md5 hash of the contents. >>> import tempfile, os >>> f = tempfile.NamedTemporaryFile(delete=False) >>> f.write(b'Hello Wirld!') 12 >>> f.close() >>> md5(f.name) '997c62b6afe9712cad3baffb49cb8c8a' >>>...
6a71e03bc64d22281c9daf00100d04ad51993ca7
656,323
import math def scale_value( value: float, input_lower: float, input_upper: float, output_lower: float, output_upper: float, exponent: float = 1, ) -> float: """Scales a value based on the input range and output range. For example, to scale a joystick throttle (1 to -1) to 0-1, we woul...
3592c0072c25a246e80fc9d5807482eb3ee456b3
656,324
def user_select_csys(client, file_=None, max_=None): """Prompt the user to select one or more coordinate systems. and return their selections. Args: client (obj): creopyson Client. `file_` (str, optional): File name. Defaults is the currently active mode...
2cacfb6c51d74b78d7da6b4d04b450375bc2457a
656,326
def copy_image_info(reference, target): """ Copy origin, direction, and spacing from one antsImage to another ANTsR function: `antsCopyImageInfo` Arguments --------- reference : ANTsImage Image to get values from. target : ANTsImAGE Image to copy values to Returns ...
113b49fe9a1b88baf7b571a275278d802a45cf20
656,327
def get_task_segments(workflow): """ Returns a dict that has the corresponding segment for each task. Segments are zero-based numbered :param workflow: :return: """ visited = dict() segment = dict() def get_segment(task): """ Calculates recursively the depth of the w...
4c39d8d53931139693799133e7ca59b0decf03ec
656,328
def get_join_parameters(join_kwargs): """ Convenience function to determine the columns to join the right and left DataFrames on, as well as any suffixes for the columns. """ by = join_kwargs.get("by", None) suffixes = join_kwargs.get("suffixes", ("_x", "_y")) if isinstance(by, tuple): ...
5410593f84ff3b43dcc169e9c7bd81839164c728
656,329
def function_sync(from_fun, to_fun): """ Copy name and documentation from one function to another. This function accepts two functional arguments, ``from_fun`` and ``to_fun``, and copies the function name and documentation string from the first to the second, returning the second. This is useful wh...
b70a5b264d6028a8389ca5f952e31213cc6917f8
656,330
def daily_profit(daily_mined: float, xmr_price: float, kwh: float, kwh_cost: float, pool_fee: float, precision: int) -> float: """ Computes how much money you gain after paying the daily mining expense. Formula: (daily_income - daily_electricity_cost) * (100% - pool_fee) :param daily_mined: Float. Amou...
6f4cbc1ff857948e3a53ea3899d424f5cc45dee1
656,333
def Re(F_mass, z_way, d_inner, n_pipe, mu_mix): """ Calculates the Reynold criterion. Parameters ---------- F_mass : float The mass flow rate of feed [kg/s] z_way : float The number of ways in heat exchanger [dimensionless] d_inner : float The diametr of inner pipe, [...
82e0128877c45dce27c7124f0fd4ac51cf3da99c
656,339
import re def snake(string): """Convert string to snake case Implementation must be consistent with tf.Module's camel_to_snake in github.com/tensorflow/tensorflow/blob/master/tensorflow/python/module/module.py """ return re.sub(r"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))", r"_\1", string).lower()
1d434ddd1bdaff54b8a418e830d9110028e1985b
656,340
def log_metrics(metrics, time, task_id, acc_db, loss_db): """ Log accuracy and loss at different times of training """ print('epoch {}, task:{}, metrics: {}'.format(time, task_id, metrics)) # log to db acc = metrics['accuracy'] loss = metrics['loss'] loss_db[task_id][time-1] = loss acc_db[task_id][time-1] = ac...
968444fa87b435391c0aba6d47e45486fa963f50
656,341
import functools def list_generalizer(f): """ A decorator that makes a function work for either a single object or a list of objects by calling the function on each element Parameters ---------- :param f: the function to decorate, of the form f(data, *args, **kwargs). Returns -------...
8b4e5cf8371a3ee1b8d02a1066e269941874c632
656,345
import json def get_target_names(json_label_decode): """Get encode of label Args: json_label_decode (string): path to json file Returns: [dict] encode of label """ if json_label_decode: with open(json_label_decode) as f: label_decode = json.load(f) t...
556dc3837fea9271b886ebcf02d6c6323061405c
656,346
import hashlib def hash256(string): """ Create a hash from a string """ grinder = hashlib.sha256() grinder.update(string.encode()) return grinder.hexdigest()
7409e5053a3ee61f534ec05edfffaf63bd6ca3e6
656,348
import re def config_attrs(config): """Returns config attributes from a Config object""" p = re.compile('^[A-Z_]+$') return filter(lambda attr: bool(p.match(attr)), dir(config))
21fc542909b16a587db04e990af8e5bc3177c93f
656,350
import logging def _get_sac_origin(tr): """ Get the origin time of an event trace in sac format. :param tr: A event trace :return origin: origin time of an event .. Note:: The trace should be sac formatted. """ try: origin = tr.stats.starttime - tr.stats.sac.b + tr.stats...
5a3709cc00e909bb5b9e088e9b46dc6ea00c0001
656,353
def word_count(phrase): """ Count occurrences of each word in a phrase excluding punctuations""" punctuations = '''!()-[]{};:"\<>./?@#$%^&*~''' counts = dict() no_punct = "" for char in phrase: if char not in punctuations: no_punct = no_punct + char no_punct = no_punct.repla...
b2ba2751b793da2b5eacb22eae49899bec6479d6
656,362
def renew_order(order, icon): """Returns the new order with the contracted indices removed from it.""" return [i for i in order if i not in icon]
b29b23ea6b1664639586376ba83efc08ba8465a1
656,363
def gcd(x, y): """Calculate greatest common divisor of x and y.""" if not y: return x if x % y == 0: return y return gcd(y, x % y)
7346ba80d4fa19b1c46a66b413d1fd08e10fc2dd
656,364
def resource_wrapper(data): """Wrap the data with the resource wrapper used by CAI. Args: data (dict): The resource data. Returns: dict: Resource data wrapped by a resource wrapper. """ return { 'version': 'v1', 'discovery_document_uri': None, 'discovery_nam...
e3606fd7d66fa1a54ba02a3ee0b6c1c3ba8a9ae0
656,365
def exists(item, playlist): """Return a boolean True if playlist contains item. False otherwise. """ for i in playlist: #for each item in playlist if i.song_id == item.song_id: #check if the primary key is equal return True return False
36fcff366499aff7532e5d3bd16826b9e91f28f6
656,366
def mask_val(val, width): """mask a value to width bits""" return val & ((1 << width) - 1)
87f70dd97d50f767604022c50223350db88966fb
656,367
def get_length(dna): """ (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 """ return len(dna)
bb4c724d1c8793fd2ce9699c5540c49db0cd226d
656,368
import re def get_function_name(line): """Get name of a function.""" func_name = re.split(r"\(", line)[0] func_name = re.split(r" ", func_name)[-1] func_name = re.sub(r"(\*|\+|\-)", r"", func_name) return func_name
f5b7048755000929822a6d97577dc872a4d4e966
656,369
import requests import json def get_swagger_dict(api_url: str) -> dict: """ Gets the lusid.json swagger file Parameters ---------- api_url : str The base api url for the LUSID instance Returns ------- dict The swagger file as a dictionary """ swagger_path = "...
c6b29a68f1fc35ed870187d81efff8a22df76f9b
656,370
def calculate_error(source, target, base, alpha): """ Calculates error for a given source/target/base colors and alpha """ alpha /= 255.0 alpha_inverse = 1.0 - alpha return abs(target - alpha * source - alpha_inverse * base)
1c8286b2634cfcb0381ed146a6e15780f2e33386
656,371
def cal_num_procs(world_size: int, gnx: int, gny: int): """Calculate the number of MPI ranks in x and y directions based on the number of cells. Arguments --------- world_size : int Total number of MPI ranks. gnx, gny : int Number of cells globally. Retunrs ------- pnx,...
24e8451b3aca642167a761737989e63baeb2bb19
656,372
def _rshift_nearest(x, shift): """Given an integer x and a nonnegative integer shift, return closest integer to x / 2**shift; use round-to-even in case of a tie. """ b, q = 1 << shift, x >> shift return q + (2 * (x & b - 1) + (q & 1) > b)
cb6fa2a2d65367766adab37e05534990dfe3b2a6
656,373
from typing import Tuple def parse_path(path: str) -> Tuple[str, str]: """Split a full S3 path in bucket and key strings. 's3://bucket/key' -> ('bucket', 'key') Parameters ---------- path : str S3 path (e.g. s3://bucket/key). Returns ------- Tuple[str, str] Tuple of ...
a62ae1bd30eaa74deb97e4ea4fe91aca41ebe730
656,374
def is_cli_tool(req): """ Returns true if the user-agent looks like curl or wget """ user_agent = req.headers.get_first("User-Agent", "") if user_agent.startswith('curl'): return True if user_agent.startswith('Wget'): return True return False
22aa21ff5c2a2f05bdc01bcf6652364fb7faba12
656,378
def valid_odd_size(size): """ Validates that a kernel shape is of odd ints and of with 2 dimensions :param size: the shape (size) to be checked :return: False if size is invalid """ if type(size) not in (list, tuple): return False if len(size) != 2: return False if size[...
5e1b1e6f6655f9732a80b97a01cd588b93e6e5f2
656,380
def make_url(photo: dict): """ Get download URL for photo :param photo: photo data as returned from API """ return photo["baseUrl"] + "=d"
532444d58af34d8911e7a303341f7f02d29c27a2
656,388
def adjacent_vectors(vector_field, neighbors): """ Query the vectors neighboring a vector field entry. """ return [vector_field.vector(key) for key in neighbors]
b43e95bfd05493b8a36c65b80461a671c6aef1ab
656,389
def dictfetchall(cursor) -> list: """ 從 cursor 獲取的資料行轉換成元素為字典的列表 [ { 'column1': '...', 'column2': '...', ...': '...', }, { 'column1': '...', 'column2': '...', '...': '...', }, ] """ columns = ...
1e0a2f7fa7a0ff7242906ec62ac738ba92b52257
656,390
def split_and_strip(sep, s): """ Split input `s` by separator `sep`, strip each output segment with empty segment dropped. """ return [y for y in (x.strip() for x in s.split(sep)) if len(y) > 0]
366dcd401ca6e3d953a75e321388d2b97465bfb5
656,392
def build_post_data_from_object(model, obj, ignore=["id"]): """ Build a payload suitable to a POST request from given object data. Arguments: model (django.db.models.Model): A model object used to find object attributes to extract values. obj (object): A instance of given model ...
77bf514a831502b930b073f2e71c1fe39e128a42
656,395
def full_name(user): """ returns users full name. Args: user (User): user object. Returns: str: full name from profile. """ if not user or not user.profile: return None profile = user.profile first = profile.first_name or profile.user.username last = " {}"....
96533a87b5bbb99f73db104f72e2b99d707f7e81
656,396
def piecewise_compare(a, b): """ Check if the two sequences are identical regardless of ordering """ return sorted(a) == sorted(b)
40316e161846e29063b0db2076ef74c3be4c72d6
656,397
def patch_many(mocker): """ Makes patching many attributes of the same object simpler """ def patch_many(item, attributes, autospec=True, **kwargs): for attribute in attributes: mocker.patch.object(item, attribute, autospec=autospec, **kwargs) return patch_many
f955c5b1c95993c035ae143e78f780ed43a8c439
656,399
def make_readable_pythonic(value: int) -> str: """Make readable time (pythonic). Examples: >>> assert make_readable(359999) == "99:59:59" """ return f"{value / 3600:02d}:{value / 60 % 60:02d}:{value % 60:02d}"
a091ef99b94cb2b4c3e0d657805a9e7b6418dd3a
656,404
def _get_index(x, x_levels): """Finds element in list and returns index. Parameters ---------- x: float Element to be searched. x_levels: list List for searching. Returns ------- i: int Index for the value. """ for i, value in enumerate(x_levels): ...
6f4e7c590ab41357faa1125485cc74c9409dd0c6
656,405
import torch def custom_collate_fn(batch): """ Since all images might have different number of BBoxes, to use batch_size > 1, custom collate_fn has to be created that creates a batch Args: batch: list of N=`batch_size` tuples. Example [(img_1, bboxes_1, ci_1, labels_1), ..., (img_N, bboxe...
885e729aeb3a5fb55866cdde73e3e5f2025340b0
656,408
def ferc1_etl_parameters(etl_settings): """Read ferc1_to_sqlite parameters out of test settings dictionary.""" return etl_settings.ferc1_to_sqlite_settings
8c1593c9b504efda99759e6fff14528876162c47
656,409
def table2tsv(table): """Represent a list of lists of strings (a "table") as a "tsv" (tab separated value) string. """ return '\n'.join(['\t'.join(row) for row in table])
77367210fd1fbdbab1bc18b3eb776f24de4430ae
656,414
def ashift(num1, num2): """ ASHIFT num1 num2 outputs ``num1`` arithmetic-shifted to the left by ``num2`` bits. If num2 is negative, the shift is to the right with sign extension. The inputs must be integers. """ return num1 >> num2
7d4f2c03b6d124770739fc49b4fef951d0d6d795
656,420
def tuples_sorted_by_keys(adict): """Return list of (key, value) pairs of @adict sorted by keys.""" return [(key, adict[key]) for key in sorted(adict.keys())]
66b1aa62e5e09fa7c269ae3463c583683d230b22
656,423
def index_of(seq, value, from_index=0): """ Description ---------- Return the index of a value in a sequence.\n Returns -1 if the value was not found. Parameters ---------- seq : (list or tuple or string) - sequence to iterate\n value: any - value to search for\n from_index : in...
b5af32b3dafe51663de372836d4fbd4e582b2e32
656,424
def coverage(pileup): """Returns the sum of nucleotide reads (no gap or N) per position""" return pileup.sum(axis=0)[:4, :].sum(axis=0)
1092bb1324f6df471a76eb44354f71d58d99137a
656,426
def split_phases(df): """ Separates DataFrame into groups by unique values of a column 'Phase', and returns a tuple of DataFrames. """ return( tuple([df.groupby('Phase').get_group(p) for p in df.Phase.unique()]) )
1774db1d8708e8d17a88ed9586234018ba701b7f
656,430
import re def FindMethods(section): """Spin through the 'method code index' section and extract all method signatures. When found, they are added to a result list.""" # Match lines like: # |[abcd] com/example/app/Class.method:(args)return # capturing the method signature methodPa...
f98c4afe63267a478330675fc7aa58bd68381ed8
656,432
def get_event_delete_role(bot, guild): """Return the event delete role, if it exists""" result = bot.db.get_event_delete_role_id(guild.id) if result: for role in guild.roles: if role.id == result.get('event_delete_role_id'): return role
ec3e8fde7cf93037004633e1558307c482b53ac8
656,433
def digitalSum(n): """Calculates the sum of the digits of `n`.""" if n < 10: return n else: return n % 10 + digitalSum(n // 10)
c7cc4ed54c61c786782669fce4f8cac943866713
656,438
def get_graph_last_edge(g, filter_out_types=set()): """ Get the last edge of the graph or an empty edge if there is non :param g: a graph as a dictionary :param filter_out_types: a set fo edge types to filter out, if not empty the last edge of the specified type is returned :return: an edge as a di...
c2ad797e806ec3542708b916057968755de50d2b
656,440
def to_number(s): """ Convert a string to a number. If unsuccessful, return the de-blanked string. """ ret = s # remove single quotes if "'" in ret: ret = ret.strip("'").strip() # try converting to booleans / None if ret == 'True': return True elif ret == 'False': ...
deb9c134965c06f0c16ec522996b507e8c7370b8
656,441
import json def get_cat_to_name_mapping(file): """ Read the json file provided and return a dictionary containing the mapping between categories and label names :param file: path to JSON file containing mapping between categories and label names :return cat_to_name: dictionary containing mapping betw...
0801f4b4ade24ed897007747c98493ad97538f8b
656,442
def _format_time(total_seconds): """Format a time interval in seconds as a colon-delimited string [h:]m:s""" total_mins, seconds = divmod(int(total_seconds), 60) hours, mins = divmod(total_mins, 60) if hours != 0: return f"{hours:d}:{mins:02d}:{seconds:02d}" else: return f"{mins:02d}...
5d36548e7dc0ec5bb3481d21131a8e0611b6c1cb
656,444
def split_into_quadrants(m): """ Split a nxn matrix into quadrants. Given A, returns A11, A12, A21, and A22. """ mid = m.shape[0] // 2 return m[:mid:, :mid:], m[:mid:, mid:], m[mid:, :mid], m[mid:, mid:]
982416f7584440a2b8bb73b40b1c7fed5ca138f3
656,446
def compreso(num, low, high): """ checks whether or not a number is between low and high """ return num>=low and num<=high
2b63cf812ce6b1222693013cadf1e382e7359313
656,447
def print_gains(odrv, axis): """ Prints gains. Also returns them. """ axis_config = axis.controller.config # shorten that print("Position:", axis_config.pos_gain ) print("Velocity:", axis_config.vel_gain) print("Velocity Integrator:", axis_config.vel_integrator_gain) return axis_config....
09ede6acd6133c9b43c13395b7d213eaeb7ae879
656,448
def categorize_local_files(manifest): """Categorize the files in the lambda function's directory into two bins: python files and other files""" python = [] other = [] for filename in manifest.basedir.iterdir(): path = filename.relative_to(manifest.basedir) if path.suffix == '.py': ...
1de437a42500ba99515eb265438c41914326258d
656,449
def read_paralogs(paralogs_file): """Read list of paralogs.""" if paralogs_file is None: # then nothing to return return set() f = open(paralogs_file, "r") paralogs = set(x.rstrip() for x in f.readlines()) f.close() return paralogs
c74d8f77fe59c411dc38c3cb31c32caf5f04e726
656,452
def seconds_into_day(time): """Takes a time in fractional days and returns number of seconds since the start of the current day. Parameters ---------- time: float The time as a float. Returns ------- int The day's duration in seconds. """ return(int(round(86400....
38927724e4a27a854bfda5aa6ef91498dcc5d35c
656,454