content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def lower(input_string: str) -> str:
"""Convert the complete string to lowercase."""
return input_string.lower() | 1ad7c0da84dbe926e5d21aa67d8cf6eee43ba268 | 72,603 |
def generate_comment(stored_location, comment_body):
"""
Purpose of file is to produce a JSON object for an comment.
Pulled JSON object from Jama SwaggeUI instance on creating an comment.
@params:
stored_location: The item id which should be comment
comment_body -> The contain of the com... | 8efba2c0d43e5e0af7ef0db67e8a1863bed8fbba | 72,605 |
def CFMtom3sec(VCFM):
"""
Convertie le debit volumique en CFM vers m3/sec
Conversion: 2118.8799727597 CFM = 1 m3/sec
:param VCFM: Debit volumique [CFM]
:return Vm3sec: Debit volumique [m3/sec]
"""
Vm3sec = VCFM / 2118.8799727597
return Vm3sec | bc5212a5dbc4036b03359ac53411657dbe862ad0 | 72,606 |
def isiterable(it):
"""Return True if 'it' is iterable else return False."""
try:
iter(it)
except:
return False
else:
return True | 62ab293bdef239fd404c63ce29ed6a78e883381a | 72,608 |
from typing import Iterable
def humanize_list(iterable: Iterable[str]) -> str:
"""Return a grammatically correct English phrase of a list of items.
Parameters
----------
iterable : iterable of str
Any list of items.
Returns
-------
phrase : str
A grammatically correct way... | a8b10c7d1c15ca415ef4215160d4f26b25a57167 | 72,611 |
def pairFR(L):
"""In : L (list of states)
Out: List of pairs with L[0] paired with each state in L[1:],
with the distinguishability distance initialized to -1.
Helper for generating state_combos.
"""
return list(map(lambda x: ((L[0], x), -1), L[1:])) | 8e6ed142a1fcf48f01cb1b50b0516580a36fac07 | 72,615 |
import collections
def align (crabs, cost):
"""Aligns the crab positions `crabs` (array) to the same position using
the least fuel, according to the given `cost` function. The `cost`
function takes a single parameter, the number of steps to move,
i.e. `cost(steps)`.
Returns `(pos, fuel)`.
""... | 577bacf52cac36155a372fca139040ba1d96e1a7 | 72,616 |
def str_to_bool(param):
"""Check if a string value should be evaluated as True or False."""
if isinstance(param, bool):
return param
return param.lower() in ("true", "yes", "1") | 1e8f3d8da23b1a6de1055788b48012c24fbe55a6 | 72,624 |
def extract_keyword(key, dict, default=None, conv=None):
"""Extracts an attribute from a dictionary.
KEY is the attribute name to look up in DICT. If KEY is missing
or cannot be converted, then DEFAULT is returned, otherwise the
converted value is returned. CONV is the conversion function.
"""
... | 60ed8323f36bb02dd046284cd0ca3b7904161e37 | 72,626 |
def prune_resort_key(scene):
"""
Used by prune_scenerios to extract the original ordering key for sorting.
"""
return scene[1]['_order'] | 2e566af3f6bb06a3c8caccbba5e6f16114eafc8a | 72,631 |
import requests
def error_parser(resp_err: requests.Response, api: str = 'graph') -> str:
"""
Parses Microsoft API error message from Requests response
:param resp_err: response with error
:param api: API to query (graph/bot)
:return: string of error
"""
try:
response: dict = resp_... | 23fbe9605fe8c19d1d11a8a3c3f81bf3ba734c31 | 72,633 |
def dict_print(d):
"""convert a dictionary to a string that can be print nicely
Args:
d (dictionary): the dictionary to be printed
"""
def listToString(s):
str1 = " "
return str1.join(s)
s = []
counter = 0
for key, value in d.items():
counter += 1
i... | 451cd58aa8722fcace2524093fe18ba6153753d9 | 72,634 |
import typing
import inspect
def repr_callable(callable: typing.Callable) -> str:
"""
Build a string representation of a callable, including the callable's
:attr:``__name__``, its :class:`inspect.Parameter`s and its ``return type``
usage::
>>> repr_callable(repr_callable)
'repr_calla... | 188b53b54c15868e7c00dac43dd6f96cf107f791 | 72,635 |
def format_collapse(ttype, dims):
"""
Given a type and a tuple of dimensions, return a struct of
[[[ttype, dims[-1]], dims[-2]], ...]
>>> format_collapse(int, (1, 2, 3))
[[[<class 'int'>, 3], 2], 1]
"""
if len(dims) == 1:
return [ttype, dims[0]]
else:
return format_colla... | 4d30356db721b6a63caed5a4594f9b56ca769488 | 72,640 |
def first_index(target, it):
"""The first index in `it` where `target` appears; -1 if it is missing."""
for idx, elt in enumerate(it):
if elt == target:
return idx
return -1 | cb1ece5a42bcde85afe79c10b587695c2e9dd815 | 72,642 |
def nfiles_str(nfiles: int) -> str:
"""Format `n files`."""
if nfiles == 0:
return "no files"
elif nfiles == 1:
return "1 file"
else:
return f"{nfiles} files" | cc55bcfc37d6c5c1deff08d285b2af3daa9f00ad | 72,646 |
def serialize(model, callbacks=None, datasets=None, dump_weights=True, keep_states=True):
"""
Serialize the model, callbacks and datasets.
Arguments:
model (Model): Model object
callbacks (Callbacks, optional): Callbacks
datasets (iterable, optional): Datasets
dump_weights (... | aa003f5c537659ee8febe90754a0ee0dd973490a | 72,650 |
def count_vowels(phrase: str) -> int:
"""Count the number of vowels in the phrase.
:param phrase: text to be examined
:return: number of vowels in phrase
"""
return len([x for x in phrase.lower() if x in 'aeiou']) | 0f099819dfa242f52ad560b88b280f9d3c38292b | 72,653 |
import torch
def box_denormalize(boxes, img_h, img_w):
"""
Denormalizes bounding box with coordinates between 0 and 1 to have coordinates in original image height and width.
Bounding boxes are expected to have format [x0, y0, x1, y1] or [x0, y0, w, h] or [x_center, y_center, w, h].
:param boxes: List... | 54cc710b530846db7c216dea38a6dc66e31cf3d0 | 72,654 |
def lorentz_factor(v):
"""Returns the lorentz factor for velocity v."""
return (1 - v**2)**(-1/2) | 37907b7af90a0162b95ecda9a138c2e85393761b | 72,662 |
def build_results_dict(tournament_results):
"""
builds results. Returns an object of the following form:
{
team-1: {
matches_played: int,
wins: int,
draws: int,
losses: int,
points: int,
}
team-2: {
...
}... | a10b4eda003745c8dfe726a718eb47a98d2c9d10 | 72,664 |
from datetime import datetime
def has_no_date(at):
"""Returns True if the given object is an ``adatetime`` where ``year``,
``month``, and ``day`` are all None.
"""
if isinstance(at, datetime):
return False
return at.year is None and at.month is None and at.day is None | 299300540ff228740e8e76200a91fe035f2a70f8 | 72,665 |
def halve(x: float):
"""Divide a number by 2"""
return x / 2 | acc35096f989b9738055ced9f4e191701b121728 | 72,666 |
def _create_ad_text_asset(client, text):
"""Creates an ad text asset with the given text value.
Args:
client: an initialized GoogleAdsClient instance.
text: a str for the text value of the ad text asset.
Returns:
an ad text asset.
"""
ad_text_asset = client.get_type("AdText... | fbc140ba86bbad3019370bd05ce19d4cde3238bb | 72,667 |
def check_standard(graph, first, second):
"""
Standard rewiring conditions as in original theory.
"""
# curiously the conditions for switching unidirectional and bidirectional
# links are the same for just slightly different reasons
if first == second:
return False
# prevent creation... | d5042db33abb874aca68663dcb40caaff05781a9 | 72,676 |
def decorateTitle(title, options):
""" Add a marker to TITLE if the TITLE is sorted on.
"""
if title.lower() == options.sortCategory:
return "%s*" % title
else:
return title | 7a0c3842375fe2a0c2b26d231e9735d91d4718b2 | 72,678 |
from typing import Dict
from typing import Any
import time
def process_work(worker: int, carrier: Dict[str, Any]) -> int:
"""Do child process's work."""
print(carrier)
time.sleep(1)
return worker | c3eeab0b3969bf6d674468e85386a29d45648259 | 72,685 |
def latexify(string_item):
"""Recursive function to turn a string, or sympy.latex to a
latex equation.
Args:
string_item (str): string we want to make into an equation
Returns:
equation_item (str): a latex-able equation.
"""
if isinstance(string_item, list):
return "\n"... | 2f0efbbbb2e627904eabb7a0ec56d3109950e8a3 | 72,690 |
from typing import Tuple
import logging
async def get_current_turn(queue_array: list) -> Tuple[int, str, int]:
"""Get the person whose turn it is to do the chore in a queue.
Returns
-------
Tuple[int, str, int]
A tuple of form: (user_id, user_name, index_position)
"""
for index, membe... | 4b28c820a858d65b967be78f7e2377622e5afec3 | 72,692 |
def get_piece(x, y, board):
"""
Utility function that gets the piece at a given (x,y) coordinate on the given board
Returns the piece if the request was valid and None if the request was not valid
Arg x: integer - x coordinate
Arg y: integer - y coordinate
Arg board: board - the board you wish t... | 821c7ec20e88419810533de19e8382c9865edcf2 | 72,699 |
def to_string(node_chain):
"""
Purpose:
Create a string representation of the node chain. E.g.,
[ 1 | *-]-->[ 2 | *-]-->[ 3 | / ]
Pre-conditions:
:param node_chain: A node-chain, possibly empty (None)
Post_conditions:
None
Return: A string representation of the node... | e3a756465c12444e11eeaa10cf95e099fe22ceac | 72,700 |
def minutes(time):
"""Convert a race time into minutes
given a time in the format hh:mm:ss, return the number of minutes"""
parts = [int(x) for x in time.split(':')]
return parts[0] * 60 + parts[1] + parts[2]/60. | e5193638223d01b5fae4c2d2d0f7f3f33100f1d0 | 72,702 |
def get_photo_path(instance, filename):
"""Define the upload path for saving the current user's photo to disk."""
user_slug = "{}{}".format(
instance.user.username,
instance.user.id
)
upload_path = "photos/{}/{}".format(user_slug, filename)
return upload_path | 685790494d1c5bf1a0b15a0b8f3d9ace4f981c5d | 72,705 |
import io
def image_to_bytes(image):
"""
Converts PIL image to bytes
:param image: PIL.Image
:return: bytes
"""
bytes_buffer = io.BytesIO()
image.save(bytes_buffer, format='PNG')
return bytes_buffer.getvalue() | b142fa512b3e7b7719772553b79eee01b33f40d1 | 72,706 |
def num_set_bits(mask):
"""Return a count of set bits in a given mask."""
return bin(mask).count("1") | 5c44ceaf898772198bd707d225fc4265347a5fea | 72,707 |
import re
def _shell_quote(arg):
"""Shell-quotes a string with minimal noise such that it is still reproduced
exactly in a bash/zsh shell.
"""
if arg == '':
return "''"
# Normal shell-printable string without quotes
if re.match(r'[-+,./0-9:@A-Z_a-z]+$', arg):
return arg
# Printable within regula... | 4ccd1ecd90901dbd2318ed4b979fb0cf22ec73f1 | 72,708 |
import random
def create_set() -> list:
""" Create domino set"""
dominos = []
for i in range(7):
for j in range(7):
if [j, i] in dominos:
continue
else:
dominos.append([i, j])
random.shuffle(dominos)
return dominos | 8e3d12eaf1071de8ae2de40f4cf26ca7fdf74c65 | 72,712 |
import json
def load_style(style: str) -> dict:
"""Load a json file containing the keyword arguments to use for plot styling
Parameters:
style: path to json file containing matplotlib style keyword arguments
Returns:
dictionary of matplotlib keyword arguments
"""
with open(styl... | 4c78f492f4e17e9540af1ae687a7d89c69fb2652 | 72,713 |
def is_valid_manifest(manifest_json, required_keys):
"""
Returns True if the manifest.json is a list of the form [{'k' : v}, ...],
where each member dictionary contains an object_id key.
Otherwise, returns False
"""
for record in manifest_json:
record_keys = record.keys()
if not ... | fb100e10d75f19a10fefa63204783c9e0efeb9f0 | 72,715 |
def skip_first_line(value):
"""Returns everything after the first newline in the string."""
parts = value.split("\n", 1)
return parts[1] if len(parts) == 2 else '' | bfd1d19f654afc963c7f27e4368f709e86984dad | 72,720 |
def reSubObject(pattern, string, repl=None):
"""
like re.sub, but replacements don't have to be text;
returns an array of alternating unmatched text and match objects instead.
If repl is specified, it's called with each match object,
and the result then shows up in the array instead.
"""
las... | 3e59d54a7a28f5793df71be53cbd39ddd3248548 | 72,721 |
def _build_self_message(msg, start, end, batch_size, total):
"""Creates a JSON object for batch processing.
The function builds the message with all the details to be able to process the
batch data when received. The aim of this message is this very same cloud
function.
Args:
msg: A JSON object represen... | 5799175465c84d581a731d7e874f1ab3c3c0ddc8 | 72,725 |
def tp(x0,U,lam=2,L=3):
"""
tp means (t)ime to escape right with (p)ositive initial vel.
"""
return ((2*(L - x0))/U + ((L - x0)*(L + x0)*lam)/U**2
+ L/(U + L*lam) - x0/(U + x0*lam))/3. | d50b723de1a98ef93f9e74a57b642d726564a5c8 | 72,727 |
from pathlib import Path
import hashlib
def md5_hash_file(path: Path) -> str:
"""
Get md5 hash of a file.
Args:
path (Path): Absolute path or relative to current directory of the file.
Returns:
str: The md5 hash of the file.
"""
m = hashlib.md5()
with path.open("rb") as ... | de398edd1476bf03cd78a3ddfd3e3c4ce8e14e1e | 72,728 |
def cipher(text, shift, encrypt=True):
"""This cipher takes string data and 'ciphers' it by shifting each letter by the number of positions specified in the alphabet.
Args:
text: Input string data to be encrypted / ciphered
shift: Number of positions in the alphabet to shift in the right... | 2dd7da5c45c9d24928c1a5906f06cb7e954bbdac | 72,733 |
import re
def filter_lines_regex(lines, regex, substitute):
"""
Substitutes `substitute` for every match to `regex` in each line of
`lines`.
Parameters
----------
lines : iterable of strings
regex, substitute : str
"""
return [re.sub(regex, substitute, line) for line in lines] | 2ed639d60b58447ca26acb75e1c190371c3974d0 | 72,734 |
from typing import Dict
from pathlib import Path
def read_image_to_bytes(filename: str) -> Dict:
"""
Function that reads in a video file as a bytes array
Parameters
----------
filename : str
Path to image file
Returns
-------
JSON
Object containing "filename" and byte... | d90721ff1231e7f1e0d2f7ea4bcf81facd2b1686 | 72,735 |
def is_nth_bit_is_set(n: int, i: int) -> bool:
"""
Test if the n-th bit is set.
>>> is_nth_bit_is_set(0b1010, 0)
False
>>> is_nth_bit_is_set(0b1010, 1)
True
>>> is_nth_bit_is_set(0b1010, 3)
True
>>> is_nth_bit_is_set(0b1010, 5)
False
"""
return bool(n & (1 << i)) | 14832450712bb43991bf488f72c659e98b7a5d95 | 72,738 |
def remove_quotes(val):
"""
Remove surrounding quotes from a string.
:param val: The string to remove quotes from.
:type val: str
:returns: str
"""
if val.startswith(('"', "'",)) and val.endswith(('"', "'",)):
val = val[1:-1]
return val | 8fc71e6eebae968ca122707aecc4094bce4c243b | 72,742 |
def map_tcp_flags(bitmap):
"""
Maps text names of tcp flags to values in bitmap
:param bitmap: array[8]
:return: dictionary with keynames as names of the flags
"""
result = {}
result["FIN"] = bitmap[7]
result["SYN"] = bitmap[6]
result["RST"] = bitmap[5]
result["PSH"] = bitmap[4... | f6388e3aa6a7540df8b26ba2061be5807f6c19be | 72,749 |
def unique(iterable):
"""Remove duplicates from `iterable`."""
return type(iterable)(x for x in dict.fromkeys(iterable)) | d4ac674105ed55ba9c969134a507838790770d77 | 72,750 |
from pathlib import Path
def parent_dir(filepath):
"""Get parent directory path from filepath"""
return Path(filepath).resolve().parent | 6b9fc56ebe248b64b2080b25efc1a335dafdda56 | 72,752 |
def get_default_parameters(args):
"""Build a default parameters dictionary from the content of the YAML file."""
return {name: values["default"] for name, values in args.items()} | 934af26ad4e19e483f7cc3fb6224f9dc5b3155b8 | 72,754 |
import heapq
def eigvec2str(eigvec, m, n, nctr, nvis = 6, npc = 6, iws = ' '):
"""
Output some prominent matrix elements for an eigenvector matrix
eigvec is given as a 1D array:
[ <B_1|1k>, <B_1|2k>, <B_2|1k>, <B_2|2k>]
which corresponds to such a matrix (m rows x n cols):
<B_1|1k> <B_... | 450dadd2d4f33681b21229c5c3b18a14b4266f81 | 72,765 |
def validate_slug_format(proposed_slug):
"""Raise an error if the proposed slug is invalid
For example, if contains a slash."""
# a regex would run faster, but getting the quoting right for a literal
# backslash probably isn’t worth it
FORBIDDEN_SLUG_CHARS = "/\\ "
if any(c in FORBIDDEN_SLUG_C... | 14458e9fde2aff66346e55bf40e0edfbfdb80de1 | 72,769 |
from typing import Dict
import json
def load_config_file(file_name: str) -> Dict:
"""
Reads the configs/config.json file and parse as a dictionary
:param file_name: name of the config file
:return: config dictionary
"""
try:
with open(f'{file_name}') as f:
conf: Dict = jso... | 827c4af5059f6db1fc8ef4f195ef1de32ce80fb2 | 72,770 |
def get_selected_attrs(stream):
"""
List down user selected fields
requires [ "selected": true ] inside property metadata
"""
list_attrs = list()
for md in stream.metadata:
if md["breadcrumb"]:
if md["metadata"].get("selected", False) or md["metadata"].get("inclusion") == "a... | b0df8a2f655f49250cd34219f785b5a8d4538643 | 72,773 |
import binascii
def pubkey_to_redeem(pubkey):
"""
Convert the public key to the redeemscript format.
Args:
pubkey (bytes): public key.
Returns:
bytes: redeemscript.
"""
return binascii.unhexlify(b'21' + pubkey + b'ac') | 318849b22b9b2813c9c0235ec00f3f87d3e3ee32 | 72,774 |
import random
def rectangles_unif_side(n: int, m: int):
"""Return list of `n` rec. with random side lengths `unif{0, m}`"""
return [(random.randint(1, m), random.randint(1, m))
for _ in range(n)] | 3cf48b22ed9a11766010af20ec5bf8ce28c9f9e8 | 72,780 |
import typing
import re
def to_snake(d: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]:
"""Converts dictionary keys from camel case to snake case."""
def convert(key: str) -> str:
camel = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", key)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", cam... | 6f12faf003a80bc050fde26770788cbaffb00122 | 72,781 |
def to_multiregion(region):
"""Convert a single region or multiple region specification into multiregion list.
If a single region (chrom, start, end), returns [(chrom, start, end)]
otherwise returns multiregion.
"""
assert isinstance(region, (list, tuple)), region
if isinstance(region[0], (list... | 8d9a41e7d9e16bd1bc8553f9be38b5152ce8c7de | 72,788 |
def extract(ts):
""" Retrieve lists of C, T, D from taskset ts """
C = []
T = []
D = []
for i in range(len(ts)):
C.append(ts[i].C)
T.append(ts[i].T)
D.append(ts[i].D)
return C, T, D | d87c675fe150c8d1c7e8db32559283a7090121d8 | 72,790 |
from typing import Dict
from typing import Tuple
def get_line_found_and_hit(dict: Dict[int, int]) -> Tuple[int, int]:
"""Return the count for entries (found) and entries with an execution count
greater than zero (hit) in a dict (linenumber -> execution count) as
a list (found, hit)"""
found = len(dict... | 4cf39b34dd11c3e702337c9b9d7f9f2ae7612ebb | 72,791 |
import torch
def preprocessing(num_ways, num_shots, num_queries, batch_size, device):
"""
prepare for train and evaluation
:param num_ways: number of classes for each few-shot task
:param num_shots: number of samples for each class in few-shot task
:param num_queries: number of queries for each cl... | 86802320714009b3c4a244dd71ca902e274bbf7b | 72,792 |
def location_to_index(location, spacing, shape):
"""Convert a location to an index.
Parameters
----------
location: tuple of float or None
Location of source in m. If None is passed at a certain location
of the tuple then the source is broadcast along the full extent
of that axi... | 457e4575761d4999fc2fcd90caccfd8b8207f78d | 72,800 |
def get_fractions(setting_fractions_df, location):
"""
Get the fraction of people with contacts in each setting of household (H), school (S), or work (W).
Args:
setting_fractions_df (pandas DataFrame) : a dataframe
location (str) : name of the location
Returns:... | efa6fbc55405c647b83f43f959b6b3c56754d819 | 72,801 |
def oncogenes_count(driver_dataframe):
"""Function to count number of oncogenes from final driver gene dataframe."""
oncogene = driver_dataframe["driver_role"] == "Oncogene"
df_oncogene = driver_dataframe[oncogene][[
"gene", "driver_role"]].drop_duplicates().reset_index(drop=True)
return len(df_... | e734b4d0f85b149ccddd2dc3bb11af7869d53fa7 | 72,803 |
def get_image_scale(image_size, target_size):
"""
Calculates the scale of the image to fit the target size.
`image_size`: The image size as tuple of (w, h)
`target_size`: The target size as tuple of (w, h).
:return: The image scale as tuple of (w_scale, h_scale)
"""
(image_w, image_h) = imag... | 2a0677754ede840f850b1337d7c14eddbae44d40 | 72,806 |
def get_list_as_str(list_of_objs):
""" Returns the list as a string. """
return '[' + ' '.join([str(x) for x in list_of_objs]) + ']' | 5b747f727d87db2ea4edd3b6aeedd27b25a7b49e | 72,808 |
def assert_utility_signal(library, session, line):
"""Asserts or deasserts the specified utility bus signal.
Corresponds to viAssertUtilSignal function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param line: spec... | cba39190520ed41f94afa7991595f51b3d4401f3 | 72,813 |
import copy
def build(cfg, registry, args=None):
"""
Build the module with cfg.
Args:
cfg (dict): the config of the modules
registry(Registry): A registry the module belongs to.
Returns:
The built module.
"""
args = copy.deepcopy(cfg)
name = args.pop("name")
... | 3a662160eed76e11a714090dcaa15367893e90f1 | 72,816 |
import warnings
def convert_method_3_nb_into_str(method_3_nb):
"""
Converts method_3_nb into string
Parameters
----------
method_3_nb : int
Number of method 3
Returns
-------
method_3_str : str
String of method 3
"""
if method_3_nb is None:
msg = 'meth... | e364ace46829c2aeac4dc4bb4f31eb6a0d304b41 | 72,822 |
import copy
def expand_list(list_1d: list) -> list:
"""Expand 1d list to 2d
Parameters
----------
list_1d : list
input list
Returns
-------
list_2d: list
output 2d list
"""
list_2d = copy.deepcopy(list_1d)
if not isinstance(list_1d[0], list):
list_2d =... | 5c594076650dbc2a50be64cbb5cb55ea2f6d184f | 72,826 |
def _parse_name(name):
"""Returns a pair namespace, name
parsing string like namespace/name.
Namespace could be None if there is not backslash in the name.
"""
if '/' in name:
return name.split('/', 1)
return None, name | fe6456cfa630d9d5e3475518264f6f1b262f1761 | 72,829 |
from typing import Union
from pathlib import Path
from typing import cast
def ensure_path(path: Union[Path, str]) -> Path:
"""Return path object from `pathlib.Path` or string.
While `Path` can be called on strings or `Path` and return a `Path`, it
does not behave correctly for mock path instances. This h... | 64c679ef37a13f9a1776e4d0b01bc4e246d966ce | 72,833 |
import configparser
def read_config(config_file):
"""Read the config file.
Args:
config_file (file) : Plugin config file
Returns:
object: config object
"""
config = configparser.ConfigParser()
config.read(config_file)
return config | 20d67952dfd6c619f5693996162e2cca984af483 | 72,834 |
def spiral_matrix(matrix):
"""Navigates a 2D array and traverses the edges in a spiral-pattern.
Args:
matrix; list: a 2D list to traverse.
Returns:
A string representation of all points traveled in the matrix in the order
they were traveled to.
"""
output = list()
rows = len(matrix[0])
colum... | 013e9e9a8f47ed0d8b5631cb2e912654f85c0897 | 72,837 |
import random
def _get_random_number(interval):
"""
Get a random number in the defined interval.
"""
return random.randrange(2**(interval-1), 2**interval - 1) | f586330e3eba08e5ccc22e31cf8a8a04b20a9aa6 | 72,838 |
import json
def json_encode(obj):
""" Serialize obj to a JSON formatted str """
return json.dumps(obj) | b04774e675971c3c234df9b2e09436cd349707c5 | 72,839 |
def scaps_script_generator(calc_param):
"""
Generate SCAPS simulation input script as a string.
"""
return "\n".join(["//Script file made by Python",
"set quitscript.quitSCAPS",
"load allscapssettingsfile {}".format(calc_param['def']),
... | fc20d8cbf004bdc3585925b018680ecb09de8022 | 72,842 |
def all_comics_for_series(series_obj):
"""
Get all published or announced comics for a series.
:param series_obj: :class:`marvelous.Series` instance
:return: `list` of :class:`marvelous.Comic` instances
"""
limit = 100
offset = 0
total = None
comics = []
fetches = 0
while t... | b45d1e39fe02be7227f25abbe13cce4226300202 | 72,844 |
def create_tuple_mapper(input_fn, output_fn):
"""
Creates a mapping function that receives a tuple (input, output) and uses the two
provided functions to return tuple (input_fn(input), output_fn(output)).
"""
def fun(item):
input, output = item
return input_fn(input), output_fn(outp... | af851dfff9f3f836f7f2e0ff28055041a7294aeb | 72,846 |
def build_youtube_resource(title, description, recording_date, coords=None, location_desc=None, tags=None, category=25,
privacy='unlisted', language='en'):
"""
Build a YouTube video resource as per https://developers.google.com/youtube/v3/docs/videos.
:param title:
:param des... | 35fe25a1f4478e11b1cb1f860d49ff3185c5d86e | 72,847 |
def ix(dot,orb,spin):
"""
Converts indices to a single index
Parameters
----------
dot : int
Dot number
orb : int
Orbital number (0 for p- and 1 for p+)
spin : int
0 for spin down, 1 for spin up.
Returns
-------
int
"""
return 4*dot+2*orb+spin | e8ce258d243d5b2933a91596c3df4b191ed7edcb | 72,861 |
def add_scale_bar(apx, s, sl, c='y'):
"""
Adds an aplpy scale bar
:param apx: aplpy fig
:param s: astropy.units quantity, size (with units) of the scale bar
:param sl: string, label for scale bar
:param c: string, colour of scalebar
:return:
"""
apx.add_scalebar(s)
apx.scalebar.... | d109560ce942f1b98777ae182e81b5842731cc03 | 72,864 |
def party_planner(cookies, people):
"""This function will calculate how many cookies each person will get in the party
and also gives out leftovers
ARGS:
cookies: int, no of cookies is going to be baked
people: int, no of people are attending this party_planner
Returns:
tuple of cookies per ... | b4d4545710f689f2b048ba4a1637647b80aac451 | 72,866 |
def zipdict(keys, vals):
"""Creates a dict with keys mapped to the corresponding vals."""
return dict(zip(keys, vals)) | 15cb1a2c5936f973703ea14126056ff076160f70 | 72,870 |
def uh(h):
"""Convert a hexadecimal string representation of a number to an integer.
Example:
uh('0xabcdef0') == 0xabcdef0
uh('abcdef0') == 0xabcdef0
"""
return int(h.replace('0x', '').replace(' ',''), 16) | 4c8bfcbbdae132807fe71c50a9bfc8e6be0651ce | 72,871 |
def generate_prompt(is_continuation):
""" calculate and return a string with the prompt to display """
if not is_continuation:
return '>>> '
return '... ' | 6f6be71caa0b1c207a69deead956c6fb12f31c15 | 72,875 |
import torch
def load_model(fname):
"""Loads a model on CPU by default."""
savable = torch.load(fname, map_location='cpu')
return savable.userdata | 54cfb716e80c83139fa4d5c4e6a40b9d74147661 | 72,878 |
def step(edge, x):
"""Return 0.0 if x < edge; otherwise result is 1.0, with x a float scalar or vector."""
return 0.0 if x < edge else 1.0 | 57f4dc9f3455b7cde342336268377fe06865fae0 | 72,881 |
def solveMP(MP, xr, yr, d):
"""
Get optimal solution and objective value for current master problem
"""
# optimize
MP.update()
MP.optimize()
MPobj = MP.objVal
# get first-stage varibles
xrsol_t = {}
for u in d.users:
for v in d.VMs:
for p in d.providers:
... | fe2d45e7f74609be12b3f2fd0a05eb6bce6beaaa | 72,882 |
import unicodedata
def remove_accents(word: str) -> str:
"""
Return the same word with all accents removed
>>> remove_accents('Mongolië')
'Mongolie'
"""
nfkd_form = unicodedata.normalize('NFKD', word)
return u''.join([c for c in nfkd_form if not unicodedata.combining(c)]) | 4602c40046914ead801496deb1ef805a6abea91e | 72,883 |
def permute(arr, permutation):
""" Permute the array: permutation[i] is the new index for the i-th element of arr """
if permutation is None:
permutation = range(len(arr))
result = [None] * len(arr)
for element, index in zip(arr, permutation):
result[index] = element
return result | b59efd8f5fdad3ccef48fe8d4920b0d7253e0a45 | 72,884 |
def ft_db_close_conn_sqlite(conn):
"""Close sqlite database connection.
"""
conn.close()
return True | 93d3334b78764947a3757417b6b988aae82a6060 | 72,885 |
def merge_fields(*fields):
"""
Provided as a convenience to merge multiple groups of fields. Equivalent
to: `fields.update(**other_fields)`. Dictionaries are processed in order
and overwrite fields that are already present.
Parameters
----------
fields : *args
Field dictionaries ... | df2bae5dfe899cc5ca2e761bd807aae9887ea64c | 72,889 |
def find_group_single_candidate(square: tuple, squares: list, grid: list) -> list:
"""
Checks for a single option a square can have based on no other square in a group having it as an option
:param square: A tuple (row, column) coordinate of the square
:param squares: A list of squares (tuples) to chec... | 1983720f4540b0bd964a2ba535455ca0510ef369 | 72,890 |
def _is_in(obj, lst):
"""Checks if obj is in lst using referential equality.
"""
return any(el is obj for el in lst) | c6ee76d82bd77f3f80d86320cdef8ac5a01506b9 | 72,892 |
def _check_features(schema1, schema2):
"""
Get list of features to check based on table schemas
Parameters
----------
schema1: table1 schema
schema2: table2 schema
Returns
-------
schema:
merged and modified schema
check_features:
a dictionary of (data type, fea... | efb50b1b1522f7d378568e9ca8e9fd1d1192bc22 | 72,895 |
def parseSingleLink(line):
"""Parse a single link having the format: src dst [weight]
line - non-empty line of the input text that starts from a non-space symbol
return [src_str, dst_str, weight_str | None],
"""
line = line.split(None, 3) # Ending comments are not allowed, but required unweighted link might c... | 32aea6ed5fa6225c9514150f67580162ae11d0c4 | 72,897 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.