content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def rev_wordpiece(str):
"""wordpiece function used in cbert"""
#print(str)
if len(str) > 1:
for i in range(len(str)-1, 0, -1):
if str[i] == '[PAD]':
str.remove(str[i])
elif len(str[i]) > 1 and str[i][0]=='#' and str[i][1]=='#':
str[i-1] +=... | ed826bd4688d1cc304597d2b34eac0e025195d8c | 650,515 |
import time
def sum_of_pow(num):
""" Time consuming process """
sum = 0
start = time.time()
for i in range(pow(num, num) + 1):
sum += i
time.sleep(0.01)
res = round(time.time() - start, 4), sum
return res | 3dadc381d46a4dabe0997d080522c698b4eef75e | 650,517 |
def files_private(self):
"""files for private repos"""
return self.get_org_files(pub_status='private') | 5bca27ebd11cddd0e7f93f2c9a03b0902ddf065c | 650,518 |
def legend_of_image(square_side, smali_dim):
"""These lines read the number of character of a class and calculate where it begins and ends inside the image"""
image_legend = ""
first = True
end = 0
for name in smali_dim:
if first:
end = smali_dim[name] + 1
xe = end % ... | 9d1ca3d4197bb6183d9ed4620fabf10fd9bfdc6a | 650,519 |
from typing import List
import re
def _scan_IDs(text: str, cpf: bool = True) -> List[str]:
"""
Scan for cpfs (social security IDs) and cnpjs (corporate IDs)
in gazette.
"""
if cpf:
regex = re.compile(r"\w{3}\.\w{3}\.\w{3}\-\w{2}")
else:
regex = re.compile(r"\w{2}\.\w{3}\.\w{3}/... | 1fad525a3d0e381bbaca157bf3a193bc77d5afe1 | 650,520 |
def tokenizer(record):
"""
Tokenizer for inverted index blocking
Params:
record: (rltk.Record)
"""
return record.name_tokenized | 5610e14773655cc0c80bf337e8ec7e4cda52e1e2 | 650,521 |
def sample_hyperparameter(_distribution, _hyper, rng):
"""Dummy function to fetch hyperparameters for univariate distribution."""
return round(rng.gamma(1,1), 6) | f615f2d297a18b436f7d0028a3153d2d3eae7e2c | 650,522 |
def create_finances_table_name(csv_name: str):
"""
Getting a readable table name from the finances csv
Example: EUHWC_-_Expense_Claims_(Responses)
expenses
:param csv_name:
:return:
"""
# table replacements
table_name = csv_name.split("_-_")[1]
table_name = table_name.sp... | 5af0c00b62759d4e38ef5de5bda6aea046a8bc86 | 650,523 |
def create_default_query(relative):
"""Get the given paper."""
query = """
select p.id as from_id, p.title as from_title, p.abstract as from_abstract, p.year as from_year, false as from_is_influential, p.citations as from_citations, a.name as from_author
from paper p, write w, author a
... | 946c2784a4bf976158041ad50c9d94f7b14cc9c7 | 650,525 |
import re
def get_edu_text(text_subtree):
"""return the text of the given EDU subtree, with '_!'-delimiters removed."""
assert text_subtree.label() == 'text', "text_subtree: {}".format(text_subtree)
edu_str = ' '.join(word for word in text_subtree.leaves())
return re.sub('_!(.*?)_!', '\g<1>', edu_str) | 4add5d6697f5bede2636fb7d2704c5b72827ed97 | 650,526 |
def _get_help_lines(content):
"""
Return the help text split into lines, but replacing the
progname part of the usage line.
"""
lines = content.splitlines()
lines[0] = 'Usage: <progname> ' + ' '.join(lines[0].split()[2:])
return lines | 71dec5dec57f257a3fd9ec844b7d9fa727bdafa6 | 650,527 |
def bestName(inRow):
"""
helper function for annotate_best_CDS
given a row with 'Label' and 'Locus tag', choose the best annotation
choose 'Label' if it's present
otherwise choose 'Locus tag'
return a string with the best name
"""
if inRow['Label'] == '':
result = inRow['Locus T... | 70a4f1cd13d9fc4c0f614a07bb6605e0706b0b50 | 650,528 |
import os
def get_required_files(
path: str,
valid_formats: list = [".jpg", ".jpeg", ".jp2", ".png", ".bmp", ".tiff", ".tif"],
):
"""
This function determines number of iteration required.
From the give path, it calculates number of images present
Right now we support the image formats which a... | dbf8491d2c6d68cb6334588b8fab7db1a0d0dbf6 | 650,529 |
import re
def col_types(df):
"""Decides column types to store for database
Arguments:
df {pandas dataframe} -- [pandas dataframe]
"""
cols = df.columns.tolist()
floattypes = re.compile(r"^[Ll]atitude$|^LATITUDE$|^[Ll]ongitude$|^LONGITUDE$|^ELEVATION.*?$|^[Ee]levation.*?$|^[A-Za-z]{2,... | 534671b6b9eb01f4d248a1f8ac029d3d0989b4e6 | 650,530 |
def decomposer(entier, divise_par):
"""Cette fonction retourne la partie entière et le reste de
entier / divise_par"""
p_e = entier // divise_par
reste = entier % divise_par
return p_e, reste | 9fd9edfad792f6788e697da9bae19eab73c767b7 | 650,531 |
import torch
def shift_image(img, shft_int = 1):
"""
Shifts the pixels of a grayscale image to the right by shft_int if the shft_int
last columns of the tensor have zero entries only (i.e. black). If they cointain
any non-zeros, the pixels are shifted to the left by shft_int.
Abortion if both ca... | b711ad60e954360507b8a2f8be775e88a027ef61 | 650,532 |
def parse_dot(d):
""" Convert dictionary with dot keys to a hierarchical dictionary """
ks = [(k, v) for k, v in d.items() if '.' in k]
for k, v in ks:
del d[k]
curr = d
*fronts, back = k.split('.')
for k_ in fronts:
curr = curr.setdefault(k_, {})
curr[bac... | 04287bfeed6642e9513fac51a44ff93e651d2ac2 | 650,533 |
import unicodedata
def width_in_terminal(text):
"""
:param six.text_type text:
"""
try:
return sum(2 if unicodedata.east_asian_width(x) in ('F', 'W', 'A') else 1 for x in text)
except UnicodeError:
return -1 | a4659838cc9bd6529449f3829dc90822fa79f330 | 650,534 |
from unittest.mock import patch
def patch_site_configs(values):
"""
Helper to mock site configuration values.
:param values dict.
Use either as `@patch_site_configs(...)` or `with patch_site_configs(...):`.
"""
return patch.dict('openedx.core.djangoapps.site_configuration.helpers.MOCK_SITE_C... | bd9f6938f57e93d053725a78ebaf5c494082fca3 | 650,535 |
def catch_all():
"""\
Simply catch all updates.
:return: always True
"""
return True | 2386b96f2b15a32a439713732634ad98dd2ca88c | 650,536 |
import os
def getMasterPath():
"""Answers the path to read master fonts, whic typically is a user/Fonts/
folder. Default is at the same level as pagebot module."""
return os.path.expanduser("~") + '/Fonts/' | de55853ce7388496a7410b9cfd4f2fc463b3a0d2 | 650,537 |
import itertools
def is_clique(old_graph, vertices):
"""
Tests if vertices induce a clique in the graph
Multigraphs are reduced to normal graphs
Parameters
----------
graph : networkx.Graph or networkx.MultiGraph
graph
vertices : list
vertices which are tested
Retu... | 97184b05c1eb89b70f83552e74e04de966790036 | 650,538 |
def str_to_int(s):
""" Takes a string provided through user input, which may be hexadecimal or an integer, and
converts it to the actual corresponding integer. """
s = s.strip().lower()
if s.startswith("$"):
return int(s[1:], 16)
elif s.startswith("0x"):
return int(s[2:], 16)
... | 1df7e74fd2a67ccd0f2a886a8629031d0feb85f6 | 650,539 |
def z_sort(node, alist):
"""Return new list sorted in document order (depth-first traversal)."""
ordered = []
id_list = list(alist)
count = len(id_list)
for element in node.iter():
element_id = element.get('id')
if element_id is not None and element_id in id_list:
id_list... | efc51fce609f6c687e9d6eff396dd238d3fbf87a | 650,540 |
def sensor_param(request):
"""
parametrize a test with sensor parameters
"""
parameters = request.param
print('test parameters')
print('Device list : ' + str(parameters.devices))
print('socket list : ' + str(parameters.sockets))
print('one socket result : ' + str(parameters.one_socket_re... | 5c24b583f157b322f9cf102791edc454efb1aaba | 650,542 |
def _get_arr_same_size_object(same_arr_size_list, size):
"""
This function, for a given list of ArraysSameSize objects, returns
the object that represents arrays of the size passed as argument
"""
for elem in same_arr_size_list:
if elem.size == size:
return elem
return None | 268f09dc1478aff37c6d51db10e61742fe8d333f | 650,543 |
from typing import OrderedDict
import operator
def evaluate_threshold_filters(isovar_result, filter_thresholds):
"""
Helper method used by apply_filters
Parameters
----------
isovar_result : IsovarResult
filter_thresholds : dict or OrderedDict
Every argument is supposed to be somethi... | 922297f487788a0048baf456b33d329b5a849540 | 650,544 |
from datetime import datetime
def datetime_json_parser(json_dict):
"""Function to convert JSON dictionary objects to datetime when possible.
This is required to get datetime objects into the database.
Adapted from: https://stackoverflow.com/questions/8793448/how-to-convert-to-a-python-datetime-object-with... | 2d2765c542df2c673f50d35803beb14222bb4a84 | 650,545 |
def _swift_xcrun_args(ctx):
"""Returns additional arguments that should be passed to xcrun."""
if ctx.fragments.apple.xcode_toolchain:
return ["--toolchain", ctx.fragments.apple.xcode_toolchain]
return [] | 92a9daadf3800df2fdd8ec5a1e9e4ef48153bc14 | 650,547 |
def is_version_compatible(version: dict, expected_version: tuple) -> bool:
"""
Args:
version: Dictionary containing version info.
Should have following fields -> 'major', 'minor', 'patch'
expected_version: Tuple of 3 elements for ('major', 'minor', 'patch')
Returns:
... | 1f042593c3306adc3ad315f447d6b3e3e1625d41 | 650,548 |
import re
def remove_html_tag(source):
"""
移除字符串中的HTML格式标签
:param source:
:return:
"""
if source:
result = re.sub('<[^>]+>', '', source)
return result
else:
return str() | 441d40e1051b83ab334452e6bf735aa140194d36 | 650,550 |
import logging
def _test_acc_token(client):
""" Tests access token by trying to fetch a records basic demographics """
try:
demo = client.get_demographics()
status = demo.response.get('status')
if '200' == status:
return True
else:
logging.warning('get_d... | 7618b6d894f08a37400617440dda35bef99b2b97 | 650,551 |
def greater(list, pivot):
"""
Get all numbers greater than the pivot which starts with the first number.
It keeps increasing to the current max number.
"""
answer = [pivot]
for i in range(len(list)):
curr = list[i]
if curr > pivot:
answer += [curr]
pivot =... | 8365406b0c383495c2e3ca74cdc22ef987800d4a | 650,555 |
import os
def cacheFindEntry(cache, cameraID, desiredTime):
"""Search given cache for image from given camera at given timestamp (within 30 seconds)
Args:
cache (dict): Cache object created by cacheDir()
cameraID (str): ID of camera to fetch images from
desiredTime (int): unix time of... | d527a2942191e3cb0905825f62520c526a46bb7d | 650,556 |
def test_nonlocal():
"""
测试python3 新特性nonlocal
:return:
"""
x = 5
def local_function():
nonlocal x
x *= x
return x
return local_function() | 9e6d82d3dc9ca2764d24cf0f2331eaa42aba3a5f | 650,557 |
def data():
"""
Setup test data
"""
return {
"id": "mycluster",
"tenant": "mytenant",
"facts": {
"distribution": "rancher",
"cloud": "cloudscale",
},
"gitRepo": {
"url": "ssh://git@git.example.com/cluster-catalogs/mycluster",
... | 78b3d8c01b58399737b00e3b6c02c3a52606416c | 650,558 |
def get_column_header(results, row_index):
"""gets column for a row.
The main data from the API is returned as rows of data. The column
headers describe the names and types of each column in rows.
Args:
results: The response returned from the Core Reporting API.
row index.
"""
headers = results.g... | a4edcc1e29add7c829f073ca7efb8bb1e83d1b28 | 650,560 |
def nf(stage, fmap_base=8192, fmap_decay=1.7, fmap_max=32, fmap_min: int = 32):
"""Computes the number of feature map given the current stage.
This function is inspired from the following Github repo:
https://github.com/tkarras/progressive_growing_of_gans/blob/master/networks.py
Arguments:
sta... | 4b952198276781980757d932b14c98740f109e98 | 650,561 |
def build_help_text(feeds):
"""
Takes field names and any proved params and makes the help text for the editor
"""
return " \n" \
"# Enter the body your message then save & quit\n" \
.format(feeds).encode() | 5a2f459cb1e5766b726d306f0fd5c62fcefbdce3 | 650,562 |
import math
def read_result_txt(path_txt, apply_sqrt=True):
"""
Parse TXT file and returns a list of variance.
"""
def is_variance_row(line):
"""
Returns true if the given line is a row of test score.
"""
return all(char in ".0123456789e+-" for char in line.strip())
... | 29c21e76d18f91996efb4600159eaa065f40d1a1 | 650,566 |
def map_range(value, from_min=0, from_max=1, to_min=0, to_max=1):
"""
Scale value from
Thanks to this SO post: http://stackoverflow.com/a/5295202/2730823
"""
return ((to_max-to_min)*(value - from_min) / (from_max - from_min)) + to_min | c975f438a580df481b23687149ed4fb9b5d7c980 | 650,568 |
def match(line,keyword):
"""If the first part of line (modulo blanks) matches keyword,
returns the end of that line. Otherwise returns None"""
line=line.lstrip()
length=len(keyword)
if line[:length] == keyword:
return line[length:]
else:
return None | 50b61c103ed0a2e0df41326036c1e069fd73ec9e | 650,569 |
def classify(e):
"""
:param e: float
:rtype: string
"""
if e > 0.75:
return 'high'
if e > 0.25:
return 'medium'
if e >= 0:
return 'low' | ce32fe217d8f0bf72a32cf9fc551ec38f55fb9ae | 650,570 |
def constructBasicJSON():
"""
Create basic JSON for operations
"""
data = {}
data['cmd'] = None
data['user'] = None
data['password'] = None
data['auth'] = None
data['error'] = []
return data | c2a63d4bb780747a7a84dd169be79baf4c0c0ee3 | 650,571 |
def ignore_empty_keys(o: dict):
"""Removes keys with None-type values from the provided dict.
Used for JSON encoding to avoid schema errors due to empty or invalid parameters.
"""
return {k: v for (k, v) in o if v is not None} | a72fafa532779e231a1f5df93b868e3c1c23d4cd | 650,572 |
def get_annotationstatetype(layer_kws):
"""Get alpha values from the interface APIs."""
# This function gets alpha/transparency values.
layer_statetype = layer_kws.get("annotationstatetype", 'precomputed')
return layer_statetype | 565238a9a74dab22b75f14d8ecb4f6ba9a69f7d2 | 650,573 |
import re
def askStudentEmail():
"""
This function asks the user for their email address and validates input using a regex.
If the input does not match the specified format,
Parameters:
-------
email: str
Returns:
-------
email: str
Note:
The function wi... | 0ffb95ec2eddeeab7ea40b6d8bcee847cf85cb2b | 650,574 |
import sys
def only_test_in_python3(func):
"""A decorator that indicates a test should not execute in python 2.
For example, in python 2 repr('a') is "u'a'" instead of "'a'" when
from __future__ import unicode is present (which it will be, since 3to2
inserts it for us). This is annoying to work aroun... | 1d9881e88ea3921ea0d613dfe9aefad7c78eccd1 | 650,575 |
def interface(site_client, attributes, device, network):
"""
Return an Interface object.
Interface is bound to ``device`` with an address assigned from ``network``.
"""
device_id = device['id']
return site_client.sites(site_client.default_site).interfaces.post(
{
'name': 'et... | 7d401e71dde4142689b1a3a12833d03d14aebd43 | 650,576 |
def remove_comments(sql: str) -> str:
"""Remove comments from SQL script."""
# NOTE Does not strip multi-line comments.
lines = map(str.strip, sql.split("\n"))
return "\n".join(line for line in lines if not line.startswith("--")) | 8dfc5f082b59d88a45a8d7fa216553df6b117afa | 650,577 |
def getprofile(space):
"""Return the profiling function set with sys.setprofile.
See the profiler chapter in the library manual."""
w_func = space.getexecutioncontext().getprofile()
if w_func is not None:
return w_func
else:
return space.w_None | 688c8c5b33152bf8b8d0754fd16ec5edf2bc730b | 650,578 |
def skip(instance, action, peek=False, unskip=False):
"""Returns True if the transition is to be SKIPPED
peek - True just checks the value, does not set.
unskip - remove skip key (for manual overrides).
called with only (instance, action_id), this will set the request variable preventing the
... | 9bba64e2452623d26b564d570d3e385cbafed77a | 650,579 |
import math
def time_str(val):
""" Convert perfcounter difference to time string minutes:seconds.milliseconds """
return f"{math.floor(val / 60):02}:{math.floor(val % 60):02}.{math.floor((val % 1) * 100):02}" | 3b713aeb693c5d2e28788b7b85a78e634b036f84 | 650,580 |
def get_summary_extension(args):
""" Get the tags to include in the filename for the created summary. """
ext = ''
if args.fl and args.en and (args.ex != '0') and args.ae and (args.aa != 'n'):
ext = '-all'
else:
if args.fl:
ext = ext + '-fl'
if args.en:
ex... | 5b4963b1884903ce09fdd5cf94e5956b30addc28 | 650,581 |
from typing import Union
from typing import Callable
from typing import Optional
import yaml
def load_callable(obj: Union[str, Callable], prefix: Optional[str] = None) -> Callable:
"""Load a callable from a name, or pass through a callable."""
if callable(obj):
pass
elif isinstance(obj, str):
... | 0b9c3225e85347195af50ca7fef663c4369764ee | 650,582 |
def tissue_disease_mapping():
"""
Maps tissue types to words associated with cancers of that tissue
:return: Tissue / disease term mapping
:rtype: dict(str, list(str))
"""
return {
'Adrenal': ['adrenal', 'adrenocortical', 'cortical', 'oncocytic', 'myxoid'],
'Bladder': ['bladder'... | 6f9b26215c8b9d44361a85030ded77b9273799c4 | 650,583 |
def is_fullname_suffix(s):
""" Returns Trus if S is a full name suffix """
return s.upper().strip() in ['JUNIOR', 'SENIOR', 'JR', 'JR.', 'SR', 'SR.', 'DR', 'DR.', 'PHD', "PHD.", "SIR", "ESQ", "ESQ.", "I", "II", "III", "IV", "V", "VI", "1ST", "2ND", "3RD", "4TH", "5TH", "6TH"] | 73fbd91594a2ea923db9960cfeaf0b21a64a8510 | 650,584 |
import pickle
def load_pkl(file_path):
"""Load serialized model with pickle library.
Parameters
----------
file_path: str Path to the serialized model.
Returns
-------
Trained model object.
"""
with open(file_path, 'rb') as model:
clf = pickle.load(model)
return ... | edb4efb464a3e5ff79c40431c18bc2cc4a78271a | 650,585 |
def filtany(entities, **kw):
"""Filter a set of entities based on method return. Use keyword arguments.
Example:
filtany(entities, id='123')
filtany(entities, name='bart')
Multiple filters are 'OR'.
"""
ret = set()
for k,v in kw.items():
for entity in entities:
if getattr(entity, k)() ... | 6f29aaa02d86c00599af02971a3efe527a3e5722 | 650,586 |
def axis_helper(y_shape, x_shape):
"""
check which axes the x has been broadcasted
Args:
y_shape: the shape of result
x_shape: the shape of x
Return:
a tuple refering the axes
"""
res = []
j = len(x_shape) - 1
for i in range(len(y_shape) - 1, -1, -1):
if j... | 5475728cbad0d7e9851fd38137631dffae360a66 | 650,587 |
def process_output(mask):
"""task mask as input, compute the target for contrastive loss"""
(B, NP, B2, NS) = mask.size() # [B, P, B, N,]
target = (mask == 1).float()
target.requires_grad = False
return target, (B, B2, NS, NP) | a6be1e9abcf2eb3f531c95fe0f173b86deab2356 | 650,588 |
def tag_limit_sibling_ordinal(tag, stop_tag_name):
"""
Count previous tags of the same name until it
reaches a tag name of type stop_tag, then stop counting
"""
tag_count = 1
for prev_tag in tag.previous_elements:
if prev_tag.name == tag.name:
tag_count += 1
if prev_t... | 3b1f48e939c0ff772fc53a0bb7705d0a7a13ab0b | 650,589 |
import os
def _assemble_datasets(raw_obs, obs_list):
"""Get my datasets as dictionary keyed on Tier."""
# check for desired datasets only (if any)
# if not, walk all over rawobs dir
# assume a RAWOBS/TierX/DATASET input structure
datasets = {}
# get all available tiers in source dir
tiers... | 877b73da043bc7136d28e8cd6c8542886be5c257 | 650,590 |
import requests
import logging
def query_books_api(title):
"""
Queries the Google Books API to find detailed information about the book
with the given title.
"""
r = requests.get('https://www.googleapis.com/books/v1/volumes', params={
'q': title
})
try:
data = r.json()['it... | 565f517f09d535b628abefa63c3d882b6d774ffa | 650,591 |
import json
def serialize_cl_items(items):
"""Given a working dictionary of checklist items, turn them in to a json list
of item dicts sutable for saving"""
return json.dumps([x.toJSON() for x in items], indent=1) | abb8b7a2bcf65a2341769356cc1248afdfa79e5f | 650,593 |
def pixel_2_pytorch_locations(px_location, image_height, image_width):
"""
Converts the pixel locations in an image to the pytorch coordinate system of [-1, 1]
pixel_locations given in [width, height]
"""
pixel_locations = px_location.clone()
pixel_locations[:,0] = pixel_locations[:,0] / (image_... | c1ee67ae8dc661f66e2e5a9208ba9f3ef628d818 | 650,594 |
import re
def original_image_extender(pipeline_index,
finder_image_urls,
extender_image_urls=[],
*args, **kwargs):
"""
Example:
http://media-cache-ec0.pinimg.com/70x/50/9b/bd/509bbd5c6543d473bc2b49befe75f4c6.jpg
http:/... | 19c4c2f61cf027acbb5ffc75cd72bd2cc802cfab | 650,595 |
from typing import Optional
def to_camel(string: str) -> Optional[str]:
"""Convert snake_case to camelCase.
This does not strip punctuation or whitespace characters.
"""
if not isinstance(string, str):
return None
return ''.join(word.lower() if idx == 0 else
word.capit... | 7ced91a8befcac4fcd6e23217d42d0a1cfde7a82 | 650,596 |
def CopyObj(source,target):
"""
拷贝对象属性,排除数据库相关特性
:param source:
:param target:
:return: 负责完成属性的对象
"""
sourcedict = source.__dict__
# 去掉数据库对象
sourcedict.pop('_sa_instance_state')
for key in sourcedict:
if hasattr(target, key):
setattr(target, key, sourcedict[... | 527659a2d75c64302ad675a3e498c8c3059db692 | 650,597 |
import os
def find_hcp_tools():
"""
Returns the hcp pipeline tools path defined in the environment.
"""
try:
dir_hcp_tools = os.getenv('HCPPIPEDIR')
except:
dir_hcp_tools = None
return dir_hcp_tools | 96a7727f19332d2c370b78687b5b21a3dcc4e34f | 650,598 |
def from_question_name(name: str) -> str:
"""
Generates GIFT text for a question name.
Parameters
----------
name : str
Name of a question.
Returns
-------
out: str
GIFT-ready question name.
"""
return f'::{name}::' | 03bc0fc3f6b63e265fd0c75f070738ceaf2fe14d | 650,599 |
import math
def _compute_sphere_overlap(d, r1, r2):
"""
Compute volume overlap fraction between two spheres of radii
``r1`` and ``r2``, with centers separated by a distance ``d``.
Parameters
----------
d : float
Distance between centers.
r1 : float
Radius of the first spher... | 13fc42154e3b45868658a27bd94df539ffa480a1 | 650,601 |
import sympy
def solve(a, b, c):
""" Determine x valid value(s) for any Quadratic Equation
`ax² + bx + c = 0` where a, b, c are known values.
Returns a tuple of solutions (x1, x2)."""
if a == 0:
if b == 0:
return (None, None)
return (sympy.Rational(-c, b),None)
d = b*... | c92e22c1e9384fee916a032a20d2f92e7e8f7f90 | 650,602 |
def analysis_krn(analysis):
"""
Returns a dictionary of keywords by row.
This index can be used to quicky find a keyword by row.
'krn' stands for 'keyword row name'.
"""
return analysis.get("krn", {}) | a22d959d0f07126c59a19491e662999e30ebf9b0 | 650,603 |
def stream_socket_get_name(interp, w_res, remote):
""" Retrieve the name of the local or remote sockets"""
return w_res.get_name(remote) | 75069fb2689490b14661d9f88325f83e95b134b0 | 650,604 |
def error_running_file(filename, section, error):
"""returns a string in log format if a module errors out"""
file_error = "ty_error_running_file=%s" % (filename, )
section_error = "ty_error_section=%s" % (section, )
error_message = "ty_error_message=%r" % (error, )
return " ".join([
file_e... | dcc7bd1f8896111100f1f517e2ecfd27e2b67768 | 650,605 |
def qualify_raw_term(term):
"""Does some qualification on the unprocessed term.
"""
try:
if "__" in term:
return False
if "--" in term:
return False
except Exception:
return False
return True | c45b4a4489770bd12fd9d97a2da766085aea2182 | 650,606 |
def subsample_for_vis(eval_task_ids, tasks_per_template):
"""Keep only 1 task per template."""
templates_sel = {}
res = []
eval_task_ids = sorted(eval_task_ids) # For repro
for task_id in eval_task_ids:
this_temp = task_id.split(':')[0]
if this_temp not in templates_sel:
... | 10f73a204cfbb04e6d5964d89f394d4e735228b7 | 650,607 |
def CheckEolStyle(input_api, output_api, affected_files):
"""Verifies the svn:eol-style is set to LF.
Canned checks implementation can be found in depot_tools.
"""
sources = lambda x: affected_files
res = input_api.canned_checks.CheckChangeSvnEolStyle(
input_api, output_api, sources)
return res | 75448d4932cefd307b648587d2ffea7d30da9f73 | 650,608 |
def BuildVisibilityMatrix(Visibility, r_indx, print_enable=False):
"""To return Visibility matrix element
Args:
Visibility (array): Visibility Matrix
r_indx (images): Index of images
print_enable (bool, optional): To print the returning element
Returns:
TYPE: Element of mat... | 482ed947eb4401d3cc1e5165c8842bd7de7d25b6 | 650,609 |
def fragment_retrieval(coll, fields, fragment, case_sensitive = False):
"""Retrieves a list of all documents from the collection where the fragment
appears in any one of the given fields
Parameters
----------
coll: generator
The collection containing the documents
fields: iterable
... | 5bbab5fca5d747588408ede9039e0ce4774d19c1 | 650,611 |
def platform_parameters(parser):
""" K210 platform parameters """
parser.add_argument("--embed_gcc", type=str, default="",
help="The Kendryte RISC-V GNU Compiler Toolchain.")
parser.add_argument("--ext_tools", type=str, default="./platforms/plugin_k210/k_tools",
... | da4673dbcca4acece62686b27c44bce9616edcb8 | 650,612 |
def convert_dict_vals_to_str(dictionary):
"""Convert dictionary to format in uppercase, suitable as env vars."""
return {k.upper(): str(v) for k, v in dictionary.items()} | c397235c40fd187041e387d4c19d6e06d1a061d5 | 650,613 |
import random
def random_color():
"""
This function chooses a random color for the special stop sign.
:return str, the color for the special stop sign
"""
num = random.choice(range(9))
if num == 0:
return "dodgerblue"
elif num == 1:
return "azure"
elif num == 2:
... | f68d0a612381a7b6611023f21ce4834f1758e494 | 650,614 |
def getifname(sock):
"""Return interface name of `sock`"""
return sock.getsockname()[0] | b13fbc359ad5d3678ffd9a714737f16c7211da85 | 650,615 |
from typing import Dict
from typing import Set
def get_allowed_courses(conflict_graph: Dict[str, Set[str]], already_selected: Set[str], prohibited: Set[str]) -> Set[str]:
"""
Returns the set of courses in course_df that do not conflict with any course names in
already_selected, according to the graph conf... | 9c24891fc2baa19eef26f3887a2148ce1dd72dc6 | 650,616 |
import itertools
def aggr_events(events_raw):
"""Aggregates event vector to the list of compact event vectors.
Parameters:
events_raw -- vector of raw events
Returns:
events_aggr -- list of compact event vectors ([onset, offset, event])
"""
events_aggr = []
s = 0
for bi... | ffb5962df2e54b5d6508ac5325746a1d3b4e7c0b | 650,617 |
import os
def _create_list_bel_files(bel_path: str) -> list:
"""Export all BEL files in directory as list. If single file is passed, returns a list with that path."""
if os.path.isdir(bel_path):
bel_files = []
for file in os.listdir(bel_path):
if file.endswith(".bel"):
... | 721ea23fe2d72c7517cbc5b94249245df4eccb5e | 650,618 |
def filter_profile_sounds(profile, sounds):
"""
Returns relative paths to sounds that are the folder specified by the profile.
:param profile: Str
:param sounds: List of Str
:return: List of Str
"""
if profile:
filter_lambda = lambda sound: sound.startswith(profile + "\\")
else: ... | 22e0c2f24acf299354383c4967b94650bbdca35b | 650,619 |
import time
def current_timestamp():
"""
当前时间戳,精确到毫秒
:return:
"""
return int(time.time() * 1000) | a2739f3f18bafd360ab6337adc4e6ebe4760a968 | 650,620 |
def get_installed_tool_shed_repository( trans, id ):
"""Get a repository on the Galaxy side from the database via id"""
return trans.sa_session.query( trans.model.ToolShedRepository ).get( trans.security.decode_id( id ) ) | 0364430b6b174378791a07b6a1e086e668a60995 | 650,621 |
import requests
def ip_info():
"""
Makes a GET request using requests library to http://jsonip.com/ then dumps response
:return:
"""
# Make a request to external API (also try http://www.timeapi.org/utc/now, or any other REST API endpoint)
r = requests.get('http://jsonip.com/')
return r.t... | f50a5310f7d01a4c64b4cc79c1595fb653c33d28 | 650,622 |
from textwrap import dedent
def get_multiwigtrack_text(track_name, parent):
"""Create a multiWig track.
Example
track myMultiWig
container multiWig
aggregate transparentOverlay
showSubtrackColorOnUi on
type bigWig 0 1000
viewLimits 0:10
maxHeighPixels 100:32:8
track myFir... | 86e462260aa0dbfdfcee058c3531f43b9dd6e427 | 650,623 |
import platform
import os
def get_user_config_filename(appname):
"""
Get user config filename.
It will return operating system dependent config filename.
Parameters
----------
appname : string
An application name used for filename
Returns
-------
string
A filenam... | 09a66fa85800a82f120d87a83251fdb68b759aa4 | 650,624 |
import json
def _GetErrorExtraInfo(error_extra_info):
"""Serializes the extra info into a json string for logging.
Args:
error_extra_info: {str: json-serializable}, A json serializable dict of
extra info that we want to log with the error. This enables us to write
queries that can understand the ... | b1edfc2740dcbeba33ddd54581c6760babffb954 | 650,625 |
def end_game(_game):
"""
Will show a end game screen and thank the player.
Args:
_game: Current game state
Returns: Returns false to end game loop
"""
print("Thank you for playing")
return False | cc95a7bded80ac1840463bb2f462ee5f6b8fdf8e | 650,626 |
def parameter_changed(parameter):
"""Check whether parameter is in a pre-validation changed state.
Args:
arcpy.Parameter: Parameter to check.
Returns:
bool: True if changed, False otherwise.
"""
return all((parameter.altered, not parameter.hasBeenValidated)) | 837c7e92a71f7ff800140b93451cb9435e1ecf33 | 650,627 |
def reset_encoding(str_):
"""
:param str_: str;
:return: str;
"""
return str_.replace(u'\u201c', '"').replace(u'\u201d', '"') | 808eb42cb1f0bb7249002770d20eb6bcb490134d | 650,628 |
import os
def setup_reg_paths(paths: dict, settings: dict) -> tuple[dict, dict]:
"""
This function sets up the appropriate paths for the
CT coregistration module. It gets run even if the module
is skipped to ensure all paths are properly stored.
"""
# Define appropriate directory
ct_regis... | c7500591bd1da5fa3e15688f60357b9634035279 | 650,629 |
from typing import Set
from typing import List
from typing import Dict
def deduped_actions(actions: Set[str]) -> List[str]:
"""Return a sorted list of all the unique items in `actions`, ignoring case."""
# First, group all actions by their lowercased values. This lumps "foo" and "FOO" together.
unique: D... | 4c5a0ee2c1bcb86f5c26b9d5a20d3293befce0fd | 650,631 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.