content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def linearize_subtable(subtable, table_page_title, table_section_title):
"""Linearize the highlighted subtable and return a string of its contents."""
table_str = ""
if table_page_title:
table_str += "<page_title> " + table_page_title + " </page_title> "
if table_section_title:
table_str... | f1b7c4263711ee47a05d4fa6f15c143ef7ef48d1 | 668,326 |
def main(args=None):
"""Main function."""
print(args)
return 0 | 11fef9547ad1f76e5bddb1acc2b98d96cbb1bbfb | 668,327 |
import functools
def user_overrides(f, overrides=None, *args, **kwargs):
"""Decorator that allows a user to fill in the remainder of a functools.partial."""
# problematically i don't really know how to do this.
@functools.wraps
def _():
return f(overrides)
return f(*args, **kwargs) | ef82fe71be746d82d3db0b356d7504f194d6a9db | 668,328 |
def apply_threshold(heatmap, threshold):
"""
Apply threshold to the heatmap to remove false positives.
Parameters:
heatmap: Input heatmap.
threshold: Selected threshold.
"""
heatmap[heatmap < threshold] = 0
return heatmap | a62a5bba0606f2b9b1ca42e3360cbbb6e4f85c78 | 668,329 |
def lower_dict(input_dict):
"""
Convert all keys in a dictionary to lowercase; keep their original values.
Keep in mind that it is possible (but not useful?) to define different
variables that have the same lowercase representation. It would be hard to
tell which is used in the final dict and which... | 6bcb70e4e33c07254036030f120acb05f881c1b0 | 668,330 |
def get_number_rows(ai_settings,ship_height,alien_height):
"""determine the number of rows of aliens that fits on a screen"""
available_space_y=(ai_settings.screen_height - (5 * alien_height)-ship_height)
number_rows=int(available_space_y/(2 * alien_height))
return number_rows | b0b7b59456c24969b03b5996c8e6dc54bc2c2077 | 668,331 |
def split_schema_obj(obj, sch=None):
"""Return a (schema, object) tuple given a possibly schema-qualified name
:param obj: object name or schema.object
:param sch: schema name (defaults to 'public')
:return: tuple
"""
qualsch = sch
if sch is None:
qualsch = 'public'
if '.' in ob... | 050900ce3bbe761dfde3ae131bf2576354a7b536 | 668,332 |
from functools import reduce
def a2bits(chars: str) -> str:
"""Converts a string to its bits representation as a string of 0's and 1's.
>>> a2bits("Hello World!")
'010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001'
"""
return bin(reduce(lambda x, y: ... | c155a9ad2b0e704d1cc3a981d10d9be1ac2e905a | 668,333 |
def get_all_combinations(node_lists):
"""
Generate a list of all possible combinations of items in the list of
lists `node_lists`. Each combination takes one item from each list
contained within `node_lists`. The order of items in the returned lists
reflects the order of lists in `node_lists`. For e... | 31531dfc77e6ccda9c9c26b62193669d9c346a34 | 668,334 |
def filepath(patched_file):
"""Return target path as this is convinient to use in GitHub"""
if patched_file.source_file.startswith('a/') and patched_file.target_file.startswith('b/'):
filepath = patched_file.target_file[2:]
elif patched_file.source_file.startswith('a/') and patched_file.target_file ... | 5df694317df3cd215fc30c18aca81899f1f6cb3e | 668,335 |
def um_to_px(um, um_per_px):
"""Conver mircon to pixel
"""
return um * 1/um_per_px | 561fe5652277f26cc7d861ab6c86a369f4951949 | 668,336 |
def recover_flattened(flat_params, indices, model):
"""
Gives a list of recovered parameters from their flattened form
:param flat_params: [#params, 1]
:param indices: a list detaling the start and end index of each param [(start, end) for param]
:param model: the model that gives the params with co... | 13f264cd16a43da9cae0e0967340e95d2ae4f647 | 668,337 |
def make_dict(keys, values):
"""
Returns a dictionary that maps keys to values correspondingly.
Assume inputs are of same length.
"""
return dict(zip(keys,values)) | cdf80e785d21b665250ec8b902721f6db8b48baf | 668,338 |
import re
def extract_phrases(text):
""" extract phrases, i.e. group of continuous words, from text """
return re.findall('\w[\w ]+', text, re.UNICODE) | a0016b40b1b9a16d5928f3314a7db8de1e20bfd2 | 668,339 |
def dict_reorder(item: dict) -> dict:
"""
Sorts dict by keys, including nested dicts
:param item: dict to sort
"""
if isinstance(item, dict):
item = {k: item[k] for k in sorted(item.keys())}
for k, v in item.items():
if isinstance(v, dict):
item[k] = dict_... | 8d756a5c19b62294db6369ae2a5b007ad33cc297 | 668,340 |
def tx_exon_aln_v_data():
"""Create test fixture for tx_aln_v_data test."""
return ["BRAF", "NM_004333.4", 1802, 1921, "NC_000007.13", 140453074,
140453193, -1, "splign", 780494, 1927263] | c289d722336c68405deaf25e8a06d391563d517e | 668,341 |
from typing import List
from typing import Dict
from typing import Any
def parse_response(raw_data: List[Dict[str, Any]], wanted_keys: List[Any], actual_keys: List[Any]) -> \
List[Dict[str, Any]]:
"""Lists all raw data and return outputs in Demisto's format.
Args:
raw_data: raw response from t... | 3b4e172636f5d514fa0dbd3e4be81c6a41d39406 | 668,343 |
def check_guess(user_number,generated_number,count):
""" check user guess number against with genrated number """
if(user_number == generated_number):
return f"Great Job! The Correct number is {generated_number}. You have made {count} guesses.\n"
elif(user_number > generated_number):
return ... | 6b95666544913b72f7d5a0cfd3538a232c037af1 | 668,344 |
def normalize_name(name):
"""Capitalize all words in name."""
words = name.split()
res = ""
for w in words:
if res != "":
res += " "
res += w.capitalize()
return res | 8cd80a37e0fc8efe89dbbb30309c74e63395351b | 668,345 |
def list_parties(component):
"""
:param component: instance of ComponentModel
:return: list of user id values.
"""
result = ''
for party in component.parties.all():
result = result + str(party.id) + ","
return result[:-1] | e383772d08479cea53742c643cd2c48e76ea2087 | 668,346 |
def get_date_formatted(date):
"""
Return the date in the format: 'YEAR-MONTH-DAY'
"""
year = str(date.year)
month = str(date.month)
day = str(date.day)
single_digits = range(1, 10)
if date.month in single_digits:
month = '0' + month
if date.day in single_digits:
d... | 6b4699460150b2d90326f29d6a22617e4e3ffdfe | 668,347 |
import os
def format_traceback(trace):
"""Does some formatting on a traceback"""
hidden = 0
final_trace = []
for frame in trace:
if "site-packages" in frame or "dist-packages" in frame:
hidden += 1
continue
if hidden > 0:
final_trace.append(f"\n{hidd... | 3bf797755927d3ac027e23291f41f8183fe0dac0 | 668,348 |
import jinja2
def render_happi_template_arg(template, happi_item):
"""Fill a Jinja2 template using information from a happi item."""
return jinja2.Template(template).render(**happi_item) | 79aa02a9a37bf23806abc527f0f896a365db72b9 | 668,349 |
def getParentPath(path):
"""Get the parent path from C{path}.
@param path: A fully-qualified C{unicode} path.
@return: The C{unicode} parent path or C{None} if C{path} represents a
root-level entity.
"""
unpackedPath = path.rsplit(u'/', 1)
return None if len(unpackedPath) == 1 else unpa... | 3b844b80b716e7dac482a891bc83245f1163f5bb | 668,350 |
def ordinal_indicator(num):
"""Appends the ordinal indicator (th/st etc.) to the end of a number."""
return "%d%s" % (num,"tsnrhtdd"[(num // 10 % 10 != 1) * (num % 10 < 4) * num % 10::4]) | 3d07b5097e900a1c9eacdc509db1fa967e28f422 | 668,351 |
def two2one(x, y):
"""Maps a positive (x,y) to an element in the naturals."""
diag = x + y
bottom = diag * (diag + 1) / 2
return bottom + y | 352b514579de48128ef1abe97dfce37b8a0fff5c | 668,352 |
def total_ordering(cls):
"""Class decorator that fills in missing ordering methods"""
convert = {
'__lt__': [('__gt__', lambda self, other: not (self < other or self == other)),
('__le__', lambda self, other: self < other or self == other),
('__ge__', lambda self, o... | dafe5160419b81a881dec6df6ee3f9bfc3890c64 | 668,353 |
def get_complementary_orientation(orientation):
"""Used to find the outcoming orientation given the incoming one (e.g. N ->
S; E-> W; S -> N; W -> E)."""
return (orientation + 2) % 4 | 98331ecddffd39041aaa2d3086e0f3dc21d7061f | 668,354 |
import requests
def send_token_request(form_values, add_headers={}):
"""Sends a request for an authorization token to the EVE SSO.
Args:
form_values: A dict containing the form encoded values that should be
sent with the request
add_headers: A dict containing additional h... | f9c00e7f598db20c69fe6bf44f3df7100ef974b8 | 668,355 |
import os
import json
def valid_agents() -> dict:
"""
Returns:
dict: A dictionary of valid agent, where each key is an valid agent shorthand.
Each dictionary key (e.g. shorthand) refers to a new dictionary containing,
additional information, such as a short description of the s... | 3894162294779d03be87f1092de0552ae2dd770d | 668,356 |
def _get_previous_month(month, year):
"""Returns previous month.
:param month: Month (integer from 1...12).
:param year: Year (integer).
:return: previous_month: Previous month (integer from 1...12).
:return: previous_year: Previous year (integer).
"""
previous_month = month - 1
if pr... | 958775c5ce23e6550f54104c1390673a913f7ff1 | 668,357 |
import math
def get_rows_cols_for_subplot(num_subplots:int)->tuple:
"""
This function calculates the rows and cols required
for the subplot..
Args:
num_subplots:int
Returns:
nrows:int
ncols:int
odd:bool
"""
try:
nrows=ncols=0
o... | 3572c31b988dbec99d339039edfacc7ed246a008 | 668,359 |
def strip_surrounding(word):
"""
Strip spaces in the front or back of word.
:param word: A word (or sentence) of which we want to strip the surrounding spaces.
:return: A string that doesn't start or end with a space.
"""
while word and (word[0] != ' ' or word[-1] != ' '):
if word[0] ==... | eacb57971e0c4ada9b7ed16c70e084cc855210f4 | 668,360 |
import itertools
def run_length_encode(tags_to_encode):
"""Perform run length encoding.
Args:
tags_to_encode: A string, usually of DeletionTags.
Returns:
the RLE string. For example, if the input was NNNNNCNNTTC,
the function would return 5N1C2N2T1C
"""
rle_list = [(... | 737b574618761f5a56a2390055b935beec8bbc6b | 668,361 |
def get_genres_dictionary(artists_by_id):
"""Short summary.
Parameters
----------
artists_by_id : type
Description of parameter `artists_by_id`.
Returns
-------
type
Description of returned object.
"""
return {key: val['genres'] for key, val in artists_by_id.items... | 6f2ff2b3d5ee730f1ff6397e4f317b5560b7523f | 668,362 |
from unittest.mock import patch
def qgs_access_control_filter():
"""
Mock some QgsAccessControlFilter methods:
- __init__ which does not accept a mocked QgsServerInterface;
- serverInterface to return the right server_iface.
"""
class DummyQgsAccessControlFilter():
def __init__(self, ... | 4fa337fd18b650269adf275703923edbcc5ad9ca | 668,363 |
def assign_x_coord(row):
"""
Assigns an x-coordinate to Statcast's strike zone numbers. Zones 11, 12, 13,
and 14 are ignored for plotting simplicity.
"""
# left third of strik zone
if row.zone in [1,4,7]:
return 1
# middle third of strike zone
if row.zone in [2,5,8]:
ret... | 76a7e3957e945803fe2b7467ca776586d5c74580 | 668,364 |
def hasPathSum(root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None and sum is 0:
return False
if not root:
return False
if (not root.left) and (not root.right) and (root.val == sum):
return True
return h... | 31e489bc8b9a2f06b8de9afef8a77309e4aed887 | 668,365 |
def housecall_status(events):
"""Returns how many housecalls there are on the calendar."""
if not events: # no events means no housecalls
print('No upcoming events found.')
return 0
count = 0
for event in events:
name = event['summary'].lower()
if ('house' in name) and (... | 1c2a4caa18f3d2067a03c6bfa032b2743316d70d | 668,367 |
import functools
import sys
def guarded_command(function):
"""
Decorator of functions that implement CLI commands.
Occasionally the node can throw some exceptions instead of properly sending us a response,
those will be deserialized on our end and rethrown by the gRPC layer.
In this case we want ... | 94bb8b20b1ef2cf6b7868ec19efd519de6e1d8d6 | 668,368 |
def CSP(resourcetype, urls, append=True):
"""Decorator that injects a new CSP allowed source into the current csp output."""
def csp_decorator(f):
def wrapper(*args, **kwargs):
args[0]._SetCsp(resourcetype, urls, append)
return f(*args, **kwargs) or {}
return wrapper
return csp_decorator | 0829895b24550194f510a5acf31c4286b660e3a8 | 668,369 |
import csv
def read_portfolio(source):
"""Returns data from a CSV file"""
with open(source, newline='') as myfile:
csv_reader = csv.DictReader(myfile)
csv_source = []
for row in csv_reader:
symbol = row['symbol']
units = (row['units'])
cost = (row['c... | cffe956321ec9bbd424c9c6d2f629019fd0b0f27 | 668,370 |
def _word_count(counter, num=1):
"""
1字词个数
:param counter:
:param num:
:return:
"""
return counter.get(num) | efae7fd844295f62fd822952849e41cf5a1ed195 | 668,372 |
def searchkw(text_list, kw_lists):
"""Search for targeted elements in the list based on the lw_lists"""
mentions_list = []
for i, x in enumerate(text_list):
if any(n in x.lower() for n in kw_lists):
mentions_list.append(i)
return mentions_list | 9cae8d3172b336330fba28ebe7f0a2a15a4443af | 668,373 |
def droptotals(df):
"""
drop all "total" columns
"""
idx = df.columns.str.contains("total")
df = df.copy()
return df.loc[:, ~idx] | 0a3ae8eb790249573e2dd8b6f8cf8479fa8ba332 | 668,374 |
import os
import argparse
def get_arg():
"""Get Arguments"""
MERIT_description = """This is MERIT - a Mutation Error Rate Identification Toolkit - that includes the following steps:
- Step 1: Run samtools mpileup to detect variants and generate Pileup and BCF/VCF
- Step 2: Optional annotation via snpEff a... | 78d0839dc305f9f7fb86b938d111b986fef62744 | 668,376 |
def dsf_func(d50, theta ):
"""
Calculate sheet flow thickess
Input:
d50 - median grain size (m)
Theta - maximum (crest or trough) Shields paramter
Returns:
dsf - thickness of sheet flow layer (m)
Based on Janssen (1999) in van der A et al. (2013), Appendix C.
See also Do... | 711f64bb1de1112dc8da9d3b1e37bbf9405e9f8d | 668,377 |
import re
def check_duplicates(self, form_names_list, form_name):
"""
Searches for duplicate form_names in form_names_list. If one is found
a number(2) is appended to the end of form_name. If the new form_name is a
duplicate, the number at the end is incremented until no duplicates are
found.
... | 710c1a2b47044e454bf25d4b151c2f2e9ef26b69 | 668,378 |
def stock_prices_2_greedy(stock_prices):
"""
Solution: Iterate through stock prices once, keeping track of the
highest profit and lowest buy.
Complexity:
Time: O(n)
Space: O(1)
"""
if len(stock_prices) < 2:
raise ValueError('stock price list must be at least 2 items long')
lowest_buy = None
highest_profi... | a95bd700e71377119e64629884a4a11075e4639e | 668,379 |
import torch
def MM_mult(x, y):
"""A function that returns x*y, where x and y are complex tensors.
:param x: A complex matrix.
:type x: torch.doubleTensor
:param y: A complex matrix.
:type y: torch.doubleTensor
:raises ValueError: If x and y do not have 3 dimensions or their first dimens... | 82c8ca0e808209b3b5826345574842350496d641 | 668,380 |
def id(left_padding=None, right_padding=None, offset=None):
"""Constructs an implicit-duration spec dictionary."""
result = {}
if left_padding is not None:
result['left_padding'] = left_padding
if right_padding is not None:
result['right_padding'] = right_padding
if offset is no... | a6b729fa8bdda22ef660854abb0e5ffcb5dec85d | 668,382 |
import math
def phi2mm(phi):
"""Convert a phi value float to mm.
Attributes:
mm <float64>: A float value for conversion"""
return(math.pow(2, -phi)) | d8bc8fa8adf30b137edab1983774e6e46f30c889 | 668,383 |
import re
import shlex
import os
def steal_cmake_flags(args):
"""
Extracts CMake-related arguments from ``args``. ``args`` is a list of
strings usually equal to ``sys.argv``. All arguments of the form
``--cmake-args=...`` are extracted (i.e. removed from ``args``!) and
accumulated. If there are no... | 08db5e2930d7dda39bc237144c5f97f0665fdc9f | 668,384 |
def parse_input(inp_string):
"""function parses user input and change multiple + and - operators to single operator"""
neg_start = False
temp = []
parsed_string = inp_string.replace(' ', '')
parse_list = []
for i, c in enumerate(parsed_string):
# group all common characters
if i ... | 111113654544f76f65ae248ad6ad61fffe218d13 | 668,385 |
import json
def load_images(img_names):
"""loads user images from given file(s)"""
if img_names[0] == '':
return {}
for image_name in img_names:
img = open(image_name)
loaded_imgs = {}
img_list = ''
img_line = ' '
name = img.readline().replace('\n', '')
... | 7504cf4da6ad1ea1298071070c8119415e6eb4c0 | 668,386 |
def isac(c):
"""
A simple function, which determine whether the
string element char c is belong to a decimal number
:param c: a string element type of char
:return: a bool type of determination
"""
try:
int(c)
return True
except:
if c == '.' or c == '-' or c == 'e... | a88d6f22db61c13858edda4efddfa9bbcb7e31c6 | 668,387 |
import math
def rhs(y1, y2):
""" RHS function. Here y1 = u, y2 = u'
This means that our original system is:
y2' = u'' = -0.25*pi**2 (u+1) """
dy1dx = y2
dy2dx = -0.25*math.pi**2 * (y1 + 1.0)
return dy1dx, dy2dx | 8b17eceafcc28918e4c3b7e45be9d43b0a156b84 | 668,388 |
import math
def _ibis_sqlite_exp(arg):
"""Exponentiate `arg`.
Parameters
----------
arg : number
Number to raise to `e`.
Returns
-------
result : Optional[number]
None If the input is None
"""
return math.exp(arg) | dafc6e476406f8354b6b51a94db3e3b850e783ed | 668,389 |
from bs4 import BeautifulSoup
def parse_contents(text):
""" 1.在html文档中查找结果
2.将查找结果写入列表
3.将各个结果压缩为一个列表
Args:
text (String): 被匹配的html字符串
Returns:
List: 最终结果
"""
soup = BeautifulSoup(text, 'lxml')
keyword_list_pro = soup.find_all(class_='td-02')
rank_list_pro... | 6a2b71ecba16c55272cd8020aa7c6a0862bfe742 | 668,390 |
def _ClassifySchemaNode(node_name, api):
"""Attempt to classify |node_name| in an API, determining whether |node_name|
refers to a type, function, event, or property in |api|.
"""
if '.' in node_name:
node_name, rest = node_name.split('.', 1)
else:
rest = None
for key, group in [('types', 'type'),
... | 15cbe1f8f1ffe5eb3c67c82e3ef3ea581aa15b1b | 668,391 |
def get_stats():
"""Statistic about given file: number of lines, number of empty lines,
number of lines with 'z', number of 'z' letter, number of lines with 'and'"""
file = input("File: ")
dict_result = {
'total_lines': 0,
'empty_lines': 0,
'z_lines': 0,
'z_letters': 0,... | 0389d17f7ad7b7b4967144fc2d9cc3dd52dcf874 | 668,392 |
from typing import Optional
def load_current_user(request_context) -> Optional[str]:
"""Load the current user from the request."""
if (authorizer := request_context.get("authorizer")) is not None:
claims = authorizer.get("claims", {})
return claims.get("sub")
return None | 5d2631f21c458711b51a935ecef6f4a827c49dab | 668,393 |
def process_subset(subset, separator="\t"):
"""Processes the given subset.
Extracts the input tokens (words) and labels for each sequence in the subset.
Forms a representation string for each sample in the following format:
SEQ_LEN [SEPARATOR] INPUT_TOKENS [SEPARATOR] LABELS
where:
... | 2058b8094ee4384950838ec4344c95e10ee5c409 | 668,394 |
import time
def get_sn() -> str:
"""
message sn
:return: str
"""
return str(int(round(time.time() * 1000))) | ebfe3afcb598217fb34395d02dc12702c21e8753 | 668,395 |
def is_spotify(raw_song):
""" Check if the input song is a Spotify link. """
status = len(raw_song) == 22 and raw_song.replace(" ", "%20") == raw_song
status = status or raw_song.find('spotify') > -1
return status | 84b85f93e34cc1f9f7e3ca0525bb51aa45e5150b | 668,396 |
def fibonacci(count:int)->list:
"""
This function takes a count an input and generated Fibonacci series element count equal to count
# input:
count : int
# Returns
list
# Funcationality:
Calcualtes the sum of last two list elements and appends it to the list until ... | f34e3ec56e3252991ab707d54bcda8c8cc371cdd | 668,397 |
def parse_row(row, cols, sheet):
"""
parse a row into a dict
:param int row: row index
:param dict cols: dict of header, column index
:param Sheet sheet: sheet to parse data from
:return: dict of values key'ed by their column name
:rtype: dict[str, str]
"""
vals = {}
for header, ... | 580afc8d38f1ea2ce13fa9ccdc5c75e56860a97c | 668,398 |
from typing import Mapping
from typing import Any
from typing import Tuple
def gate_boundaries(gate_map: Mapping[str, Any]) -> Mapping[str, Tuple[float, float]]:
""" Return gate boundaries
Args:
gate_map: Map from gate names to instrument handle
Returns:
Dictionary with gate boundaries
... | 4c9c8e8c3f7a5f2591c73de2f97da74321c02e1f | 668,399 |
def get_name(s, isconj=False):
"""Parse variable names of form 'var_' as 'var' + conjugation."""
if not type(s) is str:
if isconj:
return str(s), False
else:
return str(s)
if isconj:
return s.rstrip("_"), s.endswith("_") # tag names ending in '_' for conj
... | 9648a8b206a107f91784bd2caea1f7b9d312c5e3 | 668,400 |
def hide_string_content(s):
"""
Replace contents of string literals with '____'.
"""
if (not isinstance(s, str)):
return s
if ('"' not in s):
return s
r = ""
start = 0
while ('"' in s[start:]):
# Out of string. Add in as-is.
end = s[start:].index('"')... | 331c80b314a5644190aec6f9031a2df4b5f61f85 | 668,401 |
import os
def getCurrDir():
""" Get the current directory """
return os.path.realpath(os.path.curdir) | 65af0662dc9d823776064649d3d06eddccc2534c | 668,402 |
import os
def get_file_paths_recursive(folder=None, file_ext=None):
""" Get the absolute path of all files in given folder recursively
:param folder:
:param file_ext:
:return:
"""
file_list = []
if folder is None:
return file_list
file_list = [os.path.join(folder, f) for f in s... | 60d6811560e1bf8e6fd4d52b58163cc59f0b24b5 | 668,404 |
from pathlib import Path
def get_files_by_pattern(directory: str, glob_pattern: str) -> list[Path]:
"""Return list of files matching pattern"""
path = Path(directory)
return [file for file in path.glob(glob_pattern) if file.is_file()] | be1ce3e9e92cf5694e8ac1ee1c8fde9e7fada835 | 668,405 |
def fake_bin(x):
"""Convert a string of numbers to a string of binary."""
l = list(x)
new_l = []
for digit in l:
if int(digit) <5:
new_l.append("0")
else:
new_l.append("1")
return "".join(new_l) | 4718db9087276e74e5cdbe7a87b7a9b9c565c230 | 668,406 |
def calc_num_beats(rpeak_locs, metrics):
"""Calculates the number of beats in an ECG
This function takes an array of the ECG R-peaks. The number of R-peaks
is equivalent to the number of beats in the ECG.
Args:
rpeak_locs (1D numpy array): index locations of R-peaks in an ECG.
metrics ... | 41399a0629aa8b527b46c5eeb3dd76d696ad304f | 668,407 |
def _get_revision(config):
"""
Extracts branch and revision number from the given config parameter.
@return: (branch, revision number)
"""
if config.revision:
tokens = config.revision.split(":")
svn_branch = tokens[0]
if len(tokens) > 1:
revision = config.revision... | f6ca9df0c80727fa449e6aafdf1132113a7e9c43 | 668,408 |
def get_header(token):
""" Return a header with authorization info, given the token. """
return {
'Authorization': 'token %s' % token,
'Content-Type': 'application/json; charset=UTF-8'
} | 1b693a758eb33343d390f8f5b0dee49a195bbce4 | 668,409 |
def determine_color(memory_limit_gb, memory_usage_gb, dark_background=False):
"""Determine a display color based on percent memory usage
Parameters
----------
memory_limit_gb : int
Overall memory limit in gigabytes
memory_usage_gb : int
Memory usage value in gigabytes
dark_b... | 066b8aad7e413a391e6e8c50eae12863e09f7a7b | 668,410 |
def rename_project(oProject, filename, overwrite=True):
"""
Renames the specified project.
Parameters
----------
oProject : pywin32 COMObject
The HFSS project object upon which to operate.
filename : str
The name of the file to save, requiring the full path.
Works well w... | 41af3b3d62d42f7c1d4f7633d33e8aeb23b2747a | 668,412 |
from typing import List
def count_user_type(user_type_list:List[str]) -> List[int]:
""" Calcula a quantidade de Clientes e Assinantes.
Por meio de uma lista calcula a quantidade de clientes "Customer" e assinantes "Subscriber".
:param data_list: Lista contendo os tipos de usuário.
:returns: Lista de ... | 1b1007da0e0d75bc5cf795359bc5199c6215c078 | 668,413 |
def merge_dataframe(clinvarome_df, list_df):
"""
Add all ClinVarome additional informations into
the original ClinVarome available in Variant Alert!
"""
for df in range(len(list_df)):
clinvarome_df = clinvarome_df.merge(list_df[df], on="gene_info", how="outer")
clinvarome_df.dropna(s... | 81debc6952cce20e84fe947a9df9981c2312de60 | 668,415 |
def floatformat(number, mind=2, maxd=4):
""" Format a floating point number into a string """
rounded = int(number * (10**mind)) / float(10**mind)
if number == rounded:
return ('%%.0%df' % mind) % number
else:
return ('%%.0%dg' % maxd) % number | 452539e7591a76632c1be4a9f33a7e5c7acfd1da | 668,416 |
def normalize_img_array(img, dtype='float32'):
""" rescale to [-1.0, 1.0] """
img = img.astype(dtype)
# return (img - np.mean(img, dtype=dtype)) / 255.0
return img / 255.0
# return (img - np.median(img)) / (np.std(img, dtype=dtype) + 1e-6) # 转完以后有些情况会变得不可识别 | 27177600e81fbf8a3919482ba2bf66925e6f9835 | 668,417 |
def datetime_to_float(datetime):
"""
SOPC_DateTime* (the number of 100 nanosecond intervals since January 1, 1601)
to Python time (the floating point number of seconds since 01/01/1970, see help(time)).
"""
nsec = datetime[0]
# (datetime.date(1970,1,1) - datetime.date(1601,1,1)).total_seconds() ... | 6698c6cc02c8c34394bcf960d540f417e6422def | 668,418 |
def regularize_reliability(rel_1, rel_2):
"""
Regularizes the reliability estimates for a pair of graders.
Parameters
----------
rel_1 : float.
Estimated reliability of grader 1.
rel_2 : float.
Estimated reliability of grader 2.
Returns
-------
t_1 : float... | b62fb831c3ccbd9bb232d75b4b9ee0b802f89f14 | 668,419 |
def format_ctor_arguments(arguments, parent, id, size):
"""Format constructor arguments; returns a list
arguments: Constructor arguments (list)
parent: Parent widget (string or unicode)
id: Widget ID e.g. wxID_ANY
size: Widget size 'width, height'"""
vSize = size.split(',')
for i in range(l... | 3096ac4baba01dd263f517775697cc1d802cce37 | 668,420 |
from typing import List
from typing import Tuple
import glob
import os
def ordered_crawl(crawldir: str) -> List[Tuple[str, int]]:
"""
Returns the contents of the given crawl directory ordered by their start id (in ascending order)
Args:
crawldir
Directory containing the results of an allrepos... | 4a2d96ca325bf7083ea27e97534194668db4f04b | 668,422 |
def get_required_packages():
"""
Return required packages
Plus any version tests and warnings
"""
install_requires = ['numpy',
'scipy >= 1.5.0',
'pandas >= 1.1.0',
'matplotlib >= 3.1.1',
'palettable']
... | e5baac6e0ed9b0542e290b71a251b202403d88a4 | 668,423 |
def humanReadableSize(size):
""" Get a human-readable file size string from bytes.
:Parameters:
size : `int`
File size, in bytes
:Returns:
Human-readable file size
:Rtype:
`str`
"""
for unit in ["bytes", "kB", "MB", "GB"]:
if abs(size) < 1024:
... | a7b9f5c050d8fa8815b3685294dae0f3e8670122 | 668,424 |
def cs_rad(altitude, ext_rad):
"""
Estimate clear sky radiation from altitude and extraterrestrial radiation.
Based on equation 37 in Allen et al (1998) which is recommended when
calibrated Angstrom values are not available.
:param altitude: Elevation above sea level [m]
:param ext_rad: Extrat... | fbe5cf144b3ecf0b34e55522ca87dd49bf74dd5e | 668,425 |
from typing import List
import pathlib
def get_core_lists() -> List[pathlib.Path]:
"""Return a list of paths for all rutrivia lists packaged with the bot."""
core_lists_path = pathlib.Path(__file__).parent.resolve() / "data/lists"
return list(core_lists_path.glob("*.yaml")) | 5466290d98bc42e8198ad49686224f4f36bbd650 | 668,427 |
def test5(a, b):
"""测试装饰器"""
print("...")
return a + b | 98ff52ff787d6bec6c16b03b6ba3888d5b512be5 | 668,428 |
def get_or_else(json, name, default):
"""辞書からnameの値を取得する。nameがない、もしくはNoneの場合はdefaultを返す。"""
value = json.get(name, default)
if value is not None:
return value
else:
return default | 241c0eb6b90f3963aa41e8927dc50562f11f9101 | 668,429 |
def is_string_type(thetype):
"""Returns true if the type is one of: STRING, TIMESTAMP, DATE, or
TIME."""
return thetype in [
'STRING', 'TIMESTAMP', 'DATE', 'TIME', 'QINTEGER', 'QFLOAT', 'QBOOLEAN'
] | b6f010d0b12bf5452635be81d11b89fde074af39 | 668,430 |
def get_frame_shift(op):
"""
:param op:
:return:
"""
if op[1] == "I":
return len(op[2])
elif op[1] == "S":
return 0
elif op[1] == "D":
return -op[2] | 5b1ad71d098bf99d8444447bf8ecdbc2a8835f66 | 668,431 |
import logging
import os
def ensure_dir(f):
"""Ensure filepath is an existing directory.
INPUT:
f: Filepath
OUTPUT:
(0/1): 1 if directory created, 0 if already exists
"""
logging.info("Ensuring directory for {0} exists".format(f))
d = os.path.dirname(f)
if not os.path.exi... | 0db50eff0a52bf9a4f3d7f03adb6565a822143dc | 668,432 |
import hashlib
def convert_data_set(data_set, data_set_writer, transformation=None,
count_dist=False, prime_wise=False, remove_duplicities=False):
"""
Convert data set to a different format.
If transformation is provided, compute features and add them to the key
key that gets sav... | d3e4fd627f8ce2328fafa63021291ab260a16efe | 668,433 |
def get_picam(c):
""" Return a dict of the attributes in a PiCamera"""
d = {}
if type(c).__name__ == "PiCamera":
all_settings = ['analog_gain', 'awb_mode', 'awb_gains', 'contrast', 'drc_strength', 'digital_gain',
'exposure_mode', 'exposure_speed', 'framerate', 'hflip', 'iso',... | f24b87e81fe094dc0df874585ef890d76453a7f7 | 668,434 |
def _rot(x, shift_amount, length):
"""Rotate x shift_amount bits to the left, considering the \
string of bits is length bits long"""
shift_amount = shift_amount % length
return ((x >> (length - shift_amount)) + (x << shift_amount)) % (1 << length) | df10ea5fca3fb535061cd81aac2b95ee863b8632 | 668,435 |
import os
def where():
"""Return path to the frontend."""
return os.path.dirname(__file__) | 9f6df7d66bbce4dcaf04747a3fea0e03ff8fe66f | 668,436 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.