content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import struct def _decode_long(fp): """Decode a long integer tag :type fp: A binary `file object` :rtype: int """ return struct.unpack('>q', fp.read(8))[0]
914751cb11c531fc8655076661140b25f7d7720b
575,937
def quick_info_retrieve_doc_template_values(url_root): """ Show documentation about quickInfoRetrieve """ required_query_parameter_list = [ { 'name': 'kind_of_ballot_item', 'value': 'string', # boolean, integer, long, string 'description': 'Wh...
096e49b4a1901c94d8bd2feaaf4cbe71ca26dfe0
575,938
def comb(N, k): """ The number of combinations of N things taken k at a time. Parameters ---------- N : int, array Number of things. k : int, array Number of elements taken. """ if (k > N) or (N < 0) or (k < 0): return 0 val = 1 for j in range(min(k, N -...
1ed8afd8be51e5b62d360a9359304cc9cf4466cd
575,943
def __determine_resource_obj(service, resource): """Find the desired resource object method container from the service. Args: service: [stub] Google API stub object. resource: [string] '.' delimited resource name in service API. """ path = resource.split('.') node = service for elem in path: t...
91687f196397ddde292368d4e4429b2a5f32850a
575,944
def create_model_query(model_names): """Construct the Odoo domain filter :param model_names: the requested list of Odoo model names :return: the Odoo domain filter >>> create_model_query([]) [] >>> create_model_query(['sale.order']) [('model', '=', 'sale.order')] >>> create_model_q...
2402416db85f62a7cb16985c0c577ae098503d6b
575,951
from typing import List import math def even_groups(n: int, no_groups: int, rank_output: bool = False) -> List[int]: """ returns an array of lengths normal out put e.g. even_groups(n=5, no_groups=2) -> [3,2] :param rank_output: default False; if True -> function returns an array of ranks not of group ...
79fbe2278f2798900b5855b0085b27df8312a49b
575,952
def guess_realert_every(chronos_job_config): """Returns the job interval (in minutes) or None if the job has no interval. As we run check_chronos_jobs once a minute, we are going to skip all re-alert attempts until the next scheduled run of the job. This value is clamped by 1 day (1440 minutes) becaus...
cf8a3e7e7b12d79799c28cdcf88001a25680aea2
575,955
def missing_numbers(arr, brr): """Hackerrank Problem: https://www.hackerrank.com/challenges/missing-numbers/problem Numeros the Artist had two lists that were permutations of one another. He was very proud. Unfortunately, while transporting them from one exhibition to another, some numbers were lost out of...
c9ae9d4a26234be9b9de7adac4c49590585d81f6
575,961
import torch def mle_loss(uv_hat, uv, cov): """ Calculate the MLE loss :param uv_hat: reprojected uv shape(..., 2) :param uv: UV measurements shape(..., 2) :param cov: 2x2 covariance matrix for uv shape(..., 2, 2) """ res = uv - uv_hat # Ensure cov invertable cov[...,0,0] ...
4c1a7d4c54c6a130fea5b87898a9514fb6af231a
575,962
def format_template(template, **kwargs): """ Replace {{keys}} elements in template with the matching value in the kwargs dictionnary""" if template is None: return None formated = template for key in kwargs: replacement = kwargs.get(key, "") formated = formated.replace("{{{{{}}}}...
2d22d36e800d516bf8fe4bc29c12652a3a7ce80d
575,963
def tariff_transform(value): """Transform tariff from number to description.""" if value == "1": return "low" return "high"
5a32cc3416f9d5998c3dd6594d3c33d2578d875a
575,965
def parse_arg(x): """ Parse a string argument and attempt to turn numbers into actual number types. Parameters ---------- x : str A string arg. Returns ------- str, float, or int x type converted. """ if x.replace('.', '').isdigit(): if ...
4ab80da7070d1740ac3d7428174e7e7531103964
575,966
import re import json def json_variables_extractor(response, variables): """Extracts variables from json response.content. Variables path are written using 'dot' access and index access to lists f.i.: some.path.to.list.[0] [1].dict.access.later """ result = {} re_list = re.co...
a00432b62746c4242a7d92d2a4b6cc15eef454bd
575,968
def golden_ratio(figwidth=5): """Return the figure size (width, height) following the golden ratio given the width figwidth (default = 5)""" Phi = 1.61803 a = figwidth / Phi return [ figwidth, a ]
e8236a0a7107c950e2af26ef4824d52064a5f03d
575,971
import hashlib def get_file_sha256(filename: str) -> str: """ Get SHA256 has of a file :param filename: The path to the file. :return: Hexadecimal SHA256 hash as string. """ with open(filename, "rb") as f: file_bytes = f.read() readable_hash = hashlib.sha256(file_bytes).hexdige...
c37d9ed4a1c0b651b1f7c33a83931f0dd06cdd62
575,974
def step(x, low, high, th): """ Step function is low if x<th, else it is high """ return low*((x<th).astype(int)) + high*((x>=th).astype(int))
0e4d64fbf9af2fbcc28286049071a28961290d58
575,975
def relative_intensity(norm_power, threshold_power): """Relative intensity Parameters ---------- norm_power : number NP or xPower threshold_power : number FTP or CP Returns ------- float IF or RI """ rv = norm_power/threshold_power return rv
2b00dbb00ad61964ec6d878d4940fa7df15ba4ca
575,976
def get_tag(tokens, tag): """Extracts the value inside the given tag.""" start = tokens.index('<' + tag + '>') + 1 stop = tokens.index('</' + tag + '>') return tokens[start:stop]
a0b5dac7f305886798275845f8ad139a7a3ef87f
575,986
def is_or_node(node): """Returns True if the given node is a or node.""" return getattr(node, "_node_type", None) == "or"
dbccace08793f8c03eb67e3b7aabcb2dd9c41576
575,991
def is_inverted(photo_interp: str) -> bool: """Checks if pixel value 0 corresponds to white. See DICOM specification for more details.""" if photo_interp == "MONOCHROME1": return True elif photo_interp != "MONOCHROME2": # I don't think we need to handle any interpretations besides MONOCHROME...
8f842b9df6408a2e0a2fa315df7050965365b91d
575,997
import requests import json def update_task_id(task_id=None, gman_url=None, status=None, message=None): """ Updates a taskID status and/or message :param task_id: TaskID to update as a string :param gman_url: GMan endpoint as a string :param status: The status to apply to the task :param messa...
913d29e3d5bca43d541c0ef3912416c5cacc7354
576,000
def feature_types(df): """ Get feature types Args: df: pd.DataFrame, input data Returns: f_types: feature type """ ftypes = {} ftypes['num_cols'] = [str(x) for x in df.select_dtypes(include=['int32', 'int64', 'float32', 'float64']).columns] ftypes['cat_cols'] = [str(x) f...
72f6dfebd159a274e9a8eed5c7ccb6da25c6d8c6
576,003
def row_to_index(row): """ Returns the 0-based index of given row name. Parameters ---------- row : int or unicode Row name. Returns ------- int 0-based row index. Examples -------- >>> row_to_index('1') 0 """ row = int(row) assert row > 0...
cfeba1bf04565ce1eb458c55d2c165b057ed8fbb
576,007
def dictreverse(mapping): """ Returns a new dictionary with keys and values swapped. >>> dictreverse({1: 2, 3: 4}) {2: 1, 4: 3} """ return dict([(value, key) for (key, value) in mapping.iteritems()])
32a1fcb5ab4d7d6c25ac4ec381334e8494781fb0
576,008
def computeNumberOfTrainingPairs(obs_seqs, history_len, prediction_horizon): """ Computes the number of different training pairs (target, input) for given sequences of observations and actions. Note that it also depends on the history length and prediction horizon. """ nrollouts, length, _ = obs...
d9fa8364f25d245b59fd439824994680c16ffa9a
576,009
import json def read_json_file(filepath): """ Read articles from a json file. :param filepath: path to a file to read :return : json data from file """ with open(filepath) as infile: data = json.load(infile) return data
d070115bb034829dfc4a3a0629a5fb0558e2bd24
576,010
def get_endpoint(endpoint: str) -> str: """Returns the lowercase name of the SCIM endpoint""" return endpoint.strip("/").lower()
38dea31ff26aeb4bcb8cf4cef1347c8cc26d3d26
576,013
from typing import Any from pathlib import Path def ensure_path(path: Any) -> Any: """Ensure string is converted to a Path. path (Any): Anything. If string, it's converted to Path. RETURNS: Path or original argument. """ if isinstance(path, str): return Path(path) else: return...
90d8d78da32931ac521a30795543a0e4b25e51ae
576,015
def rows_to_columns(arr): """ For an array of the shape [[x1, y1, z1], ..., [xn, yn, zn]] returns an array of the shape [[x1, ..., xn],[y1, ..., yn],[z1, ..., zn]]. """ return arr.reshape(arr.size, order="F").reshape((3, -1))
f38865d9692804873c13824fdddec7e8e1b61bc9
576,019
def delSyno_no_tax(connection): """ Suppresses the synonyms which are not associated with any accepted taxa Parameters: ----------- connection: psycopg2 Connection connection to the database Returns: -------- List of suppressed taxon identifiers """ cur=connection.cursor...
1ae3afa2c3bf6094170d008aba007b2ad5f7b999
576,022
def _cut_series_by_quantile(df, ts_settings, quantile=0.95, top=True): """ Select top-n or bottom-n series by quantile df: pandas df ts_settings: dict Parameters for datetime DR projects quantile: np.float threshold for series to select top: bool Select highest (True...
6f9a418721eb830a1f83e84941db659c1a5f354b
576,023
def _manhattan_distance(vec_a, vec_b): """Return manhattan distance between two lists of numbers.""" if len(vec_a) != len(vec_b): raise ValueError('len(vec_a) must equal len(vec_b)') return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))
773ee40a2a4164f35331bd64f50686365e5c8a8e
576,024
import json def get_apartments_list(page_souped): """ Takes a page that has been passed through BeautifulSoup and gets the list of results on the page. :param page_souped: <class 'bs4.BeautifulSoup'>, a page that has been passed through BeautifulSoup(). :return: list of dictionaries from the given...
e8ea8369fe27711553dcc238001c50d295a40e22
576,028
def subset(shape, dims): """Returns the dims-th elements of shape.""" out = [] for dim in dims: out.append(shape[dim]) return out
1eb66727f124f7769bf64b454f0a7d0f8e9a54c4
576,029
def count_res_in_frag(residues, min_frag_len=3): """Count the number of fragments in a list Parameters ---------- residues : list A list of residue indexes min_frag_len : int The minimum length in residues of a fragment [default: 3] Returns ------- int The numb...
bbb43228373c1dee55f6dcb1df6311b19a80d263
576,031
def get_client_ip(request): """get a client IP like: "remote_addr=255.255.255.255 forwarded_for=10.0.0.0 42.0.32.12 ..." ... up to 250 characters. """ xff = request.META.get('HTTP_X_FORWARDED_FOR') ra = request.META.get('REMOTE_ADDR') if xff and ra: ret = "remote_addr=%s forw...
f4d96f212920ccd364ba7b3ea37d1747d88c3bbb
576,033
import re def remove_extra_spaces(raw_sentence): """ This method removes more than one continuous spaces and reduces to only one space. :argument: :param raw_sentence: String :returns: clean_str: String which does not contain more than 1 continuous white spaces. """ clean_str ...
84a7ea0e744637cb7336dae39240f26e6bafbb40
576,035
import torch def compute_iou_tensor(box, boxes, box_area, boxes_area): """Calculates IoU of the given box with the array of the given boxes. box: 1D vector [y1, x1, y2, x2] boxes: [boxes_count, (y1, x1, y2, x2)] box_area: float. the area of 'box' boxes_area: array of length boxes_count. Note: ...
8adced0c49a17db89557338b9fc14e8316399e34
576,036
def get_filename(filename, suffix): """ Adds a suffix to a filename. Parameters ---------- filename : str Current filename suffix : str String to add to the filename Returns ------- str New filename """ name_without_filetype = filename.split(".")[0] ...
1a8c8f6682dcf538b90ef813ff282e68bb543e72
576,037
def forgiving_join(seperator, iterator): """ A join function that is more forgiving about the type of objects the iterator returns. """ return seperator.join(str(it) for it in iterator)
b78458c7f94f68c40df25852c3c6a1ea5f46af62
576,044
def return_real_remote_addr(env): """Returns the remote ip-address, if there is a proxy involved it will take the last IP addres from the HTTP_X_FORWARDED_FOR list """ try: return env['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip() except KeyError: return env['REMOTE_ADDR']
fd1e51ba4fde3a67a800e516fa15ebd8ec873650
576,047
import re def extract_string(string : str) -> str: """ Removes some bad characters that get read in wrong. It has to do with the ^2 in the columns names. :param: string (str): string to strip :returns: The same string with any bad characters removed. :rtype: str """ return str(re....
7760e77c2400d18aa6bbd6a38ee9be4d78e2a39f
576,048
import logging import time def _shutdown_proc(p, timeout): """Wait for a proc to shut down, then terminate or kill it after `timeout`.""" freq = 10 # how often to check per second for _ in range(1 + timeout * freq): ret = p.poll() if ret is not None: logging.info("Shutdown gracefully.") ret...
2d566da9ba1c8e508d2a1d22d5c7000aeef787aa
576,050
def fix_sequence_length(sequence, length): """ Function to check if length of sequence matches specified length and then return a sequence that's either padded or truncated to match the given length Args: sequence (str): the input sequence length (int): expec...
300566ba387ac33709ed2e9eef28f1ab65ed5f60
576,054
def eval_print_fn(val, print_fn): """Evaluate a print function, and return the resulting string.""" # The generated output from explain contains the string "\n" (two characters) # replace them with a single EOL character so that GDB prints multi-line # explains nicely. pp_result = print_fn(val) ...
0e91cc5848f8c6955db2ed5a49b2570f6f9adf92
576,060
import re def is_bip66(sig): """Checks hex DER sig for BIP66 consistency""" #https://raw.githubusercontent.com/bitcoin/bips/master/bip-0066.mediawiki #0x30 [total-len] 0x02 [R-len] [R] 0x02 [S-len] [S] [sighash] sig = bytearray.fromhex(sig) if re.match('^[0-9a-fA-F]*$', sig) else bytearray(sig...
3371b2bc6bf43fbd8711874501cd0575cfebbbdb
576,061
def is_insight_article(article): """is an article object an insight article""" if ( hasattr(article, "article_type") and article.article_type == "article-commentary" ): return True return False
9c1fdcb7b18101a6153a3dae34471ec7a7b3adf6
576,065
def flatten_dict(config): """Flatten a hierarchical dict to a simple dict.""" new_dict = {} for key, value in config.items(): if isinstance(value, dict): sub_dict = flatten_dict(value) for subkey, subvalue in sub_dict.items(): new_dict[key + "/" + subkey] = subvalue elif isinstance(val...
3bcff2ba208270708c724363fbc4720306a73783
576,066
def a_group(trans,rots): """This subroutine combines that translations of the lattice with the rotatians of the lattice. Args: trans (list): A 2D array where each row is an translation of the lattice. rots (list): A 3D array. Each row's first entry is the site permutati...
218c428bd0a0e14057220b9f48417680a7da3cf4
576,067
def add_gis_ft1(super_df, sub_df, super_unit): """Identifies super_unit to with sub_unit belongs (based on centroid) and returns updated sub_df with super_unit column""" for index, row in sub_df.iterrows(): for super_index, super_row in super_df.iterrows(): if row['geometry'].centroid.within...
55ec720d78020bfdead1424455094f892ba7773e
576,068
def get_running_mode(enduse, mode_constrained, enduse_space_heating): """Checks which mode needs to be run for an enduse. Arguments ----------- mode_constrained : bool Criteria of running mode enduse_space_heating : dict All heating enduses across all models Returns -------...
2c790e7f0590060df650ed2b64ee03741840659f
576,070
import tempfile def get_file(content): """ Generates a temporary file in '/tmp' with `content` and returns the file name. """ if isinstance(content, list) or isinstance(content, tuple): content = "\n".join(content) fde = tempfile.NamedTemporaryFile(mode="w", delete=False) fname = fde.n...
1e84139a4799b0e0789a5f49f9630af3501839f1
576,071
def update_driver_profile_name(driver, name): """ Updates the name of the driver :param driver: driver :param name: new name :type driver: DriverProfile :return: updated driver profile """ return driver.update_driver_profile_name(name)
376234b737cdf53267bb1920482a86adf094d1a8
576,077
def finnish_iban_to_bban(iban: str) -> str: """ Convert a Finnish bank account number from IBAN to BBAN machine language format. :param iban: Account number in IBAN format :return: Account number in BBAN machine language format :raises ValueError: If IBAN is in incorrect format """ len_iban...
e29e3a1c9b06d300a8f7dda83de290b16f527d7f
576,081
def pick(record, field, default=None): """Get the value for a key in a dict, or None if there is no dict. !!! warning But if the value for `field` in the record is `None`, `None` will be returned. Parameters ---------- record: dict | `None` `pick` should work in both cases. fie...
5f56cc0ac9a415d335f9709236b444013311e5ef
576,082
def all_points_core_distance(distance_matrix, d=2.0): """ Compute the all-points-core-distance for all the points of a cluster. Parameters ---------- distance_matrix : array (cluster_size, cluster_size) The pairwise distance matrix between points in the cluster. d : integer The...
dd0b44441d7b7a48183fcc2dec07b4f6f4c603be
576,083
def count_models(hyper_params): """ Given a hyper_params dict, this function will return the maximum number of models that can be built out of all the combination of hyper-parameters. :param hyper_params: dict containing parameter name and a list of values to iterate over :return: max_model_number:...
3bb3cea75a3c95cab9674ad860dff34961930ed4
576,086
def dec_to_bin(decimal: int, length: int) -> str: """将十进制数转换为对应的 01 字符串。 Args: decimal: 十进制整型数。 length: 转换后的 01 字符串长度。 Returns: 转换所得的 01 字符串。 """ if decimal >= 0: return bin(decimal)[2:].zfill(length) else: return f"1{bin(decimal)[3:].zfill(length-1)}"
886b2dba9a90d31f72148b8617d69e310147d977
576,090
def get_pgroupvolume(module, array): """Return Protection Group Volume or None""" try: pgroup = array.get_pgroup(module.params['name']) for volume in pgroup['volumes']: if volume == module.params['restore']: return volume except Exception: return None
f27289ad3c9e72333eba04ee3af7e2fd4ea331b9
576,092
def expand_gids_in_list(e, L): """ Return list L with all gids replaced by their cid-list equivalent. Here L is a list of mixed cid and gid identifiers. Duplicates removed in output, of course. The operation preserves the order of the portions (like a contest-free grammar, if there are no cycl...
9259132dee7e6a33fbe1f6e55425b4c47e0f67e2
576,095
def distinct(ary): """eliminate duplicate items from list""" return list(set(ary))
e787cb7029c42b4d372833cc4daebfa9ce04a0c1
576,096
def average_rating(rating_list): """Helper method that calculates the average rating of a book.""" if not rating_list: return 0 return round(sum(rating_list) / len(rating_list))
e0fa64abb12e51793d6f148a9be81ca543a03025
576,097
import torch def validating(network, loader): """ Validating the network during and after training :param network: trained network :param loader: dataloader :return: accuracy """ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") correct_num = 0 total_num = 0 ...
ec8bdb219776bb612e68c49513f048e88c8a5457
576,101
def rotateBitmap270(bitmap): """ Rotates the `bitmap` 270 degrees. """ width = len(bitmap[0]) height = len(bitmap) rotated = [[0 for i in range(height)] for j in range(width)] for x in range(width): for y in range(height): rotated[x][y] = bitmap[y][x] return rotat...
5425a96e3da572eebcf18aad762a70752261869e
576,106
def mfi(df, high, low, close, volume, mfi, n): """ The Money Flow Index (MFI) calculates the ratio of money flowing into and out of a security. To interpret the Money Flow Index, look for divergence with price to signal reversals. Money Flow Index values range from 0 to 100. Values above 80/below 20...
396c7ea5f8bf8fdf1d169722793fef47ebbf5dd7
576,107
def iterable_to_dict(items, key_attr_name): """Converts iterable of certain objects to dict. :param iterable items: :param string key_attr_name: Attribute to use as a dictionary key. :return dict: """ items_dict = {} for item in items: items_dict.update({getattr(item, key_attr_name)...
6a2e3905941371729dcc9976b24bd4934cd7402a
576,112
import re def process_django_output(output): """ Django's loaddata, depending on the verbosity setting, will output various things during and after the fixture loading process. It's all captured by our loaddata override. This method extracts the reported object and fixture counts from the output, ...
95f25ae49f0821367d00bf92cd9db71add929eb7
576,119
import networkx as nx def generateGraphFromTopology(topology): """Geneate a NetworkX graph from a Topology object. Parameters ---------- topology : simtk.openmm.app.Topology The source topology. Returns ------- graph : networkx.Graph The resulting graph, with nodes labele...
ecf113a0fda805635fe2c4b590970d09cd99b8e4
576,123
def int2roman(num): """ Convert an integer to Roman numeral """ if not isinstance(num,int): raise TypeError("expected integer, got %s" % type(input)) if not 0 < num < 4000: raise ValueError("Argument must be between 1 and 3999") ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) nums = ...
730808d764efe3ccc66b473502d1db15db7bbb09
576,125
def _hand_copy_line_to_line(original_object, new_object): """Copies one class object attributes to another class object""" new_object.action_amount = original_object.action_amount new_object.action_from_player = original_object.action_from_player new_object.all_in = original_object.all_in new_object...
485249f04243051e3607c94728b9b84318f242ab
576,128
import re def replace_halogen(string): """Regex to replace Br and Cl with single letters""" br = re.compile('Br') cl = re.compile('Cl') string = br.sub('R', string) string = cl.sub('L', string) return string
c4e4a7b5508d3a55a7ddc7bd1f03bf8f6b5a0a36
576,129
def numpy_mean(arr): """ Compute mean (average) using NumPy. Parameters ---------- arr : ndarray """ return arr.mean()
4ba8987159fb3c615e8bc7a7470b149032c2653d
576,133
def isBool(x): """ Returns True, if x is a boolean. >>> isBool(True) True >>> isBool(False) True >>> isBool(1) True >>> isBool(0) True >>> isBool(2) False >>> isBool('true') False """ if isinstance(x, int) and x in [0,1]: return True return isinsta...
9a4c655960e81691090eb56520c027d17e0cbec6
576,136
import torch def change_box_order(boxes, order): """ Change box order between (xmin, ymin, xmax, ymax) and (xcenter, ycenter, width, height). :param boxes: (tensor) or {np.array) bounding boxes, sized [N, 4] :param order: (str) ['xyxy2xywh', 'xywh2xyxy', 'xyxy2cxcy', 'cxcy2xyxy'] :return: (tensor)...
e9a6da01b2f3937c93ea76378561fd77aeb2c343
576,138
def _is_summary(l: str) -> bool: """Checks if the line is the summary line 'Found X errors in Y files (checked Z source files)'""" return l.startswith("Found ") and l.endswith("source files)\n")
0d387cf3985665e3802234a2a8c308ef46ed0cd5
576,139
def int_to_unsigned_bytes(num: int) -> bytes: """Create a 64 bit unsigned byte representation of a positive integer (for nonce hashing purposes) Args: num: A positive (<64 bit) integer Returns: byte object representation of number """ return num.to_bytes(8, byteorder="big", signed=Fa...
244bc17d022b8bbdc3bf708b7c459ac5c729866d
576,141
def sdp_del_LT(f): """Removes the leading from `f`. """ return f[1:]
41e09a2d4429030db21f335686a25134aa9040d3
576,144
def tb(tb): """Transform the tb dataset according to what was found in the explaratory analyses, available on sp_np.ipynb 1. Select only 'journal' and 'year' columns 2. Rename these two columns to 'Journal' and 'Year', with capitalization 3. Add a column named 'Source', with all rows = 'TreatmentBa...
dcb4f6a69033e4ef779129d7c0b58715a254536d
576,148
def simplified_pos(pos, tagset=None, default=''): """ Return a simplified POS tag for a full POS tag `pos` belonging to a tagset `tagset`. By default the WordNet tagset is assumed. Does the following conversion by default: - all N... (noun) tags to 'N' - all V... (verb) tags to 'V' - all AD...
0319b381531e11d9982f9d1243d22680451fc6fd
576,149
def power_tail(x,y): """return x^y with tail recursion""" def power_tail_helper(x, y, accum): if(y==0): return accum return power_tail_helper(x, y-1, x*accum) return power_tail_helper(x, y, 1)
7d46f8c338a47f24e1b55c4ac4f54d9db2e6a844
576,153
import random def get_random_value_hex(nbytes): """ Returns a pseduorandom hex value of a fixed length Args: nbytes (:obj:`int`): integer number of random hex-encoded bytes to return. Returns: (:obj:`str`): A pseduorandom hex string representing `nbytes` bytes. """ pseudo_ra...
52f4ceee542c0c63a0cb5c7da4992427c1151afd
576,162
def script_type_default(witness_type=None, multisig=False, locking_script=False): """ Determine default script type for provided witness type and key type combination used in this library. >>> script_type_default('segwit', locking_script=True) 'p2wpkh' :param witness_type: Witness type used: stand...
df2888c358181f5a9322e0959500c29cbc7fa7ea
576,164
def is_py(file_path): """ :param file_path: the path of a file :return: true if file is a python file(ends with .py) """ return file_path.split(".")[-1] == "py"
2ead1ebecd21b1c2da044b8c76920c5cb9004674
576,165
def Sum2num(a,b): """ Given two numbers add them and return a value """ sum = a + b return sum
b110e351bb5325ecd9369efd27668d2cb9f89028
576,167
def parse_oc(data_file, label_format='tuple'): """ Returns: X: a list of tweets y: a list of (affect dimension, v) tuples corresponding to the ordinal classification targets of the tweets """ with open(data_file, 'r',encoding="utf8") as fd: data = [l.strip().split('\t') ...
5df16e607365e130d25142e1663dd5c6e9c13f8b
576,171
import pytz def utc_datetime_to_button_format(utc_dt): """ Convert a UTC datetime obj to the the date and time format we need for slack buttons in Eastern time. """ eastern = pytz.timezone('US/Eastern') east_conv = utc_dt.astimezone(eastern) time_text = east_conv.strftime("%H:%M") dat...
81bce6e8f44f62eaba595d9384b28f15db6d4de0
576,172
import string import random def make_random_file_name(state, county, size=6, chars=string.ascii_uppercase + string.digits): """ Make and return random file name for output. "output/state + RANDOM STRING + COUNTY """ file_str = "population-output/" + state + "/" + state + "_" + ''.join(random.choic...
bdc5d9c7843f371d0aa138f816797cd5e7cf08b2
576,180
def extract_limit(b): """Extract limit from fitargs dictionary.""" return dict((k, v) for k, v in b.items() if k.startswith('limit_'))
6c5de97e3db120713b9ef7c04eca602406616c87
576,181
import re def remove_all(value): """ Remove all whitespaces from a string. :param value: The value :type value: str :return: The value with all whitespaces removed :rtype: str """ return re.sub(r"\s+", "", value)
84e1c698cfbfae972b06d3af870ed5f664fc8be0
576,185
def isCompatible(c1, c2, IUPAC_compatibles): """ Checks compatibility between character c1 and c2 """ if IUPAC_compatibles[c1 + "_" + c2] == 1: return True else: return False
f8c21c1cc1b438754cd9eaa40939a59d77100536
576,187
def split_basename(basename): """ Splits a base name into schema and table names. """ parts = basename.split(".") db_name = parts[0] python_path_name = parts[1] schema_name = parts[2] table_name = parts[3] return db_name, python_path_name, schema_name, table_name
7c3f8bc3db4a6006831fb4d32020bd5c32084ed4
576,193
def clo32(val): """ Count Leading Ones starting from bit 32. """ # pylint: disable=line-too-long first_bit = val[31] ^ 0x0 ctr = (1 & val[31]) + \ (1 & val[30]) + \ (1 & val[29] & val[30]) + \ (1 & val[28] & val[30] & val[29]) + \ (1 & val[27] & val[30] & val[29] ...
8a94901a9ca30533c2124ef0f5331d6e405b427f
576,194
def _item_numbers_by_name(dfsItemInfo, item_names): """Utility function to find item numbers Parameters ---------- dfsItemInfo : MIKE dfs ItemInfo object item_names : list[str] Names of items to be found Returns ------- list[int] item numbers (0-based) Raises ...
ebd0e8d45743fa27740d35082c5d1dbdfbe7dda2
576,195
def get_list_inverse_index(unique_ids): """Get value to position index from a list of unique ids. Args: unique_ids: A list of unique integers of strings. Returns: result: a dict from value to position Raises: TypeError: If unique_ids is not a list. """ if not isinstance(uniq...
d2ff690106271b18784208f953e4e98d7f74840f
576,201
import struct def encode_len(length: int) -> bytes: """Encodes the specified length as 1,2 or 5 bytes of RDB specific length encoded byte. - For values less than 64 (i.e two MSBs zero - encode directly in the byte) - For values less than 16384 use two bytes, leading MSBs are 01 followed by 14 ...
320e7afa90750b6bae7ab0151510864e7aaf966e
576,202
def bits_to_int_le(bits, count): """ Converts bits to an integer, little endian :param bits: the bits :param count: the number of bits :return: the integer """ i = 0 for k in range(count): i |= (bits[k] & 1) << k return i
76aa503a3e4e325c893578a4ffd0c20f6c6c4ac7
576,203
import socket def get_my_ip_address(remote_server="google.com"): """ Return the/a network-facing IP number for this system. """ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.connect((remote_server, 80)) return s.getsockname()[0]
ee8b0f6def2931d23101be17a8de83e009de7b19
576,207
def mse(original_data, degradated_data): """ This calculates the Mean Squared Error (MSE) :param original_data: As Pillow gives it with getdata :param degradated_data: As Pillow gives it with getdata :return: List containing the MSE in Y, U, V and average of those 3 """ error_y = 0 error...
aaf80905df77dc8e4ec5be361b2227ff419237c1
576,208
import ast def has_elif(node: ast.If) -> bool: """Tells if this node is a part of a ``if`` chain or just a single one.""" return getattr(node, 'wps_if_chain', False)
a1ed8f1a9c733da12e2ed5dba69196237e7eea1c
576,209
async def _check_amazon_forwards(forwards: str) -> tuple: """Validate and format amazon forward emails for user input. Returns tuple: dict of errors, list of email addresses """ amazon_forwards_list = [] errors = [] # Check for amazon domains if "@amazon" in forwards: errors.append...
20780d6bc72c83f808bdcbe1c22b7961463a1fb2
576,210