content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from datetime import datetime
def check_file_time(ftime):
"""This function adds a date and time to the 'Last Modified' section of any
identified files from scan_dir_and_files()."""
dtime = datetime.utcfromtimestamp(ftime)
return dtime.strftime("%d %b %Y") | 36cca069b405c1efbf6a13018104981056cc1d0b | 663,191 |
def pad_to_two_digits(n):
"""
Add leading zeros to format a number as at least two digits
:param n: any number
:return: The number as a string with at least two digits
"""
return str(n).zfill(2) | a26d53563e4dc439750bb729d31f7dd8d775e3fd | 663,192 |
def monitor_decorator(fct):
"""Redirect to self.monitor decorator"""
def wrapper(self, *args, **kwargs):
self.monitor.monitorable(fct)(self, *args, **kwargs)
return wrapper | b0d2c1c3cd2d0dbd8de899c4621975ceeb3bd158 | 663,194 |
def generate_input_parameters():
"""Get an input parameters for ``SkeafCalculation``."""
def _generate_input_parameters(full: bool = False) -> dict:
"""Generate inputs.
:param full: return a full parameters or a minimal set, defaults to False
:type full: bool, optional
:return:... | bbd979b4e0af2b7d869f198027c4a8b1f8075863 | 663,196 |
def max_length(choices):
"""
Returns the size of the longest choice.
:param: the available choice strings or tuples
:return: the maximum length
"""
def length(item):
if isinstance(item, str):
value = item
else:
value = item[0]
return len(value... | 90041dc55373bf8bb6ab701e119bc139adb4cc6f | 663,197 |
def process_image_pipeline(tup):
""" Worker function for NumpyArrayIterator multiprocessing.Pool
"""
(pipeline, x, rng) = tup
x = x.astype('float32')
for (func, kwargs) in pipeline:
x = func(x, rng=rng, **kwargs)
return x | 901ac22629a2b156d04e1899a1f0e711a04bf9ea | 663,198 |
def _SplitLabels(labels):
"""Parse the 'labels' key from a PerfKitBenchmarker record.
Labels are recorded in '|key:value|,|key:value|' form.
This function transforms them to a dict.
Args:
labels: string. labels to parse.
Returns:
dict. Parsed 'labels'.
"""
result = {}
for item in labels.strip... | 494f038813ae73f8700e89b5d5f93c69747de0f9 | 663,199 |
import re
def small_titles(markdown):
"""Make titles smaller, eg replace '# ' with '### ' at the start of a line."""
markdown = re.sub(r'\n# |^# ', '\n### ', markdown)
markdown = re.sub(r'\n## |^##', '\n#### ', markdown)
return markdown | ffb4fbe96f2ac23f2e02a59c55acfdd24d9abe0c | 663,201 |
from subprocess import run
def execute(command):
"""Function to execute command line commands
Args:
command (object): Command
Returns:
:obj:`str`: Returning Output of Command
"""
if isinstance(command, list):
retval = ""
for cmd in command:
retval += s... | bf35556aedd62cded6d609ebf16da70bdce8fc05 | 663,202 |
import os
def _get_ngraph_shared_lib_paths(mxnet_lib_dir):
"""
Find any shared-object files that are supplied by '3rdparty/ngraph' *and* must be provided by
the same Python package as 'libmxnet.so'.
If even one of the expected libraries is present, assume that MXnet was build with nGraph
support.... | 14768047018146cfd1ffb5a32c4b6859810cf410 | 663,203 |
def vector_subtract(u, v):
"""returns the difference (vector) of vectors u and v"""
return (u[0]-v[0], u[1]-v[1], u[2]-v[2]) | 034c07a1e459725744112b51933c2c0c73c60f68 | 663,204 |
def _uniq(lst):
""" Return the unique elements from a list.
Retrieved from https://www.peterbe.com/plog/uniqifiers-benchmark """
seen = set()
seen_add = seen.add
return [i for i in lst if not (i in seen or seen_add(i))] | 801328717979ceb643f4922769a8d3f1f301ee90 | 663,205 |
def get_single_message(sqs_queue, wait_time_seconds=5):
"""Get a maximum of one message from the provided sqs queue."""
messages = sqs_queue.receive_messages(
MaxNumberOfMessages=1, WaitTimeSeconds=wait_time_seconds)
if messages:
return messages[0]
else:
return None | 5ab2043bdae4ecbb8e1026faaff4bbf0032f8121 | 663,206 |
import torch
def _convert_multi_feature_to_tensor(features):
"""
features: [(f1, f2, f3), ...]
"""
all_idx = torch.tensor([[f.idx for f in fs] for fs in features], dtype=torch.long)
all_input_ids = torch.tensor([[f.input_ids for f in fs] for fs in features], dtype=torch.long)
all_input_mask = ... | ac63ca84330f741d02f8c2125701fccbe6f6f659 | 663,207 |
def resource_filter(value, resource, field='displayName'):
""" Given a mapping (resource), gets the data at resource[field] and
checks for equality for the argument value. When field is 'name', it is
expected to look like 'organization/1234567890', and returns only the
number after the slash.
... | 932cb961af6c6969404d694450e5efee1576a59a | 663,208 |
def timeify(time):
"""Format a time in seconds to a minutes/seconds timestamp."""
time = float(time)
mins, secs = time // 60, time % 60
return f"{mins:.0f}:{secs:05.2f}" | 42757883048ce930c5cbc40da8da161daeb8324a | 663,209 |
def Zzz(gctor, *args, **kwargs):
"""Create an inverse-η-delay for a goal."""
def Zzz_goal(S):
yield from gctor(*args, **kwargs)(S)
return Zzz_goal | 9eb7b95ef0fe1401b232e343dc578743d5082978 | 663,210 |
def floor(x) -> int:
"""
Return the floor of x as an Integral.
:param x: the number
:return: the largest integer <= x.
>>> import math
>>> all(floor(n) == math.floor(n) for n
... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000))
True
"""
return int(x) if x - int(x) >= 0... | 6d61da93660c8e71876f71c89bf1441a532effcd | 663,211 |
def _verify_limits(limits):
"""
Helper function to verify that the row/column limits are sensible.
Parameters
----------
limits : None|tuple|list
Returns
-------
None|tuple
"""
if limits is None:
return limits
temp_limits = [int(entry) for entry in limits]
if ... | f0c846443cc1686da29ea6793744502ea0b1017d | 663,212 |
import os
def removeOffset(filename, offsetCount, offsetSide, rank, id):
"""Deze functie maakt de wins en losses in een database gelijk"""
if not os.path.isfile('./' + filename + '-CLEANv1.csv'):
with open(filename + '-NoDupes.csv','r') as inFile, open(filename + '-CLEANv1.csv','w') as outFile:
... | b277bf156a55432cefa8232ab5a5d88751bfbee4 | 663,213 |
def timestamp_format_to_redex(time_format):
"""
convert time stamp format to redex
Parameters
----------
time_format : str
datetime timestamp format
Returns
-------
redex : str
redex format for timestamp
"""
time_keys = {'%Y': r'\d{4}',
'%m': r... | b5e0f182681c74c51871b7d5cba1e720a468168a | 663,214 |
def convert_string(token_list):
"""
returns concatenate token to have a string (sentence)
Input=list of token Output=sentence
"""
#list is empty
if not token_list:
return ''
if len(token_list) == 1:
return token_list[0]
el... | 83d015d63a488f48dab067667945ecbadeaec2f7 | 663,215 |
import itertools
def held_karp(dists):
"""
Implementation of Held-Karp, an algorithm that solves the Traveling
Salesman Problem using dynamic programming with memoization.
Parameters:
dists: distance matrix
Returns:
A tuple, (cost, path).
"""
n = len(dists)
# Maps ea... | c620d701c6163c89cb07349203062a9dc13e614a | 663,216 |
def scale_lr_imgs(imgs):
"""Scale low-res images prior to passing to SRGAN"""
return imgs / 255. | 7c566336779e6e8a500329c77926e5388ac0b451 | 663,217 |
import argparse
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('--nout', dest='nout',
help='directory to load models', default=100)
parser.add_argument('--sess', dest='sess',
... | 49ced7b1de43d41092a9cf9a81b71d9398f2b417 | 663,218 |
import re
def parse_format(string):
"""
Parses an AMBER style format string.
Example:
>>> string = "%FORMAT(10I8)"
>>> _parse_format(string)
[10, int, 8]
"""
if "FORMAT" not in string:
raise ValueError("AMBER: Did not understand format line '%s'." % string)
pstring = str... | a494f4f2ed3708d20579092108ab840a748490e8 | 663,219 |
def bb_area(bbox):
"""
returns area: bbox in format xs, ys, xe, ye
if bbox is empty returns 0
"""
if bbox.size == 0:
area = 0
else:
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
area = width*height
return area | 0680e24f4a80b34fcae66956964cbe86e7f2957f | 663,220 |
def F1(p, r):
""" Calculate F1 score from precision and recall.
Returns zero if one of p, r is zero.
"""
return (2*p*r/(p+r)) if p != 0 and r != 0 else 0 | 5f7f6fee3bdf94e9942b317114b31fb25c8ecd08 | 663,221 |
import torch
def rot_z(gamma):
"""
Rotation around Z axis
"""
if not torch.is_tensor(gamma):
gamma = torch.tensor(gamma, dtype=torch.get_default_dtype())
return gamma.new_tensor([
[gamma.cos(), -gamma.sin(), 0],
[gamma.sin(), gamma.cos(), 0],
[0, 0, 1]
]) | ce2a05f27484ff7fe6cb7d0cfbc777f4eaf2b442 | 663,222 |
def get_package(package_info: dict) -> str:
"""Construct the package name and exact version to install."""
package_tag = f"{package_info['name']}=={package_info['version']}"
# The package is a local file
source = package_info.setdefault("source", {})
if source.get("type") == "file":
# Trim ... | d2481d3404c3f05cbb78f4db4ee8b8210515edb6 | 663,225 |
import os
import csv
def _collect_data(directory):
"""Traverses directory collecting input and target files.
Args:
directory: base path to extracted audio and transcripts.
Returns:
list of (media_base, media_filepath, label) tuples
"""
# Returns:
data_files = []
transcripts = [
filename for... | 9137e87d732a8cc9ebd13234e4d1c3d39b2806db | 663,226 |
from typing import List
from typing import Dict
def describe_topics(mlModel) -> List[Dict[str, float]]:
"""Obtain topic words and weights from the LDA model.
Returns: topics -> List[Dict[str, float]]
A list of mappings between the top 15 topic words (str) and their weights
(float) for each to... | b9836c9526f025b823a166f23d77ee073569f62e | 663,229 |
def find_shape_points(image, piece_loc, sx, sy, scale, logger):
"""Find a shape's top-center and right-most points ((x, y), (x, y))."""
start_point = [0, sy]
# Find start point
h, w = image.shape[:2]
for x in range(sx, w):
if image[sy, x]:
start_point[0] = x
else:
... | dec8c490fabe16f5c9f02e1c201e000b8e1a80e9 | 663,230 |
def _get_with_item_indices(exs):
"""Returns a list of indices in case of re-running with-items.
:param exs: List of executions.
:return: a list of numbers.
"""
return sorted(set([ex.runtime_context['with_items_index'] for ex in exs])) | c6a93a4fb43f19751163c7b01f690ef845f312de | 663,231 |
import re
def remove_non_characters(tweet):
"""
Removes non-characters from a tweet.
INPUT:
tweet: original tweet as a string
OUTPUT:
tweet with non-characters removed
"""
tweet = re.sub("[\"\'\.\,\:\;\@\_\-\+\*\\\/\%\_\(\)\[\]\{\}\&\!\?\~\=\^]", '', tweet)
return ' '.join(... | c2b1314b37443fe979347b7edbb849bee51f3af1 | 663,232 |
def get_padding_len(len_input: int) -> int:
"""
パディングの長さ(バイト数)を返す
「インプット+パディング」の長さが「64の倍数 - 8」になるように計算する
"""
return 64 - (len_input + 8) % 64 | 9fd3afeeceee1b3e382a1a7592cd707dc4dcb062 | 663,233 |
def percent(v):
"""
Transform probability into percentage.
"""
return v * 100 | 5b57f52d1eece08783d3fb829693a11f36e863b0 | 663,234 |
def is_in_region(bbox1, bbox2, tol=5):
"""
:param bbox1:
:param bbox2:
:param tol:
:return:
"""
return bbox1[0]+tol >= bbox2[0] and \
bbox1[1]-tol <= bbox2[1] and \
bbox1[2]+tol >= bbox2[2] and \
bbox1[3]-tol <= bbox2[3] | 595bd4d039e6b8fc9e38f79540b7bf8e5f711a43 | 663,235 |
import os
def file_is_empty(file_path):
""" Check if file is empty by confirming if its size is 0 bytes"""
# Check if file exist and it is empty
return os.path.exists(file_path) and os.stat(file_path).st_size == 0 | 45e687eb4b709c84ca114de1ba4bd9d01b0fc770 | 663,236 |
def is_available():
"""Returns a boolean to indicate the availability of a CUDA GPU.
"""
# Simulator is always available
return True | 31346d32739e606c59374823eb2f5cf0103b5cc4 | 663,237 |
import json
from typing import Counter
def results_from_json(json_path):
"""Return a results dictionary based on a PyLint JSON output file."""
# Read and parse JSON file.
try:
with open(str(json_path), encoding="utf-8") as inp:
data = json.load(inp)
except OSError as ex:
r... | ce727e87dd9005c977be9ec7733c5140e384e2ee | 663,239 |
import os
def expected_msg(change_dir_main_fixtures):
"""Fixture. Used to ensure that exception generated text contain full data."""
msg = (
'Missing end of comment tag\n'
' File "./files/syntax_error.txt", line 1\n'
' I eat {{ syntax_error }} {# this comment is not closed}'
)
... | 3a5e415584b11b394cc9d19e99dbda5b65ec6607 | 663,240 |
def _train_and_evaluate(
estimator,
X_train,
y_train,
X_test,
y_test,
target_transform,
target_inverse_transform,
collect_metrics,
collect_metrics_kwargs,
use_predict_proba):
""" Train and evaluate `estimator` on the given datasets
... | 1c2cb345c45d5d98c6236f82c6d950c03e7102a0 | 663,242 |
import subprocess
def etckeeper_unclean():
"""
Return True if etckeeper repository is in unclean state (there are
uncommited changes in /etc directory).
"""
retcode = subprocess.call(['etckeeper', 'unclean'])
return retcode == 0 | e2880bd2e6ec1111cab39415f1c1af2e130679b4 | 663,243 |
import re
def is_custom(text, regex):
"""
Checks if the given text matches with a given regex
Args:
text (str): The text to match
regex (str): A regular expression that you wanna match (recomended a raw string: r'')
Returns:
A boolean value, True if the text matches the string... | 5cecf21751864b3d97ecdc5bd8b561d9b385f3ee | 663,244 |
import torch
def get_grads(kernel_grad, kernel, w_p, args):
"""
Arguments:
kernel_grad: gradient with respect to quantized kernel.
kernel: corresponding full precision kernel.
w_p: quantization factor.
args: arguments
Returns:
1. gradient for the full precision ker... | a7a13ba77864dc56fd47fe499b4ea64ca810d75e | 663,245 |
def buf_emu(not_buffer):
"""Buffer emulator"""
if hasattr(not_buffer, 'tostring'):
return not_buffer.tostring()
else:
try:
return bytes(not_buffer)
except NameError:
return str(not_buffer) | f99dbecda084233754775a6be11e18aa29869245 | 663,246 |
def recursion_fac(n, result=1):
"""
递归阶乘
:param n:
:param result:
:return:
"""
if n > 0:
result *= n
return recursion_fac(n-1, result)
return result | 904c9c60d41d10358102e771c6288cba19cd7044 | 663,247 |
import random
import string
def generate_random_prefix():
"""
Generate a random prefix that is 16 characters long.
Example: 4htvo26lchkqeho1
"""
return "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16)) | 3740378b35ec48a718d1c6e24279b31f12e5e0df | 663,249 |
import re
def split_auth_header(header):
"""Split comma-separate key=value fields from a WWW-Authenticate header"""
fields = {}
remaining = header.strip()
while remaining:
matches = re.match(r'^([0-9a-zA-Z]+)="([^"]+)"(?:,\s*(.+))?$', remaining)
if not matches:
# Without qu... | 2a893b5b7f9f197b0a179bc63e741f34ba08d74b | 663,250 |
import glob
def find_preflight(path):
"""
Find preflight
"""
# Return values
preflight = None
# Glob the package directory to find preflight
pkgs_str = path + '/pmpreflight'
pkgs = glob.glob(pkgs_str)
# Found it
if pkgs:
preflight = {
'name': 'pmprefl... | 6048c2b96ed111623ec76bdaffb17c2c4473f616 | 663,253 |
from numpy import cos, pi, arange
def makeCosine(time, amplitude, frequency, phase=0):
"""
This function is for creating cosine wave of varying time, amplitude, freq,
and phase for simulating input signals
:param int time: time in seconds for cosine curve
:param int amplitude: amplitude of cosine... | 3b53b0b17bd2503bdde3e93cdb0bcf4cf50fbb11 | 663,254 |
import calendar
def get_month_button(month, text=None):
"""
Get the button corresponding to the given month.
If no `text` is given, the name of the month in English will be used.
"""
if month < 1:
month += 12
elif month > 12:
month -= 12
return {
'text': text or c... | 5724e3b74262709d5f3a45faa3e7ffcbf7e19c96 | 663,256 |
def single_or_double_residence(name, residence):
"""Function that receives as input the name of the subject as well as its residence to determine which paragraph of Article 4 OECD MTC (2017) applies."""
double_residence = False
single_residence = False
if " and " in residence:
double_residence... | 24609fea0897b648ee64253fe26b612adf65521a | 663,257 |
import math
def calc_event_price(retail_price, discount_percent, sales_tax_percent):
"""Calculate the event price from the retail price."""
# Apply discount.
price = float(retail_price) * (1.0 - float(discount_percent) / 100.0)
# Impose sales tax.
price = price * (1.0 + float(sales_tax_percent) ... | 190df064314eab07488e67110461286f9feeecde | 663,258 |
import requests
def _request(url: str, token: str) -> requests.Response:
"""
Creates a request for the IUCN API and handles HTTP exceptions.
Parameters
----------
url : str
IUCN API endpoint.
token : str
IUCN API authentication token.
Returns
-------
Response
... | f1c661551693f6eb90a494e56ecc103725f6bdd1 | 663,260 |
def shape_dark_cloud_cover_top(code, df_code):
"""
乌云盖顶形态(顶部反转) | 透刺形态(底部反转)
:param code:
:param df_code:
:return:
"""
dates_up = [] #看涨
dates_down = [] #看跌
for ix, row in df_code.iterrows():
if ix - 5 < 0:
continue
#判断趋势
pct_changes = df_code... | ef669d3b5b2f2bf25514dc0a703c84c13ea319d7 | 663,261 |
import platform
def guess_word_size():
"""
Returns the size of the pointer. For 64-bit systems, this will return '64',
and '32' for 32-bit systems.
"""
if '64' in platform.machine():
return '64'
else:
archs = platform.architecture()
for a in archs:
if '64' i... | 5a69a71cffed75e0447b920f44bf6e2075630ae5 | 663,264 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(
description='we pre-generate model parameters without BN')
parser.add_argument(
'--model_name', help='name the pre-generate model name', type=str)
return parser.parse_args() | 45e5fbad75eba2328cb797624cbbf721569f1135 | 663,265 |
def parse_topology_str(s) -> list:
"""Parses node-topology string and returns list of dicts"""
topology = []
if s:
for a in s.split(','):
(ip_port, valency) = a.split('/')
(ip, port) = ip_port.split(':')
#if resolve_hostname: ip = resolve_hostname(ip)
... | 58fb7e9dcc5618b5b4c5d30a212110b86aba3c25 | 663,266 |
import os
def token():
"""Optional access token, if none provided GoogleFHIRAuth will perform `gcloud auth print-access-token` is used."""
return os.environ.get('TOKEN', None) | 262c40d81f999362d0e30d83ac6432d660bd481a | 663,267 |
def folded_str_representer(dumper, text):
"""Warp function of the representer."""
return dumper.represent_scalar(u'tag', text, style='>') | 73cde9bc4e56cca86ea63dbad57720d009e017f4 | 663,269 |
def numestate_incolour(colour:str) -> int:
"""Return the number of fields in given colour."""
if colour in {'brown','blue'}:
return 2
return 3 | 7312dc87eaca38cde465a1d17573a505a9196b53 | 663,270 |
def strike_through(text: str) -> str:
"""Returns a strike-through version of the input text"""
result = ''
for c in text:
result = result + c + '\u0336'
return result | a178dd99d124f537bc98bcf36cdc0690862fb0bd | 663,271 |
def frohner_cor(sig1,sig2,n1,n2):
"""
Takes cross-sections [barns] and atom densities [atoms/barn] for
two thicknesses of the same sample, and returns extrapolated cross
section according to Frohner.
Parameters
----------
sig1 : array_like
Cross section of the thinner of the two sa... | 1024c83df879edaf872d80b67ef28e64b372e81b | 663,272 |
import torch
def tricky_line(x, noisy=True):
""" Toy function in: https://arxiv.org/pdf/1806.03335.pdf, Fig. 13
"""
y = torch.zeros_like(x)
y[-1] = 5
return y | d154c44bfd2e048efa09ccd311729f4be9fec66c | 663,273 |
import numpy
def makeCenteredRotation(angle, center=(0, 0)):
"""
Creates a 3x3 transform matrix for centered rotation.
:param: angle, in degrees
:param: center, a list [xcentre, ycentre]
"""
# center
Cf = numpy.array([[1, 0, -center[0]],
[0, 1, -center[1]],
... | 30ed789bc3b18910d0d067ad9cffc1316ec3deda | 663,274 |
def unblockshaped(arr, h, w):
"""
Return an array of shape (h, w) where
h * w = arr.size
If arr is of shape (n, nrows, ncols), n sublocks of shape (nrows, ncols),
then the returned array preserves the "physical" layout of the sublocks.
"""
n, nrows, ncols = arr.shape
return (arr.reshape... | 256471bec79767bfa85bd3f59401eb1e3614a34b | 663,275 |
def filename_ext(filename):
""" Function that returns filename extension """
# Taken from http://flask.pocoo.org/docs/1.0/patterns/fileuploads/
return '.' in filename and filename.rsplit('.', 1)[1].lower() | 27776ac640ca823bf7bca3f45bae85a54a7cfb68 | 663,277 |
import torch
def load_saved_model(model : torch.nn.Module, path : str) -> torch.nn.Module:
"""
Loads a pre-saved neural net model.
Args:
----
model (torch.nn.Module) : Existing but bare-bones model variable.
path (str) : Path to the saved model.
Returns:
-------
... | b241943c4426cd862d402f12f59885b73bb4d1e3 | 663,278 |
def item_based_predict(movie_data, u, m1, nn_list):
"""Returns a prediction from parameters for a movie.
Parameters
----------
movie_data : dict
Dictionary of the data set.
u : str
Id of user to be used for prediction.
m1 : str
Id of mov... | e899e469f9fa1cec11cdebd406e02795a991e7dd | 663,280 |
import re
def camel_case_to_name(text):
"""
>>> camel_case_to_name('FooBar')
'foo_bar'
>>> camel_case_to_name('TXTFile')
'txt_file'
>>> camel_case_to_name ('MyTXTFile')
'my_txt_file'
>>> camel_case_to_name('froBOZ')
'fro_boz'
>>> camel_case_to_name('f')
... | 697e8061c593dc6da7212d5f0c8faa688b939450 | 663,281 |
def guid_section(sec_type, guid, guid_attrib, inputfile):
""" generates the GUID defined section """
cmd = ["tmp.guid", "-s", "EFI_SECTION_GUID_DEFINED", "-g"]
cmd += [guid, "-r", guid_attrib, inputfile]
return cmd | d8b2bf8f56fa8364e38b574d45ccdf8bae0a8e2d | 663,283 |
import yaml
def yaml_data_import(nom_fichier):
"""Fonction pour importer et lire les fichier yaml
Args:
nom_fichier (string): nom du fichier à importer
Returns:
dict: dictionnaire des donnée chargés
"""
with open(nom_fichier) as f:
data = yaml.load(f, Loader=yaml.FullLoad... | 583cb84577748d3e0bdcdb213a7b675fc86922b1 | 663,284 |
import numpy
def construct_propagator_matrix(system, BT2, config, conjt=False):
"""Construct the full projector from a configuration of auxiliary fields.
For use with discrete transformation.
Parameters
----------
system : class
System class.
BT2 : :class:`numpy.ndarray`
One ... | 9bc9342276a62e8879182ed259763bb573bfef53 | 663,285 |
import pathlib
import os
import sqlite3
def connect_db():
""" Return db connection """
homedir = str(pathlib.Path.home())
dbfilename = "nbdata.db"
dbpath = os.path.join(homedir, dbfilename)
con = sqlite3.connect(dbpath)
con.row_factory = sqlite3.Row
return con | 245d0ce3aba7343ef0b185986a948223d6e0b9d4 | 663,286 |
import torch
def rotate_real(x):
""" Rotates the magnitude of a complex signal into the real channel. """
assert x.ndim >= 3 and (x.shape[-3] == 2)
x_rv = torch.zeros_like(x)
x_rv[..., 0, :, :] = torch.sqrt(x.pow(2).sum(-3))
return x_rv | c89cb2fba436f5ea1268416ee6084ea84ab5549e | 663,287 |
def _mu(df, formula, temp, cas, full):
"""
Helper for the `mu_gas` function to determine gas viscosity.
Parameters
----------
df : dataframe
Dataframe from inorganic or organic data
formula : str
Molecular formula for the gas
temp : float
Gas temperature
cas : st... | 25dda382184769876c1a51cba98d55357251d66a | 663,288 |
import click
def validate_section(ctx, param, value):
"""
Validate that a given section exists.
"""
config = ctx.obj.config
if value and config.has_section(value):
raise click.BadParameter(
'Missing or unknown section: {}'.format(value))
return value | 7df6bcf5e978e9a0392edc68c86ffbb1ef47c07e | 663,289 |
def extract_local_dets(data):
"""Extracts the local detectors from the TOD objects
Some detectors could only appear in some observations, so we need
to loop through all observations and accumulate all detectors in
a set
"""
local_dets = set()
for obs in data.obs:
tod = obs["tod"]
... | 47cccfc99a4f0d5f56c248a1affae07fb8d9a6f0 | 663,290 |
def all_close(max_side, area_origins, limit):
"""Return region size where distance sum of point from origins < limit."""
close_region_size = 0
for row in range(max_side+1):
for col in range(max_side+1):
distance = limit
for origin in area_origins:
distance -= ... | 0211f23c62f18dfe40b5b6650f62a45c799f6122 | 663,291 |
import os
def get_field_mapping_filename(field_name: str, config_location: str) -> str:
"""Returns the expected filename for a field mapping."""
return os.path.join(config_location, field_name + ".csv") | c6609b2dcef6071602635f9cfc6a9bf53a493901 | 663,292 |
import random
def randomize_capitalization(data):
"""
Randomize the capitalization of a string.
"""
return "".join(random.choice([k.upper(), k]) for k in data) | 09b3c79507c2335269fad8fc0e29d7ec0f89698c | 663,293 |
def nvmf_subsystem_get_controllers(client, nqn, tgt_name=None):
"""Get list of controllers of an NVMe-oF subsystem.
Args:
nqn: Subsystem NQN.
tgt_name: name of the parent NVMe-oF target (optional).
Returns:
List of controller objects of an NVMe-oF subsystem.
"""
params = {'... | 05f5ffd3cfe5db849e5348af1a18725b7b5f5ca8 | 663,294 |
def login():
"""
管理后台用户登录
:return:
"""
return {"msg": "login success"} | 7bff037656e18c017498a0aa5120e336d3f6af97 | 663,295 |
def escape_variables(environ):
"""
Escape environment variables so that they can be interpreted correctly by python configparser.
"""
return {key: environ[key].replace('%', '%%') for key in environ} | 450809d829df34b26c6ab3eb0000841a8db5600f | 663,296 |
import re
import base64
import json
def decode_token(jwt):
"""Decode the JWT and load it's respective parts as JSON.
Args:
jwt (str): The JSON Web Token to parse/decode.
"""
token_body = jwt.split(".")[1]
decodable_token_body = re.sub(r"\-", "+", token_body)
decodable_token_body = re... | ded3c230033ca92986b7f620cccf9d099c411174 | 663,298 |
def subscription_name(project, name):
"""Get subscription name."""
return 'projects/{project}/subscriptions/{name}'.format(
project=project, name=name) | 80a445c1153d69c879bb2d26f541de14e3f3060a | 663,299 |
from typing import List
from typing import Dict
from typing import Any
import random
def conflict_resolution_function(productions: List[Dict[str, Any]]) -> Dict[str, Any]:
"""ACT-R conflict resolution function. Currently selects a production at
random from the already matched productions, since utility values... | 26f35140b27cee75ce15a8f44ff061acaeb27786 | 663,300 |
def model_par(model):
"""
Given the model, return a list of associated Parameters
model - name of the model used
"""
if model == 'powerlaw':
return ['PhoIndex','norm']
if model == 'bbodyrad':
return ['kT','norm']
if model == 'ezdiskbb':
return ['T_max','norm']
if... | e7eed52f8b0a201321d98e6dd923ab89cff121b0 | 663,301 |
def blurb(bio):
"""
Returns champion blurb which cuts off around 250 characters
"""
if " " not in bio:
return bio
bio = bio[0:254]
bio = ' '.join(bio.split(' ')[:-1])
try:
if bio[-1] == ",":
bio = bio[:-1]
except Exception:
print(bio)
return bio + ... | b7256d2b30a9cd3b2df1ef6d1995286ee319817f | 663,302 |
from typing import Dict
def is_design(obj):
"""
Check if an object is a Metal Design, i.e., an instance of `QDesign`.
The problem is that the `isinstance` built-in method fails
when this module is reloaded.
Args:
obj (object): Test this object
Returns:
bool (bool): True if i... | 689428ea14e07b35916a0a69db7c503739aa4427 | 663,303 |
import sys
def has_stdin_input():
""" Return `True` if there is an stdin input """
if not sys.stdin.isatty():
return True
return False | 52ca0a96a1c2147597978b61ea4fec5577352b2e | 663,305 |
import inspect
def _repr(obj):
"""Internal :func:`repr` that tries to be more close to original
code.
"""
if inspect.isclass(obj):
return obj.__name__
elif type(obj) is tuple:
return '(%s)' % ', '.join(map(_repr, obj))
return repr(obj) | 7dd17eea0c9fa78cf4384c458c14cdf3ee8a9a30 | 663,306 |
def home():
"""Home Page."""
return "<h1>Home Page<h1>"+"<h6>Hello, world!<h6>" | a42314126094815d6e2489fd50aa9623bbc9aa5f | 663,307 |
def actor_static(actor):
"""judge whether an actor is in static state
Args:
actor: an actor of vehicle
Return:
a bool val respresents whether the actor is in static state
"""
vel = actor.get_velocity()
if abs(vel.x) <= 0.1 and abs(vel.y) <= 0.1 and abs(vel.z) <= 0.1:
retu... | 18c3cbd6ef785517fc90f693cd507e528a0fdbd5 | 663,308 |
def fix_angle(ang):
"""
Normalizes an angle between -180 and 180 degree.
"""
while ang > 360:
ang -= 360
while ang < 0:
ang += 360
return ang | c2fad1ba93b8f08b0a63d2d5a4e2920a6a541995 | 663,309 |
def plot_label(self, label=None, **kwargs):
"""
Logic to grab plot label
Note that this both takes label as a positional argument and a keyword.
This is a legacy issue where instead of grabbing label from kwargs,
which is how matplotlib handles it, I decided to make it a positional
argument,... | 2838df02108bdab8a3a56fcb0b1a1403c9201332 | 663,310 |
def ranks_already_set(args) -> bool:
"""Return True is both local and global ranks have been set."""
is_local_rank_set = args.local_rank > -1
is_global_rank_set = args.global_rank > -1
return is_local_rank_set and is_global_rank_set | 771bc2b9b6296c430c26089590f05fc983530202 | 663,312 |
def match_all_attrs(token, attrs_to_match):
"""
Return true if all the values in the given dict match the morphology attributes of the token. So attrs_to_match
is a way of filtering out which tokens will be matched.
Returns true for an empty dict.
:param token:
:param attrs_to_match:
:retur... | 0e5490a1da012a945db897b2315f79fd69dccc7b | 663,313 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.