content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def preprocess_data_for_clustering(df): """Prepare data in order to apply a clustering algorithm Parameters ---------- df : pandas.DataFrame Input data, *i.e.* city-related timeseries, supposed to have `station_id`, `ts` and `nb_bikes` columns Returns ------- pandas.DataFrame ...
deabc1feb34f1e8bf1fd4b4575964dc666552cfa
72,899
def gen_barcode_digit(engine): """Pick a random number between 0 and 9""" return int(engine.triangular(0, 9))
28c9d5ecdd6779d609a5f5d1c97101e3cc493961
72,901
import re def ppdInfo(filename): """ Get information from the printer's installed PPD file. All keys will be set to blank strings if they could not be found in the PPD. """ textfile = open(filename, 'r') filetext = textfile.read() textfile.close() info = { } matches = re.findall('...
553c89581b9be529872ead9f97e60358a27a405c
72,903
def big_sorting(unsorted): """Hackerrank Problem: https://www.hackerrank.com/challenges/big-sorting/problem Consider an array of numeric strings where each string is a positive number with anywhere from 1 to 10^6 digits. Sort the array's elements in non-decreasing, or ascending order of their integer value...
909ca4844b943a34e65b730f8efe43e355593724
72,905
from pathlib import Path def get_test_file_path(filename): """Given a filename prepend it with the correct test data location""" return str(Path(__file__).resolve().parent / "assets" / filename)
45bae871be3802cb50a3ac74a6282f3932b9e8af
72,906
import base64 def b64encode(data: str, urlsafe: bool = False) -> str: """Accepts a string and returns the Base64 encoded representation of this string. `urlsafe=True` encodes string as urlsafe base64 """ if urlsafe: b64 = base64.urlsafe_b64encode(data.encode("ascii")) return b64.decode...
7805052990646dd946ddfb2c1113dbf1bfebd866
72,911
def consolidate(arr): """Merges intersecting sets in a list of sets. Taken from: http://rosettacode.org/wiki/Set_consolidation#Python:_Iterative Recursive version will hit max recursion depth. """ sets = [s for s in arr if s] for i, s1 in enumerate(sets): if s1: for s2 in s...
6067e723cff58475f7be43224178373b1099f4f5
72,916
def translate_severity(sev): """ Translate alert severity to demisto """ if sev in ['Medium', 'High']: return 3 if sev == 'Low': return 2 return 0
a8de42c2ca3445a014633b1b5af6c4baf0d2bea7
72,917
def exclude_if_local(target_function): """A member function of Engine wrapped with this function will not execute if the Engine is in "local" mode.""" def _wrapper(self, *args, **kwargs): if self.is_local: return None return target_function(self, *args, **kwargs) return _wrappe...
2fa99ab972a47e99d254357c891c1b36bfd3672b
72,918
def build_cz_text(cz_data, prefix): """ Create a summary of Conflict Zone activity """ if cz_data == {}: return "" text = "" if 'l' in cz_data and cz_data['l'] != '0' and cz_data['l'] != '': text += f"{cz_data['l']}xL " if 'm' in cz_data and cz_data['m'] != '0' and cz_data['m'] != '': text ...
d8fdb8df8296df87745b96ea799394afd9e97c57
72,924
def to_bulk(a, size=100): """Transform a list into list of list. Each element of the new list is a list with size=100 (except the last one). """ r = [] qt, rm = divmod(len(a), size) i = -1 for i in range(qt): r.append(a[i * size:(i + 1) * size]) if rm != 0: r.append(a[(i ...
86eb380efd019fa99d8945dc22d25a0dc8d1462e
72,925
def format_bucket_prefix(base_prefix: str, dirname: str) -> str: """Format an S3 bucket key prefix by joining a base prefix with a directory name. """ base_prefix = base_prefix.rstrip("/").lstrip("/") dirname = dirname.lstrip("/") prefix = "/".join((base_prefix, dirname)) if not prefix.endsw...
567d007e2afee48832fe90ad871a698951580c69
72,932
def remove_punctuation(input_string): """Return a str with punctuation chars stripped out""" tran_table = str.maketrans('','', '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~') output_string = input_string.translate(tran_table) return output_string pass
f8b01b58563bdd0d2583558bdf7063126a47f229
72,934
def test_pkgrepo_with_architectures(pkgrepo, grains, sources_list_file, subtests): """ Test managing a repo with architectures specified """ name = "deb {{arch}}http://foo.com/bar/latest {oscodename} main".format( oscodename=grains["oscodename"] ) def _get_arch(arch): return "[a...
9e6ae74c792e2f5df05ac936624c62d096e483a4
72,942
def block_num_from_hash(block_hash: str) -> int: """ return the first 4 bytes (8 hex digits) of the block ID (the block_num) Args: block_hash (str): Returns: int: """ return int(str(block_hash)[:8], base=16)
8133afdbc13c37e28093619efbc69100001e0506
72,947
from typing import List def is_valid_rule_two(character_indices_policy: List[int], character: str, password: str) -> bool: """ Return True if a password is abides to its asscoiated policy else return False The policy is represented as follows: '[1-3] a' --> the character 'a' should occur either as...
0f7771b4d12272f9d377e156aed2dbd50ea6f9f7
72,949
import base64 def b64encode(t): """Encoder using Base64. >>> b64encode("Hola mundo") 'SG9sYSBtdW5kbw==' """ return base64.b64encode(t)
e527986f875517adb971aebdeb820d01176887ca
72,950
import colorsys def rgb2hsv(rgb_tuple): """Converts RGB floats to HSV.""" r = rgb_tuple[0] g = rgb_tuple[1] b = rgb_tuple[2] hsv_tuple = colorsys.rgb_to_hsv(r, g, b) return hsv_tuple
7f02d6efa7abc41698f561b12b3f758b5f492450
72,951
def format_time_to_subrip_timecode(timestamp): """Returns a SubRip timecode string from a datetime.time object""" return timestamp.strftime("%H:%M:%S") + ",%s" % timestamp.strftime("%f")[:3]
53ad14e31a2b46133b6caf68116e268e84de9754
72,961
def get_rpath_attribute(root, element_path, attribute, default=None): """Returns the value of an attribute at an rpath. If more than one element exists with the same name, only the first is checked. Args: root: The XML element to search from. path: The path to the element. attr...
54e84ccc4e72fcded3c9338aabf2962e517f7c24
72,970
def getTextFile(filename): """ Returns a list where each element contains text from each line of given text file. """ return [line.rstrip() for line in open(filename,'r').readlines()]
943965510b6a7bc00a2ddef1b089578937414749
72,972
def bbox_resize(bbox, scale_factor): """ Resize the bbox according to the `scale_factor` saved for resizing the image. Args: bbox (ndarray): All gt boxes in an image, and the shape of `bbox` is `K x 4` scale_factor (float or int): The `scale_factor` used in resizing ...
8596a84b3c7ee2179ac33282a709a3cedbd99672
72,974
from datetime import datetime def _construct_message(msg): """Formats a message from a dictionary Parameters ---------- msg: dict The message in dict form Returns ------- str A stringified version of the message """ date = datetime.fromisoformat(msg['timestamp']....
be8ffa51bc99adc16826fdc85a5f34818fa5e0da
72,977
def _get_aggregates_by_provider(ctx, rp): """Returns a list of UUIDs of any aggregates for the supplied resource provider. """ query = """ MATCH (rp:RESOURCE_PROVIDER {uuid: '%s'})-[:ASSOCIATED]-> (agg) RETURN agg.uuid AS agg_uuid """ % rp.uuid result = ctx.tx.run(query)....
c68ecbca0dd18726d04c0b00293a4e536b5c844c
72,985
def surface_tension(t_k=453.7): """Surface tension as a function of temperature Parameters ---------- t_k : float, default=453.7 K, temperature. Default is the melting point. Returns ------- σ : float N m, surface tension Davison, H.W. "Complication of Thermophysic...
f7f3e54d71fda918dd1aded6aef7b8d25ca38295
72,990
def _policy_profile_generator_xml(total_profiles): """ Generate policy profile response in XML format. :param total_profiles: integer representing total number of profiles to return """ xml = ["""<?xml version="1.0" encoding="utf-8"?> <set name="virtual_port_pr...
b2ee903466976aa8348f8e9a838f442b14d48976
72,996
def extended_euclidian(a, b): """ returns (x, y, d) such that: x*a + y*b = d, d = gcd(a,b) r_1 = a - b * q_1 r_2 = b - r_1 * q_2 ... r_n = r_n-2 - r_n-1*q_n = a * x_n + b * y_n x_n = x_n-2 - x_n-1 * q_n y_n = y_n-2 - y_n-1 * q_n """ # Naive version: # x2, y2 = 1, 0 ...
8fc587f142150b42337c417ecd43c6260d2f048e
73,000
def straight_line(x, m, c): """ A straight line model: y = m*x + c Args: x (list): a set of abscissa points at which the model is defined m (float): the gradient of the line c (float): the y-intercept of the line """ return m * x + c
f74a0bb1663e4d340e7f47d5317f92a3840ed171
73,003
def strToDna(seqStr): """Returns str having been reduced to capital ACTG.""" return "".join([c for c in seqStr if c in 'ACGTacgt']).upper()
055064e5f4ce6af91fb54cb5eaec0d246845c343
73,011
def convert_to_bool(value): """Function to convert string value to boolean Args: value (str): String value of the boolean value Returns: bool: True/False """ if value.lower() == 'true': return True return False
44b8fc8d41669d6bd3f6e3eac96166505d1bc0fe
73,012
def nodes(G, t=None): """Return a list of the nodes in the graph at a given snapshot. Parameters ---------- G : Graph opject DyNetx graph object t : snapshot id (default=None) If None the the method returns all the nodes of the flatt...
0f34f05ecce11ff0ae55e75608fb342db43368f4
73,015
def get_output_tensor_by_name(inference_response, name): """Find an output Tensor in the inference_response that has the given name Parameters ---------- inference_response : InferenceResponse InferenceResponse object name : str name of the output Tensor object Returns --...
4c730fbb2027fc0c333d88016826016743215016
73,017
def _ListToDictionary(lst, separator): """Splits each element of the passed-in |lst| using |separator| and creates dictionary treating first element of the split as the key and second as the value.""" return dict(item.split(separator, 1) for item in lst)
cd79b890377724bbe60346b306d25ebd5f564448
73,020
def is_error_string(return_value): """ Check if return value is error message >>> is_error_string(42) False >>> is_error_string("Some message") False >>> is_error_string("ERROR: some error message") True """ return isinstance(return_value, str) and return_value.find("ERROR") != -1
7184f3491fccb2f9ef784f4f4bd2e8570b1872a6
73,021
from pathlib import Path def find_level(filepath: Path, root: Path) -> int: """Dizin seviyesini bulma Arguments: root {Path} -- Dizin yolu startpath {Path} -- Ana dizin yolu Returns: int -- Derinlik seviyesi Examples: >>> find_level(Path("./Documents/Configuration"),...
36a994f09005385e36ce9df752d76aa09d62b530
73,031
def zero_diag(Q): """ Copy of Q altered such that diagonal entries are all 0. """ Q_nodiag = Q.copy() for ii in range(Q.shape[0]): Q_nodiag[ii, ii] = 0 return Q_nodiag
8c40fc58ee8e7af7a905de1d17b39c7d074cda17
73,034
def progress_bar(*, progress: int, maximum: int, per: int = 1) -> str: """Constructs a progress bar. .. versionadded:: 2.0 .. versionchanged:: 3.0 * Re-ordered the arguments to ``progress``, ``maximum``, and ``per``. * Raise :exc:`ValueError` if any of the following apply: ...
1d3e3bbeee5293e096839f0e56c486711ff8cbd5
73,039
def simple_split(X, train_len=None, test_len=None, valid_len=None): """ Split the data in train-test-validation using the given dimensions for each set. :param X: numpy.array or pandas.DataFrame Univariate data of shape (n_samples, n_features) :param train_len: int Length in number of da...
c6ab6a6687f8ca079d4dc679303282a6b93346e8
73,042
def whitespace_smart_split(command): """ Split a command by whitespace, taking care to not split on whitespace within quotes. >>> whitespace_smart_split("test this \\\"in here\\\" again") ['test', 'this', '"in here"', 'again'] """ return_array = [] s = "" in_double_quotes = False ...
16f55605a3fdfd7eaf94a540c680bac6b9860fb7
73,046
def default_cost_function(segments, nodes, turn_cost=3000, intersection_cost=500, min_travel_lanes_for_deadend_uturn=1, deadend_uturn_cost=0): """ Return the default cost function for building the segment->segment nework. Doesn't...
3945b743514665542e88386cc50d3b7a52298205
73,047
def binary(num, length=8): """ Format an integer to binary without the leading '0b' """ return format(num, '0{}b'.format(length))
6c02431c7ae3c00415f23c812b3cd21eae7aaf4c
73,052
def addFontColor(value, arg) : """Return the given string between <font>...</font> markup. string is colorized by the color given in arg.""" for color,status in ( ('green','UP'), ('green','OK'), ('red','CRITICAL'), ('red','DOWN'), ('gold','WARNING'), ('violet','UNKNOWN') ) : if arg == status : retu...
73a0f89f8b65c0e8a76599d0df2fb0582a391b65
73,056
def to_page_range(entry): """ Contructs a range object from a single entry for the pages it accessed. Range has increments of 8 because page access in the traces are in multiples of 8. """ parts = entry.payload.split(' ') sector = int(parts[0]) try: blocks = int(parts[2]) except...
dddc960601f937953a150c3132048bb8823e1434
73,057
import torch def invSquare(input, axis=1): """ Apply inverse square normalization on input at certain axis. Parammeters: ---------- input: Tensor (N*L or rank>2) axis: the axis to apply softmax Returns: Tensor with softmax applied on that dimension. """ input_size =...
ca7c7702ab1d36cf2ae474dbf10981bf1dab7f4b
73,062
def get_float_from_config(config, section, key, default=None): """ Get a value from the config if it exists, otherwise return the default value :param config: The configuration to get the value from :param section: The section to get the value from :param key: The key that may or may not exist :...
9831fa525f363fbe2bd75dc2eeedcc124ae4f55b
73,063
from typing import Tuple import random def estimate_probability(n: int, num_goat: int =2) -> Tuple[float, float]: """Monty hall paradox Wiki: https://en.wikipedia.org/wiki/Monty_Hall_problem Parameters ---------- :param n: number of repetitions of the experiment, n >= 1 :type n: int ...
42a5dfba0b688800905439a7c4ba25aea3e1bdd4
73,068
def _filter_by_country(tools, country): """Filters sliver tools based on the tool's country.""" return filter(lambda t: t.country == country, tools)
a3e991e5cf2d9a307169064d793a8a57c522fe25
73,071
import re def get_coincidences(text, coincidences, unique_values = False): """ Looks for the coincidences list strings in the text variable and return a list with the coincidences. :param text: a string :param coincidences: a list of strings. The strings to looking for in the text. :param unique_v...
804c0aa62f8e8e7fc9e9f1f1788d8c4185ee0f72
73,073
import ipaddress def ip_itoa(ip: int, v6: bool) -> str: """Converts an IP integer 'ip' to a string.""" if v6: return str(ipaddress.IPv6Address(ip)) else: return str(ipaddress.IPv4Address(ip))
953b4d83e6e1906d68a89a0c757a67abe5c7b21d
73,074
from typing import List from typing import Set def get_unique_values(rows: List[List], column_index: int) -> Set: """Find the unique values for a column in a dataset. Args: rows: The rows of the dataset. column_index: Column index to get the unique values of. Returns: A set of th...
d3cb1b503af483f214b859d2cd245c3bd1cf4bcb
73,076
def perm_or_factory(perm, *args, **kwargs): """Check if perm is a factory (callable) and if so, apply arguments. If not, just return the perm.""" if callable(perm): return perm(*args, **kwargs) return perm
01d6c219009926e335bca8d4e988172cb4ffe3b1
73,077
import pathlib import zoneinfo def get_zoneinfo_path() -> pathlib.Path: """Get the first zoneinfo directory on TZPATH containing the "UTC" zone.""" key = "UTC" for path in map(pathlib.Path, zoneinfo.TZPATH): if (path / key).exists(): return path else: raise OSError("Cannot ...
1df867dd946a097692bc7a450d5d7d7d0fdd67cb
73,078
import torch def numpy_to_torch32(numpy_array): """Convert numpy array into torch float32 tensor""" return (torch.from_numpy(numpy_array)).to(torch.float32)
61b76ca89a68df17d103754a22c6444618fd913e
73,081
def check_blank_line(message): """Check if there is a blank line between subject and a paragraph.""" splitted = message.splitlines() if len(splitted) > 1: # check should only be needed for multyline commit messages check = not splitted[1] else: check = True return check
956d6dc70249d74ef8190a795b9a6260ce9cc477
73,086
def _starts_with_space(line, return_on_blank=True): """ returns true if line starts with space :line: the line to be examined :return_on_blank: what to return if line == "" :returns: True if starts with space, False else """ try: return line[0] == ' ' ...
fe992032343f79e321705e1d4f7cca25acc46d9a
73,087
def make_shortcode(content: str, shortcode: str, *arguments: str, **kwargs: str) -> str: """Returns a shortcode built from the arguments, with the form {{< shortcode *args **kwargs >}}content{{< / shortcode >}}""" key_value_pairs: str = " ".join(["{}={}" for key, value in kwargs.items()]) return "{{{{< ...
0893c5b9cab2ccb00bed9b27b09c8757fb85b9f0
73,089
def graph_resources(processor, graph): """Create graph with the overall hierarchy of resources.""" if len(processor.organizations) > 0: for org in processor.organizations: graph.graph_organization(org) elif len(processor.folders) > 0: for folder in processor.folders: ...
1bfeb439b512f260a45f4a0fa92c6b7062f19997
73,093
def gamma_PML(x, gamma, PML_start, PML_thk): """ Polynomial stretching profile for a perfectly matched layer. Parameters: x : physical coordinate gamma : average value of the profile PML_start : where the PML starts PML_thk : thickness of the PML Returns: the va...
3d5bcc5aeb997e429a000b51957c61dd00661a45
73,094
def normalize_version_number(version_number): """Clean up the version number extracted from the header Args: version_number (str): Version number to normalize. Returns: The normalized version number. """ return version_number.replace('.', '_')
7cd50b850ed132a7b5e07df3596f07fa3d396a0e
73,096
import json def read_json_file(filename): """ Reads Json file Parameters: filename (string) : filename of json file to be read Returns: list of people and their stress level """ try: with open(filename, "r", encoding='UTF-8') as read_file: data = json.load(r...
647548135898ba06856ca647edb74332d324aafd
73,097
def SplitListByGrouping(list, x): """ Receive a list of items. If the length is longer than x, then split the list into several lists, each with a maximum of x elements. This is then returned as a 2D array. Args list: list of items in any format or mixed. e.g. ['AB...
87866fe3a1e62ec0421080e20b6880335d84f18c
73,098
from typing import List def producing_node_identifier(nodes:List[str])-> dict: """function to assign an unique identifier to the nodes param nodes: list of nodes in the PPI file return: dict containing node,identifier pair""" # assigning node identifier node_list={(index+1): node for index,no...
d3d9dbc79563f563d3ba9570b7e824f09ca25b96
73,101
import re def sanitize_input_name(name: str) -> str: """Sanitizes input name.""" return re.sub('[^_0-9a-z]+', '_', name.lower()).lstrip('_').rstrip('_')
84401f8da2f214e0a14afac8f84b80f28262e95c
73,103
def trim_slice(lines, slice_tuple): """ Trim a slice tuple (begin, end) so it starts at the first non-empty line (obtained via indented_tree_line_generator / get_line_info) and ends at the last non-empty line within the slice. Returns the new slice. """ def _empty(line): return not line ...
dd9bdb26eb7fddd2c856bb5a4b7a5acbf83ba59d
73,105
def create_core_file(duthost, docker_name=None): """ Create .core file in SONiC or inside in docker container :param duthost: duthost object :param docker_name: docker name - in case when you need to create .core file inside in docker container """ cmd = 'bash /etc/sonic/core_file_generator.sh' ...
ed8da0d355ae567fe71e76d4f32f21140c820371
73,106
from datetime import datetime def exceeds_threshold(last_run_created, threshold): """ Check whether a Mill run has exceeded the run threshold. This explicitly ignores timezones since the datetime should be UTC. Granularity smaller than a second is ignored. :param last_run_created: A datet...
a9fee3e59a35d43c7f0a1e133cf22fea9cdf74ca
73,107
def calc_share_weird_states(data_individual_mixed, data_group_mixed): """ In some states the strategy of the algorithm does not perfectly align with the win-stay lose-shift strategy described in the paper. I calculate the share of those states here (there are very very few). Args: data_indi...
93ffef5f09468a825d7c5931fb055533f47ef864
73,110
def convert_alt_list_to_string(alt): """ The ALT field in the VCF file is represented as a list, can convert this to a comma seperated string. """ _vars = list() for _var in alt: _vars.append(str(_var)) return ','.join(_vars)
11aef24df506094d711eb6e8e644a1272d461c78
73,123
def reconcile_sensors(sensor_key_list): """ Make a list of the unique sensors from a set of fits """ sensor_list=[] for this_dict in sensor_key_list: for key in this_dict.keys(): if key not in sensor_list: sensor_list += [key] return sensor_list
20870cce904e45de2ca63065b54b478e7911eb10
73,131
import typing import collections def route(url: str, methods: typing.Iterable[str] = ("GET", "HEAD"), **kwargs): """ A companion function to the RouteGroup class. This follows :meth:`.Blueprint.route` in terms of arguments, and marks a function as a route inside the class. This will return the o...
b0b0af22507e47d37f787abc712018fe38397f2a
73,133
import socket def get_ip_addr(return_string=True): """ Return IP Address of current host """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8",80)) ip_addr = s.getsockname()[0] s.close() return str(ip_addr) if return_string else ip_addr
174cb30ad425a053387c10d071d8970b376f9d31
73,136
def _extract_class(name: str) -> str: """Extract a predicted class name from DAI column name. Examples: >>> _extract_class('target_column.class1') 'class1' """ return name.split('.')[-1]
525d0dd47566ce32835d41979468e4a3b04c3b01
73,143
def write_output(init_dict, df): """The function converts the simulated variables to a panda data frame and saves the data in a txt and a pickle file. """ # Distribute information source = init_dict["SIMULATION"]["source"] df.to_pickle(source + ".grmpy.pkl") with open(source + ".grmpy.txt",...
a317bf570d95ef22b853f55591b5e2414071f8ac
73,144
def _ReorderMapByTypTags(result_map): """Rearranges|result_map| to use typ tags as the top level keys. Args: result_map: Aggregated query results from results.AggregateResults Returns: A dict containing the same contents as |result_map|, but in the following format: { typ_tags (tuple of st...
749a9abd18c0270d4d93f0e3c1092d53fcd237df
73,146
def create_demand_table(connector, demand_list, years): """ Writes a ``demand`` table to an SQLite database. Parameters ---------- connector : sqlite3 connection object Used to connect to and write to an sqlite database. demand_list : list A list of DemandCommodity objects. ...
f3c1410f934a25702f7474a582f5e7115baed541
73,147
def link_artist(artist_id): """Generates a link to an artist Args: artist_id: ID of the artist Returns: The link to that artist on Spotify """ return "https://open.spotify.com/artist/" + artist_id
2ba752b848f6bebc599107c715ff9287df1264a9
73,148
def box_overlap(row, window): """ Calculate the Intersection over Union (IoU) of two bounding boxes. Parameters ---------- window : dict Keys: {'x1', 'x2', 'y1', 'y2'} The (x1, y1) position is at the top left corner, the (x2, y2) position is at the bottom right corner bo...
5997c1d4085521562722257b2b78377ab8c7bdcc
73,151
from typing import TextIO import json import io def combine_clks_blocks(clk_f: TextIO, block_f: TextIO): """Combine CLKs and blocks to produce a json stream of clknblocks. That's a list of lists, containing a CLK and its corresponding block IDs. Example output: {'clknblocks': [['UG9vcA==...
9d2304b3fdcdcf79d791247165b3fa4c8dc8f339
73,152
def snp_count(vcf, chromosome, start, end): """ Count the number of snps in the window. :param vcf: vcf, a vcf file with SNPs and their genomic positions :param chromosome: str, Chromosome name :param start: int, Start position of the sequence :param end: int, End position of the sequence :r...
c18f52662f96d3013452c4884f506901e9da146b
73,153
def get_guidelines(lang): """Returns a localized url for the download of the user_guidelines. """ elri_guidelines='metashare/ELRI_user_guidelines_'+lang+'.pdf' return elri_guidelines
1a72ab831c7752d156679f69a1972da0904ab556
73,154
def amz_group_grant(uri, permission): """ Returns XML Grant for group with URI. :param uri: group URI :param permission: permission value """ grant = ( '<Grant>' '<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' 'xsi:type="Group">' '<URI>%s</URI>'...
6db69daa14e2c24544e4a2639a7b9229a15135d4
73,156
def escapeXMLChars(text): """Controls characters that need to be escaped (to obtain a well-formed XML document) Args: text: The text that will be escaped (string) Returns: text: new text containing XML entities instead of characters (string) """ text = text.replace("&", "&amp;"...
284bfefb400ebe5381a2b9454a2a8b15f199f36d
73,157
def alpha_B_HII(temperature): """ Calculate the HII recombination rate This is the rate at which ionised hydrogen recombines into neutral hydrogen Total recombinations per second per unit volume = alpha * ne * nH ne = electron number density nH = hydrogen number density Parameters ...
b3cb5b00c7a06cf42847725de6b0c9efad320806
73,162
def _PyEval_SliceIndex(space, w_obj, pi): """Extract a slice index from a PyInt or PyLong or an object with the nb_index slot defined, and store in *pi. Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX, and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1. R...
73c065681793dd93045557c42289cae3c64f16d3
73,165
import torch def make_initialization_inputs(inputs, device=None): """ Take either tensor, shape tuple or list of them, and always return tensor or list of them. """ if isinstance(inputs, torch.Tensor): pass elif isinstance(inputs, tuple): inputs = torch.rand(*inputs, device=device) eli...
e255fbce01f412088d635e31776c6b348a0a3926
73,166
def html_table_to_dict_list(soup_table): """ Input: - 'soup_table': a Beatiful soup object that was selected by the tag 'table'. Returns a list of dicts containing the table's data. It assumes the header is marked by 'th' tags. """ trs = soup_table.find_all('tr') html_header ...
36e1b5eaa1557d5eb62f41993299341c1e03131e
73,178
def to_bytes(value) : """ Decodes value to bytes. Args: value : Value to decode to bytes Returns: :obj:`bytes` : Return the value as bytes: if type(value) is :obj:`bytes`, return value; if type(value) is :obj:`str`, return the string encoded with UTF-8; ...
e38b7348c84d570caa2891b1d3be8fa789eda615
73,180
def str_to_bytes(value): """Return bytes object from UTF-8 formatted string.""" return bytes(str(value), 'UTF-8')
4bc843b070d50046b9099a8163be1888a3ba541d
73,182
def get_lattice_points(tup1, tup2, check_diagonals = True): """Returns a list of points which lie in a line defined by two endpoints""" x1, y1 = tup1[0], tup1[1] x2, y2 = tup2[0], tup2[1] # for horizontal lines, y values are same if y1 == y2: if x1 <= x2: points = [(i, y1) for i ...
8d6c5780ce227ae7b70480e929ff7e44c070d14e
73,183
def calc_total_biomass(available_forage): """Calculate the total biomass across forage types, in kg per ha.""" sum_biomass = 0. for feed_type in available_forage: sum_biomass += feed_type.biomass return sum_biomass
b94f025381526ebf58c2e01b2a60e9b1083be6b7
73,184
def load_text(filename): """Load text file Parameters ---------- filename: str Path to file Returns ------- text: string Loaded text. """ with open(filename, 'r') as f: return f.readlines()
eda3f0f05b3bc924e9d0e80dfa78b29dbbbfc7ed
73,187
def addDot(num): """Formats the number into a string and adds a '.' for every thousand (eg. 3000 -> 3.000) Parameters ---------- num : int integer number to format Returns ------- number : str a string representing that number with added dots for every thousand """ return '{0:,}'.format(int(num)).replace(...
9ac4b98a43539d123a7515328585bfb7a216d3e1
73,188
def cookie_repr(c): """ Return a pretty string-representation of a cookie. """ return f"[key]host=[/key][cyan3]{c['host_key']}[/cyan3] " +\ f"[key]name=[/key][cyan3]{c['name']}[/cyan3] " +\ f"[key]path=[/key][cyan3]{c['path']}[/cyan3]"
26720d914481ec52c230be12602052ea61b736c0
73,195
def intcode_four(parameter_list, code_list): """ Prints item in parameter_list[0] place in code_list. Returns True. """ print(parameter_list[0]) return True
2ec2ec368b9c37fbb9a2bcecd01cb939e3decda2
73,200
import torch def train_loop(dataloader, model, loss_fn, optimizer, device): """ training loop Arguments: dataloader: pytorch dataloader for training model: pytorch model loss_fn: the loss function to train the model optimizer: the optimizer to train the model device...
fcc8915209db69b45899ace83dad61a5f027a4a2
73,208
from typing import Any def str_to_python(value: str) -> Any: """ Convert a node value (string) into python native equivalent :param value: incoming variable string :returns: value as a native Python data type :rtype: Any """ try: if "." in value: # assume to be float ...
3d441d1a7eaa12a2eb6f03be302b1d06b00b84bb
73,213
from typing import Union def get_list_value(lst: Union[list, tuple], inds): """get value form index. Args: lst (Union[list, tuple]): target list. inds (Any): value from index. Returns: list: result """ return [lst[i] for i in inds]
9b57377011b792714aaa21b90016e04ef85f68d1
73,215
def get_up_hill(hosp_data): """Given the temporal data of a hospital, get the portion of the timeline belonging to an up-hill peak, up to the point of the first critical state is found. Parameters ----------- hosp_data: pd.DataFrame Historical capacidad hospitalaria of a single hospital...
5abc81776260f9e36f0b7b97684888172cccb0c8
73,216
import random def should_drop(drop_percentage): """ Based on the given percentage, provide an answer whether or not to drop the image. Args: drop_percentage: the likelihood of a drop in the form of a float from [0,1] Returns: a boolean whether to drop or not drop the image """ ...
f624577d0941c93a83db54f987dda57b7d03a5ea
73,222
def parse_instruction(raw_instruction): """ ABCDE (0)1002 DE - two-digit opcode, 02 == opcode 2 C - mode of 1st parameter, 0 == position mode B - mode of 2nd parameter, 1 == immediate mode A - mode of 3rd parameter, 0 == position mode, omitted due to being a leadin...
bcf4995be4e03f30dfe7a502f958ae2746cb0ec7
73,229