content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calculate_linear_classifier_output_shapes(operator):
"""
This operator maps an input feature vector into a scalar label if
the number of outputs is one. If two outputs appear in this
operator's output list, we should further generate a tensor storing
all classes' probabilities.
Allowed inpu... | 17,400 |
def npm_package_bin(tool = None, package = None, package_bin = None, data = [], outs = [], args = [], output_dir = False, **kwargs):
"""Run an arbitrary npm package binary (e.g. a program under node_modules/.bin/*) under Bazel.
It must produce outputs. If you just want to run a program with `bazel run`, use th... | 17,401 |
def get_mask_results(probs, boxes, im_w, im_h, pixil_score_th=0.25):
"""
Args:
probs (Tensor)
boxes (ImageContainer)
Returns:
rles (list[string])
mask_pixel_scores (Tensor)
"""
device = probs.device
N, _, H, W = probs.shape
num_chunks = N if device.type == "... | 17,402 |
def openapi() -> Dict[str, Any]:
"""
>>> client = app.test_client()
>>> response = client.get("/openapi.json")
>>> response.get_json()['openapi']
'3.0.0'
>>> response.get_json()['info']['title']
'Chapter 13. Example 2'
"""
# See dominoes_openapi.json for full specification
return... | 17,403 |
def get_config_keys(config, prefix):
"""Get configuration options matching given prefix"""
for key, value in config.items():
if key.startswith(prefix):
yield key[len(prefix):].upper(), value | 17,404 |
def koliko_izdelkov_v_skladiscu():
"""
Vrne stevilo razlicnih izdelkov v skladiscu.
>>> koliko_izdelkov_v_skladiscu()
18
"""
poizvedba = """
SELECT COUNT(*)
FROM izdelki
WHERE kolicina IS NOT null
"""
st, = conn.execute(poizvedba).fetchone()
return st | 17,405 |
def create_spline(curve_data, s_type='NURBS', len_nodes=100, spline_id=0, splines_count=1, bud_position=None):
"""
Create a spline of given type with n nodes to form a path made of sin and cos
"""
spline = curve_data.splines.new(type=s_type)
# Regular spline points need xyz + weight
got_poi... | 17,406 |
def _check_dir(repository_ctx, directory):
"""Checks whether the directory exists and fail if it does not"""
if not repository_ctx.path(directory).exists:
_auto_configure_fail("Cannot find dir: %s" % directory) | 17,407 |
def getImgN(path):
"""
入力されたフォルダにある画像を全て読み込む
[in] path:
[out] 読みこんだ画像リスト
"""
if not os.path.isdir(path):
print('path not found:', path)
exit(1)
from os.path import join as opj
return np.array([cv2.imread(opj(path, f), IMG.getCh(0))
for f in os.listd... | 17,408 |
def split(
texts_path,
summaries_path,
target_dir=Path("."),
ratio=TRAIN_VAL_TEST_SPLIT,
):
"""
Splits texts and summaries on train/test
Args:
texts_path: path to the file with texts
summaries_path: path to the file with summaries
target_dir: dir to save splitte... | 17,409 |
def get_composed_jumps(jumps, levels, win, verbose=0):
"""
Take the output of get_jumps (from landmarks)
Compose the jumps, return them as an array of array.
If intermediate=True, we return the jumps for intermediary levels,
not just the requested one.
We use a temporary sqlite3 connection to wo... | 17,410 |
def calculate_agreement_stv(agreement_dictionary, turker_accuracies):
"""
Inter agreement with most accurate chair vote
Args:
agreement_dictionary: holding sentence annotation records - 9 from non-experts and 1 expert
sentence -> list of annotations (size settings.RESPONSE_COUNT + 1)
... | 17,411 |
def count_num_peps(filename):
"""
Count the number of peptide sequences in FASTA file.
"""
with open(filename) as f:
counter = 0
for line in f:
if line.startswith(">"):
counter += 1
return counter | 17,412 |
def get_variables(examples):
"""Convert a code string to a list of variables.
We assume a variable is a 'word' with only alphanumeric characters in it."""
variables = [" ".join(re.split(r"\W+", text)) for text in examples["text"]]
return {"variables": variables} | 17,413 |
def _stored_data_paths(wf, name, serializer):
"""Return list of paths created when storing data"""
metadata = wf.datafile(".{}.alfred-workflow".format(name))
datapath = wf.datafile(name + "." + serializer)
return [metadata, datapath] | 17,414 |
def output_0_to_label_click(n):
"""
output_0_label click handler
Goes to first step of the output.
"""
if output_0_label['cursor'] == 'fleur':
load_output_step(n) | 17,415 |
def ascii_to_walls(char_matrix):
"""
A parser to build a gridworld from a text file.
Each grid has ONE start and goal location.
A reward of +1 is positioned at the goal location.
:param char_matrix: Matrix of characters.
:param p_success: Probability that the action is successful.
:param see... | 17,416 |
def test_opening_pickles():
"""Pickle open ok?"""
for n in [3, 4, 5]:
yield check_pickle_opened, n | 17,417 |
def save_to_hdf5(db_location, patches, coords, file_name, hdf5_file):
""" Saves the numpy arrays to HDF5 files. A sub-group of patches from a single WSI will be saved
to the same HDF5 file
- db_location folder to save images in
- patches numpy images
- coords ... | 17,418 |
def mock_sd(nresp=1):
"""Fake Stackdriver Monitoring API response for the ListTimeSeries endpoint.
Args:
nresp (int): Number of responses to add to response.
Returns:
ChannelStub: Mocked gRPC channel stub.
"""
timeserie = load_fixture('time_series_proto.json')
response = {'next... | 17,419 |
def cohesion_separation(chroms, doc):
"""Measure balancing both cohesion and separation of clusters."""
coh = cohesion(chroms, doc)
sep = separation(chroms, doc)
return (1 + sigmoid(coh)) ** sep | 17,420 |
def shellCall(shellCmd, stdin='', stderr=False, env=None, encoding=None):
"""Call a single system command with arguments, return its stdout.
Returns stdout, stderr if stderr is True.
Handles simple pipes, passing stdin to shellCmd (pipes are untested
on windows) can accept string or list as the first ar... | 17,421 |
def get_number_location(
input : str,
):
# endregion get_number_location header
# region get_number_location docs
"""
get the string indices of all numbers that occur on the string
format example: [ ( 0, 1 ), ( 4, 6 ), ( 9, 9 ) ]
both begin and end are inclusive, in contrast with the way the s... | 17,422 |
def update_object(obj, new_values):
"""update an object attributes from a supplied dictionary"""
# avoiding obj.__dict__.update(new_values) as it will set a new attribute if it doesn't exist
for k, v in new_values.items():
if hasattr(obj, k):
try:
setattr(obj, k, v)
... | 17,423 |
async def luck_cownd(client, message):
""" /luck an @animatedluck """
rep_mesg_id = message.message_id
if message.reply_to_message:
rep_mesg_id = message.reply_to_message.message_id
await client.send_dice(
chat_id=message.chat.id,
emoji=TRY_YOUR_LUCK,
disable_notification... | 17,424 |
def subpathNeedsRefresh(modTimes, ufoPath, *subPath):
"""
Determine if a file needs to be refreshed.
Returns True if the file's latest modification time is different
from its previous modification time.
"""
previous = modTimes.get(subPath[-1])
if previous is None:
return True
lat... | 17,425 |
def resxy_(x: float, y: float, /) -> Resolution:
"""Construct resolution from X,Y order."""
return Resolution(x=x, y=y) | 17,426 |
def copy_static_files(template_dir_path, dst_dir_path):
"""Copies the static files used by the resulting rendered site
Arguments:
template_dir_path -- path to the template directory
dst_dir_path -- destination directory
"""
subdirectories = ['/css', '/js', '/img']
for subdirectory in s... | 17,427 |
def group_toggle_modules(request, group):
"""Enable or disable modules.
"""
if request.method != 'POST':
raise Http404
referer = request.META.get('HTTP_REFERER', None)
next = SITE_ROOT if referer is None else referer
username = request.user.username
group_wiki = request.POST.ge... | 17,428 |
async def set_key_metadata(wallet_handle: int,
verkey: str,
metadata: str) -> None:
"""
Creates keys pair and stores in the wallet.
:param wallet_handle: Wallet handle (created by open_wallet).
:param verkey: the key (verkey, key id) to store metada... | 17,429 |
def bilinear_sampler(imgs, coords):
"""
Construct a new image by bilinear sampling from the input image.
Args:
imgs: source image to be sampled from [batch, height_s, width_s, channels]
coords: coordinates of source pixels to sample from [batch, height_t,
Returns:
A new sampled im... | 17,430 |
def wrap_array(typingctx, data_ptr, shape_tup):
"""create an array from data_ptr with shape_tup as shape
"""
assert isinstance(data_ptr, types.CPointer), "invalid data pointer"
assert (isinstance(shape_tup, types.UniTuple)
and shape_tup.dtype == np.intp), "invalid shape tuple"
dtype = da... | 17,431 |
def change(port, password, limit):
"""修改用户"""
port, password, limit = str(port), str(password), str(limit)
ret = subprocess.check_output([SS_ADMIN, 'change', port, password, limit], stderr=subprocess.STDOUT)
return ret | 17,432 |
def reshape_resting_ecg_to_tidy(
sample_id: Union[int, str], folder: Optional[str] = None, tmap: TensorMap = DEFAULT_RESTING_ECG_SIGNAL_TMAP,
) -> pd.DataFrame:
"""Wrangle resting ECG data to tidy.
Args:
sample_id: The id of the ECG sample to retrieve.
folder: The local or Cloud Storage folder under wh... | 17,433 |
def geometric_project_derivatives(
molecule: Molecule,
conformer: torch.Tensor,
internal_coordinates_indices: Dict[str, torch.Tensor],
reference_gradients: torch.Tensor,
reference_hessians: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""A helper method to project a set of gradients and... | 17,434 |
def api_get_script(request):
"""POST - Frida Get Script."""
if not request.POST.getlist('scripts[]'):
return make_api_response(
{'error': 'Missing Parameters'}, 422)
resp = tests_frida.get_script(request, True)
if resp['status'] == 'ok':
return make_api_response(resp, 200)
... | 17,435 |
def is_valid_slug(slug):
"""Returns true iff slug is valid."""
VALID_SLUG_RE = re.compile(r"^[a-z0-9\-]+$")
return VALID_SLUG_RE.match(slug) | 17,436 |
def KMeans_GPU(x, K=10, Niter=10, verbose=True):
"""Implements Lloyd's algorithm for the Euclidean metric."""
start = time.time()
N, D = x.shape # Number of samples, dimension of the ambient space
c = x[:K, :].clone() # Simplistic initialization for the centroids
x_i = LazyTensor(x.view(N, 1, D... | 17,437 |
def make_flat_roof(bm, faces, thick, outset, **kwargs):
"""Create a basic flat roof
Args:
bm (bmesh.types.BMesh): bmesh from current edit mesh
faces (bmesh.types.BMFace): list of user selected faces
thick (float): Thickness of the roof
outset (float): How mush the roof overhangs... | 17,438 |
def make_comma_separated_list_fiter(filter_name, field_expression):
"""
Create a filter which uses a comma-separated list of values to filter the queryset.
:param str filter_name: the name of the query param to fetch values
:param str field_expression: the field expression to filter the queryset, like ... | 17,439 |
def get_dashboard(id_, token_info=None, user=None):
"""Get a single dashboard by ID
:param id: ID of test dashboard
:type id: str
:rtype: Dashboard
"""
dashboard = Dashboard.query.get(id_)
if not dashboard:
return "Dashboard not found", 404
if dashboard and dashboard.project an... | 17,440 |
def get_recorder(execution_cmd, ml_names):
"""
The helper function for generating a recorder object
"""
if not execution_cmd.record_progress:
return DummyRecorder()
root_dir_path = Path(__file__).parent.parent
log_dir_path = root_dir_path.joinpath(
"games", execution_cmd.game_na... | 17,441 |
def eval_epoch(data_iterator, model, optimizer, args,
update=False,
log_split='',
split_name='',
n_iter=0,
epoch=0,
writer=None,
sample_path='',
debug=0,
verbose=False,
o... | 17,442 |
def get_customer_key():
""" Reutrn the key of the sample customer from file """
customer_file = open("sample_customer", "r")
customer_key = customer_file.readline().rstrip("\n")
customer_file.close()
return customer_key | 17,443 |
def init_db() -> None:
"""Initialize database."""
connection = get_db()
with current_app.open_resource("schema.sql") as schema:
connection.executescript(schema.read().decode("utf8")) | 17,444 |
def main() -> None:
"""Main function that sets up game and runs main game loop"""
game_resources = GameResources(testing, bless, path)
information = Information(game_resources)
game_resources.draw()
game_panel = Panel(game_resources.level.to_string())
layout = PanelLayout.make_layout(start=Fals... | 17,445 |
def tau_tex(tex, tau0_):
"""
Eq. (15) Goldsmith et al. (2012)
"""
g = gu/gl
return tau0_*(1. - np.exp(-tstar/tex))/(1. + g*np.exp(-tstar/tex)) | 17,446 |
def cached(f):
"""Decorator to cache result of property."""
@wraps(f)
def inner(self):
name = '_{}'.format(f.__name__)
if getattr(self, name, None) is None:
setattr(self, name, f(self))
return getattr(self, name)
return inner | 17,447 |
def thesaurus(*args, sort=False) -> dict:
"""Формирует словарь, в котором ключи — первые буквы слов,
а значения — списки, содержащие слова, начинающиеся с соответствующей буквы
:param *args: перечень слов
:param sort: признак необходимости сортировки словаря по алфавиту (True - сортировать, False - не ... | 17,448 |
def calculate_ranking(imbalanced_results):
"""Calculate the ranking of oversamplers for
any combination of datasets, classifiers and
metrics."""
wide_optimal = calculate_wide_optimal(imbalanced_results)
ranking_results = wide_optimal.apply(
lambda row: _return_row_ranking(
row[3:... | 17,449 |
def extract鏡像翻訳(item):
"""
Parser for '鏡像翻訳'
"""
if 'anime' in str(item['tags']).lower():
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [
('sodachi fiasco', 'Orokamonogatari - ... | 17,450 |
def config(live_server, django_user_model):
"""Create a user and return an auth_token config matching that user."""
user = django_user_model.objects.create(
email='jathan@localhost', is_superuser=True, is_staff=True
)
data = {
'email': user.email,
'secret_key': user.secret_key,
... | 17,451 |
def test_failure_immutable_copy():
"""Ensures that Failure returns it self when passed to copy function."""
nothing = _Nothing()
assert nothing is copy(nothing) | 17,452 |
def combine_data_by_key(
combined_outputs: Dict[str, Union[List[Any], Any]],
output: Dict[str, Union[List[Any], Any]],
) -> Dict[str, Union[List[Any], Any]]:
"""
Combine lists in two multimaps
Args:
combined_outputs: Initial multimap to combine, presumably already combined
output: N... | 17,453 |
def arango_connection() -> ArangoClient:
"""Connecting to arango."""
host = os.getenv("ARANGO_HOST")
port = os.getenv("ARANGO_PORT")
arango_client = ArangoClient(hosts=f"http://{host}:{port}")
return arango_client | 17,454 |
def default_scores(X_train, y_train, X_val, y_val):
"""
"""
svc_model = LinearSVC(random_state=0).fit(X_train,y_train)
y_pred = svc_model.predict(X_val)
print 'SVC loss:',cost_score(y_pred,y_val)
rf_model = RandomForestClassifier(random_state=0).fit(X_train,y_train)
y_pred = rf_model.predict(X_val)
print '... | 17,455 |
def in_bazel() -> bool:
"""Return whether running under bazel."""
return os.environ.get("TEST_WORKSPACE", "") != "" | 17,456 |
def run_batch(args, batch_name=None):
"""Wrapper around creating, running, and then closing a Batch run.
:param args: Parsed args from the ArgumentParser created via the init_arg_parser method
:param batch_name: (optional) batch label which will show up in the Batch web UI
Usage:
with run_batc... | 17,457 |
def acceptCode(request):
"""Redeems a code to accept invitation cash"""
params = request.get_params(schemas.AcceptCodeSchema())
device = get_device(request)
customer = device.customer
access_token = get_wc_token(request, customer)
postParams = {
'code': params['code']
}
response ... | 17,458 |
def update_integration_response(ApiId=None, ContentHandlingStrategy=None, IntegrationId=None, IntegrationResponseId=None, IntegrationResponseKey=None, ResponseParameters=None, ResponseTemplates=None, TemplateSelectionExpression=None):
"""
Updates an IntegrationResponses.
See also: AWS API Documentation
... | 17,459 |
def log_performance(item, value):
"""
do print performance with pre-defined format to console
:param item: performance item name
:param value: performance value
"""
performance_msg = "[Performance][{}]: {}".format(item, value)
Utility.console_log(performance_msg, "orange")
# update to j... | 17,460 |
def _find_available_share_drive_letter(share_ignores: List[str] = None) -> str:
"""Find an available drive letter for a share.
This function iterates backwards through the ASCII uppercase letters trying
and checks them against the current net use drive mappings. Once it finds
an available drive letter... | 17,461 |
def integrate(sde=None, *, q=None, sources=None, log=False, addaxis=False):
"""Decorator for Ito Stochastic Differential Equation (SDE)
integration.
Decorates a function representing the SDE or SDEs into the corresponding
``sdepy`` integrator.
Parameters
----------
sde : function
F... | 17,462 |
def write_generate_component(file_ptr):
"""Write generate statements in VHDL code."""
file_ptr.write("\t a_s <= std_ulogic_vector(resize(unsigned(a_i), a_s'length));\n")
file_ptr.write("\t b_s <= std_ulogic_vector(resize(unsigned(b_i), b_s'length));\n\n")
file_ptr.write("\t GEN_INPUT_A: for i in 0 to X-... | 17,463 |
def calculate_statistical_inefficiency_runs(traj_l):
"""
Using fast autocorrelation calculation to estimate statistical inefficiency. This code wraps
a function from pymbar.
References
----------
[1] Shirts MR and Chodera JD. Statistically optimal analysis of samples from
multiple e... | 17,464 |
def dataio_prep(hparams):
"""Creates the datasets and their data processing pipelines"""
# 1. define tokenizer and load it
modelpath = download_to_dir(hparams["tok_mdl_file"], hparams["save_folder"])
download_to_dir(hparams["tok_voc_file"], hparams["save_folder"])
tokenizer = SentencePiece(
... | 17,465 |
def get_superlative_type(question_normal):
"""What TV series was Mark Harmon the star of that ran the least amount of time on TV ?"""
result = 'argmax'
question_normal = question_normal.lower()
superlative_serialization_list = superlative_serialization(question=question_normal)
for element in superl... | 17,466 |
def coord_net_spec(ks=3, stride=1, pad=0, pool=2, dstride=2, dpad=0):
"""
Define net spec for simple conv-pool-deconv pattern common to all
coordinate mapping tests.
"""
n = caffe.NetSpec()
n.data = L.Input(shape=dict(dim=[2, 1, 100, 100]))
n.aux = L.Input(shape=dict(dim=[2, 1, 20, 20]))
... | 17,467 |
def note_favorite(note):
"""
get the status of the note as a favorite
returns True if the note is marked as a favorite
False otherwise
"""
if 'favorite' in note:
return note['favorite']
return False | 17,468 |
def _crossproduct(template: CheckListTemplate):
"""
Takes the output of editor.template and does the cross product of contexts and qas
"""
ret = []
ret_labels = []
for instance in template.data:
cs = instance["contexts"]
qas = instance["qas"]
d = list(itertools.product(cs... | 17,469 |
def test_enqueue15(client):
"""Tests enqueue stores IP Address for request using request address as fallback."""
pytest.skip("Not implemented") | 17,470 |
def thread(function):
"""Runs the decorated function within a concurrent thread,
taking care of the result and error management.
Decorated functions will return a concurrent.futures.Future object
once called.
"""
@wraps(function)
def wrapper(*args, **kwargs):
future = Future()
... | 17,471 |
def collapse_range(arg, value_delimiter=',', range_delimiter='-'):
"""
Collapses a list of values into a range set
:param arg: The list of values to collapse
:param value_delimiter: The delimiter that separates values
:param range_delimiter: The delimiter that separates a value range
:return: ... | 17,472 |
def test_number_of_channel_avg_mapping_tuples():
"""
Verify that FSPConfiguration fails if there are an invalid number of
entries in the channel average mapping argument.
Since this test was originally written we allow fewer than 20 entries
"""
# create a partially applied sn.FSPConfiguration co... | 17,473 |
def compute_diag_mog_params(M=int(4), snr=3.):
"""Returns diagonal mixture of Gaussian target distribution settings for d=2
Args:
M: (Optional) Integer, number of components
snr: (Optional) Scaling of the means
"""
d = int(2)
weights = np.ones(M)
weights /= np.sum(weights)
... | 17,474 |
def has_ifm2(npu_op: NpuBlockOperation) -> bool:
"""Checks if op has non-scalar IFM2"""
return npu_op.ifm2 is not None and npu_op.ifm2_scalar is None | 17,475 |
def ilsvrc_fix_args(args):
"""
Update the args with fixed parameter in ilsvrc
"""
args.ds_name="ilsvrc"
args.num_classes == 1000
# GPU will handle mean std transformation to save CPU-GPU communication
args.do_mean_std_gpu_process = True
args.input_type = 'uint8'
args.mean = get_a... | 17,476 |
def get_mock_adapter() -> Adapter:
"""Get a requests-mock Adapter with some URLs mocked by default"""
adapter = Adapter()
adapter.register_uri(
ANY_METHOD,
MOCKED_URL,
headers={'Content-Type': 'text/plain'},
text='mock response',
status_code=200,
)
adapter.reg... | 17,477 |
def ext_force_bend_from_input(ext_force_bend_list, o_molsys):
"""
Creates bend coordinate with external force
Parameters
----------
ext_force_bend_list : list
each entry is a list of 3 atoms (indexed from 1), followed by a formula
o_molsys : molsys.Molsys
optking molecular system... | 17,478 |
def eqtls_weights_summing(eqtl_occurrence_log_likelihood, ens_gene_id, target_species_hit, converted_eqtls, gtex_weights_dict, chr_start, chr_end, gtex_variants, tf_len, gene_len):
"""
Identify if any of the eQTLs associated with this gene overlap this predicted TFBS.
Retrieve the log-likelihood scores for ... | 17,479 |
def get_file_chunks_in_range(context, filediff, interfilediff,
first_line, num_lines):
"""
A generator that yields chunks within a range of lines in the specified
filediff/interfilediff.
This is primarily intended for use with templates. It takes a
RequestContext for lo... | 17,480 |
def urlread(url):
"""Return the contents of a url. Raises IOError if couldn't read url."""
try:
urlfile = urllib.request.urlopen(url)
return urlfile.read()
except IOError as e:
print("[!] Error reading url:", url)
print(e.message)
sys.exit(1) | 17,481 |
def parse_metric(y_train, goal):
"""
Parse the metric to the dictionary
"""
y_array = np.array(y_train, dtype=np.float64)
if goal == api_pb2.MINIMIZE:
y_array *= -1
return y_array | 17,482 |
def erfc(x):
"""Complementary error function (via `http://bit.ly/zOLqbc`_)"""
z = abs(x)
t = 1. / (1. + z / 2.)
r = t * math.exp(-z * z - 1.26551223 + t * (1.00002368 + t * (
0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (
0.27886807 + t * (-1.13520398 + t * (1.48851587 + t *... | 17,483 |
def request_until_success(url, max_attempts=5, wait=5):
"""Makes a request a few times in case of a 500 error.
Should use exponential backoff?
"""
req = urllib.request.Request(url)
success = False
num_tries = 0
while not success:
try:
num_tries += 1
... | 17,484 |
def uuid(name, value) -> "Optional[str]":
"""Validate that the value is a UUID
Args:
name (str): Name of the argument
value (any): A UUID string value
Returns:
The value, or None if value is None
Raises:
InvalidParameterValue: if the value is not a valid UUID
"""
... | 17,485 |
def _encode_object_json_aided(obj, name, zipfile):
"""
Encodes composed objects with the help of JSON.
Parameters
----------
obj: PyFar-type
The object, usually values from **objs, see `io.write`.
name: str
The object's name, usually keys from **objs, see `io.write`.
zipfile... | 17,486 |
def expandall(text):
"""
Search for abbreviations in text using re_abbr (defined in utils.get_res).
For each abbreviation, find likely full term. Replace each instance of the
abbreviation in the text with the full term.
Parameters
----------
text : str
Text to search for abbreviatio... | 17,487 |
def get_source_fields(client, source_table):
"""
Gets column names of a table in bigquery
:param client: BigQuery client
:param source_table: fully qualified table name.
returns as a list of column names.
"""
return [f'{field.name}' for field in client.get_table(source_table).schema] | 17,488 |
def has_user_based_permission(obj, user, allow_superuser=True, allow_staff=False):
"""
Based on obj.get_user(), checks if provided user is that user.
Accounts for superusers and staff.
"""
if hasattr(obj, "get_user"):
obj_user = obj.get_user()
# User is logged in
if user.is... | 17,489 |
def trace_stack_top(trace_stack_var: ContextVar) -> Optional[Any]:
"""Return the element at the top of a trace stack."""
trace_stack = trace_stack_var.get()
return trace_stack[-1] if trace_stack else None | 17,490 |
def fbconnect():
"""This allows users to use facebook account to sign in."""
if request.args.get("state") != login_session["state"]:
response = make_response(json.dumps("Invalid state parameter."), 401)
response.headers["Content-Type"] = "application/json"
return response
access_toke... | 17,491 |
def _get_current_task():
"""
Stub to make it easier to test without actually running Celery.
This is a wrapper around celery.current_task, which provides access
to the top of the stack of Celery's tasks. When running tests, however,
it doesn't seem to work to mock current_task directly, so this wr... | 17,492 |
def init_module_(module, method, **kwargs):
"""
Initialize a module using the specified method.
Args:
module (:obj:`nn.Module`): The module to be initialized.
method (str): The initialization method. Expected methods include
``'constant'``, ``'normal'``, ``'uniform'``, ``'xavier... | 17,493 |
def naiveMP(tsA, m, tsB=None):
"""
Calculate the Matrix Profile using the naive all-pairs calculation.
Parameters
----------
tsA: Time series containing the queries for which to calculate the Matrix Profile.
m: Length of subsequence to compare.
tsB: Time series to compare the query ... | 17,494 |
def markdown_list(
handle: Jira,
jql_text: str,
column_fields=None,
list_type: str = 'ul',
data: Mapping[str, Union[object, Iterable, Sized]] = None,
) -> str:
"""Yes we can ... document later."""
if data is None:
data = query(handle, jql_text, column_fields)
if data.get('error',... | 17,495 |
def render_html(data):
"""
"""
data.setdefault('domain', DOMAIN)
template = '''
<table border="1" cellspacing="0" cellpadding="0">
<tr><td>类型</td><td>{type}</td></tr>
<tr><td>团队</td><td>{team}</td></tr>
<tr><td>项目</td><td>{project}</td></tr>
<tr><td>名称</td><td>{n... | 17,496 |
def docs(session: Session) -> None:
"""Build and serve the documentation with live reloading on file changes."""
args = session.posargs or ["--open-browser", "docs", "docs/_build"]
session.install(".")
session.install("sphinx", "sphinx-autobuild", "sphinx-click", "furo", "sphinx-inline-tabs")
build... | 17,497 |
def segment_cells(image, max_cell_size):
"""Return segmented cells."""
image = identity(image)
wall = threshold_adaptive_median(image, block_size=101)
seeds = remove_small_objects(wall, min_size=100)
seeds = dilate_binary(seeds)
seeds = invert(seeds)
seeds = remove_small_objects(seeds, min_... | 17,498 |
def encrypt(message, key):
"""
>>> encrypt("Hello world",12)
'Tqxxa iadxp'
>>> encrypt("We are Penn State!!!",6)
'Ck gxk Vktt Yzgzk!!!'
>>> encrypt("We are Penn State!!!",5)
'Bj fwj Ujss Xyfyj!!!'
>>> encrypt(5.6,3)
'error'
>>> encrypt('Hello',... | 17,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.