content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
|---|---|---|
def file_or_filename(input):
"""Open a filename for reading with `smart_open`, or seek to the beginning if `input` is an already open file.
Parameters
----------
input : str or file-like
Filename or file-like object.
Returns
-------
file-like object
An open file, positioned at the beginning.
"""
if isinstance(input, str):
# input was a filename: open as file
return open(input, 'rb')
else:
# input already a file-like object; just reset to the beginning
input.seek(0)
return input
|
e23faac638ba7adab92640f9785b190de9ece09a
| 77,514
|
def _get_channels(image):
"""Get the number of channels in the image"""
return 0 if len(image.shape) == 2 else image.shape[2]
|
3c7fb1e76252af7f396bcc055fbdb1cc75c66606
| 77,515
|
def missing_int(array: list):
"""given array return the missing integer in the continuous sequence
the following algorithm provides the missing integer in O(N) time
"""
full_sum = (len(array) + 1) * len(array) / 2
array_sum = sum(array)
return int(full_sum - array_sum)
|
7f3602424a05e8f90a3cc2a8dc9218463cdac9bc
| 77,518
|
def find_largest_true_block(arr):
"""
Given a boolean numpy array, finds the starting and ending indices
for the largest continuous block of """
start_index = -1
max_start_index = -1
max_length = -1
length = -1
i = 0
is_in_block = False
while i < len(arr):
if arr[i] and not is_in_block:
start_index = i
length = 0
is_in_block = True
elif arr[i] and is_in_block:
length += 1
else:
is_in_block = False
if length > max_length:
max_length = length
max_start_index = start_index
i += 1
if length > max_length:
max_length = length
max_start_index = start_index
return max_start_index, max_start_index + max_length
|
f55d5a473fd5ca6c032e5ca4e4be3c6e6a07d8c3
| 77,520
|
def str2list_row(row):
"""
convert str to list in a row.
"""
row = row.strip('\n') # delete '\n'.
row = row.strip('\r') # delete '\r'.
row = row.split(',')
return row
|
167ae610a45f2a41fd778ea020ff802769649a59
| 77,522
|
def suspensionDE(Y, t, m, c, k):
"""
Colin Simpson's code...
But the beautiful docstring is all mine
Y: array_like
contains initial conditions
t: array_like
time values
m: float
mass parameter
c: float
damping coeffcient parameter
k: float
spring constant parameter
"""
return [Y[1], -c*Y[1]-k*Y[0]/m]
|
c1a58c3479002abb1ccc9e252f5e7c454c8b5d85
| 77,524
|
import re
def regex_negative_match(pattern, value):
"""
Return False if the regex is "negative" and is a complete match for the
supplied value, True otherwise.
"""
if pattern[0] != '~':
# this is a positive regex, ignore
return True
return not re.match(pattern[1:] + '\Z', value)
|
6282f21818d9792cfc2aceff00f71e861ad49695
| 77,526
|
import time
def shell_sort(array: list) -> tuple:
"""
Return sorted list, name of sorting method, number of comparisons
and execution time using Shell Sort method
"""
name = "Shell sort"
comparisons = 0
array_length = len(array)
start = time.time_ns()
h = array_length // 2
while h > 0:
for i in range(h, array_length):
element = array[i]
k = i
while k >= h and array[k - h] > element:
comparisons += 1
array[k] = array[k - h]
k -= h
array[k] = element
if k >= h:
comparisons += 1
h = h // 2
waiting = time.time_ns() - start
return array, name, comparisons, waiting
|
25b4a467e652157d2c46a37fdcedd7b623179013
| 77,531
|
def _to_int(x):
"""Converts a completion and error code as it is listed in 32-bit notation
in the VPP-4.3.2 specification to the actual integer value.
"""
if x > 0x7FFFFFFF:
return int(x - 0x100000000)
else:
return int(x)
|
de155dce733dc93c3112d5bbc10f0dbc20110978
| 77,536
|
def sum_unit_fractions_from(m, n):
"""
What comes in: Two positive integers m and n with m <= n.
What goes out: Returns the sum:
1/m + 1/(m+1) + 1/(m+2) + ... + 1/n.
Side effects: None.
Examples:
-- sum_unit_fractions_from(6, 9) returns
1/6 + 1/7 + 1/8 + 1/9
which is about 0.545635
-- sum_unit_fractions_from(10, 9000) returns about 6.853
"""
# -------------------------------------------------------------------------
# DONE: 9. Implement and test this function.
# Note that you should write its TEST function first (above).
#
# IMPORTANT: As in previous problems in this session,
# you must NOT use the 2 or 3-parameter versions
# of the RANGE expression, if you happen to know them.
# -------------------------------------------------------------------------
total = 0
for k in range(n-m+1):
total = total+1/(m+k)
return total
|
a27aeebc8a452afcaeb72aae947721ba9ad84020
| 77,541
|
def commands_match(user_command, expected_command):
"""
Checks if the commands are essentially equivalent after whitespace
differences and quote differences.
Returns:
match: boolean
True if the commands appear to be equivalent.
"""
def normalize(command):
return command.replace(" ", "").replace("'", "\"")
return normalize(user_command) == normalize(expected_command)
|
e0b8632f7e815c306fc8d68d01e26aae3d9f15ab
| 77,542
|
def get_form_field(form, field_name):
"""
Return a field of a form
"""
return form[field_name]
|
76b16c4084e8c129d31ab4b75c27e66ecd934e15
| 77,544
|
def add_survey(surveys, new_survey):
"""
Add survey to list of surveys then reorder list base on MD, survey list is list of tuples (md, inc, azm, *).
surveys parameter is existing list. new_surveys parameter is survey to be added. new_surveys should
be tuple of (md, inc, az). Brute force method for now just recalculates all the surveys since computation
time is negligible.
"""
# inject new survey into survey list, then sorting new surveys into list based on MD depth
surveys.append(new_survey)
surveys.sort(key=lambda tup: tup[0]) # sorts list in place
return surveys
|
596cc9eef0b9a0057e0c077b10a2800c2df7f2fe
| 77,546
|
from typing import List
import click
def list_options(options: List) -> int:
"""
This is a utility for click (cli) that prints of list of items as a numbered
list. It prompts users to select an option from the list.
For example, `["item1", "item2", "item3"]` would print...
```
(01) item1
(02) item2
(03) item3
```
Parameters
----------
- `options`:
a list of strings to choose from
Returns
--------
- `selected_index`:
The integer value of the choice selected. This will follw python indexing
so the index of the options list. (e.g. if item1 was selected, 0 would be
returned)
"""
for i, item in enumerate(options):
number = str(i + 1).zfill(2)
click.echo(f"\t({number}) {item}")
# Have the user select an option. We use -1 because indexing count is from 0, not 1.
selected_index = click.prompt("\n\nPlease choose a number:", type=int) - 1
if selected_index >= len(options) or selected_index < 0:
raise click.ClickException(
"Number does not match any the options provided. Exiting."
)
click.echo(f"You have selectd `{options[selected_index]}`.")
return selected_index
|
62253091f6c05b688c4d8cb62d9ef81021c3bcb0
| 77,547
|
import json
def load_dataset(path_dataset):
"""Load dataset from a JSON file
Args:
path_dataset (str): file path to a dataset
Returns:
list: list of features's dictionary
"""
with open(path_dataset, 'r', encoding='utf-8') as fd:
dataset = json.load(fd)
return dataset
|
9449df4ea30c94b5af3ef62e96c685c2ae5af7b7
| 77,549
|
def correct_max_relative_intensity(replicate_mass_peak_data):
"""Check that the max peak is 100%.
If not, find largest peak, set to 100% and apply correction factor to other peak intensities.
"""
max_average_relative_intensity = 0
max_intensity_mass = 0
max_intensity = 0
for replicate_mass_peak in replicate_mass_peak_data:
if replicate_mass_peak.average_intensity > max_intensity:
max_intensity = replicate_mass_peak.average_intensity
if replicate_mass_peak.relative_intensity > max_average_relative_intensity:
max_average_relative_intensity = replicate_mass_peak.relative_intensity
max_intensity_mass = replicate_mass_peak.average_mass
if max_average_relative_intensity != 100:
for replicate_mass_peak in replicate_mass_peak_data:
replicate_mass_peak.relative_intensity = round((replicate_mass_peak.relative_intensity /
max_average_relative_intensity) * 100, 1)
return replicate_mass_peak_data, max_intensity_mass, max_intensity
|
2ccadb5bf798f824b7a537629ffd7f807d6c1483
| 77,551
|
def compress(speakers, talks):
"""Reduce consecutive dialogue by the same person into single records"""
i = 0
current_text = ""
current_speaker = ""
compressed_speakers = []
compressed_talks = []
for speaker, text in zip(speakers, talks):
if speaker == current_speaker:
current_text = current_text + " " + text
else:
compressed_speakers.append(current_speaker)
compressed_talks.append(current_text.replace('"', ''))
current_speaker = speaker
current_text = text
compressed_speakers.append(current_speaker)
compressed_talks.append(current_text.replace('"', ''))
return compressed_speakers, compressed_talks
|
23e70d879bac9d8f5c4224c9eeb86c2338a91be0
| 77,555
|
from typing import Dict
from typing import Union
from typing import Tuple
from typing import List
import torch
def get_flatten_inputs(
model_inputs: Dict[str, Union[Tuple, List, torch.Tensor]]
) -> Dict[str, torch.Tensor]:
"""This function unwraps lists and tuples from 'model_inputs' and assigns a
unique name to their values.
Example:
model_inputs = {'A': list(tensor_0, tensor_1), 'B': tensor_3}
flatten_inputs = get_flatten_inputs(model_inputs)
flatten_inputs: {'A_0': tensor_0, 'A_1': tensor_1, 'B': tensor_3}
Args:
model_inputs (dict): Key-value pairs of model inputs with
lists and tuples.
Returns:
Dict[str, torch.Tensor]: Key-value pairs of model inputs with
unwrapped lists and tuples.
"""
flatten_inputs = {}
for name, value in model_inputs.items():
if isinstance(value, torch.Tensor):
flatten_inputs[name] = value
elif isinstance(value, (list, tuple)):
if len(value) == 1:
flatten_inputs[name] = value[0]
else:
for i, tensor in enumerate(value):
name_i = f'{name}_{i}'
flatten_inputs[name_i] = tensor
return flatten_inputs
|
2ddea01cdff5eddea3d8a55b53e216500315158a
| 77,557
|
def provider_names(providers):
"""
Returns the names of the given Provider instances.
"""
return [p.provider_name for p in providers]
|
3479909a7ef94a398b6c1784a23d79307f219904
| 77,559
|
def read_plain_vocabulary(filename):
"""
Read a vocabulary file containing one word type per line.
Return a list of word types.
"""
words = []
with open(filename, 'rb') as f:
for line in f:
word = line.decode('utf-8').strip()
if not word:
continue
words.append(word)
return words
|
3c83c5813b206147a5a4130d8fa1b9a4ffe57d85
| 77,560
|
def is_valid_host(host):
""" Check if host is valid.
Performs two simple checks:
- Has host and port separated by ':'.
- Port is a positive digit.
:param host: Host in <address>:<port> format.
:returns: Valid or not.
"""
parts = host.split(':')
return len(parts) == 2 or parts[1].isdigit()
|
e7d22558e8a41b3b3345e863e11cdeec1a37d984
| 77,561
|
def cmpExonerateResultByQueryAlignmentStart(e1, e2):
"""Comparator function for sorting C{ExonerateResult}s by query alignment start.
@param e1: first exonerate result
@type e1: C{ExonerateResult}
@param e2: second exonerate result
@type e2: C{ExonerateResult}
@return: one of -1, 0 or 1
@rtype: C{int}
"""
if e1.queryAlignmentStart < e2.queryAlignmentStart:
return -1
elif e1.queryAlignmentStart > e2.queryAlignmentStart:
return 1
return 0
|
633779c2f95282978ed5a807ba743d261937653f
| 77,565
|
import math
def pixel_coords_zoom_to_lat_lon(PixelX, PixelY, zoom):
"""
The function to compute latitude, longituted from pixel coordinates at a given zoom level
Parameters
----------
PixelX : int
x coordinate
PixelY : int
y coordinate
zoom : int
tile map service zoom level
Returns
-------
lon : float
the longitude in degree
lat : float
the latitude in degree
"""
MapSize = 256 * math.pow(2, zoom)
x = (PixelX / MapSize) - 0.5
y = 0.5 - (PixelY / MapSize)
lon = 360 * x
lat = 90 - 360 * math.atan(math.exp(-y * 2 * math.pi)) / math.pi
return lon, lat
|
021e000c22a10cf3bb3dd0642a02be136db3484c
| 77,572
|
def get_firing_cells(df, cells, min_firing_frequency=1):
"""
Only returns the cells that fire over a certain frequency
(across entire recording)
:param df:
:param cells:
:param min_firing_frequency: in hz
:return: Cells that meet the criteria
"""
total_time = df.index.max() - df.index.min()
min_firing_total = min_firing_frequency * total_time
new_cells = []
for cell in cells:
total = df[cell].sum()
if total > min_firing_total:
new_cells.append(cell)
return new_cells
|
e3c77433152d9c478c1bc4e3b3c31be338b36763
| 77,574
|
def pkcs7_unpad(text):
"""
删除PKCS#7方式填充的字符串
:param text:
:return: str
"""
# 每个填充值等于填充序列的长度
return text[: -text[-1]]
|
33bb33355eaca5ebf3b5a7ea2c678d30bffc1512
| 77,577
|
import random
def mockify(text: str):
"""
Randomizes character case in a string.
:param text: Text to randomize case on
:return: str
"""
return ''.join(random.choice((str.upper, str.lower))(x) for x in text)
|
4119cd2aa154de12eb7c2391f65af7feee37e919
| 77,578
|
def flip_cost(variant, target_value):
"""Returns cost of flipping the given read variant to target_value."""
if variant.allele == target_value:
return 0
else:
return min([x for x in variant.quality if x !=0])
|
6eb0e776d9e894218adb57ceaee831d0428eff60
| 77,580
|
import math
def circularity (
area: float,
perimeter: float
) -> float:
""" Calculates the circularity shape factor with given area and perimeter.
Args:
area (float):
area of a shape
perimeter (float):
length of the perimeter of a shape
Returns:
A float with the circularity shape factor as value
"""
if perimeter == 0:
return 0.0
return (4 * math.pi * area) / (perimeter ** 2)
|
a481aea8788c0ae0b844bfcb076d5eb842f96860
| 77,581
|
def encode_time(time):
""" Converts a time string in HH:MM format into minutes """
time_list = time.split(":")
if len(time_list) >= 2:
return (int(time_list[0]) * 60) + int(time_list[1])
return 0
|
938f0eba5dbbf2b8e61eeeddd249eb605bc618fd
| 77,582
|
from typing import Dict
from typing import List
from typing import Set
import functools
import operator
def reshape_meta(o: Dict[int | str, int]) -> List[Set[int]]:
"""Convert the CSV data to sets
Parameters:
- `o`: `Dict[int | str, int]`, data to be converted
Returns: `List[Set[int]]`
- The first set contains ID of all issues;
- The second set contains ID of closed issues;
- The third set contains ID of open issues;
- The fourth set contains ID of pending issues;
- The fifth set contains ID of languishing issues.
"""
ret: List[Set[int]] = [set() for _ in range(5)]
for i in o:
ret[o[i]].add(int(i))
ret[0] = functools.reduce(operator.or_, ret[1:])
return ret
|
33e634d464f5673dbc76920ebfb5f20686f1b484
| 77,584
|
def binary_search(dep_times_list, start_time):
"""
Function representing the binary search algorithm, from a list of ordered
values (departure times) chooses value equal or closest (higher) to given
parameter
Parameters
----------
dep_times_list: list of ordered datetime objects
start_time: datetime object
Returns: tuple of selected departure time and index of the time
-------
"""
#if start time earlier than all departure times, the first departure time
#is chosen
if (start_time <= dep_times_list[0]):
return (dep_times_list[0], 0)
#if start time is after all departure times, no connection is available
#within this route, the best time is set to None
if start_time > dep_times_list[len(dep_times_list) - 1]:
return None,None
left_index = 0
right_index = len(dep_times_list) - 1
while left_index <=right_index:
if left_index == right_index:
return (dep_times_list[left_index], left_index)
middle_index = (left_index + right_index) // 2
middle_time = dep_times_list[middle_index]
if start_time > middle_time:
left_index = middle_index + 1
elif start_time < middle_time:
right_index = middle_index
else:
return (dep_times_list[middle_index], middle_index)
return (None, None)
|
4a756d70df2ab372ea2b3c55267fb7e7b71f6903
| 77,585
|
def gi(arr, index, default=None):
"""Get the index in an array or the default if out of bounds."""
if index >= len(arr):
return default
return arr[index]
|
8755973e9c0c49b0af67d6ee0a62caf00f1ea98b
| 77,586
|
import ntpath
def _path_leaf(path: str) -> str:
"""
Return the leaf object of the given path.
:param path: directory path to parse
:return: leaf object of path
"""
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
|
6053adea690b129024e3760ebe352573b17dd43b
| 77,588
|
def head(list1: list) -> object:
"""Return the head of a list.
If the input list is empty, then return `None`.
:param list list1: input list
:return: the first item
:rtype: object
>>> head([])
None
>>> head([1,2,3])
1
"""
if len(list1) == 0:
return None
else:
return list1[0]
|
14b60ccb29c9c551d45958f8c6efc9b85050551b
| 77,589
|
def add_fixed_mods(seqs:list, mods_fixed:list, **kwargs)->list:
"""
Adds fixed modifications to sequences.
Args:
seqs (list of str): sequences to add fixed modifications
mods_fixed (list of str): the string list of fixed modifications. Each modification string must be in lower case, except for that the last letter must be the modified amino acid (e.g. oxidation on M should be oxM).
Returns:
list (of str): the list of the modified sequences. 'ABCDEF' with fixed mod 'cC' will be 'ABcCDEF'.
"""
if not mods_fixed:
return seqs
else:
for mod_aa in mods_fixed:
seqs = [seq.replace(mod_aa[-1], mod_aa) for seq in seqs]
return seqs
|
1e81c265fee6ce18071165920e770ffdb940adb0
| 77,601
|
from typing import Mapping
def render_callable(
name: str,
*args: object,
kwargs: Mapping[str, object] | None = None,
indentation: str = "",
) -> str:
"""
Render a function call.
:param name: name of the callable
:param args: positional arguments
:param kwargs: keyword arguments
:param indentation: if given, each argument will be rendered on its own line with
this value used as the indentation
"""
if kwargs:
args += tuple(f"{key}={value}" for key, value in kwargs.items())
if indentation:
prefix = f"\n{indentation}"
suffix = "\n"
delimiter = f",\n{indentation}"
else:
prefix = suffix = ""
delimiter = ", "
rendered_args = delimiter.join(str(arg) for arg in args)
return f"{name}({prefix}{rendered_args}{suffix})"
|
8d507335be5bb5e070c5c28807df301ca7572913
| 77,606
|
def format_time(seconds, total=None, short=False):
"""
Format ``seconds`` (number of seconds) as a string representation.
When ``short`` is False (the default) the format is:
HH:MM:SS.
Otherwise, the format is exacly 6 characters long and of the form:
1w 3d
2d 4h
1h 5m
1m 4s
15s
If ``total`` is not None it will also be formatted and
appended to the result separated by ' / '.
"""
def time_tuple(ts):
if ts is None or ts < 0:
ts = 0
hours = ts / 3600
mins = (ts % 3600) / 60
secs = (ts % 3600) % 60
tstr = '%02d:%02d' % (mins, secs)
if int(hours):
tstr = '%02d:%s' % (hours, tstr)
return (int(hours), int(mins), int(secs), tstr)
if not short:
hours, mins, secs, curr_str = time_tuple(seconds)
retval = curr_str
if total:
hours, mins, secs, total_str = time_tuple(total)
retval += ' / %s' % total_str
return retval
else:
units = [
(u'y', 60 * 60 * 24 * 7 * 52),
(u'w', 60 * 60 * 24 * 7),
(u'd', 60 * 60 * 24),
(u'h', 60 * 60),
(u'm', 60),
(u's', 1),
]
seconds = int(seconds)
if seconds < 60:
return u'00m {0:02d}s'.format(seconds)
for i in range(len(units) - 1):
unit1, limit1 = units[i]
unit2, limit2 = units[i + 1]
if seconds >= limit1:
return u'{0:02d}{1} {2:02d}{3}'.format(
seconds // limit1, unit1,
(seconds % limit1) // limit2, unit2)
return u' ~inf'
|
456438e356b375af77fe1527f35ea22d230450f0
| 77,607
|
import torch
def get_topk_from_heatmap(scores, k=20):
"""Get top k positions from heatmap.
Args:
scores (Tensor): Target heatmap with shape
[batch, num_classes, height, width].
k (int): Target number. Default: 20.
Returns:
tuple[torch.Tensor]: Scores, indexes, categories and coords of
topk keypoint. Containing following Tensors:
- topk_scores (Tensor): Max scores of each topk keypoint.
- topk_inds (Tensor): Indexes of each topk keypoint.
- topk_clses (Tensor): Categories of each topk keypoint.
- topk_ys (Tensor): Y-coord of each topk keypoint.
- topk_xs (Tensor): X-coord of each topk keypoint.
"""
batch, _, height, width = scores.size()
topk_scores, topk_inds = torch.topk(scores.view(batch, -1), k)
topk_clses = topk_inds // (height * width)
topk_inds = topk_inds % (height * width)
topk_ys = topk_inds // width
topk_xs = (topk_inds % width).int().float()
return topk_scores, topk_inds, topk_clses, topk_ys, topk_xs
|
cff0800fac35269234fdaa3fd35d5461efca11ad
| 77,608
|
def trimMatch(x, n):
""" Trim the string x to be at most length n. Trimmed matches will be reported
with the syntax ACTG[a,b] where Ns are the beginning of x, a is the length of
the trimmed strng (e.g 4 here) and b is the full length of the match
EXAMPLE:
trimMatch('ACTGNNNN', 4)
>>>'ACTG[4,8]'
trimMatch('ACTGNNNN', 8)
>>>'ACTGNNNN'
"""
if len(x) > n and n is not None:
m= x[0:n] + '[' + str(n) + ',' + str(len(x)) + ']'
else:
m= x
return(m)
|
43bfbcfa0286646fae75c73bccb245a9f113131e
| 77,611
|
def manhattanDistance(current: list, target: list):
"""
Calculates the Manhattan distance between two 3x3 lists
"""
count = 0
curr_1d = []
tgt_1d = []
for i in range(3):
for j in range(3):
curr_1d.append(current[i][j])
tgt_1d.append(target[i][j])
for x in tgt_1d:
count += abs(tgt_1d.index(x) - curr_1d.index(x))
return count
|
4ed95397294655d0ff9996b785fb9ed4787c0eeb
| 77,613
|
def getMetricsDense(dfA, dfC):
"""
Return metrics from binary list such as [0,1,0], [1,1,0] where the index should be the same events
dfA are the samples where the antecedent are True or False
dfC are the samples where the consequents are True or False
"""
support = dfA.sum()
precision = (dfA & dfC).sum() / dfA.sum() #P(A&C)/P(A) or P(C|A)
recall = (dfA & dfC).sum() / dfC.sum()
lift = precision / (dfC.sum() / len(dfA))
fMeasure = 2 * (precision * recall / (precision + recall))
return {
"support": round(support, 2),
"precision": round(precision, 2),
"recall": round(recall, 2),
"lift": round(lift, 2),
"fMeasure": round(fMeasure, 2)
}
|
71f3ecc9121f9d95c0982a57a77d4aaa2c864fc3
| 77,617
|
def _tup_equal(t1,t2):
"""Check to make sure to tuples are equal
:t1: Tuple 1
:t2: Tuple 2
:returns: boolean equality
"""
if t1 is None or t2 is None:
return False
return (t1[0] == t2[0]) and (t1[1] == t2[1])
|
524c0144ba21ee6f877a2fb2d83660f92a1facf8
| 77,619
|
from typing import Union
def get_precision(num: Union[int, float]) -> int:
"""Returns the precision of a number."""
if type(num) == int:
return 0
return len(str(num).split('.')[1])
|
72f3dcb09e8480b51b1d29ee6859af74491a5abd
| 77,620
|
def assert_is_dict(var):
"""Assert variable is from the type dictionary."""
if var is None or not isinstance(var, dict):
return {}
return var
|
3ed3e970662213a920854e23b6e4a18042daddf0
| 77,622
|
def _text_indent(text, indent):
# type: (str, str) -> str
"""
indent a block of text
:param str text: text to indent
:param str indent: string to indent with
:return: the rendered result (with no trailing indent)
"""
lines = [line.strip() for line in text.strip().split('\n')]
return indent + indent.join(lines)
|
00101ea91edf3207983b57aa0d9022c08a4956ba
| 77,626
|
def get_textual_column_indexes(train, test):
"""Return a tuple containing an ndarray with train and test textual column indexes.
Keyword arguments:
train -- the train dataframe
test -- the test dataframe
"""
txt_cols_train = train.select_dtypes('object').columns
txt_indexes_train = train.columns.get_indexer(txt_cols_train)
txt_cols_test = test.select_dtypes('object').columns
txt_indexes_test = test.columns.get_indexer(txt_cols_test)
return txt_indexes_train, txt_indexes_test
|
c95ee41eef37d90b3c4945a3a6d73d8295fac8ea
| 77,628
|
import time
def get_timeout(max_time):
"""
Calculates the moment in time when a timeout error should be raised.
:param max_time: maximum time interval
:return: the moment in time when the timeout error should be raised
"""
return time.time() + max_time
|
b71c5a3bff3826c172758d37dda1a22723d612e5
| 77,629
|
def make_table(oldtable=None, values=None):
"""Return a table with thermodynamic parameters (as dictionary).
Arguments:
- oldtable: An existing dictionary with thermodynamic parameters.
- values: A dictionary with new or updated values.
E.g., to replace the initiation parameters in the Sugimoto '96 dataset with
the initiation parameters from Allawi & SantaLucia '97:
>>> from Bio.SeqUtils.MeltingTemp import make_table, DNA_NN2
>>> table = DNA_NN2 # Sugimoto '96
>>> table['init_A/T']
(0, 0)
>>> newtable = make_table(oldtable=DNA_NN2, values={'init': (0, 0),
... 'init_A/T': (2.3, 4.1),
... 'init_G/C': (0.1, -2.8)})
>>> print("%0.1f, %0.1f" % newtable['init_A/T'])
2.3, 4.1
"""
if oldtable is None:
table = {
"init": (0, 0),
"init_A/T": (0, 0),
"init_G/C": (0, 0),
"init_oneG/C": (0, 0),
"init_allA/T": (0, 0),
"init_5T/A": (0, 0),
"sym": (0, 0),
"AA/TT": (0, 0),
"AT/TA": (0, 0),
"TA/AT": (0, 0),
"CA/GT": (0, 0),
"GT/CA": (0, 0),
"CT/GA": (0, 0),
"GA/CT": (0, 0),
"CG/GC": (0, 0),
"GC/CG": (0, 0),
"GG/CC": (0, 0),
}
else:
table = oldtable.copy()
if values:
table.update(values)
return table
|
8ac7e50041e2fbf85bd94af20f5bc68bd024fdaf
| 77,630
|
def item(index, thing):
"""
ITEM index thing
if the ``thing`` is a word, outputs the ``index``th character of
the word. If the ``thing`` is a list, outputs the ``index``th
member of the list. If the ``thing`` is an array, outputs the
``index``th member of the array. ``Index`` starts at 1 for words
and lists; the starting index of an array is specified when the
array is created.
"""
if isinstance(thing, dict):
return thing[index]
else:
return thing[index-1]
|
c22da02ba1ea583c5d4799d71ab728cd5f2882ac
| 77,631
|
import math
def aire_disque(r: float) -> float:
"""Précondition : r>0
Retourne l’aire πr2 d’un disque de rayon r
"""
return math.pi * r*r
|
2e43f630ae3327ecbcb14d1644bef094053bc88b
| 77,633
|
def multi_replace(text, patterns):
"""Replaces multiple pairs in a string
Arguments:
text {str} -- A "string text"
patterns {dict} -- A dict of {"old text": "new text"}
Returns:
text -- str
"""
for old, new in patterns.items():
text = text.replace(old, new)
return text
|
434d5bee6cbefc56292f77234e58316ce1146d60
| 77,635
|
def check_share_access(shares, con):
"""
Checks if a list of shares are accessible
Args:
shares: (list) A list of share objects
con: (SMBConnection) The SMB connection objects
Returns:
A list of shares that were accessible
"""
accessible = []
for share in shares:
try:
tree_id = con.connectTree(share)
print(f"[+] Share is accessible: {share}")
accessible.append({'name': share, 'id': tree_id})
except Exception as e:
print(f"[-] Share is not accessible: {share}, {str(e)}")
continue
return accessible
|
b6d19c25c19d46c67308eb204fe2f0a13e7dacae
| 77,636
|
def caption_time_to_milliseconds(caption_time):
"""
Converts caption time with HH:MM:SS.MS format to milliseconds.
Args:
caption_time (str): string to convert
Returns:
int
"""
ms = caption_time.split('.')[1]
h, m, s = caption_time.split('.')[0].split(':')
return (int(h) * 3600 + int(m) * 60 + int(s)) * 1000 + int(ms)
|
36e923e89718fb2319a97da29662f9d8ecf4cb3d
| 77,637
|
def keybase_lookup_url(username):
"""Returns the URL for looking up a user in Keybase"""
return "https://keybase.io/_/api/1.0/user/lookup.json?usernames=%s" \
% username
|
7c44d47ae2dfef9cdc699f7d7e9ee4c07adbfda3
| 77,643
|
def make_token_dict(sentences, pad_token=None, extra_tokens=None):
"""Extract tokens from tokenized *sentences*, remove all duplicates, sort
the resulting set and map all tokens onto ther indices.
:param sentences: tokenized sentences.
:type sentences: list([list([str])])
:param pad_token: add a token for padding.
:type pad_char: str
:param extra_tokens: add any tokens for other purposes.
:type extra_tokens: list([str])
:return: the dict created and the index of the padding token (it's
always the last index, if pad_token is not None); the indices of
the extra tokens.
:rtype: tuple(dict({char: int}), int, list([int])|None)
"""
t2idx = {
x: i for i, x in enumerate(sorted(set(
x for x in sentences for x in x
)))
}
def add_token(token):
if token:
assert token not in t2idx, \
"ERROR: token '{}' is already in the dict".format(token)
idx = t2idx[token] = len(t2idx)
else:
idx = None
return idx
if extra_tokens is not None:
extra_idxs = [add_token(t) for t in extra_tokens]
else:
extra_idxs = None
pad_idx = add_token(pad_token)
return t2idx, pad_idx, extra_idxs
|
35fe2d17e136559ac189d0273a2e1b93c8f439cc
| 77,644
|
def getContentChild(tag):
"""Returns true if tag has content as a class"""
if tag.get('class', None) and 'content' in tag['class']:
return True
return False
|
dc632c6fd4c8b57a0d2924e4030c2384cc4c3fd4
| 77,648
|
def test_for_a_stretch(seq, a_stretch):
"""
Test whether or not the immediate downstream bases of the PAS are A
throughout the a_stretch distance.
>>> test_for_a_stretch("AAAAATTTTTTTTTT", 5)
'a'
>>> test_for_a_stretch("AAAATTTTTTTTTTT", 5)
''
"""
return 'a' if seq[:a_stretch].count("A") == a_stretch else ''
|
d974a85a0fd7548758731f6f67ee40f4ffcd0be3
| 77,649
|
import csv
def make_empty_features_csv(fpath):
"""
creates an empty csv file to hold extracted features
returns fpath to the file
"""
# save empty csv to hold features
with open(fpath, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
print('outputting features to: ', fpath)
return fpath
|
123d3dfb795fbd3be963fbf7c15d704713f502b8
| 77,654
|
def read_fasta(fname):
"""Read in a Fasta file and returns a list of sequences."""
temp = []
seqs = []
with open(fname, 'r') as f:
for line in f.readlines():
if line.startswith('>'):
temp.append(line[1:].strip())
seqs.append('')
else:
seqs[-1] += line.strip()
# error checking
for i in seqs:
if not i.isalpha():
raise Exception('Input Error')
return seqs
|
f56d51c891f80cdd3077e244231cb63c6febdf4d
| 77,655
|
def build_project(project_name):
"""Builds eclipse project file.
Uses a very simple template to generate an eclipse .project file
with a configurable project name.
Args:
project_name: Name of the eclipse project. When importing the project
into an eclipse workspace, this is the name that will be shown.
Returns:
Contents of the eclipse .project file.
"""
template = """<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>{project_name}</name>
<comment>
</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.python.pydev.PyDevBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.python.pydev.pythonNature</nature>
</natures>
</projectDescription>"""
return template.format(project_name=project_name)
|
255207d917c6f413ec7774c018f454cc309ae537
| 77,657
|
def var(string: str, dic: dict={}):
"""Replaces a string using a dict."""
for key in dic.keys():
string = string.replace('{' + str(key) + '}', str(dic[key]))
return string
|
d5f8ea56259b9421fee0507df47c9a3dfa40e0e0
| 77,660
|
import time
def format_time(t):
"""Formats time into string with minutes and seconds
:param t: The time in seconds
:type t: float
:return: Formatted string with minutes and seconds
:rtype: string
"""
time_string = time.strftime("%M:%S", time.gmtime(t))
time_list = time_string.split(":")
num_min = time_list[0]
num_sec = time_list[1]
return f"{num_min} minutes and {num_sec} seconds"
|
7bad6fdde1cf1cdee10c1d7eeee9a95e31e7a007
| 77,661
|
from typing import Dict
from typing import Callable
from typing import Any
import inspect
def getObjPublicMethods(obj: object) -> Dict[str, Callable[..., Any]]:
""" Return a dictionary of object public methods that does not start
with '_' or '__'. Each item represents: 'name': <reference to a method>
Note:
Only class 'public' methods are returned, without ``@staticmethod``.
They are of type '<bound method...>'
Args:
obj: object to inspect.
"""
functions = inspect.getmembers(obj, inspect.ismethod)
relevantMethods = {}
for func in functions:
name, reference = func
if not name.startswith('_'):
relevantMethods[name] = reference
return relevantMethods
|
e5c31a2af3475553b615e3137760e896591705ab
| 77,668
|
from typing import Tuple
from pathlib import Path
def read_lean_template(file_name: str = 'template.lean') -> Tuple[int, str]:
"""Read a template Lean file containing at least one sorry.
Returns the line number of the first sorry"""
text = Path(file_name).read_text()
nb = 0
for line in text.split('\n'):
nb += 1
if 'sorry' in line:
break
return nb, text
|
b275b9371af15392faa2513ecf27992f748cde6b
| 77,669
|
import re
def name_string_to_list(composite_names):
"""
Split comma separated slurm composite node name format.
Composite node names contain commas so ignore them within brackets.
:param composite_names: str: a comma separated nodename list
:return: list of composite node names
"""
splitter = re.compile(r'(?:[^,\[]|\[[^\]]*\])+')
return splitter.findall(composite_names)
|
3da10aa422862946310c065673dcf5316e64db5a
| 77,670
|
def _normalize_block_name(block_name):
"""Implements Unicode name normalization for block names.
Removes white space, '-', '_' and forces lower case."""
block_name = ''.join(block_name.split())
block_name = block_name.replace('-', '')
return block_name.replace('_', '').lower()
|
eead462770a826e8d0c6f6c03a0da00cd94b7bf3
| 77,680
|
def kumaraswamy_invcdf(a, b, u):
"""Inverse CDF of the Kumaraswamy distribution"""
return (1.0 - (1.0 - u) ** (1.0 / b)) ** (1.0 / a)
|
0fef516b653079a1b046886cecc37ba66f6a186a
| 77,682
|
def get_classes(classes_path):
"""
Reads the class names from a file and returns them in a list.
Parameters
----------
classes_path : string
Path that points to where the class name information is stored.
Returns
-------
class_names : list
A list of format:
['class_1', 'class_2', 'class_3', ...]
"""
with open(classes_path) as f:
class_names = f.readlines()
class_names = [c.strip() for c in class_names]
return class_names
|
9cc59762779276dfce857c9411220a208c270079
| 77,685
|
def crop_image_to_multiple_eight(image):
"""Returns a crop of an image to be multiples of 8."""
dimensions = image.size
width = dimensions[0]
height = dimensions[1]
new_width = width - (width % 8)
new_height = height - (height % 8)
box = (0, 0, new_width, new_height)
return image.crop(box)
|
8b261fa96be1695c9f00e0fc7d54fac7e98d54fd
| 77,687
|
def lineToList(line):
"""Converts a tab-delimited line into a list of strings, removing the terminating \n and \r."""
return line.rstrip("\n\r").split("\t")
|
1f0b6ad23504d29004f5fd77506ed33cc728f8f3
| 77,689
|
def calc_prefix(_str, n):
"""
Return an n charaters prefix of the argument string of the form
'prefix...'.
"""
if len(_str) <= n:
return _str
return _str[: (n - 3)] + '...'
|
e7c666667dc24941ad496158f321bbc7706a5d06
| 77,693
|
def removeEmptyElements(list):
""" Remove empty elements from a list ( [''] ), preserve the order of the non-null elements.
"""
tmpList = []
for element in list:
if element:
tmpList.append(element)
return tmpList
|
140a9d93ff9ce18462d36d54b5e2634cecf5f4d3
| 77,694
|
import glob
def get_all_files(path, valid_suffix):
"""
Get all files in a directory with a certain suffix
"""
files = []
for suffix in valid_suffix:
files.extend(glob.glob(path + "*/**/*" + suffix, recursive=True))
return files
|
79dac548b982cd82069bb9595ec335667a09da0a
| 77,696
|
def option_rep(optionname, optiondef):
"""Returns a textual representation of an option.
option_rep('IndentCaseLabels', ('bool', []))
=> 'IndentCaseLabels bool'
option_rep('PointerAlignment', ('PointerAlignmentStyle',
[u'Left', u'Right', u'Middle']))
=> 'PointerAlignment PointerAlignmentStyle
Left
Right
Middle'
"""
optiontype, configs = optiondef
fragments = [optionname + ' ' + optiontype]
for c in configs:
fragments.append(" " * 8 + c)
rep = "\n".join(fragments)
return rep
|
005462286006469ce333ca9973c4fb1ee056be9e
| 77,698
|
def isString(strng, encoding):
"""
Returns true if the string contains no ASCII control characters
and can be decoded from the specified encoding.
"""
for char in strng:
if ord(char) < 9 or ord(char) > 13 and ord(char) < 32:
return False
try:
strng.decode(encoding)
return True
except:
return False
|
4ac7f542e1e48591ace7b07797c796434e420c76
| 77,700
|
def electrokinetic2(row):
"""
notes: 1) zeta potentials are in mV. if in V, remove the 1e3
2) relative dialectric is for water, if this is not true,
make a column and change the function.
references:
(1) You-Im Chang and Hsun-Chih Chan.
"Correlation equation for predicting filter coefficient under
unfavorable deposition conditions".
AIChE journal, 54(5):1235–1253, 2008.
(2) Rajagopalan, R. & Kim, J. S.
"Adsorption of brownian particles in the presence of potential
barriers: effect of different modes of double-layer interaction".
Journal of Colloid and Interface Science 83, 428–448 (1981).
:param row:
:return: 2nd electrokinetic parameter
"""
zp = row.enm_zeta_potential / 1e3 # particle zeta potential
zc = row.collector_zeta_potential / 1e3 # collector zeta potential
numerator = 2 * (zp / zc)
denominator = 1 + (zp / zc) ** 2
return numerator / denominator
|
ee1fd24883b85163300986a7ab279d6522d130e0
| 77,706
|
def build_quarter_string(operational_year, operational_quarter):
"""
Helper function to build quarter name for JIRA.
:param String operational_year:
:param String operational_quarter:
:return: Formatted Quarter name
:rtype: String
"""
return 'Y%s-Q%s' % (operational_year, operational_quarter)
|
eb2e1591d1f99b6bb01fed5af6d7b820514ccb3f
| 77,711
|
def derive_queue_len_from_count(df_x_name, predicted_rf_counts):
"""Use the ML classifications of queue count to estimate queue length for each link"""
# get the index values from X
idx = df_x_name.index.tolist()
# replaced veh_len_avg_in_group with avg_veh_len IF Na/0
# get the veh_len_avg_in_group
veh_len_avg_grp = df_x_name.iloc[idx]['veh_len_avg_in_group'].to_numpy()
pred_q_len = predicted_rf_counts*veh_len_avg_grp
return pred_q_len
|
5809195f04155ab369553b8a0720fd7054c37269
| 77,714
|
def is_legacy_data(sorald_stats: dict) -> bool:
"""Detect whether this data is detailed stats output from modern Sorald or
legacy data (from the old PRs.json file or simply empty).
"""
return all(
isinstance(key, str) and isinstance(value, (int, str))
for key, value in sorald_stats.items()
)
|
0d3aa3265f64af2681ac10fcfe35fcbede2779ea
| 77,715
|
def create_canvas(width, height, enable_color = True):
"""
Create a new char canvas.
Parameters
----------
height: height of the game view (int).
width: width of the game view (int).
enable_color: enable color in the game view (bool)
Return
------
canvas: 2D ascii canvas (dic).
Version
-------
Specification: Nicolas Van Bossuyt (v1. 10/02/17)
Implementation: Nicolas Van Bossuyt (v1. 10/02/17)
"""
# Initialize the canvas.
canvas = {'size': (width, height), 'color': enable_color, 'grid': {}}
# Create canvas's tiles.
for x in range(width):
for y in range(height):
canvas['grid'][(x,y)] = {'color':None, 'back_color':None, 'char':' '}
return canvas
|
b0ba6648eb47533e939321d107f64e1323e9a81d
| 77,720
|
def get_element_text(dom_element):
"""
Get the content of the element from it's text node (if one exists)
"""
return " ".join(t.nodeValue for t in dom_element.childNodes if t.nodeType == t.TEXT_NODE)
|
f7972accb717f543b1f5a49a3a4795db1bbf06a3
| 77,725
|
import re
def _strip_sql(sql: str) -> str:
"""Returns a copy of sql with empty lines and -- comments stripped.
Args:
sql: A SQL string.
Returns:
A copy of sql with empty lines and -- comments removed.
"""
lines = []
for line in sql.split('\n'):
line = re.sub(r'\s*--.*', '', line)
if line.strip():
lines.append(line)
return '\n'.join(lines)
|
e5f3ff9509133889e090337f9718280138e44549
| 77,726
|
def fasta_header(exp, N):
"""Generates random headers for the fasta file
Parameters
----------
exp : str
name of experiment (no spaces)
N : int
number of headers to be generated
Returns
-------
headers : list
names for each sequence (arbritrary)
"""
headers = [''.join(['>',exp,'_random_sequence_',str(i)]) for i,
x in enumerate(list(range(int(N))))]
return headers
|
e2a76a4509f524b6514e59d7a0154894b4311ad4
| 77,730
|
import torch
def sm_sim(q, M):
"""
q : D
M : M x D
returns : M
Computes the dot product, followed by softmax between vector q, and all vectors in M.
I.e. the distribution we aim to model using Noise Contrastive Estimation or Negative Sampling.
"""
return torch.softmax(M @ q, 0)
|
b1506381892ef6f5ee58ea2a4f1249ede18a7e12
| 77,731
|
def parse_user_prefix(prefix):
"""
Parses:
prefix = nickname [ [ "!" user ] "@" host ]
Returns:
triple (nick, user, host), user and host might be None
"""
user = None
host = None
nick = prefix
host_split = prefix.split('@', 1)
if len(host_split) == 2:
nick = host_split[0]
host = host_split[1]
user_split = nick.split('!', 1)
if len(user_split) == 2:
nick = user_split[0]
user = user_split[1]
return nick, user, host
|
b3f48eda6599dcc6d503937bae4de71c6e81098c
| 77,733
|
def calculate(not_to_exceed):
"""Returns the sum of the even-valued terms in the Fibonacci sequence
whose values do not exceed the specified number"""
answer = 0
term_one = 1
term_two = 2
while term_two < not_to_exceed:
if not term_two % 2:
answer += term_two
next_term = term_one + term_two
term_one = term_two
term_two = next_term
return answer
|
36f8dc57d25afb1dfa700b8cd391b03a80cd4e11
| 77,735
|
import decimal
def places(astring):
"""
Given a string representing a floating-point number,
return number of decimal places of precision (note: is negative).
"""
return decimal.Decimal(astring).as_tuple().exponent
|
7d613e2e36c407b8f62963aa8fe7bd83fa338dc1
| 77,736
|
def list_dictify(obj):
"""
Function for building a dictionary from all attributes that have values
"""
list_dict = {}
for attr, value in obj.__dict__.items():
if value:
list_dict[str(attr)] = value
return list_dict
|
7827043d3763b49556c10d73e9f6b9d758013be9
| 77,737
|
def get_row_name(element):
"""Row name getter"""
return getattr(element, '__name__', None)
|
91a16f6698f40c0faa2773f9895a3003d09feab5
| 77,740
|
def zero_matrix(matrix):
"""
Given an m x n matrix of 0s and 1s, if an element is 0,
set its entire row and column to 0.
Given a matrix A as input.
A = [[1, 0, 1],
[1, 1, 1],
[1, 1, 1]]
On returning the matrix A should have the rows and columns
containing the initial 0 all set to 0.
A = [[0, 0, 0],
[1, 0, 1],
[1, 0, 1]]
"""
m = len(matrix)
n = len(matrix[0])
# Space complexity is O(m) + O(n)
zero_columns = {}
zero_rows = {}
# Time complexity is O(m * n)
for y, row in enumerate(matrix):
for x, col in enumerate(row):
if col == 0:
zero_rows[y] = True
zero_columns[x] = True
for y in zero_rows.keys():
for x in range(0, n):
matrix[y][x] = 0
for x in zero_columns.keys():
for y in range(0, m):
matrix[y][x] = 0
return matrix
|
d5609381529f3eba5526f75a8aa12bebfb3865a4
| 77,741
|
def unipolar(signal):
"""
Inverse to bipolar().
Converts a bipolar signal to an unipolar signal.
"""
return signal * 0.5 + 0.5
|
b36f0245f367b63023b7ef39e6358b0bf1068b32
| 77,745
|
import re
def _StripTrailingDotZeroes(number):
"""Returns the string representation of number with trailing .0* deleted."""
return re.sub(r'\.0*$', '', str(float(number)))
|
0036f2a9bc5bc22a54a01fbfc236a48a2373e6a4
| 77,748
|
def clear_rightmost_set_bit(n):
"""Clear rightmost set bit of n and return it."""
return n & (n-1)
|
250e9bd42ec23d24443084fe7f603fdd7271692b
| 77,750
|
def latex_float(f, precision=0.2, delimiter=r'\times'):
""" Convert a float value into a pretty printable latex format
makes 1.3123e-11 transformed into $1.31 x 10 ^ {-11}$
Parameters
----------
f: float
value to convert
precision: float, optional (default: 0.2)
the precision will be used as the formatting: {precision}g
default=0.2g
delimiter: str, optional (default=r'\times')
delimiter between the value and the exponent part
"""
float_str = ("{0:" + str(precision) + "g}").format(f)
if "e" in float_str:
base, exponent = float_str.split("e")
return (r"{0}" + delimiter + "10^{{{1}}}").format(base, int(exponent))
else:
return float_str
|
b3d31afcfbf8a564d85f5f5b099b0d63bc8d89f8
| 77,753
|
def look_and_say_next(number: str='1') -> str:
"""Следующее число последовательности "Посмотри и скажи"
:param number: число последовательности, defaults to '1'
:type number: str, optional
:return: следующее за number число
:rtype: str
"""
k, last, result = 1, number[0], ''
for digit in number[1:]:
if last == digit:
k += 1
else:
result += str(k) + last
k = 1
last = digit
result += str(k) + last
return result
|
473faeacb78d7f65b745a7bab7caaaaf426e03f5
| 77,760
|
def get_type(props):
"""Given an arbitrary object from a jsdoc-emitted JSON file, go get the
``type`` property, and return the textual rendering of the type, possibly a
union like ``Foo | Bar``, or None if we don't know the type."""
names = props.get('type', {}).get('names', [])
return '|'.join(names) if names else None
|
d97dec6e9340ff977194dafe17b396c4318a2b60
| 77,763
|
import re
def find_screen_size(handle):
"""
Find the screen size of a previously written EDL file
Parameters
----------
handle : file-like object
EDL path to read screen size
Returns
-------
dimensions : tuple
Width and height of screen
Raises
------
ValueError:
Raised if no screen information is found
"""
#Compile overall screen regex match
tpl = re.compile(r'beginScreenProperties(?:.+)'
'w (\d+)\nh (\d+)'
'(?:.+)endScreenProperties',
flags=re.DOTALL)
#Search for screen properties in file
with handle as f:
props = tpl.search(f.read())
if not props:
raise ValueError("No screen dimension information "
"found within file")
return tuple(int(d) for d in props.groups())
|
3bbcc7325c5f2c8c49f8e9f23430fff5a4aa3169
| 77,766
|
def get_lib_extension(lib):
"""Return extension of the library
Takes extensions such as so.1.2.3 into account.
Args:
lib: The library File.
Returns:
String: extension of the library.
"""
n = lib.basename.find(".so.")
end = lib.extension if n == -1 else lib.basename[n + 1:]
return end
|
51252410843d279143b83f45baa008833d6868d6
| 77,775
|
import random
def randomize(x, y, length):
"""Randomize order of values in x & y"""
random_indices = list(range(length))
random.shuffle(random_indices)
x = x[random_indices]
y = y[random_indices]
return x, y
|
e9ba94bbe4d538b5862e3b709194541079ac8e03
| 77,776
|
from typing import Tuple
def get_input() -> Tuple[int, int]:
"""Returns N x M integer input for Designer Doormat.
Returns:
Tuple[int, int]: N x M, representing length & width.
"""
n, m = [int(x) for x in input().split()]
if n % 2 == 0:
raise Exception("Not odd!")
if m != 3* n:
raise Exception("M must be 3n!")
return n, m
|
c0a9166a0c61bbcb1a72966b7957556896340bc2
| 77,777
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.