content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def stringToInt(message): """ Convert input string message into an integer """ string_to_binary = message.encode('utf8') return int.from_bytes(string_to_binary, byteorder='big', signed=False)
dc98b5630120b0c8857cd8f07a55b29b964e1334
661,736
def create_calibration_controls(): """Create a dictionary containing default chanin calibration controls The fields are T: Atmospheric phase G: Electronic gains P: Polarisation B: Bandpass I: Ionosphere Therefore first get this default dictionary and then adjust pa...
eef5e8916acde2912414600b5ba6bf4dabffcb0b
661,737
def Arn(key): """Get the Arn attribute of the given template resource""" return { 'Fn::GetAtt': [key, 'Arn']}
d92f92789171c005490b4309fd1fc6570c1a0b79
661,738
def _verify_and_make_set(var, allowed_values): """ Turn a string or a list into a set so we can use set operations """ if isinstance(var, str): var = set([var]) elif isinstance(var, list): var = set(var) elif isinstance(var, set): pass else: raise ValueError("...
c2574a7298e3aa2c22cd5dff97b7a8d39e9bb1ed
661,740
from typing import Type from typing import Set def _all_subclasses_of(cls: Type) -> Set[Type]: """ All subclasses of cls, including non-direct ones (child of child of ...). """ direct_subclasses = set(cls.__subclasses__()) return direct_subclasses.union( s for d in direct_subclasses for s ...
077908503def08cf519056ca0abb09f5916804db
661,741
import os def create_fallback_destination_file_name( source_file_name, destination_file_format): """ If a destination_file_name is not provided, uses the source_file_name with a removal of the compression extension. """ format_extensions = { "tsv": ".tsv", "psv": ".psv", ...
e92790a2b868156999c70a328b806923b4c61920
661,742
import argparse def _parse_args() -> argparse.Namespace: """Parse command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "--data", type=str, default="baseline", help="Provide the subdirectory name for the training/split datasets.", ) pa...
ded592923e5d892a01b3be3398bfb902a9e2cdd7
661,743
def area_ratio_explicit(Mach): """isentropic relationship between area ratio and Mach number""" gamma = 1.4 gamma_p_1 = gamma + 1 gamma_m_1 = gamma - 1 exponent = gamma_p_1 / (2 * gamma_m_1) return (gamma_p_1 / 2.) ** -exponent * ((1 + gamma_m_1 / 2. * Mach ** 2) ** exponent) / Mach
e03940a6d2c8fa75f7fe1dd1509de90cb51f4bc1
661,744
def toSingleArray(sortedTimelessData, index): """convert a index of data to a single array Arguments: sortedTimelessData {list} -- a list sorted and removed lowest time from all values index {int} -- the index of the list to convert """ tempArray = [] for i in range(len(...
9c8888accc062e865d213d35fb2ed86ebfebcf81
661,745
def HandleNearestNeighborQuery(locale_finder, lat, lon): """Verifies passed arguments and issues a nearest neighbor lookup. Args: lat (float): Latitude of interest. lon (float): Longitude of interest. Raises: SyntaxError: If expected parameters are not provided (are None). Ret...
1316e2e0f67173a8cb1266dc33a13901eccc6328
661,746
def choose_condition(data, events, condition): """Filters out a specific condition from the data. :param data: data from which to extract conditions from :type data: numpy array :param events: event data of shape [trials x 4] :type events: numpy array :param condition: Condition to be filtered ...
8fa8cc12a11561c3a69a067b1f302dd1ccaf1b31
661,747
def add_role_owner(session, add_role_owner_payload, role_id): """Add a owner to a role""" response = session.post( "http://rbac-server:8000/api/roles/" + role_id + "/owners", json=add_role_owner_payload, ) return response
cdd1fd805db986e45605221e024db29cb58c4a96
661,748
def my_pow(x, n): """ :type x: float :type n: int :rtype: float """ if n == 0: return 1 # 0 ^ 0 = 1 if x == 0: return 0 if n < 0: x = 1 / x n = -n # bottom up res = 1 while n > 0: # pow(x, n) = pow(x * x, n // 2) * x if n is odd ...
df3c9300b40b3add31b8dc45c38e58dbef01b047
661,749
def get_user_id(): """Dummy function that returns a (constant) user ID""" return "user123456"
c59b37468c71ac47847d57a7f6e61bd34ec61c13
661,750
def get_attributes(obj): """ Returns all attributes of an object, excluding those that start with an underscore. Args: obj: the object Returns: A dictionary of attributes """ return { key: getattr(obj, key) if not key.startswith("_") else None for key in di...
1b6e39e2d97e50254e67bcbdcc6cd4121b38e370
661,751
import functools import operator def product(xs): """ product :: Num a => [a] -> a The product function computes the product of a finite list of numbers. """ return functools.reduce(operator.mul, xs, 1)
01664f7d4ecdf088a6e996120162ebf6f5e74768
661,752
def size_pt(altitude, min_alt, max_alt): """ Gives point size depending on its altitude. Higher(Lower) altitude = smaller(bigger) point """ coefa = (50/( min_alt - max_alt)) coefb = 60 - (coefa * min_alt) return coefa * altitude + coefb
91ec203ff1d2b0b88a1bcb70e6c47ca95b04e07c
661,753
def in_slots(obj, key, default=False): """ Returns true if key exists in obj.__slots__; false if not in. If obj.__slots__ is absent, return default """ return (key in obj.__slots__) if getattr(obj, '__slots__', None) else default
c64473a323302eacefcf211c1114686ef1feec2d
661,754
import os def get_enabled_and_disabled_transforms(): """ :return: tuple of lists with force enabled and disabled id of transformations. """ disabled_transforms = os.environ['MO_DISABLED_TRANSFORMS'] if 'MO_DISABLED_TRANSFORMS' in os.environ else '' enabled_transforms = os.environ['MO_ENABLED_TRANS...
041264fb1e904b9083fd2426903e3ea02a3ef9e9
661,755
import torch def vad_threshold(frames: torch.Tensor, threshold=35.) -> torch.Tensor: """ threshold : scalar in range [30,50] """ energies = 20 * torch.log10(torch.std(frames, 1) + 1e-10) max_energy = torch.max(energies) return torch.logical_and(energies > max_energy - threshold, energies > -75)
de7044d3f7c9016d2ad918f8825946ac387f5071
661,756
def _equal_room_tp(room, target): """ NOTE: Ensure <target> is always from <ALLOWED_TARGET_ROOM_TYPES>!!!! DO NOT swap the order of arguments """ room = room.lower() target = target.lower() return (room == target) or \ ((target == 'bathroom') and (room == 'toilet')) or \ ...
b9c88fb7390b22f6fd5a2fe8b3e65a8c190246a4
661,757
def get_color(node, color_map): """ Gets a color for a node from the color map Parameters -------------- node Node color_map Color map """ if node in color_map: return color_map[node] return "black"
3f601fddcb31255bf61c6ac2a61c890a658b3d13
661,758
def CallCreateInstances(holder, igm_ref, per_instance_config_message): """Make CreateInstances API call using the given per-instance config messages.""" messages = holder.client.messages if igm_ref.Collection() == 'compute.instanceGroupManagers': service = holder.client.apitools_client.instanceGroupManagers ...
adcd775eade805a223f6853b2f09c0cf080e215f
661,759
def test_appender(node, real_appender): """basically a decorator for node.append() that prints out incoming messages for each node when in test mode. Attached to append() only in test mode so we won't pay performance penalty in the normal case """ def _test_appender(msg): print(msg.depth*2*"...
d1e010dc1b17e77b18885df03ebbf7c4ef8a37b5
661,760
def format_rp_labels(rp_label: str) -> str: """ Helper function for formatting the RP label. Args: rp_label: Reaction plane orientation label to be formatted. Returns: Properly formatted RP label. """ # Replace "_" with "-" return rp_label.replace("_", "-").capitalize()
6a34102be81ee0a167aa0a24acbe2c6e84b9caa4
661,761
def address_string(content, labels=False): """content is a dict of the form:: {u'private': [{u'version': 4, u'addr': u'10.35.23.30', u'OS-EXT-IPS:kind':u'fixed'}, {u'version': 4, u'addr': u'198.202.120.194', ...
5356b946fbcfe88bcc88b5a0bf62038481eed1bf
661,762
def pad_sentence_batch(sentence_batch, pad_int): """Pad sentences with <PAD> so that each sentence of a batch has the same length""" max_sentence = max([len(sentence) for sentence in sentence_batch]) return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch]
fe586a7cd3c3f71bae7b8c753bd8be917855c15d
661,764
def check_is_video(file_name): """ Ensures passed file inputs are of recognized media format. """ formats = ['flv', 'mp4', 'avi', 'mp3', 'flaac'] return any([extension for extension in formats if file_name.endswith(extension)])
645edcf7b440b26c7f1982a38d40c3dd94baf2f5
661,766
def lr_decay_freeze_fn(param, decay_rate, n_layers, server_layers): """lr_decay_freeze_fn """ if "encoder_layer" in param.name and param.name.index("encoder_layer") == 0: depth = int(param.name.split("_")[2]) + 1 decay_rate = 0 elif "server_post_encoder_layer" in param.name or "sharing_t...
7a6187b34b4179febd5e1c74ca21cb5d1b857a5a
661,767
def FOREVER(*_, **__): """Will always return False (continue).""" return False
8da7ecdfc4af34f1c7a2f5351ffd76f205d61d71
661,768
def c(field): """Remove " from field""" return field.replace('"', "")
2441c9df35d43909aa1a189e6a349888c00c7483
661,769
def gather_possible_containers(the_rules, bag_color="shiny gold"): """ evaluate recursively how many continers can possibly contain a bag_color colored bag """ containers_found = [] for rule in the_rules: for child in rule['children']: if child['color'] == bag_color and rule['col...
2956dd86a3a5de40872e0ffba511bb293ff5888a
661,770
def find(strng, ch): """ Find and return the index of ch in strng. Return -1 if ch does not occur in strng. """ ix = 0 while ix < len(strng): if strng[ix] == ch: return ix ix += 1 return -1
8d34718b65e951e3ea957406bab27270211557df
661,771
def wrap(seq, bases=60): """ Print wrapped sequence. Args: seq (str): Nucleotide sequence bases (int): Number of bases to include on each line. """ count = 0 ret = '' for i in seq: if count >= bases: ret = ret + '\n' count = 0 ret = re...
2777fc5c42d36a18dda28966a4db300a212c2a60
661,772
def filter_octects(ip_address): """functional approach filters the list""" terms = ip_address.split(".") if not len([*filter(lambda octet: octet.isdecimal(), terms)])==4: return False elif not len([*filter(lambda octet: 0<=int(octet)<=255, terms)])==4: return False else: return True
03d47e48169fd3b918e3815a90979d694eb4deb2
661,773
from typing import Any def is_shutdown_time_int(hour: Any, minute: Any) -> bool: """Check if shutdown time are numbers. Args: hour (Any): hour according to user config minute (Any): minute according to user config Returns: bool: True if both are numbers """ return type(h...
767816d79c73bda92ad2bd9d92426073f9e6c18e
661,774
def convert(list): """ Converts list to categories. """ categories = dict() for dict_row in list: try: categories[tuple(dict_row[0][0])][dict_row[1]].append(dict_row[2][0]) except KeyError: try: categories[tuple(dict_row[0][0])][dict_row[1]] = [dict_row[2][0]] ...
f026f6195d75f2cc2c7c981c531cbe152ef69788
661,775
def get_next_one(wint): """ returns next generation as list of rows where each row contain string of 0|1 characters :param wint array of integers 0|1 older generation :retval next_one list of rows next generation """ next_one = [] rows = len(wint) ...
737481b356303e814b1b6bbf25622e436cdf38d2
661,777
def transform_fs_access_output(result): """ Transform to convert SDK output into a form that is more readily usable by the CLI and tools such as jpterm. """ new_result = {} useful_keys = ['acl', 'group', 'owner', 'permissions'] for key in useful_keys: new_result[key] = result[key] retur...
7cbd87d49c1c1781d6de847ce3c0ccbb7b697f2a
661,778
import math def equal_devision(length, div_num): """ # 概要 length を div_num で分割する。 端数が出た場合は誤差拡散法を使って上手い具合に分散させる。 """ base = length / div_num ret_array = [base for x in range(div_num)] # 誤差拡散法を使った辻褄合わせを適用 # ------------------------------------------- diff = 0 for idx in rang...
a2865942d4a630d775c49a600a2835c623da1419
661,779
import numbers def validate_int(x, name, minimum=None, maximum=None) -> int: """Validate integer function parameters. Parameters ---------- x : object Object to validate as an int. name : str Name of the function parameter. minimum : int, optional Minimum value x can t...
f3d56cc494312873d038c92b2f12a21a0a0da1cd
661,782
import re def get_columns_matching(dataframe, pattern, regex=False): """ Returns the columns containing pattern (or satisfying the regex pattern, if regex=True). :param dataframe: Dataframe whose columns are being tested :param pattern: String to test columns for :param regex: If True, then check...
612efab6fbd17d42307f64451a0bfe6eca7f45be
661,783
def allow_state(state): """Returns True if the state code is for a queued or running job.""" return state in ["CG", "PD", "R", "RD", "RS", "SO"]
22c42e07c4169db03033fd899b7ec9fd2fa048fa
661,784
def isinAngleLimits(angle, min_angle, max_angle): """Check if an angle value is between min and max angles in degrees""" if (min_angle <= angle <= max_angle) or (min_angle <= 180 - angle <= max_angle): return True return False
3ed0ea5857b81b1281afbb7ae1ac91b3e2eb9e1d
661,785
def say_hello(name: str) -> str: """ Greet someone in English. :param name: Name of the person to greet. :return: The greeting. """ return f"Hello {name}!"
819d4dff77813faaa4a852b0d2d4cf9d9020f31e
661,786
import csv import json def parse_tsv(data_path, intent_set=[], slot_set=["O"], istrain=True): """ Input: data_path: the path of data intent_set: set of intent (empty if it is train data) slot_set: set of slot type (empty if it is train data) Output: data_tsv: {"text": [[to...
88afe7407f74e2047e469b81fc40fad45c998e3a
661,787
import re def x_fuzzily_contains_y(x:str, y:str): """ checks if all parts of x are somewhat in y """ if y is None: return False if x is None: return False xx = x.lower().replace('&amp;', '&').replace('&#39;',"'").replace('&quot;','"') # split on non-word characters of ...
8a1d76372ff92b31fb480a094519803fe36ac85d
661,788
def replace(s: str): """ Replace blank to "%20". Parameters ---------- s: str given string Returns ------- out: str return string """ if not s: return s num_blank = 0 for i in s: if i == " ": num_blank += 1 raw_len = len(s...
632c9096a93d5cc3ef08ce4fbf4d699c7fc7c2fc
661,789
import argparse def _define_flags(): """Defines an `ArgumentParser` for command-line flags used by this program.""" flags = argparse.ArgumentParser( description='Compile binary data from "assembly" files.') flags.add_argument('assembly_files', type=str, nargs='+', help=( '"Assembly" files of the ki...
56746bb01d1d4ef7c8bb0c515b698deefde0a128
661,790
def is_same_domain(host, pattern): """ Return ``True`` if the host is either an exact match or a match to the wildcard pattern. Any pattern beginning with a period matches a domain and all of its subdomains. (e.g. ``.example.com`` matches ``example.com`` and ``foo.example.com``). Anything else ...
8581fd2d46a87d5533a017dbaa6a74bf5d98e5fa
661,791
def is_float(s): """ :param s: s is a string :return: True if string s can be cast to a float """ try: x = float(s) return True except: return False
4b98a6a8694868528da801d11a1d93103b97e2b1
661,792
def get_type( type_name ): """Return the type of the given node type string (without *? modifier).""" if type_name[ -1 ] == '*' or type_name[ -1 ] == '?': return type_name[ : -1 ] return type_name
b6fc297d16d704a67d094b1f7e40c0bec51ce049
661,793
def get_container_tool_map(options): """ convenience function to parse the above _container options into a dictionary """ cmap = [dict(), options.container] cmap[0]["vg"] = options.vg_docker cmap[0]["bcftools"] = options.bcftools_docker cmap[0]["tabix"] = options.tabix_docker cmap[0]["bgzip"] =...
651e74d6ec25545895eb0c202f6b9a2e26df73ed
661,794
def char_age(p0=1.0, p1=1e-12): """ Accepts a spin period (in s) and spin period derivative (in s/s) and returns the characteristic age. Units: years. """ tau = p0 / (2 * p1) return tau / (60 * 60 * 24 * 365)
70d7d124557ee83c1c56ef529b146c272c066870
661,795
def check_dermoscopic(meta): """Checking if a image is acquired through dermoscopy by ISIC's API. Parameter: meta: The metadata of the image getting through the API Return: True if the image is acquired through dermoscopy, False if it isn't """ if "image_type" not in meta["meta"]["acquisiti...
c1e2e31986090a5744fd283b6b702e4beb9b310d
661,796
def validate_business_payload(new_payload): """ this method validate the business payload """ if len(new_payload['business_name']) > 50: return {'message': 'name is too long'}, 400 if len(new_payload['category']) > 50: return {'message': 'body is too long'}, 400 if len(new_pa...
8c6e36c3433aaec1f51dacc94030035786ae46e5
661,798
def getattr_chained(obj, methods): """Return value from chained method calls - eg a = 'A Big Thing' > getattr_chained(a, 'str.lower') """ try: for method in methods.split('.'): obj = getattr(obj, method)() return obj except Exception: return None
f9a02211eb509d9e41939d6a9d29bd3bf96fbaf9
661,799
def tuple_mul(tuple_item, num): """Perform element-wise multiplication by a scaler for a tuple or a number.""" if not isinstance(tuple_item, tuple): return tuple_item * num List = [] for item in tuple_item: if item is not None: List.append(item * num) else: ...
c9eef7ded731065f322752eb498868934a2ceda2
661,801
import uuid import itertools def convert_secret_key(config_secret_key): """ Converts the secret key from the app config into a secret key that is usable by AES Cipher. """ secret_key = None # First try parsing the key as an int. try: big_int = int(config_secret_key) secret_key...
efee7a6932aeb60924b2ec9ef51bb80790a7f102
661,802
def _clean_job(job): """Remove and key/value pairs from job where the key is prefixed by an underscore. Args: job (JobState): The job to clean. Returns: JobState with all underscore-prefixed keys removed. """ for key in job.keys(): if key.startswith('_'): job....
e793f8b5626f64ee95a75655bbdba48f3fb9440e
661,803
def capitalization_check(text_in: str) -> str: """ If all letters are capitalized, switch to lower case as Pint is case sensitive. Parameters ---------- text_in Returns ------- """ if text_in.isupper() and sum(char.isalpha() for char in text_in) > 2: # 2 is used to avoid single ...
9efa2d76620bde27e09629f2382aca64b806b0cb
661,805
def _tensor_to_list_of_channel_tensors(img): """Converts a tensor with dimensions of HWC or BHWC to a list of channels.""" if len(img.shape) == 3: # HWC. img_list = [img[:, :, c] for c in range(img.shape[-1])] elif len(img.shape) == 4: # BHWC. img_list = [img[:, :, :, c] for c in range(img.shape[-1])] ...
b257814bb8b10aec8decd3934315105f635a6dae
661,806
def name_without_commas(name): """ Takes a name formatted as "[LastNames], [FirstNames]" and returns it formatted as "[FirstNames] [LastNames]". If a name without commas is passed it is returned unchanged. """ if name and "," in name: name_parts = name.split(",") if len(name_pa...
19cec9abbef59fee3010fb5819febe28edf3fbf5
661,807
def nullcnt(xs): """Counts null values in Graphite query result""" return len([x for x in xs if x is None])
140d97d4748b005ace9b162b539b80e567f71b15
661,808
import inspect def methodName() -> str: """Returns string containing name of the calling method.""" return inspect.stack()[1][3]
df66e422d387ca398b1d7a0ddefe168318663bb0
661,809
def is_proto_range(proto): """protocol range is 0-255""" try: val_int = int(proto) if val_int < 0 or val_int > 255: return False except Exception: return False return True
ccf05199a009a717e3de047bcf6ff00000e728ac
661,810
def _dirname_map_fn(f): """Returns the dir name of a file. This function is intended to be used as a mapping function for file passed into `Args.add`. Args: f: The file. Returns: The dirname of the file. """ return f.dirname
4d2d54ff3395dedf571a9e24dbd0cbd3a03fdf8e
661,811
def indent(string, prefix=' '): """ Indent every line of this string. """ return ''.join('%s%s\n' % (prefix, s) for s in string.split('\n'))
9d6ed0fc3d19f2e59b8d34c9f98cbc011c2edd07
661,812
import pandas def read_gff3_using_pandas( file ): """Helper function to read the given GFF3 file into a dataframe, without any postprocessing.""" result = pandas.read_table( file, comment = '#', names = [ 'seqid', 'source', 'type', 'start', 'end', 'score', 'strand', 'phase', 'attribute...
86d8e8ebfb9799e344e664bba86e001e1b363a7e
661,814
def get_dtype(parameter_value): """Get the TopoFlow data type of a parameter. Parameters ---------- parameter_value : object An object, a scalar. """ try: float(parameter_value) except ValueError: return 'string' else: return 'float'
c0e9831c3349d697d5ca0163babd13a2e46bd244
661,815
import hashlib def hash_file(file): """ Computes the SHA-256 hash of the file file - The file to hash """ hasher = hashlib.sha256() with open(file, 'rb') as f: for block in iter(lambda: f.read(1024), b''): hasher.update(block) return hasher.digest()
6b3c80feca43129bc09f6a9043dbe25f39cb3e04
661,816
def report(batch_size, epochs, lr, resize, model_name, back_bone, remark, scales): """ create the reporter dict, record important information in the experiment """ specs = {} specs['model_name'] = model_name specs['batch_size'] = batch_size specs['training_epochs'] = epochs specs['learni...
3d341c0674a092e4278aa547c12564f0d70e3505
661,818
import random def generate_gaussian_inputs(num_inputs,mean,sigma): """ randomly generate inputs from a gaussian distribution (rounded to integers). however, these values should not be too large, to avoid integer overflows.. """ values = {} for i in range(num_inputs): values["x_"+str(i)...
30271024865b20076b011b5f39c788ce91460620
661,819
def _build_node_query(lng_min, lat_min, lng_max, lat_max, where=[]): """ Internal function that build the string for a node-based OSM query. Parameters ---------- lng_min, lat_min, lng_max, lat_max : float the bounding box to search within tags : dict dictionary of key/value...
1a64a7a9fec37b3ce2b70b97d31c445f2bcf0ad1
661,821
import os import fnmatch def findfiles(dirpath, match=None): """Return a list of the files""" res = [] for f in sorted(os.listdir(dirpath)): abspath = os.path.join(dirpath, f) if os.path.isdir(abspath): res.extend(findfiles(abspath, match)) if match: if fnm...
147afdbc5c62eaa5e689612fc94320f5142febd7
661,823
import re def interpret_cv(cv_index, settings): """ Read the cv_index'th CV from settings.cvs, identify its type (distance, angle, dihedral, or differance-of-distances) and the atom indices the define it (one-indexed) and return these. This function is designed for use in the umbrella_sampling jobtyp...
01ef867caf1aa8756182dcab3a0e3bc2261cacc2
661,824
def _classifier_has(attr): """Check if we can delegate a method to the underlying classifier. First, we check the first fitted classifier if available, otherwise we check the unfitted classifier. """ return lambda estimator: ( hasattr(estimator.classifier_, attr) if hasattr(estimato...
5c676af4c121ff54bde23856a67a2adac2b7e79d
661,825
def _parent_dirs(dirs): """Returns a set of parent directories for each directory in dirs.""" return set([f.rpartition("/")[0] for f in dirs])
33254c411bad173b8b02fc444d5ca04ed8748457
661,826
import textwrap def wrap(s): """ Wrap lines of text, retaining existing newlines as paragraph markers. >>> print(wrap(lorem_ipsum)) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nos...
f77a6b98b9a5ab729245fdfd9dfa1c9c823737d4
661,827
import yaml def dumps(obj): """dump dict object into yaml stream Arguments: obj (dict) : the dict which will be dumped Returns: string : the yaml stream """ return yaml.dump(obj)
e29f383bebff1108197f9a0a1397bb7855726cd6
661,828
def cases(test_inputs): """ A decorator for passing various test cases. """ def nested_decorator(func): def wrapper(*args, **kwargs): for test_input in test_inputs: test_input = ( (test_input,) if not isinstance(test_input, tup...
6e3d1a14342a46659d488ac897349ce7079e147f
661,829
def is_string(data): """Utility method to see if data is a string.""" return isinstance(data, str)
0b60e2e766875f80d59ef57dce52a450d6a787e8
661,830
import torch def get_device(is_gpu=True, gpu_number=0): """ Set the backend for model training """ gpu_count = torch.cuda.device_count() if gpu_count < gpu_number: raise ValueError("number of cuda devices: '{}'".format(gpu_count)) else: if torch.cuda.is_available() and is_gpu:...
93c7546b87816afd00a1a82527dc35697c2e2183
661,831
def convert_cache_variables(cache_json: list) -> dict: """ Convert list of cache variables returned by server to dictonary without unnecessary information. cache_json is 'cache' object from response to 'cache' request. """ return dict((entry['key'], entry['value']) for entry in cache_json)
497a1a75efdbbe1760243b4654680e4b0c13894c
661,832
def menu_vales(request): """ Funcão que contém as configurações do menu de gerenciamento de vale do Controle de combustível. Retorna um dicionário com as configurações """ menu_buttons = [ {'link': '/patrimonio/combustivel/talao/vales/entrega-1', 'text': 'Entregar vale'}, {'link': '...
7ff76556ff85c6c4ab4c1a77514bd10f67f72c6b
661,833
def sort_dict_by_value(d): """ Returns the keys of dictionary d sorted by their values """ items=list(d.items()) backitems=[[v[1],v[0]] for v in items] backitems.sort() return [backitems[i][1] for i in range(0, len(backitems))]
7957b6abc77e29738f3aaa502857af49b7016ed1
661,834
def e(d): """Encode the given string instance using UTF-8.""" return d.encode('UTF-8')
a574fc5123ee838dfc975e3dbe3d101bfe3b5bef
661,835
def _pretty_state_identifier(state): """ returns 'off' for False and 'on' for True """ if state: return 'on' else: return 'off'
a4383b7061e2da73a6faab4819b848bc1375e884
661,838
def parent(path): """Returns the parent path""" parent = path if parent[-1] == ']' and '[' in parent: while parent[-1] != '[': parent = parent[:-1] elif '.' in parent: while parent[-1] != '.': parent = parent[:-1] else: return '' parent = parent[:-...
d87f1f70fd094abc334124f0e62e8599deb46771
661,839
async def is_in_right_combinations(combination, right_combinations): """対象のセットがいずれかのセット球(クジに使う色違いのボールのセット)のパターンを満たすか判定 :pram combination: 判定対象のセット :pram right_combinations: セット球(クジに使う色違いのボールのセット)のパターンのセット :return: bool 判定結果 """ return combination in right_combinations
79500e365a54fca97a5a1ddd62d98d1dbcd129cd
661,840
def clip(v, vMin, vMax): """ @param v: number @param vMin: number (may be None, if no limit) @param vMax: number greater than C{vMin} (may be None, if no limit) @returns: If C{vMin <= v <= vMax}, then return C{v}; if C{v < vMin} return C{vMin}; else return C{vMax} """ try: return...
6f3573c2228a92492853875547a8d5151c890879
661,841
def to_dict(ret, deref_list=[]): """ Converts MongoEngine result to a dict, while dereferencing the fields provided. """ retdict = ret.to_mongo().to_dict() for ref in deref_list: if isinstance(ret._data[ref], list): retdict[ref] = [x.to_mongo().to_dict() for x in ret._data[re...
00408e013df2680cefdadba03106600debf91bf1
661,842
def task_list_item_list_description(data, singular, plural): """ Returns a description for a task list item depending on how many items are in its contents """ if len(data) == 0: return None elif len(data) == 1: return f"1 {singular} added" else: return f"{len(data)} ...
6fe2230e40690377be8377c332d970fc649c2782
661,843
def is_dlang(syntax): """Returns whether the given syntax corresponds to a D source file""" return syntax == 'Packages/D/D.sublime-syntax'
d4b5b752b0dda3d424068f3c6761a7e65b487454
661,844
def decode_sudoku_to_ascii(n, solution): """Encodes a Sudoku from complex Datastructure to Ascii-art. :param n: Sidelength of the Sudoku. :param solution: The Sudoku in complex Datastructure. """ grid = [["."] * n for _ in range(n)] for i, j, d in solution: grid[i][j] = d return "\n...
7fa8b25bddc8c88dfc3aba09228ec0bae200fdc3
661,845
import collections def tcl_findprd_prepd_end(prdx): """ Convert list of center:end entries to final center:[ends] dict. :param prdx: List of center:end dict entries. :type prdx: list(dict(str: str)) """ prdf = collections.defaultdict(list) for prdc in prdx: for key, value in prdc....
c417a915076f6371fd31d72d18554af84139a2ae
661,846
def get_confirmation(warningtext): """ Prints a warning message and asks for user confirmation Return Values: True: User selected Yes False: User selected No """ print() print(warningtext) while True: try: user_input = input("Please confirm (Y/N): ") ...
d34f66935d199b5cf230691bb197f0d9f4b78370
661,847
def groupname(gid=None): """Return the name of the group with the given gid. If gid is None, return the name of the current group.""" return None
f41923722f1684e8a9135bb7d56160a7ab37f0b4
661,848
def get_formal_writers(writers_string): """Return 'Lennon-McCartney' if at least one of them is present in the argument""" first_writer = writers_string.split(',')[0] if first_writer == 'Starkey': return 'Starkey' if first_writer == 'Harrison': return 'Harrison' if 'Lennon' in wr...
8fb02fbda80240ab59a24c9fc04a7eb5823c57bb
661,849
def package_resource_url(package_url, resource_path): """ Converts a package and resource path into a fuchsia pkg url with meta. """ return package_url + "#" + resource_path
88c3da427b383005b4805522b9ed065fe73cc2ee
661,850