content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def check_id_username(userid, pdpath):
"""
Check blobs for usernames in primary.docobjects
:param userid:
:param pdpath:
:return:
"""
check = checkPD(userid, pdpath)
if check != "":
return check
else:
pass | 797bd4edd5f6d19c0d02d928a7091cb70be9ac77 | 62,715 |
def check_def_has_docstring(def_docstring, context, is_script):
"""Exported definitions should have docstrings.
...all functions and classes exported by a module should also have
docstrings. Public methods (including the __init__ constructor)
should also have docstrings.
"""
if is_script:
... | d9bb7ff278102e78505d77b28eb42010d7a13338 | 62,716 |
def full_service_acct_email(account_id, project_id):
"""Generate the full service account email.
Args:
account_id (str): The service account id, i.e. the part before
the "@".
project_id (str): The project id the service account belongs to
Returns:
str: The full service ... | 42c55bb0e813830d406110cba833b2d49d0b224e | 62,717 |
def pre_process(iid, image):
"""Data augmentation function."""
image = image.transpose((1, 2 ,0))
if not isinstance(image, Image.Image):
image = Image.fromarray(image)
image_size = cfg.img_shape
image, image_size = _infer_data(image, image_size)
return {
'x': Tensor(image),
... | 23684df73709a18b232112e0f0dce432aed5d63d | 62,718 |
def update_youth_profile(input, youth_profile, staff_update=False) -> YouthProfile:
"""Update the given youth profile.
:param staff_update: Calling user has manage permission on youth membership service.
"""
contact_persons_to_create = input.pop("add_additional_contact_persons", [])
contact_persons... | 7ae12a21ead9b49b612d0dc786ff96b4212617a6 | 62,719 |
def hello():
""" Return a greeting.
"""
return "Greetings from Python!" | 871175e50ee4e2d2ebd33829f1dff568cdfd0bb7 | 62,720 |
from typing import Callable
from typing import NamedTuple
def get_market_value() -> Callable[[str], NamedTuple]:
""" 获取上市公司的最近交易日的市值和相关信息
Precondition
=====================================================================================================
../data/jq.db 存在
jq.db中存在'market_value'表,其内容... | 5fb47eb25bc20608125535190f5ad6d3065e3b30 | 62,721 |
def dump(txblkhash):
"""
/dump/<hash> return state dump after transaction or block
"""
try:
blk = chain_manager.get(txblkhash.decode('hex'))
except:
try: # index
test_blk, tx, i = _get_block_before_tx(txblkhash)
except (KeyError, TypeError):
re... | 967a30707c2bb21a3420cbed3ebeabc2b6c5f76c | 62,723 |
def split_byte(x):
"""Split byte into groups of bits: (2 bits, 3 bits, 3 bits)"""
return x >> 6, x >> 3 & 7, x & 7 | 7743fdf78c201dce66803ae0eb62cbdf58cccc7d | 62,728 |
def total_histogram_diff(pixel_diff):
"""
Sums up all histogram values of an image. When used with the black/white pixel-diff image
this gives the difference "score" of an image.
:param pixel_diff: the black/white image containing all differences (output of imagecompare.pixel_diff function)
:return... | 93675cafcb82513513ddd5d078ab91e36c52de27 | 62,729 |
def predict_genre_prob(img_file):
""" Given an image file, returns the top five genre predictions and their
percent confidence. """
prediction = genre_learn.predict(open_image(img_file))
probs_list = prediction[2].numpy()
# format and round results
probs_dict = {
c: probs_list[i] for (i,... | 413518f08a8d9a24de5857290805272717b69f20 | 62,730 |
def shared_nx_struct_data():
"""
Return a tuple of shared probes. The second is a
nx_varied_struct_t rebinding.
"""
return (loader.lookup("ProbeTestC$nx_struct_data").bind(1),
loader.lookup("ProbeTestC$nx_struct_data",
["", "nx_varied_struct_t"]).bind(1)) | 0e1bffa7a877525e0ad3299c96b23950ee52b4eb | 62,731 |
def _counts_to_probs(counts, foll_gids, trial_count, adjust_missing):
"""
Normalise the number of times a follower takes a particular rank over all trials.
Because not all followers fire on all trials, high-rank values are typically empty.
This gives them a very low entropy.
In Hemberger 2019 they ... | c94d73324b73657213c5849173e20dac7d2dbe7b | 62,732 |
import requests
import json
def send_request(sub_url, data):
"""
Send a POST request with form-data to a given sub-URL and retrieve the JSON response.
Throws a RuntimeError if there was an error while submitting
:param sub_url: Sub-URL to send the POST request to
:param data: Data dictionary that... | 8a40d5abf91463b439b3606a4b025795418b2db7 | 62,733 |
def resolve_partitions(patterns):
"""
Given a list of patterns, returns all the files matching or in folders matching
one of them.
The file are returned in a list of tuple of 2 elements:
- The first tuple is the file path
- The second being the partition keys and values if any were encountered ... | 1e3292235b79e3fdf3a89f0bbc50e3e428e589d3 | 62,734 |
def get_palette(categories, cmap):
"""
Generate dictionary mapping categories to color.
"""
cc = plt.get_cmap(cmap)
if len(categories) > len(cc.colors):
raise ValueError("Number of categories more than number of colors in cmap.")
palette = {x: cc(i) for i, x in enumerate(categories)}
... | 20e5ea98e126df87dfcc18db368976851514bd13 | 62,735 |
import logging
def geocoded_hitlist_cache(key,couple_key,update=False):
"""Get a list of eatery entities that have been geocoded"""
geocoded_hitlist = memcache.get(key)
if not geocoded_hitlist or update:
geocoded_hitlist = []
hitlist_keys = hitlist_cache("Hitlist|" + str(couple_key... | 8ee899dae9aef297203d87f42f7b82bbe6fd6c3e | 62,736 |
def random_std(loc, scale):
"""
Draws a random std from a gaussian distribution with mean ``loc`` and std ``scale``.
"""
def wrapper():
return np.clip(np.random.normal(loc=loc, scale=scale), np.finfo(float).eps, np.inf)
return wrapper | 2cc33df0f8ba6e8639676446c08a0afa615e8cc5 | 62,737 |
from typing import Sequence
def isin(
arg: ir.ValueExpr, values: ir.ValueExpr | Sequence[ir.ValueExpr]
) -> ir.BooleanValue:
"""Check whether `arg`'s values are contained within `values`.
Parameters
----------
arg
Expression
values
Values or expression to check for membership
... | 40ea4907147cd421afec476c2cfdc4cdeb6c2b0f | 62,738 |
def test_decompose():
"""
Test cases for the functions in decompose.py
Returns True if passed all test cases, otherwise returns False
"""
print("Testing: decompose.py")
for n in range(1, 6):
top = np.hstack((np.zeros((n, n)), np.identity(n)))
bottom = np.hstack((np.identity(n), ... | f612d79e57ad26de6d37b55e59323dc966a098e2 | 62,739 |
from typing import Optional
from datetime import datetime
import asyncio
def get_persistence_data(item_name: str, persistence: Optional[str],
start_time: Optional[datetime.datetime],
end_time: Optional[datetime.datetime]) -> OpenhabPersistenceData:
"""Query histor... | e0becca1972d28e4de716985a5ed9451b0cf684a | 62,740 |
def create_diag_ping():
"""
Generate a TR50 JSON request for a diagnostic ping
"""
cmd = {"command":TR50Command.diag_ping}
return cmd | 8024a8799a66fcfa7b2a54915a87414b64544760 | 62,741 |
def __plot_contours(ax, clf, xx, yy, **params):
"""Plot the decision boundaries for a classifier.
Parameters
----------
ax: matplotlib axes object
clf: a classifier
xx: meshgrid ndarray
yy: meshgrid ndarray
params: dictionary of params to pass to contourf, optional
"""
Z = clf.predict(np.c_[xx.rave... | c2ed896ccf69ebf824c1c643e628cb8f02023249 | 62,742 |
import tqdm
def cosine_similarity_matrix(vocab, d):
"""
Create the cosine similarity matrix.
Input
vocab -- a list of words derived from the keys of d
d -- a two-dimensional defaultdict mapping word pairs to counts,
as created by cooccurrence_matrix()
Output
cm -- a two-dimensional d... | d7aa3540df44730842e121adab57d25b53a52738 | 62,743 |
def dict_to_asc(dict_item: dict, filename: str) -> bool:
"""
Save a dict into an asc file.
:param dict_item: The dict object to save.
:param filename: The file path to be saved to.
:return bool: True on success.
"""
return list_to_asc(dict_to_list(dict_item), filename) | 7b4f7d5b5b1b8376103677b1e40cce31cb59e6fe | 62,744 |
def distance(point1, point2):
""" calc distance between two 3d points """
return ((point1[0]-point2[0])**2 +
(point1[1]-point2[1])**2 +
(point1[2]-point2[2])**2)**0.5 | bb9e56b786daf085f5d4fec02001ec561ae77a3c | 62,746 |
import requests
def fetch_uniprot_mapping(ids, from_="ACC", to="ACC", format="fasta"):
"""
Fetch data from UniProt ID mapping service
(e.g. download set of sequences)
Parameters
----------
ids : list(str)
List of UniProt identifiers for which to
retrieve mapping
from_ : st... | 2e8fcc2a27e6f6519b5c286ec7be8302fd88f1a5 | 62,747 |
import requests
def ngram_book(word = ['.'], title = None, period = None, publisher = None, lang=None, city = None, ddk = None, topic = None):
"""Get a time series for a word as string, title is name of book period is (year, year), lang is three letter iso code.
Use % as wildcard where appropriate - no wildca... | 7a56e0b107930e89ba1be1edfa35bd0e03fc762d | 62,748 |
from typing import Callable
import functools
import collections
def recursive_repr(maybe_func=None, max_depth=1, max_repr="..."):
"""
Decorate a representation method/function to prevent infinite recursion.
:param maybe_func: The '__repr__' and/or '__str__' method/function or None.
:param max_depth: ... | 22266e4eec51c9e8d6ae2afaba1e534938a2f3c8 | 62,749 |
def get_process_list(node: Node):
"""Analyse the process description and return the Actinia process chain and the name of the processing result layer
which is a single raster layer
:param node: The process node
:return: (output_objects, actinia_process_list)
"""
input_objects, process_list = c... | f1a029652c369ee4629cf4832ee3c439ad7ec41c | 62,750 |
import binascii
def _request_message(worker):
"""
Transform HTTP message into an action that can be invoked by a worker
"""
message = request.form["message"]
message = binascii.unhexlify(message[2:-1])
response = worker._recv_msg(message)
response = str(binascii.hexlify(response))
retu... | 0443009a13f3ba61589393a60bd6932e81b2264d | 62,751 |
def soil_adjusted_vegetation_index(Red, Near, L=.5):
"""
References
----------
.. [1] Huete, "A soil vegetation adjusted index (SAVI)" Remote sensing of
environment, vol.25 pp.295–309, 1988.
"""
SAVI = np.divide(np.multiply(1+L, Near - Red),
Near + Red + L)
return... | 86fe47f69b44a9ea3d650a8893497cd5b5b97523 | 62,752 |
import socket
import time
def udp(q, where, timeout=DNS_QUERY_TIMEOUT, port=53, af=None, source=None,
source_port=0, ignore_unexpected=False):
"""coro friendly replacement for dns.query.udp
Return the response obtained after sending a query via UDP.
@param q: the query
@type q: dns.message.Me... | bfc401d85a0ecc1232181c078ed31a1967c2eaa2 | 62,754 |
def angle_from_DDDMMSSs(DDDMMSSs):
""" Returns a decimal angle provided a string in right ascension DDDMMSSs format.
Input can be in the forms:
DDDMMSSs (unsigned right ascension)
+DDMMSSs (signed declination / elevation)
"""
DDDMMSSs = right_zero_pad(DDDMMSSs)
if (DDDMMSSs[0] in ("+","-")):
SIGN = DDDMMSSs... | 0eb4e9775f11115b757d32be8ef7c7cd4034e9af | 62,756 |
from typing import List
def ogc_wmts(
endpoint: str,
tms: morecantile.TileMatrixSet,
bounds: List[float] = [-180.0, -90.0, 180.0, 90.0],
minzoom: int = 0,
maxzoom: int = 24,
query_string: str = "",
title: str = "Cloud Optimizied GeoTIFF",
) -> str:
"""
Create WMTS XML template.
... | 61e3a2ae7573a4c2204a4b635210b7c7205254f3 | 62,757 |
from typing import Dict
from typing import Any
import json
async def apiDiscordLogsListEvents(cls:"PhaazebotWeb", _WebRequest:ExtendedRequest) -> Response:
"""
Default url: /api/discord/logs/list
"""
result:Dict[str, Any] = dict(
result=TRACK_OPTIONS,
status=200
)
return cls.response(
text=json.dumps(re... | 240a0de379acb8a2361c57026389c2735d2c0601 | 62,758 |
def _is_transition_allowed(from_tag: str,
from_entity: str,
to_tag: str,
to_entity: str):
"""
BIO 是否被允许转移。比如: "B-Per" "I-Per" 这是被允许的; 而 "B-Per" "I-Loc" 或者 "O", "I-Per" 这是不被允许的
:param from_tag: The tag that the transition origin... | dbbef187e9444eb11b95b4a0bf84d29ccf604bcd | 62,759 |
from pathlib import Path
def root_path() -> str:
"""Fixture that returns the root path of this git repository"""
return str((Path(__file__).parent / "..").resolve()) | 9b9ef56614ea22cca222f21254ab611ae04da364 | 62,760 |
def filter_type_between(left, right, supports_midi = False, is_drum_pad = False, supports_instrument = False):
"""
Given 'left' and 'right' are two consecutive devices in a valid
device chain, returns the appropriate browser filter type for valid
devices fitting between them. Either 'left' or 'right' ca... | c7b7455cbdfae0dc596c775f5779104a1b7fa435 | 62,762 |
import multiprocessing as mp
import psutil
def nproc_use_ng(det):
"""Optimize processor usage.
Attempt to estimate a reasonable number of processes to use for multiple
simultaneous slope_to_ramp() calculations. We attempt to estimate how many
calculations can happen in parallel without swapping... | 0fa6bdf26e7145a96be46d0342716f806233a288 | 62,763 |
def preserve_patron_loan(data, prev_record=None):
"""Preserve `patron_loan` system field."""
if not has_request_context():
return data
if prev_record and "patron_loan" in prev_record:
data["patron_loan"] = deepcopy(prev_record["patron_loan"])
return data | 5750f7f54a3d2a8c89f2bb45af502da8ed046f24 | 62,764 |
def preprocess_data(data, desired_length):
"""Forces the data to be the desired length.
Input is a 2D matrix of [timestep, features].
desired_length is in the first (time) dimension.
Output is another 2D matrix.
"""
if len(data) < 1:
raise Exception('Input score is length 0.')
if l... | 80132a5d6e23e9fd19427808dd6ef1f35a490dde | 62,765 |
import json
def test_platform_declaration():
"""Test platform declaration generation runs without error, and can be saved
to JSON file (ChemifyAPI needs this functionality).
"""
return json.dumps(PlaceholderPlatform().declaration) | 6523e314a48584b47826933393303ab66fbf6b12 | 62,766 |
def randint(low, high=None, size=None):
"""
Return random integers from low (inclusive) to high (exclusive).
Return random integers from the “discrete uniform” distribution in the “half-open” interval [low, high).
If high is None (the default), then results are from [0, low).
"""
if high is No... | 848ceb46246501198f2cb2f852984ef84dc5c2d1 | 62,767 |
def remove_odd_whitespaces(text):
"""Remove multiple and trailing/leading whitespaces."""
return " ".join(text.split()) | 09e0fe6088ad14e58c8cbc0571f72d304a1a43d6 | 62,768 |
def jinja2_getattr(self, obj, attribute):
"""Get an item or attribute of an object but prefer the attribute.
Unlike :meth:`getitem` the attribute *must* be a bytestring.
This is a customised version to work with properties
"""
try:
value = getattr(obj, attribute)
if isinstance(value... | cdd84d4a69ad16b03aa20e79ac019699f2b3506b | 62,769 |
def gradient_d4(dem, dx, dy, aspect_rad=False):
"""Calculate the slope and aspect for provided dem,
this will mimic the original IPW gradient method that
does a finite difference in the x/y direction.
Given a center cell e and it's neighbors:
| a | b | c |
| d | e | f |
| g | h | i |
... | 8ef1909055cde77f3ea9519a7eb36fd2ab4afdea | 62,770 |
def select_angle(attr_a, attr_b=0, condition=False):
"""Create math_SelectAngle-node to get one of the given attrs, depending on condition-state.
Args:
attr_a (NcNode or NcAttrs or string): Maya node attribute.
attr_b (NcNode or NcAttrs or float): Maya node attribute.
condition (NcNode ... | 24f898bf5dcf88fb64964b73a996d1189e6cfa92 | 62,771 |
from typing import Dict
def build_census_df(
admits_df: pd.DataFrame,
lengths_of_stay: Dict[str, int],
) -> pd.DataFrame:
"""Average Length of Stay for each disposition of COVID-19 case (total guesses)"""
return pd.DataFrame({
'day': admits_df.day,
'date': admits_df.date,
**{
... | 9402d0b51720fe18c5f74592789bcd670956451a | 62,772 |
import json
def get_all_user_stats(user_ids, user_records=None):
"""Get some additional information about observers"""
iconic_taxa_lookup = {v.lower(): k for k, v in ICONIC_TAXA.items()}
iconic_taxon_id = iconic_taxa_lookup[ICONIC_TAXON.lower()]
user_ids = set(user_ids)
user_info = {}
user_rec... | f8b9a22125eacf0c95e25c9d6edee6bc933459ee | 62,774 |
def create_opssat_devices():
"""Returns a list of 3 devices instances representing OPS-SAT optical devices"""
return [Device(DeviceId.STAR_TRACKER, DeviceState.ON, PhotoDiode.PD3, PD_ELEVATION_THRESHOLD_IADCS_ST),
Device(DeviceId.HD_CAMERA, DeviceState.ON, PhotoDiode.PD6, PD_ELEVATION_THRESHOLD_HD_C... | 98a16a7b974b1bfe1ea4ef2a583cad8ed61e3fad | 62,775 |
import json
def add_loc_data(reduced_df, all_data, to_csv=False):
"""
Adds location data generated by `generate_spatial_data` to the `all_data` dataframe in a new `final_df`.
"""
# Load in the data
file = open('../data/arcgis_latlong_data.json')
data = json.load(file)
# Creating a map... | 71ffcbfb49143ff5183e01de332d188e4abe2da0 | 62,776 |
import random
import re
def sf_prepare(u_boot_console, env__sf_config):
"""Check global state of the SPI Flash before running any test.
Args:
u_boot_console: A U-Boot console connection.
env__sf_config: The single SPI Flash device configuration on which to
run the tests.
Retur... | 01cb5931a47dd225a21d146754709e6c56021fcd | 62,777 |
def _next_power_of_2(x):
"""
Calculate the closest power of 2, greater than the given x.
:param x: positive integer
:return: int - the closest power of 2, greater than the given x.
"""
return 1 if x == 0 else 2**(x - 1).bit_length() | 616c01f6aacb7442ce1b2afbcac35b26c8f79701 | 62,778 |
def chrono(alg, coalg):
"""
Performing a histomorphism right after a futumorphism.
"""
return lambda a: histo(alg)(futu(coalg)(a)) | bd44baa1efef93837d891654f64dfeba4442a14c | 62,780 |
import torch
def f_score(pr, gt, beta=1, eps=1e-7, threshold=None, activation='sigmoid'):
"""
Args:
pr (torch.Tensor): A list of predicted elements
gt (torch.Tensor): A list of elements that are to be predicted
eps (float): epsilon to avoid zero division
threshold: threshold f... | e6b6f381c15906b9accf88374c88d781ae94f6ca | 62,781 |
def getExtremeN(toSort, N, keyFunc):
"""
Returns the indices
"""
enumeratedToSort = [x for x in enumerate(toSort)]
sortedVals = sorted(enumeratedToSort, key=lambda x: keyFunc(x[1]))
return [x[0] for x in sortedVals[0:N]] | 0a8d4979cd5179fa65d02f5c8362581134abea8c | 62,783 |
def is_available():
# type: () -> bool
"""Returns whether visualization is available or not.
.. note::
:mod:`~optuna.visualization` module depends on plotly version 4.0.0 or higher. If a
supported version of plotly isn't installed in your environment, this function will return
:obj... | ffb8110a7e4672af1f11ab972e3416dc2b6afc34 | 62,784 |
def dict_representer(dumper, data):
""" Dumper with OrderedDict
"""
return dumper.represent_mapping(BaseResolver.DEFAULT_MAPPING_TAG,
iter(data.items())) | c0d7d959c926dc5983fc5a16759c46be114ab945 | 62,786 |
def delete_user(request):
"""delete a user completely"""
user_id = int(request.matchdict["user_id"])
if asbool(get_settings().get("enable_user_authentication", False)):
# ensure that the user exists and we have the permission to update it
may_delete = request.has_perm(perm_global_delete_use... | 65d7d3816fe938f3ca6197129062ffab7b7a6fe4 | 62,788 |
async def test_do_api_call_async_patch_method_with_success(mock_get_connection, mock_session):
"""
Asserts the _do_api_call_async for PATCH method.
"""
async def mock_fun(arg1, arg2, arg3, arg4):
return {"status": "success"}
mock_session.return_value.__aexit__.return_value = mock_fun
m... | 9797f0e4797bfd902b4e1c1a3a048c80dd33e754 | 62,789 |
def ffmpeg_get_audio_buffer_size(audio_format):
"""Return the audio buffer size
Buffer size can accomodate 1 sec of audio data.
"""
return audio_format.bytes_per_second | adfb290b9377d680c0a3b0f79adb8f01dcf131fa | 62,790 |
def check_osd_tree_3az_aws(osd_tree, number_of_osds):
"""
Checks whether an OSD tree is created/modified correctly. This can be used as a verification step for
deployment and cluster expansion tests.
This function is specifically for ocs cluster created on 3 AZ AWS config
Args:
osd_tree (di... | ba459d91af0ae5b6796602825e4cfd744a4b087b | 62,791 |
def set_bdev_options(client, bdev_io_pool_size=None, bdev_io_cache_size=None):
"""Set parameters for the bdev subsystem.
Args:
bdev_io_pool_size: number of bdev_io structures in shared buffer pool (optional)
bdev_io_cache_size: maximum number of bdev_io structures cached per thread (optional)
... | 1eaa1403a45845a3d742438cb9ff5f8b408f0684 | 62,792 |
def mask_pos_lt(source_length, target_length):
"""A mask with 1.0 wherever source_pos < target_pos and 0.0 elsewhere.
Args:
source_length: an integer
target_length: an integer
Returns:
a Tensor with shape [1, target_length, source_length]
"""
return tf.expand_dims(
tf.cast(tf.less(tf.expand... | 9f56fdaa30adc31a0407f964117a1c00feead352 | 62,793 |
def get_requirement_items(filename):
"""
Get install requirements from a file.
:param filename: A file path to a requirements file.
:return: A list of requirement items.
:rtype: A `list` of :class:`pip.req.InstallRequirement`
"""
with PipSession() as session:
return list(parse_requir... | dd48ba7417cdfc9758d55001c90c01a179ff3de2 | 62,794 |
def hasanyattrs (object ,returnlist = False):
"""
Checks if the object has any attributes (rather than a particular
attribute as implemented in python 2.7.5 function hasattr )
args:
object : name of object
returns:
tuple, ( Bool, listof attributes)
example usage:
>>> import typeutils as tu
>>> p... | 4ad87d0026cf443e2b968c16c0ac85158149f348 | 62,795 |
def calc_mod3D_ls(data, periods, nphases):
"""
Need to change this so that it:
- first tries to fit only the amplitude and phase
- if that doesn't work, estimate amp and only fit phase
- then do full fit
Also, add a Jacobian for the curve_fit
"""
# only deal with finite data
# N... | e64909355158f4ae9d40dfc38c898a90f7ad2321 | 62,796 |
import random
def roll_nl(n=2, d=6):
"""
>>> random.seed("test")
>>> roll_nl()
12
"""
def dice():
nonlocal total
points= tuple(random.randint(1,d) for _ in range(n))
total = sum(points)
return points
total= 0
dice()
return total | 07e2a245820896e26c462ac59251c55591bdff76 | 62,797 |
from typing import Dict
from typing import Any
from typing import List
def check_md5_command(client: Client, args: Dict[str, Any], params) -> List[CommandResults]:
""" Performs the api call to cofense threts-search endpoint to get all threats associated with the given file hash,
analyze the response and gene... | 00870c61382e403f97321970b50106df985b593a | 62,798 |
import re
def get_definitions(word):
"""
Load a page from pl.wikt and find all definitions in the Polish section.
This can be used to show the user a list of definitions beside an example,
so they can match the two.
Args:
word (str): page title on pl.wikt
Returns:
tuple:
... | 2d2afc2287e4c78b10be6cc9a5ddaa5205b0fa46 | 62,800 |
import json
def stream_n_messages(n):
"""Stream n JSON messages"""
response = get_dict('url', 'args', 'headers', 'origin')
n = min(n, 100)
def generate_stream():
for i in range(n):
response['id'] = i
yield json.dumps(response) + '\n'
return Response(generate_strea... | 5dd2e3acc6bd09c01f3c0e3aff96aaed5eea239a | 62,801 |
def param_samples(sample_names: StringList = SAMPLES):
"""Parametrize with list of samples"""
names = 'samp'
vals = get_samples(sample_names)
ids = sample_names
return parametrize(names, vals, ids) | 32f833cc4c41b0c009f046887acebaf8b2bd8731 | 62,803 |
def add_ingredient_item(user_id, recipe_id):
""" Adds an ingredient to the database and references the recipe id
:return
returns the edit-recipe.html form ingredient tab with updated ingredient list
"""
# Insert ingredient record
DB_INGREDIENTS.insert_one(
{'ingredient_item': reque... | 642b363ce8baa07a76a9ec5f039207b6f33255e7 | 62,804 |
import inspect
def docstring(obj):
""" return un-inherited doc-attribute of obj.
(i.e. we detect inheritance from its type).
XXX: this should eventually go into the inspect module!
"""
if getattr(type(obj),'__doc__','')!=getattr(obj,'__doc__',''):
return inspect.getdoc(obj) | 94f2089b8b25e9d7e83192dd5e3c02992559a2e2 | 62,805 |
def question_encoder(question, hparams, name="encoder"):
"""Question encoder, run LSTM encoder and get the last output as encoding."""
with tf.variable_scope(name, "encoder", values=[question]):
question = common_layers.flatten4d3d(question)
padding = common_attention.embedding_to_padding(question)
leng... | f1dd3ef983cfe0ddc0c77f7ac021b266b595eac4 | 62,807 |
def isstub(fn):
"""Returns true if a function is likely only a stub"""
if len(fn.basic_blocks) > 1 or len(fn.llil.basic_blocks) > 1:
return False
if fn.llil.basic_blocks[0].has_undetermined_outgoing_edges or len(fn.callees) == 1:
return True
return False | c980fdcaef2b1dc24b7e25bbf2230ded08b8615d | 62,808 |
import json
def flag_validate(flag:str,id:int):
""" flag_valiate : validate the flag
Args:
flag (str): flag string
id (int): user discord id
Returns:
result(str): result after validate
"""
solve_level = []
flaglist = open("./challenge/flaglist.txt").read().s... | 932cafcc6e3d62a0a095c019ff4d78bc04faabfc | 62,809 |
def query_preview(request):
"""Apply the query to the connection and return render with the column names and a preview of the data."""
connection_id = request.POST.get("connection_id", None)
query = request.POST.get("query", None)
connection = Connection.objects.get(id=connection_id)
# Only get th... | a7a42daa748d9a1147d66e99eb77942ec589cc99 | 62,810 |
def supplies_profit(buyer):
"""Calculate profit from supply transactions
supply profit = supply revenue - supply cost
Where supply revenue is pulled from FishdataExpense costs are pulled from
FishdataSupplypurchases.
Arguments:
buyer -- FishdataBuyer object
Returns:
supplies_income -... | e5c0da614904935a35837f629846eaa67984f9ff | 62,811 |
from typing import Optional
import pathlib
import json
def write_component(
component: Component,
gdspath: Optional[PosixPath] = None,
path_library: PosixPath = CONFIG["gds_directory"],
precision: float = 1e-9,
settings: None = None,
with_settings_label: bool = conf.tech.with_settings_label,
)... | 9c5b093977e830d20aba0d67dec79098b3707ba6 | 62,812 |
def getGeolocalisationFromJson(image):
"""Get geolocalisation data of a image in the database
Parameters:
image (json): image from the validation data
Returns:
float: lng (degree)
float: lat (degree)
float: alt (degree)
float: azimuth (degree)
float: tilt (degree)
float: roll (... | 4ea02780b4254dfb03ac335ca1214a7b7d6bf521 | 62,813 |
import tqdm
def evaluate(
data, parameters, feature_names, tagset, score_func, verbose=False
):
"""
Evaluates precision, recall, and F1 of the tagger compared to the gold standard in the data
:param data: Array of dictionaries representing the data. One dictionary for each data point (as created by t... | d097bf93147daae1a3662c3b28c20dd7d408cd60 | 62,814 |
def _class_for_name(module_and_class_name):
"""
Return the class object given an name.
Parameters
----------
module_and_class_name : strictly
The module and class name, e.g. "mymodule.MyClass"
Returns
-------
class
"""
parts = module_and_class_name.split('.')
module... | 5972b6d45e592e426db9516a74cf33fd3381eebe | 62,815 |
import random
def get_random_header():
"""
:return (dict): A header with a random browser/OS configurations out of the available list.
"""
return headers_list[random.randint(0, len(headers_list) - 1)] | cc42d553ec1dc17d41e139528055add5cde7cd69 | 62,816 |
def experiment_name_resolution(setup_pickleddb_database, experiment_name_conflict):
"""Create a resolution for a code conflict"""
return experiment_name_conflict.ExperimentNameResolution(
experiment_name_conflict, new_name="new-exp-name"
) | 1172fc3380cce7190528cf6125ed8ec3a625eaf2 | 62,817 |
import hashlib
def createBase(secret):
"""
Creates a base from a given secret
"""
hx = [e for e in "0123456789abcdef"]
base = ""
if not isinstance(secret, bytes):
secret = secret.encode()
for c in hexlify(hashlib.md5(secret).digest()):
try:
base += hx.pop(hx.ind... | d10c8953175c13a0f0ac8a771dcbe34bdb0d8e12 | 62,819 |
import re
def get_used_non_latest_image_tags():
"""Get the list of image tags that are currently used by Docker files"""
image_tags = {}
for file_path in BASE_DIR.glob('Dockerfile-*'):
image_tag = None
with file_path.open('r') as fdockerfile:
for line in fdockerfile:
... | 10588b59c91fb79b319cb369ebf33dba6069dfd2 | 62,820 |
def get_largest_components(np_array, nr_components):
"""
Get largest connected components (how many defined by nr_components) from a binary image, background==0
:param np_array: a binary np array (e.g. segmentation mask)
:param nr_components: the number of largest components to keep
:return: a binar... | 9374bc81024c9ecb023edc20e7a48bde021124e5 | 62,821 |
def model(pDict, lamSqArr_m2):
"""Single Faraday component with Burn depolarisation"""
# Calculate the complex fractional q and u spectra
pArr = pDict["fracPol"] * np.ones_like(lamSqArr_m2)
quArr = (pArr * np.exp( 2j * (np.radians(pDict["psi0_deg"]) +
pDict["RM_rad... | 5083a4bd03b96afc3c9350064587fb4ad0867cfa | 62,823 |
def isPalidrome(subject: str):
"""Returns True if subject is a palidrome string, False otherwise."""
inputLength = len(subject)
if(inputLength < 2):
return True
# Ignore the single mid character in odd length input
if inputLength % 2 != 0:
subject = subject[0:inputLength//2] + subj... | 6653f3d0421fc62387037a6f3a9a632229b0dcab | 62,824 |
def fixquotes(u):
"""
Given a unicode string, replaces "smart" quotes, ellipses, etc.
with ASCII equivalents.
"""
if not u:
return u
# Double quotes
u = u.replace('\u201c', '"').replace('\u201d', '"')
# Single quotes
u = u.replace('\u2018', "'").replace('\u2019', "'")
# E... | 28f8ff0068b28ae0cca60ac850c89403bc347346 | 62,826 |
def parse_username(username):
"""
parses uncapitalized, whitespace-padded, and weird-charactered mediawiki
user names into ones that have a chance of being found in the database
needs to accept either a unicode or string input, returns str of bytes
"""
# not pretty but python 2.7 is a box of
... | 929706d4ec909f41fed1fe7184f5856d208fd545 | 62,827 |
def get_role_tempalte(context=None,name=None,opts=None):
"""
Use this data source to retrieve information about a Rancher v2 role template resource.
> This content is derived from https://github.com/terraform-providers/terraform-provider-rancher2/blob/master/website/docs/d/roleTemplate.html.markdown.
... | 42ba6baaa72eeaa587b9ff0083ca82d866b67240 | 62,828 |
def jp_server_config():
"""Allows tests to setup their specific configuration values. """
return {} | 20d71f1e271eaf4859e5e6f2c86a80b5b3c2c52a | 62,829 |
def coa_livestock_parse(*, df_list, year, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param args: dictionary, used to run flowbyactivity.py
('year' and 'source')
:return: df, parsed and partially formatted to flowbyact... | 2233d6c3f28dd6ef645af0d16155277cc323c930 | 62,830 |
def draw_figure(canvas, figure, canvas_toolbar):
"""
This is Matplotlib helper code to draw a canvas in Pysimplegui window.
"""
if canvas.children:
for child in canvas.winfo_children():
child.destroy()
if canvas_toolbar.children:
for child in canvas_toolbar.winfo_children... | fd361c035814a4c25b3d10e0acac75d82205b395 | 62,831 |
def is_form_15(data, encoding, delim, quotechar):
"""
Files that start with "Fornecedor;"
These files never have quotes (in the current training set)
"""
is_form_15.ID = 15
if data.startswith("Fornecedor;"):
return (True, None)
return (False, "no_match") | a788a1f26fdc30f8f64523e53ce38918a9b4accd | 62,832 |
def compare_tau1(G,L,sir_list,community,MRCNN):
"""使用肯德尔相关系数对比不同方法
Parameters:
G:目标网络
dc:度中心性
bc:介数中心性
ks:k-shell
sir_list:不同beta下的SIR模拟结果
model:训练好的模型
p:选择比较节点的比例
return:
tau_list:在不同beta情况下的tau值
"""
num_nodes = int(p*G.number_of_nodes... | 9ee589e11b311da5f30263ca83fa79baa401667f | 62,833 |
import random
def round1(teams):
"""Run the first round and return a sorted list of team names.
teams is the sorted list [group0, group1, ...] and not the actual names of
the agents. This is necessary to start the agents.
"""
raw_input('--- Press ENTER to continue ---\n')
print()
print("R... | 9153395bea1d825211c358412d4f8938cb8ceeb5 | 62,834 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.