content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _end_of_set_index(string, start_index): """ Returns the position of the appropriate closing bracket for a glob set in string. :param string: Glob string with wildcards :param start_index: Index at which the set starts, meaning the position right behind the opening b...
ef9b68b4065992900c6d3dd7b2f8c5591b36c596
631,368
def fix_brace_c(a, b): """Move any `}`s between the contents of line `a` and line `b` to the end of line `a`. :param a: A line of Lean code, ending with `\n' :param b: A line of Lean code, ending with `\n' :returns: A tuple `(anew, bnew, merge)`, where `anew` and `bnew` are `a` and `b` with co...
972354cc1a6ec684a24503c4e31b3d0b02855645
631,371
def twochannel37(tb37v, tb37h, tiepts): """Simple 2 channel algorithm 37 GHz """ ow37v = tiepts[0] ow37h = tiepts[3] fy37v = tiepts[2] fy37h = tiepts[5] my37v = tiepts[1] my37h = tiepts[4] cf = ((tb37h - ow37h)*(my37v - ow37v) - (tb37v - ow37v)*(my37h - ow37h))/((fy3...
a04b731e448daf40a896425cc610555c51717433
631,372
def search(term): """ """ return "https://finance.yahoo.com/quote/%s/history?p=%s" % (term, term)
6792111b5213d82377058b7eed1da92ff8fdb91c
631,373
def success_function(a, b): """Function which completes successfully.""" return a * b
042dca50021152faf44b8375f46ee8b7a22c9e7e
631,374
def f_sq(num: int) -> int: """Return [num] squared.""" return num**2
0c7e2403afb58235fb398bb8c8dd473aa8f8e5bd
631,375
import numpy def support_indicator(n_rows, cross_plan): """return a vector indicating which rows had app assignments""" support = numpy.full(n_rows, False, dtype=bool) for ci in cross_plan: support[ci["app"]] = True return support
b8c55bedb5363dc4c797c53e012fd12afda66ee0
631,376
import re def token_condition(token) -> bool: """ Check conditions on the token. URLs primarily. """ cond_1 = re.match(r"[/]*w{3}[.\D{3,}+]+", token) is None # Most of the URLs cond_2 = re.match(r"http\S+", token) is None # String having "http:" . cond_3 = re.match(r"\d+", token) is None # ...
70b33be6f8042b65cb015520753088d33c8bb0a8
631,377
import math def Sine(amplitude=1.0, phase=0, end_phase=2.0 * math.pi): """ Depending on the arguments, moves at a different pace according to the sine function. """ def sin_easing(sprite, delta): return amplitude * math.sin(phase + delta * (2.0 * math.pi - phase)) return sin_easing
bf8097a5668adc1b2fac98b4921a677f2c788ade
631,378
def container(**criteria): """ Turns keyword arguments into a formatted container criteria. """ criteria = ['%s="%s"' % (key, val) for key, val in criteria.items()] return '[%s]' % ' '.join(criteria)
1c581691840d3a33f0d203e53901824bd566d61c
631,379
import os import hashlib def file_to_MD5(filepath): """ :param filepath: str 文件路径 :return: hash """ if not os.path.isfile(filepath): return obj = hashlib.md5() with open(filepath, 'rb') as f: while True: b = f.read(8096) if not b: br...
cdc6e95920fa3bd765b709025993b3a2c64bf27f
631,380
def convert_points_to_letter(point): """ Converts a given point to a letter grade. Parameters: A number in range of 0 to 100. Returns: Letter grade. """ if point >= 94: grade = 'A' elif point >= 87 and point < 94: grade = 'A-' elif point >= 83 and point < 86: ...
e350c2b401cfbbc1248a5ebe30e1c77781c35fbe
631,381
from typing import List import os def get_paths_to_data(path: str, model: str, metric: str, dataset: str) -> List[str]: """ Function gets paths to results. :param path: (str) Path to results :param model: (str) Name of model :param metric: (str) Name of metric :return: (List[str]) List of all ...
95686aeb6d68829fafb94c06ddc9328a49d741c6
631,382
def measure_counts_deterministic(shots, hex_counts=True): """Measure test circuits reference counts.""" targets = [] if hex_counts: # Measure |00> state targets.append({'0x0': shots}) # Measure |01> state targets.append({'0x1': shots}) # Measure |10> state ta...
fa530ca0252f91097cd3af41e3638e4a1d536921
631,383
import subprocess def submit_slurm_job(node, node_index, num_gpus, num_nodes, cpus_per_task, params_file): """ Submit a job to a node using all of its available gpus. Args: node (str): name of ...
c6c86c822fc7fdc645ebb05c05fd56514357561b
631,384
import sys def _python_path(ctxt): """Return the path to the Python interpreter. If the configuration has a ``python.path`` property, the value of that option is returned; otherwise the path to the current Python interpreter is returned. """ python_path = ctxt.config.get_filepath('python....
127490f4a399702f2840e425e1582d1aa3826f7e
631,385
import re def camelback2snake(camel_dict: dict): """Convert the passed dictionary's keys from camelBack case to snake_case.""" converted_obj = {} for key in camel_dict.keys(): converted_key = re.sub(r'[A-Z]', lambda x: '_' + x.group(0).lower(), key) converted_obj[converted_key] = camel_dic...
a6f08f5bdec441662a8feca0898e1bde9f25a456
631,386
def join_lines(x): """Inverse of split_lines""" if all(isinstance(i, str) for i in x): return "\n".join(x) elif all(isinstance(i, list) for i in x): return [join_lines(i) for i in x] else: raise TypeError(f"{[type(i) for i in x]} {str(x)[:20]}")
6f269888ec26cb78f654241d516ae01fee000323
631,387
def calculate_square_area(a): """Возвращает площадь квадрата""" return a ** 2
f0e231307ce7e4e79fa218fadbf25899e086285c
631,388
from pathlib import Path def find_lovpy_ignore(): """Returns paths of all .lovpyignore files found under current working directory.""" return list(Path().absolute().rglob(".lovpyignore"))
fa7e7ec84185c5a393ec5483450954152776c6d4
631,389
def find_on_grid(grid, wanted): """Find location of wanted on grid.""" for row_no, row in enumerate(grid): for col_no, col in enumerate(row): if col == wanted: return (row_no, col_no) return None
370785637254c18764da3a404e51033020631c34
631,390
def match_node(var_name, node_id, node_label): """Query to match a node into the variable. Parameters ---------- var_name Variable name to use for the matched node node_id Id of the node to match label Label of the node to match, default is 'node' """ return "MAT...
d52ea0b7abf149de9cb164ee7d51a3c3cf8e0a53
631,391
import re def get_r_filename(r_file): """Remove the file extension from an r_file using regex. Probably unnecessary but improves readability Parameters ---------- r_file : string name of R file including file extension Returns ------- string name of R file without f...
bde15f79afcc585d0f86b45debf932c22d22f271
631,392
import os def setup_cuda_environment(gpu_id): """Setup the GPU/CPU configuration for PyTorch. """ if gpu_id < 0: print("Running on CPU...") os.environ["CUDA_VISIBLE_DEVICES"] = "" return False else: print("Running on GPU {0}...".format(gpu_id)) os.environ["CUDA_...
848e17916f04c4fa0bce3627c92b8ca4e24234ab
631,393
def set_show_scroll_bottleneck_rects(show: bool) -> dict: """Requests that backend shows scroll bottleneck rects Parameters ---------- show: bool True for showing scroll bottleneck rects """ return {"method": "Overlay.setShowScrollBottleneckRects", "params": {"show": show}}
9e2a16540015084154d612d2a3dedbd8523b5058
631,394
import warnings import numpy def alpha_blend(top, bottom, alpha): """Blend top image onto bottom image using the provided alpha value(s). Parameters: top, bottom: images, either of shape (x, y) or (x, y, c). alpha: alpha value for blending, either scalar, or (x, y) mask. Must be i...
b87d659580f820d2bfe8b78d43c9cafd59733cd1
631,397
import re def count_vocals(file_name, start=0, end=100): """ Count vocals in specified file Args: file_name (str): path to file start (int): first line in file end (int): last line in file Returns: int : number of vocals in file """ vocals_number = 0...
bd3de89d95a7c0c3fa1f73a0627c5be2fa9ecab3
631,398
import sys def get_python_version(verbose=0): """ Returns the python version.""" version = sys.version if verbose: print('Python', version) return version
6a2b175683d4157e321489e932f5e4f057fb4bce
631,399
import glob import json def load_emrqa_datasets(data_dir="../data/datasets/*json"): """ :return: dictionary from filename to decoded json objects in data directory """ datasets = {} files = glob.glob(data_dir) for file in files: with open(file, "r") as f: json_file = f....
9d7952eb6ca54a2491f2c67afa1b04b45710b3e2
631,401
def _requirements_with_three_elements(requirements): """Return true if requirement list looks like ['<', '$ram', '1024'].""" return (isinstance(requirements, list) and len(requirements) == 3 and isinstance(requirements[0], str) and isinstance(requirements[1], str) and ...
ccb05ca4dd46bf4202a2a4b16c10666e43a3af35
631,403
def _check_mutual_preference(resident, hospital): """ Determine whether two players each have a preference of the other. """ return resident in hospital.prefs and hospital in resident.prefs
29856e3ef65e60f06c6b12e8b598579b89156295
631,404
def posting(client, route, title_field='test title', content_field='test body', is_page=False, categories_field_0='', categories_field_1='', categories_field_2='', publish='yes', preview=None): """Helper function to create/edit posts and drafts by posting to our routes. This helper ...
fb20f18284d6066c8ff07946c3b55751dec94abc
631,406
def create_component(class_name, constructor_args={}): """Create an instance of a component of given name. This is used in dynamic loading and component composition based on configuration file. class_name - fully qualified name of the class (module.submodule.classname) constructor_args - optional dict ...
a99d434a600593c97e031430f7d21bc5cae9cbbc
631,407
def summa_xn(x_list, n_power): """Функция, которая считает сумму элементов в указанной степени""" return sum((elem ** n_power for elem in x_list))
96065abb473805710d118756be307c2936ac7de7
631,408
import os def mpirun(cmd, procs=1, implementation='openmpi', hostfile=None): """Return a modified `cmd` that runs the given `cmd` (list) using MPI. If `hostfile` is given, it will be overwritten and used in such a manner as to force the use of the given number of processes. Args: cmd (list):...
f085d0b68bddef6177c69864e6ee25702e9219c3
631,409
def format_str_value(value, format_str): """Format value based on format code in field in format id:02d""" if not format_str: return str(value) format_str = "{0:" + f"{format_str}" + "}" return format_str.format(value)
57ffd872fa6c1ae7c5dfe01129660fec1de6d3d7
631,410
import networkx def get_all_paths_from(G, source_id): """ get all paths from source node to all possible nodes in a dictionary """ return networkx.single_source_dijkstra_path(G, source_id)
fd52853ba3cb101ef1d972777175a2be5c92abeb
631,411
import re def create_paired_list(value): """ Create a list of paired items from a string. :param value: the format must be 003,003,004,004 (commas with no space) :type value: String :returns: List :example: create_paired_list('003,003,004,004') [['003','003'...
7733ab7ef576a226522bfacadf4e5eeb306f1053
631,412
import typing def get_ctffind_4_1_0_header_names() -> typing.List[str]: """ Returns the header names for the ctffind4 input file. Arguments: None Returns: List of names """ return [ 'DefocusU', 'DefocusV', 'DefocusAngle', 'PhaseShift', 'CtfFigu...
8e8ea28cc1a66690b67c5fe1d5f4f11aed79a49d
631,413
from pathlib import Path def _get_dataset_path_from_args(args_dataset): """Remove 'benchmark:' from the dataset name and add .csv suffix. Parameters ---------- args_dataset : str Name of the dataset. Returns ------- str Dataset name without 'benchmark:' if it started with...
f34d5185f439751cb54765c32634727726ca426b
631,414
import re def normalize_name(str): """Converts names into JavaScript-safe ascii string keys that adhere to the expected conventions.""" if not str: return str # The Tam\u2013Tara Deepcroft str = re.sub(r"\u2013", "-", str) # The <Emphasis>Whorleater</Emphasis> Extreme str = re.sub(r"...
9575a96454a0a874c8a2d94b04a89eb57646ab49
631,415
def _cast_value_to_type(value, cast_type_string): """Return the value casted to the type specified by the cast_type_string, as defined in the type maps in the ReferenceGenome object's variant_key_map field """ if cast_type_string == 'Integer': return int(value) elif cast_type_string == 'Floa...
d01a83c465703c66134ece06df7f67deb366525a
631,416
import pkg_resources def get_package_root(): """Returns project root folder.""" return pkg_resources.get_distribution('rciam_probes').location
b462d1f1249192ee6e556e2d2be0b6f5f60ef1d4
631,417
def kebab2camel(kebab: str, case: str = "lower"): # "lower" dromedary or "upper" Pascal """Convert kebab case to camel case.""" if not isinstance(kebab, str): raise RuntimeError(f"bad arg to kebab2camel {str(kebab)}") kebab_words = kebab.split('-') camel_words = list() if case in ["...
0109050078331444a1eaeae9a13994bd19ed6c7f
631,418
def merge(numbers_list): """ Mergesort algorithm :param numbers_list: list of number to order :return: new list with numbers ordered """ if len(numbers_list) <= 1: return numbers_list result = [] # identify the middle item mid = len(numbers_list) // 2 numbers_list_a = m...
c5e713a7fb22de36fa20ee4d982e89b5f7585b2e
631,420
import time import os import signal def wait_for_process_completion_or_timeout(process, timeout): """ Utility function that waits for the process to complete within the given time frame. This function will terminate the process if when the given time frame elapses. :param process: Reference to a runni...
4b939a5631dc25d752a6d0a29bdb1d47b8389e2c
631,421
def fizz_buzz_elif(n): """ Return the correct FizzBuzz value for n by testing divisibility in an if-elif. """ divisible_by_3 = n % 3 == 0 divisible_by_5 = n % 5 == 0 if divisible_by_3 and divisible_by_5: return "Fizz Buzz!" elif divisible_by_3: return "Fizz!" elif div...
d98b01d2dc73328884a875de753338dea58f4799
631,422
def get_checkpoint_indices(worker, actor_id): """Get the checkpoint indices associated with a given actor ID. Args: worker: The worker to use to get the checkpoint indices. actor_id: The actor ID of the actor to get the checkpoint indices for. Returns: The indices of existing check...
e71705ebcdc42e09a9909ce79a2187512315b91f
631,423
def factorial(n): """ Input: a number. Output: find the factorial of the input number via iteration. """ product = 1 if n == 0: return 0 for thing in range(1, n+1): product *= thing return product
8006c96ec916156840fd20914430c7ff9e24af80
631,424
def npix_above_threshold(pix, thr): """ Calculate number of pixels above a given threshold Parameters ---------- pix: array-like array with pixel content, usually pe thr: float threshold for the pixels to be counted Returns ------ npix_above_threshold: float ...
a464605f724db3a40be24a62e6eb532e7249114a
631,425
def _unpack_tupla(tupla): """Unpack_tupla""" (word1, word2) = tupla return word1 + " " + word2
36afb4b1200e7a880b2341617f29a0ce72b7cb00
631,427
def SplitRange(regression): """Splits a range as retrieved from clusterfuzz. Args: regression: A string in format 'r1234:r5678'. Returns: A list containing two numbers represented in string, for example ['1234','5678']. """ if not regression: return None revisions = regression.split(':') ...
3f81178c1eee611e73acdf03b3f006c03b0f1ca8
631,428
def is_import(line): """Returns if the line is an import.""" return "import " in line or "__import__" in line
7a145fff7177bb222a14a439cee554dc2a93b6de
631,429
def latest_output(link, status=None): """get the latest output that each archive method produced for link""" latest = { 'title': None, 'favicon': None, 'wget': None, 'warc': None, 'pdf': None, 'screenshot': None, 'dom': None, 'git': None, ...
9d806c5fe7c04eb882469dbf1f35bcddf21f3bef
631,430
def drop_zero_and_na(dataframe): """ Drop columns that include NaN or camera id is 0 :param dataframe: a pandas dataframe (after combining original dataframe with Reinjection dataframes) :return: a pandas dataframe after dropping """ new = dataframe.reset_index(drop=True) new = new.drop(data...
b3479290cf27943177f4d5e484ad5228ac22e8c6
631,432
import pickle def pickle_from_file(path): """Load the pickle file from the provided path and returns the object.""" return pickle.load(open(path, 'rb'))
71cacc34457314853897f2835d52a893d6a56547
631,434
def truncate(text, max_length=1024): """Limit huge texts in number of characters""" text = str(text) if text and len(text) >= max_length: return text[:max_length//2-3] + " ... " + text[-max_length//2+3:] return text
fa69b875a1921bd6b0f2754a061ef6f8f4f77d2c
631,435
def get_outliers(df, forecast, today_index, predict_days=21): """ Combine the actual values and forecast in a data frame and identify the outliers Args ---- df : pandas DataFrame The daily time-series data set contains ds column for dates (datetime types such as datetime64[ns]) and ...
93184cbebd46dab654d4224d9a4d0f4cea190bc3
631,436
from io import BytesIO from io import StringIO from zipfile import ZipFile import requests def get_zip_file(url, filepath): """Gets zip file from url. Args: url: A string, the url of zip file. filepath: A string, the file path inside the zip file. Returns: A String, the content of ...
6630fadd083523a3575acebf9a3db49bb5aa8537
631,437
def swap_bytes(value, size): """ Swaps a set of bytes based on size :param value: value to swap :param size: width of value in bytes :return: swapped """ if size == 1: return value if size == 2: return ((value & 0xFF) << 8) | ((value & 0xFF00) >> 8) if size == 4:...
6f7a1c97132192afe830c9e55d6f85b8292bf723
631,438
import re def get_old_theme(settings): """returns the theme which is currently used uses regex to find the currently used theme i excpect that themes follow this pattern XXXX-XXXX-ui XXXX-XXXX-syntax """ with open(settings, "r") as file: string = file.read() # them...
469d37631acee58026707f5c3c6cce40d1bae911
631,439
def expand_layers_dim(input_dim, mid_dim, output_dim, layers): """ Returns a list [(in dim, out dim), ...] with layers count of elements. """ if layers < 0: raise ValueError("Expecting layers >= 0 but received layers = {layers}".format(layers=layers)) if layers == 0: layers_dim = []...
58c74a0d2fc2f1bdf903167ce381c5719619fab1
631,441
def check_vocab_file(file, special_tokens): """Check a vocab file, adding special tokens to it. Args: file: A constant string, path of the vocab file special_tokens: A list of special tokens Returns: The size of the processed vocab. """ vocabs = set() with open(file, mo...
7e21578d1fa96789d7f8d646d3111fab13ee2e84
631,442
def project_mat(pnt, norm): """Projects pnt following norm.""" t = -(pnt@norm)/(norm.T@norm) ret = pnt + t return ret
abe8a788bebbf16299271def40354108a04d157c
631,443
def extract_vertices_from_name(name: str) -> str: """Takes the number of vertices from a string of the form: '{type}_{num_vertices}_{k}_{rank}_{m1}_{m2}' """ suffix = name[name.find('_')+1:] return suffix[:suffix.find('_')]
e66a72142fea08446473049fa26799b04ce6ce18
631,444
def is_switchport_default(existing): """Determines if switchport has a default config based on mode Args: existing (dict): existing switchport configuration from Ansible mod Returns: boolean: True if switchport has OOB Layer 2 config, i.e. vlan 1 and trunk all and mode is access ...
5a8707ea4ac70dfa2b5bbefa6fe57ec15eb6c023
631,445
def _header_search_paths_for_target(target_name, all_transitive_targets): """Helper method transforming valid hmap paths into full absolute paths and concat together Args: target_name: The name of the target whose header search paths we want to aggregate all_transitive_targets: all targets that...
056d52ecbfa875276c095caa5ec0479e6e30be41
631,446
def get(user_id, client): """Requests information on certain user.""" return client.get_user(str(user_id))
e59bded519edbb8b01f4a9f916327736093242c1
631,447
def set_postgresqlmanager_db_variables(): """ set_db_variables is used to provide the credentials to the integration postgresql database. :return: """ dbvars = {"username": "testing1234", "password": "testing1234", "hostname": "127.0.0.1", "database": "testi...
7343cd33107ea8da436de3cba61cbab6ddc5ff0b
631,448
import torch def try_all_gpus(): """Return all available GPUs, or [cpu(),] if no GPU exists.""" devices = [ torch.device(f"cuda:{i}") for i in range(torch.cuda.device_count()) ] return devices if devices else [torch.device("cpu")]
d1397a6a18cdc9af4a8834d8c04c95f6c3525307
631,449
def removeDup(head): """ 方法功能:对带头结点的有序单链表删除重复的结点 输入参数:head: 链表头结点 """ if head is None or head.next is None: return cur = head.next # while cur is not None and cur.next is not None: while cur.next is not None: if cur.val == cur.next.val : cur.next = cur.ne...
2d6a00b1c8b379aa1b9ddadad2f74e9e0a6ec65d
631,450
def parse_taxa_report(local_path): """Return a dict of taxa_name to read_counts.""" out, abundance_sum = {}, 0 with open(local_path) as taxa_file: for line_num, line in enumerate(taxa_file): line = line.strip() tkns = line.split('\t') if not line or len(tkns) < 2:...
a427d15244d6b1edab11171fc33c250bb37c56f2
631,451
def digimon(string): """recurses over a string until it finds an alphabetical character, which it then returns the index of""" for ch in string: if ch.isalpha()==True: return(ch) break else: dex=string.index(ch) digimon(string[dex+1:])
a446efbbd8c59cdcf8be334c9592716a07a3fd97
631,452
def EncodeFileRecordSegmentReference(FileRecordSegmentNumber, SequenceNumber): """Encode a file record segment reference and return it.""" return (SequenceNumber << 48) | FileRecordSegmentNumber
ecde23e47c929b84c309504c1798cd160979c864
631,453
def calculate(tri_list): """Returns the number of valid triangles""" acc, a, b, c = 0, [], [], [] for line in tri_list: coords = list(map(int, (line.split()))) for i, triangle in enumerate((a, b, c)): triangle.append(coords[i]) if len(a) == 3: for triangle in ...
3a33a0fa73e0c6389d96fde111b22c242745cba5
631,454
def to_setting( checked: bool, text: str, active_style='class:toolbar-setting-active', inactive_style='', mouse_handler=None, ): """Apply a style to text if checked is True.""" style = active_style if checked else inactive_style if mouse_handler: return (style, text, mouse_handle...
61ecece14d1260e922cf2a9871a26184882ab92b
631,456
def parse_compute_version(compute_version): """Parse compute capability string to divide major and minor version Parameters ---------- compute_version : str compute capability of a GPU (e.g. "6.0") Returns ------- major : int major version number minor : int min...
ab48bbd69ebbb99d3671d3c39fb77fbb12a76ad4
631,457
def aero(v,w,b,e,f,sigma): """ computes the aero drag based on the equation """ dp = (sigma/f)*(v**2)*391 dl = 1245/(sigma*e)*(w**2/b)*(1/v**2) fov= dp-dl return(fov)
9007ec11cbbafe16dfed95e85fc31866cbb13758
631,458
def remove_dup_loop(input_list): """ Remove all duplicates in list. Using loop method. Arguments: input_list -- a list input Returns: new_list -- a list remove all the duplicates. """ new_list = [] new_list.extend(i for i in input_list if i not in new_list) return new_l...
08c20c3fb40a0294811bc78305aab9dbd0f5bc71
631,460
from typing import Union from pathlib import Path import json def load_json(ffp: Union[Path, str]): """Loads a data from a json file""" with open(ffp, "r") as f: return json.load(f)
0bb8240f858f69f8c0ede131403c59ad5703ec42
631,461
def assignment_history(task): """ Return all assignments for `task` ordered by `assignment_counter`. Args: task (orchestra.models.Task): The specified task object. Returns: assignment_history ([orchestra.models.TaskAssignment]): All assignments for `task` ordere...
7dc71357093a3a83c897c80ae378a7e53b6bfe72
631,463
def coords_in_image(rr_cc, shape): """ Taken almost directly from skimage.draw(). Decided best not to do any formatting implicitly in the shape models. Attributes ---------- rr_cc : len(2) iter rr, cc returns from skimage.draw(); or shape_models.rr_cc shape : ...
4243374d5eee3e6a51f8dee1ece4a77d5e319df1
631,464
def toBase(n, base): """ Utility function, converts certain number to another base """ convertString = "0123456789ABCDEF" if n < base: return convertString[n] else: return toBase(n // base, base) + convertString[n % base]
692571148bee8c3b679bdaa61cbfd1fa9598ff4e
631,465
import logging def sort_stats(dict_data, sort_key, limit): """ :param dict_data: Dictionary data to sort. sort_key: The key used to sort :return: sorted json """ try: sorted_x = sorted(dict_data, key=lambda x: dict_data[x][sort_key], reverse=True) k = limit i = 0 ...
aa595744f0e70ddea1073d6996d71f443a7b7171
631,466
def A1superfunction(a,b,cool=99): """ This is a seriously superb function. It does nothing. """ return None
8ec2b53754b545a16d2b2557db776cf7587c99d1
631,468
def _try_pydatetime(x): """Opportunistically try to convert to pandas time indexes since plotly doesn't know how to handle them. """ try: x = x.to_pydatetime() except AttributeError: pass return x
fed728e763633ea349a2bfd49464295ecd517aca
631,469
def sort_list(data, ind, ascending=True): """sort_list方法用于 Parameters ---------- data : list 列表 ind : int 第几列 ascending : pool 升序或降序 Returns ---------- """ if ascending: data = sorted(data, key=lambda x: x[ind]) else: data = sorted(dat...
d8f100d229371e113cdfcdc690b32c748281a804
631,470
from pathlib import Path def create_filename(name_segments, part=None, num=None, extension='.jpg'): """Returns a Path object comprising a filename built up from a list of name segments. Parameters: name_segments (list): file name segments part (str): optional LOC image designator (e.g., i...
5ce9f2c58cb512acb8e1144c99badfbbb893fcb0
631,471
def _check_bases(seq_string): """Check characters in a string (PRIVATE). Remove digits and white space present in string. Allows any valid ambiguous IUPAC DNA single letters codes (ABCDGHKMNRSTVWY, lower case are converted). Other characters (e.g. symbols) trigger a TypeError. Returns the string ...
1aaa4bf8a939a8a3a0898d7991f394d84b7ded3f
631,472
import random def generate_password(pw_len=15): """Generate a password""" alphabet = 'abcdefghijklmnopqrstuvwxyz' upperalphabet = alphabet.upper() pwlist = [] for _ in range(pw_len // 3): pwlist.append(alphabet[random.randrange(len(alphabet))]) pwlist.append(upperalphabet[random.r...
4213432442511ce1f5faa403ce24611cb83a76fd
631,473
import logging def get_logger(name: str) -> logging.Logger: """ Create new logger. :param name: The logger domain. :return: New logger. """ return logging.getLogger(name)
d19f287e2ed62cb094de297de09f32d26d02d5ef
631,474
def lag_to_suffix(lag: int) -> str: """ Return the suffix for a column, given its lag. """ if lag < 0: str_lag = "f" + str(abs(lag)) else: str_lag = "l" + str(abs(lag)) return str_lag
c2208d55aa53f343817ffbe9163410feddc050ac
631,475
import math def nPVI(items): """Calculate the Normalized Pairwise Variability Index. :param items: (list) list of data values :returns: (float) """ if len(items) < 2: return 0. n = len(items) - 1 sumd = 0. for i in range(n): d1 = items[i] d2 = items[i+1] ...
b6b3e5efea9d97755a92763d0994415d30c7a4cd
631,476
def search_PointIOKey(values, PointIOKey): """Fonction qui retourne un objet cherche par les PointIOKey""" for item in values: if PointIOKey == item["PointIOKey"]: return item return None
797190f3f6f615ce4b4749e97d87445007d8bb25
631,477
def bdev_virtio_scsi_get_devices(client): """Get list of virtio scsi devices.""" return client.call('bdev_virtio_scsi_get_devices')
26e9926ae4920000e524e38363258b2cb495ea58
631,478
def treestring(t, tab=0,sep=' '): """ Return a string representation of a syntax tree. Print preterminals on same line as their terminals (e.g. n dog) Use indentation to signal nesting level. Parameters ========== t: syntax tree The tree to be printed. E...
99dc7e2ef892d5a3aaae1289cd5ce8dc873e3e34
631,479
def is_odd(n): """Determines whether `n` is odd """ # odd = n % 2 == 1 odd = bool(n & 1) return odd
ce1ab902fa85bee571e59831e22ffa39e5f0a106
631,480
def create_server_raw(conn, attrs, wait_for_server=True): """ method wraps the conn.compute.create_server() method """ os_server = conn.compute.create_server(**attrs) if wait_for_server: os_server = conn.compute.wait_for_server(os_server) return os_server
c47fc6a3befcd3f81e9bc7b7ef729085db957db2
631,481
import functools def flat_map(l): """Transform a list of list in a list with all the elements of the nested lists >>> flat_map([[1, 2, 3], [4, 5]]) [1, 2, 3, 4, 5] """ l = list(l) return functools.reduce(list.__add__, l) if l else []
737ab9e620aea120e24458f45256bf663a0bc3ec
631,483
def _must_contain_scenarios(must_contain_conf, scenario_model): """ Return a set of scenarios and process names that are entries of must contain configuration. :param must_contain_conf: dict. :param scenario_model: ScenarioModel. :return: set of process names, set of Scenario objects. """ n...
bd02bee56c0670065e0fe46e82f95893db488aa1
631,484