content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def uniquify(words): """Remove duplicates from a list. Args: words (list): The list of words Returns: list: An updated word list with duplicates removed. """ return {}.fromkeys(words).keys() if words is not None else words
97916fdbff95989d495de83468cdbaf617db523f
654,740
import os import glob def mostRecentFile(dir, file_pattern, after_time=None): """Search 'dir' for all files matching glob 'file_pattern', and return the mostRecent one(s). If 'after_time' is given, it should be a number of seconds since the epoch UTC; no files will be returned if none is on or after t...
7aa2868b652562080ccd39d852e3a6a38793667c
654,741
def generate_attributes(num_replications, num_global_memory_banks=32): """ Generates the kernel attributes for the global memory. They specify in which global memory the buffer is located. The buffers will be placed using a round robin scheme using the available global memory banks and the number of ...
c9c32e15d668f8a9dbc2672ef5758e5b5359d4b6
654,742
def inject_special_character( str_input, offset, reserved, seed, len_out, char_start, char_num ): """ Inject a special character. This is a very specialized method to inject a character chosen from a range of character codes into a block at the fr...
15227f22539090cc46d2d722f72b2ca0b926d247
654,743
def transform_ip(block: str) -> str: """ Returns the transformed filters from a list of IPs. >>> transform_ip("localhost:65535,udp") '(host localhost and port 65535 and (udp))' >>> transform_ip("10.28.24.100:65535") '(host 10.28.24.100 and port 65535)' >>> transform_ip("*:80,tcp") '(por...
4b083f13eabb5615140f098403919171b5dbbb29
654,744
import struct def get_hyperheader(file): """ Unpack hypercomplex header parameters to a list. Reads the 28-bytes block header from file and unpacks into a list. Endianness is corrected as needed. Returned list contents: = ======== ================ N Variable Description = ...
6efd6b37695d0f3d7113f1c0a0250838e7f8612a
654,746
def output(s, version): """Return bot controls""" if version == 2: U = 32766 if s.poG: s.yaw = s.steer else: s.powerslide = 0 if not s.poG and s.roll != 0 and s.counter % 2 == 1 and abs(s.r) > .03 and abs(s.a) < .15: s.yaw = s.roll ...
05e4057ec9b2c8265533f2a71d1f6e05227892bb
654,747
def clean_off_file(file_name): """ Fixes header of OFF file Args: file_name (str): Name of file to fix """ file_cleaned = False with open(file_name) as f_check: file_str = f_check.read() if file_str[0:3] != 'OFF': raise AttributeError('Unexpected Header for {0}'.fo...
1f95245060542e0e2f3e9192ce7cba6c6a89ae48
654,748
def get_output_names_from_json(sym_json): """ Judge if the node is weight. Args: sym_json: Json object load from mxnet json file. Returns: A list of output tensor names. """ #heads = [lst[0] for lst in sym_json["heads"]] output_names = list() for index in sym_json["heads"]: i = index[0] ...
3a39bb2fa02fe00eb8a7f423ecad5b00479097bb
654,749
from typing import List from typing import Tuple import re def make_range(string: str) -> List[Tuple[str]]: """将 ``1-9``, ``1-4,6-9`` 这样的字符串解析为最小单位(a-b 或 n)序列。 源字符串中 ``s-e`` 表示一个闭区间 >>> make_range("1") [1] >>> make_range("1-9") [(1, 9)] >>> make_range("1,3-9") [1, (3, 9)] """ ...
074790e57d151f13fc9950641039a4f6cb4bf0b0
654,750
def jenkins_node_names(name, count): """Returns the names for `count` production jenkins node prefixed by `name`.""" return ["%s-%s" % (name, i) for i in range(1, count+1)]
44e6f6e32dbcae83632b57bd6aa06cb19cbfad59
654,751
from typing import Optional import requests def get_latest_flexget_version_number() -> Optional[str]: """ Return latest Flexget version from https://pypi.python.org/pypi/FlexGet/json """ try: data = requests.get('https://pypi.python.org/pypi/FlexGet/json').json() return data.get('info'...
7bad9ac1cac3a9a7edaf4d15e5bc8d4074a96243
654,752
from datetime import datetime def str_to_time(stage: str): """字符串转换成时间""" try: return datetime.strptime(stage,'%Y-%m-%d %H:%M:%S') except: pass try: return datetime.strptime(stage,'%Y-%m-%d %H:%M') except: pass try: return datetime.strptime(stage,'%Y-%m-%d %H') except: pass try: return...
9c65c5d047c785eefe0533e2350ef436b152b6a9
654,753
def Lambda(zhub, IECedition): """ Calculate the IEC length scale. Lambda = 0.7*min(Zhat,zhub) Where: Zhat = 30,60 for IECedition = 2,3, respectively. """ if IECedition <= 2: return 0.7 * min(30, zhub) return 0.7 * min(60, zhub)
101c87f9a65b05efb831b42038419ba3251ac333
654,754
import os def get_default_template_dir(): """Generates the complete path to the template directory for the API generator Returns: str: the absolute path to the default template directory. """ directory = os.path.dirname(__file__) return os.path.join(directory, "templates")
039063118427ef256ca9c55ddf35d94800da017a
654,755
import os def get_user_basic_auth_from_environment(): """get abeja platform user basic auth id and pass from environment variables basic auth id : user_id basic auth pass : personal access token of the user :return: dict { "user_id": ABEJA_PLATFORM_USER_ID, "personal_access_token"...
82d15f878d9d477f80b488095f3515d8d512ba57
654,756
import os def get_list_of_files_in_dir_for_ext(dir, ext='.xtc'): """Returns the list of files in the directory for specified extension or None if directory is None.""" if dir is None: return [] if not os.path.exists(dir): return [] list_of_files_in_dir = os.listdir(dir) list_of_files = [] for...
7f5170e63f85e629173fb360fc6b72e5fff2c2f9
654,757
def device_loc_to_type(loc): """Get the fixed, hardcoded device type for a device location.""" if loc in [461, 501]: return "ETC" elif loc in [541, 542]: return "GIF" elif loc in [11, 75, 150, 239, 321, 439, 482, 496, 517, 534]: return "FIF" elif loc in [ 38, ...
456547c1c153f460e53cff361b0f1239ff52c166
654,758
from typing import List def reverse(s: str) -> str: """ Reverse a string. - Time Complexity: O(len(s)) - Space Complexity: O(len(s)) :param s: a string :return: a reversed string """ length = len(s) rlist: List[str] = [''] * length for i in range(length): rlist[length...
248d2c70b819d05ce1101d08c6365831f8b1929f
654,759
import sys def _decode_text(text): """ SonoBat uses the system locale for encoding text, so we have to guess what it might have been. Try Mac_Roman first if we're running on OS X, otherwise default to Windows 1252. Yuck. """ encodings = ['windows-1252', 'latin-1'] encodings.insert(0 if sys.pla...
f6d68d04cccef20724013a27c939323d04b28f2d
654,760
def has_multi_stage_heating(heat_stage): """Determines if the heating stage has multi-stage capability Parameters ---------- cool_stage : str The name of the cooling stage Returns ------- boolean """ if heat_stage == "variable_speed" or heat_stage == "modulating": ...
cfc99c74c2d3b42e539aa179ec3a6c18cfd54f68
654,761
def look_up(index, keyword): """ Takes two inputs: - A dictionary type index - The keyword to lookup in the index Returns a list of the urls associated with the keyword. If the keyword is not in the index, returns an empty list. """ try: return index[keyword] except KeyError:...
aeb894d46178467514f69818f3e2df50519fbfd5
654,762
def get_xi(a: float, i: int, delta_x: float) -> float: """ Calculating x_i = a + i * delta_x """ return a + (i * delta_x)
45c15f1c10ff5ffa5f88af10c676d57e5513e5fc
654,763
def roll_left(sequence, alleles, ref_pos, bound): """Determines common distance all alleles can be rolled (circularly permuted) left within the reference sequence without altering it. Args: sequence (str): The reference sequence. alleles (list of str): The sequences to be normalized. ...
34343a5f6cc3f2f9fe787ce9155b36991ae55822
654,765
def legc(leg,col='color'): """Color legend text to match linecolor. :Inputs: 'leg' is a legend object. 'col' sets the field of the leg.get_lines() objects to use to find the color. You may need to refresh the figure to see the changes.""" # 2009-12-14 09:50 IJC: Created tex...
42d08aff3cb72e35a045ea44e8d3fd6172735caf
654,766
import re def regquote(s): """Quote regular expressions. :param s: string to be quoted. """ return re.sub(r'([][.^$*+])', r'\\\1', s)
de68814fd10dafd946e782added79afd4fdf966c
654,767
def _build_dict(words): """Builds a dictionary of words :param list[str] words: words :returns: dictionary of words :rtype: dict """ d = {} for i, word in enumerate(words): try: first, second, third = words[i], words[i + 1], words[i + 2] except IndexError: ...
3f4348b16f120828d293a5ab9e8cc35e71d0f5c3
654,768
import torch def validate_model(model, valid_loader, criterion, device): """Validate the accuracy of the model during training Arguments: model -- The model to validate valid_loader -- Valdation data loader criterion -- Loss function used by the model device -- If it is to tra...
46ff820c3d26c1afe32634650841e7923b7ec3a7
654,769
def wraps(wrapped): """Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argument and the arguments to wraps() as the remaining arguments. Default arguments are as for update_wrapper(). ...
697dab7e045137d98f9a834db44dead5905e3f2d
654,770
import inspect def arg_names(receiver): """ Get the expected keyword arguments for a function or class constructor. """ return list(inspect.signature(receiver).parameters.keys())
3267c2cb36ee54ff99f972a7a0e1e8ba90393bef
654,771
def to_language(locale): """Turns a locale name (en_US) into a language name (en-us).""" p = locale.find('_') if p >= 0: return locale[:p].lower() + '-' + locale[p + 1:].lower() else: return locale.lower()
260735d10cd06bf5d149cbed126f1bb99659c0be
654,772
def beautify(functions): """Pretty prints an array of compiled functions as one string. Args: functions (list): The functions to pretty print. """ output = '\n\n'.join(functions) output = output.replace('{', '{\n') # Sort out braces. output = output.replace('}', '\n}') lines = out...
18be1259e455f54363933467c8a7ff92cce7ebb3
654,773
def process_input(input_name): """ Returns the processed input as well as the max size of the ocean matrix """ with open(input_name) as input: max_size = 0 processed = [] for line in input: points = line.strip().split(' -> ') line_array = [] ...
1e4f53e375ca2368027c0f80c36ccd158639b02f
654,774
def newman_conway(num, storage=None): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: O(n) Space Complexity: O(n) """ if storage is None: storage = [None, 1, 1] if num == 0: raise ValueError while num >= len(storage): st...
26ef3dcf2dfc00136a744744747bc854977bd2e1
654,775
def get_spans_in_offsets(spans, start, end): """Return the list of spans (nlplingo.text.text_span.Span) that are within (start, end) offsets :type spans: list[nlplingo.text.text_span.Span] Returns: list[text.text_span.Span] """ ret = [] for span in spans: if start <= span.start_c...
ffc1d910595074ba3340ce3187ef0b1566bd2909
654,776
from typing import Counter def ordered_count(inp): """ Count the number of occurrences of each character. :param inp: a string input. :return: a list of tuples of each string character and that characters occurrence. """ return sorted(list(Counter(inp).items()), key=lambda x: inp.index(x[0]))
98b4dee29f36e94729a6cac6ee816fb1957e6b73
654,778
def run_one_phot_method(allInput): """ Do a photometry/spectroscopy method on one file For example, do aperture photometry on one file This is a slightly awkward workaround because multiprocessing doesn't work on object methods So it's a separate function that takes an object and runs the method ...
49e8e119eb7f46ddf3910cf06c6a83bf12be38b9
654,781
def generate_snake_order(teams, n_rounds): """Create a snake draft order Args: teams (iterable): e.g. ('Team1', 'Team2', 'Team3') n_rounds (int): number of rounds in draft Returns: list Examples: >>>generate_snake_order(teams=['A', 'B', 'C'], n_rounds=4) ['A', ...
4dc864fa3c6a9a39b35f1586c41cc50c3e502726
654,782
import os def list_full_file_paths(directory): """List the absolute paths of files in |directory|.""" directory_absolute_path = os.path.abspath(directory) paths = [] for relative_path in os.listdir(directory): absolute_path = os.path.join(directory_absolute_path, relative_path) if os.path.isfile(absol...
8e6fbd2bbce3ca1e922d8b5928d32895cc518a75
654,783
import math import random def prob_round(x): """ Rounds up with probability proportional to decimal places. """ floor = math.floor(x) if random.random() < x - floor: floor += 1 return floor
62bc7ed686b581cca6b883c08a5232093feeb788
654,784
def read_byte(dev, bits=8): """Reads a single byte from the IR transmission.""" margin = 200 # acceptable margin of error margin2 = 15000 byte = 0 i = 0 durations = [] while i < bits: is_pulse, pulse_len = dev.read() durations.extend([is_pulse, pulse_len]) # wait for pulse if not is_pulse and i == 0: ...
52344cdc09ace605a1863a3fffacbc5742bf21bf
654,785
def make_users_groups_url(base_url, duke_unique_id): """ Create url for fetching a users groups. :param base_url: base group manager url (eg. 'https://groups.oit.duke.edu/grouper-ws/servicesRest/json/v2_1_500/') :param duke_unique_id: str: unique id (number) of the user we want to build a url for :r...
500135d68a71df7d7f0dbedbe587dbc998663295
654,786
def get_stylesheets_for_decorator(decorator: dict, count: int) -> list: """ Gets stylesheets for a decorator. Args: decorator (dict): Decorator config object. count (int): Current page count. Returns: list: List of CSS documents that apply to current usage of decorator. """...
3caade502a3a93c2805ea822d3ba14bb33a3c196
654,787
def count_mismatches_before_variant(reference_prefix, cdna_prefix): """ Computes the number of mismatching nucleotides between two cDNA sequences before a variant locus. Parameters ---------- reference_prefix : str cDNA sequence of a reference transcript before a variant locus cdna...
59754e259de5331f8b330bfa4b5651544ee0d3d4
654,788
from typing import Callable from typing import Union import logging def get_logger_method(fn: Callable, logger_method: Union[str, Callable]) -> Callable: """ Get logger method for function. Get logger in `fn` definion module or creates logger is module.__name__. Or return logger_method if it's callab...
ea49fe784897eee170a9298d587321f2a1d70b73
654,789
def is_GKsave_same_min_and_sec(event_stat_1, event_stat_2): """Returns true if the two events are exact same game minute / second""" min_1 = event_stat_1.minute sec_1 = event_stat_1.second min_2 = event_stat_2.minute sec_2 = event_stat_2.second event_stat_1.type_id return min_1 == min_2 and sec_1 == sec_2 and ...
576d7ff585761a406b23b6d9bdffd2f7cb1d2e6c
654,790
import numpy def Preprocessdata(d1, d2): """ discard some data when z is smaller than -0.8. then remove the z coordinates. """ d2 = d2[d2[:,2] > -0.8,:] d = numpy.vstack((d1,d2)) t = numpy.empty(d.shape[0]) t[:] = 0 t[0:d1.shape[0]] = 1 return d[:,:2], t
7ee283a7a636ffb2c9b655c545d797b7d839d7bb
654,791
def ensure_array(exemplar, item): """Coerces *item* to be an array (linear sequence); if *item* is already an array it is returned unchanged. Otherwise, an array of the same length as exemplar is created which contains *item* at every index. The fresh array is returned. """ try: item[...
5b32b1972713abcbd988eb06969e13408e486f62
654,792
import torch def normalise_quat_in_pose(pose): """Takes a pose and normalises the quaternion portion of it. Args: pose: shape N, 7 Returns: Pose with normalised quat. Shape N, 7 """ pos = pose[:, 0:3] quat = pose[:, 3:7] quat /= torch.norm(quat, dim=-1, p=2).reshape(-1, 1)...
c538c85edbe9b8d69df07885c3c199e0afe8f050
654,793
def get_slurm_directives(user: str, job_name: str = 'BlenderRender', gpu: int = 2, cpu: int = 4, ssd: int = 10, ram: int = 16, days: int = 0, hh:...
f8e95eb336bde17804d45dda6a366b00df450b59
654,794
def token_query(subnet, token_keys, ip_index): """Lookup a single value based on the token split by underscores. :param token_keys: An array of the token keys split by underscores. :param ip_index: The ip_index value used to select a static IP. :return value: The value based on the token_keys lookup. ...
93fb87eee3b50457fe5bd71420f5bf3a7ae63574
654,795
def build_requested_schemas(qparams): """" Fills the `requestedSchemas` part with the request data It includes valid and invalid schemas requested by the user. """ requested_schemas = {} if qparams.requestedSchemasVariant[0] or qparams.requestedSchemasVariant[1]: requested_schemas['Var...
e358fae46fc2d177906de4de948bdcf839fa13bd
654,796
def _make_reference_data_frame(base_df, ref_df, reference): """ This applies the reference metrics to the data frame given the base data frame and the reference data frame. When a reference is selected as a delta or a delta percentage, the calculation is performed here. Otherwise, the reference data fr...
790c491aa3ad4dce59ac4f3ea0e7a2f871172f00
654,797
def tensor_size(tensor): """get tensor size""" size = 1 for i in tensor.shape: size *= i return size
658cfbc8fee6a4fa139ad236102ecc13e9744d9c
654,798
import torch def exp_se3(xi): """ :param x: Cartesian vector of Lie Algebra se(3) :return: exponential map of x """ w = xi[:3].squeeze() # rotation v = xi[3:6].squeeze() # translation w_hat = torch.tensor([[0., -w[2], w[1]], [w[2], 0., -w[0]], ...
0acba9aaddd92484e1b98a8b47d44ea0ba54dadf
654,799
import re def is_long_algebraic(arg: str) -> bool: """Return True if arg matches long algebraic notation used in UCI""" if not isinstance(arg, str): return False return bool(re.match(r'^[abcdefgh][12345678][abcdefgh][12345678][qrbnp]?$', arg))
387ad0700ce118c5eb877caaa19708cf85b3a9db
654,800
def socket_read_n(sock, n): """ Read exactly n bytes from the socket. Raise RuntimeError if the connection closed before n bytes were read. """ buf = '' while n > 0: data = sock.recv(n) if data == '': raise RuntimeError('unexpected connection close') buf += da...
166fe86c8c5987177f982f3d49e597f8f750da1b
654,801
def activity_logging_world_check(member): """Returns if an isolated world check is required when generating activity logging code. The check is required when there is no per-world binding code and logging is required only for isolated world. """ extended_attributes = member.extended_attributes ...
fd1ad06df21f0b6c63fe2d15286c128bb1dad273
654,802
def avg_list(jac_list): """Average a list of jaccard results This is useful for computations like pairwise which need summarization """ if len(jac_list) == 0: return 0 return sum(jac_list)/float(len(jac_list))
8f2e07fe82f2a0b85634dde3a6534787359067fb
654,803
def listminuslist(minuend, subtrahend): """ For each element in subtrahend, removes an equal element in minuend, with earlier elements removed first. The order of the remaining elements in minuend is preserved. """ difference = minuend[:] for elem in subtrahend: if elem in difference: difference.remove(elem...
aaf1a17fb0d29487fd912956dff3cef1d8f6dbe5
654,805
def get_jittering(seed_rng, scale_size, translate_size, rotation_size, img_width): """ This method returns uniform random values for scaling, translation, and rotation in the range given by user. Parameters: ------------- scale_size: float in [0,1] the maximum ratio by w...
d257377cfcf88a50011b2c477ef6968ba8598c9b
654,806
def IsEven( x ): """Tests if x is even""" return ( x % 2 ) == 0
e068cae86b19f364e398b05a11b8b5062a35db6a
654,807
def _sorted_images(images, start_name): """Retrieve a sorted list of images with most recent first. """ images = [(i.name, i) for i in images if i.name.startswith(start_name)] images.sort(reverse=True) return [(i.id, name) for (name, i) in images]
7f878983533a31c40ced51522d5d051b75fde96d
654,808
from datetime import datetime def _basic_error_handler(exception: Exception) -> dict: """This is a basic error handler that just says something went wrong. Make sure your handlers have the same signature! """ return {'statusCode': '500', 'headers': {'Date': datetime.now().strftime("%a, %d ...
aea8922a3a6a7813e46e9b4d638c168c894e754d
654,809
import math def lcm(p, q): """ 最小公倍数を求める。 """ return (p * q) // math.gcd(p, q)
e6bea5286963268d2eca3fd58d13b527807d417d
654,810
import argparse def parse_args(): """ Return dictionary of command line arguments """ parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, usage=argparse.SUPPRESS) parser.add_argument('program', help=argparse.SUPPRESS) parser.add_argument('--name', typ...
be3ad6a4e62d789486707ca28faa97be0cbe085d
654,811
def polyXY2(x,y,coeff): """XY quadratic with cross-terms | - | x | x2| ---+---+---+---+ - | a | b | d | y | c | e | g | y2| f | h | i | """ a,b,c,d,e,f,g,h,i = coeff return a + x*(b + x*d) + y*(c + y*f) + x*y*(e + x*g + y*h + x*y*i)
7721b9588443a657cabaa2b64890a66ffff59d8f
654,812
def nested_inc(op, _, attr_val, attr_name, state, step=1): """Increments relevant counter by step from args array""" oph = state.setdefault(op, {}) nameh = oph.setdefault(attr_name, {}) nameh.setdefault(attr_val, 0) nameh[attr_val] += step return state
1d36f491901ee3f6a52b57fc809a7a355d38769a
654,813
import math def wrap_always(text, width): """A simple word-wrap function that wraps text on exactly width characters. It doesn't split the text in words.""" return '\n'.join([text[width * i:width * (i + 1)] \ for i in range(int(math.ceil(1. * len(text) / width)))])
f6e5b85007fffc78576c8d5bbe89077400ca96b0
654,814
from pathlib import Path import fcntl import errno def lock_script() -> bool: """ Locks a file pertaining to this script so that it cannot be run simultaneously. Since the lock is automatically released when this script ends, there is no need for an unlock function for this use case. Returns: ...
49e8205992e8c34eeffedffd38e657ac64b2d76d
654,815
def flatten(list1): """ Simple function to flatten peers list Format: [((node1 endpoint1 tuple), (node1 endpoint2 tuple), ..., (node1 endpointm tuple)), ....] Example: [(("172.17.0.1",3000,None),), (("2001:db8:85a3::8a2e",6666,None), ("172.17.0.3",3004,None))] """ f_list = [] for i in list1...
a62aa1fbab622a89ed33a125a0fb3dcab8aada51
654,816
def rows(matrix): """ Returns the no. of rows of a matrix """ if type(matrix) != list: return 1 return len(matrix)
4f39ce7793c1dcb92337d04c0c85ac21d0830f1f
654,817
def assignment_explicit_no_context(arg): """Expected assignment_explicit_no_context __doc__""" return "assignment_explicit_no_context - Expected result: %s" % arg
c11ef28d9942d73bea6ed14547aa11648d37f3a9
654,818
import subprocess def get_packet(interface): """ Retrieve the DHCP packet information to obtain the option data See the uppermost docstring for information on DHCP option 121 not appearing in the responses due to the fact that they are not requested in older client versions. interface: ...
6ce583752ca177bcd510bc41427611376475ced0
654,819
def server_supports_alter_user(cursor): """Check if the server supports ALTER USER statement or doesn't. Args: cursor (cursor): DB driver cursor object. Returns: True if supports, False otherwise. """ cursor.execute("SELECT VERSION()") version_str = cursor.fetchone()[0] version = v...
e5c05c3a1c119ef2969792ac7d420c049f127ee2
654,820
def get_insight(df): """ Get insight from a youtube_history dataframe transformed by transform() Parameters ---------- df : DataFrame A youtube_history dataframe transformed by transform() Returns ------- df_info : dictionary Contains informations about a specific youtu...
86e586fe1cdad77d0f3248585c4b2feb8716503f
654,821
import math def exp_schedule(k=20, lam=0.005, limit=2000): """One possible schedule function for simulated annealing""" return lambda t: (k * math.exp(-lam * t) if t < limit else 0)
9db0689185120ddd4ae55b2d330cbfe8c62196c3
654,822
def ensure_absent(spec): """ test if an 'Ensure' key is set to absent in dictionary 'spec' """ if 'Ensure' in spec and spec['Ensure'] == 'absent': return True return False
fe6beeb7925934536edde75a2f2514011f679b29
654,823
def problema_pythonico(a, b): """ Mucho más rápido en este caso """ return len({i ** j for i in range(a, b+1) for j in range(a, b+1)})
69b756068295573333e703fe64add42f4e445ea2
654,825
def cases_tour(col,lig): """Retourne la liste des indices (col,lig) des cases où peut se déplacer une tour positionnée sur la case (col, lig) Ex: tour en (5,3) - - - - - - - - - - | x | | x | | x | | x x x x x T x x | | x | ...
1fb241c0cd270862fdbf6624afcff290e1680f57
654,826
def expand_hex(x): """Expands shorthand hexadecimal code, ex: c30 -> cc3300""" if len(x) == 3: t = list(x) return "".join([t[0], t[0], t[1], t[1], t[2], t[2]]) else: return x
31f8a58a8d98f2e078a842a6ae1ebec7c95b20cf
654,827
def _check_skip(selector, chrom): """ :param selector: :param chrom: :return: """ if selector is None: return False elif selector.match(chrom) is None: return True else: return False
753281e590bb00a84d068f54677130cd74389c7f
654,828
def percentagify(numerator, denominator): """Given a numerator and a denominator, return them expressed as a percentage. Return 'N/A' in the case of division by 0. """ if denominator: return '{:04.2f}%'.format((numerator / denominator) * 100) else: return 'N/A'
d166c5ff9f70acf7938f6a82b8b0d498c466bd50
654,829
def getBranchCategory(branch_name): """There are 3 categories of releases. Map branch name on them.""" if ( branch_name.startswith("release") or branch_name == "master" or branch_name.startswith("hotfix/") ): category = "stable" elif branch_name == "factory": cat...
46e1af6e6bab48525849c8f51ce468232b64eca6
654,830
def split_word_cnt_eff(word, A, sett, origin, original_word=False): """ Adding sett mapping for counting :param word: string of the curr word :param A: array of words :param sett: adding the mapping :param origin: origin word string :param original_word: boolean flag :return: """ ...
ba89c0cdb326fe8b6d19d04402943d10242b6a83
654,831
def model_file_name(result_dir): """Model file name for lowest loss""" return '{0}/model.h5'.format(result_dir)
354c8ba343af543660e0a5244e03f961dbdf40b3
654,832
import torch def labels(batch_size: int, num_items: int) -> torch.Tensor: """A large tensor of binary relevance labels""" probabilities = torch.empty(batch_size, num_items).fill_(0.5) labels = torch.bernoulli(probabilities) return labels
8d10e30ae7f93edcf9de24b55da55739a10b7a4d
654,833
import six def force_str(s): """ force s to be str - should work both in py2 and py3 """ if six.PY3: return s.decode() return s
91817e040fc0aa8d9bcc0c5c36709647695cb414
654,834
from bs4 import BeautifulSoup def convert_html_links(html): """Convert all html links to url tag.""" soup = BeautifulSoup(html, "html.parser") for link in soup.find_all("a"): link["href"] = "{{ url }}" return soup.prettify()
27b05892f979330f9035cc77216fc7a6bb02b591
654,835
import torch def load_model( model_path: str = "saved_models/traced_pspnet_model.pt", ) -> torch.ScriptModule: """Loads and returns the torchscript model from path. Parameters ---------- model_path : str, optional The path to the torchscript model, by default "models/face_blur.pt" Re...
b88225b57b19650ce21334bc12bab0b596bd49fb
654,836
import typing def _versify ( py_version_info: typing.Tuple ) -> str: """ Semiprivate helper function to convert Python version to a point release (a string). py_version_info: Python version info as a named tuple from the operating system, e.g., from [`sys.version_info[:2]`](https://docs.python.org/3/...
d43e617cebeff0f60fbea2173ae9cddd01027dcc
654,838
def fahrenheit_to_celsius(fahrenheit): """ Fahrenheit to Celsius :param celsius: Degrees Fahrenheit float :return: Fahrenheit float """ return (float(fahrenheit) - 32) * 5.0/9.0
83a718fe60130bb2b699aa03592a31cf65d5c025
654,839
def is_int(value): """Check whether the `value` is integer. Args: value: arbitrary type value """ try: if int(f"{value}") == int(value): return True except ValueError as e: pass return False
345710e68d468383146cd2a14625657333e3338b
654,840
def secondOrderTrans(high_phase, low_phase, Tstr='Tnuc'): """ Assemble a dictionary describing a second-order phase transition. """ rdict = {} rdict[Tstr] = 0.5*(high_phase.T[0] + low_phase.T[-1]) rdict['low_vev'] = rdict['high_vev'] = high_phase.X[0] rdict['low_phase'] = low_phase.key r...
cad8401f27d2313e38fed5ba3c1221d720ba4ead
654,841
def colorize(text, color): """ Display text with some ANSI color in the terminal. """ code = f"\033[{color}m" restore = "\033[0m" return "".join([code, text, restore])
8dcefe14ba17fbd71cb1460010f2dba49e152738
654,842
def strip(pre, s): """Strip prefix 'pre' if present. """ if s.startswith(pre): return s[len(pre):] else: return s
4fd3a227d2404ed1fdcdfcbea628aad1170cc278
654,844
def secs_to_readable(secs: int): """ Parameters ---------- secs >>> secs_to_readable(100) '1m40s' """ secs = round(secs) readable = "" hours, remainder = divmod(secs, 3600) minutes, seconds = divmod(remainder, 60) if hours: readable += str(hours) + "h" if ho...
71ceca9fb9229607946f010a44d2457d2e991c8e
654,845
def id_list_from_editor_output(bs, **kwargs): """bs is a string of console output the lines are: # delete me if you .... (must be deleted) id col1 col2 010101 c11 c22222 ... If first line begins with # then return an empty list Ignore the second line Return a list composed of...
cc45f93f065c00f1394827e3da340471c6c9f11e
654,846
import copy def pop_from_list(lst, items): """Pop all `items` from `lst` and return a shorter copy of `lst`. Parameters ---------- lst: list items : sequence Returns ------- lst2 : list Copy of `lst` with `items` removed. """ lst2 = copy.deepcopy(lst) for item...
a4cd56c42a688a23e861752a871654db622e47d0
654,847
def count_site_values(nexus_obj, characters=('-', '?')): """ Counts the number of sites with values in `characters` in a nexus :param nexus_obj: A `NexusReader` instance :type nexus_obj: NexusReader :param characters: An iterable of the characters to count :type characters: tuple :return:...
d37b993ac78e2e4eb2d552b7bc2d3ed81141c6a6
654,848