content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def setToC(doc, toc, collapse=1):
"""Create new outline tree (table of contents, TOC).
Args:
toc: (list, tuple) each entry must contain level, title, page and
optionally top margin on the page. None or '()' remove the TOC.
collapse: (int) collapses entries beyond this level. Zero or... | 5,343,100 |
def test_card_update_rect():
"""
Called whenever the application size changes to ensure that the rectangle
that contains the screen to be drawn is also updated in size (so the
background colour / image is updated, if required).
"""
card = Card("title")
card.rect = mock.MagicMock()
instan... | 5,343,101 |
def _map_dvector_permutation(rd,d,eps):
"""Maps the basis vectors to a permutation.
Args:
rd (array-like): 2D array of the rotated basis vectors.
d (array-like): 2D array of the original basis vectors.
eps (float): Finite precision tolerance.
Returns:
RP (list): The perm... | 5,343,102 |
def get_vacsi_non_vacsi(name, column, statut, multi, filter = False, region = True):
"""Process each geozone for Rate type of KPIs with exception.
Specific function dedicated to vaccin_vaccines_couv
"""
indicateurResult = get_empty_kpi()
config = get_config(name)
log.debug('Processing - '+name... | 5,343,103 |
def dump_lightcurves_with_grcollect(photfileglob, lcdir, maxmemory,
objectidcol=3,
lcextension='grcollectilc',
observatory='tess'):
"""
Given a list of photometry files (text files at various times output... | 5,343,104 |
def main(): # pragma: no cover
"""Entrypoint invoked via a console script."""
try:
while True:
print(format_datetime())
sleep(1)
except KeyboardInterrupt:
pass | 5,343,105 |
def varPostV(self,name,value):
""" Moving all the data from entry to treeview """
regex = re.search("-[@_!#$%^&*()<>?/\|}{~: ]", name) #Prevent user from giving special character and space character
print(regex)
if not regex == None:
tk.messagebox.showerror("Forbidden Entry","The variable name f... | 5,343,106 |
def _mysql_int_length(subtype):
"""Determine smallest field that can hold data with given length."""
try:
length = int(subtype)
except ValueError:
raise ValueError(
'Invalid subtype for Integer column: {}'.format(subtype)
)
if length < 3:
kind = 'TINYINT'
... | 5,343,107 |
def get_ci(vals, percent=0.95):
"""Confidence interval for `vals` from the Students' t
distribution. Uses `stats.t.interval`.
Parameters
----------
percent : float
Size of the confidence interval. The default is 0.95. The only
requirement is that this be above 0 and at or below 1.
... | 5,343,108 |
def kb_overview_rows(mode=None, max=None, locale=None, product=None, category=None):
"""Return the iterable of dicts needed to draw the new KB dashboard
overview"""
if mode is None:
mode = LAST_30_DAYS
docs = Document.objects.filter(locale=settings.WIKI_DEFAULT_LANGUAGE,
... | 5,343,109 |
def test_query_devicecontrolalert_facets(monkeypatch):
"""Test a Device Control alert facet query."""
_was_called = False
def _run_facet_query(url, body, **kwargs):
nonlocal _was_called
assert url == "/appservices/v6/orgs/Z100/alerts/devicecontrol/_facet"
assert body == {"query": "B... | 5,343,110 |
def plot_logs(experiments: List[Summary],
smooth_factor: float = 0,
ignore_metrics: Optional[Set[str]] = None,
pretty_names: bool = False,
include_metrics: Optional[Set[str]] = None) -> Figure:
"""A function which will plot experiment histories for comparison ... | 5,343,111 |
def regularity(sequence):
"""
Compute the regularity of a sequence.
The regularity basically measures what percentage of a user's
visits are to a previously visited place.
Parameters
----------
sequence : list
A list of symbols.
Returns
-------
float
1 minus th... | 5,343,112 |
def _make_tick_labels(
tick_values: List[float], axis_subtractor: float, tick_divisor_power: int,
) -> List[str]:
"""Given a collection of ticks, return a formatted version.
Args:
tick_values (List[float]): The ticks positions in ascending
order.
tick_divisor_power (int): The po... | 5,343,113 |
def load_coco(dataset_file, map_file):
"""
Load preprocessed MSCOCO 2017 dataset
"""
print('\nLoading dataset...')
h5f = h5py.File(dataset_file, 'r')
x = h5f['x'][:]
y = h5f['y'][:]
h5f.close()
split = int(x.shape[0] * 0.8) # 80% of data is assigned to the training set
x_train,... | 5,343,114 |
def eval_rule(call_fn, abstract_eval_fn, *args, **kwargs):
"""
Python Evaluation rule for a numba4jax function respecting the
XLA CustomCall interface.
Evaluates `outs = abstract_eval_fn(*args)` to compute the output shape
and preallocate them, then executes `call_fn(*outs, *args)` which is
the... | 5,343,115 |
def bev_box_overlap(boxes, qboxes, criterion=-1):
"""
Calculate rotated 2D iou.
Args:
boxes:
qboxes:
criterion:
Returns:
"""
riou = rotate_iou_gpu_eval(boxes, qboxes, criterion)
return riou | 5,343,116 |
def filter_shape(image):
"""画像にぼかしフィルターを適用。"""
weight = (
(1, 1, 1),
(1, 1, 1),
(1, 1, 1)
)
offset = 0
div = 9
return _filter(image, weight, offset, div) | 5,343,117 |
def ppretty(obj, indent=' ', depth=4, width=72, seq_length=5,
show_protected=False, show_private=False, show_static=False, show_properties=False, show_address=False,
str_length=50):
"""Represents any python object in a human readable format.
:param obj: An object to represent.
... | 5,343,118 |
def traj_colormap(ax, traj, array, plot_mode, min_map, max_map, title=""):
"""
color map a path/trajectory in xyz coordinates according to
an array of values
:param ax: plot axis
:param traj: trajectory.PosePath3D or trajectory.PoseTrajectory3D object
:param array: Nx1 array of values used for c... | 5,343,119 |
def dict2pkl(mydict, path):
"""
Saves a dictionary object into a pkl file.
:param mydict: dictionary to save in a file
:param path: path where my_dict is stored
:return:
"""
import cPickle
if path[-4:] == '.pkl':
extension = ''
else:
extension = '.pkl'
with open(p... | 5,343,120 |
def makeTriangularMAFdist(low=0.02, high=0.5, beta=5):
"""Fake a non-uniform maf distribution to make the data
more interesting - more rare alleles """
MAFdistribution = []
for i in xrange(int(100*low),int(100*high)+1):
freq = (51 - i)/100.0 # large numbers of small allele freqs
for ... | 5,343,121 |
def export_inference_graph(
config_path: str,
trained_ckpt_dir: str,
input_type: str,
output_dir: str,
config_override: Optional[pipeline_pb2.TrainEvalPipelineConfig] = None,
use_side_inputs: bool = False,
side_input_shapes: str = '',
side_input_types: str... | 5,343,122 |
def create_structures_hdf5_stitched_ref_gene_file_npy(stitching_file, joining, nr_pixels,
reference_gene, blend = 'non linear'):
"""Takes an HDF5 file handle and creates the necessary structures.
Modification of create_structures_hdf5_files to work with .npy list of
files
... | 5,343,123 |
def contains_whitespace(s : str):
"""
Returns True if any whitespace chars in input string.
"""
return " " in s or "\t" in s | 5,343,124 |
def get_files_to_check(files, filter_function):
# type: (List[str], Callable[[str], bool]) -> List[str]
"""Get a list of files that need to be checked based on which files are managed by git."""
# Get a list of candidate_files
candidates_nested = [expand_file_string(f) for f in files]
candidates = l... | 5,343,125 |
def main(argv):
"""Parse the argv, verify the args, and call the runner."""
args = arg_parse(argv)
return run(args.top_foods, args.top_food_categories) | 5,343,126 |
def _failover_read_request(request_fn, endpoint, path, body, headers, params, timeout):
""" This function auto-retries read-only requests until they return a 2xx status code. """
try:
return request_fn('GET', endpoint, path, body, headers, params, timeout)
except (requests.exceptions.RequestException, Non200R... | 5,343,127 |
def update_image_viewer_state(rec, context):
"""
Given viewer session information, make sure the session information is
compatible with the current version of the viewers, and if not, update
the session information in-place.
"""
if '_protocol' not in rec:
# Note that files saved with p... | 5,343,128 |
def test_block_legacy_send_from_dict():
"""
When deserializing a legacy send block, the balance has to be hex-formatted
"""
block_data = BLOCKS["send"]["data"].copy()
block_data["balance"] = "10000000"
with pytest.raises(InvalidBalance) as exc:
Block.from_dict(block_data)
assert "n... | 5,343,129 |
def GenerateConfig(context):
"""Generates configuration."""
image = ''.join(['https://www.googleapis.com/compute/v1/',
'projects/google-containers/global/images/',
context.properties['containerImage']])
default_network = ''.join(['https://www.googleapis.com/compute/v1/projec... | 5,343,130 |
async def read_all_orders(
status_order: Optional[str] = None,
priority: Optional[int] = None,
age: Optional[str] = None,
value: Optional[str] = None,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
db: AsyncIOMotorClient = Depends(get_database),
) -> List[OrderSchema]:
... | 5,343,131 |
def read_log_file(path):
"""
Read the log file for 3D Match's log files
"""
with open(path, "r") as f:
log_lines = f.readlines()
log_lines = [line.strip() for line in log_lines]
num_logs = len(log_lines) // 5
transforms = []
for i in range(0, num_logs, 5):
meta_data... | 5,343,132 |
def visualize_OOP_and_F_timeseries(OOP_list,J_list,folder_name):
"""Plot timeseries."""
external_folder_name = 'ALL_MOVIES_PROCESSED'
out_analysis = external_folder_name + '/' + folder_name + '/analysis'
plt.figure()
plt.subplot(1,2,1)
plt.plot(OOP_list)
plt.xlabel('frame number')
plt.ylabel('OOP')
plt.tight_l... | 5,343,133 |
def divide_list(l, n):
"""Divides list l into n successive chunks."""
length = len(l)
chunk_size = int(math.ceil(length/n))
expected_length = n * chunk_size
chunks = []
for i in range(0, expected_length, chunk_size):
chunks.append(l[i:i+chunk_size])
for i in range(len(chunks), n):... | 5,343,134 |
def sigma(n):
"""Calculate the sum of all divisors of N."""
return sum(divisors(n)) | 5,343,135 |
def ATOMPAIRSfpDataFrame(chempandas,namecol,smicol):
"""
AtomPairs-based fingerprints 2048 bits.
"""
assert chempandas.shape[0] <= MAXLINES
molsmitmp = [Chem.MolFromSmiles(x) for x in chempandas.iloc[:,smicol]]
i = 0
molsmi = []
for x in molsmitmp:
if x is not None:
x... | 5,343,136 |
def test_backend_get_set_pin_mode() -> None:
"""Test that we can get and set pin modes."""
pin = 2
backend = SBArduinoHardwareBackend("COM0", SBArduinoSerial)
assert backend.get_gpio_pin_mode(pin) is GPIOPinMode.DIGITAL_INPUT
backend.set_gpio_pin_mode(pin, GPIOPinMode.DIGITAL_OUTPUT)
assert back... | 5,343,137 |
def filter_by_minimum(X, region):
"""Filter synapses by minimum.
# Arguments:
X (numpy array): A matrix in the NeuroSynapsis matrix format.
# Returns:
numpy array: A matrix in the NeuroSynapsis matrix format.
"""
vals = np.where((X[:,2] >= i[0])*(X[:,3] >= i[1])*(X[:,4]... | 5,343,138 |
def gen_graphs(sizes):
"""
Generate community graphs.
"""
A = []
for V in tqdm(sizes):
G = nx.barabasi_albert_graph(V, 3)
G = nx.to_numpy_array(G)
P = np.eye(V)
np.random.shuffle(P)
A.append(P.T @ G @ P)
return np.array(A) | 5,343,139 |
def daemonize(identity: str, kind: str = 'workspace') -> DaemonID:
"""Convert to DaemonID
:param identity: uuid or DaemonID
:param kind: defaults to 'workspace'
:return: DaemonID from identity
"""
try:
return DaemonID(identity)
except TypeError:
return DaemonID(f'j{kind}-{id... | 5,343,140 |
def count_gender(data_list:list):
"""
Contar a população dos gêneros
args:
data_list (list): Lista de dados que possui a propriedade 'Gender'
return (list): Retorna uma lista com o total de elementos do gênero 'Male' e 'Female', nessa ordem
"""
genders = column... | 5,343,141 |
async def card_balance(request: Request):
""" 返回用户校园卡余额 """
cookies = await get_cookies(request)
balance_data = await balance.balance(cookies)
return success(data=balance_data) | 5,343,142 |
def _grid_vals(grid, dist_name, scn_save_fs,
mod_thy_info, constraint_dct):
""" efef
"""
# Initialize the lists
locs_lst = []
enes_lst = []
# Build the lists of all the locs for the grid
grid_locs = []
for grid_val_i in grid:
if constraint_dct is None:
... | 5,343,143 |
def group_images_by_label(label_arr, gid_arr):
"""
Input: Length N list of labels and ids
Output: Length M list of unique labels, and lenth M list of lists of ids
"""
# Reverse the image to cluster index mapping
import vtool as vt
labels_, groupxs_ = vt.group_indices(label_arr)
sortx = n... | 5,343,144 |
def ask_user(prompt: str, default: str = None) -> Optional[str]:
"""
Prompts the user, with a default. Returns user input from ``stdin``.
"""
if default is None:
prompt += ": "
else:
prompt += " [" + default + "]: "
result = input(prompt)
return result if len(result) > 0 else... | 5,343,145 |
def fetch_lords_mocks_data():
"""Fetch mocks data for unit tests of Lords."""
# Download Lords
l = lords.fetch_lords_raw()
validate.write(l, 'lords_raw')
time.sleep(constants.API_PAUSE_TIME)
# Download Lords memberships
l_cm = lords.fetch_lords_memberships_raw()
validate.write(l_cm, '... | 5,343,146 |
def tensor_index_by_tuple(data, tuple_index):
"""Tensor getitem by tuple of various types with None"""
if not tuple_index:
return data
op_name = const_utils.TENSOR_GETITEM
tuple_index = _transform_ellipsis_to_slice(data, tuple_index, op_name)
data, tuple_index = _expand_data_dims(data, tupl... | 5,343,147 |
def extract_text(savelocation, file):
"""Splits text into seperate files starting from 1. to the next 1.
Args:
savelocation (string): directory to where it should extract files to
file (string): file you want to extra files FROM
"""
# If the save location doesn't exist, we create... | 5,343,148 |
def are_neurons_responsive(spike_times, spike_clusters, stimulus_intervals=None,
spontaneous_period=None, p_value_threshold=.05):
"""
Return which neurons are responsive after specific stimulus events, compared to spontaneous
activity, according to a Wilcoxon test.
:param... | 5,343,149 |
def _get_book(**keywords):
"""Get an instance of :class:`Book` from an excel source
Where the dictionary should have text as keys and two dimensional
array as values.
"""
source = factory.get_book_source(**keywords)
sheets = source.get_data()
filename, path = source.get_source_info()
re... | 5,343,150 |
def handler(
state_store: StateStore,
hardware_api: HardwareAPI,
movement_handler: MovementHandler,
) -> PipettingHandler:
"""Create a PipettingHandler with its dependencies mocked out."""
return PipettingHandler(
state_store=state_store,
hardware_api=hardware_api,
movement_h... | 5,343,151 |
def get_domain(domain_name):
"""
Query the Rackspace DNS API to get a domain object for the domain name.
Keyword arguments:
domain_name -- the domain name that needs a challenge record
"""
base_domain_name = get_tld("http://{0}".format(domain_name))
domain = rax_dns.find(name=base_domain_na... | 5,343,152 |
def lobatto(n):
"""Get Gauss-Lobatto-Legendre points and weights.
Parameters
----------
n : int
Number of points
"""
if n == 2:
return ([0, 1],
[sympy.Rational(1, 2), sympy.Rational(1, 2)])
if n == 3:
return ([0, sympy.Rational(1, 2), 1],
... | 5,343,153 |
def login():
"""Login."""
username = request.form.get('username')
password = request.form.get('password')
if not username:
flask.flash('Username is required.', 'warning')
elif password is None:
flask.flash('Password is required.', 'warning')
else:
user = models.User.login_user(username, password... | 5,343,154 |
def comp_periodicity(self, p=None):
"""Compute the periodicity factor of the lamination
Parameters
----------
self : LamSlotMulti
A LamSlotMulti object
Returns
-------
per_a : int
Number of spatial periodicities of the lamination
is_antiper_a : bool
True if an s... | 5,343,155 |
def tagger(c):
"""
Find usage value or AWS Tags.
Using a json input to stdin we gather enough data to be able to specify the
usage of some resources.
"""
p_log("Task: Tagger")
params = {}
lines = [x.strip() for x in sys.stdin.readlines()]
lines = list(filter(None, lines))
if le... | 5,343,156 |
def sha2_384(data: bytes) -> hashes.MessageDigest:
"""
Convenience function to hash a message.
"""
return HashlibHash.hash(hashes.sha2_384(), data) | 5,343,157 |
def cat(arr, match="CAT", upper_bound=None, lower_bound=None):
"""
Basic idea is if a monkey typed randomly, how long would it take for it
to write `CAT`. Practically, we are mapping generated numbers onto the
alphabet.
>"There are 26**3 = 17 576 possible 3-letter words, so the average number of
... | 5,343,158 |
def encrypt_data(key: bytes, data: str) -> str:
"""
Encrypt the data
:param key: key to encrypt the data
:param data: data to be encrypted
:returns: bytes encrypted
"""
# instance class
cipher_suite = Fernet(key)
# convert our data into bytes mode
data_to_bytes = bytes(data, "ut... | 5,343,159 |
def make_doi_table(dataset: ObservatoryDataset) -> List[Dict]:
"""Generate the DOI table from an ObservatoryDataset instance.
:param dataset: the Observatory Dataset.
:return: table rows.
"""
records = []
for paper in dataset.papers:
# Doi, events and grids
doi = paper.doi.uppe... | 5,343,160 |
def do_volume_connector_list(cc, args):
"""List the volume connectors."""
params = {}
if args.node is not None:
params['node'] = args.node
if args.detail:
fields = res_fields.VOLUME_CONNECTOR_DETAILED_RESOURCE.fields
field_labels = res_fields.VOLUME_CONNECTOR_DETAILED_RESOURCE.... | 5,343,161 |
def get_output_file_path(file_path: str) -> str:
"""
get the output file's path
:param file_path: the file path
:return: the output file's path
"""
split_file_path: List[str] = list(os.path.splitext(file_path))
return f'{split_file_path[0]}_sorted{split_file_path[1]}' | 5,343,162 |
def test_custom_grain_with_annotations(grains_dir):
"""
Load custom grain with annotations.
"""
opts = salt.config.DEFAULT_MINION_OPTS.copy()
opts["grains_dirs"] = [grains_dir]
grains = salt.loader.grains(opts, force_refresh=True)
assert grains.get("example") == "42" | 5,343,163 |
def test_relative_and_other_root_dirs(offline, request):
"""Test styles in relative and in other root dirs."""
another_dir = TEMP_ROOT_PATH / "another_dir" # type: Path
project = (
ProjectMock(request)
.named_style(
"{}/main".format(another_dir),
"""
[nit... | 5,343,164 |
def binarySearch(arr, val):
"""
array values must be sorted
"""
left = 0
right = len(arr) - 1
half = (left + right) // 2
while arr[half] != val:
if val < arr[half]:
right = half - 1
else:
left = half + 1
half = (left + right) // 2
if arr[ha... | 5,343,165 |
def foreign_key(
recipe: Union[Recipe[M], str], one_to_one: bool = False
) -> RecipeForeignKey[M]:
"""Return a `RecipeForeignKey`.
Return the callable, so that the associated `_model` will not be created
during the recipe definition.
This resolves recipes supplied as strings from other module path... | 5,343,166 |
def posterize(image, num_bits):
"""Equivalent of PIL Posterize."""
shift = 8 - num_bits
return tf.bitwise.left_shift(tf.bitwise.right_shift(image, shift), shift) | 5,343,167 |
def cli(
from_proj: str,
from_x_column: str,
from_y_column: str,
from_x_format: str,
from_y_format: str,
to_proj: str,
to_x_header: str,
to_y_header: str,
input_filename: str,
output_filename: str
):
"""Reproject a CSV from one Coordina... | 5,343,168 |
def validate_targetRegionBedFile_for_runType(
value,
field_label,
runType,
reference,
nucleotideType=None,
applicationGroupName=None,
isPrimaryTargetRegion=True,
barcodeId="",
runType_label=ugettext_lazy("workflow.step.application.fields.runType.label"),
):
"""
validate targe... | 5,343,169 |
def run_find_markers(
input_h5ad_file: str,
output_file: str,
label_attr: str,
de_key: str = "de_res",
n_jobs: int = -1,
min_gain: float = 1.0,
random_state: int = 0,
remove_ribo: bool = False,
) -> None:
"""
For command line use.
"""
import xlsxwriter
from natsort im... | 5,343,170 |
def polyFit(x, y):
"""
Function to fit a straight line to data and estimate slope and
intercept of the line and corresponding errors using first order
polynomial fitting.
Parameters
----------
x : ndarray
X-axis data
y : ndarray
Y-axis data
Return... | 5,343,171 |
def test_delete_no_pk():
"""Validate a delete returning a pkdict without specifying the primary key."""
_logger.debug(stack()[0][3])
config = deepcopy(_CONFIG)
t = table(config)
returning = t.delete('{id}={target}', {'target': 7},
('uid',), container='pkdict')
row = t.se... | 5,343,172 |
def stability_test_standard(
umbrella: Path,
outdir: Path | None = None,
tests: str | list[str] = "all",
) -> None:
"""Perform a battery of standard stability tests.
This function expects a rigid `umbrella` directory structure,
based on the output of results that are generated by rexpy_.
.... | 5,343,173 |
def evaluate_error(X, y, w):
"""Returns the mean squared error.
X : numpy.ndarray
Numpy array of data.
y : numpy.ndarray
Numpy array of outputs. Dimensions are n * 1, where n is the number of
rows in `X`.
w : numpy.ndarray
Numpy array with dimensions (m + 1) * 1, where m... | 5,343,174 |
def call_later(fn, args=(), delay=0.001):
"""
Calls the provided function in a new thread after waiting some time.
Useful for giving the system some time to process an event, without blocking
the current execution flow.
"""
thread = _Thread(target=lambda: (_time.sleep(delay), fn(*args)))
thr... | 5,343,175 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up ha_reef_pi from a config entry."""
websession = async_get_clientsession(hass)
coordinator = ReefPiDataUpdateCoordinator(hass, websession, entry)
await coordinator.async_config_entry_first_refresh()
if not coor... | 5,343,176 |
def get_list(client):
"""
"""
request = client.__getattr__(MODULE).ListIpBlocks()
response, _ = request.result()
return response['results'] | 5,343,177 |
def g(z: Set[str]):
""" Test set default """
print(z) | 5,343,178 |
def file_asset(class_obj):
"""
Decorator to annotate the FileAsset class. Registers the decorated class
as the FileAsset known type.
"""
assert isinstance(class_obj, six.class_types), "class_obj is not a Class"
global _file_asset_resource_type
_file_asset_resource_type = class_obj
return... | 5,343,179 |
def main(username: str, output: str, file_format: str, token: str) -> None:
"""A Python CLI to backup all your GitHub repositories."""
# More info:
# - https://ghapi.fast.ai/core.html#GhApi
# - https://ghapi.fast.ai/core.html#Operations
# (if don't pass the token parameter, then your GITHUB_TOKEN en... | 5,343,180 |
def get_bam_list(args):
"""
Retrieve bam list from given tumor bam directory
"""
bamList = []
for bam in glob.glob(os.path.join(args.tumor_bams_directory, "*.bam")):
# Todo: CMO bams don't always end in 'T'
# if os.path.basename(bam).split('_')[0].split('-')[-1].startswith('T'):
... | 5,343,181 |
def test_init_raw():
"""
tests whether the ADPBulk object can be instantiated correctly
"""
adat = build_adat()
# tests singular group conditions
for group in adat.obs.columns:
_ = ADPBulk(adat, groupby=group, use_raw=True)
# tests multiple group conditions
_ = ADPBulk(adat, gr... | 5,343,182 |
def run_time_it():
"""Trigger timeit"""
dynamicArray(n, queries) | 5,343,183 |
def scheming_field_by_name(fields, name):
"""
Simple helper to grab a field from a schema field list
based on the field name passed. Returns None when not found.
"""
for f in fields:
if f.get('field_name') == name:
return f | 5,343,184 |
def saveResult(img_file, img, boxes, dirname='./result/', verticals=None, texts=None):
""" save text detection result one by one
Args:
img_file (str): image file name
img (array): raw image context
boxes (array): array of result file
Shape: [num_detect... | 5,343,185 |
def merge_sort(items):
"""Sorts a list of items.
Uses merge sort to sort the list items.
Args:
items: A list of items.
Returns:
The sorted list of items.
"""
n = len(items)
if n < 2:
return items
m = n // 2
left = merge_sort(items[:m])
right = mer... | 5,343,186 |
def sshkey_generate(private, public, path):
"""Génération de clé privée , public ssh"""
try:
from Crypto.PublicKey import RSA
key = RSA.generate(2048)
public_key = key.publickey()
enc_data = public_key.encrypt("""admin-manager-hash""", 32)
x = key.decrypt(enc_data)
x = x.deco... | 5,343,187 |
def hunk_boundary(
hunk: HunkInfo, operation_type: Optional[str] = None
) -> Optional[HunkBoundary]:
"""
Calculates boundary for the given hunk, returning a tuple of the form:
(<line number of boundary start>, <line number of boundary end>)
If operation_type is provided, it is used to filter down o... | 5,343,188 |
def get_activities_list(log, parameters=None):
"""
Gets the activities list from a log object, sorted by activity name
Parameters
--------------
log
Log
parameters
Possible parameters of the algorithm
Returns
-------------
activities_list
List of activities ... | 5,343,189 |
def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob,
source_vocab_size,
encoding_embedding_size):
"""
:return: tuple (RNN output, RNN state)
"""
embed = tf.contrib.layers.embed_sequence(rnn_inputs,
vocab_size=s... | 5,343,190 |
def point_selection(start, end, faces):
""" Calculates the intersection points between a line segment and triangle mesh.
:param start: line segment start point
:type start: Vector3
:param end: line segment end point
:type end: Vector3
:param faces: faces: N x 9 array of triangular face vertices... | 5,343,191 |
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar, and the first date is not after
the second."""
month = month2
year = year2
day = day2 ... | 5,343,192 |
def derive_sender_1pu(epk, sender_sk, recip_pk, alg, apu, apv, keydatalen):
"""Generate two shared secrets (ze, zs)."""
ze = derive_shared_secret(epk, recip_pk)
zs = derive_shared_secret(sender_sk, recip_pk)
key = derive_1pu(ze, zs, alg, apu, apv, keydatalen)
return key | 5,343,193 |
def collapse(board_u):
"""
takes a row/column of the board
and collapses it to the left
"""
i = 1
limit = 0
while i < 4:
if board_u[i]==0:
i += 1
continue
up_index = i-1
curr_index = i
while up_index>=0 and board_u[up_index]==0:
... | 5,343,194 |
def find_match_in_file(search_term, file_location):
"""
This function is used to query a file
search_term = Term to find
file_location = Location of file to query.
"""
try:
with open(file_location) as line:
for search in line:
result = re.match(search_term,... | 5,343,195 |
def write_long(encoder, datum, schema, named_schemas, fname):
"""int and long values are written using variable-length, zig-zag coding."""
encoder.write_long(datum) | 5,343,196 |
def get_cost_function(cost_function_name: str):
"""
Given the name of a cost function, retrieve the corresponding function and its partial derivative wrt Y_circ
:param cost_function_name: the name of the cost function
:return: the corresponding cost function and its partial derivative wrt Y_circ
"""... | 5,343,197 |
def create_C1(data_set):
"""
Create frequent candidate 1-itemset C1 by scaning data set.
Args:
data_set: A list of transactions. Each transaction contains several items.
Returns:
C1: A set which contains all frequent candidate 1-itemsets
"""
C1 = set()
for t in data_set:
... | 5,343,198 |
def timezone(name):
"""
Loads a Timezone instance by name.
:param name: The name of the timezone.
:type name: str or int
:rtype: Timezone
"""
return Timezone.load(name) | 5,343,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.