content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def choose(text: str, prompt: str, options: Dict[str, str], suggestion: str, none_allowed: bool):
"""
Helper function to ask user to select from a list of options (with optional description).
Suggestion can be given. 'None' can be allowed as a valid input value.
"""
p = ColorPrint()
key_list = l... | 5,339,000 |
def gen(n):
""" (int) -> generator
Generate n, n - 2, n - 3, ..., 0
"""
for i in range(n, -1, -2):
yield i | 5,339,001 |
def visualize_Large(model_name, feature):
"""
visualize one large plot for a model and
color it according to certain feature labels
:param model_name:
:param feature:
"""
embedding = ut.load_numpy_file(ut.embedding_path + model_name + "_embedding.npy")
tsne = TSNE(n_components=2, verbose... | 5,339,002 |
def get_environ_list(name, default=None):
"""Return the split colon-delimited list from an environment variable.
Returns an empty list if the variable didn't exist.
"""
packed = os.environ.get(name)
if packed is not None:
return packed.split(':')
elif default is not None:
retur... | 5,339,003 |
def util_color(
graph: list[list[int]], max_color: int, colored_vertices: list[int], index: int
) -> bool:
"""
alur :
1. Periksa apakah pewarnaan selesai
1.1 Jika pengembalian lengkap True
(artinya kita berhasil mewarnai grafik)
Langkah Rekursif:
2. Iterasi atas setiap warna:
... | 5,339,004 |
def reverse_complement(sequence):
""" Return reverse complement of a sequence. """
complement_bases = {
'g':'c', 'c':'g', 'a':'t', 't':'a', 'n':'n',
'G':'C', 'C':'G', 'A':'T', 'T':'A', 'N':'N', "-":"-",
"R":"Y", "Y":"R", "S":"W", "W":"S", "K":"M", "M":"K",
"B":"V", "V":"B", "D": ... | 5,339,005 |
def saveT(T, sbs, out):
"""
Save a complex T matrix, input as an Nx2x2, into a text file. Dumps it as a CSV
where the first four columns are the real components, the last four are imaginary
:param T:
:param out:
:return:
"""
T = np.array(T.transpose(2, 0, 1))
## I'm nervous of trust... | 5,339,006 |
def get_variable_ddi(
name, shape, value, init, initializer=None, dtype=tf.float32,
regularizer=None, trainable=True):
"""Wrapper for data-dependent initialization."""
kwargs = {"trainable": trainable}
if initializer:
kwargs["initializer"] = initializer
if regularizer:
kwargs["regularizer"] = re... | 5,339,007 |
def convert_to_mp3(path, start=None, end=None, cleanup_after_done=True):
"""Covert to mp3 using the python ffmpeg module."""
new_name = path + '_new.mp3'
params = {
"loglevel": "panic",
"ar": 44100,
"ac": 2,
"ab": '{}k'.format(defaults.DEFAULT.SONG_QUALITY),
"f": "mp3... | 5,339,008 |
def conv3x3(in_planes, out_planes, Conv=nn.Conv2d, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return Conv(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation) | 5,339,009 |
async def async_setup(hass, config):
"""Set up the AirVisual component."""
hass.data[DOMAIN] = {}
hass.data[DOMAIN][DATA_CLIENT] = {}
hass.data[DOMAIN][DATA_LISTENER] = {}
if DOMAIN not in config:
return True
conf = config[DOMAIN]
hass.async_create_task(
hass.config_entrie... | 5,339,010 |
def hasConnection(document):
"""
Check whether document has a child of :class:`Sea.adapter.connection.Connection`.
:param document: a :class:`FreeCAD.Document` instance
"""
return _hasObject(document, 'Connection') | 5,339,011 |
def trsfrm_aggregeate_mulindex(df:pd.DataFrame,
grouped_cols:List[str],
agg_col:str,
operation:str,
k:int=5):
"""transform aggregate statistics for multiindex
Examples:
>... | 5,339,012 |
def get_hub_virtual_network_connection(connection_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
virtual_hub_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = Non... | 5,339,013 |
def run_ab3dmot(
classname: str,
pose_dir: str,
dets_dump_dir: str,
tracks_dump_dir: str,
max_age: int = 3,
min_hits: int = 1,
min_conf: float = 0.3
) -> None:
"""
#path to argoverse tracking dataset test set, we will add our predicted labels into per_sweep_annotations_amodal/
... | 5,339,014 |
def newcombe_binomial_ratio_err(k1,n1, k2,n2, z=1.0):
""" Newcombe-Brice-Bonnett ratio confidence interval of two binomial proportions.
"""
RR = (k1/n1) / (k2/n2) # mean
logRR = np.log(RR)
seLogRR = np.sqrt(1/k1 + 1/k2 - 1/n1 - 1/n2)
ash = 2 * np.arcsinh(z/2 * seLogRR)
lower ... | 5,339,015 |
def parse_metrics(rpcs: Any, detokenizer: Optional[detokenize.Detokenizer],
timeout_s: Optional[float]):
"""Detokenizes metric names and retrieves their values."""
# Creates a defaultdict that can infinitely have other defaultdicts
# without a specified type.
metrics: defaultdict = _tr... | 5,339,016 |
def missing_logic(scenario, fn):
"""Figure out what to do when this filename is missing"""
print("Searching for replacement for '%s'" % (fn,))
lon = float(fn[17:23])
lat = float(fn[24:30])
if not os.path.isdir(os.path.dirname(fn)):
os.makedirs(os.path.dirname(fn))
# So there should be a ... | 5,339,017 |
def cigarlist_to_cigarstring(cigar_list):
"""
Convert a list of tuples into a cigar string.
Example::
[ (0, 10), (1, 1), (0, 75), (2, 2), (0, 20) ]
=> 10M 1I 75M 2D 20M
=> 10M1I75M2D20M
:param cigar_list: a list of tuples (code, l... | 5,339,018 |
def check_transaction_entries(tsplit, entries):
"""Check that a list of Transaction Entries are equivalent.
Validate a list of TransactionEntry objects are equivalent, meaning they
contain the same items but do not necessarily share ordering.
"""
assert tsplit.entries is not None
assert isinsta... | 5,339,019 |
def add(x, y):
"""Add two numbers"""
return x+y | 5,339,020 |
def generateCSR(host_id, key):
"""Generate a Certificate Signing Request"""
pod_name = os.environ['MY_POD_NAME']
namespace = os.environ['TEST_APP_NAMESPACE']
SANURI = f'spiffe://cluster.local/namespace/{namespace}/podname/{pod_name}'
req = crypto.X509Req()
req.get_subject().CN = host_id
re... | 5,339,021 |
def get_s4_function_details(carray, item):
"""
Gets function details for S4 Class Functions
Details are appended to carray
:param item: Node to be queried.
:type item: Node
:return: None
"""
found = False
etags, etxt, elist = get_child_list(item)
idx = find_sublist_index(['OP-LE... | 5,339,022 |
def sdecorator(decoratorHandleDelete: bool = False, expectedProperties: list = None, genUUID: bool = True,
enforceUseOfClass: bool = False, hideResourceDeleteFailure: bool = False,
redactConfig: RedactionConfig = None, timeoutFunction: bool = True):
"""Decorate a function to add input ... | 5,339,023 |
def export_jsx(session, program, start_date, end_date, title):
"""Do not mess with this function it exports roundups"""
filename = program + '.html'
f = open(filename, 'w')
opening_wrapper = f"""<html>
<head>
<title>{title}</title>
</head>
<body><p>{title}</p>"""#.format(title)
f.wr... | 5,339,024 |
def send_mail(user,server):
#def send_mail():
"""Sending the mails by voice 3 arguments required
1.to_address
2.subject
3.Message
these all info you can give by voice"""
fromaddr = '' #your email_id from this it can send the mails
tolist = to_addrs()
#print tolist
sub = subj()
#print sub
body1 = body()
#pr... | 5,339,025 |
def clean_acl(name, value):
"""
Returns a cleaned ACL header value, validating that it meets the formatting
requirements for standard Swift ACL strings.
The ACL format is::
[item[,item...]]
Each item can be a group name to give access to or a referrer designation
to grant or deny base... | 5,339,026 |
def test(X, Y, perms=10000, method="pearson", tail="two-tail", ignore_nans=False):
"""
Takes two distance matrices (either redundant matrices or condensed vectors)
and performs a Mantel test. The Mantel test is a significance test of the
correlation between two distance matrices.
Parameters
---... | 5,339,027 |
def get_format_datestr(date_str, to_format='%Y-%m-%d'):
"""
Args:
date_str (str): ''
to_format (str): '%Y-%m-%d'
Returns:
date string (str)
"""
date_obj = parser.parse(date_str).date()
return date_obj.strftime(to_format) | 5,339,028 |
def lor(*goalconsts):
""" Logical or for goal constructors
>>> from logpy.arith import lor, eq, gt
>>> gte = lor(eq, gt) # greater than or equal to is `eq or gt`
"""
def goal(*args):
return lany(*[gc(*args) for gc in goalconsts])
return goal | 5,339,029 |
def kalman_smoother(Z, M_inv, plotting=False):
"""
X: state
U: control
Z: observation (position and forces)
F: state transition model
B: control input model
Q: process variance
R: observation variance
"""
t_steps = Z.shape[0]
x0 = np.r_[Z[0,0:6],
np.zeros(... | 5,339,030 |
def create_barplot(ax, relevances, y_pred, x_lim=1.1, title='', x_label='', concept_names=None, **kwargs):
"""Creates a bar plot of relevances.
Parameters
----------
ax : pyplot axes object
The axes on which the bar plot should be created.
relevances: torch.tensor
The relevances for... | 5,339,031 |
def deploy():
"""Run deployment tasks."""
from flask_migrate import init, migrate, upgrade
# migrate database to latest revision
try: init()
except: pass
migrate()
upgrade() | 5,339,032 |
def get_convex_hull(coords, dim = 2, needs_at_least_n_points = 6): #FIXME restrict only for 2D?
"""
For fitting an ellipse, at least 6 points are needed
Parameters
----------
coords : 2D np.array of points
dim : dimensions to keep when calculating convex hull
Returns
---------
coo... | 5,339,033 |
def sk_page(
name,
html_file,
ts_entry_point,
scss_entry_point = None,
ts_deps = [],
sass_deps = [],
sk_element_deps = [],
assets_serving_path = "/",
nonce = None):
"""Builds a static HTML page, and its CSS and JavaScript development and produc... | 5,339,034 |
def score(input,
index,
output=None,
scoring="+U,+u,-s,-t,+1,-i,-a",
filter=None, # "1,2,25"
quality=None,
compress=False,
threads=1,
raw=False,
remove_existing=False):
"""Score the input. In addition, you can specify a tuple... | 5,339,035 |
def keyword_search(queryset: QuerySet, keywords: str) -> QuerySet:
"""
Performs a keyword search over a QuerySet
Uses PostgreSQL's full text search features
Args:
queryset (QuerySet): A QuerySet to be searched
keywords (str): A string of keywords to search the QuerySet
Returns:
... | 5,339,036 |
def classification_loss(hidden, labels, n_class, initializer, name, reuse=None,
return_logits=False):
"""
Different classification tasks should use different scope names to ensure
different dense layers (parameters) are used to produce the logits.
An exception will be in tr... | 5,339,037 |
def do_pdfimages(pdf_file, state, page_number=None, use_tmp_identifier=True):
"""Convert a PDF file to images in the TIFF format.
:param pdf_file: The input file.
:type pdf_file: jfscripts._utils.FilePath
:param state: The state object.
:type state: jfscripts.pdf_compress.State
:param int page_... | 5,339,038 |
def git_patch_tracked(path: Path) -> str:
""" Generate a patchfile of the diff for all tracked files in the repo
This function catches all exceptions to make it safe to call at the end of
dataset creation or model training
Args:
path (Path): path to a directory inside a git repo. Unless yo... | 5,339,039 |
def connect(transport=None, host='localhost', username='admin',
password='', port=None, key_file=None, cert_file=None,
ca_file=None, timeout=60, return_node=False, **kwargs):
""" Creates a connection using the supplied settings
This function will create a connection to an Arista EOS nod... | 5,339,040 |
def cov_hc2(results):
"""
See statsmodels.RegressionResults
"""
# probably could be optimized
h = np.diag(np.dot(results.model.exog,
np.dot(results.normalized_cov_params,
results.model.exog.T)))
het_scale = results.resid**2/(1-h)
cov_hc2_ ... | 5,339,041 |
def add_people():
"""
Show add form
"""
if request.method == 'POST':
#save data to database
db_conn = get_connection()
cur = db_conn.cursor()
print ('>'*10, request.form)
firstname = request.form['first-name']
lastname = request.form['last-name']
address = request.form['address']
country = request.... | 5,339,042 |
def api_to_schema(api: "lightbus.Api") -> dict:
"""Produce a lightbus schema for the given API"""
schema = {"rpcs": {}, "events": {}}
if isinstance(api, type):
raise InvalidApiForSchemaCreation(
"An attempt was made to derive an API schema from a type/class, rather than "
"f... | 5,339,043 |
def sum2(u : SignalUserTemplate, initial_state=0):
"""Accumulative sum
Parameters
----------
u : SignalUserTemplate
the input signal
initial_state : float, SignalUserTemplate
the initial state
Returns
-------
SignalUserTemplate
the output signal of the filter
... | 5,339,044 |
def approve_report(id):
"""
Function to approve a report
"""
# Approve the vulnerability_document record
resource = s3db.resource("vulnerability_document", id=id, unapproved=True)
resource.approve()
# Read the record details
vdoc_table = db.vulnerability_document
record = db(vdo... | 5,339,045 |
def sparse_column_multiply(E, a):
"""
Multiply each columns of the sparse matrix E by a scalar a
Parameters
----------
E: `np.array` or `sp.spmatrix`
a: `np.array`
A scalar vector.
Returns
-------
Rescaled sparse matrix
"""
ncol = E.shape[1]
if ncol != a.shape[... | 5,339,046 |
def soup_extract_enzymelinks(tabletag):
"""Extract all URLs for enzyme families from first table."""
return {link.string: link['href']
for link in tabletag.find_all("a", href=True)} | 5,339,047 |
def choose(db_issue: Issue, db_user: User, pgroup_ids: [int], history: str, path: str) -> dict:
"""
Initialize the choose step for more than one premise in a discussion. Creates helper and returns a dictionary
containing several feedback options regarding this argument.
:param db_issue:
:param db_u... | 5,339,048 |
def loops_NumbaJit_parallelFast(csm, r0, rm, kj):
""" This method implements the prange over the Gridpoints, which is a direct
implementation of the currently used c++ methods created with scipy.wave.
Very strange: Just like with Cython, this implementation (prange over Gridpoints)
produces wrong r... | 5,339,049 |
def sobel_vertical_gradient(image: numpy.ndarray) -> numpy.ndarray:
"""
Computes the Sobel gradient in the vertical direction.
Args:
image: A two dimensional array, representing the image from which the vertical gradient will be calculated.
Returns:
A two dimensional array, representin... | 5,339,050 |
def custom_field_sum(issues, custom_field):
"""Sums custom field values together.
Args:
issues: List The issue list from the JQL query
custom_field: String The custom field to sum.
Returns:
Integer of the sum of all the found values of the custom_field.
"""
... | 5,339,051 |
def routingAreaUpdateReject():
"""ROUTING AREA UPDATE REJECT Section 9.4.17"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0xb) # 00001011
c = GmmCause()
d = ForceToStandbyAndSpareHalfOctets()
packet = a / b / c / d
return packet | 5,339,052 |
def parse_file_list(file_list_file, in_img_data_dir, out_img_data_dir, write_txt = True):
"""
do the following:
1. put the list of image to outdir/file_list.txt, with name mapping
2. link the image from the original data directory to outdir/
"""
p = re.compile("\w+/[\w,\_]+/([\w,\_,.,\-,\+]+)")
... | 5,339,053 |
def compile_gyms_table():
""" supposed to run from /py directory """
os.chdir('../gyms')
compiled_gyms_table = ""
for file in filter(lambda _: os.path.splitext(_)[1] == '.json', os.listdir()):
gym = json.loads(open(file, 'r', encoding='utf-8').read())
assert gym['type'] == 'gym'
... | 5,339,054 |
def parse(complete_file_name, stop_at_line_number=None):
"""
:param complete_file_name:
:param stop_at_line_number: if None, parses the whole file, if not None, stops parsing line "stop_at_line_number"
:return: an iterator of ProteinRow
"""
c = 0
def tsv_iterator():
with open(comp... | 5,339,055 |
def doRipsFiltration(X, maxHomDim, thresh = -1, coeff = 2, getCocycles = False):
"""
Run ripser assuming Euclidean distance of a point cloud X
:param X: An N x d dimensional point cloud
:param maxHomDim: The dimension up to which to compute persistent homology
:param thresh: Threshold up to which to... | 5,339,056 |
def test_contest(gc: GetContestsDocument):
"""Tests contest document"""
contest = random.choice(gc.contests)
assert isinstance(contest, ContestDocument) | 5,339,057 |
def build_target_areas(entry):
"""Cleanup the raw target areas description string"""
target_areas = []
areas = str(entry['cap:areaDesc']).split(';')
for area in areas:
target_areas.append(area.strip())
return target_areas | 5,339,058 |
def convert_to_celcius(scale, temp):
"""Convert the specified temperature to Celcius scale.
:param int scale: The scale to convert to Celcius.
:param float temp: The temperature value to convert.
:returns: The temperature in degrees Celcius.
:rtype: float
"""
if scale == temp_scale.FARENHEI... | 5,339,059 |
def setMotor(id, speed):
""" Set a motor speed """
_controllers[id].set(speed) | 5,339,060 |
def config_file_settings(request):
"""
Update file metadata settings
"""
if request.user.username != 'admin':
return redirect('project-admin:home')
if request.method == 'POST':
update_file_metadata(request.POST)
return redirect('project-admin:home')
files = FileMetaData... | 5,339,061 |
def roundtrip(sender, receiver):
"""
Send datagrams from `sender` to `receiver` and back.
"""
return transfer(sender, receiver), transfer(receiver, sender) | 5,339,062 |
def basic_takeoff(altitude):
"""
This function take-off the vehicle from the ground to the desired
altitude by using dronekit's simple_takeoff() function.
Inputs:
1. altitude - TakeOff Altitude
"""
vehicle.mode = VehicleMode("GUIDED")
vehicle.armed = True
time.... | 5,339,063 |
def match_demo():
"""
2. match()
传入要匹配的字符串以及正则表达式,就可以检测这个正则表达式是否匹配字符串。
match()方法会尝试从字符串的起始位置匹配正则表达式,如果匹配,就返回匹配成功
的结果;如果不匹配,就返回None
"""
content = 'Hello 123 4567 World_This is a Regex Demo'
# print(len(content))
result = re.match(r"^Hello\s\d\d\d\s\d{4}\s\w{10}", content)
# 使用... | 5,339,064 |
def loadHashDictionaries():
"""
Load dictionaries containing id -> hash and hash -> id mappings
These dictionaries are essential due to some restrictive properties
of the anserini repository
Return both dictionaries
"""
with open(PATH + PATH_ID_TO_HASH, "r") as f:
id_to_hash_di... | 5,339,065 |
def preprocess(tensor_dict, preprocess_options, func_arg_map=None):
"""Preprocess images and bounding boxes.
Various types of preprocessing (to be implemented) based on the
preprocess_options dictionary e.g. "crop image" (affects image and possibly
boxes), "white balance image" (affects only image), etc. If se... | 5,339,066 |
def update_comment(id):
"""修改单条评论"""
comment = Comment.query.get_or_404(id)
if g.current_user != comment.author and not g.current_user.can(Permission.COMMENT):
return error_response(403)
data = request.get_json()
if not data:
return bad_request('You must put JSON data.')
comment.... | 5,339,067 |
def resnet18(num_classes, pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
encoder = ResNetEncoder(BasicBlock, [2, 2, 2, 2])
if pretrained:
encoder.load_state_dict(model_zoo.load_url(model_urls... | 5,339,068 |
def display_page(pathname):
"""displays dash page"""
if pathname == '/':
return main.layout
elif pathname == '/explore':
return explore.layout
elif pathname == '/eval':
return eval.layout
elif pathname == '/train':
return train.layout
else:
return html.Div... | 5,339,069 |
def getFilterDict(args):
"""
Function: An entire function just to notify the user of the arguments they've passed to the script? Seems reasonable.
Called from: main
"""
## Set variables for organization; this can be probably be removed later
outText = {}
outAction = ""
userString = ""... | 5,339,070 |
def iter_object_annotations(obj) -> (str, CasterUnion, Any):
"""Iter over annotations of object."""
if isclass(obj):
yield from iter_class_annotations(obj)
elif isroutine(obj):
yield from iter_function_annotations(obj)
else:
raise InvalidSchema(obj) | 5,339,071 |
def pointwise_multiply(A, B):
"""Pointwise multiply
Args:
-----------------------------
A: tvm.te.tensor.Tensor
shape [...]
B: tvm.te.tensor.Tensor
shape same as A
-----------------------------
Returns:
-----------------------------
tvm.te.tensor.Tensor
shap... | 5,339,072 |
def generate_negative_data(data):
"""Generate negative data."""
# Big movement -> around straight line
for i in range(100):
dic = {config.DATA_NAME: [], config.LABEL_NAME: "negative"}
start_x = (random.random() - 0.5) * 2000
start_y = (random.random() - 0.5) * 2000
start_z = (random.random() - 0.... | 5,339,073 |
def create_website(self):
"""
:param self:
:return:
"""
try:
query = {}
show = {"_id": 0}
website_list = yield self.mongodb.website.find(query, show)
return website_list
except:
logger.error(traceback.format_exc())
return "" | 5,339,074 |
def _get_sparsity(A, tolerance=0.01):
"""Returns ~% of zeros."""
positives = np.abs(A) > tolerance
non_zeros = np.count_nonzero(positives)
return (A.size - non_zeros) / float(A.size) | 5,339,075 |
def findPeaks(hist):
"""
Take in histogram
Go through each bin in the histogram and:
Find local maximum and:
Fit a parabola around the two neighbor bins and local max bin
Calculate the critical point that produces the max of the parabola
(critical point represents orientation... | 5,339,076 |
def tph_chart_view(request, template_name="monitor/chart.html", **kwargs):
"""Create example view.
that inserts content into the dash context passed to the dash application.
"""
logger.debug('start')
context = {
'site_title': 'TPH monitor',
'title': 'TPH chart via Plotly Dash for D... | 5,339,077 |
def gradient_descent(x_0, a, eta, alpha, beta, it_max, *args, **kwargs):
"""Perform simple gradient descent with back-tracking line search.
"""
# Get a copy of x_0 so we don't modify it for other project parts.
x = x_0.copy()
# Get an initial gradient.
g = gradient(x, a)
# Compute the norm... | 5,339,078 |
def ExtractCalledByNatives(contents):
"""Parses all methods annotated with @CalledByNative.
Args:
contents: the contents of the java file.
Returns:
A list of dict with information about the annotated methods.
TODO(bulach): return a CalledByNative object.
Raises:
ParseError: if unable to parse... | 5,339,079 |
def test_raw_html_642a():
"""
Test case 642a: variation on 642 with a closing tag character without a valid closing tag name
"""
# Arrange
source_markdown = """</>"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\a/\a>\a>\a:]",
"[end-para:::True]",
]
... | 5,339,080 |
def deckedit(ctx: EndpointContext) -> None:
"""Handles requests for the deck editor page.
Serves the deck editor template.
Args:
ctx: The request's context.
"""
# Populate symbol table
symtab = {"nickname": ctx.session["nickname"],
"theme": ctx.session["theme"],
... | 5,339,081 |
def knn_python(input_x, dataset, labels, k):
"""
:param input_x: 待分类的输入向量
:param dataset: 作为参考计算距离的训练样本集
:param labels: 数据样本对应的分类标签
:param k: 选择最近邻样本的数目
"""
# 1. 计算待测样本与参考样本之间的欧式距离
dist = np.sum((input_x - dataset) ** 2, axis=1) ** 0.5
# 2. 选取 k 个最近邻样本的标签
k_labels = [labels[inde... | 5,339,082 |
def charReplace(contentData, modificationFlag):
"""
Attempts to convert PowerShell char data types using Hex and Int values into ASCII.
Args:
contentData: [char]101
modificationFlag: Boolean
Returns:
contentData: "e"
modificationFlag: Boolean
"""
startTime = dat... | 5,339,083 |
def _prepare_config(separate, resources, flavor_ref,
git_command, zip_patch,
directory, image_ref, architecture, use_arestor):
"""Prepare the Argus config file."""
conf = six.moves.configparser.SafeConfigParser()
conf.add_section("argus")
conf.add_section("openst... | 5,339,084 |
def print_verb_conjugation(verb):
"""Print a verb conjugations in different output formats"""
if parameters["ABU output"]:
print_ABU_inflections(verb)
elif parameters["DELA output"]:
print_DELA_inflections(verb)
elif parameters["Display columns"] == 1:
print_verb_conjugation_odd_... | 5,339,085 |
def all_logit_coverage_function(coverage_batches):
"""Computes coverage based on the sum of the absolute values of the logits.
Args:
coverage_batches: Numpy arrays containing coverage information pulled from
a call to sess.run. In this case, we assume that these correspond to a
batc... | 5,339,086 |
async def create_audio(request):
"""Process the request from the 'asterisk_ws_monitor' and creates the audio file"""
try:
message = request.rel_url.query["message"]
except KeyError:
message = None
LOGGER.error(f"No 'message' parameter passed on: '{request.rel_url}'")
raise w... | 5,339,087 |
def checkConfigChanges(configuration, director):
"""
A scheduled checker for configration changes.
"""
if not configuration.manager.configCheckEnabled:
return
util.saveConfig(configuration, director) | 5,339,088 |
def reinterpret_axis(block, axis, label, scale=None, units=None):
""" Manually reinterpret the scale and/or units on an axis """
def header_transform(hdr, axis=axis, label=label, scale=scale, units=units):
tensor = hdr['_tensor']
if isinstance(axis, basestring):
axis = tensor['labels... | 5,339,089 |
def duel(board_size, player_map):
"""
:param board_size: the board size (i.e. a 2-tuple)
:param player_map: a dict, where the key is an int, 0 or 1, representing the player, and the value is the policy
:return: the resulting game outcomes
"""
board_state = init_board_state(board_size)
result... | 5,339,090 |
def set_processor_type(*args):
"""
set_processor_type(procname, level) -> bool
Set target processor type. Once a processor module is loaded, it
cannot be replaced until we close the idb.
@param procname: name of processor type (one of names present in
\ph{psnames}) (C++: const char *)
... | 5,339,091 |
def convert_repeat(node, **kwargs):
"""Map MXNet's repeat operator attributes to onnx's Tile operator.
"""
from onnx.helper import make_node
from onnx import TensorProto
name, input_nodes, attrs = get_inputs(node, kwargs)
opset_version = kwargs['opset_version']
if opset_version < 11:
... | 5,339,092 |
def on_message(client, _u, msg):
"""
defines callback for message handling, inits db table from first data row received
"""
data = json.loads(msg.payload.decode("utf-8"))[0]
if not client.db_con.table_created:
client.data_is_dict = init_table(data, client.db_cols, client, client.env_args)
... | 5,339,093 |
def my_quote(s, safe = '/'):
"""quote('abc def') -> 'abc%20def'
Each part of a URL, e.g. the path info, the query, etc., has a
different set of reserved characters that must be quoted.
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
the following reserved characters.
reserve... | 5,339,094 |
def test_onfail_requisite_no_state_module(state, state_tree):
"""
Tests a simple state using the onfail requisite
"""
sls_contents = """
failing_state:
cmd.run:
- name: asdf
non_failing_state:
cmd.run:
- name: echo "Non-failing state"
test_failing_state:
c... | 5,339,095 |
def GetExperimentStatus(experiment, knobs, exp_data, track='stable'):
"""Determine the status and source of a given experiment.
Take into account all ways that a given experiment may be enabled and allow
the client to determine why a given experiment has a particular status.
Experiments at 100% are always on.... | 5,339,096 |
def test_plot_crystal_field_calculation():
"""
Test of the plot illustrating the potential and charge density going into the calculation
"""
from masci_tools.tools.cf_calculation import CFCalculation, plot_crystal_field_calculation
cf = CFCalculation()
cf.readPot('files/cf_calculation/CFdata.hd... | 5,339,097 |
async def submit_changesheet(
uploaded_file: UploadFile = File(...),
mdb: MongoDatabase = Depends(get_mongo_db),
user: User = Depends(get_current_active_user),
):
"""
Example changesheet [here](https://github.com/microbiomedata/nmdc-runtime/blob/main/metadata-translation/notebooks/data/changesheet-... | 5,339,098 |
def get_notes(request, course, page=DEFAULT_PAGE, page_size=DEFAULT_PAGE_SIZE, text=None):
"""
Returns paginated list of notes for the user.
Arguments:
request: HTTP request object
course: Course descriptor
page: requested or default page number
page_size: requested or defau... | 5,339,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.