content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def splitblocks(lst, limit): """Split list lst in blocks of max. limit entries. Return list of blocks.""" res = [] start = 0 while start < len(lst): res.append(lst[start:start + limit]) start += limit return res
3189355235cfada1cd0548e3362b501fccfef0eb
653,487
def get_P_Elc_game_play(P_Elc_game_play_measured): """稼働時の消費電力を計算する Parameters ---------- P_Elc_game_play_measured : float 稼働時の平均消費電力(実測値), W Returns ---------- P_Elc_game_play : float 稼働時消費電力, W """ P_Elc_game_play = P_Elc_game_play_measured ...
e97c14ea73f8071ff15781f404baf734d94accac
653,488
def _is_subrange(rng1, rng2): """Return True iff rng1 is wholly inside rng2""" # Nonpolymers should have an empty range if rng1 == (None, None) or rng2 == (None, None): return rng1 == rng2 else: return rng1[0] >= rng2[0] and rng1[1] <= rng2[1]
25641fe477d2bf1e2e2e14020a01ccc9e96926b0
653,490
import re def decontracted(text): """ de-contract the contraction """ # specific text = re.sub(r"(W|w)on\'t", "will not", text) text = re.sub(r"(C|c)an\'t", "can not", text) # general text = re.sub(r"(I|i)\'m", "i am", text) text = re.sub(r"(A|a)in\'t", "is not", text) text = ...
69f725b6ed220e7f77324cdd65cea39acfcfa4d1
653,491
def str_from_collec(collection, no_space=False): """ Given a collection, return a string of values Collection can be: column of DataFrame (Series), list, etc. Useful in creating fv_str strings for example, by feeding row of DataFrame containing only feature columns """ if no_space: ...
a6c96a0e1fadd6f7531ac488a10464b349d36538
653,492
import os def readFile(some_file): """ Reads an ascii file if it exists, removes blank lines, whitespace, and comments (denoted by #), and spits out a list of lines. """ # Make sure the file is truly a file if os.path.isfile(some_file): # Read in the file f = open(some_file) ...
4760f2dec6ca3d2cad720a97539ef2e796247af1
653,495
def role_ids_for_account(dynamo_table, account_number): """ Get a list of all role IDs in a given account by querying the Dynamo secondary index 'account' Args: account_number (string) Returns: list: role ids in given account """ role_ids = set() results = dynamo_table.que...
73ee88813d7ae6ee5a48f89c7e37fe2cdb8e1093
653,497
def _get_unique_links(page_url, soup): """ Returns all unique links. Includes: "a"->"href", "img"->"src", "link"->"href", and "script"->"src" links. """ if not page_url.startswith("http://") and not page_url.startswith( "https://" ): return [] prefix = "http:" if ...
1b640517deaa51b2cbf9e556c44253070f6b4a2e
653,498
import sqlite3 def book_member(database: sqlite3.Connection, rno: int, email: str, seats: int, seat_price: int, src: str, dst: str) -> bool: """Books a member on a ride and generates its booking number""" dbcursor = database.cursor() dbcursor.execute("Select MAX(bno) from bookings") bn...
aafd5987efd123af165dd554a60a694051c65ac1
653,500
def test_inp(test_obj, test_if, name_inp, value=False): """ Test a value if it returns false raise an exception :param: test_obj Object to be tested. :param:test_if The input that is tested to be equal as. (in int, str, double etc) :param: value Bool, if True the exception also shows tes...
2023aed82b12552a9e6bf1f604881f60dc9449ef
653,501
def reconnect(device, **kwargs): """Reconnect an unreal device Parameters ---------- device (UnrealDevice): an unreal device instance kwargs (dict): keyword arguments Returns ------- bool: connection status """ result = device.reconnect(**kwargs) return result
a8623d15053d2525460eb8d4ad90522a7bc5826b
653,502
import torch def negative_sampling(batch, num_nodes, head_corrupt_prob, device='cpu'): """ Samples negative examples in a batch of triples. Randomly corrupts either heads or tails.""" bs, ns, _ = batch.size() # new entities to insert corruptions = torch.randint(size=(bs * ns,),low=0, high=num_nodes, ...
568fa8e4859fc356f3a5b7f1fffe8ac07799d224
653,503
def get_edges_by_snapshot_dict(G, edgelist, active_years): """ Organizes edges by ing snapshot year (year before citing year) list is igraph indices """ num_edges = len(edgelist) # get the citing year of each edge snap_years = [G.vs[edge[0]]['year'] - 1 for edge in edgelist] # dict th...
7094ae38458115666fb1830b5a93d96fff84dea7
653,506
def lie_bracket(element_1, element_2): """ Unfolds a Lie bracket. It is assumed that the second element is homogeneous (the bracket grows to the left). Returns a string encoding the result of unfolding: each addend is represented as a sequence of indeces (which are separated by '.'), the addends are sep...
53ab152f92ae058cdacea944e12dd8717b5fa2d0
653,508
from typing import Dict from typing import List def get_production_weighted_losses( losses: Dict[str, Dict[str, float]], locs: List[str] ) -> Dict[str, Dict[str, float]]: """ Return the transformation, transmission and distribution losses at a given voltage level for a given location. A weighted avera...
daf7eeb28d3c1b98ee19b77729b0eb98d2a29207
653,509
def UsersInvolvedInTemplate(template): """Return a set of all user IDs referenced in the template.""" result = set( template.admin_ids + [fv.user_id for fv in template.field_values if fv.user_id]) if template.owner_id: result.add(template.owner_id) for av in template.approval_values: result.upda...
0e40a08fe9d74bccc4a51ca549738e652a2e9097
653,510
def compute_f1_score(predict_y,eval_y): """ compoute f1_score. :param logits: [batch_size,label_size] :param evalY: [batch_size,label_size] :return: """ f1_score=0.0 p_5=0.0 r_5=0.0 return f1_score,p_5,r_5
fdcb072f5f6c8d415fda55087f912da60e3a218c
653,511
import torch def predict_fn(input_object, model): """Execute the model on input data""" with torch.no_grad(): model.eval() prediction = model(input_object) return prediction
a89f90fa41fde15308d7496f5e73a3bac435443b
653,512
def ibmqx(index): """ Creates one of the IBM Quantum Experience coupling maps based on the index provided Args: index (integer between 2 and 5): specify which of the QX chips should be returned Returns: dict { "qubits" : the number of qubits in the coupling map ...
9a02a4aeb80ba9493ecc2fcee53e16386e95b9d8
653,513
import collections def find_duplicate_basenames(paths): """Return a dict mapping duplicate basenames to their full paths.""" pathmap = collections.defaultdict(list) for p in paths: pathmap[p.name].append(p) # Remove any entries that only have one item in their associated list for name in l...
3770b0c7fcef894552fbbf0e4e2ec9c89b38f96d
653,514
def get_calendar(intent_message, default_calendar): """ Get the calendar from an intent. This returns the default calendar if the intent doesn't have a calendar. Parameter intent_message: the intent message Parameter default_calendar: the default calendar """ # The user has specified a ca...
583f939e2cddd83cc4fd5ba3b007c22c8834acfa
653,515
def rx_port(b2b_raw_config): """Returns a receive port""" return b2b_raw_config.ports[1]
269307acacb87f996264ba5e7690a4f269de4abe
653,516
def is_binary(data): """ Return True if the input series (column of dataframe) is binary """ return len(data.squeeze().unique()) == 2
7f895fe03461bc2a1a66f4332f82c13eabe8b4b8
653,517
def job_id(conf): # type: (dict) -> str """Get job id of a job specification :param dict conf: job configuration object :rtype: str :return: job id """ return conf['id']
269e802f9b8c21647bde2e597ee6fc21e7c081c8
653,518
import random def _generate_placeholder_string(x, default_placeholder="{}"): """Generate and return a string that does not appear in `x`.""" placeholder = default_placeholder rng = random.Random(5) while placeholder in x: placeholder = placeholder + str(rng.randint(0, 9)) return placeholder
143ba87fb28b56af998e54d97a486574f62a3f41
653,519
import copy def convertFindFurthestFieldMapToFreePlaceFormat(inputMap): """ Converts map into a type for an other function to use it :param inputMap: tempCS from findFurthestField :return: converted map """ outputMap = copy.deepcopy(inputMap) for y in range(len(outputMap)): for x i...
e7452baee263a59b92d07b34f9942f8c5dcc7426
653,521
import os def create_output_dir(outputdir = None): """ A simple function to e an output directory to store important logging informmtion, as well as important figures for qc """ if outputdir is None: i = 1 outputdir = "output" + str(i) while os.path.exists(outputdir): ...
1ad386304312d74c78714e0ddb4a4c0c10639e30
653,522
import os def image_file_name_to_height(storm_image_file_name): """Parses radar height from name of storm-image file. :param storm_image_file_name: Path to input file. :return: radar_height_m_agl: Radar height (metres above ground level). :raises: ValueError: if radar height cannot be parsed from fil...
463caddc9809a8fea3533232fd24928505899252
653,524
import subprocess import os def test_no_banned_pickle_usage(): """ Check that dumping of pickled content uses our internal functions, not built-in pickle. Python 3.8 changed the default protocol for pickle. To avoid any inconsistencies in the output of dumped pickle content across different python ve...
55c545bcb9fa071420f76387c0869b88332b5a14
653,525
import configparser def configure(config_file='../docs/default_config.ini'): """ Reads a configuration (INI format) file that specifies the three working directories for binary image files, as well as the preferred database connection. A configuration file should contain two sections: 1. A ...
09f58edd29748497e8ee81bc91ae09a9acd7972f
653,526
import os import errno def get_metadata_from_file(path, attr_key): """Get metadata from key attr_key in file at given path.""" try: mdbytes = os.getxattr(path, attr_key) except OSError as e: if e.errno == errno.ENODATA: return None raise return os.fsdecode(mdbytes)
cbeaa37239470b7dbe20e1039a021e094adc523a
653,527
def drillPath(diameter): """ Returns an SVG path for a drill symbol of diameter 'diameter' """ r = diameter/2.0 # The calculation to obtain the 'k' coefficient can be found here: # http://itc.ktu.lt/itc354/Riskus354.pdf # "APPROXIMATION OF A CUBIC BEZIER CURVE BY CIRCULAR ARCS AND VICE VER...
e9abf3336d721d8646f0db12f10dde2a2d272c02
653,529
def isInTag(text, start, end): """ Checks whether the string in link or not. @param {string} text Text containing a string. @param {number} start Start position of a string. @param {number} end End position of the string. @result {boolean} True if a string is in tag. ...
787349add26e0315e286388e6942c4c0f7750069
653,530
def approximates(ref_point, point, max_deviation): """Helper function to check if two points are the same within the specified deviation.""" x = ref_point[0] - max_deviation <= point[0] <= ref_point[0] + max_deviation y = ref_point[1] - max_deviation <= point[1] <= ref_point[1] + max_deviation ...
8e53bf9a3fef2c04323d7000c43bcd09be0c2cce
653,531
def set_color_code(qf): """Return color based on the given flag.""" if qf == 'B': return 'red' elif qf == 'S': return 'orange' elif qf == 'E': return 'green' else: return 'navy'
ae854ed1f39324cac0a1561530b5cc708c1c3c99
653,532
def get_distances(clusters): """Extract distances as intermediate values between 2 clusters""" distances = [] for idx, _ in enumerate(clusters[:-1]): clst_0 = float(clusters[idx]) clst_1 = float(clusters[idx + 1]) distances.append((clst_1 - clst_0) / 2 + clst_0) return tuple(dist...
4da9653ae5ed98e9060780f4865ab91ed80f8bee
653,533
import math def roundup(x): """ This function rounds up a number to the first higher 200-fold Argument: Float or Int Returns 200-fold int """ return int(math.ceil(x / 200.0)) * 200
3b675a2682c1413326c259babae4e7224f90e42e
653,534
from datetime import datetime import pytz def get_seconds_from_epoch(datetime_obj): """Get datetime as total seconds from epoch. Provides datetime in easily sortable format Args: datetime_obj (datetime): Datetime. Returns: (float): Seconds from epoch """ from_epoch = datetime...
8bfdeb10d1131525e4eb909f3215f4c75a2e499b
653,535
def createVocabularyList(moodWords): """ 创建语料库 :param moodWords: :return: """ vocabularySet = set([]) for words in moodWords: vocabularySet = vocabularySet | set(words) vocabularyList = list(vocabularySet) return vocabularyList
bef0efb1dca0ba981a30092c4e68cbd592845c74
653,536
def normalize_encoding(encoding): """ Normalize an encoding name. Normalization works as follows: all non-alphanumeric characters except the dot used for Python package names are collapsed and replaced with a single underscore, e.g. ' -;#' becomes '_'. Leading and trailing undersc...
5f3f6d46c2893660b6c390c61bf83af7fe1d4e5a
653,537
def alignment_patterns_table() -> dict[int, list[int]]: """A dictionary that contains the positions of the alignment patterns. Returns: dict[int, list[int]]: Returns a list of positions. """ table = { 2: [18], 3: [22], 4: [26], 5: [30], 6: [34], 7...
86bf868cfd00b66b1175abe34f7824567e38808a
653,538
import re def strip_md_header_and_links(md): """strip markdown headers and links from markdown text md Args: md: str, markdown text Returns: str with markdown headers and links removed Note: This uses a very basic regex that likely fails on all sorts of edge cases but works for ...
27990d688756846e8eb7d22acc54cea6552cdb9e
653,539
def dispatch(obj, replacements): """make the replacement based on type :param obj: an obj in which replacements will be made :type obj: any :param replacements: the things to replace :type replacements: tuple of tuples """ if isinstance(obj, dict): obj = {k: dispatch(v, replacements...
34318316d26091c374934ce68f6186f3b984a05a
653,540
def title_case(text: str) -> str: """Convert the text to title case. Args: text: The text to convert to title case. Returns: str: The text converted to title case. """ return text.title()
d4e87ecd4fbc003e6370ae2d96cf9a3aef114243
653,541
import os def _MigrationFilenameToInt(fname): """Converts migration filename to a migration number.""" base, _ = os.path.splitext(fname) return int(base)
d169167644059f5f3bc4a753da13988d714b3490
653,542
def cut_to_specific_word(dataframe, specific_word, part_in_bid): """ Takes in a dataframe and a column, and then creates a new dataframe containing only the rows from the original dataframe that had the search word in that column :params: a dataframe, a specific_word to look for, and a column name relat...
c8ee42088cb85c053b1a5a8b3877436a50df689d
653,543
import numpy as np def mesh_function ( r, q, sc ): """Function to assign charges to a 3-d mesh.""" # This function assigns a set of charges to a cubic mesh using the # triangular shape cloud distribution described by Hockney and Eastwood (1988) # It is assumed that the charges are in a box of unit le...
047f9cbb8eed4b4770935560c1b4cb58714a42a1
653,544
import json def parse_line(line): """Parse a JSON string into a Python object.""" try: line = line.strip() return json.loads(line) except json.decoder.JSONDecodeError: return None
cd2e1e230da656c3adfd8ecede0c1fdb14e00423
653,545
from pathlib import Path import logging def _check_file_existence(file_path: str) -> bool: """ Validates the existence of a file """ path = Path(file_path) if not path.exists(): logging.error('Provided file cannot be found.') return False return True
d7e147132d824fe62e4bb4f498df79d3c5bd02bb
653,546
def getKaryotype(fname): """returns dictionary e.g.: {'chr13': 115169878, ... } """ data = [i.strip().split() for i in open(fname) if i[:3] == 'chr'] hs = {} for i in data: hs[i[6]] = int(i[5]) return hs
f013d7e61416d543d1c08f79b8c44ea7f616bd51
653,547
def piecewise_linear_continuous(x, x_b, m_1, b_1, m_2): """ Eq. 10. 2-Part Piecewise Linear Continuous Function Used to fit D18O_cc-w fractionation versus drip rate. Describes two lines that intersect at x_b. Parameters ---------- x : numpy array independent variable x_b : ...
f8dae31e083a75bb8aee3d080604fd7061e78ea9
653,548
import torch def prj_vtx_pth(vtx, pose, cam_K): """ project 3D vertices to 2-dimensional image plane using pytorch :param vtx: (N, 3), vertices, tensor :param pose: (3, 4), tensor :param cam_K: (3, 3), intrinsic camera parameter, tensor :return: pts_2D: (N, 2), pixel coordinates, tensor; z: (N...
5364d328696e19232a06d8c41c0acfbc6f270514
653,551
def get_description_dict(parser): """Return a dictionary of descriptions.""" retval = dict() for group_name, group in parser.sections(): retval[group_name] = dict() for attr_name, attr_value in group.options(): retval[group_name][attr_name] = attr_value.get_desc() return...
65ac53df2bf2cac1a5336a47cb693e03564445c6
653,552
def preprocess(batch_input): """If batch_input isn't numpy""" flatten, offsets = [], [] index = 0 for ex in batch_input: offsets.append(index) flatten.extend(ex) index += len(ex) return flatten, offsets
917fd573ed1d4900cb464252138b001a51617b22
653,553
def is_table_locked(connection, table_name, schema=None): """Returns the locks for a table or `None` if no lock is present.""" schema = schema or '%%' sql = ('SELECT mode FROM pg_locks JOIN pg_class ' 'ON pg_class.oid = pg_locks.relation ' 'JOIN pg_namespace ON pg_namespace.oid = pg_...
012ee2ed82a03594ae1734fda17dcbea4c6c1a32
653,554
from typing import Dict import os def getDirectoryInfo(dirname: str, depth: int) -> Dict: """ start with an empty dict and fill it with information describing the contents of the current directory as defined at the top of this file. if depth is greater than 0, for each sub directory in this dir...
6c584cf532da162657c360d20ed1da12ee79373f
653,555
def repeat_to_length(string_to_expand, length): """Repeats string_to_expand to fill up a string of the provided length. Args: string_to_expand: string to repeat length: length of string to return Returns: generated string of provided length """ return (string_to_expand * (int(leng...
84b7b20569022ea630020441071cbffa2b016b61
653,556
def select_rows_by_regex(df, column_name, regex_str): """Returns pandas dataframe rows matching regex in a specific column. Returns a dataframe with a subset of rows where the value in the column contains the regex. Args: df: A pandas dataframe. column_name: Name of the column...
c48e6e732864f33b959d3a6c002873b5b9b581eb
653,557
def append_verbosity_argument(cmd, verbosity): """ Just in case we want to modify how many v's we use, centralise this here. """ return cmd + " -vvvv" if verbosity else cmd
1ade3e64a0f14551558837f573e9de228b9919e4
653,558
import importlib import inspect import dis def get_core_function(translated, language, stage=False): """Get core API function for a translated function name. Use the function metadata to determine the correct translated API function based on a given core function name. Parameters ---------- ...
9b01deddc6ad1227d591ae23e8217fe986041509
653,559
def with_lock(method): """ Execute method with lock. Instance should have lock object in lock attribute. """ def wrapper(self, *args): with self.lock: return method(self, *args) return wrapper
1114afa821c9245588328a6757b3ca5e16805a34
653,560
def sql_file(tmp_path): """ Construct a file containing a SQL statement """ directory = tmp_path / "sql" directory.mkdir() file = directory / "sql.txt" file.write_text("SELECT\n 1 as foo;") return file.absolute()
e5adb73bc24519ab7547aa2ca897bcca70e4aaca
653,561
import math def logistic_func(x, k): """ Return the value of the logistic function for variable x and steepness parameter k. Function multiplied by an adjuster to make it better mimic a forest stand's volume grown over time. Logistic function has parameters L = 150 and x0 = 0. """ ...
cb681df98bc846e679db3754f8c7d5aae052e3a5
653,562
import re import os def getDomainFromPlist(plist_path_or_name): """Assuming the domain is also the name of the plist file, strip the path and the ending '.plist'""" domain_info = {} domain_info['is_byhost'] = False # Match a domain ending in .ByHost, the Ethernet MAC, or the Hardware UUID byhost_...
b25502e7542b1b7a45b287327dc5244c00dbb695
653,564
from typing import Optional import hashlib def transport_channel_id(transport, is_server: bool, channel_id_type: Optional[str] = None) -> bytes: """ Application-layer user authentication protocols are vulnerable to generic credential forwarding attacks, where an authentication credential sent by a cli...
5d87cdea3843651b67a75d5735cd6a58401c38cd
653,567
from pathlib import Path from typing import List def _split_pbn(file_path: Path) -> List[List[str]]: """ Read in the entire PBN file. Split on lines consisting of '*\n' into a list of strings per board :param file_path: path to PBN file :return: """ with open(file_path, "r") as pbn_file: ...
628ec0be07f96e3640dc08527bc6a3de600c0472
653,569
import shlex def build_remote_command(working_directory, args, post_command=''): """ These machinations ensure that the command is run (a) in the project working directory (b) using an 'interactive' shell, which ensures that .bashrc is read and loaded, as that is how domino propogates environm...
4e5c9f70d3cb612836c118121ad83efe0a9add5c
653,571
def _maybe_overlapping_memory(shape, strides): """Returns bool value indicating the array with such shape and strides might have overlapping memory. Args: shape (tuple of int): The shape of output. strides (tuple of int): The strides of output, given in the unit of steps. storage_offset (int): ...
df8c6c8ebf3b4d7116c6ca297a5565980eaf51cc
653,572
def _construct_source_string(sources): """ From a list of sources, return a fancy string output displaying them as a list. """ num_sources = len(sources) if num_sources == 1: this_source_string = 11 * ' ' + u"└──────────────────" else: this_source_string = 11 * ' ' + u"└────────...
ac742b2217474c0edc2ab4f3c302022edd3e9a61
653,573
def is_finite_ordinal(n): """ Return True if n is a finite ordinal (non-negative int). """ return isinstance(n, int) and n >= 0
c4a191bf15b550c1fe368d1921d63d821439ff60
653,574
import os import re import json def cutadapt_log_parser(log): """ Parsing the output of cutadpat support multiple run output save data in JSON format """ logdict = {} _cutadapt_ver = [] _python_ver = [] _cmd = [] _fname = [] _raw = [] _clean = [] outfile = os.path.s...
a537d1d35e024e71c1422334c09de13b573c31cd
653,575
def _EnableTypoCorrection( flags ): """Adds the -fspell-checking flag if the -fno-spell-checking flag is not present""" # "Typo correction" (aka spell checking) in clang allows it to produce # hints (in the form of fix-its) in the case of certain diagnostics. A common # example is "no type named 'strng' in n...
f632e22c0aa02577fb1936e4c38b04fe1b234a9c
653,576
import six def _get_column_pairs(columns, require_qualifier=False): """Turns a list of column or column families into parsed pairs. Turns a column family (``fam`` or ``fam:``) into a pair such as ``['fam', None]`` and turns a column (``fam:col``) into ``['fam', 'col']``. :type columns: list ...
44336b76fc82d560a42b2306188a87f93f80ae82
653,577
def myzip(*cols): """Zip columns function used to zip forecast lists together""" return zip(*cols)
9d16ec74932e38998032f33da6eda205ea586f89
653,579
import re def to_separate_metadata_list(args) : """ 将数据变成是元数据的各个项目,每个项目作为单独的数据列表而出现。每次获取单独生成页面。 """ result = [] taskfunc = lambda theme: re.sub(r'[=]', r'_', args['pattern'] % theme) #savefunc = lambda theme: re.sub(r'[=]', r'_', theme) + '.md' savefunc = lambda theme: re.sub(r'[=:/,\'\(\)...
35cbc9b06b0a841cedbcf290dbf5cb04a8a2365d
653,580
import subprocess def read_count(fastq): """Very fast read counter (assuming the FASTQ is formatted properly). Args: fastq (str): fastq file path Returns: int """ return int(subprocess.check_output("awk '{n++}END{print n/4}' %s" % fastq, shell=True).decode())
2ff1f93fee2700e835239453b1e5c28de7eba674
653,581
def fix2range(vals, minval, maxval): """ A helper function that sets the value of the array or number `vals` to fall within the range `minval` <= `vals` <= `maxval`. Values of `vals` that are greater than `maxval` are set to `maxval` (and similar for `minval`). Parameters ---------- va...
d5df9ec213fdc48f6a30342b71571608a6bd1103
653,582
def quadratic_taylor(f, location): """Compute the parameters for a quadratic model at a location. Args: f (Objective): The reference function to be Taylor-approximated. location (torch.Tensor): The location. Returns: dict: The coefficients describing a quadratic function (offset, d...
89eaeefdf91d7541cf39951d0f26dff0ed433dbc
653,583
def _dict_with_extra_specs_if_authorized(context, inst_type_query): """Convert type query result to dict with extra_spec and rate_limit. Takes a volume type query returned by sqlalchemy and returns it as a dictionary, converting the extra_specs entry from a list of dicts. NOTE: the contents of...
68ed1b89d73f3a991082a42aafdfcae8851bc636
653,584
def split_idx(nums, start, end): """ 对group list进行切分,获得其start到end之间的子group list """ res = [] for idx in nums: if start >= len(idx): start -= len(idx) end -= len(idx) else: if end > len(idx): res.append(idx[start:]) s...
fba9528e4d46f01010a924b153f17413432c374c
653,585
import collections def xml2dict(t): """Convert an attribute-less etree.Element into a dict.""" dd = collections.defaultdict(list) for dc in map(xml2dict, list(t)): for k, v in dc.items(): dd[k].append(v) return {t.tag: dd or t.text}
ffec90ad5e75ed7229ffb9005255c2c1e62200ef
653,586
import requests def newSDDCGroupIPaddress(proxy_url,sessiontoken,gw,group_id,ip_addresses): """ Creates a single SDDC Group based on IP addresses. Use 'mgw' or 'cgw' as the parameter """ myHeader = {'csp-auth-token': sessiontoken} proxy_url_short = proxy_url.rstrip("sks-nsxt-manager") # removing 'sks-...
8b54d55eeccd9d7372f07cd8ea219bf02b9a1e0b
653,587
def null_case(): """Route is not marked for monitoring so should not be included in output""" return 0
d1f9f67b61ace597c8c7251c1e7ac3f3a44a6f44
653,589
def maker_file_path_fromidx(digits=1, levels=1): """ Creates a method that returns a file path for the given number of leading digits and levels. Args: digits: minimum number of digits to use for the path, any number with less digits will have leading zeros added. levels: how to ...
6d279c9a8b5eb0d3e4919a738114f7b49841743e
653,590
import requests def query_to_json(query): """Query with requests and return response as json Parameters ---------- query : string query Returns ------- json response """ return requests.get(query).json()
fc3226e33b53b4de7d9e6b1f5dc2cec8afdd27ce
653,591
async def files_for_PR(gh, pull_request): """Get files for a pull request.""" # For some unknown reason there isn't any files URL in a pull request # payload. files_url = f'{pull_request["url"]}/files' data = [] async for filedata in gh.getiter(files_url): # pragma: no branch data.appen...
fb87aaf206538020555c7d3e7872bfceb400b354
653,592
import math def create_geographic_chunks(longitude=None, latitude=None, geographic_chunk_size=0.5): """Chunk a parameter set defined by latitude, longitude, and a list of acquisitions. Process the lat/lon/time parameters defined for loading Data Cube Data - these should be produced by dc.list_acquisition...
dbc23c6e332edbe57c96c786f63d29c3454987bd
653,593
def _check_mean_sub_values(value, channels): """ Checks if mean subtraction values are valid based on the number of channels 'value' must be a tuple of dimensions = number of channels Returns boolean: True -> Expression is valid False -> Expression is invalid """ if value...
624cbe3ced20da45eb9f7ded2afd69301e86d414
653,594
def check(checkRow, checkColumn): """checks if this row and column is valid, used when looking at possible piece movement""" if 0 <= checkRow <= 7 and 0 <= checkColumn <= 7: return True return False
7d87344a245e8f9053d99ff38d78505b3be6caf8
653,595
def Propagate(goidlist,GOparentsDict): """ Input list of GO identifiers Return list inclusing all GO parents """ parents={} stack=[] for goid in goidlist: stack.append(goid) while len(stack)>0: goid=stack.pop() parents[goid]=1 if not goid in GOparentsDict: continu...
58c500de2cde5577dcaa4c5688f0cccb29f80b8c
653,596
def _parse_clusters(filename): """ Private function to parse clusters.out file Args: path: directory to perform parsing Returns: List of dicts """ with open(filename) as f: lines = f.readlines() clusters = [] cluster_block = [] for line in lines: li...
84671b86feff13d6195ac66a8db83ea4e86d9a4a
653,597
def compute_test_matrix(training, testing): """ Compute the gram matrix for the test set""" return testing.dot(training.T)
4eeffe715bacfc36b9da7a4fe7ff2b7abb5f4c7a
653,598
def doc_template(object_name: str, body: str)->str: """Returns an html page :param object_name: name of the object :param body: body of the page :return: the page """ doc = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>""" + object_name + """</title> <m...
faf7a74f58dd1d2957b29d125b9d24d950c2429a
653,600
import requests from bs4 import BeautifulSoup def fetch_swimmer_urls(url): """Fetch all of the swimmers and urls from a team url""" # Download/parse the pages page = requests.get(url) soup = BeautifulSoup(page.content, features="html.parser") # The last table in the page contains all the swimmer...
73c2dcaf7db5d68dc3774683b08210b1f05add0b
653,601
def _copy_with_ignore(dct, keep, ignore=()): """ Copy the entries in the given dict whose keys are in keep. Parameters ---------- dct : dict The dictionary to be copied. keep : set-like Set of keys for entries we want to keep. ignore : set or tuple Don't issue a warn...
b08df5db5506f9b687469686fd71400830b2820b
653,602
import numpy def delete_shuffle_async(i, popsize): """Delete current solution from population for mutation (asynchronous).""" return numpy.random.permutation(numpy.delete(numpy.arange(popsize), i))
90c9cde186b4ab41f5cc8b3bac94683d53136f91
653,603
def convert_to_bool(string): """ Converts string to bool :param string: String :str string: str :return: True or False """ if isinstance(string, bool): return string return string in ['true', 'True', '1']
ad73878e595a4127e2ba8510e14e446f282533dc
653,604
def coordinates(width, height): """ Returns coordinates [x1, y1, x2, y2] for a centered box of width, height """ with open('/sys/class/graphics/fb0/virtual_size', 'r') as res: screenx, screeny = map(int, res.read().strip('\n').split(',')) posx = (screenx/2) - (width/2) posy = (screeny/2) -...
8e0b34a300f2a81f303d7592baeb18d4143145be
653,606
def evaluate_ser(entity, outputs): """ Get all correct and incorrect queries. Correct means all entities are identified correctly with exact span :param entity: list of (start_index, end_index, label) tuples for EACH query :param outputs: PARSED mallard/duckling responses :return: Two lists of ...
142e4b4a85d92625e86cc1ecc664fa265eac8871
653,608
def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if is...
fe53bff4168380d1c3be8b9c48c6a235b7e5abce
653,609