content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _arithmetic_mean(nums) -> float: """Return arithmetic mean of nums : (a1 + a2 + ... + an)/n""" return sum(nums) / len(nums)
4917bbccc5f3e960dbedd57489cb148c207dd962
669,239
def to_pm1(samples): """Converts a tensor of spins from the :math:`\sigma_i = 0, 1` convention to the :math:`\sigma_i = -1, +1` convention. :param samples: A tensor of spins to convert. Must be using the :math:`\sigma_i = 0, 1` convention. :type samples: |Tensor| """ return ...
79cc58a8512bdc1cb86c8d88c8e8be34f6732de5
669,240
def make_dict_from_tuple(row: tuple) -> dict: """Make dict for table 'vault' from tuple obtained from select query. """ dict_keys = ("id", "name", "login", "password", "note") return dict(zip(dict_keys, row))
70820185e411b71c4df07fc092aee28eeb09cfb0
669,241
def tag(tag, url_name=None): """ Render a tag and a URL to filter by it if the base URL is provided. """ return {"tag": tag, "url_name": url_name}
8434bcbf80202978e8c09229d2b6eb411f6a4ddd
669,242
def get_reference_id(url: str): """ Return the reference id from a URL For example: >>> get_reference_id("https://github.com/advisories/GHSA-c9hw-wf7x-jp9j") 'GHSA-c9hw-wf7x-jp9j' """ _url, _, ref_id = url.strip("/").rpartition("/") return ref_id
370af3938b88b9c704e4777358a4c57bd66a20f0
669,243
def centroid_of_points(pts): """Returns the centroid of a cluster of points. Automatically works with either 2D or 3D point tuples.""" xs, ys, zs = 0, 0, 0 for pt in pts: xs += pt[0] ys += pt[1] if len(pt) > 2: zs += pt[2] if len(pts) > 0: xs /= len(pts) ...
a274583a09d7272c9a680f44d44b9b58d2f5a346
669,244
def cons(env, args): """For any x and y, constructs a list (x, y). """ if len(args) != 2: raise TypeError( "Function 'cons' expects two arguments, got: {}" .format(args) ) else: return args.cdr().car().eval(env).cons(args.car().eval(env))
54ab1aa92a6409595c32c96c5496b3ab4def6a6f
669,245
def disable_options_method(): """Decorator function to disable OPTIONS method on the endpoint.""" def wrapper(f): f.provide_automatic_options = False return f return wrapper
3faac0cf7a4082ed18e5a73c24bfcdfd1e57cec5
669,246
def bishop_moves(): """ Sequences of relative figure positions for bishop moves. >>> list(map(lambda x: (x[0][:4], x[1][:4]), bishop_moves())) [([1, 2, 3, 4], [1, 2, 3, 4]), ([-1, -2, -3, -4], [1, 2, 3, 4]), ([1, 2, 3, 4], [-1, -2, -3, -4]), ([-1, -2, -3, -4], [-1, -2, -3, -4])] """ return [ ...
30cef9db12032b6b597af28e3f14f54f9640d063
669,247
from typing import Callable from typing import Tuple def _get_callable_info(callable: Callable) -> Tuple[str, str]: """Returns type and name of a callable. Parameters ---------- callable The callable Returns ------- Tuple[str, str] The type and name of the callable. Type ...
f6e913f16556cc8ae078fd8562c2070bda8046a3
669,248
import re import logging def entry_variant_type(entry): """ How svtype is determined: - Starts by trying to use INFO/SVTYPE - If SVTYPE is unavailable, infer if entry is a insertion or deletion by looking at the REF/ALT sequence size differences - If REF/ALT sequences are not available, try ...
b32aba34e4bfbc42f916102650e1d0d4c5cbd2a5
669,249
from typing import Mapping from typing import Union from typing import Tuple from typing import Any def get_res_off( d: Mapping, resolution: Union[str, Tuple[float, ...]], offset: Union[str, Tuple[float, ...]], ) -> Tuple[Any, Any, Any, Any]: """ Account for whether the resolution/offset given is ...
5f2ac94de6f0ca915cd7f5e046bf8e83ec4f5d6d
669,250
from typing import Callable import functools from typing import Any import weakref def memoized_method(*lru_args, **lru_kwargs) -> Callable: """Instance oriented wrapper of lru_cache. from https://stackoverflow.com/questions/33672412/python-functools-lru-cache-with-class-methods-release-object Arguments...
586eb511ccc8af4a43b4df2c7b3840d35a213aca
669,251
import re def uncamel(phrase, sep='-'): """ converts camelcase phrase into seperated lower-case phrase Parameters --- phrase : str phrase to convert Examples --- >>> uncamel('HTTPRequestHeader') 'http-request-header' >>> uncamel('StatusCode404', sep=' ') '...
bceea017e31258a6768e5197aee86c168e683303
669,252
def load_data_and_labels(filename, encoding="utf-8"): """Loads data and label from a file. Args: filename (str): path to the file. encoding (str): file encoding format. The file format is tab-separated values. A blank line is required at the end of a sentence. For exam...
8d69c0cf28053fefacad5a2ff549e25cccb52f5a
669,255
def cround(val): """ Rounds a complex number Parameters ---------- val: complex Returns ------- complex """ return complex(round(val.real), round(val.imag))
bd9f38395f33f34eec76235251785b00140141d1
669,256
import itertools def gridspec_to_geojson(gs, xx, yy, styles): """ :param gs: GridSpec instance to render to GeoJSON :param xx: (x_start, x_end) in tile space :param yy: (y_start, y_end) in tile space """ def to_geojson(gs, tidx): bbox = gs.tile_geobox(tidx) return dict(geometr...
ff1d18f7124521929304678dc4a77c471f0de872
669,257
def trim_middle(arbitrary_string: str, max_length: int) -> str: """ Trim down strings to max_length by cutting out the middle. This assumes that the most "interesting" bits are toward the beginning and the end. Adds a highly unusual '✂✂✂' in the middle where characters were stripped out, to avo...
00da48df252e6304d9f5a1faf1ef9848d63b5a02
669,258
def train_2d(trainer): """Optimize the objective function of 2d variables with a customized trainer.""" x1, x2 = -5, -2 s_x1, s_x2 = 0, 0 res = [(x1, x2)] for i in range(20): x1, x2, s_x1, s_x2 = trainer(x1, x2, s_x1, s_x2) res.append((x1, x2)) print('epoch %d, x1 %f, x2 %f' ...
34a2f164801d1a2f0571a39c914fd1f701613ae9
669,259
import pickle def load(): """ load classifier from disk """ with open('/Users/kanishksinha/Desktop/TwitterBotDetection/ApproachV3/src/spam_metric/model.pkl', 'rb') as file: vectorizer, classifier = pickle.load(file) return vectorizer, classifier
7fc9ff53eeb85e99955c8f7162d7f9e0de61057b
669,260
def get_edges(graph, cities): """ Determine if a graph representing an airline route map and an itinerary list of destination cities can be completed with direct flights. Cities are reachable by direct flights if they share a vertex. :input: graph: Graph object representing the vertices and edges :...
369a9d25e2f5501aa63f1ec12fb508618b185e1d
669,261
def _get_categorization_parameters_for_extract_study(extract_study_id, dict_cur): """ returns a dictionary keyed by (vocabulary_id, concept_code) of lists of rows. The rows are dictionaries as those returned by a dict_cur. param extract_study_id Returns dictionary keyed by (vocabu...
c6ed4ea3dc410f187cbd92661d1c093881bc781c
669,263
def get_new_image_size(width, height, image_min_size=600): """ 按照 image_min_size 的标准来计算 resized 后的 image size :param width: :param height: :param image_min_size: :return: resized_width, resized_height """ if width <= height: ratio = float(image_min_size) / width resized_h...
8f044f58ab52fa6909d3f719ef2caa25006a6061
669,265
def float_or_none(arg): """Returns None or float from a `float_or_none` input argument. """ if arg is None or str(arg).lower() == 'none': return None return float(arg)
ee4c835f0dae4e01d388e1f6c30677315dbfd1d9
669,266
def get_position_left(original_position): """ Given a position (x,y) returns the position to the left of the original position, defined as (x-1,y) """ (x,y) = original_position return(x-1,y)
c4b928d90bea3a06322cb0b3631904df0c3eea3e
669,267
import logging def _exclude_namespaces(file_groups, exclude_namespaces): """ Exclude namespaces (classes/modules) which match any of the exclude_namespaces :param list[Group] file_groups: :param list exclude_namespaces: :rtype: list[Group] """ for namespace in exclude_namespaces: ...
281358047ecf710051a835dcd98c72b9bf7eddeb
669,268
def get_fields(fields, response): """Extracts desired fields from the API response""" results = {} for field in fields: results[field] = response.get(field) return results
1ee509723f66de1dd95b60b7b5bbba069c3020fb
669,269
def withdraw_money(amount, card_balance): """Withdraw given amount of money from the account.""" card_balance -= amount # save new balnace to the database return card_balance
da538bf9f99e04dc8717854d04566dcd83a9d652
669,270
def run_length_decode(compressed_data): """ Decodes the input sequence using the RLE method. See: https://en.wikipedia.org/wiki/Run-length_encoding Args: data: list, format [number_of_letters, repeated_letter, ....] Returns: list, result of the decompression. """ out = '' ...
959ca4fc65f8223dffd5c5857f22540b7d5e9869
669,272
import os def get_movie_path(movies_path, name, year): """ Return a movie path given its title and year. """ return os.path.join(movies_path, "%s (%d).mp4" % (name, year))
90db72e7d4e61eff73a96ce67bc10916a5bdb264
669,273
def strip_bottoms(documents): """Remove article byline and ads from the article body """ stripped = [] for doc in documents: try: end = [s.root.i for s in doc.sents if s.root.orth_ == "_"][0] - 2 except IndexError: end = -1 stripped.append(doc[:end].as_doc...
ebb02c7c790596bcbcc9cc67654779d4fea83de7
669,276
def rotate_in_place(matrix): """ Modify and return the original matrix. rotated 90 degrees clockwise in place. """ try: n = len(matrix) m = len(matrix[0]) for i in range(n//2): for j in range(i, m-1-i): ii, jj = i, j hold = matrix[...
0072158da852b3ddfbd07a964f6773a0122cfb68
669,278
def fetch_empty_dummy_response(): """To mock requests.response object it is a dummy method.""" return {}
e015598044176eacbee1c507907eef19ee149293
669,280
def convert_batch_idx_to_window_idx(batch_idx, ws_multiplier): """return absolute_window_idx that batch_idx is in""" return int(batch_idx/ws_multiplier)
654925153e7724c64865c918e364b5a1e86fc145
669,281
import torch def stack_pad(ts, padding_value=float('nan')): """Converts an iterable into a tensor array using padding if necessary Args: ts: padding_value: Returns: """ row_length = len(max(ts, key=len)) result = torch.full((len(ts), row_length), padding_value) for i, ro...
3985988724829b268037ddec936f3a26d0d79339
669,282
import pickle def read_object(filename): """Convenience function for retrieving object from file using pickle. Arguments: filename {str} -- path to file Returns: object -- object in file (uses pickle) """ with open(filename, 'rb') as file: obj = pickle.load(file) ...
c6b53d5cb7260a397eb197fa84ed2b8802410bb4
669,283
def is_valid_seed(seed: int) -> bool: """Checks if the given int is a valid seed""" # NOTE(RKM 2019-11-19) This is based on numpy's random seed range return not (seed < 0 or seed >> 32)
61f1217d067a19219a7d8b545c54345e3feef147
669,284
def match_content_type(filename: str) -> str: """ Match file extensions to content-type. A quick lightweight list. This is needed so s3 vends the right MIME type when the file is downloaded directly from the bucket. """ content_type_match = { 'json': 'application/json', 'js': 'ap...
ff4ef5d752a96a39845baad8516e3057408c1b27
669,286
import os def getVICExecutable(options): """Get VIC executable from configuration options or set it to default location of not given.""" if 'exe' in options: vicexe = options['exe'] else: if os.path.abspath(os.getcwd()).find("bin") >= 0: vicexe = "{0}/vicNl".format(os.path....
0fc7243b600fb8bed36a082c133216cd03d0a6c6
669,289
def duplicate(my_list): """Return a new list that repeats the input twice""" return my_list + my_list
738aa7301ec26532f1162ff062c2ccc7b54918e3
669,290
def filter_providers_by_type(providers, type): """ helper function to filter a list of providers by type :param providers: ``list`` :param type: str :returns: filtered ``dict`` provider """ providers_ = {provider['type']: provider for provider in providers} return providers_.get(type,...
7cf3204907b9cf9e6ee0fddf33ec10fb321c8a03
669,291
import math def get_plain_woe(labels, features): """ get plain woe for test """ labels = [item for sublist in labels for item in sublist] total_pos = sum(labels) total_neg = len(labels) - total_pos woe_list = [] for feature_idx in range(len(features[0])): pos_sum = {} ...
b0c367fc1e8a6e973898062835767e0c705b06e4
669,292
import argparse def setup_prioritized_parser(): """ Prioritized options. :return: parser """ parser = argparse.ArgumentParser(add_help=False) parser.add_argument("--no-config", action="store_true") parser.add_argument("-c", "--config", nargs=1) parser.add_argum...
1f7a650488f98a6d0aea0d21fc12de3266c101fd
669,293
def get_full_module_name(o, lower=False): """ Returns the full module and class name of an object o. For example, for our :class: OntonotesReader, returns 'nlp.forte.data.readers.ontonotes_reader.OntonotesReader'. """ if not isinstance(o, type): o = o.__class__ module = o.__module__ ...
a5e5d8fa54124f103f66f8a3cb0678325d0932ee
669,295
def expression_polynomial(cobj, prop, T): """ Create expressions for CoolProp rational polynomial forms Args: cobj: Component object that will contain the parameters prop: name of property parameters are associated with T: temperature to use in expression Returns: Pyomo...
8aa677b22c5239e95b962204049eed48941e36e6
669,296
import os def get_git_version(): """Return the git version.""" if not os.path.exists(".git") or not os.path.isdir(".git"): return "nogitversion" version = open(".git/HEAD", "r").read().strip() if not version.startswith("ref: "): return version version = version[5:] git_ver = "...
0a961e40ad45945259929e94d5a34029debfc8f9
669,297
def get_target(): """get url of video to download from user terminal input""" video_url = input("Enter URL you want to download: ") return video_url
706724c920b3231d4292143fdd7751f752fd8cc6
669,298
def any_ga(geoawi): """ GEOAWI: GA W/I GRID 0=None 1=Quest 2=<I2 3=<O2 4=<1/2 DA 5=<1DA 6=<2DA 7=>2DA 8=CG Returns: 0, 1, 88 """ if geoawi == 0: return 0 elif 1 <= geoawi <= 7: return 1 elif geo...
1db941f44a23f8ec99fb27efd395cc12c8902544
669,299
def _merge_weights(spin_d1, spin_d2): """Sum the weights stored in two dictionaries with keys being the spins""" if len(spin_d1) != len(spin_d2): raise RuntimeError("Critical - mismatch spin-dict length") out = {} for spin in spin_d1: out[spin] = spin_d1[spin] + spin_d2[spin] return ...
6e99afd66192954db1eae9d4f958dd2ca2b23c59
669,300
def put_tau_together(fine_tau, fine_grad, coarse_grad, ops): """ Numerical work to construct the tau correction vector. @param fine_tau <ParamVector> The tau correction vector from the next-finer level. [f^h] @param fine_grad <ParamVector> The gradient from the next-finer level. [A^h(u)] @param coarse...
4a7410336a25567df0946530ad350234bbfed582
669,301
def get_value(field): """ Returns the values based on valuetype """ if field.ValueType == "singleValue": return field.SingleValue elif field.ValueType in ["increment", "decrement"]: return field.StartValue, field.StepValue, field.CountValue elif field.ValueType in ["repeatableRan...
82ea98d12ff49c76478db05d9242e2e5e1594b7b
669,302
def read(path, open_flags='r'): """Opens file at |path| with |open_flags| reads it and then returns the result.""" with open(path, open_flags) as file_handle: return file_handle.read()
4eaee0fe9e5467388104644b535500df1210eca8
669,303
def extract_value(expect_keys, json_dict): """ expect_keys: tuple , e.g ("nodeuser", "user") return: None if no value, else value """ temp_val = json_dict.get(expect_keys[0]) if isinstance(temp_val, dict) and len(expect_keys) > 1: return extract_value(expect_keys[1:], temp_val) elif...
c79941014301b7b763ff4735e5fd797029d2cf7c
669,304
def valueToString(v): """ >>> valueToString(0) '0' >>> valueToString(10) '10' >>> valueToString(-10) '-10' >>> valueToString(0.1) '0.1' >>> valueToString(0.0001) '0.0001' >>> valueToString(0.00001) '0' >>> valueToString(10.0001) '10.0001' >>> valueToString...
74026c993ac2510c075a34d6b2568f8b8f6efcf5
669,305
import subprocess def _is_server_listening(port): """Determine whether a server at the given port is listening.""" command = ["netstat", "-tln", "|", "grep", ":" + str(port)] result = subprocess.check_output(command) result = result.strip() if len(result) > 0: # Non empty output means foun...
577ee40db674388b889963c860d203b7f6978497
669,307
def period_starts(counter, period): """ Utility function to test whether we are at the beginning of a cycle of length `period`. If the period is non positive, this always return False, otherwise it returns True when `counter` is 0, cycle, 2*cycle, etc. @param counter typically an epoch index, o...
6691dc2e35ea74086a43c1d9a0cd4a3be5022afb
669,308
from typing import List from typing import Any from typing import Sequence def compute_response_track_location_statistics( video_annotations: List[Any], ) -> List[Sequence[float]]: """ Compute the set of response track lengths in # frames. """ rt_bbox_locations = [] for v in video_annotations:...
092d74f6eb9aeaaf59770e7b21b68a0b21e36a2a
669,309
from numpy import floor, linspace, hstack, ones, zeros, flipud def discrete_cmap_2(clines): """ Construct a discrete color map for the regions between the contour lines given in clines. Colors go from red to turquoise. Good for arrival times. """ nlines = len(clines) n1 = int(floor((nline...
8f742d9c3a1d234f8c0d532e68944efd07216953
669,310
import os def load_file_paths_brain(data_dir, label_dir, volumes_txt_file=None): """ This function returns the file paths combined as a list where each element is a 2 element tuple, 0th being data and 1st being label. It should be modified to suit the need of the project :param data_dir: Directory whi...
6c71d71f7b1365c5d8be0bde700c70cd851eb131
669,311
def adjust_cluster_indices(clusters, subtoken_map, sent_start, sent_end): """ Adjust cluster indices to reflect their position within an individual sentence. """ adjusted_clusters = [] for cluster in clusters: for span in cluster: if span[0] >= sent_start and span[1] <= sent_end:...
28a1447bb3f7d125a35f175e506a387233c99fa7
669,312
def get_vararg_name(varargs_name, i): # type: (str, int) -> str """ Given some integer i, return the name of the ith vararg. Note that the given internal names to these parameters are impossible to be assigned by the user because they are invalid Python variable names, as they start with a star ...
b8a2566ab611c2fdefff584383808e224aad2f00
669,313
import unittest import functools import cProfile def show_profile(fn): """ Decorator for unittest cases. This decorator enables profiler in a test case and prints result. It is useful for investigating bottlenecks. Usage: Decorate test methods by show_profile function. >>> import benchmar...
be9b374dc7a6d681e72efc5288e27388598d50a9
669,314
def get_options(options, names): """Returns a dictionary with options for the given keys. Args: options: dict names: list of keys Returns: dict """ new = {} for name in names: if name in options: new[name] = options[name] return new
1b4df1967cf73b56d5ae2ed998daf7c49ce76a7a
669,315
def _field_matches_upper_bound_inclusive(field): """ Return :bool:`True` if the given field matches its maximum bound value. """ below = field.matches(field.max - 1) exact = field.matches(field.max) above = field.matches(field.max + 1) return below is True and exact is True and above is Fals...
7cc1b96cbf0f5cf4df7ffa0b17b4eb26a60a16d1
669,316
def is_empty(value): """ a boolean test except 0 and False are considered True """ if not value and value != 0 and value is not False: return True return False
e1468da609e168af480e951e66060e1a13ca52bd
669,317
import hashlib def list_digest(inp_list): """Return a digest to uniquely identify a list.""" if type(inp_list) is not list: raise TypeError("list_digest only works on lists!") if not inp_list: raise ValueError("input must be a non-empty list!") # If we can rely on python >= 3.8, shlex....
e63a52bd1d4356c437a16d8a16101a8c9ac852c1
669,319
def parse_total(tokens): """ >>> parse_total(Tokenizer("7999-999 000000000000004668670000466867 000002 ")) {'CreditTotalAmount': 466867, 'NetTotalAmount': 0, 'DebitTotalAmount': 466867, 'NumTypeOneRecords': 2} """ entry...
ac93afa2238d2f694be94351b9b8b16c54e0ebab
669,320
def create_api_auth_refresh_parms(_client_id, _api_secret, _refresh_token): """ Creates the request parameters necessary to refresh an authentication token. @param _client_id: Client ID magic string from the API setup. @param _api_secret: Super secret API secret from the API setup that you are never allowed to see ...
db71d5b06f60f71690cf016fc0e4f58969f8fa00
669,321
def github_disable_two_factor_requirement_user(rec): """ author: @mimeframe description: Two-factor authentication requirement was disabled for a user. repro_steps: (a) Visit /settings/two_factor_authentication/configure reference: https://help.github.com/enterprise/2.11/admin/articles/au...
75c99efaca8c7faa084ef038348685094d4ac8d8
669,322
def get_health(): """ Usage on K8S readinessProbe: httpGet: path: /notify/v1/health port: 80 livenessProbe: httpGet: path: /notify/v1/health port: 80 :return: dict(msg='OK') """ return dict(msg='OK')
1c562fe6dcf52c53cc5c67acd9d099e5184369cc
669,323
def quote_title(title): """Quote an article name of a MediaWiki page.""" return title.replace(" ", "_")
806ab68a809c9d6bd82304e474ed88b074169a23
669,324
def rm_reverse_paths(simple_paths): """ Remove reverse cycles/paths from a list of cycles/paths. Note: Assume a path and its reverse one are next to each other in the input list! Args: simple_paths (list): a list of simple paths Returns: List: left paths """ left_paths = [] ...
18a709ff40f677122160e57d4a8ad54c081f2ef4
669,325
import random def max_weight_paths(k, weight_paths_dict, paths_to_edges, overlap=True, norev=False, rgen=None): """ Returns k largest-weight paths. The function proceeds in order through descending weight values to select paths, and if an entire weight class of paths is not to be included, applies a pred...
50264effde7c0f7f97c6e5a4c6c34899ad5462db
669,326
def load_processed_data(processed_path, parsed_reader): """ Load parsed results from disk :param processed_path: the file name to a file that stores parsed results :type processed_path: str :param parsed_reader: the parsed reader to load parsed results :type parsed_reader: ParsedReader :return:...
c4ef54e5967c5952d86cc4b6748580914fee3ad4
669,328
def get_month_as_str_col(df, date_col): """Generate a pandas series of the month as a string in YYYY-MM format from the date column. Parameters ---------- df : pandas df Pandas dataframe date_col : str Name of the column in the dataframe containing the timestamp Returns ---...
74b017ee3b5c56d8c2ae8be7d67c665603aabef1
669,330
def calc_IoU(bbox1, bbox2): """ Calculate intersection over union for two boxes. Args: bbox1 (array_like[int]): Endpoints of the first bounding box in the next format: [ymin, xmin, ymax, xmax]. bbox2 (array_like[int]): Endpoints of the second bounding box in the next...
96aaebde2b7572de5b58002a8694b8708598b989
669,331
def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state
0a0ad30f4c09a4a1d7d0434220a0213b7fe4206d
669,332
def add_v1_features(df): """ 입력 DataFrame에 첫 번째 특성을 추가합니다. :param df: 질문 DataFrame :return: 특성이 추가된 DataFrame """ df["action_verb_full"] = ( df["full_text"].str.contains("can", regex=False) | df["full_text"].str.contains("What", regex=False) | df["full_text"].str.contains...
a93d763dda950c36bdc70e930ff4080489dca9d7
669,334
def is_balanced(string: str) -> bool: """ Args: string: A string consisting only of parentheses. Time: O(n) Space: O(n) """ stack = [] braces = {")": "(", "]": "[", "}": "{"} for char in string: if char in braces.values(): stack.append(char) elif not s...
3067058f58ba7bebe7591a826e9ab5290ed34bb9
669,335
def remove_quotation_marks(source_string): """ :param source_string: String from which quotation marks will be removed (but only the outermost). :return: String without the outermost quotation marks and the outermost white characters. """ first = source_string.find('"') second = source_string[fi...
13157e80cb701b915e0ccab1e38f9099de7f90bb
669,336
def unpartial(partial): """ turn a partial into a callback_fn undo the badness """ def _unpartial(cb, *args, **kwargs): return partial(*args, **kwargs)(cb) return _unpartial
f9573fe77b48eb88ac66680331ab818f90846098
669,338
def write_file(filename="", text=""): """Write a string to a text file""" with open(filename, 'w') as f: c = f.write(text) return c
06dbe59c18a9c1750eb9cc0998b2fe7fbcbfc015
669,339
import re def pick_only_key_sentence(text, keyword): """ If we want to get all sentence with particular keyword. We can use below function. Parameters ---------- text: str Text selected to apply transformation. keyword: str Word to search within the phrase...
46a85d7edf3033e11ea0c4f11a656c7e48069cc3
669,340
import os import hashlib def sha1sum(path_file): """ This method calculates SHA-1 checksum of file. :param path_file: the relative or absolute path of a file """ if not os.path.isfile(path_file): return None sha1 = hashlib.sha1() with open(path_file, "rb") as fp: while True...
68d0fe77a55b093cf9d0975e0341066f9a81f49d
669,341
from typing import OrderedDict import torch def optimizer_to_cpu(state_dict): """Copy a optimizer to cpu. Args: state_dict (OrderedDict): Model weights on GPU. Returns: OrderedDict: optimizer on CPU. """ state_dict_cpu = OrderedDict() for key, val in state_dict.items(): ...
f7014e1dd94b67d4b867d2cc7153a4c6b493451e
669,342
import time def some_function(n): """Return the nth fibonacci number.""" time.sleep(1) return n*2
8c2236fb3a8b29d382c27b28f7ddf59c0d55164c
669,343
def rotmol(frag_atoms, rotmat): """ ROTMOL rotate a molecule n - number of atoms filelol (x) - input coordinates filelol (y) - rotated coordinates y = u * x rotmat (u) - left rotation matrix """ for i in range(len(frag_atoms)): yx = rotmat[0][0] * frag_atoms[i][0] + rotmat[1]...
af24e84100b6daba017abae66c974ef03afed888
669,344
def coverageTruncatedToString(coverage) : """Converts the coverage percentage to a formatted string. Returns: coveragePercentageAsString, coverageTruncatedToOneDecimalPlace Keyword arguments: coverage - The coverage percentage. """ # Truncate the 2nd decimal place, rather than rounding # to...
be9bbf940985d93d89d00e0c3f307c6d2b199321
669,345
def get_nodes(dag): """ Returns the names of all nodes found in dag """ nodes = dag.sig.names for node in dag.nodes: if node not in nodes and isinstance(node, str): nodes.append(node) return nodes
1f4bd8d7d007fed038c45cb162cf05a723ab6c52
669,346
def validate_transaction(spend_amounts, tokens_amounts): """ A transaction is considered valid here if the amounts of tokens in the source UTXOs are greater than or equal to the amounts to spend. :param spend_amounts: amounts to spend :param tokens_amounts: existing amounts to spend from :retur...
5a1de72aefe6d5d401864defc46c225afc218dba
669,347
def _update_host_personality(module, array, answer=False): """Change host personality. Only called when supported""" personality = array.get_host(module.params['host'], personality=True)['personality'] if personality is None and module.params['personality'] != 'delete': try: array.set_ho...
31ce7d21215eb865e6bc7237e64aab7189534c05
669,348
import importlib def load_dictionary(): """ Load dictionary. """ # Get module module = importlib.import_module('filthypasswordgenerator.data.english') # Save env dict in the global scope return getattr(module, 'dictionary')
9704f1be919e42bccc295dbf93cf6d2d05b3e021
669,349
from typing import List from typing import Dict import collections def partition_labels_back(S: str) -> List[int]: """ consumed: 60ms 60ms :param S: :return: >>> partition_labels_back('ababcbacadefegdehijhklij') [9, 7, 8] >>> partition_labels_back('eccbbbbdec') [10] """ if not ...
fbf28f319c82fe6f49e010466407c968ed65f1f6
669,350
def poly(X, Y, degree): """ Polynomial kernel implementation. X, Y: The matrices between which pairwise distances are computed. degree: The degree of the polynomial """ return (X @ Y.T + 1)**degree
5bc61c3c8b0d0f6aab6321dcb8e99db8fd8dade1
669,352
def get_default_assignment_policy(is_human): """ Return the default assignment policy. Args: is_human (bool): Indicates whether the policy is for a human or machine. Returns: default_policy (dict): A dictionary specifying the assignment policy. """ return {}...
a68d377678f18fb97e6d32d11c51581e24ec5b86
669,353
def k2f(k: float, r: int = 2) -> float: """Kelvin to Fahrenheit.""" return round(((k - 273.15) * (9 / 5)) + 32, r)
39de3421a9977f0ec0d66ca939efffb4b8809907
669,354
def sumas(matriz): """ Desarrollo de sumas de columnas. Función que genera el promedio de las sumas de las columnas pares de la matriz ingresada y las sumas de las columnas individuales. .. attention:: La numeración de las columnas corresponde a la numeración tradicional de python do...
bb767397d23aad088c666c3866980c7c8ec8934d
669,355
import argparse def parse_args(): """Copy from https://github.com/GregDMeyer/IT8951/blob/master/test/integration/test.py""" p = argparse.ArgumentParser(description="Test EPD functionality") p.add_argument( "-v", "--virtual", action="store_true", help="display using a Tkinte...
8212024293f0da24094248ae9f365e68f96e9848
669,356
import pkg_resources def resource_string(modulename, resource, basefilename=None): """Locate and return a resource as a string. >>> f = resource_string( __name__, 'somedatafile', __file__) """ return pkg_resources.resource_string(modulename, resource)
0ddec8fce71c0f3e5c1623677da09df91ed3584b
669,357
from pathlib import Path def resolve_doc_file_path(module_name: str, out_dir: Path, file_extension: str) -> Path: """Return the absolute path to a rendered doc file Args: module_name (str): the module name, i.e. "networkx.drawing.layout" out_dir (Path): the output directory, i.e. Path("/build...
703b6c91725380291fd53cae578ddd01c31eac3a
669,359