content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_fixed_weight_optimiser(initial_weights, expected_weights):
"""
Tests initialisation and 'pass through' capability of
FixedWeightPortfolioOptimiser.
"""
dt = pd.Timestamp('2019-01-01 00:00:00', tz=pytz.UTC)
data_handler = DataHandlerMock()
fwo = FixedWeightPortfolioOptimiser(data_han... | 4,300 |
def _UpdateCountsForNewFlake(start_date):
"""Updates counts for new, re-occurred or rare flakes.
Args:
start_date(datetime): Earliest time to check.
"""
more = True
cursor = None
while more:
ndb.get_context().clear_cache()
flakes, cursor, more = Flake.query().filter(
Flake.last_occurre... | 4,301 |
def save_quotas() -> None:
"""Create or update existing project quotas."""
nova = nova_client.Client(
version='2.1',
session=settings.OPENSTACK_SESSION,
endpoint_type='public',
)
cinder = cinder_client.Client(
version='3.40',
session=settings.OPENSTAC... | 4,302 |
def main():
"""
the application startup functions
:return:
"""
app = QtWidgets.QApplication(sys.argv)
# set stylesheet
file = QFile("UI/dark.qss")
file.open(QFile.ReadOnly | QFile.Text)
stream = QTextStream(file)
app.setStyleSheet(stream.readAll())
main_window = QtWidgets.... | 4,303 |
def balance_generic(array: np.ndarray, classes: np.ndarray, balancing_max: int, output: int, random_state:int=42)->Tuple:
"""Balance given arrays using given max and expected output class.
arrays: np.ndarray, array to balance
classes: np.ndarray, output classes
balancing_max: int, maximum nu... | 4,304 |
def jsexternal(args, result, **kwds):
"""Decorator to define stubbed-out external javascript functions.
This decorator can be applied to a python function to register it as
the stubbed-out implementation of an external javascript function.
The llinterpreter will run the python code, the compiled interp... | 4,305 |
def get_icon(filename):
""" """
icon = get_image_path(filename)
if icon:
return QIcon(icon)
else:
return QIcon() | 4,306 |
def permission_confirm(perm_key_pair: list) -> Union[bool, str, None]:
"""Converts string versions of bool inputs to raw bool values."""
if perm_key_pair[1].strip() == 'true': pi = True
elif perm_key_pair[1].strip() == 'false': pi = False
elif perm_key_pair[1].strip() == 'none': pi = None
else: pi =... | 4,307 |
def _parse_policy_controller(configmanagement, msg):
"""Load PolicyController with the parsed config-management.yaml.
Args:
configmanagement: dict, The data loaded from the config-management.yaml
given by user.
msg: The Hub messages package.
Returns:
policy_controller: The Policy Controller co... | 4,308 |
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data))) | 4,309 |
def _type_cast(type_cast: Any, content_to_typecast: bytes, func_dict: dict) -> Any:
"""
Basis for type casting on the server
If testing, replace `func_dict` with a dummy one
Currently NOT guarenteed to return, please remember to change this API
"""
if type_cast == bytes:
return content_t... | 4,310 |
def paster_create(package, tempdir, user, template, email, fullname):
"""
Run paster to create a new package given a template and user info.
"""
dist_root = os.path.join(tempdir, package)
name = get_name(user)
email = get_email(user)
url = '%s/%s/%s' % (config.GITHUB_URL, user, package)
... | 4,311 |
def report_trend(old_report, new_report, html_tag):
"""
Report the trending
"""
if 'trend' in old_report and 'trend' in new_report:
old_trend = analysis.trend(old_report)
new_trend = analysis.trend(new_report)
if old_trend['short term'] != new_trend['short term']:
pri... | 4,312 |
def get_data_dir() -> Path:
"""
Get the pda data dir
"""
app_name = "pda"
app_author = "StarrFox"
cache_dir = Path(appdirs.user_data_dir(app_name, app_author))
cache_dir.mkdir(parents=True, exist_ok=True)
return cache_dir | 4,313 |
def directory_structure_to_front_matter(file_path: str) -> dict[str, str]:
"""
Converts the directory structure of a recipe into a front matter.
"""
# Make sure the path is well-formed and normalised
path_to_recipe = os.path.normpath(file_path)
# Unpack the directory structure into variable nam... | 4,314 |
def is_gradle_build_python_test(file_name):
"""
Return True if file_name matches a regexp for on of the python test run during gradle build. False otherwise.
:param file_name: file to test
"""
return file_name in ["gen_all.py", "test_gbm_prostate.py", "test_rest_api.py"] | 4,315 |
def ppis_as_cxs(ppis, cxs):
"""
Use the complex number to both prefix the protein id and add as an
attribute. Copy the original ids to the end for mapping in cytoscape.
"""
ppis = ppis_label_cxs(ppis, cxs)
# Requires that the last column be a list of complex ids. Replace that.
def pfx(id, cx... | 4,316 |
def patch_get(monkeypatch, mockresponse):
"""monkeypatch the requests.get function to return response dict for API calls. succesful API responses come from Tradier website.
:param mockresponse: [description]
:type mockresponse: [type]
:return: [description]
:rtype: [type]
:yield: [description]
... | 4,317 |
def test_reaction_auto2():
"""
init
auto
0 7
4 7
4 4
4 4
end
"""
print('init')
m = MyObject3()
print(m.report.get_mode())
loop.iter()
# Invoke the reaction by modifying foo
m.set_foo(3)
m.set_foo(4)
loop.iter()
# Or bar
m.set_bar(3)
m.se... | 4,318 |
def test_compare_img_hist():
"""
Test Command
------------
$ python run_tests.py --module_name plot_playground.tests.test_img_helper:test_compare_img_hist --skip_jupyter 1
"""
_remove_test_img()
img = Image.new(mode='RGB', size=(50, 50), color='#ff0000')
img.save(TEST_IMG_PATH_... | 4,319 |
def _split_out_parameters(initdoc):
"""Split documentation into (header, parameters, suffix)
Parameters
----------
initdoc : string
The documentation string
"""
# TODO: bind it to the only word in the line
p_res = __parameters_str_re.search(initdoc)
if p_res is None:
retu... | 4,320 |
def test_steps_reject():
"""Test the correct rejection for an invalid steps Datapoint."""
acc_tester = AcceptanceTester('steps')
dp = Datapoint(datetime(2018, 1, 1, 12, 0, 0), -1)
assert acc_tester(dp) is False | 4,321 |
def print_command(cmd):
""" print command in custom window """
t_custom.insert(END, cmd + " ") | 4,322 |
def get_context() -> RequestContext:
""" See GlobalContextManager.get_context()
"""
return global_context_manager.get_context() | 4,323 |
def create_fixed(parent,fixed):
"""
Function checks for fixed field and if valid creates an
SKOS elements for each position in an OrderedList
:param parent: Parent element
:param fixed: Fixed position value, may include range notation
in format of xx-xx
"""
if fixed != 'n/... | 4,324 |
def crazy_lights(length=100, wait_time=1):
"""
Function to build a playlist of crazy blinking lights.
"""
# get the busylight opbject
bl = BusyLight()
random_colors = np.random.randint(0,255, size=(length,3))
for r,g,b in random_colors:
bl.set_color(r,g,b)
bl.add_to_playlist... | 4,325 |
def show_raid_configuration(ctx, profile, configuration):
""" Get the matching RAID profile or fail """
raid_recipe = RAIDRecipe(ctx.obj['client'])
config_data = raid_recipe.get_selected_configuration(configuration, profile=profile)
print(json.dumps(config_data, indent=4, sort_keys=True)) | 4,326 |
def extract(filepath, output, usebasename=False, outputfilenamer=None):
"""
Load and extract each part of MIME multi-part data as files from given data
as a file.
:param filepath: :class:`pathlib.Path` object represents input
:param output: :class:`pathlib.Path` object represents output dir
:pa... | 4,327 |
def main():
"""Main entry point."""
current_dir = os.getcwd()
project_name = os.path.basename(current_dir)
parser = pbs.comments.Parser()
for filename in os.listdir(current_dir):
language = parser.infer_language(filename)
with open(filename, 'r') as source_file:
procedure... | 4,328 |
def Main():
"""Main generates the size difference between two targets.
"""
parser = argparse.ArgumentParser(
description='Size difference between two targets')
parser.add_argument(
'--source_project', required=True, help='The path to the source project')
parser.add_argument(
'--source_schem... | 4,329 |
def sched_yield(space):
""" Voluntarily relinquish the CPU"""
while True:
try:
res = rposix.sched_yield()
except OSError as e:
wrap_oserror(space, e, eintr_retry=True)
else:
return space.newint(res) | 4,330 |
def preformatted(s):
"""Return preformatted text."""
return _tag(s, "pre") | 4,331 |
def jitter_colors(rgb, d_brightness=0, d_contrast=0, d_saturation=0):
"""
Color jittering by randomizing brightness, contrast and saturation, in random order
Args:
rgb: Image in RGB format
Numpy array of shape (h, w, 3)
d_brightness, d_contrast, d_saturation: Alpha for blending ... | 4,332 |
def split_numpy_array(array, portion=None, size=None, shuffle=True):
"""
Split numpy array into two halves, by portion or by size.
Args:
array (np.ndarray): A numpy array to be splitted.
portion (float): Portion of the second half.
Ignored if `size` is specified.
size (i... | 4,333 |
def test_sinkhorn_consistency_sym_asym(solv, entropy, atol, p, m, reach):
"""Test if the symmetric and assymetric Sinkhorn
output the same results when (a,x)=(b,y)"""
entropy.reach = reach
cost = euclidean_cost(p)
a, x = generate_measure(2, 5, 3)
f_a, g_a = solv.sinkhorn_asym(
m * a, x, ... | 4,334 |
def make_valid(layer):
"""update invalid shapes in postgres
"""
sql = f'UPDATE {layer} SET shape = ST_MakeValid(shape) WHERE ST_IsValid(shape) = false;'
unfixable_layers = ['utilities.broadband_service']
if layer in unfixable_layers:
return
try:
execute_sql(sql, config.DBO_CONN... | 4,335 |
def test_protmap():
"""CRG: extract protein-->iLocus mapping from GFF3"""
db = genhub.test_registry.genome('Dqcr')
mapping = {'DQUA011a006022P1': 'DquaILC-14465',
'DQUA011a006023P1': 'DquaILC-14466',
'DQUA011a006024P1': 'DquaILC-14467'}
infile = 'testdata/gff3/dqua-275-loci... | 4,336 |
def constraint_layer(
stencils: Sequence[np.ndarray],
method: Method,
derivative_orders: Sequence[int],
constrained_accuracy_order: int = 1,
initial_accuracy_order: Optional[int] = 1,
grid_step: float = None,
dtype: Any = np.float32,
) -> tf.keras.layers.Layer:
"""Create a Keras layer for ... | 4,337 |
def test_cancellation_with_infinite_duration(http_test_server_fixture):
"""Test that we can use signals to cancel execution."""
args = [
http_test_server_fixture.nighthawk_client_path, "--concurrency", "2",
http_test_server_fixture.getTestServerRootUri(), "--no-duration", "--output-format", "json"
]
... | 4,338 |
def parse_excel_xml(xml_file=None, xml_string=None):
"""Return a list of the tables (2D arrays) in the Excel XML.
Provide either the path to an XML file, or a string of XML content.
"""
handler = ExcelHandler()
if xml_file is not None:
parse(xml_file, handler)
elif xml_string is not Non... | 4,339 |
def test_init_with_no_child_kernel(concat_kernel_function):
"""
Test that creating a `ConcatKernel` with no child kernel raises an exception.
"""
with pytest.raises(AssertionError) as exp:
concat_kernel_function([])
assert str(exp.value).find("There must be at least one child kernel.") >= 0 | 4,340 |
def load_stt_plugin(module_name):
"""Wrapper function for loading stt plugin.
Arguments:
module_name (str): Mycroft stt module name from config
Returns:
class: STT plugin class
"""
return load_plugin(module_name, PluginTypes.STT) | 4,341 |
def remove_all_autobash_sections_from_backup():
"""Remove all autobash sections from the backup file."""
PROFILES = 'profiles'
LAYOUTS = 'layouts'
AUTOBASH_STR = 'autobash-'
config = ConfigObj(TERMINATOR_CONFIG_BACKUP_FILE)
# remove autobash profiles
# print("REMOVING PROFILES")
for pro... | 4,342 |
def writeToExportedModule(moduleName, prefix, exporModuleTpl, functionsList, outputDir):
"""
Write the binding file for the module
"""
filePath = os.path.join(outputDir, prefix + moduleName + ".cpp")
out = file (filePath, "wb")
out.write (exporModuleTpl.render(moduleName = moduleName, exportFunc... | 4,343 |
def copy_nucleotide_peptide_sketches(
peptide_sketch_dir,
nucleotide_sketch_dir,
pre_sketch_id_outdir,
nucleotide_sketch_ids=NUCLEOTIDE_SKETCH_IDS,
peptide_sketch_ids=PEPTIDE_SKETCH_IDS,
select_cell_ids=None,
dryrun=False,
cell_id_fun=None
):
"""Copy both nucleotide and peptide sketc... | 4,344 |
def backward_softmax(
x, dc_decomp=False, convex_domain={}, slope=V_slope.name, mode=F_HYBRID.name, previous=True, axis=-1, **kwargs
):
"""
Backward LiRPA of softmax
:param x:
:param dc_decomp:
:param convex_domain:
:param slope:
:param mode:
:param axis:
:return:
"""
i... | 4,345 |
def predict_label(model, data, as_prob=False):
"""Predicts the data target
Assumption: Positive class label is at position 1
Parameters
----------
name : Tensorflow or PyTorch Model
Model object retrieved by :func:`load_model`
data : DataCatalog
Dataset used for predictions
... | 4,346 |
def meshW_plan(insert):
"""
Inserts/retracts W mesh (post-M0M1)
insert bool: ``True`` if should insert, ``False`` to retract
"""
yield from _diagnostic_plan(insert,5) | 4,347 |
def show_subpath(subpath):
"""
使用转换器,为变量指定规则为 path类型(类似 string ,但可以包含斜杠)
"""
# show the subpath after /path/
return 'Subpath %s' % escape(subpath) | 4,348 |
def backward_propagation(parameters, cache, X, Y):
"""
Implement the backward propagation using the instructions above.
Arguments:
parameters -- python dictionary containing our parameters
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
X -- input data of shape (2, number of example... | 4,349 |
def MakeCdfFromHist(hist, name=''):
"""Makes a CDF from a Hist object.
Args:
hist: Pmf.Hist object
name: string name for the data.
Returns:
Cdf object
"""
return MakeCdfFromItems(hist.Items(), name) | 4,350 |
def box_iou(boxes, clusters):
"""
Introduction
------------
计算每个box和聚类中心的距离值
Parameters
----------
boxes: 所有的box数据
clusters: 聚类中心
"""
box_num = boxes.shape[0]
cluster_num = clusters.shape[0]
box_area = boxes[:, 0] * boxes[:, 1]
#每个box的面积重复9次,对应9个聚类中心
b... | 4,351 |
def addr(arr):
""" Get address of numpy array's data """
return arr.__array_interface__['data'][0] | 4,352 |
def rank_five_cards(cards):
"""Returns an (array) value that represents a strength for a hand.
These can easily be compared against each other."""
# List of all card values
values = sorted([card.number for card in cards])
# Checks if hand is a straight
is_straight = all([values[i] == values... | 4,353 |
def test_data_p1_no_gas():
"""TODO."""
data: Data = Data.from_dict(json.loads(load_fixtures("data_p1_no_gas.json")))
assert data
assert data.smr_version == 50
assert data.meter_model == "ISKRA 2M550T-101"
assert data.wifi_ssid == "My Wi-Fi"
assert data.wifi_strength == 100
assert data.... | 4,354 |
def upload(d_list: List[Dict], upload_urls: List[str]):
"""Upload to FHIR server"""
for base_url in upload_urls:
for d in d_list:
# Reason for adding ID to url: https://www.hl7.org/fhir/http.html#update
url = f'{base_url}/{d["id"]}'
response = requests.put(url, json=d... | 4,355 |
def action_path(args):
"""show path to selected backup"""
b = Restore()
b.evaluate_arguments(args)
sys.stdout.write('{}\n'.format(b.current_backup_path)) | 4,356 |
def _get_wmi_wbem():
"""Returns a WMI client connected to localhost ready to do queries."""
client, _ = _get_win32com()
if not client:
return None
wmi_service = client.Dispatch('WbemScripting.SWbemLocator')
return wmi_service.ConnectServer('.', 'root\\cimv2') | 4,357 |
def make_ndx(mpirun, scan_atoms, index_input, np=1):
"""
Python wrapper for gmx make_ndx
Parameters
----------
index_input : str
file (with extension) used for gmx make_ndx
mpirun : bool
Is this a multi-node run or not gmx (False) vs gmx_mpi (Default: True)
number of pro... | 4,358 |
def get_skmtea_instances_meta(version, group_instances_by=None) -> Dict[str, Any]:
"""
Args:
group_by (str, optional): How to group detection labels.
Currently only supports grouping by "supercategory".
"""
assert group_instances_by in [None, "supercategory"], f"group_by={group_inst... | 4,359 |
def join_arrays(a, b):
"""
Joining Arrays Row-wise
Parameters
----------
a : array
One of the arrays
b : array
Second of the arrays
Returns
-------
arr : array
Joined two arrays row wise
"""
return (np.r_[a, b]) | 4,360 |
def notify_user(dataset_obj_id, user_id) -> None:
"""Send an email notification to user
If the gui_user is specified, we will send the notification to the person
that is doing actions via the GUI. Otherwise, we will notify the user that
created the ContactJob.
"""
user = User.objects.get(id=use... | 4,361 |
def test_list_g_month_day_max_length_nistxml_sv_iv_list_g_month_day_max_length_1_1(mode, save_output, output_format):
"""
Type list/gMonthDay is restricted by facet maxLength with value 5.
"""
assert_bindings(
schema="nistData/list/gMonthDay/Schema+Instance/NISTSchema-SV-IV-list-gMonthDay-maxLen... | 4,362 |
def psvd(a: np.ndarray):
"""Photonic SVD architecture
Args:
a: The matrix for which to perform the svd
Returns:
A tuple of singular values and the two corresponding SVD architectures :math:`U` and :math:`V^\\dagger`.
"""
l, d, r = svd(a)
return rectangular(l), d, rectangular(r... | 4,363 |
def vmatrix(vma):
""" write a variable zmatrix (bohr/radian) to a string (angstroms/degree)
"""
assert automol.zmatrix.v.is_valid(vma)
vma_str = automol.zmatrix.v.string(vma)
return vma_str | 4,364 |
def test_get_pdp_list():
"""
Test the function raises a TypeError if a list is in the input
"""
full_pipe = 1
df_1 = 2
feat = ['a', 'b']
with pytest.raises(TypeError):
pdp = tml.get_pdp(full_pipe, feat, df_1) | 4,365 |
def list_all(request,
next_function: Callable,
response_keyword='items') -> Iterator[Any]:
"""Execute GCP API `request` and subsequently call `next_function` until
there are no more results. Assumes that it is a list method and that
the results are under a `items` key."""
while True:
... | 4,366 |
def test_python_memoization(n=4):
"""Testing python memoization disable via config
"""
x = random_uuid(0)
for i in range(0, n):
foo = random_uuid(0)
assert foo.result() != x.result(
), "Memoized results were used when memoization was disabled" | 4,367 |
def set_above_compare_strategy(analyzer: SensorAvgThreshAnalyzer):
"""
Sets the analyzer's compare strategy as a "greater than" comparison.
:param analyzer: Sensor analyzer to set the strategy to.
"""
analyzer.set_compare_strategy(operator.gt) | 4,368 |
def quote_etag(etag_str):
"""
If the provided string is already a quoted ETag, return it. Otherwise, wrap
the string in quotes, making it a strong ETag.
"""
if ETAG_MATCH.match(etag_str):
return etag_str
else:
return '"%s"' % etag_str | 4,369 |
def dummy_func_1(input_array):
"""
a sample fitness function that uses the closeness of fit to a polynomial with random coefficients to calculate
fitness (loss)
Args:
input_array(array): iterable of 16 floats between 0 and 1
Returns:
loss(float): an approximation of how close the p... | 4,370 |
def validation_loop(sess, model, ops, handles, valid_summary_writer, external=False):
""" Iterates over the validation data, calculating a trained model's cross-entropy. """
# Unpack OPs
batch_loss_op, sentence_losses_op = ops
# Initialize metrics
valid_losses = list()
sentence_losses = list()
... | 4,371 |
def tile_image (layer, z, x, y, start_time, again=False, trybetter = True, real = False):
"""
Returns asked image.
again - is this a second pass on this tile?
trybetter - should we try to combine this tile from better ones?
real - should we return the tile even in not good quality?
"""
x = x % (2 *... | 4,372 |
def register_geoserver_db(res_id, db):
"""
Attempts to register a GeoServer layer
"""
geoserver_namespace = settings.DATA_SERVICES.get("geoserver", {}).get('NAMESPACE')
geoserver_url = settings.DATA_SERVICES.get("geoserver", {}).get('URL')
geoserver_user = settings.DATA_SERVICES.get("geoserver"... | 4,373 |
def move_file(source,destination):
"""perform mv command to move a file from sourc to destination
Returns True if move is successful
"""
#print("MOV:"+source+"-->"+destination)
mv_cmd=['mv',source,destination]
if not getReturnStatus(mv_cmd):
return False
return True | 4,374 |
def test_config_constructor():
"""Test Constructor"""
cfg = ConfigOptions()
# state = cfg.__getstate__()
assert cfg.loglevel.name == "INFO" | 4,375 |
def _freedman_diaconis_bins(a):
"""Calculate number of hist bins using Freedman-Diaconis rule."""
# From http://stats.stackexchange.com/questions/798/
a = np.asarray(a)
iqr = stats.scoreatpercentile(a, 75)-stats.scoreatpercentile(a, 25)
h = 2*iqr/(len(a)**(1/3))
bins=int(np.ceil((a.max()-a.min()... | 4,376 |
def to_ascii_bytes(string):
"""Convert unicode to ascii byte string."""
return bytes(string, 'ascii') if PY3 else bytes(string) | 4,377 |
def get_user(user_id):
""" get a user """
app.logger.debug("get_user({0})".format(user_id))
try:
response = app.usersClient.get_user(user_id)
return jsonify(response)
except OktaError as e:
message = {
"error_causes": e.error_causes,
"error_summary": e.err... | 4,378 |
def matrix_conv_both_methods_from_avg(n_realz, input_folder, mapping,
v_tuple, t_tuple,
prefix='real_', numbered=True, verbose=False):
"""
Convergence of the aggregate transition matrix both considering the frequency and not considering... | 4,379 |
def zipper(sequence):
"""Given a sequence return a list that has the same length as the original
sequence, but each element is now a list with an integer and the original
element of the sequence."""
n = len(sequence)
rn = range(n)
data = zip(rn,sequence)
return data | 4,380 |
def normalizeRows(x):
"""
Implement a function to normalizes each row of the matrix x (to have unit length)
Argument:
x -- A numpy matrix of shape (n, m)
Returns:
x -- The normalized (by row) numpy matrix
"""
x_norm = np.linalg.norm(x, ord=2, axis=1, keepdims=True)
x = x / x_norm
... | 4,381 |
def weat_p_value(X, Y, A, B, embd, sample = 1000):
"""Computes the one-sided P value for the given list of association and target word pairs
Arguments
X, Y : List of association words
A, B : List of target words
embd : Dictonary of word-to-embedding for all words
... | 4,382 |
def plot_pauli_bar_rep_of_state(state_pl_basis, ax, labels, title):
"""
Visualize a quantum state in the Pauli-Liouville basis. The magnitude of the operator
coefficients are represented by the height of a bar in the bargraph.
:param numpy.ndarray state_pl_basis: The quantum state represented in the Pa... | 4,383 |
def toggle_nullclines():
"""Make an interactive plot of nullclines and fixed points of
the Gardner-Collins synthetic toggle switch.
"""
# Set up sliders
params = [
dict(
name="βx", start=0.1, end=20, step=0.1, value=10, long_name="beta_x_slider",
),
dict(
... | 4,384 |
def write_smiles_to_file(f_name, smiles):
"""Write dataset to a file.
Parameters
----------
f_name : str
Path to create a file of molecules, where each line of the file
is a molecule in SMILES format.
smiles : list of str
List of SMILES
"""
with open(f_name, 'w') as ... | 4,385 |
def is_chinese_word_add_number(s):
"""中文混数字"""
if len(s) == 0:
return False
else:
for w in s:
if is_chinese(w) == False and is_number(w) == False:
return False
return True | 4,386 |
def get_rack_id_by_label(rack_label):
"""
Find the rack id for the rack label
Returns:
rack_id or None
"""
rack_id = None
session = persistent_mgr.create_database_session()
rack = persistent_mgr.get_rack_by_label(session, rack_label)
if rack:
rack_id = rack.rack_id
se... | 4,387 |
def cat(xs: torch.Tensor, lx: torch.Tensor) -> torch.Tensor:
"""Cat the padded xs via lengths lx
Args:
xs (torch.FloatTensor): of size (N, T, V)
lx (torch.LongTensor): of size (N, ), whose elements are (lx0, lx1, ...)
Return:
x_gather (torch.FloatTensor): size (lx0+lx1+..., V)
... | 4,388 |
def rule(n: int) -> dict:
"""Implement one of the 256 rules of elementary cellular automata.
Args:
n: The id of the rule (1-256).
Returns:
A mapping from a tuple of 3 cellvalues to a single cell value.
"""
assert n > 0 and n < 257, "must choose a rule between 1 and 256"
val... | 4,389 |
def soundtone_type(value):
"""
Parse tone sounds parameters from args.
value: 'square:90hz,10s,100%'
returns: {'waveform': 'square', 'frequency': '90', 'amplitude': '100'}'
"""
abbr_map = {"hz": "frequency", "%": "amplitude", "s": "duration"}
tone_form, generator_raw_params = value.lower().... | 4,390 |
def rouge_l_sentence_level(evaluated_sentences, reference_sentences):
"""Computes ROUGE-L (sentence level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/ rouge-
working-note-v1.3.1.pdf.
Calculated according to:
R_lcs = LCS(X,Y)/m
P_lcs = LCS(X,Y)/n
... | 4,391 |
def median(array, width=None, axis=None, even=False):
"""Replicate the IDL ``MEDIAN()`` function.
Parameters
----------
array : array-like
Compute the median of this array.
width : :class:`int`, optional
Size of the neighborhood in which to compute the median (*i.e.*,
perfor... | 4,392 |
def test_partitions(os_partition_table):
""" check that partion_table returns same info as /proc/partitions """
# # independent tests
# tests that work as non-root user
#
# get independent list of partitions from kernel
re_part = re.compile(' (sd[a-z][1-9])$')
lines_out = os_one_liner('cat... | 4,393 |
def print_result(feature):
"""
Status message for Sensu - this will show up in any alerts.
"""
print(feature_message(feature)) | 4,394 |
def stitch_frame(frames, _):
"""
Stitching for single frame.
Simply returns the frame of the first index in the frames list.
"""
return frames[0] | 4,395 |
def project_add():
"""
Desc: 新增项目接口
"""
form_data = eval(request.get_data(as_text=True))
pro_name, remark = form_data['projectName'], form_data['remark']
user_id = get_jwt_identity()
response = ProjectM().add_project(user_id, pro_name, remark)
return response | 4,396 |
def date_sequence(start, end, stats_duration, step_size):
"""
Generate a sequence of time span tuples
:seealso:
Refer to `dateutil.parser.parse` for details on date parsing.
:param str start: Start date of first interval
:param str end: End date. The end of the last time span may extend pa... | 4,397 |
def end_of_next_month(dt):
"""
Return the end of the next month
"""
month = dt.month + 2
year = dt.year
if month > 12:
next_month = month - 12
year+=1
else:
next_month = month
return (
dt.replace(
year=year, month=next_month, day=1
) - ... | 4,398 |
def get_version():
"""
Reads version from git status or PKG-INFO
https://gist.github.com/pwithnall/7bc5f320b3bdf418265a
"""
# noinspection PyUnresolvedReferences
git_dir = os.path.join(base_dir, '.git')
if os.path.isdir(git_dir):
# Get the version using "git describe".
cmd =... | 4,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.