content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def start(timeout=5, backlog_reassign_delay=None):
"""Create, start, and return the block pipeline."""
pipeline = create_pipeline(timeout=timeout,
backlog_reassign_delay=backlog_reassign_delay)
pipeline.start()
return pipeline | 14,500 |
def preprocess_variable_features(features, interaction_augmentation, normalization):
"""
Features preprocessing following Khalil et al. (2016) Learning to Branch in Mixed Integer Programming.
Parameters
----------
features : 2D np.ndarray
The candidate variable features to preprocess.
i... | 14,501 |
def load_dicomdir_records(datasets):
""" If a Data Set is a DICOMDIR Record, replace it by the file it
(or its children) references.
"""
result = []
file_ids = set()
for dataset in datasets :
if "directory_record_type" in dataset : # Directory Record Type
... | 14,502 |
def reverse_inverse_from_cholesky_band_proto(S, l):
"""
S -> L
:param S: sparse subset inverse of banded matrix L
:param l: number of subdiagonals in S
:return: Ls: reconstructed cholesky decomposition
"""
# forward pass
k = l + 1 # bandwidth
n = S.shape[1]
# construct vector e ... | 14,503 |
def set_run_state(
collection: Collection,
run_id: str,
task_id: Optional[str] = None,
state: str = 'UNKNOWN',
):
"""Set/update state of run associated with Celery task."""
if not task_id:
document = collection.find_one(
filter={'run_id': run_id},
projection={
... | 14,504 |
def fused_bn_grad_5D_run_2(shape, dtype, eps, kernel_name, attrs):
""" test bnGrad_2 """
def get_expect(dgamma_red_hw, dbeta_red_hw, var, gamma, eps, data_shape):
m = data_shape[0] * data_shape[2] * data_shape[3]
neg_m_rec = -1.0 / m
eps = np.array([eps], dtype=var.dtype).reshape([1] * 5... | 14,505 |
async def test_set_states(aresponses, v2_server, v2_state_response):
"""Test the ability to set the state of a v2 system."""
v2_state_response["requestedState"] = "away"
v2_server.add(
"api.simplisafe.com",
f"/v1/subscriptions/{TEST_SUBSCRIPTION_ID}/state",
"post",
response=... | 14,506 |
def get_best_distance(pdb_file, reference_point, resname="GRW"):
"""
Finds fragment atom closest to the user-defined reference point.
Parameters
----------
pdb_file : str
Path to PDB file.
reference_point : list[float]
Coordinates of the reference point to which the distance sho... | 14,507 |
def process(
hw_num: int,
problems_to_do: Optional[Iterable[int]] = None,
prefix: Optional[Path] = None,
by_hand: Optional[Iterable[int]] = None,
legacy: bool = False,
) -> None:
"""Process the homework problems in ``prefix`` folder.
Arguments
---------
hw_num
The number of ... | 14,508 |
def set_build_revision(revision):
"""Set the p4 revision for following jobs in this build"""
set_metadata(__REVISION_METADATA__, revision)
set_metadata(__REVISION_METADATA_DEPRECATED__, revision) | 14,509 |
def delete_entity(entity: EntityID):
"""
Queues entity for removal from the world_objects. Happens at the next run of process.
"""
if entity:
if snecs.exists(entity, snecs.world.default_world):
snecs.schedule_for_deletion(entity)
name = get_name(entity)
loggin... | 14,510 |
def default_IM_weights(IM_j: IM, IMs: np.ndarray) -> pd.Series:
"""
Returns the default IM weights based on the conditioning IM
If the conditioning IM (IM_j) is spectral acceleration (SA) the
weighting is 70% across the SAs and 30% across all other IMs
Otherwise a uniform weighting distribution is... | 14,511 |
def guess_file_type(filename: FileSystemPath) -> Type[PackFile]:
"""Helper to figure out the most appropriate file type depending on a filename."""
filename = str(filename)
if filename.endswith(".json"):
return JsonFile
elif filename.endswith((".yml", ".yaml")):
return YamlFile
elif... | 14,512 |
def _fcn_mg_joint_pos(t, q_init, q_end, t_strike_end):
"""Helper function for `create_mg_joint_pos_policy()` to fit the `TimePolicy` scheme"""
return ((q_end - q_init) * min(t / t_strike_end, 1) + q_init) / 180 * math.pi | 14,513 |
def test_circuit_run(default_compilation_configuration):
"""Test function for `run` method of `Circuit`"""
def f(x):
return x + 42
x = hnp.EncryptedScalar(hnp.UnsignedInteger(3))
inputset = range(2 ** 3)
circuit = hnp.compile_numpy_function(f, {"x": x}, inputset, default_compilation_confi... | 14,514 |
def detection():
"""
Programmed by: David Williams, Aspen Henry, and Slate Hayes
Description: detection is a state where the server tries to find all the faces in a frame, if a face is registered
then it looks for fingers held up next to the face.
"""
#STEP 1: Get and Process frame
# print("Detection!")
fra... | 14,515 |
def rex_coverage(patterns, example_freqs, dedup=False):
"""
Given a list of regular expressions and a dictionary of examples
and their frequencies, this counts the number of times each pattern
matches a an example.
If ``dedup`` is set to ``True``, the frequencies are ignored, so that only
the n... | 14,516 |
def build_diamond(validated_letter):
"""
>:param str validated_letter: A capital letter, that will be used to generate the
list of strings needed to print out the diamond.
>**Returns:** A list a strings that contains the correct spacing for printing
the diamond.
build_diamond is used to genera... | 14,517 |
def animate_resize(object, size_start, size_end, duration_ms=250):
"""Create resize animation on the UI.
Args:
object (App(QDialog)): UI element to be resized.
size_start (QSize): QT tuple of the window size at start.
size_end (QSize): QT tuple of the window size after resizing.
... | 14,518 |
def human_timestamp(timestamp, now=datetime.datetime.utcnow):
"""Turn a :py:class:`datetime.datetime` into a human-friendly string."""
fmt = "%d %B at %H:%M"
if timestamp.year < now().year:
fmt = "%d %B %Y at %H:%M"
return timestamp.strftime(fmt) | 14,519 |
def inception_block(x: tf.keras.layers.Layer, nb_filters: int=64, name: str="block1"):
"""
3D inception block, as per Itzik et al. (2018)
"""
conv3d = partial(Conv3D, activation="linear", use_bias=False, padding="same")
batchn = partial(BatchNormalization, momentum=0.99, fused=True)
activn = pa... | 14,520 |
def _flatten_dict(d, parent_key='', sep='/'):
"""Flattens a dictionary, keeping empty leaves."""
items = []
for k, v in d.items():
path = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(_flatten_dict(v, path, sep=sep).items())
else:
item... | 14,521 |
def secret():
"""
Authenticated only route
@authenticated will flash a message if not authed
"""
return render_template('secret.html') | 14,522 |
def init_logging(log_level):
"""
Initialise the logging by adding an observer to the global log publisher.
:param str log_level: The minimum log level to log messages for.
"""
log_level_filter = LogLevelFilterPredicate(
LogLevel.levelWithName(log_level))
log_level_filter.setLogLevelForN... | 14,523 |
def mk_graph(img_dim, num_labels, poly_width = 3, depth = 3, hidd_repr_size = 512):
""" The function that creates and returns the graph required to
img_dim = image dimensions (Note, that the image needs to be flattened out before feeding here)
num_labels = no_of classes to classify into
"""
... | 14,524 |
def bandpassHLS_1_4(img, band, satsen):
"""Bandpass function applied to Sentinel-2 data as followed in HLS 1.4 products.
Reference:
Claverie et. al, 2018 - The Harmonized Landsat and Sentinel-2 surface reflectance data set.
Args:
img (array): Array containing image pixel values.
b... | 14,525 |
def save_dataset(df: pd.DataFrame, filename: str, sep) -> None:
"""Save dataset in format CSV
"""
file_path_to_save = f"{config.DATASET_DIR}/{filename}"
df.to_csv(file_path_to_save, sep=sep, index=None) | 14,526 |
def test_coordinates(device, backend, random_state=42):
"""
Tests whether the coordinates correspond to the actual values (obtained
with Scattering1d.meta()), and with the vectorization
"""
torch.manual_seed(random_state)
J = 6
Q = 8
T = 2**12
scattering = Scattering1D(J, T, Q, max... | 14,527 |
def test_get_or_create_suggested_object_id(registry):
"""Test that suggested_object_id works."""
entry = registry.async_get_or_create(
'light', 'hue', '1234', suggested_object_id='beer')
assert entry.entity_id == 'light.beer' | 14,528 |
def read_dictionary(vocab_path):
"""
从路径文件中读取字典
:param vocab_path:
:return:
"""
vocab_path = os.path.join(vocab_path)
with open(vocab_path, 'rb') as fr:
word2id = pickle.load(fr)
return word2id | 14,529 |
def createrawtransaction(inputs, outputs, outScriptGenerator=p2pkh):
"""
Create a transaction with the exact input and output syntax as the bitcoin-cli "createrawtransaction" command.
If you use the default outScriptGenerator, this function will return a hex string that exactly matches the
output of bit... | 14,530 |
def get_versions() -> List[str]:
"""
Gets a list of recognized CRSD urns.
Returns
-------
List[str]
"""
return list(sorted(urn_mapping.keys())) | 14,531 |
def test_cube_io_larger_case_ertrun(tmp_path):
"""Larger test cube io as ERTRUN, uses global config from Drogon to tmp_path.
Need some file acrobatics here to make the tmp_path area look like an ERTRUN first.
"""
current = tmp_path / "scratch" / "fields" / "user"
current.mkdir(parents=True, exist_... | 14,532 |
def k2_factor_sq(df=inf,p=95):
"""Return a squared coverage factor for an elliptical uncertainty region
:arg df: the degrees-of-freedom (>=2)
:arg p: the coverage probability (%)
:type df: float
:type p: int or float
Evaluates the square of the coverage factor for an elliptical uncerta... | 14,533 |
def get_cluster_version_path(cluster_id):
"""
Gives s3 full path of cluster_version file of a given cluster_id
"""
base_path = s3.get_cluster_info_base_path()
return "%s/%s/cluster_version.json"%(base_path, cluster_id) | 14,534 |
def MsfParser(f):
"""Read sequences from a msf format file"""
alignmentdict = {}
# parse optional header
# parse optional text information
# file header and sequence header are seperated by a line ending in '..'
line = f.readline().strip()
for line in f:
line = line.strip()
i... | 14,535 |
def import_module_attribute(function_path):
"""Import and return a module attribute given a full path."""
module, attribute = function_path.rsplit(".", 1)
app_module = importlib.import_module(module)
return getattr(app_module, attribute) | 14,536 |
def rgb_to_hex(red, green, blue):
"""Give three color arrays, return a list of hex RGB strings"""
pat = "#{0:02X}{1:02X}{2:02X}"
return [pat.format(r & 0xff, g & 0xff, b & 0xff)
for r, g, b in zip(red, green, blue)] | 14,537 |
def run_cli(cmd: str, print_output: bool = True, check: bool = False,) -> Tuple[int, str, str]:
"""Runs the command with `dcos` as the prefix to the shell command
and returns a tuple containing exit code, stdout, and stderr.
eg. `cmd`= "package install pkg-name" results in:
$ dcos package install pkg-n... | 14,538 |
def get_initialization(arg, indent_count):
"""Get the initialization string to use for this argument."""
t = get_base_c_type(arg)
if arg.is_array():
if t == "char*":
init = '[] = { "String 1", "String 2", "String 0" }'
else:
if arg.is_dictionary() or arg.is_structure... | 14,539 |
def get_time_source_from_output(output):
""" Parse out 'Time Source' value from output
Time source output example : 'Time source is NTP, 23:59:38.461 EST Thu Jun 27 2019'
'Time source is NTP, *12:33:45.355 EST Fri Feb 7 2020'
Args:
output ('str'): Te... | 14,540 |
def getStyleFX():
"""
Defines and returns the style effects
Returns: style effects (list of MNPR_FX)
"""
# general effects
distortionFX = MNPR_FX("distortion", "Substrate distortion", "controlSetB", [[1, 0, 0, 0]], ["distort", "revert"], ["noise"])
gapsOverlapsFX = MNPR_FX("gaps-overlaps", "... | 14,541 |
def raise_from(exccls, message, exc):
"""
raise exc with new message
"""
raise exccls(message) from exc | 14,542 |
def deaths_this_year() -> dict:
"""Get number of deaths this year."""
return get_metric_of(label='deaths_this_year') | 14,543 |
def get_cls_dropdown_tree_view_item(object_name):
"""Get and return class of TreeViewItem Dropdown object according to
snapshotability
"""
base_cls = tree_view_item.CommonDropdownTreeViewItem
if object_name in objects.ALL_SNAPSHOTABLE_OBJS:
base_cls = tree_view_item.SnapshotsDropdownTreeViewItem
return ... | 14,544 |
def make_webhdfs_url(host, user, hdfs_path, op, port=50070):
""" Forms the URL for httpfs requests.
INPUT
-----
host : str
The host to connect to for httpfs access to HDFS. (Can be 'localhost'.)
user : str
The user to use for httpfs connections.
hdfs_path : str
The full... | 14,545 |
def send_email(to, subject, template):
"""
if mailgun's api goes down failover to flask-mail
takes to/from email and an email template.
"""
msg = Message(
subject,
recipients=[to],
html=template,
sender=''
)
mail.send(msg) | 14,546 |
def get_slash_mapping(bot: commands.Bot):
"""Get all the prefix commands groupped by category."""
categories = {}
for command in bot.slash_commands:
if command:
category_name = get_cog_category(command.cog)
# categories are organized by cog folders
try:
... | 14,547 |
def test_bootstrap_from_submodule_no_locale(tmpdir, testpackage, capsys,
monkeypatch):
"""
Regression test for https://github.com/astropy/astropy/issues/2749
Runs test_bootstrap_from_submodule but with missing locale/langauge
settings.
"""
for varnam... | 14,548 |
def rose_plot(ax, angles, bins=16, density=None, offset=0, lab_unit="degrees",
start_zero=False, **param_dict):
"""
Plot polar histogram of angles on ax. ax must have been created using
subplot_kw=dict(projection='polar'). Angles are expected in radians.
** This function is copied directly... | 14,549 |
def create_xml_regression(lfiles, lsbj, foxml):
"""
take a list of files, create a xml file data_set.xml
only 'one' subject, each case seen as a visit...
"""
impl = xml.dom.minidom.getDOMImplementation()
doc = impl.createDocument(None, "some_tag", None)
top_element = doc.documentElement
... | 14,550 |
def generate_site():
"""Generate site in local directory"""
shutil.rmtree(SITE_DIR, ignore_errors=True)
SITE_DIR.mkdir()
print("Copy template to site folder")
for filename in TEMPLATE_DIR.iterdir():
if filename.is_dir():
shutil.copytree(str(filename), SITE_DIR / filename.name)
... | 14,551 |
def get_memcached_client(servers, debug=False):
"""
mc.set("name", "python")
ret = mc.get('name')
print(ret)
"""
if isinstance(servers, str):
servers = servers.split(',')
return memcache.Client(servers, debug=debug) | 14,552 |
def part_to_text(part):
"""
Converts an e-mail message part into text.
Returns None if the message could not be decoded as ASCII.
:param part: E-mail message part.
:return: Message text.
"""
if part.get_content_type() != 'text/plain':
return None
charset = part.get_content_char... | 14,553 |
def icwt(Wx, wavelet='gmw', scales='log-piecewise', nv=None, one_int=True,
x_len=None, x_mean=0, padtype='zero', rpadded=False, l1_norm=True):
"""The inverse Continuous Wavelet Transform of `Wx`, via double or
single integral.
# Arguments:
Wx: np.ndarray
CWT computed via `ssque... | 14,554 |
def AdvApp2Var_MathBase_msc_(*args):
"""
:param ndimen:
:type ndimen: integer *
:param vecte1:
:type vecte1: doublereal *
:param vecte2:
:type vecte2: doublereal *
:rtype: doublereal
"""
return _AdvApp2Var.AdvApp2Var_MathBase_msc_(*args) | 14,555 |
def chunkify(arr, n):
"""Breaks a list into n chunks.
Last chunk may not be equal in size to other chunks
"""
return [arr[i : i + n] for i in range(0, len(arr), n)] | 14,556 |
def featurize(data):
"""
put in a data table and get one back including features
"""
#try gradient | 14,557 |
def _run_command(command, targets, options):
# type: (str, List[str], List[str]) -> bool
"""Runs `command` + `targets` + `options` in a
subprocess and returns a boolean determined by the
process return code.
>>> result = run_command('pylint', ['foo.py', 'some_module'], ['-E'])
>>> result
Tr... | 14,558 |
def _usage():
"""Print command line usage."""
txt = "[INFO] Usage: %s ldt_file topdatadir startYYYYMM model_forcing" \
%(sys.argv[0])
print(txt)
print("[INFO] where:")
print("[INFO] ldt_file is path to LDT parameter file")
print("[INFO] topdatadir is top-level directory with LIS dat... | 14,559 |
def find_untranscribed_words(
gt: Counter, machine: Counter
) -> List[Dict[str, any]]:
"""
Finds untranscribed words.
That is, we find if there exist words in the GT which never occur in the machine transcription.
:param gt: Counter of GT words.
:param machine: Counter of machine words.
:return: List of ... | 14,560 |
def get_vcvars(vs_tools, arch):
"""Get the VC tools environment using vswhere.exe or buildtools docker
This is intended to work either when VS is in its standard installation
location, or when the docker instructions have been followed, and we can
find Visual C++ in C:/BuildTools.
Visual Studio pr... | 14,561 |
def set_line_length(length):
"""
set_line_length(int length)
Sets the maximum line length for log messages.
Messages longer than this amount will be broken up into multiline messages.
Parameters
----------
* length :
the maximum log message line length in characters
... | 14,562 |
def get_teams(pbp_json):
"""
Get teams
:param pbp_json: raw play by play json
:return: dict with home and away
"""
return {'Home': shared.get_team(pbp_json['gameData']['teams']['home']['name'].upper()),
'Away': shared.get_team(pbp_json['gameData']['teams']['away']['name'].upper())... | 14,563 |
def makeCapture(theGame, startCoordinate, endCoordinate):
""" Update the board for a capture between a start and end coordinate """
startX = startCoordinate.get_x_board()
startY = startCoordinate.get_y_board()
endX = endCoordinate.get_x_board()
endY = endCoordinate.get_y_board()
startPieceType ... | 14,564 |
def register(args):
"""Register a new user using email and password.
Return CONFLICT is a user with the same email already exists.
"""
if db.session.query(User).filter_by(email=args['email']).first():
return conflict("User already exists.")
new_user = User(args['email'], args['password'])
... | 14,565 |
def _scale_value_to_rpm(value, total):
"""Scale value to reads per million"""
return value * 1 / (total / 1e6) | 14,566 |
def file_exists_not_empty(filename,):
"""
Tests if file exists and is not empty
:param filename: full path of file to be checked
:type filename: str
"""
if os.path.isfile(filename):
if os.stat(filename).st_size == 0:
return False
else:
return False
re... | 14,567 |
def poly_vals_in_range(minimum, maximum, roots):
"""Return a list of all results of a given polynomial within a range
based on the roots of the polynomial itself.
These roots will be selected by a user from the GUI.
Arguments:
minimum -- the lowest value in the dataset
maximum -- the h... | 14,568 |
def merge_files_in_range(cli_args, file_names, range_to, args):
"""
:param cli_args: Dictionary containing all command-line arguments from user
:param file_names: List of strings where each is a filename
:param range_to: Integer, the number of files to merge
:param args: List, the rest of the argume... | 14,569 |
def width_angle(rectangle: Polygon):
"""Returns the length and angle(in degrees) of the longest side of a
rotated rectangle
"""
point_a, point_b, point_c = rectangle.exterior.coords[:3]
a = distance(point_a, point_b)
b = distance(point_b, point_c)
if a > b:
angle = line_angle(point_a... | 14,570 |
def mean_absolute_error(y_true, y_pred, discretise = False):
"""
requires input arrays to be same np.dtype.
returns average, not sum of errors
discretising (for classification problems) makes little sense to me,
but may be necessary in some obscure scenarios
"""
if discretise:
y_p = tools.round_probabilities(y... | 14,571 |
def population_fit_feature_cal(population,
fitFunction,
fitFunctionInput,
ite):
"""Parallel population fitness calculation function
Args:
population (list): Single population
fitFunction (function): Fit... | 14,572 |
def cblaster_gne(job_id: str, options: ImmutableMultiDict = None,
file_path: t.Union[str, None] = None) -> None:
"""Executed when requested job is cblaster_gne (forges + exec. command)
Input:
- job_id: ID of the submitted job
- options: user submitted parameters via HTML form
... | 14,573 |
def intilise_database2():
"""
Initilse the database and make a table instance
Returns
pymongo object of the table
"""
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb=myclient['subreddit']
maintable2 = mydb["posts2"]
return maintable2 | 14,574 |
def first(id_):
"""The first service of the station."""
return jsonify(
[
(n.removeprefix("_"), t)
for n, t in r.zrange(f"Station:_{id_}:first", 0, -1, withscores=True)
]
) | 14,575 |
def plot_set_points(set_data, color="black", size=10, marker="o", scale=1):
"""
Plot the individual points of a two dimensional isl set.
:param set_data: The islpy.Set to plot.
:param color: The color of the points.
:param size: The diameter of the points.
:param marker: The marker used to mark... | 14,576 |
def sample(df, n, shape):
"""
randomly sample patch images from DataFrame
Parameters
----------
df : pd.DataFrame
DataFrame containing name of image files
n : int
number of patches to extract
shape : list
shape of patches to extract
Returns
-------
image... | 14,577 |
def bitsizeof_varint32(value: int) -> int:
"""
Gets bit size of variable 32-bit signed integer value.
:param value: Value to use for bit size calculation.
:returns: Bit size of the value.
:raises PythonRuntimeException: Throws if given value is out of range for varint32 type.
"""
return _b... | 14,578 |
def sort_faces(path):
"""
Sorts the faces with respect facial features
:param path: The path that is checked : Provided by the user
:return: None
"""
count = 0
to_find = get_directories(path)
faces = load_faces(to_find, path)
print("No. of faces to detect: ", len(to_find))
for i ... | 14,579 |
def slack(channel, message, subject=''):
"""
Sends a notification to meerkat slack server. Channel is '#deploy' only if
in live deployment, otherwise sent privately to the developer via slackbot.
Args:
channel (str): Required. The channel or username to which the message
should be post... | 14,580 |
def setFigFormat(figFormat):
"""
Set figure size for either journal/conference paper or presentation.
<333 T. Harrison 10/2020
Input:
1) figFormat - string - either 'paper' or 'presentation'
Output:
1) changed matplotlib rcParams
"""
##########################... | 14,581 |
def compute_similarity(img_one,img_two):
"""Performs image resizing just to compute the
cosine similarity faster
Input:
Two images
Output:
Cosine Similarity
"""
x = cv2.resize(img_one, dsize=(112, 112), interpolation=cv2.INTER_CUBIC)
y = cv2.resize(img_two, dsize=(112, 112), int... | 14,582 |
def get_results_from_firebase(firebase):
"""
The function to download all results from firebase
Parameters
----------
firebase : pyrebase firebase object
initialized firebase app with admin authentication
Returns
-------
results : dict
The results in a dictionary with t... | 14,583 |
def merge_sort(items):
"""
Sorts the items in the list
:param items: The list to sort
"""
# Base case: if the list has 1 we're done
if len(items) <= 1:
return
# Break the list into halves
middle = len(items) // 2
part1 = items[:middle]
part2 = items[middle:]
# Recu... | 14,584 |
def validate_response(response: Response, method: str, endpoint_url: str) -> None:
"""
This function verifies that your OpenAPI schema definition matches the response of your API endpoint.
It inspects your schema recursively, and verifies that the schema matches the structure of the response.
:param re... | 14,585 |
def mtci_vi(imgData, wave, mask=0, bands=[-1,-1,-1]):
"""
Function that calculates the MERIS Terrestrial Chlorophyll Index.
This functions uses wavelengths 753.75, 708.75, and 681.25 nm. The closest bands to these values will be used.
Citation: Dash, J. and Curran, P.J. 2004. The MERIS terrestrial chlo... | 14,586 |
def test_convert_overflow(fast_reader):
"""
Test reading an extremely large integer, which falls through to
string due to an overflow error (#2234). The C parsers used to
return inf (kind 'f') for this.
"""
expected_kind = 'U'
dat = ascii.read(['a', '1' * 10000], format='basic',
... | 14,587 |
def GetSourceFile(file, sourcepath):
"""Return a relative file if it is embedded in a path."""
for root in sourcepath:
if file.find(root) == 0:
prefix_length = len(root)
if not root.endswith('/'):
prefix_length += 1
relative_file = file[prefix_length:]
return relative_file
retu... | 14,588 |
def trace_cmd_installed():
"""Return true if trace-cmd is installed, false otherwise"""
with open(os.devnull) as devnull:
try:
subprocess.check_call(["trace-cmd", "options"], stdout=devnull)
except OSError:
return False
return True | 14,589 |
def getmessage(msg_type) :
""" Renvoie le message qui doit être affiché """
cfg = configparser.ConfigParser()
cfg.read(clt_path)
if not msg_type in cfg.options('Messages') :
sys.stderr.write("{} is not a valide type message : {}".format(msg_type, cfg.options('Messages')))
sys.stderr.flus... | 14,590 |
def refine_gene_list(adata, layer, gene_list, threshold, return_corrs=False):
"""Refines a list of genes by removing those that don't correlate well with the average expression of
those genes
Parameters
----------
adata: an anndata object.
layer: `str` or None (default: `None`)
... | 14,591 |
def shape_to_coords(value, precision=6, wkt=False, is_point=False):
"""
Convert a shape (a shapely object or well-known text) to x and y coordinates
suitable for use in Bokeh's `MultiPolygons` glyph.
"""
if is_point:
value = Point(*value).buffer(0.1 ** precision).envelope
... | 14,592 |
def get_args():
"""
Supports the command-line arguments listed below.
"""
parser = argparse.ArgumentParser(
description='Test Runner script')
parser.add_argument('-c', '--controller', type=str, required=True, help='Controller host name')
parser.add_argument('-s', '--server', type=str, r... | 14,593 |
def view_image(image, label=""):
"""View a single image."""
print("Label: %s" % label)
imshow(image, cmap=cm.gray)
show() | 14,594 |
def create_sink(sink_id: str, project_id: str, dataset_id: str, pubsub_topic: str, query: str = None) -> None:
"""Creates a sink to export logs to the given PubSub Topic.
:param sink_id: A unique identifier for the sink
:type sink_id: str
:param project_id: The project_id that is associated ... | 14,595 |
def max_union(map_list):
"""
Element-wise maximum of the union of a list of HealSparseMaps.
Parameters
----------
map_list : `list` of `HealSparseMap`
Input list of maps to compute the maximum of
Returns
-------
result : `HealSparseMap`
Element-wise maximum of maps
... | 14,596 |
def getDtypes(attributes, forecastHorizon):
"""
Auxillary function to generate dictionary of datatypes for data queried from dynamo.
Parameters
----------
attributes : list,
Attributes queried from dynamo.
forecastHorizon : integer,
Number of forecast horizons which have been qu... | 14,597 |
def cazy_synonym_dict():
"""Create a dictionary of accepted synonms for CAZy classes."""
cazy_dict = {
"Glycoside Hydrolases (GHs)": ["Glycoside-Hydrolases", "Glycoside-Hydrolases", "Glycoside_Hydrolases", "GlycosideHydrolases", "GLYCOSIDE-HYDROLASES", "GLYCOSIDE-HYDROLASES", "GLYCOSIDE_HYDROLASES", "GL... | 14,598 |
def alignment_patterns(matrix: list[list[Point]], version: int) -> None:
"""Adding alignment patterns (from version 2).
Args:
matrix: Matrix containing qr code pixels.
version: QR code version.
"""
if version > 1:
patterns = tables.alignment_patterns_table().get(version)
... | 14,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.