content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calc_cutoff_date(keep):
"""given a retention period, calculates the date before which files should be deleted"""
keep_match = re.fullmatch(keep_re, keep)
if keep_match is None:
raise RuntimeError("KEEP must be in the format <number>[dw]")
keep_range = int(keep_match.group("range"))
i... | 57,800 |
def scale_bar(ax, proj, length, location=(0.5, 0.05), linewidth=3,
linecolor='k',fontcolor='k',fontsize='8',zorder=2,
units='km', m_per_unit=1000):
# ===============================================================
"""
http://stackoverflow.com/a/35705477/1072212
ax is the axes to ... | 57,801 |
def traveling_salesperson(pos_list,
restarts=100000,
beam_search=True,
k=4,
nstart=None,
verbose=False,
):
"""
Finds an approximate solution to the travelin... | 57,802 |
def test_local_deletion_during_upload(m):
"""Tests the case where a local item is deleted during the upload."""
# we mimic a deletion during upload by queueing a fake FileCreatedEvent
fake_created_event = FileCreatedEvent(m.test_folder_local + "/file.txt")
m.manager.sync.fs_events.queue_event(fake_crea... | 57,803 |
def extract_pq_flags(array, flags=None, invert=None, check_zero=False,
combine=False, quiet=True):
"""
Extracts pixel quality flags from the pixel quality bit array.
:param array:
A NumPy 2D or 3D array containing the PQ bit array. If array
is 3D, then combine is set to... | 57,804 |
def readPatterns(sequence):
"""Read in the patterns to be matched.
"""
seqs = {}
seqfile = open(sequence)
for line in seqfile:
toks = line.strip().split()
if len(toks) != 2:
print "Number of tokens on line is not 2. Kill!!!", line
sys.exit(1)
seqs[toks... | 57,805 |
def construct_parameters(**kwargs):
"""Translates data to a format suitable for Zabbix API
Args:
**kwargs: Arguments passed to the module.
Returns:
A dictionary of arguments in a format that is understandable by Zabbix API.
"""
if kwargs['mappings'] is None:
return dict(
... | 57,806 |
def _extreact_qml_file_info(file):
"""Returns file object in QML-ready format"""
return {
"name": file["name"],
"path": file["path"],
"isFile": file["is_file"],
"isDir": file["is_dir"],
"level": file["level"]
} | 57,807 |
def main(url):
"""Return the version number."""
c = latest(url)
print(c) | 57,808 |
def check_cn_match(sv_list, cn_increase, cn_decrease, final_cn):
"""
Check that the CNV combination produces the right final copy number.
"""
if sv_list == []:
return False
initial_cn = 2
for sv in sv_list:
if sv in cn_increase:
initial_cn += 1
if sv in cn_dec... | 57,809 |
def pipeline_master_unexpectedShutdownHandler(signum, frame):
"""Singnal handler to catch SIGUSR1 and SIGTERM sent by child processes."""
global mp_shutdown_recv
print(" Master: Shutdown signal received from child process!")
if not mp_shutdown_recv:
mp_shutdown_recv = True
# give bogus c... | 57,810 |
def rotateMatrix(m):
"""
rotate matrix
:param m: matrix
:type m: list of list of integers
:return: rotated matrix
:rtype: list of list
"""
for i in range(int(len(m) / 2)):
last_layer = len(m) - i - 1
for j in range(i, last_layer):
offset = j - i
to... | 57,811 |
def get_beautiful_base_image_map(df_flux, thin=False):
""" Create the beautiful folium map containing routes, with blur effect """
# Initialize folium map parameters
folium_map = folium.Map(location = sgs._location_map,
zoom_start = sgs._zoom_map,
... | 57,812 |
def lambda_handler(event, context):
"""Main Lambda Handler."""
print 'event ', event
LOG.debug('event %s', event)
namespace = event['directive']['header']['namespace']
if namespace == 'Alexa.Discovery':
return handle_discovery(context, event)
elif namespace == 'Alexa.RemoteVideoPlayer':
... | 57,813 |
def test_show_list_empty(capsys):
"""Test that show_list() writes expected output when list is empty.
"""
expected = 6 * "-"
viewer.show_list([], "")
stdout, stderr = capsys.readouterr()
assert stderr == ""
assert expected in stdout | 57,814 |
def u_crit_switch_lat_hh80(thermal_ro):
"""Where RCE and AMC winds are equal in Held Hou 1980 model."""
return np.rad2deg(np.arccos((((1 + 2*thermal_ro)**-0.25)))) | 57,815 |
def GetUniqueName(context, name):
""" Fixup any sbsar naming collision """
foundName = False
nameCount = 1
lastChar = ''
for sb in context.scene.loadedSbsars:
if sb.name.startswith(name):
foundName = True
# find the highest value suffix on the name
lastCh... | 57,816 |
def _print_pipeline_info(pipeline, out_format):
"""print pipeline info"""
headers = [
'pipeline id', 'name', 'fsname', 'username',
'pipeline md5', 'create time', 'update time'
]
data = [[
pipeline.pipelineid, pipeline.name, pipeline.fsname,
pipeline.username, pipeline.pi... | 57,817 |
def _make_text_table(
explainer_values,
normalized_values,
pipeline_features,
original_features,
top_k,
include_explainer_values=False,
algorithm="shap",
):
"""Make a table displaying the explainer values for a prediction.
Args:
explainer_values (dict): Dictionary mapping th... | 57,818 |
def find_best_ncut(G, x, y, cell_to_idx=None, mut_to_idx=None):
"""
Given bipartite graph G, 1-dimensional representation x of "left" vertices, 1-dimensional representation y of "right" vertices, exhaustively finds the cut-points in these 1D representations that minimizes the normalized cut.
"""
i2... | 57,819 |
def triaxial_strain(magnetic_field):
"""Triaxial strain corresponding to a homogeneous pseudo-magnetic field
Parameters
----------
magnetic_field : float
Intensity of the pseudo-magnetic field to induce.
"""
from .constants import a_cc, beta
def field_to_strain(field):
retu... | 57,820 |
def p_cmdexpr_spath(p):
"""spathcmd : SPATH
| SPATH spatharglist"""
p[0] = ParseTreeNode('COMMAND', raw='spath')
if len(p) > 2:
p[0].add_children(p[2].children) | 57,821 |
def test_handle_api_hint():
"""Check handle_api_hint method"""
from optimade.server.routers.utils import BASE_URL_PREFIXES
from optimade.server.warnings import FieldValueNotRecognized, TooManyValues
api_hint = ["v1", "v2"]
warning_detail = "`api_hint` should only be supplied once, with a single val... | 57,822 |
def read_data( x_range, y_range, geoboundary, batch_size=0, set_size=0, data_dir=os.path.abspath(''), rand_seed=1234,
normalize_input=True, test_ratio=0.2):
"""
:param set_size: input size of sets
:param input_size: input size of the arrays
:param output_size: output size of the arr... | 57,823 |
def plot_indv(ax, indv, visible=np.ones((13,)), color='red'):
"""
plots the individual onto the axis
:param ax:
:param indv:
:param visible:
:param color:
:return:
"""
for (x, y, z), v in zip(indv, visible):
if v == 1:
ax.scatter(x, y, z, color=color)
lim... | 57,824 |
def get_least_sig_bit(band):
"""Return the least significant bit in color value"""
mask = 0x1
last_bit = band & mask
return str(last_bit) | 57,825 |
def GenerateConformanceCorpus(args):
"""Generate the conformance test corpus for the given arguments."""
files = []
for jxl in args.inputs:
if os.path.isdir(jxl):
# Add all the .jxl files recursively.
for root, _, dir_files in os.walk(jxl):
files.extend(os.path.join(root, filename) for fil... | 57,826 |
def _str(val):
"""
Ensures that the val is the default str() type for python2 or 3
"""
if str == bytes:
if isinstance(val, str):
return val
else:
return str(val)
else:
if isinstance(val, str):
return val
else:
return str... | 57,827 |
def test_augment_column_permut_er(dai, empty_data):
"""
Augment column with normal distribution
"""
with pytest.raises(ValueError):
dai.augment_column_norm(empty_data) | 57,828 |
def test_global():
""" Test various assignments of global
variables through imports.
"""
global PATH, OS, collections, deque
from os import path as PATH
import os as OS
import collections
from collections import deque
# make sure that these triggers unused-variable
from sys impor... | 57,829 |
def CurrentColumn():
"""Returns the 0-based current column. Do NOT access the CurrentColumn in
vim.current.line. It doesn't exist yet when the cursor is at the end of the
line. Only the chars before the current column exist in vim.current.line.
"""
# vim's columns are 1-based while vim.current.line... | 57,830 |
def sort_data_mnist(
x_train,
y_train,
x_test,
y_test,
num_points_per_task,
test_points_per_task,
n_tasks=10,
shift=1,
):
"""
Sorts data into training and testing data sets for each task.
Generalized for MNIST datasets and different task numbers.
"""
# reformat data
... | 57,831 |
def test_write_twoline_no_pad():
"""Write a table as a fixed width table with no padding."""
out = StringIO()
ascii.write(dat, out, Writer=ascii.FixedWidthTwoLine,
delimiter_pad=' ', position_char='=')
assert_equal_splitlines(out.getvalue(), """\
Col1 Col2 Col3 Col4
==== ... | 57,832 |
def show_confmap_grid(net, X, Y, plot=True, save_path=None, show_figure=False):
"""
Shows predictions from the model using every channel in the confmap.
"""
if X.ndim == 2:
X = X[None,...,None]
if X.ndim == 3:
if X.shape[0] == 1: # missing singleton channel
X = X[..., No... | 57,833 |
def make_sign_from_network(Network):
"""
Make an NxN numpy array describing the interaction sign between edges
Input:
Network - DSGRN network object
Output:
numpy array with 1 if j->i, -1 if j-|i, and 0 otherwise.
"""
N = Network.size()
sign = np.zeros([N,N])
for j in ra... | 57,834 |
def open_file(filename, mode):
"""Open json file for the current user and given filename, and mode."""
return open('users/' + user_info['username'] + '/' + filename + '.json', mode, encoding='utf-8') | 57,835 |
def rc4(data, key):
"""RC4 encryption and decryption method."""
S, j, out = list(range(256)), 0, []
for i in range(256):
j = (j + S[i] + ord(key[i % len(key)])) % 256
S[i], S[j] = S[j], S[i]
i = j = 0
for ch in data:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[... | 57,836 |
def fill_notebook(work_notebook, script_blocks):
"""Writes the Jupyter notebook cells
Parameters
----------
script_blocks : list of tuples
"""
for blabel, bcontent in script_blocks:
if blabel == 'code':
add_code_cell(work_notebook, bcontent)
else:
add_ma... | 57,837 |
def test(img, r=3, d=8, option="single"):
"""Standardized Tester
Parameters
----------
img : np.array
Input binary image to run DBScan on
Keyword Arguments
-----------------
r : int
Ball radius for DBScan
d : int
Density threshold; how many neighbors must be pre... | 57,838 |
def test_deactivate_lid(
decoy: Decoy,
engine_client: SyncClient,
subject_module_id: str,
subject: ThermocyclerModuleContext,
) -> None:
"""It should use the engine client to deactivate the lid."""
subject.deactivate_lid()
decoy.verify(engine_client.thermocycler_deactivate_lid(subject_module... | 57,839 |
def main() -> None:
"""Main method.
:return: None
"""
_help = ["-h", "--help"]
parser = None # type: typing.Optional[argparse.ArgumentParser]
# Check params
if len(sys.argv) > 1 and sys.argv[1] not in TAGS and sys.argv[1] not in _help:
# No action specified. Assume run.
ar... | 57,840 |
def rename_topics_in_rviz_file(templ_file, replace_dict):
"""Read from a single template file and write the modified contents to an
actual rviz file one directory prior to the templates directory.
"""
with open(templ_file, 'r') as templ:
templ_lines = templ.readlines()
head, tail = os.p... | 57,841 |
def create_logger(name, silent=False, to_disk=True, log_file=None):
"""Logger wrapper
"""
# setup logger
log = logging.getLogger(name)
log.setLevel(logging.DEBUG)
log.propagate = False
formatter = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S')
if not silent... | 57,842 |
def binomial_ci(series, alpha=0.05, method="wilson", side="both"):
"""Returns a binomial confidence interval
Computes a binomial confidence interval based on boolean data. A symbolic
wrapper for statsmodels.stats.proportion.proportion_confint.
Args:
series (pandas.Series): Column to summarize;... | 57,843 |
def plot_marginal(pred, pred_se, names_pred, x_name, x_values_in, x_type,
c_dict, regrf, minus_ate=False):
"""Show the plots, similar to GATE and IATE.
Parameters
----------
pred : Numpy array. Predictions.
pred_se : Numpy array. Standard errors.
names_pred : List of strings.
... | 57,844 |
def _redirect_func_check_failed(request):
"""
跳转功能权限检测失败的提示页面
"""
url = '%saccount/check_failed/?code=func_check' % settings.SITE_URL
if request.is_ajax():
# ajax跳转页面,需要借助settings.js实现页面跳转或redirect跳转。
resp = HttpResponse(status=402, content=url)
return resp
else:
... | 57,845 |
def request_policy_rules(data):
"""Request policies.""" | 57,846 |
def I(box):
"""
Integrate even function over a box
"""
level = 0
ub = []
return Ir(box, level, ub) | 57,847 |
def register_models(app):
"""All database models need to be registered for Flask-Migrate to see them"""
for model in [
"biography",
"comments",
"contacts",
"downloads",
"guestbook",
"news",
"people",
"photos",
"releases",
... | 57,848 |
def test_model_monitoring(tmpdir):
"""Test the model monitoring works properly."""
dataset = SimpleDataset()
model = TrainableModel(dataset=dataset, log_dir=tmpdir, **_IO, optimizer=_OPTIMIZER)
batch = next(iter(dataset.train_stream()))
outputs = model.run(batch, False, None)
assert BaseModel.SI... | 57,849 |
def encode_data(data, tokenizer, punctuation_enc):
"""
Converts words to (BERT) tokens and puntuation to given encoding.
Note that words can be composed of multiple tokens.
"""
X = []
Y = []
for line in data:
word, punc = line.split()
punc = punc.strip()
tokens = tok... | 57,850 |
def get_status(jobdir, jobid=None):
"""
Given list of jobs, returns status of each.
"""
cmd_template = "aws batch describe-jobs --jobs {}"
if jobid is None:
print(("Describing jobs in {}/ids/...".format(jobdir)))
jobs = os.listdir(jobdir + "/ids/")
for job in jobs:
... | 57,851 |
def full(resultsfile, conc):
""" The [full] command scans all available projects on a gitlab server """
scanner = GLScanner(conc)
starttime = time.time()
results = scanner.scan_all_projects()
#do recap
results['time_elapsed'] = time.time() - starttime
recap = scanner.get_dacgl_recap(res... | 57,852 |
def superpixel_mask(img, mod_specific = True):
"""
assume dim 0 of img is the batch_size
SLIC - K-Means based image segmentation
https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_segmentations.html
:param input: Input image, which can be 2D or 3D, and grayscale or multichannel (see m... | 57,853 |
def get_experiment_random_states_data():
"""Get the data for random states experiment
Params:
episode: int
The episode for which the data of an
experiment instance shall be returned
Returns:
exp_data: dict
The experiment data. For further explanation
... | 57,854 |
def openpty():
"""
Call :func:`os.openpty`, raising a descriptive error if the call fails.
:raises mitogen.core.StreamError:
Creating a PTY failed.
:returns:
`(master_fp, slave_fp)` file-like objects.
"""
try:
master_fd, slave_fd = os.openpty()
except OSError:
... | 57,855 |
def _private_key_filename(file_prefix):
"""
Construct the name of a file for use in storing a private key.
:param str file_prefix: base file name for the private key (without the
extension)
:return: private key filename
:rtype: str
"""
return file_prefix + ".key" | 57,856 |
def possible_jp(decay_chain, max_J=2):
"""get possible resonances jp of J <= max_J"""
ret = []
A = decay_chain.top
outs = decay_chain.outs
jp_list = [jp_seq(max_J) for _ in decay_chain.inner]
ret = {}
for jps in itertools.product(*jp_list):
res_map = {}
for jp, res in zip(jp... | 57,857 |
def set_mock_context(msg, monkeypatch, writerfqdn='test.bar.example.com'):
"""
establish the mock context for our testing
"""
print("================ %s ================" % msg)
# pylint: disable=bad-continuation
props = {
'writerfqdn': writerfqdn,
'use_existing': False,
'readerfqdn': 'test-ro.b... | 57,858 |
def default(mol, gerebtzoff = True):
"""
Calculates the QED descriptor using average descriptor weights and Gregory Gerebtzoff parameters.
"""
return weights_mean(mol, gerebtzoff) | 57,859 |
def build_context_residual(offxml, molfile, dihedrals):
"""Builds context for the openmm calculation keeping the dihedral frozen and the
specific energy contributions from the dihedral zeroed out
Parameters
----------
offxml: forcefield file
molfile: molecule file in sdf format
dihedrals: li... | 57,860 |
def sparse_tensor_to_sparse_adj(x: torch.Tensor) -> sp.csr_matrix:
"""Converts a SparseTensor to a Scipy sparse matrix (CSR matrix)."""
x = x.coalesce()
data = x.values().detach().cpu().numpy()
indices = x.indices().detach().cpu().numpy()
shape = tuple(x.size())
return sp.csr_matrix((data,... | 57,861 |
def preprocess(question):
"""Do all steps of question preprocessing.
Args:
question (str): Original question in natural language.
ctx_entities (list): Context entities.
Returns:
str: Question lower, without punctuation and with stopwords
replaced by wildcards.
"""
... | 57,862 |
def _genome_asset_path(
genomes, gname, aname, tname, seek_key, enclosing_dir, no_tag=False
):
"""
Retrieve the raw path value for a particular asset for a particular genome.
:param Mapping[str, Mapping[str, Mapping[str, object]]] genomes: nested
collection of key-value pairs, keyed at top leve... | 57,863 |
def create_body(arch, pretrained=True, cut=-2):
""" Cut off the body of a typically pretrained `model` at `cut` or as specified by `body_fn` """
model = arch(pretrained)
if pretrained:
freeze(model)
return nn.Sequential(*list(model.children())[:cut]) | 57,864 |
def get_stock_basics(date=None):
"""
获取沪深上市公司基本情况
Parameters
date:日期YYYY-MM-DD,默认为上一个交易日,目前只能提供2016-08-09之后的历史数据
Return
--------
DataFrame
code,代码
name,名称
industry,细分行业
area,地区
pe,市盈率
... | 57,865 |
def _RunWorkload(vm, num_threads):
"""Runs stress-ng on the target vm.
Args:
vm: The target vm to run on.
num_threads: Number of instances of stressors to launch.
Returns:
A list of sample.Sample objects.
"""
metadata = {
'duration_sec': FLAGS.stress_ng_duration,
'threads': num_thre... | 57,866 |
def denormalize_image(image):
""" Undo normalization of image. """
image = (image / 2) + 0.5
return image | 57,867 |
def find_overlapping_selections(selections, selection_strings):
"""
Given a list of atom selections (:py:class:`scitbx.array_family.flex.bool`
arrays) and corresponding selection strings, inspect the selections to
determine whether any two arrays overlap. Returns a tuple of the first pair
of selection string... | 57,868 |
def map(ctx, fxyz, design_matrix, prefix, output, extra_properties,
use_atomic_descriptors, only_use_species, peratom, keepraw,
color, color_column, color_label, colormap, color_from_zero, normalized_by_size,
annotate, adjusttext, style, aspect_ratio):
"""
Making 2D maps using dimensiona... | 57,869 |
def main(filename, id_only=False):
"""Read in a file and print each course by chapter."""
course = build_course_tree(filename, id_only)
for block in course:
print block | 57,870 |
def write_stack(
debug : bool = False
):
"""
Write Docker Compose configuration files
"""
from meerschaum.config._edit import general_write_yaml_config
from meerschaum.config._sync import sync_files
general_write_yaml_config(get_necessary_files(), debug=debug)
return sync_files(... | 57,871 |
def compute_pdf(obs, histogram):
"""
Compute the PDF of the given observable histogram
"""
(_, _, bin_size) = constants.HISTOG_PARAM_TABLE[obs]
pdf = histogram / sum(histogram) / bin_size
return pdf | 57,872 |
def day_lte(query: int, field_name: str, object: Any) -> bool:
"""
Check if value of object is less than or equal to value of query
"""
return _datetime_lte(query, getattr(object, field_name).day) | 57,873 |
def dot(x,y):
""" dot product of two vectors """
return tf.reduce_sum(tf.multiply(x,y)) | 57,874 |
def check_bmp(input_file_name):
""" Check if filename is a BMP file
:param input_file_name: input file name
:type input_file_name: string
:return whether the file is .bmp
:rtype boolean
"""
return 'bmp' == imghdr.what(input_file_name) | 57,875 |
def mediapackage_channels(region):
"""
Return the MediaPackage channels for the given region.
Tags included.
"""
items = []
service_name = 'mediapackage'
if region in boto3.Session().get_available_regions(service_name):
service = boto3.client(service_name, region_name=region, config=... | 57,876 |
def doc_fb_threshold_filter(threshold, session, docs = None, with_fb = True):
"""
Filter documents by feedback value
threshold: float, the threshold value
session: Session,
docs: DocumentList, the documents to be considered
with_fb: Boolean, if True, then those without feedback values are ... | 57,877 |
def save_df(args: dict, df: pd.DataFrame) -> bool:
"""Save Pandas DataFrame to a file in excel or CSV format (depending on extension)"""
if args['outfile']:
base, ext = os.path.splitext(args['outfile'])
if ext == '.xlsx':
df['datetime'] = df.index.to_series().dt.tz_localize(None)
... | 57,878 |
def test_linear_trend_latitude(cube_3_time):
"""Test calculation of linear trend along latitude coordinate."""
cube_3_time.data[0, 0, 0] = np.nan
cube_3_time.data = np.ma.masked_invalid(cube_3_time.data)
cube_trend = linear_trend(cube_3_time, coordinate='latitude')
assert cube_trend.shape == (3, 2)
... | 57,879 |
def time2char(qr_time, dico):
"""
Calcule le code alphanumérique à partir d'un datetime.
Parameters:
qr_time (dt): le datetime à convertir
dico (str): le dictionnaitre pour décoder le code (correspondance entre lettre et chiffre)
Returns:
str: Code alphanumérique
"""
... | 57,880 |
def enumerate_spans(
sentence: List[T],
offset: int = 0,
max_span_width: int = None,
min_span_width: int = 1,
filter_function: Callable[[List[T]], bool] = None,
) -> List[Tuple[int, int]]:
"""
Given a sentence, return all token spans within the sentence. Spans are `inclusive`.
Additional... | 57,881 |
def test_bswap_liquidity_add_without_poolId():
"""Tests the API endpoint to add liquidity to a pool without poolId."""
client = Client(key, secret)
client.bswap_liquidity_add.when.called_with("", "BUSD", "1").should.throw(
ParameterRequiredError
) | 57,882 |
def create_quay_org(endpoint, token, org_name):
"""
Creates an organization in quay
Args:
endpoint (str): Quay endpoint url
token (str): Super user token
org_name (str): Organization name
Returns:
bool: True in case org creation is successful
"""
data = f'{{"rec... | 57,883 |
def main():
"""Test run entrypoint"""
test_plan("examples/payloads/payload1.json", "examples/plans/response1.json")
test_plan("examples/payloads/payload2.json", "examples/plans/response2.json")
test_plan("examples/payloads/payload3.json", "examples/plans/response3.json") | 57,884 |
async def create_recipe_tag(
tag: TagIn, session: Session = Depends(generate_session), current_user=Depends(get_current_user)
):
""" Creates a Tag in the database """
return db.tags.create(session, tag.dict()) | 57,885 |
def test_raises():
"""test failed"""
with pytest.raises(TypeError):
tasks.add(task='not a task object') | 57,886 |
def update_weights(point_to_weight, misclassified_points, error_rate):
"""Given a dictionary mapping training points to their old weights, a list
of training points misclassified by the current weak classifier, and the
error rate of the current weak classifier, returns a dictionary mapping
training poin... | 57,887 |
def edge_intersect(p1, q1, edge):
"""Return True if edge from A, B interects edge.
http://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/"""
p2 = edge.p1
q2 = edge.p2
o1 = ccw(p1, q1, p2)
o2 = ccw(p1, q1, q2)
o3 = ccw(p2, q2, p1)
o4 = ccw(p2, q2, q1)
# Ge... | 57,888 |
def get_reversibles_in_direction(color, size, board, x, y, direction):
"""
Get Reversibles in Direction
"""
ret = []
next_x, next_y = x, y
dx, dy = direction
while True:
next_x, next_y = next_x + dx, next_y + dy
if in_range(size, next_x, next_y):
next_value = bo... | 57,889 |
def full_batch_mc(N):
"""Build computations to use the full batch and the GGN-MC."""
return BaseComputations(
extension_cls_directions=SqrtGGNMC,
extension_cls_second=SqrtGGNMC,
subsampling_first=None,
subsampling_directions=None,
subsampling_second=None,
verbose=... | 57,890 |
def enabled(serviceName):
"""Return True if serviceName is enabled in the run level 3"""
return hasRunLevel(serviceName, 3) | 57,891 |
def as_mb(in_size: int) -> int:
"""
Converter functions to convert the size in bytes to megabytes.
"""
conv = 1024 * 1024
return in_size // conv | 57,892 |
def _mp_ParameterGrid_getitem(self, ind):
"""Get the parameters that would be ``ind``th in iteration
Parameters
----------
ind : int
The iteration index
Returns
-------
params : dict of str to any
Equal to list(self)[ind]
"""
# This is used to make discrete sampling... | 57,893 |
def mycv2_cvt_gray(img):
"""
将图片转换为灰度图
:param img: numpy.ndarray()
:return:
"""
channels = img.shape[2]
if channels == 3:
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
elif channels == 4:
return cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
else: # channels == 2... | 57,894 |
def find_cea_coord(header,phi_c,lambda_c,nx,ny,dx,dy):
"""Convert the index to CCD coordinate (xi,eta)"""
nx = int(nx)
ny = int(ny)
# Array of CEA coords
x = []
y = []
for j in range(ny):
col = []
row = []
for i in range(nx):
col.append(np.radians((i-(nx... | 57,895 |
def allowed_gai_family():
"""
https://github.com/shazow/urllib3/blob/master/urllib3/util/connection.py
"""
return socket.AF_INET #* this to force use ipv4 (issue with ipv6, get 2s delay)
| 57,896 |
def build_dict_from_file(path: PosixPath, value_func: Callable = str) -> dict:
"""Build dictionary from file of key, value pairs separated by tab character.
Args:
path (PosixPath): Path to dictionary-containing text file
value_func (Callable): Function to run over each value
Returns:
output (dict): Dictionar... | 57,897 |
def _get_list_pairs(pairs, idx_class_dict, num_feature):
"""Creates flattened list of (repeated) pairs.
The indexing corresponds with the flattened list of T values and the
flattened list of p-values obtained from _get_list_signif_scores().
Arguments:
pairs: [(int, int)]
list of pa... | 57,898 |
def sign_out(addon_id):
"""
Usage:
addon.xml
---
<import addon="plugin.video.youtube" version="6.1.0"/>
---
.py
---
import youtube_registration
import youtube_authentication
youtube_registration.register_api_keys(addon_id='plugin.video.example',
... | 57,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.