content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gaussian_image_pyramid(img):
"""Computes image gaussian pyramid from frame or image."""
gaussian = img.copy() #needs better name
pyramid = [gaussian]
for i in range(6):
gaussian = cv.pyrDown(gaussian)
pyramid.append(gaussian)
return pyramid | 5,297,400 |
def find_endpoint(method, handler, parameters, url_parameters, ids_parameters, dir_to_list, endpoint):
"""Find the route from endpoint and call the correct method when found"""
if not endpoint:
return do_method(method, handler, parameters, url_parameters, ids_parameters, dir_to_list, ".all")
if "/" ... | 5,297,401 |
def validation_errors(record, schema):
"""Return a dict of errors upon validating the record against the schema.
"""
v = AutaValidator(schema, allow_unknown=True)
v.validate(record)
return v.errors | 5,297,402 |
def test_redirect_domain_discard_query_parameters(
test_client: TestClient,
) -> None:
"""Test that query parameters are discarded."""
response = test_client.get(
"/?a=b", headers=HEADERS_302_KEEP_NONE, **REDIRECT_REQUEST_OPTS
)
assert response.headers["location"] == "https://nu.nl" | 5,297,403 |
def wifi_configure():
"""
Perform initial (one-time) configuration of the WiFi adapter.
"""
global wlan
wlan = network.WLAN(network.STA_IF)
wlan.config(dhcp_hostname='iot-envsensor')
wlan.active(True) | 5,297,404 |
def run_test(
schema: BaseSchema,
endpoint: Endpoint,
test: Union[Callable, InvalidSchema],
checks: Iterable[Callable],
results: TestResultSet,
**kwargs: Any,
) -> Generator[events.ExecutionEvent, None, None]:
"""A single test run with all error handling needed."""
# pylint: disable=too-... | 5,297,405 |
def clear_access_list_hitcounts_all(
enode,
_shell='vtysh',
_shell_args={
'matches': None,
'newline': True,
'timeout': None,
'connection': None
}
):
"""
Clear all ACL stat values.
This function runs the following vtysh command:
::
# clear access... | 5,297,406 |
def get_javac_version() -> Tuple[Optional[str], Optional[int]]:
"""
A function that shells out to the ``javac`` tool to determine the installed
version. We use ``javac`` as we want to make sure that the JDK is installed
and not just the JRE.
:return: a tuple with the version of the JDK that's inst... | 5,297,407 |
def split_by_type(activity_references):
"""Given a list of activity references, returns two lists: the first list
contains the exploration ids, and the second contains the collection ids.
The elements in each of the returned lists are in the same order as those
in the input list.
Args:
acti... | 5,297,408 |
def get_nodes_by_namespace(graph, namespaces):
"""Get all nodes in the namespace or namespaces.
:param pybel.BELGraph graph: A BEL graph
:param namespaces: namespaces to be filtered
:type namespaces: str or iter[str]
:rtype: set[BaseEntity]
"""
return get_nodes(graph, namespace_inclusion_bu... | 5,297,409 |
def do_poseur(filename: str, **kwargs: object) -> None:
"""Wrapper function to catch exceptions."""
try:
poseur(filename, **kwargs) # type: ignore[arg-type]
except Exception: # pylint: disable=broad-except
with TaskLock():
print('Failed to convert file: %r' % filename, file=sys... | 5,297,410 |
def convert_eof():
"""A context manager to convert some socket errors into EOFError."""
try:
yield
except ConnectionResetError:
raise EOFError
except BrokenPipeError:
raise EOFError
except OSError as exc:
if exc.errno in EOF:
raise EOFError
... | 5,297,411 |
def add_relative_events():
"""Run add_relative_events command."""
parser = argparse.ArgumentParser()
parser.add_argument('raw', type=str,
help='The electrophysiology raw object or filepath')
parser.add_argument('--beh', type=str, required=False,
help='The ... | 5,297,412 |
def prepare_playlists(user,labelled_data):
"""
prepares the user's playlists for upload and display
Args:
user (SpotifyUser)
labelled_data (DataFrame or array-like)
Returns:
Dictionary: uploadable playlists in JSON format
"""
return user.generate_uploadable_playlists(la... | 5,297,413 |
def add(i):
"""得到114个add函数对应的的字符串"""
return ".add(user_id_list[" + str(i) + "][0], \n" \
"\tpeople[" + str(i) + "], \n" \
"\txaxis3d_opts=opts.Axis3DOpts(type_='value', min_='dataMin', max_='dataMax'), \n" \
"\tyaxis3d_opts=opts.Axis3DOpts(type_='value', min_='dataMin', max_=... | 5,297,414 |
def is_structured_array(array: np.ndarray) -> bool:
"""
Determines whether a numpy array-like object is a structured array.
Parameters
----------
array : numpy.ndarray
The array to be checked.
Raises
------
TypeError
The input array is not a numpy array-like object.
... | 5,297,415 |
def full_alsfrst(project, num_iter=100, num_seeds=5, run_by_seed=False, seed=None, kernel=None, multiprocess=False):
""" Run MoGP for all datasets (PROACT, AALS, CEFT, EMORY, GTAC)
For PROACT: enable running seeds/kernels separately
For all other datasets: run both rbf/linear kernels for 5 seeds
... | 5,297,416 |
def find_path(path, topdir):
"""Find a file in a top to bottom search through the repository hierarchy.
For all repositories/directories from `topdir` down to the core repository in BASE_DIR, check whether the relative
`path` exists and, if yes, return its absolute path.
`path` can be any file system o... | 5,297,417 |
def filter_representative_sites_patient(
df: pd.DataFrame, representative_sites: List[str]) -> pd.DataFrame:
"""
Filters out representative sites from the given data frame for a single
patient.
Args:
df: The data frame to filter.
representative_sites: Representative sites to fil... | 5,297,418 |
def get_letters():
"""Get letters dataset (TODO: implement)"""
pass | 5,297,419 |
def main():
"""
Main function
"""
crypt = sys.argv[1]
splitted_chars = re.findall(r'.{1,2}', crypt)
splitted = [int(x, 16) for x in splitted_chars]
list_chars = []
for index, char in enumerate(splitted):
# Appending the char with the 8 bit turned off
validated_char = ch... | 5,297,420 |
def print_python_dict(
matched_ids: Dict[str, List[Union[PointResult, LineResult, PolygonResult]]]
):
"""
Prints dict with different annotation result lists
"""
result = {}
for key in matched_ids:
result[key] = []
for annotation_result in matched_ids[key]:
r... | 5,297,421 |
def do(huc12, mode):
"""Do work"""
pgconn = get_dbconn("idep")
cursor = pgconn.cursor()
utcnow = datetime.datetime.utcnow()
if mode == "daily":
cursor.execute(
"""
SELECT valid, avg_loss * 4.463, avg_delivery * 4.463,
qc_precip / 25.4, avg_runoff / 25.4, 1... | 5,297,422 |
def save_library():
"""Save library to file"""
all_lines = []
words = []
for word_pair in LIBRARY:
words.append(word_pair[0])
if word_pair[2] == "\n":
words.append(word_pair[1])
all_lines.append(' '.join(words))
words = []
f = open("OutputBrain.tx... | 5,297,423 |
def read_config(config_file):
"""Read configuration file infomation
:config_file: Configuration file
:type config_file: string
"""
cfg = configparser.ConfigParser()
try:
cur_dir = os.path.dirname(os.path.abspath(__file__))
if os.sep not in config_file:
config_fil... | 5,297,424 |
def get_domains():
"""
Coroutine - Get all domains from db `DomainExpiration`
"""
for domain in db.domains.find():
domain = DomainExpiration(**domain)
yield from domain.run() | 5,297,425 |
def get_recent_assets():
"""
Returns the last created assets
"""
assets_list = []
assets = list()
for group_id in settings.LIST_GROUP_ID:
assetgroup = PATROWL_API.get_assetgroup_by_id(group_id)
assets += sorted(assetgroup['assets'], key=lambda k: k['id'], reverse=True)
for a... | 5,297,426 |
def rates_for_yr(rates_all_years, sim_year):
"""
Filter specific rates for a given year
Parameters
----------
rates_all_years : pandas DataFrame
rates, to be filtered by year
sim_year : int
year being simulated
Returns
-------
pop_w_rates : pandas DataFrame
... | 5,297,427 |
def _check_areas_and_format(areas, grid_model="usa_tamu"):
"""Ensure that areas are valid. Duplicates are removed and state abbreviations are
converted to their actual name.
:param str/list/tuple/set areas: areas(s) to check. Could be load zone name(s),
state name(s)/abbreviation(s) or interconnect... | 5,297,428 |
def add_handover_volunteer(full_name, phone_number, languages):
"""
add a volunteer to the handover list
:param full_name: volunteer's first name and last name
:param phone_number: volunteer's phone number
:param languages: language(s) the person can speak (answer users' queries) - used for matching... | 5,297,429 |
def test_jdbc_query_executor_successful_query_event(sdc_builder, sdc_executor, database):
"""Simple JDBC Query Executor test for successful-query event type.
Pipeline will insert records into database and then using sqlalchemy, the verification will happen
that correct data is inserted into database. Event ... | 5,297,430 |
def list_key_pairs(profile, **libcloud_kwargs):
"""
List all the available key pair objects.
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's list_key_pairs method
:type libcloud_kwargs: ``dict``
CLI Example:
.. code-bl... | 5,297,431 |
def randint(low, high, m=1, n=1):
"""
:param low: Lower bound on possible random ints
:param high: Max possible random int (INCLUSIVE)
:param m: number of rows in output
:param n: number of cols in output
Generates an ``m x n`` whose elements are integers selected uniform random
in the rang... | 5,297,432 |
def path_xy(port1, port2, directions = 'xxyx'):
""" Creates a Path that travels only in x and y directions (manhattan) from
one point (or Port) to another. The `directions` string determines the order
of the x/y steps. Example: `directions = 'xyx'` will travel
1/2 the distance in x from p1 to p2
... | 5,297,433 |
def _get_initializer(
initialization_method: str,
initialization_range: float,
initialization_std: float) -> tf.keras.initializers.Initializer:
"""Gets variable initializer."""
if initialization_method == 'uniform':
initializer = tf.keras.initializers.RandomUniform(
minval=-initialization_ra... | 5,297,434 |
def topic_matches_sub(sub, topic):
"""Check whether a topic matches a subscription.
For example:
foo/bar would match the subscription foo/# or +/bar
non/matching would not match the subscription non/+/+
"""
result = True
local_sub = _fix_sub_topic(sub)
local_topic = _fix_sub_to... | 5,297,435 |
def unregister_custom_op_onnx_export(opname: str, opset_version: int, min_version: str) -> None:
"""
Unregister PyTorch's symbolic `opname`-`opset_version` for ONNX export.
The un-registration is performed only when PyTorch's version is < `min_version`
IMPORTANT: The symbolic must have been manually reg... | 5,297,436 |
def lambda_handler(event, context):
"""lambda entry"""
LOGGER.info(f'REQUEST RECEIVED: {json.dumps(event, default=str)}')
# get current account
execution_account_id = context.invoked_function_arn.split(':')[4]
# check if lambda call by AWS CloudWatch Event in response to creation of new AWS... | 5,297,437 |
def test_tar_pack(archive, unicode_filename):
"""
Validate using the tar function to create archives
"""
with Archive("tar", unicode_filename=unicode_filename) as arch:
ret = archive.tar("-cvf", str(arch.archive), sources=str(arch.src))
assert isinstance(ret, list)
arch.assert_ar... | 5,297,438 |
def main():
"""Make a jazz noise here"""
args = get_args()
file1_word = []
file2_word = []
for line in args.input1:
file1_word += line.split()
for line in args.input2:
file2_word += line.split()
common_word = sorted(set(file1_word) & set(file2_word))
for word in common_w... | 5,297,439 |
def draw_fancy_table(
data: List[List[Union[Number, str]]],
rows: bool = True,
lines: str = "│─",
corners: str = "┌┐┘└",
crossings: str = "┼├┤┬┴",
align: str = "<",
) -> List[str]:
"""
TODO (2021-01-18): Add documentation
"""
if len(data) < 1:
raise ValueError("Data shoul... | 5,297,440 |
def delete_link(GlobalNetworkId=None, LinkId=None):
"""
Deletes an existing link. You must first disassociate the link from any devices and customer gateways.
See also: AWS API Documentation
Exceptions
:example: response = client.delete_link(
GlobalNetworkId='string',
LinkI... | 5,297,441 |
def _create_time(model: sbml.Model, time_var: str):
"""
Creates the time variable, add assignment to 'time'
Arguments:
model: the SBML model to which the species will be added.
time_var: str, the time variable
Returns:
Raises:
"""
time_parameter = model.createParameter()
... | 5,297,442 |
def joinPath(path: str, cwd: str = os.getcwd()):
"""
Helper function to make using os.path.join(os.gecwd()) a lot easier
Ex:
joinPath(["modules", "modules.py"])
joinPath("modules/modules.py")
Returns: a string path
"""
if type(path) != list:
path = path.split("/")
if cwd:... | 5,297,443 |
def absent_downstream_subtypes(subtype: str,
subtypes: pd.Series,
scheme_subtypes: List[str]) -> Optional[List[str]]:
"""Find the downstream subtypes that are not present in the results
Args:
subtype: Final subtype result
subtypes: S... | 5,297,444 |
def get_estimated_prob(key):
"""
Gets estimated probability which is the sum of worst NRR probability and only-NRR-based probability.
"""
return get_worst_prob(key) + get_nrr_prob(key) | 5,297,445 |
def test_should_raise_if_no_conf(input_notebook):
"""
Test command raise if no conf, neither auto detected or given to command line
"""
arguments = ['-n', input_notebook, '--working-directory', './']
with pytest.raises(MlVToolException):
IPynbToDvc().run(*arguments) | 5,297,446 |
def _build_score_dict(pitches, onsets, durations, melody,
vel_trend, vel_dev, log_bpr,
timing, log_art, pedal=None):
"""Helper method to build a dictionary with score and performance information
for each score position.
Parameters
----------
pitches : ... | 5,297,447 |
def create(request):
""" create command, called from the djangy command line client."""
email = request.POST.get('email')
application_name = request.POST.get('application_name')
# check for that application name
if not name_available(application_name):
return HttpResponseBadRequest('Error: ... | 5,297,448 |
def merge_atlas_segmentations(img_paths, show=True, atlas=True, suffix=None):
"""Merge atlas segmentations for a list of files as a multiprocessing
wrapper for :func:``merge_atlas_segmentations``, after which
edge image post-processing is performed separately since it
contains tasks also performed in... | 5,297,449 |
def getGraphComponents(model: str, scalable_components: list = []):
"""
Gets the list of component and their instances, as well as the list of conflicts between
components.
Args:
model (str): The name of the minizinc model.
scalable_components (list, optional): A list of scalable compon... | 5,297,450 |
def test_human_readable_conversion(value, expected):
"""Converts value to human readable format and matches with the expected answer."""
assert human_readable(value) == expected | 5,297,451 |
def get_BIC(gwr):
"""
Get BIC value
Gaussian: p61 (2.34), Fotheringham, Brunsdon and Charlton (2002)
BIC = -2log(L)+klog(n)
GWGLM: BIC = dev + tr_S * log(n)
"""
n = gwr.n # (scalar) number of observations
k = gwr.tr_S
y = gwr.y
mu = gwr.mu
if isinstance(gwr.family, ... | 5,297,452 |
def precmd(cmdMethod, before = None, after = None):
"""
Decorator to declare method to call 'pre' command method from wscript
"""
def decorator(func):
return _hookDecorator(func, _hooks[cmdMethod].pre, before, after)
return decorator | 5,297,453 |
def create_service():
"""Creates the service object for calling the Cloud Storage API."""
# Construct the service object for interacting with the Cloud Storage API -
# the 'storage' service, at version 'v1'.
# You can browse other available api services and versions here:
# https://develope... | 5,297,454 |
def read_file_json(json_file_path) -> any:
"""
Accepts a Path object to a JSON file and read it into a dict or array structure
"""
if not json_file_path.exists():
raise FileNotFoundError(json_file_path, "File with path '{}' does not exist!".format(
json_file_path.absolute()))
tr... | 5,297,455 |
def test_custom_regex(tmpdir, capsys):
"""Test custom word regex."""
d = str(tmpdir)
with open(op.join(d, 'bad.txt'), 'w') as f:
f.write('abandonned_abondon\n')
assert cs.main(d) == 0
assert cs.main('-r', "[a-z]+", d) == 2
capsys.readouterr()
assert cs.main('-r', '[a-z]+', '--write-c... | 5,297,456 |
def test_post_empty(capsys):
"""Correct empty ouput."""
a = K()
a.post_order(lambda n: print(n.__str__()))
sys.stderr.write("")
out, err = capsys.readouterr()
assert out == err | 5,297,457 |
def test_to_rainrate(R, metadata, expected):
"""Test the to_rainrate."""
assert_array_almost_equal(conversion.to_rainrate(R, metadata)[0], expected) | 5,297,458 |
def snmp_list(snmpstring=None, hostfilter=None, host=None):
"""Returns a list of SNMP information for a host or hostfilter
:param snmpstring: A specific SNMP string to list
:param hostfilter: Valid hostfilter or None
:param host: t_hosts.id or t_hosts.f_ipaddr
:return: [ [ record_id, ipaddr, hostna... | 5,297,459 |
def page(fn, args, cursor_key='max_id', get_cursor=lambda r: r.get('next_max_id'), wait=5):
"""
A helper method to page through a feed/listing api call
.. code-block:: python
from instagram_private_api import Client
from instagram_web_api import WebClient
from instagram_private_api... | 5,297,460 |
def func5(X, pth, v0, a, b, c, d):
"""
Function that represents the curve to fit error rates to in order to determine the threshold. (see:
arXiv:quant-ph/0207088)
Probabilities are fine as long as p > 1/(4*distance). See paper by Watson and Barrett (arXiv:1312.5213).
Args:
X:
a:
... | 5,297,461 |
def login(app_name='spotify'):
"""Start the OAuth login process.
Query Parameters
----------------
complete : {yes, no}, default=yes
Direct the OAuth login process to complete; must be 'no' in order to
allow commandline interfaces to successfully authenticate.
"""
app_name = app... | 5,297,462 |
def ACV_A7(T, Hz=50):
"""
Generate a growing sine wave, where the wave starts at 0 and reaches 0.9 of
full amplitude at 250 cycles. Thereafter it will linearly increase to full
amplitude at 500 cycles and terminate to 0
Frequency locked to 50Hz and = 0 at t>10
keyword arguments:
T ... | 5,297,463 |
def init_model():
"""加载训练模型"""
with open('word.txt', encoding="utf-8") as f:
with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as m:
while 1:
pass | 5,297,464 |
def parse_output(output_file):
"""Parse output file for void fraction data.
Args:
output_file (str): path to simulation output file.
Returns:
results (dict): total unit cell, gravimetric, and volumetric surface
areas.
"""
results = {}
with open(output_file) as orig... | 5,297,465 |
def is_positive_integer(obj, name: str) -> None:
"""Checks if obj is a positive integer and
raises appropriate errors if it isn't.
Arguments:
obj: object to be checked.
name (str): name of object for error messages.
"""
if type(obj) != int:
raise ValueError(f"{name} should ... | 5,297,466 |
def find_max_risk_player_pair(play):
"""
Finds the maximum risk for each player pair
in the play
"""
play_max_risk = play.groupby(['gsisid','gsisid_partner'])[['risk_factor']].max().reset_index()
max_risk_partner = pd.merge(play, play_max_risk)
return max_risk_partner | 5,297,467 |
def patch_transport():
"""
This function path transport constructor to fix timeout in sockets
"""
from amqp.transport import _AbstractTransport
_AbstractTransport.__init__ = new_transport_init | 5,297,468 |
def replace_import_names(
source_store,
from_to_dict,
target_store=None,
dryrun=True,
verbose=True,
replacer_factory=mk_import_root_replacer,
add_comment_at_the_end_of_lines_replaced=False,
):
"""Replace import names.
Use case: You've renamed something or moved some modules (remembe... | 5,297,469 |
def my_mixup_cutmix(batch):
"""Apply mixup to half the batch, and cutmix to the other."""
batch = dict(**batch)
bs = tf.shape(batch['images'])[0] // 4
mixup_ratio = batch['mixup_ratio'][:bs, None, None, None]
mixup_images = (mixup_ratio * batch['images'][:bs]
+ (1.0 - mixup_ratio) * batch['i... | 5,297,470 |
def lambda_handler(event, context):
"""Lambda function for recursive Fibonacci"""
return fibonacci(event["n"]) | 5,297,471 |
def test_update_wishlist_book_does_not_exist(client, sample_user):
"""Assert that trying to put a book that does not exist into a wishlist returns a 404 error."""
data = {
'book_id': '1', 'password': 'p4$$VV0RD'
}
res = client.put(f"/users/wishlist/{sample_user['data']['id']}", data=data)
as... | 5,297,472 |
def unpack_allhits(res, explain=False, es_id='es_id', es_score='es_score', suffix_score='es', es_rank='es_rank'):
"""
Args:
res (dict): raw output of the search engine
explain (bool): if the results have the _explain field from the explain func of ES
es_id (str): 'es_id' name of the key ... | 5,297,473 |
def mssql_service(docker_ip, docker_services):
"""Ensure that Docker service is up and responsive."""
port = docker_services.port_for("sqlserver", 1433)
print("Mssql is running on port {}".format(port))
url = "http://localhost:8585"
time.sleep(180)
docker_services.wait_until_responsive(
... | 5,297,474 |
def fit(ncomp, samples):
"""esitmate gmm model"""
# init and fit model
init_prec = np.eye(2)[np.newaxis,:].repeat(ncomp, axis=0) * 4
est_model = GaussianMixture(ncomp, weights_init=np.ones(ncomp) / ncomp,
precisions_init=init_prec)
est_model.fit(samples)
print '=... | 5,297,475 |
def load(path=None, n_processes=6):
"""10-class image classification form imagenet
Imagenette is a subset of 10 easily classified classes
from Imagenet (tench, English springer, cassette player, chain saw, church,
French horn, garbage truck, gas pump, golf ball, parachute).
Parameters
---------... | 5,297,476 |
def image_extraction_fn(data_record, min_dim):
"""Parses a tf.Example from the tfrecord data"""
features = {
'image/encoded': tf.FixedLenFeature([], tf.string),
'image/object/class/label': tf.FixedLenFeature([], tf.int64),
}
sample = tf.parse_single_example(data_record, features)
... | 5,297,477 |
def combine_cases_t_thresh(cases, gap=datetime.timedelta(hours=12)):
"""Combine cases with echo gaps less than threshold."""
cc = multicase.MultiCase.by_combining(cases)
grpr_orig = grouper_orig(cc)
egaps = echo_gaps(cc)
grouper_new = (egaps>gap).cumsum()+10000
groupers = pd.concat([grouper_new,... | 5,297,478 |
def train_and_evaluate_pmap(model_p: InstantiableParams,
train_input_p: InstantiableParams,
job_log_dir: Optional[str],
restore_checkpoint_dir: Optional[str],
restore_checkpoint_step: Optional[int],
... | 5,297,479 |
def cleanup_volumes():
"""
Delete orphaned volumes so we don't pay for them
"""
volumes = client.describe_volumes()
volume_ids = [v["VolumeId"] for v in volumes["Volumes"] if v["State"] == "available"]
for v_id in volume_ids:
logger.info(f"Deleting orphaned volume {v_id}")
client... | 5,297,480 |
def get_r(request):
""" Prepare the reddit variable handle 'r' for use.
Called mainly as a helper function by view methods proper. """
consumer_key = get_global_option('reddit-consumer-key')
consumer_secret = get_global_option('reddit-consumer-secret')
r = praw.Reddit(REDDIT_BOT_DESCRIPTION)
# ... | 5,297,481 |
def get_phase_correction_periodic(times, freq_hz):
""" Calculate phase correction for the frequencies in the case of moving frequencies,
or otherwise the resulting tone will rise or fall much faster due to the various frequencies
being out of phase with each other.
https://stackoverflow.com/questions/30... | 5,297,482 |
def load_dataframe(fobj, compression='gzip'):
"""Given an open file for `hip_main.dat.gz`, return a parsed dataframe.
If your copy of ``hip_main.dat`` has already been unzipped, pass the
optional argument ``compression=None``.
"""
try:
from pandas import read_fwf
except ImportError:
... | 5,297,483 |
def generate_passphrase(passphrase_length, word_list):
"""Generate the passphrase string.
For each word, read 2 bytes from the kernel-space CSPRNG via ``os.urandom``
and convert them to an integer which serves as a list index. A list of
65,536 words is probably enough so we don't need more than 2 byte... | 5,297,484 |
def enum(*sequential, **named):
"""
Handy way to fake an enumerated type in python.
Example
-------
>>> Numbers = enum(ONE=1, TWO=2, THREE='three')
>>> Numbers.ONE
1
>>> Numbers.TWO
2
>>> Numbers.THREE
'three'
Source
------
"http://stackoverflow.com/questions/36... | 5,297,485 |
def load_dbsnp(dbsnp_files, threads):
"""Creates and populates MongoDB collection for dbSNP variants.
Arguments:
dbsnp_files -- list of one or more files with variants compressed using bgzip and indexed using tabix. File(s) must have 3 tab-delimited columns without header: integer part of rsId, chromosome,... | 5,297,486 |
def get_granted_queue_consumer_config(group_id, topic, version, cluster_type, is_pattern):
"""
获取已经授权的producer记录
:param group_id: 需要授权的topic
:param topic: queue队列 topic
:param version 版本号
:param cluster_type 集群类型
:param is_pattern 是否为正则表示的topic
:return: {list} db中对应的完整记录列表
"""
if... | 5,297,487 |
def getUnitType(index):
"""
Returns the <index>th UnitType.
"""
try:
return UNITS[index]
except IndexError:
BugUtil.error("ReligionUtil - invalid unit type %i", index)
return None | 5,297,488 |
def deploy(relpath='../dist', dryrun=False):
"""
sync folder to s3 bucket
"""
dryrun = prep_bool_arg(dryrun)
INPUT_PATH = os.path.join(cwd, relpath)
OUTPUT_PATH = os.path.join(cwd, '../.gzip')
# Wipe the old .gzip folder
shutil.rmtree(OUTPUT_PATH, ignore_errors=True)
# Create output ... | 5,297,489 |
def log(level: int, msg, *args, **kwargs):
"""Log the given message at the given log level. See ``logger`` lib."""
f = log_function(level)
if f is not None:
f(msg, *args, **kwargs) | 5,297,490 |
def download_dataset():
"""
Download full cats vs dogs dataset
"""
os.system("python -m wget https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip -o" + DOWNLOAD_ZIP) | 5,297,491 |
def get_account_history():
"""
get_account_history
"""
account = request.args.get('account', None)
if account is None:
return jsonify({})
token = request.args.get('token', None)
limit = request.args.get('limit', 100)
offset = request.args.get('offset', 0)
hist_type = request... | 5,297,492 |
def token_view(request, token):
"""Show form to let user set password.
"""
i = get_object_or_404(Invitation, token=token)
if i.is_expired():
raise Http404
if request.method == 'GET':
try:
user = User.objects.get(email=i.accepter)
if user.is_active is True:
... | 5,297,493 |
def view_round_matches(r0und):
""" Displays the list of the matches of a given round.
The display is different depending on whether the matches are over or not.
If the match are all over, the results are displayed too.
"""
view = f"\n ### Matchs du Tour {r0und.round_nb + 1} " \
f"du Tou... | 5,297,494 |
def _match_by_tag(inp, params):
"""Match joints by tags. Use Munkres algorithm to calculate the best match
for keypoints grouping.
Note:
number of keypoints: K
max number of a image: M
L: 2 if use flip test else 1
Args:
inp(tuple):
tag_k (np.ndarray[KxMxL]):... | 5,297,495 |
def mean_(x, dimension, track_types = True, **kwargs):
"""Calculate the mean of a set of values.
Parameters
----------
x : :obj:`xarray.DataArray`
The data cube to be reduced.
dimension : :obj:`str`
Name of the dimension to apply the reduction function to.
track_types : :obj:`bool`
... | 5,297,496 |
async def test_client_proto_packet_received() -> None:
"""
Ensure we properly process received packets
"""
proto = tpt.SNMPClientProtocol(b"SNMP-packet")
proto.datagram_received(b"fake-packet", ("192.0.2.1", 42))
result = proto.future.result()
assert result == b"fake-packet" | 5,297,497 |
def UpdateThresholdRules(ref, args, req):
"""Add threshold rule to budget."""
messages = GetMessagesModule()
client = apis.GetClientInstance('billingbudgets', 'v1beta1')
budgets = client.billingAccounts_budgets
get_request_type = messages.BillingbudgetsBillingAccountsBudgetsGetRequest
get_request = get_requ... | 5,297,498 |
def synonym(
string: str,
threshold: float = 0.5,
top_n=5,
cleaning=augmentation_textcleaning,
**kwargs
):
"""
augmenting a string using synonym, https://github.com/huseinzol05/Malaya-Dataset#90k-synonym
Parameters
----------
string: str
threshold: float, optional (default=0... | 5,297,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.