content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def memcached_clean(request, memcached_client, do_memcached_clean):
"""Clean memcached instance."""
if do_memcached_clean:
memcached_client.flush_all() | 5,302,000 |
def get_max_node(candidates, gr_values, column_prefix=""):
"""Given a set of candidate nodes, and return the one with the
highest Gain Ratio.
Args:
candidates (list): List of candidate nodes.
gr_values (dict): Dictionary with column names as keys and
the corresponding Gain Rat... | 5,302,001 |
def tablefy(data, column=None, gutter=1, width=79):
"""
Convert a list of strings into being a table, displaying in a left-to-right
and top-to-bottom pattern. This does not sort the values.
:param data: list of strings
:param column: width of column, if None, detected
:param gutter: width of g... | 5,302,002 |
def slice_hyper(model, input_data, output_data, n_vertices, sorted_partition):
"""
:param model:
:param input_data:
:param output_data:
:return:
"""
grouped_input_data = group_input(input_data=input_data, sorted_partition=sorted_partition, n_vertices=n_vertices)
inference = Inference(train_data=(grouped_input_... | 5,302,003 |
def stations_by_distance(stations, p):
"""This function uses haversine to calculate the distance between all the UK river monitoring stations
and a given co-ordinate named in this function as p. We then return a list of the stations as instances
of MonitoringStations and sort the list by the distances to th... | 5,302,004 |
def once(func):
"""
Decorate func so it's only ever called the first time.
This decorator can ensure that an expensive or non-idempotent function
will not be expensive on subsequent calls and is idempotent.
>>> func = once(lambda a: a+3)
>>> func(3)
6
>>> func(9)
6
>>> func('12... | 5,302,005 |
def pytest_pyfunc_call(pyfuncitem):
"""
Run asyncio marked test functions in an event loop instead of a normal
function call.
"""
for marker_name, fixture_name in _markers_2_fixtures.items():
if marker_name in pyfuncitem.keywords:
event_loop = pyfuncitem.funcargs[fixture_name]
... | 5,302,006 |
def shutil_idfolder_byTspan(Fspan = 18, shutil_func=shutil.copy):
"""
@param Fspan: 该id的trajectory的时间跨度需要大于等于 1s,当前程序 1s 对应的是18帧左右
@return:
"""
dir_src = r'D:\work\dset\cue_mot_Data\compare_index_yhw\patch_ids\\'
dir_dst = r'D:\work\dset\cue_mot_Data\compare_index_yhw\ge{}frame_p... | 5,302,007 |
def contourAverage(inputC):
"""Function that approximate a contour by a line inside the contour.
It realizes the mean of the lines of two points on a same column.
If there is one point or strictly more than 2 points in a same
column, the column is not considered and no mean is realized.
... | 5,302,008 |
def repeat(x, repeats, axis=None):
"""Repeat elements of an array.
It returns an array which has the same shape as `x`, except
along the given axis. The axis is used to speficy along which
axis to repeat values. By default, use the flattened input
array, and return a flat output array.
The num... | 5,302,009 |
def test_fact_author_setter(garbage, test_fact_empty_fx):
"""
Assert that a TypeError is thrown, if the wrong type is passed to the property.
"""
test_fact = test_fact_empty_fx
with pytest.raises(TypeError):
test_fact.author = garbage | 5,302,010 |
def ptb_raw_data(data_path=None, vocab_path=None, args=None):
"""Load PTB raw data from data directory "data_path".
Reads PTB text files, converts strings to integer ids,
and performs mini-batching of the inputs.
The PTB dataset comes from Tomas Mikolov's webpage:
http://www.fit.vutbr.cz/~imikolov/rnnlm/... | 5,302,011 |
def test_include_context(get_loader, hello_include, hello_import):
"""
Context variables are passes to the included template by default.
"""
_, jinja = get_test_saltenv(get_loader)
result = jinja.get_template("hello_include").render(a="Hi", b="Salt")
assert result == "Hey world !Hi Salt !" | 5,302,012 |
def process_log_data(spark, input_data, output_data):
"""
1. Process raw logs dataset using Spark and create Users and Time dimensional tables stored in S3.
2. Process both raw logs and songs dataset and create Songplays fact table stored in S3.
"""
print('Start processing log data...')
... | 5,302,013 |
def format_search_filter(model_fields):
"""
Creates an LDAP search filter for the given set of model
fields.
"""
ldap_fields = convert_model_fields_to_ldap_fields(model_fields)
ldap_fields["objectClass"] = config.LDAP_AUTH_OBJECT_CLASS
search_filters = import_func(config.LDAP_AUTH_FORMAT_SEA... | 5,302,014 |
def play_data(audio_data, audio_fs):
"""
Plays a data array (in the numpy format).
"""
# write to temporary wave file and reproduce it
write("temp.wav", audio_fs, audio_data)
play_wav("temp.wav")
os.remove("temp.wav")
return | 5,302,015 |
def explore_match(win, img1, img2, kp_pairs, status = None, H = None, show=True):
"""
This function draws a set of keypoint pairs obtained on a match method of a descriptor
on two images imgf and imgb
:param win: window's name (str)
:param img1: image1 (numpy array)
:param img2: image2 (numpy ar... | 5,302,016 |
def get_sorted_list_of_expr_not_in_use(path_to_db: str) -> list:
"""
Only expressions that are not in use can be deleted
This list is used in the dropdown menu of expressions to be deleted
Args:
path_to_db: filename of the SQL database containing
a JSON entry that returns a... | 5,302,017 |
def register_decriptor(file_descriptor) -> None:
"""Registers enums and messages defined by protobuf file DESCRIPTOR.
"""
for msg_desc in file_descriptor.message_types_by_name.values():
_msgreg.store(ProtoMessageType(msg_desc.full_name, msg_desc._concrete_class))
for enum_desc in file_descriptor... | 5,302,018 |
def test_errors_cli(error, classinfo):
"""Ensure that exception types remain consistent."""
assert issubclass(error, IsilonHadoopToolError)
assert issubclass(error, directories.DirectoriesError)
assert issubclass(error, classinfo) | 5,302,019 |
def missing_query(*args, **kwags):
"""
A query returning something not in the local DB
"""
response = {
'responseHeader': {'params': {'rows': 1}},
'response': {
'numFound': 1,
'docs': [{
'id': 'abcde',
'chec... | 5,302,020 |
def _element_basis(string: str):
"""
Parse element and basis from string
Args: str
Returns: element, basis
"""
cut_list = string.split(".")
element = cut_list[0]
basis = " ".join(cut_list[1:])
return element, basis | 5,302,021 |
def loads(*args, **kwargs): # pragma: no cover (!CPython) # TODO
"""
Alias of :func:`json.loads`.
"""
return json.loads(*args, **kwargs) | 5,302,022 |
def test_guloso_teo(vertices, arestas, cores):
"""
Testes da função que implementa o algoritmo heurístico
guloso com base em teoremas da literatura. A quantidade de cores
é exata.
"""
algoritmos_gulosos = Gulosos()
G = igraph.Graph()
G.add_vertices(vertices)
G.add_edges(arestas)
... | 5,302,023 |
def calc_hist(img):
"""
To calculate histogram of an RGB image
Parameters
----------
img : Array of uint8
Image whose histogram is to be calculated
Returns
-------
histogram : np.array
The required histogram
"""
histogram = [0] * 3
for j in ... | 5,302,024 |
def upper_bound(x):
"""Return the upper bound of interval x."""
"*** YOUR CODE HERE ***"
return x[1] | 5,302,025 |
def proportion_linear(time_right: float,
time_between: float,
time_step: float) -> tuple:
"""
:param time_right: right border in time
:param time_between: time between borders
:param time_step: step in time between borders
:return: _Iterable_(alpha, beta)
... | 5,302,026 |
def create_custom_field(field_name: str, label: str, models: List, apps, cf_type: Optional[str] = "type_date"):
"""Create custom field on a given model instance type.
Args:
field_name (str): Field Name
label (str): Label description
models (List): List of Django Models
apps: Dja... | 5,302,027 |
def getusercid(username):
"""
getusercid(string) -> string
tries to retrieve the CID of an avatar for a name to cid lookup
"""
getuser = 'http://www.imvu.com/catalog/web_av_pic.php?av=%s' % (username)
r = requests.get(getuser)
link = r.url
cid = link[link.index('avatars/')... | 5,302,028 |
def channels(sound_object):
"""
DETERMINE IF A SOUND OBJECT IS MONO OR STEREO
RETURN AN INTEGER REPRESENTING THE NUMBER OF CHANNELS (1, 2, 4, 6)
CHANNEL 4 and 6 ARE NOT IMPLEMENTED YET (NEW FEATURE IN SDL 2.0)
:param sound_object: numpy.ndarray; Sound samples into an array
:return: int; re... | 5,302,029 |
def validate_request():
""" This method validates the Request payload.
Args
expected_args(tuple): where i = 0 is type and i > 0 is argument to be
validated
Returns
f(*args, **kwargs)
"""
def real_validate_request(f):
@wraps(f)
def decorated(... | 5,302,030 |
def mr2rho(w,t,p):
"""rho = mr2rho(w,t,p)
w in g/kg
t in K
p in mb
This was provide by Holger Linne' from Max Planck Institute.
Dave Turner
Pacific Northwest National Laboratory
Currently at the University of Wisconsin-Madison
dave.turner@pnl.gov
"""
rho = w * (p * 0.3477) / t
return rho | 5,302,031 |
def dir_to_cart(v, lattice):
"""
Convert direct coordinates to cartesian.
Parameters
----------
v : ndarray
| Dimension: (3)
The direct vector to be converted.
lattice : ndarray
| Dimension: (3,3)
The crystal lattice, where the first lattice vector is
[... | 5,302,032 |
def parse_conf(stream, profile=PARSECONF_MID, encoding=None):
"""
Parse a .conf file. This is a wrapper around :func:`parse_conf_stream` that allows filenames
or stream to be passed in.
:param stream: the path to a configuration file or open file-like object to be parsed
:type stream: str, file
... | 5,302,033 |
def fetch_new_sushi_data_task():
"""
Fetch sushi data for dates and platforms where they are not available
"""
with cache_based_lock('fetch_new_sushi_data_task', blocking_timeout=10):
fetch_new_sushi_data() | 5,302,034 |
def test_failure(database):
""" Test failure for PrimaryPlaceOfPerformanceCode must be 00FORGN when PrimaryPlaceofPerformanceCountryCode
is not USA, not 00FORGN otherwise. """
det_award_1 = DetachedAwardFinancialAssistanceFactory(place_of_performance_code="00FORGN",
... | 5,302,035 |
def alpine2(x):
"""Alpine 2's function.
It can be used with 'n' variables and has minimum at -2.808^n.
Also, it is expected to be within [0, 10] bounds.
Args:
x (np.array): An n-dimensional input array.
Returns:
y = -prod(sqrt(x) * sin(x))
"""
# Declaring Alpine 2's func... | 5,302,036 |
def enum(*sequential, **named):
"""
Create enumeration-like classes, see: http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python
A possibly better (yet heavier) recipe is here: http://code.activestate.com/recipes/67107/
"""
enums = dict(zip(sequential, range(len(sequential)... | 5,302,037 |
def fileSelected(selection):
"""
Here's how to play back a sample.
The first line gives you a way to choose the audio file.
The (commented, optional) second line allows you to stream the audio rather than loading it all at once.
The third line creates a sample player and loads in the Sample.
Sa... | 5,302,038 |
def get_block_time():
"""
Returns block time
Currently hardcoded
"""
return 0.25 | 5,302,039 |
def ur5():
"""Return a UR5 created programatically instead of from a file."""
return Robot('ur5',
joints=[
Joint('shoulder_pan_joint', 'revolute', 'base_link', 'shoulder_link'),
Joint('shoulder_lift_joint', 'revolute', 'shoulder_link', 'upper_arm_link')... | 5,302,040 |
def get_rpm_packager(rpm_file_path):
""" returns the rpm package PACKAGER tag """
fnull = open(os.devnull, 'w')
return subprocess.Popen('rpm -qp --queryformat "%{PACKAGER}" ' +
rpm_file_path,
stdout=subprocess.PIPE,
stderr=f... | 5,302,041 |
def wav_format_code(encoding=None):
"""Calculate the format code for 'pcm16' encoded 'wav' files."""
if not encoding:
encoding = 'pcm16'
return construct_format('wav', encoding) | 5,302,042 |
def detect_supported_hardware():
"""Determine if UART for this Raspbery Pi is supported"""
with open("/proc/device-tree/model", encoding="ascii") as file:
model_string = file.readline().rstrip()
for model in SUPPORTED_MODELS:
if model in model_string:
LOGGER.info("Detected suppo... | 5,302,043 |
def _check_error(error_code: int) -> None:
"""Helper function, to check given error_code"""
error_code = ErrorCode(error_code)
if error_code.value != 0:
location = inspect.stack()[1][3]
raise RuntimeError(f"Error in {location}() -> {error_code}") | 5,302,044 |
def main():
"""Entry point"""
import re
from datetime import datetime
from .. import __version__
from ..classifier.helper import CVHelper
warnings.showwarning = warn_redirect
opts = get_parser().parse_args()
log_level = int(max(3 - opts.verbose_count, 0) * 10)
if opts.verbose_coun... | 5,302,045 |
def get_model_device(model: nn.Module) -> torch.device:
"""
The device the `model` is on (assuming that all
the model parameters are on the same device).
"""
return get_next_parameter(model).device | 5,302,046 |
def uninstall():
"""Unload and remove the launchd script that keeps this script running
"""
launch_script = get_launch_script_path()
with settings(warn_only='true'):
local('launchctl unload ' + launch_script)
local('rm ' + launch_script)
local('rm /tmp/send_temperature-err.log')
... | 5,302,047 |
def write_file(
mt_object,
fn,
file_type=None,
longitude_format="lon",
latlon_format="dms",
overwrite=False,
):
"""
write a file based on extension or file type
:param fn: DESCRIPTION
:type fn: TYPE
:param file_type: DESCRIPTION, defaults to None
:type file_type: TYPE, o... | 5,302,048 |
def _create_asset_group_operation(
client,
customer_id,
final_url,
headline_asset_resource_names,
description_asset_resource_names,
):
"""Creates a list of MutateOperations that create a new asset_group.
A temporary ID will be assigned to this asset group so that it can
be referenced by... | 5,302,049 |
def _get_special_odd_composite_numbers() -> Iterable[int]:
"""Get odd composite numbers
that cannot be written as the sum of a prime and twice a square."""
primes = {2}
for odd_number in count(start=3, step=2):
if is_prime(odd_number):
primes.add(odd_number)
else:
... | 5,302,050 |
def test(links, walf):
"""test sample graph,
take graph,
return true/false
"""
node1 = random.choice(walf)
node2 = random.choice(walf)
print ("looking for path from", node1, "to node", node2)
links = relink(links, walf)
# find way using depth first search
res1, way = dfs(links... | 5,302,051 |
def browser():
"""Return an instance of chrome headless browser."""
br = Browser("chrome", headless=True)
yield br
br.quit() | 5,302,052 |
def plain(*numbers):
"""
Example function which accepts multiple positional arguments.
The arguments are plain integers.
:param int numbers: Numbers to display
"""
for number in numbers:
print(number) | 5,302,053 |
def check_column_header(maf_df, in_maf_file):
"""Check that in_maf_file have all 34 standard MAF columns."""
columns = list(maf_df)
missing_columns = list(set(std_MAF_columns) - set(columns))
if len(missing_columns) > 0:
raise Exception("Missing standard MAF column(s) %s in input_maf %s." % (... | 5,302,054 |
def reno(ghi, ghi_clearsky):
"""Identify times when GHI is consistent with clearsky conditions.
Uses the function :py:func:`pvlib.clearsky.detect_clearsky`.
.. note::
Must be given GHI data with regular (constant) time intervals
of 15 minutes or less.
Parameters
----------
ghi ... | 5,302,055 |
def get_decoder(encoding, *args, **kwargs):
"""
Returns a L{codec.Decoder} capable of decoding AMF[C{encoding}] streams.
@raise ValueError: Unknown C{encoding}.
"""
def _get_decoder_class():
if encoding == AMF0:
try:
from cpyamf import amf0
except Imp... | 5,302,056 |
def add(inputs_list):
"""
Add input tensors list
Parameters
----------
inputs_list: Input tensors list
"""
return Add()(inputs_list) | 5,302,057 |
def jars_from_output(output):
"""Collect jars for intellij-resolve-files from Java output."""
if output == None:
return []
return [jar
for jar in [output.class_jar, output.ijar, output.source_jar]
if jar != None and not jar.is_source] | 5,302,058 |
def init_gpu_memory_growth():
"""Sets TensorFlow to allocate memory on GPU as needed instead of
all at once.
"""
for gpu in tf.config.list_physical_devices("GPU"):
tf.config.experimental.set_memory_growth(gpu, True) | 5,302,059 |
def hz_warping(
frequency: Union[float, np.ndarray],
warp_factor: Union[float, np.ndarray],
boundary_frequency_ratio: Union[float, np.ndarray],
highest_frequency: float
):
"""Performs piece wise linear warping of frequencies in Hz.
http://www.cs.toronto.edu/~ndjaitly/jaitly-icml1... | 5,302,060 |
def mock_post(mocker, mocked_json):
"""Mock post with successful json response"""
mocked = mocker.patch(
"requests.post",
autospec=True,
return_value=mocker.Mock(
spec=Response, status_code=HTTP_200_OK, json=mocked_json
),
)
yield mocked | 5,302,061 |
def class_permissions(cls, permission_list):
"""
Associate a permissions list to a class
"""
stored_permissions = _class_permissions.setdefault(cls, [])
stored_permissions.extend(permission_list) | 5,302,062 |
def lint():
"""get that linty fresh feeling"""
return max(
map(
call,
[
["isort", "-rc", *ALL_PY],
["black", *ALL_PY],
["flake8", *ALL_PY],
# ["pylint", *ALL_PY],
["mypy", *PY_SRC],
[... | 5,302,063 |
def satellite(isochrone, kernel, stellar_mass, distance_modulus,**kwargs):
"""
Wrapping the isochrone and kernel simulate functions.
"""
mag_1, mag_2 = isochrone.simulate(stellar_mass, distance_modulus)
lon, lat = kernel.simulate(len(mag_1))
return mag_1, mag_2, lon, lat | 5,302,064 |
def run_base(
experience,
device,
use_interactive_logger: bool = False
):
"""
Runs Naive (from BaseStrategy) for one experience.
"""
def create_sub_experience_list(experience):
"""Creates a list of sub-experiences from an experience.
It returns a list of expe... | 5,302,065 |
def check_negation(text, NEGATION_MAP):
"""
Utility function to check negation of an emotion
:param text: text chunk with the emotion term
:return: boolean value for negation
"""
neg_word_list = NEGATION_MAP
neg_match = False
for neg_word in neg_word_list:
if neg_word.strip() in ... | 5,302,066 |
def init_args():
"""
:return:
"""
parser = argparse.ArgumentParser()
parser.add_argument('--net', type=str, help='The network you used', default='xception')
parser.add_argument('--dataset', type=str, help='The dataset', default='ilsvrc_2012')
parser.add_argument('--weights_path', type=str, ... | 5,302,067 |
def latex_to_unicode(string):
"""Returns a unicode representation from latex strings used by pyFAI.
.. note:: The latex string could be removed from the pyFAI core.
:param str string: A latex string to convert
:rtype: str
"""
string = string.replace("$", u"")
string = string.replace("^{-2}... | 5,302,068 |
def return_viewer(structure: Structure, labels: list = None):
"""Returns nglview viewer with oxidationstates labels"""
coords = structure.cart_coords # - atoms.get_center_of_mass()
visualizer = nv.show_pymatgen(structure, center=False, dis=False)
visualizer.clear_representations()
visualizer.compon... | 5,302,069 |
def load_teacher_models(file_list, num_classes, config, strategy):
"""Loads teacher models for distillation."""
teacher_config = copy.deepcopy(config)
teacher_config.proj_dim = -1
num_teacher_models = len(file_list)
teacher_models = [[]] * num_teacher_models
for i in range(num_teacher_models):
with stra... | 5,302,070 |
def _tree_to_json(clf, features, labels, node_index=0):
"""Structure of rules in a fit decision tree classifier
Parameters
----------
clf : DecisionTreeClassifier
A tree that has already been fit.
features, labels : lists of str
The names of the features and labels, respectively.
... | 5,302,071 |
def align(q, p):
"""Align
Aligns the desired formation p onto the current swarm state q.
This is a wrapper to decide if we should do 2D or 3D Arun.
in:
q dxn np.array (d is 2D or 3D) - current state
p dxn np.array - desired formation
out:
paligned dxn... | 5,302,072 |
def api_simulationData(simulation_type, simulation_id, pretty=False, section=None):
"""First entry point for a simulation
Might be non-session simulation copy (see `simulation_db.CopyRedirect`).
We have to allow a non-user to get data.
"""
#TODO(pjm): pretty is an unused argument
#TODO(robnagle... | 5,302,073 |
def find_bean_by_name(jsn, nme):
"""
Extracts a bean of the given name from jmx metrics json object.
"""
if 'beans' not in jsn:
return None
else:
return next((b for b in jsn['beans'] if b['name'] == nme), None) | 5,302,074 |
def convert_datetime_to_timestamp(dt):
"""Convert pandas datetime to unix timestamp"""
return int(dt.timestamp()) | 5,302,075 |
def delete_session(db, usernick):
"""remove all session table entries for this user"""
flowTowCursor = db.cursor()
flowTowCursor.execute("DELETE FROM sessions WHERE usernick = ?", [usernick])
db.commit() | 5,302,076 |
def archive(request, name=None, slug=None, year=None, month=None):
"""
Parameters
----------
name:
Tag name
slug:
Tag slug
year:
Article year (published_date)
month:
Article month (published_date), most likely in norwegian written format.
"""
articles... | 5,302,077 |
def test_can_slice_pipeline():
"""If we slice a pipeline, we should get a new pipeline object"""
pipe1 = make_partial_pipeline(
Cleaner(),
make_concat(
Identity(),
HyphenTextPrep(),
),
HashingVectorizer(),
LogisticRegression()
)
slice = pi... | 5,302,078 |
def get_indicator_type_value_pair(field):
"""
Extracts the type/value pair from a generic field. This is generally used on
fields that can become indicators such as objects or email fields.
The type/value pairs are used in indicator relationships
since indicators are uniquely identified via their ty... | 5,302,079 |
def test_renamed_propagates_to_autosave(editor_plugin_open_files, mocker):
"""Test that editor.renamed() propagates info to autosave component if,
and only if, renamed file is open in editor.
Regression test for spyder-ide/spyder#11348"""
editor_factory = editor_plugin_open_files
editor, expected_f... | 5,302,080 |
def vertica_python_conn(config: dict,
account: str='user',
server: str='vertica',
use_ssl: bool=False):
"""
Generate vertica_python configuration object from configuration.
Args:
config -- dictionary that optionally contains config... | 5,302,081 |
def doc_arg(name, brief):
"""argument of doc_string"""
return " :param {0}: {1}".format(name, brief) | 5,302,082 |
def var_usage_namespace_region(view, var_usage):
"""
Returns the namespace Region of var_usage, or None.
For some (odd) reason, a var_usage might not have name row & col.
"""
try:
name_row_start = var_usage["name-row"]
name_col_start = var_usage["name-col"]
name_row_end = ... | 5,302,083 |
def display_discounted_cash_flow(
ticker: str, number: int, quarterly: bool = False, export: str = ""
):
"""Financial Modeling Prep ticker discounted cash flow
Parameters
----------
ticker : str
Fundamental analysis ticker symbol
number: int
Number to get
quarterly: bool
... | 5,302,084 |
def _ordinals_to_nn(ordinal, nn=False):
"""Ordinals 1-99 int to string. Reverse in separate func calling on this func. Parsing and returning strings of the type "9." will be the task of a higher func"""
if type(ordinal) is int:
if ordinal < 10 and ordinal != 0:
if nn == False:
... | 5,302,085 |
def decode_message(G, coded_msg):
"""
Function that decodes given message using the given generator matrix.
Firsly we create all combinations of length n, where n is the number of rows of the matrix, of zeros and ones.
Then each combinations is transposed and multiplied by the generator matrix until the... | 5,302,086 |
def test_write_raises_when_fmt_does_not_exists(tmpdir):
"""Inspired by https://github.com/mwouts/jupytext/issues/462"""
nb = new_notebook()
tmp_md = str(tmpdir.join("notebook.md"))
with pytest.raises(JupytextFormatError):
jupytext.write(nb, tmp_md, fmt="unknown_format") | 5,302,087 |
def assign_colors(classes):
"""
Assigns colors to specific classes
:param classes: ``Dict[class_id, "name of class"]``, dictionary of class names
:return: ``Tuple(Tuple(R,G,B))``, list of colors format RGB
"""
colors = np.random.randint(80, 255, size=(len(classes), 3), dtype='int32')
# bio
... | 5,302,088 |
def add_point_sup_config(cfg):
"""
Add config for point supervision.
"""
# Use point annotation
cfg.INPUT.POINT_SUP = False
# Sample only part of points in each iteration.
# Default: 0, use all available points.
cfg.INPUT.SAMPLE_POINTS = 0 | 5,302,089 |
def get_frames(user_id):
"""Video streaming generator function."""
video = cv2.VideoCapture(0)
while True:
rval, frame = video.read()
if not rval:
load_faces()
break
else:
new_frame = frame[:, :, ::-1]
locations, face_encoding... | 5,302,090 |
def lib_to_orig_opt_rep(s):
"""
Translates an option from the form used by Tidy python to the form used by the Tidy utility.
"""
if gen_utils.is_bool_type(s):
if s:
return 'yes'
return 'no'
return s | 5,302,091 |
def example_project(tmp_path):
""" a minimal project
"""
my_module = tmp_path / "my_module"
starter_content = my_module / "starter_content"
starter_content.mkdir(parents=True)
(tmp_path / "README.md").write_text("# My Module\n")
(my_module / "__init__.py").write_text("__version__ = '0.0.0\n... | 5,302,092 |
def update_page(wiki, path, version, comment=_DEFAULT_PAGE_UPDATE_MESSAGE, content=None, file_path=None,
organization=None, project=None, detect=None):
"""Edit a page.
:param wiki: Name or Id of the wiki.
:type wiki: str
:param path: Path of the wiki page.
:type path: str
:param... | 5,302,093 |
def test_update_category():
"""Test that categories can be updated"""
results = []
category_obj = prism.Categories(api_client=_api())
categories = [
{'name': 'test_category', 'description': 'api test category updated'},
]
for category in categories:
category_obj.set_category(**... | 5,302,094 |
def uu_query_STK_SHAREHOLDER_FLOATING_TOP10():
"""
十大流通股东
获取上市公司前十大流通股东的持股情况,包括持股数量,所持股份性质,变动原因等
:param :query(finance.STK_SHAREHOLDER_FLOATING_TOP10):表示从finance.STK_SHAREHOLDER_FLOATING_TOP10这张表中查询上市公司前十大流通股东的持股情况,还可以指定所要查询的字段名,格式如下:query(库名.表名.字段名1,库名.表名.字段名2),多个字段用英文逗号进行分隔;query函数的更多用法详见:sqlalchemy.o... | 5,302,095 |
def parallelize(data, method):
"""
Helper method for parallelization
"""
cores = mp.cpu_count()
data_split = np.array_split(data, cores)
pool = mp.Pool(cores)
data = pd.concat(pool.map(method, data_split))
pool.close()
pool.join()
return data | 5,302,096 |
def foo():
"""
example function documentation
an example doctest is included below
returns: None
>>> x = foo()
>>> x
'foo'
"""
return "foo" | 5,302,097 |
def string_date(mnthDay, year):
"""Return a string date as 'mm/dd/yyyy'.
Argument format:
'mm/dd' string
'yyyy'"""
return(mnthDay + '/' + str(year)) | 5,302,098 |
def check_who_queued(user):
"""
Returns a function that checks if the song was requested by user
"""
def pred(song):
if song.requested_by and song.requested_by.id == user.id:
return True
return False
return pred | 5,302,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.