content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
async def _close_invoke_if(btn, _, user):
"""This button is special in that it will only respond to the author."""
return user == btn.owner.invoked_by.author | d376a53c9784ea0328e634b549a01d5c126283b5 | 633,794 |
def find(predicate, seq):
"""A helper to return the first element found in the sequence
that meets the predicate. For example: ::
member = find(lambda m: m.name == 'Mighty', channel.server.members)
would find the first :class:`Member` whose name is 'Mighty' and return it.
If an entry is not fo... | 1eaf56257f612185d748248f81fbb06b34ec4b76 | 633,795 |
import pickle
def load_from_file(filename):
"""Loads hypha object"""
print("Loading hypha "+filename)
return pickle.load(open(filename, 'rb')) | d91505fea8cef9012b9c0bf3ed410ff911e3d027 | 633,796 |
def scan_available(redis_client):
""""Scan Command is available since redis-server 2.8.0"""
if "scan" in dir(redis_client):
info = redis_client.info()
server_version = info["redis_version"]
version_list = server_version.split(".")
if len(version_list) > 2:
n = int(ve... | b1665269c8a0b8abaaa0866d603b0976ae8e5e54 | 633,797 |
def dom2dict(element):
"""Converts DOM elements to dictionaries of attributes."""
keys = list(element.attributes.keys())
values = [val.value for val in list(element.attributes.values())]
return dict(list(zip(keys, values))) | ecf828218236961d03d7abff71beec15384622ed | 633,799 |
def split(text):
"""
Convenience function to parse a string into a list using two or more spaces
as the delimiter.
Parameters
----------
text : string
Contains text to be parsed
Returns
-------
textout : list
list of strings containing the parsed input text
"""
... | abc45882e8b333a608e65d8e171fc155b9b3e749 | 633,800 |
import requests
def get_playerid(acc_id, server_id):
"""
Function to get the account id of a player by looking up the player's nickname.
:return: player's account id and server or an error message.
"""
account_name = acc_id
server = server_id
params = {'application_id': '6e556537f926af38c... | 0e3b24c0be7959e69d59658094b5e18853930c82 | 633,801 |
def format_time(t, format_spec='dhms'):
"""
Return a formatted time string describing the duration of
the input in seconds in terms of days,hours,minutes and seconds.
"""
if format_spec == '':
sb, mb, hb, db = True, True, True, True
else:
sb = 's' in format_spec
mb = 'm' in format_spec
hb = 'h' in format... | 405e9e914cca2b620704f82c08826d50af7f30ce | 633,802 |
def scale_for_curses(rgb_value: int) -> int:
"""Scale a single RGB value for curses.
:param rgb_value: One RGB value
:returns: The value scaled for curses
"""
curses_ceiling = 1000
rgb_ceiling = 255
return int(rgb_value * curses_ceiling / rgb_ceiling) | 9b1b36466c8f63b249c92bfc91deb39bbcbba651 | 633,803 |
import requests
def minify(file_content:str) -> str:
"""Access Toptal's CSS Minifier API.
Parameters
----------
file_content : str
CSS file content in str format.
Returns
-------
str
Minifier CSS in str format.
"""
payload = {'input': file_content}
url =... | 1a81b822f56262cd18e9405a40c5ee3cdc529726 | 633,804 |
def removeEmoji(msg):
"""
removes non ASCII chars
:param msg:
:return: new_msg with emjoy char removed
"""
new_msg = ""
for ch in msg:
pass
return new_msg | fd4275ccb1dd6b073ad9491fb68e1cc0cfec71cd | 633,805 |
def simple_wsgi(_, start_response):
"""A simple wsgi app that always returns an empty response."""
start_response("200 OK", [("Content-Type", "text/html")])
return [b""] | b0d576bfa684f6d7edb8d54afae680d1b93b91c6 | 633,806 |
import os
def choose_parentdir(dname, dlist):
"""Returns parentdir of dname if its parent is contained in dlist else None.
Example:
dlist =['/Users/mahmudhassan', '/Users/mah/', '/Users/mahmud/Docs/worddocs']
dname = '/Users/mahmud'
Returns None
dlist =['/Users/mahmud... | 39f921fb52fc0c5a2b4a054ca111b8bad2036323 | 633,807 |
def task_dict_to_list(iterator, total_parts, partition_num):
"""
Convert a dictionary to a list to be used as partitions later.
:param iterator:
:param total_parts:
:param partition_num:
:return:
"""
ret = list()
sorted_keys = sorted(iterator.keys())
total = len(sorted_keys)
... | 1be5bccd0d7b156dfc468e0e29a55c547ef66021 | 633,808 |
def count_consecutives(tosses):
"""
Counts the number of consecutive heads or tails.
"""
consecutive_tosses = 1
max_consecutive_tosses = 1
for i in range(0, len(tosses) - 1):
if tosses[i] == tosses[i + 1]:
consecutive_tosses += 1
max_consecutive_tosses = max(max_c... | cc985dce259302f60c124668f539a5d1cd0a2c4e | 633,809 |
def get_target_for_label(label):
"""Convert a label to `0` or `1`.
Args:
label(string) - Either "POSITIVE" or "NEGATIVE".
Returns:
`0` or `1`.
"""
if(label == 'POSITIVE'):
return 1
else:
return 0 | 88b9a7ec3efec5cfa8c26d4651aabe28b1e63adf | 633,810 |
import torch
def boundary_corrected_holland(potential_fn, has_vdW=True):
""" Calculates the log-likelihood ell of a trajectory.
Uses left Riemann sum for integration.
Corrects for the boundary term in the RN. """
def loss_fn(state_traj, drift_traj, dW_traj, dt):
potential = potential_fn(state... | b8c334a75fcb7375a8fe478b679ee0fe424dd0d2 | 633,811 |
from functools import reduce
def format_enum_values(enum) -> str:
"""
Creates and returns a textual representation of an enum's values.
:param enum: The enum to be formatted
:return: The textual representation that has been created
"""
return '{' + reduce(lambda a, b: a + (', ' if l... | fbf87f08438358785c5851d7c5239ea08ff6c141 | 633,813 |
def custom_format(template, **kwargs):
"""
Custom format of strings for only those that we provide
:param template: str - string to format
:param kwargs: dict - dictionary of strings to replace
:return: str - formatted string
"""
for k, v in kwargs.items():
template = template.replac... | 9664bbd5799286f6950b3515e6d4144c0569dcdd | 633,815 |
def extract_emoji(line):
"""extract *unparsed* emoji from the beginning of a line
the emoji may be separated by either ')' or whitespace"""
return line.split(')')[0].split()[0].strip() | d7df25b04fa6d1177d7aca4370117610547c44a5 | 633,816 |
import random
import string
def generate_random_order_id():
"""
Generates a random order id.
:return: A random 6 character string that can be used as order
"""
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=12)) | 84fc45a0d3d47ac29330b5fed25810faefecd108 | 633,817 |
import argparse
import glob
def get_argument_parser() -> argparse.ArgumentParser:
"""Returns the ArgumentParser object for the script."""
parser = argparse.ArgumentParser(
description="Convert Xournal++ files to SVGs.",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
# svg mar... | a7f9f4c4b968b6912fc1e80040f0f041463e3a40 | 633,818 |
def group(s, n):
"""Repack iterator items into groups"""
# See http://www.python.org/doc/2.6/library/functions.html#zip
return zip(*[iter(s)] * n) | 051d86c9985579098894b37f3d743da83f13debb | 633,819 |
def scale_tors_pot(pf_models, to_scale):
""" determine if we need to scale the potential
"""
onedhr_model = bool('1dhr' in pf_models['tors'])
return bool(onedhr_model and to_scale) | d9aae67845b2c6ebac5082ca44cf122be9bdf6c8 | 633,820 |
def invert(dct):
""" Transposes the keys and values in a dictionary
:param dct: dictionary to transpose
:tupe dct: dict
:rtype: dict
"""
return {val: key for key, val in dct.items()} | 29a788c05982c72ee9bb77018ae9fabb402042bb | 633,821 |
def comp_stacked_rating_hist_allbrands(review_item):
"""
Compute rating distributions for all brands
:param review_item: a merged data frame containing item and review info
:return: brands: an ascending list containing names of all brands
scores: an ascending list containing all possible ra... | 55392ce55e137efe8af1746f757fef33430f362f | 633,823 |
def get_int_input(message):
"""
Function to get whole number as input
:param message:
:return:
"""
number = input(message)
if number.isnumeric():
return int(number)
else:
print('Please provide a whole number input.')
return get_int_input(message) | e1f6cc5700d7afa406028ea243b6728570244fcf | 633,824 |
def is_number(term):
"""check if term is a number. Returns bool"""
if isinstance(term, int) or term.isdigit():
return True | 9bf36372e98759d9b1b471de32d0b608fa9143b1 | 633,825 |
import os
def get_user_home_dir():
""" work both on Linux & Windows, this dir will be the parent dir of
the .bru/ dir for storing downloaded tar.gzs on a per-user basis"""
return os.path.expanduser("~") | 38e6b4ff2601b8b65fb0c7ce1be718797325ed90 | 633,826 |
def compact(inDict, keep_if=lambda k, v: v is not None):
"""
Takes a dictionary and returns a copy with elements matching a given lambda removed. The
default behavior will remove any values that are `None`.
Args:
inDict (dict): The dictionary to operate on.
keep_if (lambda(k,v), option... | 68633968b0e1f3e4e22a1f4d4793b3174a00392d | 633,827 |
def all_tag_filter(tags):
"""Return a filter of the element by all the tags for a json post advance search.
:param List of :class:`str` tags: Desired filtering tags
:returns: json structure to call the the asking tasks.
"""
if not isinstance(tags, list):
tags = [tags]
tag_selector = {
... | 099fa9ca372b4bee6f1744eb703b2ed64a97da06 | 633,828 |
import time
def now():
"""Get the current time as seconds since the POSIX epoch (UTC)."""
return time.time() | a1d0f52bea242bcd25ce9b2cabe56cf023a1a578 | 633,829 |
def simple_filter(**kwargs):
"""Return a simple filter that requires all keyword arguments to be equal
to their specified value."""
criteria = []
for key, value in kwargs.items():
criteria.append({'type': 'SIMPLE', 'propertyName': key,
'operator': 'Equals', 'operand': va... | aae4cbd9263345ea6a561ea40ba4f412323c589b | 633,830 |
def lmst(d_time, lon):
"""Calculates Local Mean Sideral Time (lmst) based on D_time
Args:
d_time : time elapsed since Greenwich noon, terrestrial time,
on january 2000, in days.
lon : longitude of the observer
Return:
Local mean sideral time in degrees
"""
# Julian Ephemer... | 71c824fa79cc596f627ebd980995bc6c87217039 | 633,833 |
def fixture_repo_id() -> int:
"""Return a repository ID."""
return 102909380 | abc7cd8e79ba499ce6412ce7c4f8a9216696a573 | 633,834 |
import inspect
def disable_for_loaddata(signal_handler):
"""The signals to update denormalized data should not be called
during loaddata management command (can raise an IntegrityError)"""
def wrapper(*args, **kwargs):
for fr in inspect.stack():
if inspect.getmodulename(fr[1]) == 'load... | ed91b7e354b6ba27ff4cf3da4a26ea94bb0920d4 | 633,835 |
def remove_short_segments(
lbl_tb, segment_inds_list, timebin_dur, min_segment_dur, unlabeled_label=0
):
"""remove segments from vector of labeled timebins
that are shorter than specified duration
Parameters
----------
lbl_tb : numpy.ndarray
vector of labeled spectrogram time bins, i.e.... | c9bf2d57e6a404d268fac4dcae5fef76e6ca3a97 | 633,836 |
def rhino_to_plottable(rhino_geom):
"""Takes rhino polylines or point arrays
and outputs plottable geometries resempling linestrings
"""
return [
(rhino_geom.Point(i).X, rhino_geom.Point(i).Y)
for i in range(rhino_geom.PointCount)
] | fe5471a23141af0c3a87587509669080292dd50a | 633,838 |
def conj(fs):
"""Conjunction of features fs"""
def feature(s, i):
return all(f(s, i) for f in fs)
return feature | 07231ad027a1e6e07f593313b90771cd88df719a | 633,839 |
import re
def dummy_md_index(cigar):
""" Creates dummy MD string from CIGAR in case of missing MD.
cigar: cigar string
Return value: dummy MD string
"""
cigar = re.split(r'([MINDS])', cigar)[:-1]
cigar_index = 0
max_cigar_index = len(cigar)
md = []
while cigar_index != ma... | a96ac96c65804a23074996bcf83c5e8c52f5e0be | 633,840 |
def simple_decorator(pattern=None):
"""Build a simple decorator function from the given pattern.
The decorator will prefix each line with the given pattern. If the given
pattern contains a '{}' placeholder, it will be used as a separator
between the prefix and suffix. In other words, this:
simpl... | e294c491a5443a47cd1b36db0bc7a23beda5ae03 | 633,841 |
def parse_tf_ids(target_tfs_filename):
"""
If user has provided a file with Ensembl transcript ids, parse these to a list.
"""
with open(target_tfs_filename, 'r') as target_tfs_file:
target_tfs_list = target_tfs_file.read().splitlines()
target_tfs_list = [x.upper() for x in target_tfs_l... | 0f29175e300c651588bddcf3c98e76c5c39abcea | 633,842 |
from typing import List
def acumulate_l1_by_l2(l1 : List[float], l2 : List[List[float]]) -> List[List[float]]:
"""
Splits a list (l1) using the shape of l2.
Args:
l: List of floats
Returns: List of list of floats divided by the shape of l2
Example: [0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.... | 6f80d24b3f1fb4b289a93fb9862d3b2a4f38c4e4 | 633,843 |
def Lax(cfg, Uo, Courant):
"""Return the numerical solution of dependent variable in the model eq.
This routine uses the explicit Lax method
to obtain the solution of the
first-order 1D wave equation or inviscid Burgers equation.
Call signature:
Lax(cfg, Uo, Courant)
Parameters
-... | 07316c77a3834ea16a7f25a1a243db6d5105a40b | 633,844 |
def rhoh_from_rho_p(gamma, rho, p):
"""
Given rho and p, return h
"""
return rho + gamma / (gamma - 1) * p | 6eb97d9242c87ca58b9cea66edcd161c3d5ac72a | 633,845 |
def strfdelta(tdelta, fmt):
"""Utility function. Formats a `timedelta` into human readable string."""
d = {"days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
return fmt.format(**d) | 0057311e65dc8517a46ff4bbaff53b4e99417187 | 633,847 |
def grouper(text):
"""
Group text into triplets
"""
source = text[1:][:-1]
forward = text[2:]
backward = text[:-2]
X = (source, forward, backward)
return X | 72a845777265c7397ac2c41ad29d1afb0e7ab05f | 633,848 |
def dimensions_from_entity_types(entity_types):
"""
Args:
entity_types (list)
Returns:
(list)
"""
entity_types = entity_types or []
dims = set()
for entity_type in entity_types:
if entity_type == "sys_interval":
dims.add("time")
if entity_type.sta... | c62d576ba42e0672f84457cd7de8c9fdf692ee3f | 633,849 |
import torch
def torch_multivariate_gaussian_heatmap(coordinates, H, W, dist, sigma_factor, ratio, device, rot=False):
"""
Create Gaussian Kernel for CWS
"""
ax = torch.linspace(0, H, H, device=device) - coordinates[1]
ay = torch.linspace(0, W, W, device=device) - coordinates[0]
xx, yy = torch... | 753ed915c3e6b8c9a4af9327beeda6af9b833ab3 | 633,850 |
from typing import Any
import functools
import inspect
def is_coroutine_function(obj: Any) -> bool:
"""
Correctly determines if an object is a coroutine function,
including those wrapped in functools.partial objects.
"""
while isinstance(obj, functools.partial):
obj = obj.func
return i... | 9bd275de3f27c6b7e6653eb052e9dd45f3832688 | 633,851 |
def is_kernel_module_loaded(module_name):
"""
Checks whether the kernel module with the specified name is loaded.
Args:
module_name (str) : Name of the module to check.
Returns:
True, if the module is loaded; otherwise False.
"""
with open("/proc/modules") as file:
lin... | 3b5018e05c494d7791eb994a2433c2062ee91589 | 633,852 |
def GenerateAnnulusRZPhiToNode(nRCoords, nZCoords, phiPoints):
"""
Generate the map from r, z phi IDs to node IDs for a structured 3D linear
tet annulus mesh
"""
rzphiToNode = []
index = 0
for i in range(nRCoords):
rzphiToNode.append([])
for j in range(nZCoords):
rzphiToNode[i].append([]... | 0a017582fe5cc3c6fd72fc44e90aa69f08e7be09 | 633,853 |
def needed_qt_libs(mname):
"""Return a list of libraries needed by the specified module.
@type: c{str}
@mname: The name of the module.
@return: c{list} of library names (.e.g qtcore.lib)
"""
libs = []
# The dependencies between the different Qt libraries. The order within
... | b07721bf306ec5982abba4b93b42ae2630f4ebb2 | 633,854 |
def my_command(**kwargs: dict) -> str: # type: ignore
"""Text that will appear in the help section"""
# kwargs will hold user, channel, text (from a Slack message object)
# use them like this, or just delete these line:
user = kwargs.get("user") # noqa: F841
channel = kwargs.get("channel") # noq... | 9dd23272211a8ea169c8d401264e5ac45cbfed8a | 633,855 |
def _label(files_info):
"""Get a suitable label for the files.
Returns "config-2" if the openstack metadata is present.
"""
if any(x.startswith('openstack/') for x in files_info.values()):
return 'config-2'
else:
return 'VMEDIA_BOOT_ISO' | 0004ada97072343f69fa10d7ee4120306239bde7 | 633,856 |
import argparse
def get_parser():
"""get params from cmd python bmatFilter.py -<item> [parma]
Returns:
object: Object instance of argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(
description="filter of bmat/bmat.gz, filter param全是与或非中的与关系,也就是条件同时成立!"
)
parser.add_... | 172935b3bc5dcf7816ab5a3de782c52008034d01 | 633,857 |
def clip_command(command):
"""Is this a clip command?
:param command: string
"""
# It is possible to have `\clip` or `SELECT * FROM \clip`. So we check
# for both conditions.
return command.strip().endswith('\\clip') or command.strip().startswith('\\clip') | 3b2b167ea36f8e095dcda22708a18cd5cf809e64 | 633,858 |
def le_matriz():
"""Recebe a dimensao da matriz"""
lin = int(input("Digite o número de linhas da matriz: "))
col = int(input("Digite o número de colunas da matriz: "))
return lin, col | 8d7ad16d6b7c33166e1372c8aadef3a28433a669 | 633,859 |
def sum_digits(n):
"""Calculate the sum of digits.
Parameters:
n (int): Number.
Returns:
int: Sum of digitis of n.
Examples:
>>> sum_digits(42)
6
"""
s = 0
while n:
s += n % 10
n //= 10
return s | b017b1ad886c65536bd47316f92cc14b9ab0885c | 633,861 |
def create_test_data():
"""Use the longest example for our test data
Returns
-------
list
opcode from the examples
"""
test_list = [1, 1, 1, 4, 99, 5, 6, 0, 99]
return test_list | c926580cbad8ecb0831568c5f5fce485c4cb4f80 | 633,862 |
import difflib
def calculate_delta(actual_svg: str, expected_svg: str) -> str:
"""Calculate diff of two SVG images."""
delta = difflib.unified_diff(
actual_svg.splitlines(),
expected_svg.splitlines(),
"actual",
"expected",
lineterm="",
)
return "\n".join(delta) | 368c4402e7fa9c99ed160c12f809baba157031ab | 633,863 |
import os
import sys
def toLinesArray(file):
""" toLinesArray(file)
Converte um arquivo de texto em um array de suas linhas
Entradas:
file: O arquivo a ser convertido
Saída:
array: Um array em cada elemento é uma liha do arquivo original
"""
fileToConvert = os.path.join(sys.pat... | a8d9fa7d88841ad3702ccce92b49748a6d5bf424 | 633,864 |
def load_local(estimator, path):
"""Loads estimator checkpoints from a local path."""
estimator.load(path)
return path | 41a664ebb3fa5abe5a7a370e0f02589c34e2f3f0 | 633,865 |
def _get_starting_age(postgame, de_data):
"""Get starting age."""
if de_data is not None:
return (de_data.starting_age_id, de_data.starting_age)
if postgame is not None:
return (postgame.starting_age_id, postgame.starting_age)
return (None, None) | 110c09095915c74462b24c87f4bd500ffcf639f9 | 633,866 |
def keep_only_max_recips(dic_ranks, max_recips=10):
"""
Keeps only top @max_recips for each mid in dic_ranks
Input and output dic in same format : {mid:[sender1, sender2, ...], }
Also converts mid key from str to int if needed !
"""
cropped_recips = {}
for mid, recipients in dic_ranks.items(... | a597c20df1f2f006aed1065b2b81a768931c9ea7 | 633,867 |
import numpy
def create_array():
"""Creates a simple 3D numpy array with unique values at each
location in the matrix.
"""
rows, cols, depth = 2, 3, 4
arr = numpy.zeros((rows, cols, depth), 'i')
count = 0
for i in range(rows):
for j in range(cols):
for k in range(depth... | a7f7cb9a4a7c255ddb4ee356f1310783a2300d3b | 633,868 |
def Pad(ids, pad_id, length):
"""Pad or trim list to len length.
Args:
ids: list of ints to pad
pad_id: what to pad with
length: length to pad or trim to
Returns:
ids trimmed or padded with pad_id
"""
assert pad_id is not None
assert length is not None
if len(ids) < length:
a = [pad... | 3533e3d38c6f5ed4dae25b565ce2805a9b55c2ef | 633,869 |
def checker_iris(final_location):
"""
和真实的聚类结果进行校验比对
"""
right = 0.0
for k in range(0, 3):
checker = [0, 0, 0]
for i in range(0, 50):
for j in range(0, len(final_location[0])):
if final_location[i + (50 * k)][j] == 1:
checker[j] += 1
... | 5ddf520de4f4ecca51daedba6023b4335b9e0fd6 | 633,870 |
def get_quota(module, blade):
"""Return Filesystem User Quota or None"""
fsys = []
fsys.append(module.params["name"])
try:
if module.params["uid"]:
res = blade.quotas_users.list_user_quotas(
file_system_names=fsys, filter="user.id=" + str(module.params["uid"])
... | e617c3d74e6bb9258ab2ab385a2c51e8ed35291a | 633,871 |
import re
def value_matches_regex(value, pattern_list):
"""
:param str value:
:param list[str] pattern_list:
:rtype: bool
"""
return any((re.match(pattern, value) is not None) for pattern in pattern_list) | 5a81347b4a657824d02db046b9930ddcd56327e9 | 633,872 |
import csv
def read_symbols(symbol_file='symbols.csv'):
"""
Read symbols.
Parameters
----------
symbol_file : str
Path to a CSV (with ',' as delimiter) which contains one symbol label
in the second colum
Returns
-------
list
Of symbol labels
"""
with o... | 65cc8c41f860c779ab8d8a1f94266fbc9930ea5a | 633,874 |
def extract_inventions_dreamcoder(dc_json):
"""
extract the learned inventions from a dreamcoder json file and sort by length
"""
return sorted([prod["expression"] for prod in dc_json["DSL"]["productions"] if prod["expression"].startswith("#")], key=len) | b32831439a5f7729004604a2765a9f20bf443871 | 633,875 |
from functools import reduce
def rcompose(*fns):
"""Right compose for stack, left compose to traverse stack afterwards for
Clojure style transducers. This is an _intended_ pun on 'reducer compose',
i.e., you should use it to compose against the reducer argument to
transduce if you want to use a Clojur... | 7b388b605255e31cef2862f4bafda9ca7b2cac17 | 633,876 |
import argparse
def parse_args():
"""
:rtype: dict
"""
parser = argparse.ArgumentParser()
parser.add_argument('url_to_m3u8', help="Url to main.m3u8")
parser.add_argument('download_dir', help="Path to save files")
parser.add_argument('-v', '--verbose', action="store_true", help="Be more ve... | 9fbee3e2efce6d16d1f531c408f43f5919b946ea | 633,877 |
def load_cluster_labels(clusterpath, one_indexed=True):
"""
one_indexed: if true, assume cluster index starts at 1 (e.g. as in 2018_scMCA data)
"""
cluster_labels = {}
if one_indexed:
dec = 1
else:
dec = 0
# expected format of csv file is "cluster number, name"
with open(... | fed3adb9dc9c5653aaf05548a8c7e6d5739f6e82 | 633,878 |
def initialize_dict(data, values):
"""
Description:
intialiezed all values in a given list in a dict to 0
Args:
data - the dictionary to work on (dict)
values - the keys to intialize to 0 (list)
Returns:
A dictionary with all keys in values set equal to 0
Raises:
... | 48a7377ef4ed1577d077a444e949b4a9b8a909bb | 633,879 |
from typing import List
from typing import Dict
from typing import Any
def exact_str_match_fn(targets: List[str], responses: List[str]) -> Dict[str, Any]:
"""Exact match between targets and responses."""
# aitor: might want to use these metrics after removing irrelevant words.
# they do something like thi... | e36a81358cdbd3eee383b827cfac79bbdb29c99d | 633,880 |
import argparse
def parse_args(args):
""" Parse the arguments.
"""
parser = argparse.ArgumentParser(description='Evaluation script for the AIR detector.')
subparsers = parser.add_subparsers(help='Arguments for specific dataset types.', dest='dataset_type')
subparsers.required = True
coco_... | 46d43db1d22ad13b58c1b80fcb1ea7cb00b4f113 | 633,881 |
def parse_coverage_list(coverage_list):
"""
Given a coverage_list (structured as a list of coverage statements (which
are strings) that define the poset, parses them into a dictionary.
Parameters
----------
coverage_list : `list`
list of coverage statements defining a poset, e.g.:
... | 9715bd6fed1c3d032ef5ef5524429c35a7370307 | 633,882 |
def TakeEnsemble(vect, ensembleIds, isDataVect=False):
"""
>>> v = [10,20,30,40,50]
>>> TakeEnsemble(v,(1,2,3))
[20, 30, 40]
>>> v = ['foo',10,20,30,40,50,1]
>>> TakeEnsemble(v,(1,2,3),isDataVect=True)
['foo', 20, 30, 40, 1]
"""
if isDataVect:
ensembleIds = [x + 1 for x in ... | 18bc784f371aff1e79dd879d4a2c13ba01c6176d | 633,884 |
def group_scans_custom(array, header, scans):
"""Custom time window version of group_scans.
Use when a custom time window is wanted, and not the default 1.5-2 second window.
Assumes the middle of the firing window is the actual bottle close, then computes
needed scans and reaches forwards and backwards ... | cb506b4dcdbabb9965d4d7f813439ef542641931 | 633,885 |
def m(eigenvalues):
"""
>>> m(np.array([1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.05, 0.025]))
11
"""
i = 2
m = 0
while i < len(eigenvalues) and m == 0:
if eigenvalues[i] <= eigenvalues[1]*0.1:
return i+1
i = i+1
if m == 0:
return max(round(len... | 76f4c69c57a316b8c8b52798e8f5ebaad3722b20 | 633,886 |
def author_name(author):
"""
Rewrite author name in a specific form:
Take the last word that is present in 'author'. Set that as last name.
If a different word is present, take the first letter. If not, set a default of X.
e.g. the name 'Albert de Vries' gets turned into 'A. Vries';
... | de7831b5f5e9dd4225275e3dc07d6608697aa9ee | 633,887 |
def type(resource, resource_type):
"""
We need to check if a specific resource type is greater that 3
"""
count = 0
for r in resource:
if r.resource.name == resource_type:
count += 1
return count | 20a63d652e56c155783d676d7edec90032271d80 | 633,888 |
def update_pos(pos1,pos2):
"""
Get the coordinate of the bounding box containing two parts
:param pos1: Coordinate of the first part.
:param pos2: Coordinate of the second part.
:return: Coordinate of the bounding box containing the two parts
"""
x1 = min(pos1[0],pos2[0])
y1 = min(pos1[1... | db671fb75640436852e96e86b3af96985e52e605 | 633,889 |
def FOG(conf, value):
"""Get FOG Color code from config"""
if value == 1:
return conf.get_color("colors", "color_fog1")
else:
return conf.get_color("colors", "color_fog2") | bc50f383f2fe42e47ed95b00fc8d579529513322 | 633,891 |
def is_id(argument: str) -> bool:
"""
Determines whether the given argument is a valid id (i.e. an integer).
:param argument: the string argument to evaluate
:return: true if the argument can be evaluated as an interger, false otherwise
"""
try:
int(argument)
except ValueError:
... | 280ca87168366e9c4fae6c4e7297cdabc9ee497e | 633,892 |
def author_clean(author):
""" Clean an author and return the formatted string """
replace = [".", ";", " ", ",", "_", "-"]
author_split = author.strip().split(",")
clean_author = ""
if len(author_split) >= 2:
last_name = author_split[0]
first_name = author_split[1]
for rep in... | 85f43ab0d8d2c6f40508a3770aad0d24c75daaa1 | 633,893 |
def fill_array(x,x_val):
"""
fill_array(x,x_val)
If x_val[i] != None then x[i] == x_val[i].
"""
constraints = []
for i in range(len(x)):
if x_val[i] != None:
constraints += [x[i] == x_val[i]]
return constraints | 68c5260a95a4cf23daf556b225cc270152b21088 | 633,894 |
import re
def replace_version(line, new_version, regex):
"""
COPIED FROM TITO
Attempts to replace common setup.py version formats in the given line,
and return the modified line. If no version is present the line is
returned as is.
Looking for things like version="x.y.z" with configurable ca... | d394cdca52be26bcde5a70d20b9c6b9c6ddd8753 | 633,895 |
from typing import Callable
from typing import Optional
from typing import Any
def contains(f: Callable) -> Callable:
"""
Checks if an index is within an attribute's array
"""
def wrap(self: object, attr: str, x: Optional[Any] = None, i: Optional[int] = None) -> bool:
try:
arr = self.__dict__[attr]
if i ... | 6428ffa4dbf896caf9f891e44d06882752d91130 | 633,896 |
from typing import Union
def fibonacci(num: int, *, ret_text: bool = False) -> Union[list, str]:
"""
Generates the sequence of Fibonacci
>>> from snakypy import helpers
>>> helpers.calcs.fibonacci(50)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> helpers.calcs.fibonacci(50, ret_te... | 99969eff62b2d4bcd1f79c16e4a378cfdf64d925 | 633,897 |
def simplify(ints: list) -> list:
"""
In order to speed up the process we should simplify
the input list by reducing duplicate values, see sample below:
[1,4,5,1,1,1,1,1,4,7,8] >>> [1,4,5,1,4,7,8]
:param ints: a list of integers
:return: simplified list of integers
"""
result = list()
temp = -1
for i in in... | d01efca30b790983035bf4837cb62848124d431f | 633,898 |
def hex_uid(uid_raw):
"""
Convert key to Hex string
:param uid_raw: Input UID
:return: Hex string
"""
uid_list = list(uid_raw)
uid_hex_str = ""
for uid_item in uid_list:
uid_hex = format(uid_item, 'x')
if len(uid_hex) == 1:
uid_hex = "0" + uid_hex
uid_... | c4d8a9fe6cfc50ea42efb8d11c1f1954b01ae93e | 633,899 |
import re
def search_prs(log):
"""
Search lines of text for PR numbers
"""
# Find all matches using regex iterator, using the PR # as the group match
resultlist = [str(m.group(1)) for m in re.finditer(r"erge pull request #(\d+)", log)]
return sorted(resultlist) | f2628dc6457cc3b1aa2b6e89b4cdefbfd1078b47 | 633,900 |
def market_usage():
"""Buying and selling resources at the market."""
query = """
select
players.match_id, timestamp::interval(0),
player_number as number,
case when action_id=122 then 'Gold' else resources.name end as sold_resource,
(amount * 100) as sold... | 0ec310bbaf1c00bb9fc7d52ea014d23d85f41168 | 633,901 |
import click
def question(text, *args, **kwargs):
"""
Args:
text:
*args:
**kwargs:
"""
return click.prompt(text=text, *args, **kwargs) | a87e5eba7b8540620beb10bdd3c5053b96d3b463 | 633,903 |
import csv
def load_inputs(inputs_file):
"""Load Inputs for AutoSpider."""
with open(inputs_file, 'Ur') as f:
data = list(tuple(rec) for rec in csv.reader(f, delimiter=','))
return data | fb6f53eea739237c96489ef10f653aab96d0e6c5 | 633,904 |
def calculateMatrixSize(sample_count: int) -> int:
"""
2 - 1 2 - 3
- - 1 -
1 - 2 3
3 - 3 3 - 6
- - - 1 - -
1 - - 2 3 -
2 3 - 4 5 6
4 - 6 4 - 10
- - - - 1 - - -
1 - - - 2 3 - -
2 3 - - 4 5 6 -
4 ... | ed8932ddbf7429a5642d9b4b2f21c7e715988a75 | 633,905 |
def _quote(text):
"""
Quote the given string so ``_split_quoted`` will not split it up.
:param str text: The string to quote:
:return: A str string representing ``text`` as protected from
splitting.
"""
return (
'"' +
text.replace("\\", "\\\\").replace('"', '\\"') +
... | 24224ed6a0cac7cf4cb6207081e87ad095c07e59 | 633,906 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.